diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 5880459d75a12..144879ecdb565 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,4 +1,4 @@ -// Dev container for T3 Code. Mirrors CI (ubuntu-24.04, Node 24, Rust stable) +// Dev container for T3 Code. Mirrors CI (ubuntu-24.04, Node 26, Rust stable) // and the canonical setup in docs/operations/development.md: global `vp`, `vp i`. // Contributor doc: docs/internals/devcontainer.md { @@ -8,7 +8,7 @@ // nodeGypDependencies (default true) brings python3/make/g++, which Linux // needs for node-pty's node-gyp fallback (its prebuilds are mac/win only). "ghcr.io/devcontainers/features/node:2": { - "version": "24" + "version": "26" }, // native/resource-monitor (edition 2024, needs stable >= 1.85). The server // degrades gracefully without the binary, but CI checks cargo fmt + test. diff --git a/.gitattributes b/.gitattributes index ffcc4445fe8a1..24860868b59bc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,6 +3,7 @@ # Batch files need CRLF for cmd.exe to parse them reliably. *.cmd text eol=crlf *.bat text eol=crlf -# GitHub's GraphQL schema and the operations graphqlgen writes from it. +# GitHub's and Expo's GraphQL schemas and the operations graphqlgen writes from them. packages/source-control-github/schema/** linguist-generated +apps/server/schema/** linguist-generated **/*.graphql.ts linguist-generated diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index ab3fb7deba6bc..e0ef427bd1d36 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -1,30 +1,89 @@ name: Setup CI dependencies description: Install Vite+ and the workspace dependencies from cache. +inputs: + task-cache-read-token: + description: Read-only credential for the private maintainer task cache + required: false + default: "" runs: using: composite steps: - # setup-vp reuses an installed exact version, so restoring its home skips the - # installer download on every job. + # ~/.vite-plus holds vp, the Node.js runtime, and pnpm. A cache entry never + # updates, so the key names all three versions; otherwise a pnpm or Node.js + # bump makes every job download them from npm again. - name: Resolve Vite+ version id: vp shell: bash run: | echo "version=$(sed -nE 's/^ vite-plus: ([0-9][^ ]*)$/\1/p' pnpm-workspace.yaml)" >> "$GITHUB_OUTPUT" + echo "node=$(jq -r '.engines.node' package.json)" >> "$GITHUB_OUTPUT" + echo "pnpm=$(jq -r '.packageManager' package.json)" >> "$GITHUB_OUTPUT" - name: Cache Vite+ + id: vp_cache if: steps.vp.outputs.version != '' uses: actions/cache@v6 with: path: ~/.vite-plus - key: vite-plus-home-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }} + key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} + # setup-vp always runs the installer, which fetches vp from npm even when + # this exact version is installed. A cache hit already has everything, so + # skip setup-vp and do its remaining work here. This keeps npm outages from + # failing jobs. + - name: Use cached Vite+ + if: steps.vp_cache.outputs.cache-hit == 'true' + shell: bash + run: | + echo "$HOME/.vite-plus/bin" >> "$GITHUB_PATH" + "$HOME/.vite-plus/bin/vp" env use "${{ steps.vp.outputs.node }}" + + - name: Setup Vite+ + if: steps.vp_cache.outputs.cache-hit != 'true' + uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: false + run-install: false + + - name: Resolve pnpm store path + id: pnpm_store + shell: bash + run: | + store_path="$(vp pm cache dir)" + echo "path=$store_path" >> "$GITHUB_OUTPUT" + + # setup-vp's shared cache key ignores install filters. Keep full installs in a + # separate namespace, including fallback restores. # The pnpm store stays a cache tarball on the runner's own disk. A store on a # Blacksmith sticky disk mounts in under a second, but pnpm then copies every # package across filesystems instead of hard-linking it: install took 28-49s # against 9s plus an 11s restore. - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Cache full pnpm store + uses: actions/cache@v6 with: - node-version-file: package.json - cache: true - run-install: true + path: ${{ steps.pnpm_store.outputs.path }} + key: pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json') }} + restore-keys: | + pnpm-full-v1-${{ runner.os }}-${{ runner.arch }}- + + - name: Install dependencies + shell: bash + run: vp install + + - name: Enable shared task cache + if: >- + github.repository == 'pingdotgg/t3code' && + (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && + hashFiles('.task-cache.json') != '' && + inputs.task-cache-read-token != '' + shell: bash + env: + T3_TASK_CACHE_READ_TOKEN: ${{ inputs.task-cache-read-token }} + run: | + node infra/task-cache/scripts/install-ci.ts + if [[ ( "$GITHUB_EVENT_NAME" == pull_request && "$GITHUB_BASE_REF" == main ) || ( "$GITHUB_EVENT_NAME" == push && "$GITHUB_REF" == refs/heads/main ) ]]; then + echo 'VP_REMOTE_CACHE=read-write' >> "$GITHUB_ENV" + else + echo 'VP_REMOTE_CACHE=read' >> "$GITHUB_ENV" + fi diff --git a/.github/scripts/check-nightly-release.test.cjs b/.github/scripts/check-nightly-release.test.cjs index 64d8c8d6c0bd6..f55d29c10dc6a 100644 --- a/.github/scripts/check-nightly-release.test.cjs +++ b/.github/scripts/check-nightly-release.test.cjs @@ -61,12 +61,6 @@ for (const releaseChannel of ["stable", "nightly"]) { ); assert.equal(calls.length, 0); }); - - test(`allows a manual ${releaseChannel} release from main`, async () => { - const { options, calls } = releaseSourceFixture(); - await assertReleaseSource({ ...options, releaseChannel }); - assert.equal(calls[0].basehead, "candidate...main"); - }); } for (const comparisonStatus of ["behind", "diverged"]) { @@ -79,13 +73,6 @@ for (const comparisonStatus of ["behind", "diverged"]) { }); } -test("accepts a release commit already contained in main", async () => { - for (const comparisonStatus of ["ahead", "identical"]) { - const { options } = releaseSourceFixture({ comparisonStatus, eventName: "push" }); - await assertCommitOnDefaultBranch({ ...options, sha: "release-commit" }); - } -}); - function fixture({ releases = [nightly(7)], comparisonStatus = "ahead" } = {}) { const calls = []; return { @@ -119,26 +106,6 @@ test("releases the first nightly when no nightly is published", async () => { assert.equal(await shouldReleaseNightly(options), true); }); -test("waits six hours after publication, including manual nightlies", async () => { - for (const age of [0, 3, 6 - 1 / 3600]) { - const { options, calls } = fixture({ releases: [nightly(age)] }); - assert.equal(await shouldReleaseNightly(options), false); - assert.equal(calls.length, 0); - } -}); - -test("releases new commits at six hours and after an idle period", async () => { - for (const age of [6, 7, 24]) { - const { options } = fixture({ releases: [nightly(age)] }); - assert.equal(await shouldReleaseNightly(options), true); - } -}); - -test("skips unchanged commits after the gap", async () => { - const { options } = fixture({ comparisonStatus: "identical" }); - assert.equal(await shouldReleaseNightly(options), false); -}); - test("uses publication time, not release order or the tagged commit date", async () => { const { options } = fixture({ releases: [nightly(10), nightly(1), nightly(20, { tag_name: "nightly-v0.9.0" })], @@ -153,13 +120,6 @@ test("ignores stable releases and drafts when checking the gap", async () => { assert.equal(await shouldReleaseNightly(options), true); }); -test("compares against the published tag, including legacy nightly tags", async () => { - const tag = "nightly-v0.9.0"; - const { options, calls } = fixture({ releases: [nightly(7, { tag_name: tag })] }); - assert.equal(await shouldReleaseNightly(options), true); - assert.equal(calls[0].basehead, `${tag}...new`); -}); - test("fails instead of releasing when GitHub cannot supply release state", async () => { const { options } = fixture(); options.github.paginate = async () => { @@ -211,8 +171,3 @@ test("stable releases derive the version from legacy nightly tags", async () => }); assert.equal((await resolveLatestNightlyCommit(options)).version, "0.9.0"); }); - -test("stable releases fail without a published nightly", async () => { - const { options } = nightlyCommitFixture({ releases: [nightly(0, { tag_name: "v1.0.0" })] }); - await assert.rejects(resolveLatestNightlyCommit(options), /No published nightly/); -}); diff --git a/.github/scripts/ci-changes.cjs b/.github/scripts/ci-changes.cjs index 1904f3790a4a8..2ff10b84fd3a9 100644 --- a/.github/scripts/ci-changes.cjs +++ b/.github/scripts/ci-changes.cjs @@ -1,19 +1,10 @@ -// Decides which CI jobs a change needs. Prints `key=value` lines for -// $GITHUB_OUTPUT; a job runs unless its key is "false". -// -// node ci-changes.cjs --paths gate by the listed paths -// node ci-changes.cjs --paths --full run every Linux job, gate only the macOS lint -// node ci-changes.cjs changed paths unknown: run everything -// -// Every changed path maps to workspace packages, which then pull in their -// dependents from package.json. A path this file does not recognize runs -// everything, so a new root file or directory can only cost minutes. +// Unknown paths run every job; recognized packages pull in their dependents. +// scripts/check-changed.ts shares these decisions so local checks match CI. const fs = require("node:fs"); const path = require("node:path"); const root = path.resolve(__dirname, "../.."); -// Never read by a build, typecheck, or test. Lint still formats them. const INERT = [ /^docs\//, /^\.(agents|cursor|vscode|devcontainer|macroscope|repos)\//, @@ -21,28 +12,25 @@ const INERT = [ /^LICENSE$/, ]; -// Run everything: the root vite.config.ts loads the first as setup for every -// package's tests, and the vendored mobile tarballs are installed dependencies. +// Shared test setup and vendored mobile dependencies affect every package. const RUNS_EVERYTHING = [ /^packages\/shared\/src\/(HostProcess|testing\/longTempDir)\.ts$/, /^apps\/mobile\/deps\//, ]; -// Paths outside a package, or files inside one that other packages read -// through relative imports rather than a package.json dependency. +// Includes cross-package reads absent from package.json dependencies. const EXTRA_OWNERS = [ // Vite configs and tsconfigs of these apps import scripts/lib directly. [/^scripts\/lib\//, ["@t3tools/desktop", "@t3tools/mobile", "@t3tools/web", "t3"]], // scripts/build-desktop-artifact.ts reads the GNOME extension manifest. [/^apps\/desktop\/gnome-extension\//, ["@t3tools/scripts"]], [/^native\/browser-secret\//, ["@t3tools/desktop"]], + [/^native\/kde-snap-shot\//, ["@t3tools/desktop"]], [/^native\/libghostty-vt\//, ["@t3tools/web"]], ]; const RUST = /^native\/(resource-monitor|kde-snap-shot|hyprland-snap-shot)\//; -// Tests that read another package's files without declaring it. The scripts -// tests read app manifests, assets, and sources (cursor-sdk-packaging, -// third-party-licenses, brand-assets, build-desktop-artifact). +// These tests read other packages without declaring dependencies. const TEST_ONLY_DEPS = { "@t3tools/provider-pi": ["@t3tools/client-runtime"], "@t3tools/scripts": [ @@ -53,17 +41,12 @@ const TEST_ONLY_DEPS = { "@t3tools/provider-cursor", ], }; -// Declared dependencies that only feed a build step: the server bundles the -// built web app (apps/server/vite.config.ts) but never imports it. +// The server bundles the web build without importing it. const BUILD_ONLY_DEPS = { t3: ["@t3tools/web"] }; -// Sources scripts/mobile-native-static-check.ts lints, plus the tool and rule -// configuration that decides how it lints them, plus the root package.json -// that defines the lint:mobile command. const MOBILE_NATIVE = /^apps\/mobile\/.*\.(swift|kt|kts)$|^apps\/mobile\/(\.swiftlint\.yml|detekt\.yml|\.editorconfig|Brewfile)$|^scripts\/mobile-native-static-check\.ts$|^package\.json$|^\.github\/workflows\/ci\.yml$|^\.github\/scripts\/ci-changes\.cjs$|^\.github\/actions\/ci-changes\//; -// Jobs that test every package except these, which have jobs of their own. const OWN_TEST_JOB = new Set(["t3", "@t3tools/web", "@t3tools/monorepo"]); function readWorkspace() { @@ -105,17 +88,16 @@ function readWorkspace() { return packages; } -// Returns the packages a path touches, [] for an inert path, or null when the -// path is not understood and everything must run. +// [] means inert; null means unknown and requires every job. function ownersOf(file, packages) { if (INERT.some((pattern) => pattern.test(file))) return []; // A manifest can change dependencies or versions other packages read. if (path.posix.basename(file) === "package.json") return null; if (RUNS_EVERYTHING.some((pattern) => pattern.test(file))) return null; + const extra = EXTRA_OWNERS.flatMap(([pattern, names]) => (pattern.test(file) ? names : [])); // scripts/build-desktop-artifact.test.ts reads the crates' sources. - if (RUST.test(file)) return ["@t3tools/scripts"]; + if (RUST.test(file)) return ["@t3tools/scripts", ...extra]; - const extra = EXTRA_OWNERS.flatMap(([pattern, names]) => (pattern.test(file) ? names : [])); const owner = packages .filter((pkg) => file.startsWith(`${pkg.dir}/`)) .sort((a, b) => b.dir.length - a.dir.length)[0]; @@ -145,7 +127,6 @@ function decide(files, packages, full) { if (everything) { affected = all; } else { - // Add dependents until nothing changes. let grew = true; while (grew) { grew = false; @@ -200,4 +181,6 @@ function main() { for (const [key, value] of Object.entries(outputs)) console.log(`${key}=${value}`); } -main(); +module.exports = { readWorkspace, decide }; + +if (require.main === module) main(); diff --git a/.github/scripts/ci-changes.d.cts b/.github/scripts/ci-changes.d.cts new file mode 100644 index 0000000000000..afe6f61339362 --- /dev/null +++ b/.github/scripts/ci-changes.d.cts @@ -0,0 +1,27 @@ +interface WorkspacePackage { + readonly name: string; + readonly dir: string; + readonly hasTest: boolean; + readonly deps: ReadonlyArray; +} + +export function readWorkspace(): Array; + +export function decide( + files: ReadonlyArray | null, + packages: ReadonlyArray, + full: boolean, +): { + affected: Array; + outputs: { + typecheck: boolean; + build: boolean; + test: boolean; + test_packages: string; + test_web: boolean; + test_server: boolean; + rust: boolean; + release_smoke: boolean; + mobile_native: boolean; + }; +}; diff --git a/.github/scripts/mirror-play-apk.cjs b/.github/scripts/mirror-play-apk.cjs index 90b368b2aa036..d017fc907f124 100644 --- a/.github/scripts/mirror-play-apk.cjs +++ b/.github/scripts/mirror-play-apk.cjs @@ -1,7 +1,4 @@ -// Publishes closed-testing betas, or downloads the internal APK for a normal -// nightly release. Play generates and signs the APK from the -// uploaded bundle with the app signing key, so it carries the same signature -// as the Play Store install. Run by .github/workflows/mobile-android-apk.yml. +// Play signs generated APKs with the app signing key, matching Play Store installs. const { execFileSync } = require("node:child_process"); const crypto = require("node:crypto"); const fs = require("node:fs"); @@ -50,10 +47,7 @@ async function play(token, method, url) { return response; } -// Highest version code the track serves, with its release name. Play names a -// release after the bundle's versionName unless the uploader sets one. This -// endpoint reads without opening an edit; an edit would invalidate any open -// EAS Submit edit made with the same service account. +// Opening an edit would invalidate any EAS Submit edit using the same service account. async function newestTrackBuild(token, appUrl, trackName) { const { releases = [] } = await ( await play(token, "GET", `${appUrl}/tracks/${trackName}/releases`) @@ -82,8 +76,7 @@ function readRelease(tag) { } } -// Download to a temporary directory so a failed request cannot leave a partial -// APK among the release assets. +// Stage downloads so failed requests cannot leave partial release assets. async function downloadApk({ token, appUrl, build, apkName }) { const generated = await ( await play(token, "GET", `${appUrl}/generatedApks/${build.versionCode}`) diff --git a/.github/scripts/stage-preview-bundle.py b/.github/scripts/stage-preview-bundle.py index 0b3a53285916b..1730ee5c8d752 100644 --- a/.github/scripts/stage-preview-bundle.py +++ b/.github/scripts/stage-preview-bundle.py @@ -12,8 +12,7 @@ "server/dist/client/index.html", "desktop/dist-electron/main.cjs", } -# The current bundle is about 32 MiB compressed. Bound extraction on the -# trusted runner even when the PR replaces the uploader entirely. +# Bound trusted-runner extraction even when a PR replaces the uploader. MAX_ARCHIVE_BYTES = 512 * 1024 * 1024 MAX_EXPANDED_BYTES = 2 * 1024 * 1024 * 1024 MAX_ENTRIES = 50_000 @@ -58,9 +57,7 @@ def stage_bundle(archive: Path, destination: Path): files.add(name) if not REQUIRED_FILES <= files: raise ValueError("Preview bundle is missing required entry points") - # Validate all names before writing anything. This is a fresh directory - # outside the checkout; neither pre-existing links nor trusted files - # can be followed or overwritten. ZIP permissions are never restored. + # Validate before writing into a fresh directory so existing links/files cannot be followed or overwritten. destination.mkdir(parents=True, exist_ok=False) for entry in entries: target = destination / entry.filename diff --git a/.github/scripts/thread-transfer-report.cjs b/.github/scripts/thread-transfer-report.cjs index a85fec9ee04a4..ca57769ed490c 100644 --- a/.github/scripts/thread-transfer-report.cjs +++ b/.github/scripts/thread-transfer-report.cjs @@ -244,10 +244,26 @@ async function resolve({ github, context, core }) { let pullNumber = source.pull_requests?.[0]?.number; if (!pullNumber) { - const associated = await github.paginate( - github.rest.repos.listPullRequestsAssociatedWithCommit, - { owner, repo, commit_sha: source.head_sha, per_page: 100 }, - ); + let associated; + try { + associated = await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { + owner, + repo, + commit_sha: source.head_sha, + per_page: 100, + }); + } catch (error) { + // A force-pushed or deleted PR head can disappear before this workflow runs. + if ( + error.status === 422 && + error.response?.data?.message === `No commit found for SHA: ${source.head_sha}` + ) { + core.info(`Skipping CI result for unavailable commit ${source.head_sha}.`); + core.setOutput("publish", "false"); + return; + } + throw error; + } const matchingPulls = associated.filter( (pull) => pull.state === "open" && @@ -278,8 +294,7 @@ async function resolve({ github, context, core }) { const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id); const sourceArtifact = findResultArtifact(sourceArtifacts); - // CI requires the artifact whenever the server tests run, so a passing run - // without one skipped them because the PR cannot affect the server. + // Successful server tests require this artifact; its absence means CI skipped them. if (!sourceArtifact && source.conclusion === "success") { core.info("CI skipped the server tests for this change; nothing to report."); core.setOutput("publish", "false"); diff --git a/.github/scripts/thread-transfer-report.test.cjs b/.github/scripts/thread-transfer-report.test.cjs index 5b1749fc53f49..753c3eb759072 100644 --- a/.github/scripts/thread-transfer-report.test.cjs +++ b/.github/scripts/thread-transfer-report.test.cjs @@ -2,7 +2,6 @@ const assert = require("node:assert/strict"); const test = require("node:test"); const { - renderComment, resolve, upsertCommentForCurrentHead, validateResult, @@ -53,39 +52,6 @@ test("validates the fixed artifact schema", () => { ); }); -test("renders baseline, impact, ceiling, and ceiling changes", () => { - const baseline = result(); - const current = result({ measuredTurnWebSocketWireBytes: 260_000 }); - current.providers.codex.ceiling = { - ...current.providers.codex.ceiling, - measuredTurnWebSocketWireBytes: 330_000, - }; - const comment = renderComment({ - current, - baseline, - currentRun: { - sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - conclusion: "success", - url: "https://github.com/pingdotgg/t3code/actions/runs/2", - }, - baselineRun: { - sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - matchesBase: true, - url: "https://github.com/pingdotgg/t3code/actions/runs/1", - }, - }); - - assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/); - assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/); - assert.match(comment, /This PR changes transfer ceilings/); - assert.match(comment, /312\.5 KiB → 322\.3 KiB/); - assert.match(comment, //); - assert.match( - comment, - //, - ); -}); - test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => { const outputs = {}; const listWorkflowRunArtifacts = () => {}; @@ -216,6 +182,47 @@ test("does not guess when a fallback commit belongs to multiple PRs", async () = assert.equal(fetchedPull, false); }); +test("skips a missing PR commit but preserves other lookup failures", async () => { + for (const [status, message, shouldSkip] of [ + [422, "No commit found for SHA: old-head", true], + [422, "Validation Failed", false], + [403, "API rate limit exceeded", false], + ]) { + const outputs = {}; + const error = Object.assign(new Error(message), { + status, + response: { data: { message } }, + }); + const run = resolve({ + github: { + paginate: async () => { + throw error; + }, + rest: { repos: { listPullRequestsAssociatedWithCommit: () => {} } }, + }, + context: { + repo: { owner: "pingdotgg", repo: "t3code" }, + payload: { + workflow_run: { event: "pull_request", head_sha: "old-head", pull_requests: [] }, + }, + }, + core: { + info: () => {}, + setOutput: (key, value) => { + outputs[key] = value; + }, + }, + }); + if (shouldSkip) { + await run; + assert.equal(outputs.publish, "false"); + } else { + await assert.rejects(run, (caught) => caught === error); + assert.deepEqual(outputs, {}); + } + } +}); + test("does not report a passing run that skipped the server tests", async () => { const outputs = {}; const listWorkflowRunArtifacts = () => {}; @@ -332,21 +339,3 @@ test("preserves a successful result when a same-SHA rerun has no artifact", asyn assert.equal(published, true); assert.equal(updatedComment, false); }); - -test("accepts V2 without comparing it to the V1 scenario", () => { - const current = result(); - current.scenario.id = "thread-transfer-v2"; - current.providers.codex.ceiling = { ...current.providers.codex.ceiling, totalWireBytes: 3000000 }; - assert.equal(validateResult(current), current); - const comment = renderComment({ - current, - baseline: result(), - currentRun: { sha: "bbbbbbbb", conclusion: "success", url: "https://example.com/current" }, - baselineRun: { sha: "aaaaaaaa", matchesBase: true, url: "https://example.com/baseline" }, - }); - assert.match(comment, /fixture changed/); - assert.doesNotMatch(comment, /This PR changes transfer ceilings/); - assert.doesNotMatch(comment, /[+-]\d+\.\d+%/); - current.scenario.id = "unrecognized"; - assert.throws(() => validateResult(current), /not supported/); -}); diff --git a/.github/scripts/vercel-deployment-output.test.cjs b/.github/scripts/vercel-deployment-output.test.cjs new file mode 100644 index 0000000000000..a249653350f22 --- /dev/null +++ b/.github/scripts/vercel-deployment-output.test.cjs @@ -0,0 +1,87 @@ +const assert = require("node:assert/strict"); +const { spawnSync } = require("node:child_process"); +const { mkdtempSync, readFileSync, rmSync, existsSync } = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { test } = require("node:test"); + +const release = readFileSync(join(__dirname, "../workflows/release.yml"), "utf8"); +const preview = readFileSync(join(__dirname, "../workflows/web-preview.yml"), "utf8"); +const stepPattern = + / name: (?:Build staged deployment|Deploy preview)\n shell: bash\n run: \|\n((?: .*\n|\n)+)/g; +const steps = [ + ...Array.from(release.matchAll(stepPattern), (match, index) => [ + index === 0 ? "hosted web" : "marketing", + match[1], + ]), + ...Array.from(preview.matchAll(stepPattern), (match) => ["web preview", match[1]]), +]; +assert.equal(steps.length, 3, "Expected both release steps and the preview step"); + +const url = "https://t3code-fixture-pinglabs.vercel.app"; +const warning = 'Error while parsing config file: "/runner/t3code/pnpm-lock.yaml"'; + +function runStep(script, stdout, exitCode = 0) { + const directory = mkdtempSync(join(tmpdir(), "t3-vercel-output-")); + const outputFile = join(directory, "output"); + try { + const result = spawnSync( + "bash", + [ + "-c", + 'vp() { printf "%s\\n" "$FIXTURE_STDOUT"; return "$FIXTURE_EXIT"; }\n' + + 'curl() { printf \'{"id":"fixture-project"}\\n\'; }\n' + + script.replace(/^ /gm, "").replace(/\$\{\{.*?\}\}/g, "fixture"), + ], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + VERCEL_TOKEN: "fixture-token", + VERCEL_ORG_ID: "fixture-org", + VERCEL_PROJECT_ID: "fixture-project", + GITHUB_OUTPUT: outputFile, + FIXTURE_STDOUT: stdout, + FIXTURE_EXIT: String(exitCode), + }, + }, + ); + assert.ifError(result.error); + return { + ...result, + output: existsSync(outputFile) ? readFileSync(outputFile, "utf8") : "", + }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +for (const [name, script] of steps) { + for (const [label, stdout] of [ + ["plain URL", url], + ["lockfile warning", `${warning}\n${url}`], + ["trailing diagnostic", `${url}\nDone`], + ]) { + test(`${name}: saves one deployment URL after ${label}`, () => { + const result = runStep(script, stdout); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual( + result.output.split("\n").filter((line) => !line.startsWith("project_id=")), + [`deployment_url=${url}`, ""], + ); + }); + } + + for (const [label, stdout, exitCode] of [ + ["missing URL", warning, 0], + ["invalid URL", "https://example.invalid/deployment", 0], + ["multiple URLs", `${url}\nhttps://other.vercel.app`, 0], + ["failed deployment", url, 1], + ]) { + test(`${name}: rejects ${label} without saving output`, () => { + const result = runStep(script, stdout, exitCode); + assert.notEqual(result.status, 0); + assert.equal(result.output, ""); + }); + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b92d4095f205..8023fafd61559 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,6 +59,9 @@ jobs: # file, docs included. The `Check` job at the end of this file passes only # when every other job passes or was skipped by `changes`. lint: + permissions: + contents: read + id-token: write name: Lint runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 @@ -82,6 +85,16 @@ jobs: - name: Setup Vite+ uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} + + # electron's install.js (run by ensure:electron) reads this cache before it + # downloads from GitHub. The key changes only with the Electron version. + - name: Cache Electron download + uses: actions/cache@v6 + with: + path: ~/.cache/electron + key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} - name: Ensure Electron runtime is installed run: vp run --filter @t3tools/desktop ensure:electron @@ -93,10 +106,16 @@ jobs: - name: Check generated GitHub GraphQL operations run: vp run --filter @t3tools/source-control-github generate --check + - name: Check generated Expo GraphQL operations + run: vp run --filter t3 generate --check + - name: Check run: vp check build: + permissions: + contents: read + id-token: write name: Build and Typecheck needs: changes if: ${{ !cancelled() && (needs.changes.outputs.build != 'false' || needs.changes.outputs.typecheck != 'false') }} @@ -128,6 +147,16 @@ jobs: - name: Setup Vite+ uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} + + # electron's install.js (run by ensure:electron) reads this cache before it + # downloads from GitHub. The key changes only with the Electron version. + - name: Cache Electron download + uses: actions/cache@v6 + with: + path: ~/.cache/electron + key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} - name: Ensure Electron runtime is installed id: electron @@ -178,6 +207,9 @@ jobs: # dependency layers. The concurrency limit stays at the default 4 so peak load # per runner is unchanged. test: + permissions: + contents: read + id-token: write name: Test needs: changes if: ${{ !cancelled() && needs.changes.outputs.test != 'false' }} @@ -218,6 +250,16 @@ jobs: - name: Setup Vite+ uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} + + # electron's install.js (run by ensure:electron) reads this cache before it + # downloads from GitHub. The key changes only with the Electron version. + - name: Cache Electron download + uses: actions/cache@v6 + with: + path: ~/.cache/electron + key: electron-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('node_modules/.pnpm/electron@*/node_modules/electron/package.json') }} - name: Ensure Electron runtime is installed run: vp run --filter @t3tools/desktop ensure:electron @@ -226,7 +268,7 @@ jobs: run: python3 -B .github/scripts/stage-preview-bundle.test.py - name: Test release checks - run: node --test .github/scripts/check-nightly-release.test.cjs + run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs - name: Finish installing browser secret helper build libraries timeout-minutes: 5 @@ -249,7 +291,11 @@ jobs: # The web suite is the largest outside the server. In the shared Test job it # started last and ran alone for about 40s after everything else finished. + # release.yml mirrors this test, test_web, and test_server split. test_web: + permissions: + contents: read + id-token: write name: Test Web needs: changes if: ${{ !cancelled() && needs.changes.outputs.test_web != 'false' }} @@ -267,6 +313,8 @@ jobs: - name: Setup Vite+ uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} # The browser project runs React tests in headless Chromium. Same cache key as # test_server, so both jobs share one downloaded browser. @@ -305,6 +353,9 @@ jobs: # The shards are the longest jobs, so they gate themselves instead of waiting # ~15s for `changes`: a shard the change cannot affect stops after checkout. test_server: + permissions: + contents: read + id-token: write name: Test Server ${{ matrix.shard }} runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 10 @@ -331,6 +382,8 @@ jobs: - name: Setup Vite+ if: steps.changes.outputs.test_server != 'false' uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} # No Electron setup here: `t3` (apps/server) has no Electron dependency # and none of its tests touch the runtime. Only the non-server `test` @@ -467,6 +520,9 @@ jobs: run: vp run lint:mobile release_smoke: + permissions: + contents: read + id-token: write name: Release Smoke needs: changes if: ${{ !cancelled() && needs.changes.outputs.release_smoke != 'false' }} @@ -482,10 +538,10 @@ jobs: !/apps/mobile/modules/t3-terminal/Vendor/**/*.a sparse-checkout-cone-mode: false - # A full install: a filtered one that misses the cache first saves its - # partial store under the shared lockfile key for every later job. - name: Setup Vite+ uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} - name: Exercise release-only workflow steps run: node scripts/release-smoke.ts diff --git a/.github/workflows/cursor-hygiene-webhook.yml b/.github/workflows/cursor-hygiene-webhook.yml deleted file mode 100644 index 8f8dde38a5fe6..0000000000000 --- a/.github/workflows/cursor-hygiene-webhook.yml +++ /dev/null @@ -1,50 +0,0 @@ -name: Forward to Cursor hygiene - -on: - push: - branches: [main] - pull_request: - types: [opened, reopened, ready_for_review] - issues: - types: [opened, closed, reopened] - discussion: - types: [created, closed, reopened] - -permissions: - contents: read - -jobs: - forward: - name: POST to Cursor - runs-on: ubuntu-24.04 - steps: - - name: POST to Cursor - env: - URL: ${{ secrets.CURSOR_T3CODE_WEBHOOK_URL }} - AUTH: ${{ secrets.CURSOR_T3CODE_WEBHOOK_AUTH }} - run: | - set -euo pipefail - if [ -z "${URL:-}" ] || [ -z "${AUTH:-}" ]; then - echo "Missing CURSOR_T3CODE_WEBHOOK_URL or CURSOR_T3CODE_WEBHOOK_AUTH — skipping." - exit 0 - fi - for attempt in 1 2 3; do - curl_status=0 - http_status=$(curl -fsS --max-time 60 -X POST "$URL" \ - --output /dev/null --write-out '%{http_code}' \ - -H "Authorization: $AUTH" \ - -H "Content-Type: application/json" \ - -H "X-GitHub-Event: ${{ github.event_name }}" \ - -H "X-GitHub-Delivery: ${{ github.run_id }}-${{ github.run_attempt }}" \ - --data-binary @"${{ github.event_path }}") || curl_status=$? - if [ "$curl_status" -eq 0 ]; then - exit 0 - fi - if [ "$GITHUB_REF" != "refs/heads/main" ] || \ - [ "$curl_status" -ne 22 ] || [ "$http_status" != "400" ] || \ - [ "$attempt" -eq 3 ]; then - exit "$curl_status" - fi - echo "Cursor webhook returned HTTP 400; retrying in 5 seconds ($attempt/2)." - sleep 5 - done diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index 400f7152c617e..bf8591f81da9b 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -27,7 +27,7 @@ jobs: deploy_relay: name: Deploy production relay # A manual run from another branch would deploy that branch to production. - if: github.ref == 'refs/heads/main' + if: github.repository == 'pingdotgg/t3code' && github.ref == 'refs/heads/main' runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 15 environment: @@ -41,6 +41,8 @@ jobs: RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }} RELAY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_TUNNEL_CLEANUP_MODE }} RELAY_LEGACY_TUNNEL_CLEANUP_MODE: ${{ vars.RELAY_LEGACY_TUNNEL_CLEANUP_MODE }} + RELAY_ALERT_NOTIFIER_ID: ${{ vars.RELAY_ALERT_NOTIFIER_ID }} + RELAY_WARNING_NOTIFIER_ID: ${{ vars.RELAY_WARNING_NOTIFIER_ID }} CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }} APNS_ENVIRONMENT: ${{ vars.APNS_ENVIRONMENT }} diff --git a/.github/workflows/desktop-macos-preview.yml b/.github/workflows/desktop-macos-preview.yml index 43b6c8220aaf3..6dcdd702c2da1 100644 --- a/.github/workflows/desktop-macos-preview.yml +++ b/.github/workflows/desktop-macos-preview.yml @@ -78,7 +78,10 @@ jobs: - name: Install browser secret helper build libraries run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config + # desktop-macos-preview-publish.yml packages this bundle as the preview channel. - name: Build JS bundle + env: + T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && 'preview' || 'dev' }} run: vp run build:desktop # Same layout as release.yml's js-bundle so release-desktop.yml can diff --git a/.github/workflows/mobile-android-apk.yml b/.github/workflows/mobile-android-apk.yml index c3db7142e67ff..18d977c50f4a0 100644 --- a/.github/workflows/mobile-android-apk.yml +++ b/.github/workflows/mobile-android-apk.yml @@ -15,6 +15,7 @@ concurrency: jobs: mirror: name: Mirror beta APK + if: github.repository == 'pingdotgg/t3code' runs-on: blacksmith-2vcpu-ubuntu-2404 timeout-minutes: 10 permissions: diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index 16be6ee5f2968..b6581e0e8ea49 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -75,6 +75,7 @@ concurrency: jobs: production: name: EAS ${{ inputs.profile || 'production' }} ${{ github.event_name == 'push' && 'auto' || inputs.mode }} + if: github.repository == 'pingdotgg/t3code' runs-on: blacksmith-8vcpu-ubuntu-2404 permissions: contents: read diff --git a/.github/workflows/mobile-showcase-screenshots.yml b/.github/workflows/mobile-showcase-screenshots.yml index fc75c447c6db7..c02be425c1ab7 100644 --- a/.github/workflows/mobile-showcase-screenshots.yml +++ b/.github/workflows/mobile-showcase-screenshots.yml @@ -43,7 +43,7 @@ env: jobs: ios: - name: iPhone 6.9, iPhone 6.5, and iPad 13 + name: iPhone, iPhone Duo, and iPad 13 if: inputs.platform == 'all' || inputs.platform == 'ios' runs-on: blacksmith-12vcpu-macos-26 # Capturing every palette multiplies the device matrix by six, and only the @@ -87,6 +87,9 @@ jobs: brew install cameroncooke/axe/axe axe --version + - name: Install foldable simulator controls + run: npm install --global agent-device@0.21.25 + - name: Capture iOS showcase run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --theme "${{ inputs.theme }}" diff --git a/.github/workflows/publish-aur.yml b/.github/workflows/publish-aur.yml index 62f8fd1f5470c..4ab6db89ab703 100644 --- a/.github/workflows/publish-aur.yml +++ b/.github/workflows/publish-aur.yml @@ -37,6 +37,7 @@ concurrency: jobs: publish: name: Validate and publish + if: github.repository == 'pingdotgg/t3code' runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 30 container: diff --git a/.github/workflows/relay-preview-cleanup.yml b/.github/workflows/relay-preview-cleanup.yml new file mode 100644 index 0000000000000..eed067adfd773 --- /dev/null +++ b/.github/workflows/relay-preview-cleanup.yml @@ -0,0 +1,203 @@ +name: Clean up relay preview + +# Tears down stage `pr-` when `relay:preview` is removed or the PR closes, +# and retries teardown for closed labeled PRs on a schedule. A label stays on a +# PR only while its teardown is outstanding, so the scheduled retry lists +# exactly the failures. +# +# This runs under pull_request_target, so the workflow and the Alchemy program +# come from the default branch. No PR code runs here, which is why it needs no +# reviewer approval and why a PR cannot edit its own teardown to reach secrets. +on: + pull_request_target: + types: [unlabeled, closed] + schedule: + - cron: "17 7 * * *" + workflow_dispatch: + +permissions: + contents: read + issues: read + pull-requests: read + +jobs: + cleanup_pr: + name: Tear down relay preview + if: >- + github.ref == 'refs/heads/main' && + github.event_name == 'pull_request_target' && + ( + (github.event.action == 'unlabeled' && github.event.label.name == 'relay:preview') || + (github.event.action == 'closed' && contains(github.event.pull_request.labels.*.name, 'relay:preview')) + ) + # Job-level so that events which skip this job, such as a closed PR without + # the label, never take the group's pending slot. GitHub replaces a pending + # run in a group with a newer one, which would drop a queued teardown. + concurrency: + group: relay-preview-${{ github.event.pull_request.number }} + cancel-in-progress: false + permissions: + contents: read + issues: write + pull-requests: write + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 30 + environment: + name: relay-preview-cleanup + env: + GH_TOKEN: ${{ github.token }} + STAGE: pr-${{ github.event.pull_request.number }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }} + AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }} + RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }} + RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }} + CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} + CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }} + APNS_ENABLED: "false" + ALCHEMY_TELEMETRY_DISABLED: "1" + steps: + - name: Checkout default branch + uses: actions/checkout@v6 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: | + args: + - --filter=t3code-relay... + + # Destroy also runs the preview tunnel sweep, which is part of the stack. + - name: Destroy preview stage + run: vp run --filter t3code-relay destroy --stage "$STAGE" --yes --no-input + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }} + PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }} + AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} + CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} + + # Only reached after a successful destroy. A failed one keeps the label, + # so the scheduled retry picks the PR up again. + - name: Clear the teardown marker + if: github.event.action == 'closed' + run: gh pr edit "${{ github.event.pull_request.number }}" --repo "$GITHUB_REPOSITORY" --remove-label relay:preview + + # An unlabeled event has already removed the label, so a failed teardown + # must put it back or no retry will ever see the stage. Labels added with + # GITHUB_TOKEN do not start new runs, so this does not redeploy. + - name: Restore the teardown marker after a failed destroy + if: failure() && github.event.action == 'unlabeled' + run: gh pr edit "${{ github.event.pull_request.number }}" --repo "$GITHUB_REPOSITORY" --add-label relay:preview + + list_closed_previews: + name: List closed relay previews + if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request_target' + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 10 + outputs: + numbers: ${{ steps.list.outputs.numbers }} + steps: + # The issues endpoint is paginated by gh, so there is no listing cap. Pull + # requests appear there with a `pull_request` key. + - name: List closed PRs labeled relay:preview + id: list + env: + GH_TOKEN: ${{ github.token }} + run: | + numbers=$(gh api --paginate --method GET "repos/$GITHUB_REPOSITORY/issues" \ + -f labels=relay:preview -f state=closed -f per_page=100 \ + --jq '.[] | select(.pull_request) | .number') \ + || { echo "Could not list closed relay:preview PRs" >&2; exit 1; } + json=$(printf '%s\n' "$numbers" | jq -Rsc 'split("\n") | map(select(length > 0) | tonumber)') + echo "Closed relay:preview PRs: $json" + echo "numbers=$json" >> "$GITHUB_OUTPUT" + + sweep_pr: + name: Retry teardown for PR ${{ matrix.number }} + needs: list_closed_previews + if: github.ref == 'refs/heads/main' && needs.list_closed_previews.outputs.numbers != '[]' + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 30 + strategy: + fail-fast: false + max-parallel: 4 + matrix: + number: ${{ fromJSON(needs.list_closed_previews.outputs.numbers) }} + # Same group as the deploy and teardown for this PR, so a reopened PR's + # deploy cannot run concurrently with a teardown of its previous stage. + concurrency: + group: relay-preview-${{ matrix.number }} + cancel-in-progress: false + permissions: + contents: read + issues: write + pull-requests: write + environment: + name: relay-preview-cleanup + env: + GH_TOKEN: ${{ github.token }} + STAGE: pr-${{ matrix.number }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }} + AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }} + RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }} + RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }} + CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} + CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }} + APNS_ENABLED: "false" + ALCHEMY_TELEMETRY_DISABLED: "1" + steps: + # The lock above is taken before this runs, so the state read here is + # current. An open PR, including one reopened since the listing, is left + # alone. GitHub reports merged PRs as MERGED, so anything not OPEN counts. + - name: Confirm the PR is not open + id: eligible + run: | + state=$(gh pr view "${{ matrix.number }}" --repo "$GITHUB_REPOSITORY" \ + --json state --jq 'if .state == "OPEN" then "no" else "yes" end') \ + || { echo "Could not read PR ${{ matrix.number }}" >&2; exit 1; } + echo "eligible=$state" >> "$GITHUB_OUTPUT" + [ "$state" = yes ] || echo "PR ${{ matrix.number }} is open again; leaving $STAGE alone." + + - name: Checkout default branch + if: steps.eligible.outputs.eligible == 'yes' + uses: actions/checkout@v6 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup Vite+ + if: steps.eligible.outputs.eligible == 'yes' + uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: | + args: + - --filter=t3code-relay... + + - name: Destroy preview stage + if: steps.eligible.outputs.eligible == 'yes' + run: vp run --filter t3code-relay destroy --stage "$STAGE" --yes --no-input + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }} + PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }} + AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} + CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} + + - name: Clear the teardown marker + if: steps.eligible.outputs.eligible == 'yes' + run: gh pr edit "${{ matrix.number }}" --repo "$GITHUB_REPOSITORY" --remove-label relay:preview diff --git a/.github/workflows/relay-preview.yml b/.github/workflows/relay-preview.yml new file mode 100644 index 0000000000000..53a71110cef1f --- /dev/null +++ b/.github/workflows/relay-preview.yml @@ -0,0 +1,81 @@ +name: Deploy relay preview + +# Labeling a same-repository PR `relay:preview` deploys Alchemy stage `pr-`. +# This job runs the PR's own code with account credentials, so it waits for an +# approval in the `relay-preview` environment on every run. Teardown is in +# relay-preview-cleanup.yml and never runs PR code. +on: + pull_request: + types: [labeled, synchronize, reopened] + +permissions: + contents: read + pull-requests: read + +concurrency: + group: relay-preview-${{ github.event.pull_request.number }} + cancel-in-progress: false + +jobs: + deploy_preview: + name: Deploy relay preview + if: >- + github.event.pull_request.head.repo.full_name == github.repository && + contains(github.event.pull_request.labels.*.name, 'relay:preview') + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 20 + environment: + name: relay-preview + env: + STAGE: pr-${{ github.event.pull_request.number }} + CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }} + PLANETSCALE_ORGANIZATION: ${{ vars.PLANETSCALE_ORGANIZATION }} + AXIOM_ORG_ID: ${{ vars.AXIOM_ORG_ID }} + RELAY_API_ZONE_NAME: ${{ vars.RELAY_API_ZONE_NAME }} + RELAY_TUNNEL_ZONE_NAME: ${{ vars.RELAY_TUNNEL_ZONE_NAME }} + CLERK_PUBLISHABLE_KEY: ${{ vars.CLERK_PUBLISHABLE_KEY }} + CLERK_JWT_AUDIENCE: ${{ vars.CLERK_JWT_AUDIENCE }} + # Previews take no alert notifier, no tunnel cleanup, and no custom + # domain, so they stay silent and reap nothing outside their own stage. + APNS_ENABLED: "false" + ALCHEMY_TELEMETRY_DISABLED: "1" + steps: + - name: Confirm the PR is still open and labeled + env: + GH_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + state=$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --json state,labels \ + --jq 'if .state == "OPEN" and any(.labels[]; .name == "relay:preview") then "ok" else "stale" end') + if [ "$state" != "ok" ]; then + echo "PR #$PR_NUMBER is no longer open with relay:preview; not deploying." >&2 + exit 1 + fi + + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@v1 + with: + node-version-file: package.json + cache: true + run-install: | + args: + - --filter=t3code-relay... + + - name: Deploy preview stage + run: vp run --filter t3code-relay deploy --stage "$STAGE" --yes --no-input + env: + T3CODE_RELAY_CLIENT_CONFIG_ENV: ${{ runner.temp }}/relay-client-config.env + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + PLANETSCALE_API_TOKEN_ID: ${{ secrets.PLANETSCALE_API_TOKEN_ID }} + PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }} + AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} + CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 7c2bcc89bb1a0..516a0a7785a95 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -64,6 +64,13 @@ on: required: false default: false type: boolean + # A runner of the target's own platform and architecture, for a `runner` + # that cannot execute the target. The build job skips everything that + # runs the packaged binaries, and a second job runs it there. + verify_runner: + required: false + default: "" + type: string version: required: true type: string @@ -92,6 +99,11 @@ on: required: true type: string +# electron-builder leaves the default arch (x64) out of the unpacked app's +# directory name. +env: + UNPACKED_DIR: ${{ inputs.platform }}-${{ inputs.arch != 'x64' && format('{0}-', inputs.arch) || '' }}unpacked + permissions: # Windows builds read this run's artifact list to wait for the Linux CLI archive. actions: read @@ -129,50 +141,11 @@ jobs: git sparse-checkout set --no-cone '/*' '!/.repos/' git -c checkout.workers=0 checkout --detach FETCH_HEAD - # The runner's PowerShell 7.6/.NET 10 intermittently crashes during signing: - # https://github.com/dotnet/runtime/issues/131636 - # Put the .NET 8 release first for both workflow shells and electron-builder. - - name: Use PowerShell 7.4 for Windows ARM builds - if: inputs.platform == 'win' && inputs.arch == 'arm64' - shell: powershell - run: | - $ErrorActionPreference = "Stop" - $ProgressPreference = "SilentlyContinue" - $version = "7.4.20" - $archive = Join-Path $env:RUNNER_TEMP "PowerShell-$version-win-arm64.zip" - $installDir = Join-Path $env:RUNNER_TEMP "powershell-$version-arm64" - Invoke-WebRequest -UseBasicParsing ` - -Uri "https://github.com/PowerShell/PowerShell/releases/download/v$version/PowerShell-$version-win-arm64.zip" ` - -OutFile $archive - $expectedHash = "67eff749d5dae357501c95a3eec1dcd93f669824e3ca2b1d2adcdecdebf04f35" - if ((Get-FileHash $archive -Algorithm SHA256).Hash -ne $expectedHash) { - throw "PowerShell archive checksum mismatch" - } - Expand-Archive -Path $archive -DestinationPath $installDir - $installDir | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - & "$installDir\pwsh.exe" -NoProfile -NonInteractive -Command '$PSVersionTable; [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture' - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - - - name: Verify Windows ARM PowerShell selection - if: inputs.platform == 'win' && inputs.arch == 'arm64' - shell: pwsh - run: | - $expectedPath = Join-Path $env:RUNNER_TEMP "powershell-7.4.20-arm64\pwsh.exe" - if ((Get-Command pwsh.exe).Source -ne $expectedPath -or $PSVersionTable.PSVersion -ne [version]"7.4.20") { - throw "Windows ARM builds must use the pinned PowerShell runtime" - } - - # Windows installs straight from the registry. There, linking the packages - # takes the time, not downloading them, so a ~700 MB package cache did not - # pay for its own restore. Across recent nightlies, restore plus install - # took 183-233s on arm64 and 116-172s on x64, while a plain install took - # 142-210s and 84-160s. The arm64 entries also filled 4 GB of the - # repository's 10 GB Actions cache. - name: Setup Vite+ uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 with: node-version-file: package.json - cache: ${{ inputs.platform != 'win' }} + cache: true run-install: false # pnpm checks the lockfile and policy before reusing this result. A missing @@ -241,25 +214,140 @@ jobs: name: js-bundle path: apps - # Only the resource monitor build needs these libraries. With a cached - # monitor, the desktop build's preflight skips its MSVC check, and node-pty - # ships prebuilt Windows binaries, so the 30-60s install is skipped too. - - name: Install Spectre-mitigated MSVC libs + - name: Install cargo-xwin if: inputs.platform == 'win' && steps.resource_monitor_cache.outputs.cache-hit != 'true' - shell: pwsh + uses: taiki-e/install-action@8cca0918f8471c33515202b73f56ab27f2bed283 # v2 + with: + tool: cargo-xwin@0.23.1 + + # Built here rather than inside the desktop build so the CLI archive, + # which bundles the same binary, can be built and uploaded first. + - name: Build resource monitor + if: steps.resource_monitor_cache.outputs.cache-hit != 'true' + shell: bash + run: cargo ${{ inputs.platform == 'win' && 'xwin build' || 'build' }} --locked --release --manifest-path native/resource-monitor/Cargo.toml --target "${{ inputs.rust_target }}" + + # Off Windows, scripts/lib/windows-jsign.ts signs through jsign instead of + # the TrustedSigning PowerShell module. + - name: Install jsign + if: inputs.platform == 'win' + shell: bash run: | - $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" - $installPath = & $vswhere -products * -latest -property installationPath - $setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe" - $proc = Start-Process -FilePath $setupExe ` - -ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", ` - "Microsoft.VisualStudio.Component.VC.Runtimes.${{ inputs.arch == 'arm64' && 'ARM64' || 'x86.x64' }}.Spectre", "--quiet", "--norestart" ` - -Wait -PassThru -NoNewWindow - if ($null -eq $proc -or $proc.ExitCode -ne 0) { - $code = if ($null -ne $proc) { $proc.ExitCode } else { 1 } - Write-Error "Visual Studio Installer failed with exit code $code" - exit $code - } + set -euo pipefail + dir="$RUNNER_TEMP/jsign" + mkdir -p "$dir" + curl -fsSL --retry 3 -o "$dir/jsign.jar" https://github.com/ebourg/jsign/releases/download/7.6/jsign-7.6.jar + echo "6cf58aa080e7ff82656f320cff8d4a3bff30408df8766806dcba3740dd839fa5 $dir/jsign.jar" | sha256sum -c - + printf '#!/bin/sh\nexec java -jar "%s" "$@"\n' "$dir/jsign.jar" > "$dir/jsign" + chmod +x "$dir/jsign" + echo "T3CODE_JSIGN=$dir/jsign" >> "$GITHUB_ENV" + + # The desktop build applies the same branding to apps/server/dist/client + # (resolveDesktopWebAssetBrand in scripts/build-desktop-artifact.ts); the + # CLI archive below ships that client and is now built first. + - name: Apply web client branding + if: inputs.cli_archive + shell: bash + run: | + brand=production + if [[ "${{ inputs.version }}" =~ -nightly\.[0-9]{8}\.[0-9]+$ ]]; then brand=nightly; fi + node scripts/apply-web-brand-assets.ts "$brand" apps/server/dist/client + + # Setup Vite+ selects the exact engines.node version from package.json. + # Native builds embed that executable; cross-target builds download the + # same version for their target. + - name: Build CLI single-executable + if: inputs.cli_archive + shell: bash + env: + # The executable bundles the server again, so it needs the same stamp + # as release.yml's JS bundle. + T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && inputs.release_channel || 'dev' }} + run: node apps/server/scripts/cli.ts build-exe --verbose ${{ inputs.platform == 'win' && format('--target win-{0}', inputs.arch) || '' }} + + - name: Import macOS signing certificate for the CLI archive + if: inputs.cli_archive && inputs.platform == 'mac' + shell: bash + env: + CSC_LINK: ${{ secrets.CSC_LINK }} + CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} + run: | + set -euo pipefail + if [[ -z "$CSC_LINK" || -z "$CSC_KEY_PASSWORD" ]]; then + echo "macOS CLI signing disabled (missing CSC_LINK); the archive is signed ad hoc." + exit 0 + fi + keychain="$RUNNER_TEMP/t3-cli-signing.keychain-db" + keychain_password="$(openssl rand -hex 16)" + cert_path="$RUNNER_TEMP/t3-cli-signing.p12" + printf '%s' "$CSC_LINK" | base64 --decode > "$cert_path" + security create-keychain -p "$keychain_password" "$keychain" + security set-keychain-settings -lut 21600 "$keychain" + security unlock-keychain -p "$keychain_password" "$keychain" + security import "$cert_path" -k "$keychain" -P "$CSC_KEY_PASSWORD" -T /usr/bin/codesign + security set-key-partition-list -S apple-tool:,apple: -s -k "$keychain_password" "$keychain" >/dev/null + security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"') + identity="$(security find-identity -v -p codesigning "$keychain" | sed -n 's/.*"\(Developer ID Application: [^"]*\)".*/\1/p' | head -n 1)" + if [[ -z "$identity" ]]; then + echo "No Developer ID Application identity found in CSC_LINK." >&2 + exit 1 + fi + echo "::add-mask::$keychain_password" + echo "T3CODE_CLI_MAC_SIGN_IDENTITY=$identity" >> "$GITHUB_ENV" + echo "macOS CLI signing enabled." + + - name: Stage resource monitor for the CLI archive + if: inputs.cli_archive + shell: bash + run: | + set -euo pipefail + binary_name="t3-resource-monitor" + if [[ "${{ inputs.platform }}" == "win" ]]; then + binary_name="${binary_name}.exe" + fi + target_dir="$RUNNER_TEMP/cli-resource-monitor/${{ inputs.resource_key }}" + mkdir -p "$target_dir" + cp "native/resource-monitor/target/${{ inputs.rust_target }}/release/${binary_name}" "$target_dir/$binary_name" + + - name: Build CLI archive + if: inputs.cli_archive + shell: bash + env: + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} + AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} + AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }} + run: | + set -euo pipefail + if [[ "${{ inputs.platform }}" == "mac" && -n "${APPLE_API_KEY:-}" ]]; then + key_path="$RUNNER_TEMP/AuthKey_cli_${APPLE_API_KEY_ID}.p8" + printf '%s' "$APPLE_API_KEY" > "$key_path" + export APPLE_API_KEY="$key_path" + fi + node scripts/build-cli-archive.ts \ + --platform "${{ inputs.platform }}" \ + --arch "${{ inputs.arch }}" \ + --version "${{ inputs.version }}" \ + --resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \ + --output-dir release-cli + + - name: Smoke-test CLI archive + if: inputs.cli_archive && inputs.verify_runner == '' + shell: bash + run: node scripts/smoke-cli-archive.ts --archive release-cli/* --expect-version "${{ inputs.version }}" + + - name: Upload CLI archive + if: inputs.cli_archive + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: cli-${{ inputs.platform }}-${{ inputs.arch }} + path: release-cli/* + if-no-files-found: error - uses: ./.github/actions/setup-apt-mirrors if: inputs.platform == 'linux' @@ -280,68 +368,6 @@ jobs: convert -version fi - - name: Prepare Azure Trusted Signing - if: inputs.platform == 'win' - shell: pwsh - env: - AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} - AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} - AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} - AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} - AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }} - AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }} - run: | - $ErrorActionPreference = "Stop" - - $requiredSecrets = @( - $env:AZURE_TENANT_ID, - $env:AZURE_CLIENT_ID, - $env:AZURE_CLIENT_SECRET, - $env:AZURE_TRUSTED_SIGNING_ENDPOINT, - $env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME, - $env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME, - $env:AZURE_TRUSTED_SIGNING_PUBLISHER_NAME - ) - if ($requiredSecrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) { - Write-Host "Azure Trusted Signing disabled; skipping TrustedSigning module preparation." - exit 0 - } - - try { - Install-PackageProvider ` - -Name NuGet ` - -MinimumVersion 2.8.5.201 ` - -Force ` - -Scope CurrentUser ` - -ErrorAction Stop - } catch { - Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)" - } - - Install-Module ` - -Name TrustedSigning ` - -MinimumVersion 0.5.0 ` - -Force ` - -AllowClobber ` - -Repository PSGallery ` - -Scope CurrentUser ` - -ErrorAction Stop - - Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force - Get-Command Invoke-TrustedSigning -ErrorAction Stop - - $moduleRoots = @( - [System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "PowerShell", "Modules"), - [System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "WindowsPowerShell", "Modules"), - [System.IO.Path]::Combine($env:ProgramFiles, "PowerShell", "Modules"), - [System.IO.Path]::Combine($env:ProgramFiles, "WindowsPowerShell", "Modules") - ) - $modulePathEntries = @($moduleRoots + ($env:PSModulePath -split ";")) | - Where-Object { $_ -and (Test-Path $_) } | - Select-Object -Unique - "PSModulePath=$($modulePathEntries -join ';')" >> $env:GITHUB_ENV - # The WSL backend runs the Linux CLI archive inside the distro, so the # Windows desktop embeds the same-arch archive the release attaches. # This job starts alongside that Linux job instead of after it, and the @@ -407,7 +433,7 @@ jobs: shell: bash env: pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata - T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: ${{ steps.resource_monitor_cache.outputs.cache-hit == 'true' }} + T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: true T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS: ${{ steps.capture_helper_cache.outputs.cache-hit == 'true' }} CSC_LINK: ${{ secrets.CSC_LINK }} CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} @@ -433,6 +459,9 @@ jobs: --skip-build --verbose ) + if [[ -n "${{ inputs.verify_runner }}" ]]; then + args+=(--keep-stage) + fi has_all() { for value in "$@"; do @@ -488,104 +517,35 @@ jobs: vp run dist:desktop:artifact "${args[@]}" - # The single-executable is built with a Node that supports --build-sea - # (25.7+); the repo itself stays on the engines.node version. It always - # injects into the runner's own Node: tsdown's cross-target download path - # runs `tar` on a drive-letter path on Windows, which GNU tar reads as a - # remote host, and a cross-built macOS binary cannot be smoke-tested. - - name: Build CLI single-executable - if: inputs.cli_archive - shell: bash - env: - # The exact version, not a major: vp downloads it from nodejs.org/dist on - # the runner, and only exact versions have a dist directory. Keep in - # step with SEA_NODE_VERSION in apps/server/vite.config.ts. - VP_NODE_VERSION: "26.8.2" - run: node apps/server/scripts/cli.ts build-exe --verbose - - - name: Import macOS signing certificate for the CLI archive - if: inputs.cli_archive && inputs.platform == 'mac' + # The verify job runs what this host could not: the packaged natives and + # the CLI. Its scripts are bundled so that job needs no install. + - name: Stage verification inputs + if: inputs.verify_runner != '' shell: bash - env: - CSC_LINK: ${{ secrets.CSC_LINK }} - CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} run: | set -euo pipefail - if [[ -z "$CSC_LINK" || -z "$CSC_KEY_PASSWORD" ]]; then - echo "macOS CLI signing disabled (missing CSC_LINK); the archive is signed ad hoc." - exit 0 - fi - keychain="$RUNNER_TEMP/t3-cli-signing.keychain-db" - keychain_password="$(openssl rand -hex 16)" - cert_path="$RUNNER_TEMP/t3-cli-signing.p12" - printf '%s' "$CSC_LINK" | base64 --decode > "$cert_path" - security create-keychain -p "$keychain_password" "$keychain" - security set-keychain-settings -lut 21600 "$keychain" - security unlock-keychain -p "$keychain_password" "$keychain" - security import "$cert_path" -k "$keychain" -P "$CSC_KEY_PASSWORD" -T /usr/bin/codesign - security set-key-partition-list -S apple-tool:,apple: -s -k "$keychain_password" "$keychain" >/dev/null - security list-keychains -d user -s "$keychain" $(security list-keychains -d user | tr -d '"') - identity="$(security find-identity -v -p codesigning "$keychain" | sed -n 's/.*"\(Developer ID Application: [^"]*\)".*/\1/p' | head -n 1)" - if [[ -z "$identity" ]]; then - echo "No Developer ID Application identity found in CSC_LINK." >&2 - exit 1 - fi - echo "::add-mask::$keychain_password" - echo "T3CODE_CLI_MAC_SIGN_IDENTITY=$identity" >> "$GITHUB_ENV" - echo "macOS CLI signing enabled." - - - name: Stage resource monitor for the CLI archive - if: inputs.cli_archive - shell: bash - run: | - set -euo pipefail - binary_name="t3-resource-monitor" - if [[ "${{ inputs.platform }}" == "win" ]]; then - binary_name="${binary_name}.exe" - fi - target_dir="$RUNNER_TEMP/cli-resource-monitor/${{ inputs.resource_key }}" - mkdir -p "$target_dir" - cp "native/resource-monitor/target/${{ inputs.rust_target }}/release/${binary_name}" "$target_dir/$binary_name" - - - name: Build CLI archive - if: inputs.cli_archive - shell: bash - env: - APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} - APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} - APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} - AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} - AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} - AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} - AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }} - AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }} - AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }} - run: | - set -euo pipefail - if [[ "${{ inputs.platform }}" == "mac" && -n "${APPLE_API_KEY:-}" ]]; then - key_path="$RUNNER_TEMP/AuthKey_cli_${APPLE_API_KEY_ID}.p8" - printf '%s' "$APPLE_API_KEY" > "$key_path" - export APPLE_API_KEY="$key_path" - fi - node scripts/build-cli-archive.ts \ - --platform "${{ inputs.platform }}" \ - --arch "${{ inputs.arch }}" \ - --version "${{ inputs.version }}" \ - --resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \ - --output-dir release-cli - - - name: Smoke-test CLI archive - if: inputs.cli_archive - shell: bash - run: node scripts/smoke-cli-archive.ts --archive release-cli/* --expect-version "${{ inputs.version }}" - - - name: Upload CLI archive - if: inputs.cli_archive + mkdir -p verify + unpacked=$(ls -d "${TMPDIR:-/tmp}"/t3code-desktop-${{ inputs.platform }}-stage-*/app/dist/"$UNPACKED_DIR") + tar -C "$(dirname "$unpacked")" -cf verify/unpacked.tar "$(basename "$unpacked")" + esbuild=scripts/node_modules/.bin/esbuild + banner="import{createRequire as __cr}from'node:module';const require=__cr(import.meta.url);" + # build-desktop-artifact.ts's own import.meta.main guard must not run + # its CLI inside the verify bundle. + "$esbuild" scripts/verify-windows-desktop-artifact.ts --bundle --platform=node --format=esm \ + --target=node24 --define:import.meta.main=false --banner:js="$banner" \ + --outfile=verify/verify-windows-desktop-artifact.mjs + "$esbuild" scripts/smoke-cli-archive.ts --bundle --platform=node --format=esm \ + --target=node24 --banner:js="$banner" --outfile=verify/smoke-cli-archive.mjs + + - name: Upload verification inputs + if: inputs.verify_runner != '' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: - name: cli-${{ inputs.platform }}-${{ inputs.arch }} - path: release-cli/* + name: verify-${{ inputs.platform }}-${{ inputs.arch }} + path: verify/* if-no-files-found: error + retention-days: 1 + compression-level: 1 - name: Collect release assets shell: bash @@ -658,3 +618,81 @@ jobs: name: resource-monitor-${{ inputs.resource_key }} path: resource-monitor-publish/${{ inputs.resource_key }}/* if-no-files-found: error + + verify: + name: Verify + needs: [build] + if: inputs.verify_runner != '' + runs-on: ${{ inputs.verify_runner }} + timeout-minutes: 15 + steps: + - name: Download verification inputs + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: verify-${{ inputs.platform }}-${{ inputs.arch }} + path: verify + + - name: Download CLI archive + if: inputs.cli_archive + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: cli-${{ inputs.platform }}-${{ inputs.arch }} + path: release-cli + + - name: Verify packaged natives + shell: bash + run: | + set -euo pipefail + tar -C verify -xf verify/unpacked.tar + node verify/verify-windows-desktop-artifact.mjs \ + --app-dir "$(cygpath -w "$PWD/verify/$UNPACKED_DIR")" \ + --arch "${{ inputs.arch }}" --build-version "${{ inputs.version }}" --verbose + + - name: Smoke-test CLI archive + if: inputs.cli_archive + shell: bash + run: node verify/smoke-cli-archive.mjs --archive release-cli/* --expect-version "${{ inputs.version }}" + + # cargo-xwin links this binary on Linux, and nothing else runs it before users do. + # Node rather than pwsh: PowerShell on Windows ARM crashes intermittently + # (https://github.com/dotnet/runtime/issues/131636), which is why this + # target stopped building on Windows. + - name: Smoke-test resource monitor + shell: bash + env: + MONITOR: verify/${{ env.UNPACKED_DIR }}/resources/resource-monitor/t3-resource-monitor.exe + EXPECTED_ARCH: ${{ inputs.arch == 'arm64' && 'aarch64' || 'x86_64' }} + run: | + node --input-type=module <<'EOF' + import { spawn } from "node:child_process"; + const monitor = spawn(process.env.MONITOR, { stdio: ["pipe", "pipe", "inherit"] }); + monitor.stdout.setEncoding("utf8"); + let output = ""; + const exited = new Promise((resolve) => monitor.on("close", resolve)); + const hello = await new Promise((resolve, reject) => { + monitor.on("error", reject); + monitor.on("close", () => reject(new Error(`Resource monitor exited before hello: ${output}`))); + monitor.stdout.on("data", (chunk) => { + output += chunk; + const end = output.indexOf("\n"); + if (end !== -1) resolve(JSON.parse(output.slice(0, end))); + }); + }); + if (hello.type !== "hello" || hello.arch !== process.env.EXPECTED_ARCH) { + throw new Error(`Unexpected hello: ${JSON.stringify(hello)}`); + } + const send = (message) => monitor.stdin.write(`${JSON.stringify({ version: hello.version, ...message })}\n`); + send({ type: "configure", rootPid: process.pid, sampleIntervalMs: 1000 }); + send({ type: "sampleNow", requestId: "verify" }); + monitor.stdin.end(); + const exitCode = await exited; + const sample = output + .split("\n") + .filter((line) => line.trim()) + .map((line) => JSON.parse(line)) + .find((message) => message.requestId === "verify"); + if (exitCode !== 0 || sample?.type !== "snapshot" || !sample.processes.some((p) => p.pid === process.pid)) { + throw new Error(`Resource monitor exited ${exitCode} with: ${output}`); + } + console.log(`Resource monitor sampled ${sample.scannedProcessCount} processes.`); + EOF diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 715edafee09d6..d1045a239c876 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -50,6 +50,7 @@ jobs: # have already run. Scheduled runs also decide here whether a nightly is due. resolve_commit: name: Resolve release commit + if: github.repository == 'pingdotgg/t3code' runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 5 outputs: @@ -128,12 +129,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: true + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} env: pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata @@ -246,12 +245,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: true + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} - name: Ensure Electron runtime is installed run: vp run --filter @t3tools/desktop ensure:electron @@ -263,7 +260,7 @@ jobs: run: vp run typecheck # Keep tests on their own runners, using the same package split and server - # shards as CI, so the release check job does not spend its budget on tests. + # shards as CI (test, test_web, test_server in ci.yml). Keep the two in sync. test: name: Release tests needs: [preflight] @@ -280,12 +277,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: true + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} - name: Ensure Electron runtime is installed run: vp run --filter @t3tools/desktop ensure:electron @@ -297,23 +292,69 @@ jobs: sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config build-essential - # The web package's browser project runs React tests in headless Chromium. + - name: Test + run: vp run --parallel --concurrency-limit 4 --filter '!t3' --filter '!@t3tools/monorepo' --filter '!@t3tools/web' test + + # Web browser tests time out when they share a runner with the other package + # suites: Chromium gets too little CPU and diff workers miss their 10s start budget. + test_web: + name: Release web tests + needs: [preflight] + if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }} + runs-on: blacksmith-8vcpu-ubuntu-2404 + timeout-minutes: 10 + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + ref: ${{ needs.preflight.outputs.ref }} + sparse-checkout: | + /* + !/.repos/ + sparse-checkout-cone-mode: false + + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps + with: + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} + + - name: Resolve Playwright version + id: playwright_version + run: echo "version=$(node -p "require('./apps/web/node_modules/playwright/package.json').version")" >> "$GITHUB_OUTPUT" + + - name: Cache Chromium + id: chromium_cache + uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} + - name: Install Chromium for web browser tests - run: node apps/web/node_modules/playwright/cli.js install --with-deps --only-shell chromium + if: steps.chromium_cache.outputs.cache-hit != 'true' + run: node apps/web/node_modules/playwright/cli.js install --only-shell chromium + + - name: Install missing Chromium system dependencies + run: | + browser=$(find "$HOME/.cache/ms-playwright" -name chrome-headless-shell -type f -print -quit) + test -n "$browser" + if ldd "$browser" | grep '=> not found'; then + node apps/web/node_modules/playwright/cli.js install-deps chromium + fi - name: Test - run: vp run --parallel --concurrency-limit 4 --filter '!t3' --filter '!@t3tools/monorepo' test + run: vp run --filter @t3tools/web test + # Server test files run one at a time, so more small runners beat fewer big ones. test_server: name: Release server tests ${{ matrix.shard }} needs: [preflight] if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: blacksmith-4vcpu-ubuntu-2404 timeout-minutes: 10 strategy: fail-fast: false matrix: - shard: [1, 2, 3] + shard: [1, 2, 3, 4, 5, 6, 7, 8] steps: - name: Checkout uses: actions/checkout@v6 @@ -324,12 +365,10 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false - - name: Setup Vite+ - uses: voidzero-dev/setup-vp@v1 + - name: Setup dependencies + uses: ./.github/actions/setup-ci-deps with: - node-version-file: package.json - cache: true - run-install: true + task-cache-read-token: ${{ secrets.T3_TASK_CACHE_READ_TOKEN }} # No Electron setup here: `t3` (apps/server) has no Electron dependency # and none of its tests touch the runtime. Only the non-server `test` @@ -525,7 +564,11 @@ jobs: # Runs t3#build (which depends on @t3tools/web#build) and # @t3tools/desktop#build, so apps/server/dist holds the server bundle # plus the web client and apps/desktop/dist-electron the Electron main. + # The release channel is already stable, nightly, or preview. Builds in + # other repositories report "dev" telemetry. - name: Build JS bundle + env: + T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && needs.preflight.outputs.release_channel || 'dev' }} run: vp run build:desktop # Two paths under apps/ so the artifact root is apps/; consumers download @@ -540,8 +583,9 @@ jobs: if-no-files-found: error retention-days: 1 - # One job per platform and architecture (see release-desktop.yml), each on - # hardware of its own architecture, and each gated only on the JS bundle. + # One job per platform and architecture (see release-desktop.yml), each + # gated only on the JS bundle. Windows targets build on Linux and run their + # native checks on a Windows runner of their own architecture. # The Windows jobs also embed the same-arch Linux CLI archive as the WSL # runtime; they wait for that artifact partway through instead of for the # whole Linux job. Every job builds the desktop app; all but macOS x64 also @@ -644,9 +688,11 @@ jobs: resource_key: linux-arm64 cli_archive: true - # The Windows jobs start with the other platforms. Their checkout, install, - # and toolchain setup take longer than the same-arch Linux job needs to - # upload its CLI archive, so the wait inside is usually instant. + # The Windows jobs start with the other platforms and wait for the same-arch + # Linux CLI archive after their other setup. Packaging is mostly CPU and + # small-file work, which Linux runners do faster than Windows ones, so both + # Windows targets build and sign on Linux and only the native checks run on + # Windows. desktop_win_x64: name: Desktop Windows x64 needs: [preflight, relay_public_config, build_bundle] @@ -662,7 +708,8 @@ jobs: clerk_cli_oauth_client_id: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }} relay_url: ${{ needs.relay_public_config.outputs.relay_url }} label: Windows x64 - runner: blacksmith-32vcpu-windows-2025 + runner: blacksmith-16vcpu-ubuntu-2404 + verify_runner: windows-2025 platform: win target: nsis arch: x64 @@ -685,7 +732,8 @@ jobs: clerk_cli_oauth_client_id: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }} relay_url: ${{ needs.relay_public_config.outputs.relay_url }} label: Windows arm64 - runner: windows-11-arm + runner: blacksmith-16vcpu-ubuntu-2404 + verify_runner: windows-11-arm platform: win target: nsis arch: arm64 @@ -701,6 +749,7 @@ jobs: relay_public_config, quality, test, + test_web, test_server, desktop_mac_arm64, desktop_mac_x64, @@ -709,7 +758,7 @@ jobs: desktop_win_x64, desktop_win_arm64, ] - if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.quality.result == 'success' && needs.test.result == 'success' && needs.test_server.result == 'success' && needs.desktop_mac_arm64.result == 'success' && needs.desktop_mac_x64.result == 'success' && needs.desktop_linux_x64.result == 'success' && needs.desktop_linux_arm64.result == 'success' && needs.desktop_win_x64.result == 'success' && needs.desktop_win_arm64.result == 'success' }} + if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' && needs.quality.result == 'success' && needs.test.result == 'success' && needs.test_web.result == 'success' && needs.test_server.result == 'success' && needs.desktop_mac_arm64.result == 'success' && needs.desktop_mac_x64.result == 'success' && needs.desktop_linux_x64.result == 'success' && needs.desktop_linux_arm64.result == 'success' && needs.desktop_win_x64.result == 'success' && needs.desktop_win_arm64.result == 'success' }} runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 30 permissions: @@ -1033,7 +1082,7 @@ jobs: fi echo "Building hosted web app for $channel_name channel." - deployment_url="$( + deployment_output="$( vp dlx vercel@53.1.1 deploy \ --archive=tgz \ --prod \ @@ -1052,6 +1101,13 @@ jobs: --build-env "VITE_HOSTED_APP_URL=$router_url" \ --build-env "VITE_HOSTED_APP_CHANNEL=$channel_name" )" + printf '%s\n' "$deployment_output" + # Vercel can print lockfile warnings to stdout before the deployment URL. + deployment_url="$(printf '%s\n' "$deployment_output" | grep -E '^https://[[:alnum:].-]+\.vercel\.app$')" + if [[ "$deployment_url" == *$'\n'* ]]; then + echo "Vercel returned multiple deployment URLs." >&2 + exit 1 + fi echo "Staged $deployment_url." echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT" @@ -1180,7 +1236,7 @@ jobs: )" export VERCEL_PROJECT_ID - deployment_url="$( + deployment_output="$( vp dlx vercel@53.1.1 deploy \ --archive=tgz \ --prod \ @@ -1189,6 +1245,13 @@ jobs: --token "$VERCEL_TOKEN" \ --scope "${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}" )" + printf '%s\n' "$deployment_output" + # Vercel can print lockfile warnings to stdout before the deployment URL. + deployment_url="$(printf '%s\n' "$deployment_output" | grep -E '^https://[[:alnum:].-]+\.vercel\.app$')" + if [[ "$deployment_url" == *$'\n'* ]]; then + echo "Vercel returned multiple deployment URLs." >&2 + exit 1 + fi echo "Staged $deployment_url." echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT" echo "project_id=$VERCEL_PROJECT_ID" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/stale-needs-more-info.yml b/.github/workflows/stale-needs-more-info.yml new file mode 100644 index 0000000000000..b7b475a6117dc --- /dev/null +++ b/.github/workflows/stale-needs-more-info.yml @@ -0,0 +1,30 @@ +name: Close stale "needs more info" issues + +on: + schedule: + - cron: "17 6 * * *" + workflow_dispatch: + +permissions: + actions: write + issues: write + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + only-issue-labels: "needs more info" + # The label is applied by the triage flow, so never auto-mark; close 7 days after it was added. + days-before-issue-stale: -1 + days-before-issue-close: 7 + days-before-pr-stale: -1 + days-before-pr-close: -1 + remove-issue-stale-when-updated: true + stale-issue-label: "needs more info" + close-issue-reason: not_planned + close-issue-message: >- + Closing: no reply in 7 days after we asked for more information. + Comment with the missing details and we will reopen. + operations-per-run: 200 diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.yml index f9cc3b063fcdb..3def8478bbdc2 100644 --- a/.github/workflows/web-preview.yml +++ b/.github/workflows/web-preview.yml @@ -77,13 +77,20 @@ jobs: vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}" - deployment_url="$( + deployment_output="$( vp dlx vercel@53.1.1 deploy \ --archive=tgz \ --yes \ --token "$VERCEL_TOKEN" \ --scope "$vercel_scope" )" + printf '%s\n' "$deployment_output" + # Vercel can print lockfile warnings to stdout before the deployment URL. + deployment_url="$(printf '%s\n' "$deployment_output" | grep -E '^https://[[:alnum:].-]+\.vercel\.app$')" + if [[ "$deployment_url" == *$'\n'* ]]; then + echo "Vercel returned multiple deployment URLs." >&2 + exit 1 + fi echo "Deployed $deployment_url" echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT" diff --git a/.macroscope/check-run-agents/effect-service-conventions.md b/.macroscope/check-run-agents/effect-service-conventions.md index 52fd09fd1b333..f7cef3929ab10 100644 --- a/.macroscope/check-run-agents/effect-service-conventions.md +++ b/.macroscope/check-run-agents/effect-service-conventions.md @@ -44,6 +44,18 @@ Review changed TypeScript for the conventions below. They apply when a pull requ - Use plain `make` and `layer` in a module named for its implementation (`BunPtyAdapter.ts`). Keep implementation-specific names when one abstract port module holds several implementations (`makeCloudflaredRelayClient`, `layerCloudflared` in `RelayClient.ts`). `infra/relay/src/db.ts` may keep its inline `Layer.succeed(RelayDb, db)`. - When a service moves, delete the old files and update every consumer, including orchestration, MCP, tests, and integration harnesses. Do not leave compatibility re-export shims. +## Effect functions and tracing + +- Reusable functions use named `Effect.fn("Service.operation")`, not functions wrapping + `Effect.gen`. Inline programs, callbacks, and layer construction can keep `Effect.gen`. +- Named `Effect.fn` creates a span; the unnamed form does not. Default to named spans for service + operations and I/O. `Effect.fnUntraced` is deliberate for per-chunk/per-event work, tight loops, + or helpers duplicating an existing tracing boundary; require a nearby reason for new uses. +- Preserve existing span names/options and avoid adding duplicate spans. Pass combinators after + the generator body; transforms receive the original function arguments after the effect. +- Preserve generic signatures, laziness, resource scope, and interruption behavior. An explicit + generator return type is `Effect.fn.Return`. + ## Dependency acquisition and runtime boundaries - Production service construction acquires its Effect dependencies from the environment with `yield* Foo.Foo`, and `make`/`layer` types expose those requirements. Flag a factory that takes `Foo["Service"]` (or an object of Effect-returning methods) as a parameter when that value is a service dependency. Passing service instances explicitly in tests is fine; passing pure configuration, immutable domain values, or deliberate callback strategies is not service injection. @@ -57,6 +69,7 @@ Review changed TypeScript for the conventions below. They apply when a pull requ - Define service failures with `Schema.TaggedError` and structured attributes: operation or stage, resource path or entity identifier, normalized category or status. Derive `message` from those attributes only. Never derive it from `cause`, `cause.message`, or a stringified defect, and do not add a `detail` field that copies `cause.message`. - When wrapping a real failure, keep the immediate underlying error as `cause` so the chain and stack survive. Make `cause` required if every construction wraps a failure. Pure validation or domain errors created without an underlying failure need no cause. - Keep attributes and log annotations safe and bounded: no raw wire payloads, command arguments or output, signed URLs, credentials, query strings, or arbitrary defect text. Preserve the exact value only as `cause`; expose normalized categories, lengths, counts, and safe URL protocol or hostname where useful. + The documented exception is `DeviceBootError.diagnostics`: device hub launch commands and failure text are intentionally exposed to authorized device users and agents, capped at 2,000 characters and included in the error message. Do not apply this exception to other service errors. - At a translation boundary, pass through an already structured domain error when it is part of the target error channel; wrap only unknown or lower-level failures. Map failures where the context is known instead of wrapping a whole multi-step pipeline in one generic error. - Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Split into separate error classes when a discriminator drives caller control flow or the user-facing message; a discriminator used only for diagnostics may stay a field. Caller-visible messages exposed through HTTP, RPC, persisted state, or UI are behavior and must survive a structural refactor. - Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`. Construct the error at the failure boundary. Keep a mapper only when it performs real normalization, passes through domain errors, or adds reusable context; when such a mapper belongs to the target error type, prefer a static factory on that class. diff --git a/.macroscope/ignore.md b/.macroscope/ignore.md index 0541e7407c0c9..66e5434c5ed13 100644 --- a/.macroscope/ignore.md +++ b/.macroscope/ignore.md @@ -255,3 +255,27 @@ ENV/** # (see scripts/lib/reference-repos.ts). Nothing imports from them; findings # there belong upstream. .repos/** + +# Generated code. Review its source (the script, GraphQL document, schema +# definition, or theme) instead; review agents can still read these on demand. +**/*.generated.ts +**/*.graphql.ts +apps/server/schema/expo.graphql +packages/source-control-github/schema/github.graphql +apps/mobile/generated-uniwind-* +apps/mobile/clerk-theme.json +apps/server/src/testUtils/shardWeights.json +infra/relay/migrations/**/snapshot.json + +# Provider transcripts recorded from real CLI runs for the orchestration replay +# tests. Each scenario's input.ts and *_output.ts assertions stay reviewed. +**/*.ndjson + +# Ghostty build output vendored from upstream. +apps/mobile/modules/t3-terminal/Vendor/** +native/libghostty-vt/include/** + +# @pierre/highlights compiled to C by wasm2c, plus the wasm2c runtime and simde +# it needs. Regenerated by apps/mobile/scripts/generate-highlights.mts; review +# that script and cpp/t3_highlights.c instead. +apps/mobile/modules/t3-highlights/Vendor/** diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs new file mode 100644 index 0000000000000..a7b10f64404a6 --- /dev/null +++ b/.pnpmfile.cjs @@ -0,0 +1,27 @@ +// Windows installs need Linux x64 glibc binaries because WSL shares node_modules. +// Keep other platforms native; release scripts set their own architectures. +module.exports = { + hooks: { + // `typescript` is @tsc-rs/typescript (the catalog entry). Its npm version (0.8.x) is outside + // vite-plus-core's typescript peer range, so pnpm gave the vite-plus that @effect/vitest + // imports apps/marketing's typescript@6.0.3 instead, and tests loaded a second vitest. + readPackage(pkg) { + if (pkg.name === "@voidzero-dev/vite-plus-core" && pkg.peerDependencies?.typescript) { + pkg.peerDependencies.typescript = "*"; + } + return pkg; + }, + updateConfig(config) { + // oxlint-disable-next-line t3code/no-global-process-runtime -- pnpm loads this file before any Effect runtime exists. + if (process.platform !== "win32") return config; + return { + ...config, + supportedArchitectures: { + os: ["current", "linux"], + cpu: ["current", "x64"], + libc: ["current", "glibc"], + }, + }; + }, + }, +}; diff --git a/.repos/alchemy-effect/packages/frontend-frameworks/src/core/NodeServe.ts b/.repos/alchemy-effect/packages/frontend-frameworks/src/core/NodeServe.ts index cb2954120928e..3484d6696953b 100644 --- a/.repos/alchemy-effect/packages/frontend-frameworks/src/core/NodeServe.ts +++ b/.repos/alchemy-effect/packages/frontend-frameworks/src/core/NodeServe.ts @@ -48,7 +48,7 @@ export interface NodeServeHandler { export interface NodeServeEntryOptions { /** * JS expression resolving the on-disk client-assets directory - * (typically `fileURLToPath(new URL("../client/", import.meta.url))`). + * (typically `fileURLToPath(new URL("../shared/", import.meta.url))`). * Omit to skip static-file serving (Next.js handles its own assets). */ readonly clientDirExpression?: string | undefined; diff --git a/.repos/alchemy-effect/packages/frontend-frameworks/src/core/test/NodeServe.test.ts b/.repos/alchemy-effect/packages/frontend-frameworks/src/core/test/NodeServe.test.ts index 66667e6fb44c3..01147c61d5302 100644 --- a/.repos/alchemy-effect/packages/frontend-frameworks/src/core/test/NodeServe.test.ts +++ b/.repos/alchemy-effect/packages/frontend-frameworks/src/core/test/NodeServe.test.ts @@ -28,14 +28,14 @@ describe("relativeClientDirExpression", () => { "/project/dist/server/serve-node.mjs", "/project/dist/client", ), - ).toBe(`fileURLToPath(new URL("../client/", import.meta.url))`); + ).toBe(`fileURLToPath(new URL("../shared/", import.meta.url))`); }); }); describe("makeNodeServeEntrySource", () => { it("listens on PORT, answers /health, serves static files, then the fetch handler", () => { const source = makeNodeServeEntrySource({ - clientDirExpression: `fileURLToPath(new URL("../client/", import.meta.url))`, + clientDirExpression: `fileURLToPath(new URL("../shared/", import.meta.url))`, handler: { kind: "fetch", imports: `import { handler } from "./index.mjs";`, @@ -131,7 +131,7 @@ describe("makeNodeServeEntrySource", () => { it("does not map GET / onto public/index.html (SSR home stays on the handler)", () => { const source = makeNodeServeEntrySource({ - clientDirExpression: `fileURLToPath(new URL("../client/", import.meta.url))`, + clientDirExpression: `fileURLToPath(new URL("../shared/", import.meta.url))`, handler: { kind: "node", imports: `import { handler } from "./index.mjs";`, diff --git a/.task-cache.json b/.task-cache.json new file mode 100644 index 0000000000000..0e62827f9d64e --- /dev/null +++ b/.task-cache.json @@ -0,0 +1,3 @@ +{ + "endpoint": "https://t3-task-cache.pinglabs.workers.dev/projects/t3code" +} diff --git a/.vercelignore b/.vercelignore new file mode 100644 index 0000000000000..e3576c995f40a --- /dev/null +++ b/.vercelignore @@ -0,0 +1,2 @@ +# Vercel's default .pnp* rule also excludes pnpm's hook, whose checksum is in the lockfile. +!/.pnpmfile.cjs diff --git a/AGENTS.md b/AGENTS.md index 810d26e313413..3de7b3f45aa1e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,28 +78,60 @@ The most common defect in this repo is a change that works on the path you teste ## Dev servers - `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run. +- Setup runs in the background. While `.t3/setup-running` names a live PID, wait for it and do not run `vp i`. It ends with `.t3/setup-done` or `.t3/setup-failed` (with the error tail). With no marker at all, setup never ran here, so run `vp i` yourself. - `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins. - Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift. - Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, then give that full URL to an unpaired browser. Do not wire up `tailscale serve` by hand, open the URL yourself, or consume the user's pairing link. A browser with the reusable dev cookie can use the bare origin. If a normal one-time token was consumed, mint a fresh one with `node apps/server/src/bin.ts pair`. It carries standard scopes, while the startup URL carries admin scopes needed for Connections settings. - To reuse web dev auth across worktrees, configure one fixed `T3CODE_DEV_AUTH_TOKEN` in the main checkout's gitignored `.env`. The `t3.json` setup links that file into worktrees. Never commit or publish the token or a startup URL. See [Reusable dev credential](docs/operations/development.md#reusable-dev-credential). - Stop what you started, by the PID you tracked. See rule 1. +- Need a second checkout? `git worktree add` it next to this worktree, not in `/tmp`. Remove it when done. ## Test data An empty database is a bad test. Seed your worktree's `.t3` with a copy of real data instead of pointing at live state: -- Run `vp run migrate-dev-db` with your dev server stopped. It rebuilds `/.t3/userdata/statev2.sqlite` from a read-only snapshot of `~/.t3/userdata/statev2.sqlite`, the developer's real data. It keeps recent projects and their stopped threads, and drops scheduled tasks, pending work, and auth sessions, so your dev server never runs the developer's agents. Raise `--projects` and `--threads-per-project` for more data. +- The first `vp run dev` in a worktree does this for you when its database is missing. `--no-seed` or `T3CODE_DEV_SEED=0` skips it. +- Run `vp run migrate-dev-db` with your dev server stopped to refresh. It rebuilds `/.t3/userdata/statev2.sqlite` from a read-only snapshot of `~/.t3/userdata/statev2.sqlite`, the developer's real data. It keeps recent projects and their stopped threads, and drops scheduled tasks, pending work, and auth sessions, so your dev server never runs the developer's agents. Raise `--projects` and `--threads-per-project` for more data. - Refresh `statev2.sqlite`, not `state.sqlite`. The server copies the V1 `state.sqlite` only when `statev2.sqlite` is missing. - Bring `secrets` and `settings.json` only if the flow under test needs them. - Copy in, never symlink. Data flows one way: into your sandbox, never back out. ## Verifying -- Smallest proof that the change works. `vp test run ` for the tests you touched, targeted lint and typecheck for the scope you changed. +- Before you push, run `vp run check:changed`. It runs CI's fast checks for changed files: format, lint, knip, typecheck of affected packages and dependents, and tests beside changes. CI still runs the full test suites. +- While you iterate, run `vp test run `. For big files, add `-t ""`. +- Use `vp run typecheck`, not `npx tsc`; it caches per package. Both run tsc-rs (`typescript` is the `@tsc-rs/typescript` drop-in). +- Run `node -e` snippets from `apps/server` or the owning package. `effect` does not resolve from the repo root. - Test meaningful logic or observable behavior. Do not render components to static markup to assert props or attributes, or add tests that merely assert callback wiring or mirror the implementation. - **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite. - Backend behavior changes ship with focused tests for that behavior. -- The server is event-sourced, and side effects run after the command commits. In tests, drain the effect worker (`OrchestrationEffectWorkerV2.drain`) or await the specific persisted event or `Deferred` that marks the milestone. Never wait on sleeps or polling. A test that needs a timeout to pass is wrong. +- Proof for a bug fix depends on the bug. Logic, data, state, and protocol bugs get a failing test first (the fewest that fail on `main` for that reason, in the module's existing test file), then the fix. Purely visual bugs (spacing, colour, alignment, a layout shift) get before/after captures as their proof and no test: do not add UI tests for nitpicks, and do not ask for one in review when a capture already shows it. A server-only fix with no visible surface ships the test plus a short runtime transcript. +- The server is event-sourced, and side effects run after the command commits. In tests, drain the effect worker (`OrchestrationEffectWorkerV2.drain`) or await the specific persisted event or `Deferred` that marks the milestone. Never wait on sleeps or polling. A test that needs a timeout to pass is wrong. Concretely: + - `it.effect` runs on a `TestClock`; `Effect.sleep` only advances through `TestClock.adjust`. `it.live` is wall-clock and only for subprocess or network fixtures. + - No `yieldNow` or `sleep` polling loops. Await the `Deferred`, take from the `Queue`, or drain the worker. + - No per-test timeout argument or `retry`. The project timeout is the ceiling, and flaky tests are fixed, not retried. + - No `performance.now()` or `Date.now()` deltas. Assert on events and counts, not elapsed time. + - Browser tests assert through `expect.element` or `vi.waitFor`, never `requestAnimationFrame` or `transitionend`. + - `vi.mock` factories must not spread a real module that pulls in Shiki or the diff workers. + - `it.skip` and friends need a tracking issue on the line above: `// quarantine: #1234 `. + - Lint enforces this: `t3code/no-test-timeout-or-unreasoned-skip`, `t3code/no-frame-waits-in-browser-tests`, `t3code/no-wall-clock-in-tests`, `t3code/no-real-time-wait-in-tests`, `t3code/no-polling-loop-in-tests`. +- Web browser tests are `*.browser.test.tsx` or `*.browser.test.ts` and render with `await using screen = await render(...)` from `apps/web/test/render.tsx`. `t3code/require-disposable-render` errors on the old patterns. + - Acquire what the test drives after mounting (fake timers it advances, spies it sets up after mounting) after the render, so it disposes before the unmount. Anything the first render reads comes before it. + - A helper that renders and then waits or clicks puts the screen in an `AsyncDisposableStack` and `move()`s it out only on success, so a failed wait still unmounts. + - `rerender` needs a fresh element on every call. + - No lifecycle hooks and no module-level mutable state. Shared mock state that `vi.mock` factories read is reset by a `setup()` call at the top of the test. + - `router` is on by default. Pass `router: false` only with a one-line comment saying why. + + ```tsx + it("saves on Enter", async () => { + const onSave = vi.fn(); + using _now = vi.spyOn(Date, "now").mockReturnValue(0); + await using screen = await render(, { router: "/threads/1" }); + await userEvent.type(screen.getByRole("textbox"), "Title{Enter}"); + expect(onSave).toHaveBeenCalledWith("Title"); + }); + ``` + - Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers. For authorized mobile verification, a missing or outdated native client is a build step, not a blocker. Run `node scripts/mobile-native-client.ts ensure ` on the simulator host before starting Metro. It checks the local Expo fingerprint and builds/installs when needed. See `test-t3-mobile` for the full workflow. @@ -107,12 +139,13 @@ For authorized mobile verification, a missing or outdated native client is a bui ## Pull requests - Never make a PR unless the developer explicitly asks you to do so. +- If `origin` is git.cafe, follow [GitCafe mirror](docs/operations/development.md#gitcafe-mirror-optional): use `cafe` for existing PRs, issues, comments and labels, but push and open PRs on GitHub, where CI runs. - Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`. - Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work. - UI changes need before/after images. Motion or timing needs a short video. - Upload PR evidence to GitHub. Never commit PR-only screenshots or assets such as `.github/pr-assets/`. - One request is one PR. Split it only when the maintainer asks. Outside contributions follow the stricter [one problem per PR](CONTRIBUTING.md#one-problem) rule. -- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit. +- When babysitting: call `watch_pull_request` and end your turn. T3 Code wakes you on checks, comments, or conflicts. Do not poll or sleep. Verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit. ## Documentation @@ -120,7 +153,7 @@ Most code changes do not need an internal documentation change. Agents can read - `docs/internals/` is for architectural decisions and their reasons, constraints that span components, and implementation traps that are hard to discover from the source. Before adding a paragraph, ask what a maintainer would get wrong without it. If reading the relevant code answers the question, leave it out. - Do not document every feature, enumerate fields or methods, narrate control flow, maintain file catalogs, or append PR summaries. Types, tests, and code already record the implementation. The glossary defines shared vocabulary; it is not a feature index. -- Keep a local implementation explanation in a nearby code comment. Use an internal doc when the reasoning crosses boundaries or needs context the code cannot carry well. Link to the relevant source instead of copying it. +- A local reason the code can't show goes in a short nearby code comment. Use an internal doc when the reasoning crosses boundaries or needs context the code cannot carry well. Link to the relevant source instead of copying it. - When a documented decision or constraint changes, rewrite or remove the affected text. Do not append another account of the new behavior. A new internal page needs a distinct, durable reason to exist. - `docs/user/` helps users accomplish tasks. Give each major feature a concise section explaining what it does, how to start, and anything unintuitive. A settings path is useful; descriptions of visible buttons, icons, layouts, animations, or every UI state are not. Before adding text, ask what task or decision it helps the user with. - Keep user docs in the shipped product's voice, without implementation details or contributor tooling. Update the relevant feature section when how to use it changes. A UI tweak does not need a documentation entry, and a new control does not need its own page. @@ -145,7 +178,7 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/ - `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic. - `packages/shared` - shared runtime utils, subpath exports, no barrel. - `packages/client-runtime` - client code shared by web and mobile. -- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency. +- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency. If it is missing (sparse checkout), read a file with `git show origin/main:.repos/`. ## Taste @@ -153,8 +186,14 @@ Architecture and its constraints: `docs/internals/overview.md`. Glossary: `docs/ - Client mutations use `createEnvironmentRpcCommand`. Add protected methods to `CLIENT_GUARDED_RPC_SCOPES` in contracts and use the command's `permissionAtom` for UI availability. Grants are checked at execution against the destination environment; the server remains authoritative. Keep raw RPC clients inside `rpc/`, and extend the permission behavior tests when adding a protected method. - Server features are services; transports stay thin. A `ws.ts` RPC handler, HTTP route, or MCP tool decodes input, calls one service method, and maps errors. See [Effect services](docs/internals/effect-services.md). - `apps/web/src/components/ui` exports own their look. Pick a `variant` or `size`; do not restyle one with `className`. If none fits and the look is a generic concept, add a variant to the component; a look that belongs to one feature stays in that feature's own component, not in `components/ui`. Layout classes (width, flex, margin, position) belong on the parent. `shadcn/no-restyle` fails lint on violations. See [Web UI](docs/internals/web-ui.md). +- Reusable Effect functions use `Effect.fn("Service.operation")` with a stable span name, not a + function wrapping `Effect.gen`. Keep `Effect.gen` for inline programs and layer construction. + Use `Effect.fnUntraced` only when spans would be too frequent (stream chunks, per-event + projection, tight loops) or duplicate an existing tracing boundary; explain that choice nearby. + Named `Effect.fn` creates a span; the unnamed form does not. Preserve existing span names and + options, and pass combinators as additional function-builder arguments. - Inferred types over annotations. `any` is the enemy. -- Comments say why: a constraint, an external quirk, or an invariant the code can't show. Don't restate names or signatures, narrate steps, or record history. `t3code/no-low-value-comments` catches the mechanical cases. +- Default to no comment. Write one only for a constraint, an external quirk, or an invariant the code can't show, in one line where you can and four at most. Don't restate names or signatures, narrate steps, record history, or explain the fix you just made; the PR carries that. `t3code/no-low-value-comments` enforces the length cap and the mechanical cases. - Our users drive agents all day and notice a dropped frame, a lying spinner, and a stale label. No continuously repainting animations; they peg the GPU on high-refresh displays. - If a rule here fights the task in front of you, say so loudly and get a human sign-off before breaking it. diff --git a/apps/desktop/gnome-extension/captureFeedback.test.js b/apps/desktop/gnome-extension/captureFeedback.test.js index 501f2586f1bf3..fb6003bf39706 100644 --- a/apps/desktop/gnome-extension/captureFeedback.test.js +++ b/apps/desktop/gnome-extension/captureFeedback.test.js @@ -151,17 +151,6 @@ it("waits for T3 to remap and cancels that wait when disabled", async () => { expect(shell.mapped.size).toBe(0); }); -it("does not animate under reduced motion but still activates T3", async () => { - shell.animations = false; - shell.windows = [target()]; - const { feedback, started } = begin(); - expect(started).toBe(false); - expect(shell.actors).toHaveLength(0); - await feedback.activate(":1.23", "T3"); - expect(shell.activate).toHaveBeenCalledOnce(); - feedback.dispose(); -}); - it("rejects another sender and locked-session activation", async () => { shell.windows = [target()]; const { feedback } = begin(); diff --git a/apps/desktop/gnome-extension/captureService.test.js b/apps/desktop/gnome-extension/captureService.test.js index b8313f920f72a..fa45cd604a0d0 100644 --- a/apps/desktop/gnome-extension/captureService.test.js +++ b/apps/desktop/gnome-extension/captureService.test.js @@ -28,11 +28,6 @@ it("rejects other clients before looking at the active window", async () => { expect(await service.capture(":1.23")).toBe("pixels"); }); -it.each(CLIENT_NAMES)("accepts the current owner of %s", async (client) => { - const { service } = fixture({ getNameOwner: async (name) => (name === client ? ":1.23" : null) }); - expect(await service.capture(":1.23")).toBe("pixels"); -}); - it("rechecks the name owner on each capture", async () => { let owner = ":1.23"; const { service } = fixture({ getNameOwner: async () => owner }); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index d78ac0fd286a3..f87fa20453f36 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,13 +1,12 @@ { "name": "@t3tools/desktop", - "version": "0.1.0", + "version": "0.1.2", "private": true, "type": "module", "main": "dist-electron/boot.cjs", "scripts": { "ensure:electron": "node scripts/ensure-electron-runtime.mjs", "start": "node scripts/start-electron.mjs", - "typecheck": "tsc-rs --noEmit", "test": "vp test run --passWithNoTests", "smoke-test": "node scripts/smoke-test.mjs" }, @@ -24,7 +23,7 @@ "@t3tools/tailscale": "workspace:*", "dbus-next": "0.10.2", "effect": "catalog:", - "electron": "44.4.5", + "electron": "44.9.3", "electron-store": "^8.2.0", "electron-updater": "^6.8.9", "electron-webauthn": "catalog:", @@ -38,7 +37,7 @@ "@types/node": "catalog:", "acorn": "8.16.0", "cross-env": "^10.1.0", - "electron-builder": "26.15.6", + "electron-builder": "26.16.1", "tailwindcss": "^4.0.0", "vite-plus": "catalog:" }, diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nsh new file mode 100644 index 0000000000000..092f641c3359f --- /dev/null +++ b/apps/desktop/resources/installer.nsh @@ -0,0 +1,10 @@ +!macro customInstall + !ifndef DO_NOT_CREATE_START_MENU_SHORTCUT + ${IfNot} ${FileExists} "$newStartMenuLink" + !insertmacro createMenuDirectory + CreateShortCut "$newStartMenuLink" "$appExe" "" "$appExe" 0 "" "" "${APP_DESCRIPTION}" + ClearErrors + WinShell::SetLnkAUMI "$newStartMenuLink" "${APP_ID}" + ${EndIf} + !endif +!macroend diff --git a/apps/desktop/scripts/build-preview-annotation-css.mjs b/apps/desktop/scripts/build-preview-annotation-css.mjs index a5dbdcfbe69ce..943a1f7547bfd 100644 --- a/apps/desktop/scripts/build-preview-annotation-css.mjs +++ b/apps/desktop/scripts/build-preview-annotation-css.mjs @@ -29,7 +29,16 @@ const compilerInput = [ annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"), ].join("\n"); const compiler = await compile(compilerInput, { base: appRoot }); -const css = compiler.build([...candidates]); +// Shadow-root styles cannot register @property defaults. Make Tailwind's +// fallback unconditional so border, shadow, and ring utilities have defaults. +const compiledCss = compiler.build([...candidates]); +const css = compiledCss.replace( + /(@layer properties \{\n) @supports [^\n]*\{\n([\s\S]*?)\n \}\n(\})/, + "$1$2\n$3", +); +if (css === compiledCss || /@layer properties\s*\{\s*@supports\b/.test(css)) { + throw new Error("Tailwind @property fallback was not unwrapped; update the pattern above."); +} const encodedCss = `'${css .replaceAll("\\", "\\\\") .replaceAll("'", "\\'") diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 6cdcb43c9cb62..07578297f06d7 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -94,9 +94,14 @@ function cleanupStaleDevApps() { return; } - NodeChildProcess.spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { - stdio: "ignore", - }); + const escapedDesktopDir = desktopDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + NodeChildProcess.spawnSync( + "pkill", + ["-f", "--", `(^| )--t3code-dev-root=${escapedDesktopDir}( |$)`], + { + stdio: "ignore", + }, + ); } function startApp() { diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index 780cf639fd18c..e433dc498cada 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -94,7 +94,7 @@ function runChecked(command, args) { throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim()); } -export function resolveMacCodeSignArguments(appBundlePath) { +function resolveMacCodeSignArguments(appBundlePath) { return ["--force", "--deep", "--sign", "-", "--timestamp=none", appBundlePath]; } @@ -201,7 +201,7 @@ function registerMacLauncherBundle(appBundlePath) { } // Bundle-internal paths are macOS paths whatever host builds them. -export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) { +function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) { return { sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath, generatedIconPath: NodePath.posix.join( @@ -260,7 +260,7 @@ function ensureMacIconIcns(runtimeDir) { } } -export function resolveMacBundleInfoPlistStrings(executableName) { +function resolveMacBundleInfoPlistStrings(executableName) { return { CFBundleDisplayName: APP_DISPLAY_NAME, CFBundleName: APP_DISPLAY_NAME, @@ -372,9 +372,7 @@ function buildMacLauncher(electronBinaryPath) { JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata) ) { if (isDevelopment) { - // The launcher also handles protocol activations outside the dev runner, - // so refresh its fallback environment on every launch. Never let a value - // captured by an older parent app override the live dev-runner environment. + // Protocol activations bypass the dev runner, so refresh the fallback environment on every launch. writeDevelopmentEnvironmentScript(); if (writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath)) { signMacLauncherBundle(targetAppBundlePath); @@ -385,10 +383,7 @@ function buildMacLauncher(electronBinaryPath) { } NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true }); - // verbatimSymlinks keeps the framework's relative symlinks intact - // (e.g. Resources -> Versions/Current/Resources). Without it cpSync - // rewrites them to absolute paths into node_modules, which escape the - // bundle and crash sandboxed helper processes (icudtl.dat not found). + // Without verbatimSymlinks, cpSync makes framework symlinks point outside the bundle and crashes helpers. NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true, verbatimSymlinks: true, @@ -400,10 +395,7 @@ function buildMacLauncher(electronBinaryPath) { ); patchHelperBundleInfoPlists(targetAppBundlePath); if (isDevelopment) { - // Launching the node_modules copy makes macOS associate the process (and Dock label) with - // Electron.app even though this bundle's Info.plist has the T3 Code name. Its conventional - // executable name also keeps Electron's default-app runtime in development mode instead of - // making app.isPackaged report true. + // Electron.app's executable name keeps default-app mode active without making app.isPackaged true. writeDevelopmentEnvironmentScript(); writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath); } diff --git a/apps/desktop/scripts/electron-launcher.test.mjs b/apps/desktop/scripts/electron-launcher.test.mjs index c2440f364e7be..fa6e56b5800eb 100644 --- a/apps/desktop/scripts/electron-launcher.test.mjs +++ b/apps/desktop/scripts/electron-launcher.test.mjs @@ -1,6 +1,9 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeEvents from "node:events"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import * as NodeVM from "node:vm"; import { assert, describe, it } from "vite-plus/test"; @@ -8,9 +11,6 @@ import { makeDevelopmentEnvironmentScript, makeDevelopmentLauncherScript, resolveElectronBinaryPath, - resolveMacBundleInfoPlistStrings, - resolveMacCodeSignArguments, - resolveMacLauncherIconPaths, resolveMacLauncherPaths, writeDevelopmentLauncherScript, } from "./electron-launcher.mjs"; @@ -103,30 +103,6 @@ describe("electron development launcher", () => { assert.notInclude(script, "node_modules/electron"); }); - it("declares why the macOS app needs protected access", () => { - const values = resolveMacBundleInfoPlistStrings("T3 Code (Dev) Launcher"); - - assert.equal( - values.NSScreenCaptureUsageDescription, - "T3 Code captures the active window when you use the snapshot shortcut.", - ); - assert.equal( - values.NSDocumentsFolderUsageDescription, - "T3 Code reads project files you open in the desktop app.", - ); - }); - - it("ad-hoc signs the complete development app bundle", () => { - assert.deepEqual(resolveMacCodeSignArguments("/runtime/T3 Code (Dev).app"), [ - "--force", - "--deep", - "--sign", - "-", - "--timestamp=none", - "/runtime/T3 Code (Dev).app", - ]); - }); - it("restores execute permissions on an unchanged launcher", () => { const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-launcher-")); const launcherPath = NodePath.join(directory, "launcher"); @@ -140,14 +116,94 @@ describe("electron development launcher", () => { NodeFS.rmSync(directory, { recursive: true, force: true }); } }); +}); - it("derives launcher icons from canonical development and production assets", () => { - const development = resolveMacLauncherIconPaths("/runtime", true); - const production = resolveMacLauncherIconPaths("/runtime", false); - - assert.match(development.sourceIconPath, /assets[\\/]dev[\\/]blueprint-macos-1024\.png$/); - assert.equal(development.generatedIconPath, "/runtime/icon-dev.icns"); - assert.match(production.sourceIconPath, /assets[\\/]prod[\\/]black-macos-1024\.png$/); - assert.equal(production.generatedIconPath, "/runtime/icon-prod.icns"); - }); +async function startupCleanupPattern(desktopDir) { + const source = NodeFS.readFileSync(new URL("./dev-electron.mjs", import.meta.url), "utf8"); + let pattern; + // Supply inert imports so the real startup runs without launching Electron or signalling processes. + await NodeVM.runInNewContext( + `(async () => { ${source.replace(/^import\s[\s\S]*?;\n/gm, "")} })()`, + { + NodeChildProcess: { + execFileSync: () => undefined, + spawnSync: (command, args) => { + if (command === "pkill" && args.includes("-f")) pattern = args.at(-1); + }, + spawn: () => new NodeEvents.EventEmitter(), + }, + NodeFS: { watch: () => ({ close: () => undefined }) }, + NodeOS: { platform: () => "linux" }, + NodePath, + desktopDir, + resolveDevProtocolClient: () => null, + resolveElectronLaunchCommand: (args) => ({ electronPath: "electron", args }), + waitForResources: async () => undefined, + URL, + process: { + env: { VITE_DEV_SERVER_URL: "http://localhost:1234" }, + execPath: "node", + once: () => undefined, + }, + }, + ); + assert.isString(pattern); + return pattern; +} + +it + // oxlint-disable-next-line t3code/no-global-process-runtime -- Native pgrep is unavailable on Windows. + .skipIf(NodeOS.platform() === "win32") + .each([ + "/tmp/t3-feature.one/apps/desktop", + "/tmp/t3-feature.one [two](three)+?^${four}|back\\slash*/apps/desktop", + ])("dev cleanup matches only the literal root argument: %s", async (desktopDir) => { + const pattern = await startupCleanupPattern(desktopDir); + const flag = `--t3code-dev-root=${desktopDir}`; + const argvCases = [ + [flag], + [flag, "main.cjs"], + [flag.replace(".one", "Xone")], + [`${flag}-two`], + [`prefix${flag}`], + [`--t3code-dev-root=/other${desktopDir}`], + ]; + const children = []; + try { + for (const args of argvCases) { + const child = NodeChildProcess.spawn( + process.execPath, + ["-e", "process.send('ready'); setInterval(() => {}, 1000)", "--", ...args], + { stdio: ["ignore", "ignore", "inherit", "ipc"] }, + ); + children.push(child); + await Promise.race([ + NodeEvents.once(child, "message"), + NodeEvents.once(child, "exit").then(() => { + throw new Error("Fixture exited before readiness"); + }), + ]); + } + // Use the native ERE engine, but never execute the launcher's signal-producing command. + const result = NodeChildProcess.spawnSync( + "pgrep", + ["-P", String(process.pid), "-f", "--", pattern], + { encoding: "utf8" }, + ); + assert.equal(result.status, 0, result.stderr); + const matches = result.stdout.trim().split(/\s+/).map(Number); + assert.sameMembers( + matches, + children.slice(0, 2).map((child) => child.pid), + ); + } finally { + await Promise.all( + children.map(async (child) => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = NodeEvents.once(child, "exit"); + child.kill("SIGTERM"); + await exited; + }), + ); + } }); diff --git a/apps/desktop/scripts/ensure-electron-runtime.mjs b/apps/desktop/scripts/ensure-electron-runtime.mjs index b8b8254c9b3c7..933a763dfa354 100644 --- a/apps/desktop/scripts/ensure-electron-runtime.mjs +++ b/apps/desktop/scripts/ensure-electron-runtime.mjs @@ -116,13 +116,39 @@ function runChecked(command, args) { ); } -function installElectronRuntime(electronDir, version) { +// electron's own installer goes through @electron/get, which reuses its +// download cache (~/.cache/electron, ~/Library/Caches/electron) and verifies +// the bundled checksums. pnpm 11 never runs it because electron has no +// install script, so a new worktree would otherwise download 130 MB again. +function installFromElectronCache(electronDir) { + const result = NodeChildProcess.spawnSync( + process.execPath, + [NodePath.join(electronDir, "install.js")], + { stdio: ["ignore", "inherit", "inherit"] }, + ); + if (result.status === 0) { + return true; + } + process.stderr.write( + `electron install.js failed with exit code ${result.status ?? "unknown"}, downloading with curl instead\n`, + ); + return false; +} + +function downloadElectronRuntime(electronDir, version) { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-electron-")); const zipPath = NodePath.join(tempDir, `electron-v${version}-${hostPlatform}-${hostArch}.zip`); try { runChecked("curl", [ "-fsSL", + "--retry", + "3", + "--retry-all-errors", + "--connect-timeout", + "30", + "--max-time", + "300", `https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${hostPlatform}-${hostArch}.zip`, "-o", zipPath, @@ -142,21 +168,27 @@ function installElectronRuntime(electronDir, version) { } } +function resetRuntime(electronDir) { + NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true }); + NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true }); +} + export function ensureElectronRuntime() { const electronPackageJsonPath = require.resolve("electron/package.json"); const electronPackageJson = JSON.parse(NodeFS.readFileSync(electronPackageJsonPath, "utf8")); const electronDir = NodePath.dirname(electronPackageJsonPath); const platformPath = getPlatformPath(); const electronPath = NodePath.join(electronDir, "dist", platformPath); - const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath); - const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath); - - if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) { - if (NodeFS.existsSync(NodePath.join(electronDir, "dist"))) { - NodeFS.rmSync(NodePath.join(electronDir, "dist"), { recursive: true, force: true }); + const needsInstall = () => + missingRuntimePaths(electronDir, platformPath).length > 0 || + invalidRuntimePaths(electronDir, platformPath).length > 0; + + if (needsInstall()) { + resetRuntime(electronDir); + if (!installFromElectronCache(electronDir) || needsInstall()) { + resetRuntime(electronDir); + downloadElectronRuntime(electronDir, electronPackageJson.version); } - NodeFS.rmSync(NodePath.join(electronDir, "path.txt"), { force: true }); - installElectronRuntime(electronDir, electronPackageJson.version); } const missingAfterInstall = missingRuntimePaths(electronDir, platformPath); diff --git a/apps/desktop/scripts/verify-preload-bundle.test.mjs b/apps/desktop/scripts/verify-preload-bundle.test.mjs index d2055e2c68177..8af6ae00c3f92 100644 --- a/apps/desktop/scripts/verify-preload-bundle.test.mjs +++ b/apps/desktop/scripts/verify-preload-bundle.test.mjs @@ -60,12 +60,6 @@ describe("desktop preload bundle verifier", () => { ); }); - it("ignores import-like text in strings", () => { - assert.doesNotThrow(() => - verifyPreloadBundle(`${validPreload}\nconst message = 'import /* comment */("module")';`), - ); - }); - it("rejects unsupported require calls with comments before the opening parenthesis", () => { assert.throws( () => verifyPreloadBundle(`${validPreload}\nrequire /* @__PURE__ */ ("node:fs");`), @@ -73,13 +67,6 @@ describe("desktop preload bundle verifier", () => { ); }); - it("rejects unsupported optional require calls", () => { - assert.throws( - () => verifyPreloadBundle(`${validPreload}\nrequire?.("node:fs");`), - /unsupported sandbox imports: node:fs/, - ); - }); - it("accepts Electron sandbox module aliases", () => { assert.doesNotThrow(() => verifyPreloadBundle(` diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 68febbc6386ff..f57e709bca7af 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -147,7 +147,7 @@ const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupErr const fatalStartupCause = (stage: string, cause: Cause.Cause) => handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause))); -export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( +const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( function* (): Effect.fn.Return { const pool = yield* DesktopBackendPool.DesktopBackendPool; const instances = yield* pool.list; @@ -339,11 +339,7 @@ const scopedProgram = Effect.scoped( const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory; yield* Effect.addFinalizer(() => - // Stop every backend in the pool, not just the primary. The - // electronApp.quit() path can race ahead of the layer-scope - // cascade, so leaving the WSL instance for its parent scope - // finalizer means it gets hard-killed by the OS instead of - // receiving SIGTERM + grace. + // Quit can outrun layer finalizers; stop pooled backends here so they receive SIGTERM before OS teardown. stopAllPoolInstances().pipe( Effect.ensuring(rendererHistory.shutdown), Effect.ensuring(shutdown.markComplete), diff --git a/apps/desktop/src/app/DesktopAppActivation.test.ts b/apps/desktop/src/app/DesktopAppActivation.test.ts index 6e0c76842f244..2bf1e716a99a8 100644 --- a/apps/desktop/src/app/DesktopAppActivation.test.ts +++ b/apps/desktop/src/app/DesktopAppActivation.test.ts @@ -81,46 +81,6 @@ function exchange(address: string, payload: DesktopAppActivationRequest) { } describe("desktop app control server", () => { - it.effect("roundtrips a request and removes its socket on shutdown", () => - Effect.gen(function* () { - const platform = yield* HostProcess.Platform; - const userId = yield* HostProcess.UserId; - yield* Effect.promise(async () => { - const root = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-app-control-test-")); - const target = makeTarget(NodePath.join(root, "userdata"), platform, userId); - const received: DesktopAppActivationRequest[] = []; - const server = await startDesktopAppControlServer({ - ...target, - userId, - handle: async (input) => { - received.push(input); - return { - version: 1, - requestId: input.requestId, - ok: true, - projectId: ProjectId.make("project-1"), - threadId: ThreadId.make("thread-1"), - }; - }, - cancel: () => undefined, - onReclaimError: () => undefined, - }); - openServers.push(server); - - const response = await exchange(target.address, request("request-1", platform)); - - expect(received).toHaveLength(1); - expect(response).toMatchObject({ ok: true, requestId: "request-1" }); - await server.close(); - openServers.splice(openServers.indexOf(server), 1); - if (target.directory !== null) { - await expect(NodeFSP.stat(target.address)).rejects.toMatchObject({ code: "ENOENT" }); - } - await NodeFSP.rm(root, { recursive: true, force: true }); - }); - }), - ); - it.effect("cancels a queued request when the client disconnects", () => Effect.gen(function* () { const platform = yield* HostProcess.Platform; diff --git a/apps/desktop/src/app/DesktopAppActivation.ts b/apps/desktop/src/app/DesktopAppActivation.ts index 688bd789572f7..05d5a3254a84f 100644 --- a/apps/desktop/src/app/DesktopAppActivation.ts +++ b/apps/desktop/src/app/DesktopAppActivation.ts @@ -186,10 +186,7 @@ export async function startDesktopAppControlServer(input: { server.listen(address); }); - // Closing a Unix socket server unlinks the path it was bound to, even when - // another app's socket lives there now. Bind a staging path and move it onto - // the address instead, so a later close only unlinks the staging path, which - // is already gone. + // Closing unlinks the original bind path, even if another app replaced it. Bind a staging path first. const bindUnix = async (directory: string, mode: "take-over" | "claim-free") => { const staging = NodePath.join(directory, `${NodeCrypto.randomBytes(6).toString("hex")}.tmp`); @@ -213,7 +210,6 @@ export async function startDesktopAppControlServer(input: { let server: NodeNet.Server; let inode: number | null = null; if (input.directory === null) { - // Named pipes close with the app that owns them, so no other app can remove this one. server = await listen(input.address); } else { await prepareUnixDirectory({ directory: input.directory, userId: input.userId }); @@ -222,10 +218,10 @@ export async function startDesktopAppControlServer(input: { let closed = false; const reclaimOnce = async () => { - // Never replace a socket that exists, so two apps cannot trade the path back and forth. + // Replacing an existing socket would let two apps trade the path indefinitely. if (closed || input.directory === null || (await inodeAt(input.address)) !== null) return; if (await prepareUnixDirectory({ directory: input.directory, userId: input.userId })) { - // A watch follows the directory's inode, so a recreated directory needs a new one. + // Directory watches follow inodes, so recreate the watch after directory replacement. watchDirectory(input.directory); } const next = await bindUnix(input.directory, "claim-free").catch( @@ -269,7 +265,7 @@ export async function startDesktopAppControlServer(input: { close: async () => { if (closed) return; closed = true; - // A running reclaim can replace the watcher, so close the watcher after it. + // Reclaim can replace the watcher; close it afterward. await pendingReclaim; watcher?.close(); for (const socket of sockets) socket.destroy(); diff --git a/apps/desktop/src/app/DesktopAppActivationBroker.test.ts b/apps/desktop/src/app/DesktopAppActivationBroker.test.ts index 7a889c2e91d34..ab20c7610909d 100644 --- a/apps/desktop/src/app/DesktopAppActivationBroker.test.ts +++ b/apps/desktop/src/app/DesktopAppActivationBroker.test.ts @@ -49,44 +49,6 @@ describe("DesktopAppActivationBroker", () => { broker.close(); }); - it("queues requests after unsubscribe until a new renderer registers", async () => { - const previousSend = vi.fn(); - const nextSend = vi.fn(); - const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() }); - broker.registerRenderer(previousSend); - broker.clearRenderer(); - - const response = broker.request(request); - expect(previousSend).not.toHaveBeenCalled(); - expect(nextSend).not.toHaveBeenCalled(); - - broker.registerRenderer(nextSend); - expect(nextSend).toHaveBeenCalledWith(request); - broker.complete({ - version: 1, - requestId: request.requestId, - ok: true, - projectId: ProjectId.make("project-1"), - threadId: ThreadId.make("thread-1"), - }); - - await expect(response).resolves.toMatchObject({ ok: true }); - broker.close(); - }); - - it("removes a queued request when its CLI connection closes", async () => { - const send = vi.fn(); - const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() }); - - const response = broker.request(request); - broker.cancel(request.requestId); - broker.registerRenderer(send); - - await expect(response).resolves.toMatchObject({ ok: false, code: "renderer-unavailable" }); - expect(send).not.toHaveBeenCalled(); - broker.close(); - }); - it("never sends a canceled request that was queued behind another request", async () => { const send = vi.fn(); const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() }); @@ -112,19 +74,4 @@ describe("DesktopAppActivationBroker", () => { expect(send).toHaveBeenCalledTimes(1); broker.close(); }); - - it("times out a request without polling", async () => { - vi.useFakeTimers(); - try { - const broker = new DesktopAppActivationBroker({ requestTimeoutMs: 1_000, activate: vi.fn() }); - const response = broker.request(request); - - await vi.advanceTimersByTimeAsync(1_000); - - await expect(response).resolves.toMatchObject({ ok: false, code: "request-timeout" }); - broker.close(); - } finally { - vi.useRealTimers(); - } - }); }); diff --git a/apps/desktop/src/app/DesktopAppErrors.test.ts b/apps/desktop/src/app/DesktopAppErrors.test.ts deleted file mode 100644 index 666c36d391de2..0000000000000 --- a/apps/desktop/src/app/DesktopAppErrors.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; - -import { - DesktopBackendPortUnavailableError, - DesktopDevelopmentBackendPortRequiredError, -} from "./DesktopApp.ts"; - -describe("DesktopApp errors", () => { - it("preserves unavailable backend port context", () => { - const error = new DesktopBackendPortUnavailableError({ - startPort: 3_773, - maxPort: 65_535, - hosts: ["127.0.0.1", "0.0.0.0", "::"], - }); - - assert.equal(error.startPort, 3_773); - assert.equal(error.maxPort, 65_535); - assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]); - assert.equal( - error.message, - "No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.", - ); - }); - - it("reports the required development port", () => { - const error = new DesktopDevelopmentBackendPortRequiredError(); - - assert.equal(error.message, "T3CODE_PORT is required in desktop development."); - }); -}); diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.ts index 1cd8485a1ec9b..32e7b3b3118d9 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.test.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts @@ -14,7 +14,6 @@ import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopAssets from "./DesktopAssets.ts"; import * as DesktopConfig from "./DesktopConfig.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; -import * as DesktopUserData from "./DesktopUserData.ts"; const defaultEnvironmentInput = { dirname: "/repo/apps/desktop/dist-electron", @@ -176,66 +175,6 @@ describe("DesktopAppIdentity", () => { ), ); - it.effect("preserves failures while inspecting the legacy userData path", () => { - const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Dev)"; - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "exists", - description: "permission denied", - pathOrDescriptor: legacyPath, - }); - - return withIdentity( - Effect.gen(function* () { - const identity = yield* DesktopAppIdentity.DesktopAppIdentity; - const error = yield* identity.resolveUserDataPath.pipe(Effect.flip); - - assert.instanceOf(error, DesktopUserData.DesktopUserDataInitializationError); - assert.equal(error.resourcePath, legacyPath); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - `Could not initialize Electron user data during inspect at ${legacyPath} (PermissionDenied).`, - ); - }), - { - legacyPathProbeError: cause, - environment: { env: { VITE_DEV_SERVER_URL: "http://localhost:5173" } }, - }, - ); - }); - - it.effect("configures app identity from the environment commit override", () => { - const calls: ElectronAppCalls = { - setAboutPanelOptions: [], - setDockIcon: [], - setName: [], - }; - - return withIdentity( - Effect.gen(function* () { - const identity = yield* DesktopAppIdentity.DesktopAppIdentity; - yield* identity.configure; - - assert.deepEqual(calls.setName, ["T3 Code Beta"]); - assert.equal(calls.setAboutPanelOptions[0]?.applicationName, "T3 Code (Beta)"); - assert.equal(calls.setAboutPanelOptions[0]?.applicationVersion, "1.2.3"); - assert.equal(calls.setAboutPanelOptions[0]?.version, "0123456789ab"); - assert.deepEqual(calls.setDockIcon, []); - }), - { - calls, - environment: { - env: { - T3CODE_COMMIT_HASH: "0123456789abcdef", - }, - }, - pngIconPath: Option.some("/icon.png"), - }, - ); - }); - it.effect.each([ { stage: "Beta", environment: {} }, { @@ -267,26 +206,4 @@ describe("DesktopAppIdentity", () => { { calls, environment }, ); }); - - it.effect("sets the dock icon only when running unpackaged", () => { - const calls: ElectronAppCalls = { - setAboutPanelOptions: [], - setDockIcon: [], - setName: [], - }; - - return withIdentity( - Effect.gen(function* () { - const identity = yield* DesktopAppIdentity.DesktopAppIdentity; - yield* identity.configure; - - assert.deepEqual(calls.setDockIcon, ["/icon.png"]); - }), - { - calls, - environment: { isPackaged: false }, - pngIconPath: Option.some("/icon.png"), - }, - ); - }); }); diff --git a/apps/desktop/src/app/DesktopAppIdentity.ts b/apps/desktop/src/app/DesktopAppIdentity.ts index 395c06141d64c..5fd6983c66682 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.ts @@ -38,7 +38,7 @@ const normalizeCommitHash = (value: string): Option.Option => { : Option.none(); }; -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const assets = yield* DesktopAssets.DesktopAssets; const electronApp = yield* ElectronApp.ElectronApp; @@ -91,9 +91,7 @@ export const make = Effect.gen(function* () { const configure = Effect.gen(function* () { const commitHash = yield* resolveAboutCommitHash; - // Electron removes spaces from this name to build the native User-Agent - // product token, but leaves parentheses intact. Keep the runtime name valid - // without rewriting preview sessions (which breaks Turnstile, #7110). + // Electron strips spaces but keeps parentheses in its User-Agent token, breaking Turnstile in preview sessions. yield* electronApp.setName( `${environment.branding.baseName} ${environment.branding.stageLabel}`, ); @@ -107,9 +105,7 @@ export const make = Effect.gen(function* () { yield* electronApp.setAppUserModelId(environment.appUserModelId); } - // Unpackaged runs only. A packaged bundle already carries its icon in - // Info.plist, so setting the dock tile again changes nothing except to - // overwrite a custom icon the user attached to the app themselves. + // Packaged bundles carry their icon in Info.plist; setting it again overwrites the user's custom icon. if (environment.platform === "darwin" && !environment.isPackaged) { const iconPaths = yield* assets.iconPaths; yield* Option.match(iconPaths.png, { diff --git a/apps/desktop/src/app/DesktopAssets.test.ts b/apps/desktop/src/app/DesktopAssets.test.ts deleted file mode 100644 index 6d2179f0256ab..0000000000000 --- a/apps/desktop/src/app/DesktopAssets.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import * as NodePath from "@effect/platform-node/NodePath"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -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 Option from "effect/Option"; -import * as PlatformError from "effect/PlatformError"; - -import * as DesktopAssets from "./DesktopAssets.ts"; -import * as DesktopConfig from "./DesktopConfig.ts"; -import * as DesktopEnvironment from "./DesktopEnvironment.ts"; - -const layerEnvironment = DesktopEnvironment.layer({ - dirname: "/repo/apps/desktop/dist-electron", - homeDirectory: "/Users/alice", - platform: "darwin", - processArch: "arm64", - appVersion: "1.2.3", - appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar", - isPackaged: true, - resourcesPath: "/Applications/T3 Code.app/Contents/Resources", - runningUnderArm64Translation: false, -}).pipe( - Layer.provide( - Layer.mergeAll(NodeServices.layer, NodePath.layerPosix, DesktopConfig.layerTest({})), - ), -); - -describe("DesktopAssets", () => { - it.effect("uses canonical source-tree icons for unpackaged development", () => - Effect.gen(function* () { - const layerDevelopmentEnvironment = DesktopEnvironment.layer({ - dirname: "/repo/apps/desktop/dist-electron", - homeDirectory: "/Users/alice", - platform: "linux", - processArch: "x64", - appVersion: "1.2.3", - appPath: "/repo", - isPackaged: false, - resourcesPath: "/repo/apps/desktop/resources", - runningUnderArm64Translation: false, - }).pipe( - Layer.provide( - Layer.mergeAll( - NodeServices.layer, - NodePath.layerPosix, - DesktopConfig.layerTest({ VITE_DEV_SERVER_URL: "http://localhost:5733" }), - ), - ), - ); - const layerFileSystem = FileSystem.layerNoop({ - exists: (path) => Effect.succeed(String(path).includes("/assets/dev/")), - }); - const assets = yield* DesktopAssets.DesktopAssets.pipe( - Effect.provide( - DesktopAssets.layer.pipe( - Layer.provide(Layer.merge(layerFileSystem, layerDevelopmentEnvironment)), - ), - ), - ); - - const icons = yield* assets.iconPaths; - - assert.match(Option.getOrThrow(icons.ico), /assets\/dev\/blueprint-windows\.ico$/); - assert.match(Option.getOrThrow(icons.png), /assets\/dev\/blueprint-universal-1024\.png$/); - assert.isTrue(Option.isNone(icons.icns)); - }), - ); - - it.effect("preserves the failed asset candidate and filesystem cause", () => - Effect.gen(function* () { - const fileName = "custom.bin"; - const candidatePath = "/repo/apps/desktop/resources/custom.bin"; - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "exists", - pathOrDescriptor: candidatePath, - description: "private filesystem diagnostic", - }); - const layerFileSystem = FileSystem.layerNoop({ - exists: (path) => (path === candidatePath ? Effect.fail(cause) : Effect.succeed(false)), - }); - const layerAssets = DesktopAssets.layer.pipe( - Layer.provide(Layer.merge(layerFileSystem, layerEnvironment)), - ); - const assets = yield* DesktopAssets.DesktopAssets.pipe(Effect.provide(layerAssets)); - - const error = yield* assets.resolveResourcePath(fileName).pipe(Effect.flip); - - assert.instanceOf(error, DesktopAssets.DesktopAssetProbeError); - assert.equal(error.fileName, fileName); - assert.equal(error.candidatePath, candidatePath); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - `Failed to probe desktop asset "${fileName}" at ${candidatePath}.`, - ); - assert.notInclude(error.message, "private filesystem diagnostic"); - }), - ); -}); diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts index 58fff8297898b..1e572412d4693 100644 --- a/apps/desktop/src/app/DesktopClerk.test.ts +++ b/apps/desktop/src/app/DesktopClerk.test.ts @@ -5,7 +5,6 @@ import { codexAuthHandoffUrl, readCodexAuthDelivery } from "@t3tools/shared/code import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { assert, describe, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { beforeEach, vi } from "vite-plus/test"; @@ -112,40 +111,6 @@ describe("DesktopClerk", () => { storageMock.mockReset(); }); - it.effect("acquires and releases the SDK bridge with the layer", () => { - const cleanup = vi.fn(); - const events: string[] = []; - storageMock.mockReturnValue(storageAdapter); - createClerkBridgeMock.mockImplementation(() => { - events.push("createClerkBridge"); - return { cleanup, isPrimaryInstance: true }; - }); - - return Effect.gen(function* () { - yield* Effect.scoped(Layer.build(layerDesktopClerk(true, events))); - - assert.deepEqual(createClerkBridgeMock.mock.calls, [ - [ - { - storage: storageAdapter, - manageSingleInstanceLock: false, - passkeys: true, - renderer: { scheme: "t3code-dev", host: "app" }, - }, - ], - ]); - assert.equal(cleanup.mock.calls.length, 1); - assert.deepEqual(events, [ - "setPath:userData:/tmp/app-data/t3code-dev", - "requestSingleInstanceLock", - "on:second-instance", - "createClerkBridge", - ]); - storageMock.mockClear(); - createClerkBridgeMock.mockClear(); - }); - }); - it.each([ { name: "packaged macOS", @@ -198,54 +163,6 @@ describe("DesktopClerk", () => { }, ); - it.effect("preserves bridge initialization failures", () => { - const cause = new Error("bridge initialization failed"); - storageMock.mockReturnValue(storageAdapter); - createClerkBridgeMock.mockImplementationOnce(() => { - throw cause; - }); - - return Effect.gen(function* () { - const error = yield* Effect.scoped(Layer.build(layerDesktopClerk())).pipe(Effect.flip); - - assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError); - assert.equal(error.stateDir, "/tmp/t3-state"); - assert.equal(error.isDevelopment, true); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - 'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).', - ); - }); - }); - - it.effect("preserves bridge cleanup failures", () => { - const cause = new Error("bridge cleanup failed"); - storageMock.mockReturnValue(storageAdapter); - createClerkBridgeMock.mockReturnValue({ - cleanup: () => { - throw cause; - }, - }); - - return Effect.gen(function* () { - const exit = yield* Effect.exit(Effect.scoped(Layer.build(layerDesktopClerk(false)))); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError); - assert.equal(error.stateDir, "/tmp/t3-state"); - assert.equal(error.isDevelopment, false); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - 'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).', - ); - } - }); - }); - it.effect.each(["before configure", "after configure"] as const)( "reveals the running window when a second instance launches %s", (entry) => { diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts index 505b48194cf7c..3e0d753d1bfba 100644 --- a/apps/desktop/src/app/DesktopClerk.ts +++ b/apps/desktop/src/app/DesktopClerk.ts @@ -95,7 +95,7 @@ function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean) { }); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const electronApp = yield* ElectronApp.ElectronApp; @@ -105,14 +105,12 @@ export const make = Effect.gen(function* () { const userDataPath = yield* DesktopUserData.resolveUserDataPath(environment); yield* electronApp.setPath("userData", userDataPath); - // T3 owns the profile-scoped lock on every platform; Clerk skips it on macOS. - // Quit is asynchronous, so interrupt before the application runtime is built. + // Clerk skips the profile lock on macOS. Interrupt before runtime construction because quit is asynchronous. if (!(yield* electronApp.requestSingleInstanceLock)) { yield* electronApp.quit; return yield* Effect.interrupt; } - // Retain launch arguments while asynchronous startup builds the application runtime. const pendingSecondInstances: Array = []; let handleSecondInstance = (argv: readonly string[]) => { pendingSecondInstances.push(argv); diff --git a/apps/desktop/src/app/DesktopCliCommand.test.ts b/apps/desktop/src/app/DesktopCliCommand.test.ts index 7b44fab01855c..db56aa3c83b03 100644 --- a/apps/desktop/src/app/DesktopCliCommand.test.ts +++ b/apps/desktop/src/app/DesktopCliCommand.test.ts @@ -83,7 +83,6 @@ const fakePowerShell = (initial: string) => { return { registry, spawner }; }; -// The machine's own PATH may already hold a t3; each test sets the PATH it means. const machinePath = process.env.PATH; beforeEach(() => { process.env.PATH = ""; @@ -151,22 +150,6 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { }).pipe(Effect.scoped), ); - it.effect("does not read a large binary another t3 links to", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const home = yield* fs.makeTempDirectoryScoped(); - const binary = path.join(home, "native-t3"); - yield* fs.writeFileString(binary, `${"\0".repeat(64 * 1024)}${DesktopCliShim.MARKER}`); - yield* fs.makeDirectory(path.join(home, ".local", "bin"), { recursive: true }); - yield* fs.symlink(binary, path.join(home, ".local", "bin", "t3")); - const command = yield* commandIn({ home }); - expect((yield* command.state).installedPath).toBeNull(); - yield* command.uninstall; - expect(yield* fs.readLink(path.join(home, ".local", "bin", "t3"))).toBe(binary); - }).pipe(Effect.scoped), - ); - it.effect("refuses to install behind another t3 that runs first", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -237,15 +220,4 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect(registry.path).toBe(userPath); }).pipe(Effect.scoped), ); - - it.effect("offers nothing for a development build", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const command = yield* commandIn({ - home: yield* fs.makeTempDirectoryScoped(), - isPackaged: false, - }); - expect((yield* command.state).supported).toBe(false); - }).pipe(Effect.scoped), - ); }); diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.ts index aebe8adb4a05e..95d844e602124 100644 --- a/apps/desktop/src/app/DesktopCliCommand.ts +++ b/apps/desktop/src/app/DesktopCliCommand.ts @@ -28,14 +28,8 @@ const pathEntries = (value: string | undefined, separator: string) => const sameWindowsPath = (left: string, right: string) => left.replace(/[\\/]+$/, "").toLowerCase() === right.replace(/[\\/]+$/, "").toLowerCase(); -/** - * Reads, or with `T3_SET` set writes, the user's PATH in the registry, keeping - * `%VAR%` entries unexpanded. Writes keep REG_EXPAND_SZ (Windows' default for - * PATH; `SetEnvironmentVariable` would store REG_SZ and break every `%VAR%` - * entry), then broadcast WM_SETTINGCHANGE so Explorer and the terminals it - * opens see the change. A failed read exits nonzero rather than reading as - * empty, so a write never replaces the user's PATH wholesale. - */ +// Preserve REG_EXPAND_SZ and %VAR% expansion; notify Explorer with WM_SETTINGCHANGE. +// Failed reads must exit nonzero to prevent replacing PATH wholesale. const WINDOWS_USER_PATH_SCRIPT = ` $ErrorActionPreference = 'Stop' if ($env:T3_SET -eq '1') { @@ -64,7 +58,7 @@ export class DesktopCliCommand extends Context.Service< } >()("@t3tools/desktop/app/DesktopCliCommand") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fs = yield* FileSystem.FileSystem; @@ -83,15 +77,17 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); - const isOurLink = (link: string) => - Effect.gen(function* () { + const isOurLink = Effect.fn("DesktopCliCommand.isOurLink")( + function* (link: string) { yield* fs.readLink(link); // The launcher is a few KB; never read a large binary another `t3` links to. const info = yield* fs.stat(link); if (info.type !== "File" || Number(info.size) > 16_384) return false; const content = yield* fs.readFileString(link); return content.includes(DesktopCliShim.MARKER); - }).pipe(Effect.orElseSucceed(() => false)); + }, + Effect.orElseSucceed(() => false), + ); const powershell = (env: Record) => Effect.scoped( diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 92f42dd2b247e..50fcb08d9c64a 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -64,25 +64,6 @@ const fakeAppImage = (canMount = true) => { }; describe("renderCliShim", () => { - it("runs the AppImage's bundled CLI with every argument and unmounts after", () => { - const { root, image, shim } = fakeAppImage(); - const result = run(shim, ["browser", "setup", "a b"]); - expect(result.status).toBe(3); - expect(result.stdout.split("\n")).toEqual([ - `node=1 cli=${shim} home=${root}/home`, - `${image}/resources/app.asar/apps/server/dist/bin.mjs`, - "browser", - "setup", - "a b", - "", - ]); - NodeChildProcess.spawnSync("sh", [ - "-c", - `i=0; while [ ! -e '${root}/unmounted' ] && [ $i -lt 40 ]; do sleep 0.05; i=$((i+1)); done`, - ]); - expect(NodeFS.existsSync(NodePath.join(root, "unmounted"))).toBe(true); - }); - it("extracts the AppImage where it cannot be mounted", () => { const { shim } = fakeAppImage(false); const result = run(shim, ["--version"], { APPIMAGE_EXTRACT_AND_RUN: "1" }); @@ -100,7 +81,6 @@ describe("renderCliShim", () => { executable: NodePath.join(root, "app"), entry: "/bin.mjs", }); - // sudo clears the environment, so the launcher supplies its own. expect(run(shim, []).stdout).toContain(`home=${root}/home`); expect(run(shim, [], { T3CODE_HOME: "/elsewhere" }).stdout).toContain("home=/elsewhere"); const relative = NodeChildProcess.spawnSync("./bin/t3", [], { cwd: root, encoding: "utf8" }); @@ -124,18 +104,6 @@ describe("renderCliShim", () => { ]); }); - it("tells a person whose app moved to reopen it", () => { - const root = tempRoot(); - const shim = writeShim(root, { - kind: "direct", - executable: NodePath.join(root, "Gone.app/Contents/MacOS/T3 Code"), - entry: "/bin.mjs", - }); - const result = run(shim, ["--version"]); - expect(result.status).toBe(127); - expect(result.stderr).toContain("Open the app once to update this command."); - }); - it("writes a Windows launcher that keeps cmd from reinterpreting paths", () => { const executable = "C:\\Apps\\R&whoami&X 100%\\!CHANNEL!\\T3 Code.exe"; const script = renderCliShim({ @@ -155,14 +123,4 @@ describe("renderCliShim", () => { expect(bare).toEqual([]); expect(lines).toContain('set "T3CODE_CLI_PATH=C:\\Users\\José\\.t3\\bin\\t3.cmd"'); }); - - it("switches the Windows console to UTF-8 only when a path needs it", () => { - const ascii = renderCliShim({ - target: { kind: "windows", executable: "C:\\T3\\T3 Code.exe", entry: "C:\\T3\\bin.mjs" }, - shimPath: "C:\\Users\\me\\.t3\\bin\\t3.cmd", - t3Home: "C:\\Users\\me\\.t3", - }); - expect(ascii).not.toContain("chcp"); - expect(ascii.split("\r\n")).toContain("exit /b %t3_exit%"); - }); }); diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index a9d9f04c4e829..3d4b94abff462 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -6,8 +6,7 @@ import * as Option from "effect/Option"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import { makeComponentLogger } from "./DesktopObservability.ts"; -// An AppImage mounts somewhere new each run, so its launcher mounts the -// AppImage itself instead of pointing into it. +// AppImage mounts change each run; the launcher must mount the image itself. const { logInfo, logWarning } = makeComponentLogger("desktop-cli-shim"); export const MARKER = "Written by T3 Code: runs the desktop app's bundled t3 CLI."; @@ -26,12 +25,7 @@ export type CliShimTarget = | { readonly kind: "direct"; readonly executable: string; readonly entry: string } | { readonly kind: "windows"; readonly executable: string; readonly entry: string }; -/** - * Electron runs the server as plain Node with `ELECTRON_RUN_AS_NODE`, which - * reads the entry from inside the asar archive. The launcher's own path and the - * app's T3 home are written in, so the command the server shows is absolute and - * `sudo`, which clears the environment, still runs against this install's home. - */ +/** Embed this install's home and executable path so `sudo`, which clears the environment, uses the same install. */ export const renderCliShim = (input: { readonly target: CliShimTarget; readonly shimPath: string; @@ -48,9 +42,7 @@ export const renderCliShim = (input: { `rem ${MARKER}`, // Delayed expansion would rewrite `!name!` in paths and arguments. "setlocal EnableExtensions DisableDelayedExpansion", - // Only a non-ASCII path needs the console switched to UTF-8 to read it; a - // Ctrl-C that ends the batch skips the restore, so the switch is left out - // for the common all-ASCII install. + // Ctrl-C skips codepage restoration, so switch to UTF-8 only for non-ASCII install paths. ...(utf8 ? [ `for /f "tokens=2 delims=:." %%c in ('chcp') do set "t3_codepage=%%c"`, @@ -97,8 +89,7 @@ export const renderCliShim = (input: { ...header, // Extract-and-run would make the runtime start the app instead of mounting it. "unset APPIMAGE_EXTRACT_AND_RUN", - // The AppImage runtime prints its mount point, then stays mounted until - // killed. Background jobs ignore Ctrl-C, so the traps unmount it on any exit. + // The runtime stays mounted until killed; traps unmount it because background jobs ignore Ctrl-C. "work=$(mktemp -d) || exit 1", '"$app" --appimage-mount >"$work/mount" 2>/dev/null &', "mounter=$!", diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts index 773ea24509cf1..11f975a6b86af 100644 --- a/apps/desktop/src/app/DesktopConfig.ts +++ b/apps/desktop/src/app/DesktopConfig.ts @@ -55,6 +55,7 @@ export const DesktopConfig = Config.all({ otlpProtocol: Config.schema(OtlpProtocol, "T3CODE_OTLP_PROTOCOL").pipe( Config.withDefault("http/json"), ), + desktopLauncherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), appImagePath: trimmedString("APPIMAGE"), disableAutoUpdate: optionalBoolean("T3CODE_DISABLE_AUTO_UPDATE"), mockUpdates: optionalBoolean("T3CODE_DESKTOP_MOCK_UPDATES"), diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index a8ac69b345358..0b446f8ada300 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -8,7 +8,6 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; @@ -267,144 +266,6 @@ describe("DesktopConnectionCatalogStore", () => { ), ); - it.effect("surfaces catalog filesystem failures instead of treating them as missing", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const baseFileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-connection-catalog-test-", - }); - const permissionError = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFileString", - pathOrDescriptor: path.join(baseDir, "userdata", "connection-catalog.json"), - }); - const layerFileSystem = Layer.succeed( - FileSystem.FileSystem, - FileSystem.makeNoop({ - readFileString: () => Effect.fail(permissionError), - }), - ); - const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( - Effect.provide(layerFor(baseDir, true, null, layerFileSystem)), - ); - - const error = yield* store.get.pipe(Effect.flip); - assert.instanceOf( - error, - DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError, - ); - assert.equal(error.catalogPath, path.join(baseDir, "userdata", "connection-catalog.json")); - assert.strictEqual(error.cause, permissionError); - assert.equal( - error.message, - `Failed to read the desktop connection catalog at ${path.join(baseDir, "userdata", "connection-catalog.json")}.`, - ); - assert.notEqual(error.message, permissionError.message); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - - it.effect("reports the failed catalog write operation and path", () => - Effect.gen(function* () { - const baseFileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-connection-catalog-test-", - }); - const permissionError = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "makeDirectory", - pathOrDescriptor: path.join(baseDir, "userdata"), - }); - const layerFileSystem = Layer.succeed( - FileSystem.FileSystem, - FileSystem.makeNoop({ - makeDirectory: () => Effect.fail(permissionError), - }), - ); - const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( - Effect.provide(layerFor(baseDir, true, null, layerFileSystem)), - ); - - const error = yield* store.set("{}").pipe(Effect.flip); - assert.instanceOf( - error, - DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError, - ); - assert.equal(error.operation, "create-directory"); - assert.equal(error.path, path.join(baseDir, "userdata")); - assert.strictEqual(error.cause, permissionError); - assert.equal( - error.message, - `Desktop connection catalog write failed during create-directory at ${path.join(baseDir, "userdata")}.`, - ); - assert.notEqual(error.message, permissionError.message); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - - it.effect("reports the legacy migration stage", () => - withStore( - Effect.gen(function* () { - const path = yield* Path.Path; - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore; - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json"); - - const error = yield* store.get.pipe(Effect.flip); - assert.instanceOf( - error, - DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreMigrationError, - ); - assert.equal(error.operation, "read-legacy-registry"); - assert.equal(error.catalogPath, path.join(environment.stateDir, "connection-catalog.json")); - assert.instanceOf( - error.cause, - DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError, - ); - const registryError = - error.cause as DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError; - assert.exists(registryError.cause); - assert.equal( - error.message, - `Legacy desktop saved-environment migration failed during read-legacy-registry into ${path.join(environment.stateDir, "connection-catalog.json")}.`, - ); - assert.notEqual(error.message, registryError.message); - }), - ), - ); - - it.effect("reports invalid encrypted catalog data without exposing it", () => - withStore( - Effect.gen(function* () { - const path = yield* Path.Path; - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore; - const catalogPath = path.join(environment.stateDir, "connection-catalog.json"); - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(catalogPath, '{"version":1,"encryptedCatalog":"%%%"}\n'); - - const error = yield* store.get.pipe(Effect.flip); - assert.instanceOf( - error, - DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreDecodeError, - ); - assert.equal(error.resource, "encryptedCatalog"); - assert.equal(error.catalogPath, catalogPath); - assert.exists(error.cause); - assert.equal( - error.message, - `Failed to decode encryptedCatalog for the desktop connection catalog at ${catalogPath}.`, - ); - assert.notInclude(error.message, "%%%"); - }), - ), - ); - it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/desktop/src/app/DesktopDetachedActionErrors.test.ts b/apps/desktop/src/app/DesktopDetachedActionErrors.test.ts deleted file mode 100644 index ae78080539b7e..0000000000000 --- a/apps/desktop/src/app/DesktopDetachedActionErrors.test.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; - -import { DesktopLifecycleRelaunchError } from "./DesktopLifecycle.ts"; -import { DesktopApplicationMenuActionError } from "../window/DesktopApplicationMenu.ts"; - -describe("desktop detached action errors", () => { - it("preserves the complete relaunch failure cause and reason", () => { - const cause = Cause.combine( - Cause.fail(new Error("shutdown failed")), - Cause.die(new Error("relaunch defect")), - ); - const error = new DesktopLifecycleRelaunchError({ - reason: "apply update", - cause, - }); - - assert.strictEqual(error.cause, cause); - assert.equal(error.reason, "apply update"); - assert.equal(error.message, 'Desktop relaunch failed for reason "apply update".'); - }); - - it("preserves the complete menu action failure cause and action", () => { - const cause = Cause.combine( - Cause.fail(new Error("window unavailable")), - Cause.die(new Error("dispatch defect")), - ); - const error = new DesktopApplicationMenuActionError({ - action: "open-settings", - cause, - }); - - assert.strictEqual(error.cause, cause); - assert.equal(error.action, "open-settings"); - assert.equal(error.message, 'Desktop menu action "open-settings" failed.'); - }); -}); diff --git a/apps/desktop/src/app/DesktopEarlyElectronStartup.test.ts b/apps/desktop/src/app/DesktopEarlyElectronStartup.test.ts index 01d1aa1b115e5..6d40bd128b77f 100644 --- a/apps/desktop/src/app/DesktopEarlyElectronStartup.test.ts +++ b/apps/desktop/src/app/DesktopEarlyElectronStartup.test.ts @@ -3,7 +3,7 @@ import * as NodePath from "node:path"; import { assert, describe, it } from "@effect/vitest"; import { - resolveEarlyLinuxElectronOptions, + restoreEarlyLinuxDeviceScaleFactor, resolveEarlyLinuxPasswordStorePreference, resolveLinuxDisableFeaturesSwitch, } from "./DesktopEarlyElectronStartup.ts"; @@ -52,83 +52,11 @@ describe("DesktopEarlyElectronStartup", () => { assert.equal(preference, "auto"); }); - it("preserves absolute root paths when resolving early settings", () => { - const preference = resolveEarlyLinuxPasswordStorePreference({ - env: { T3CODE_HOME: "/" }, - homeDirectory: "/home/user", - joinPath, - readFileString: (path) => { - assert.equal(path, "/userdata/desktop-settings.json"); - return JSON.stringify({ linuxPasswordStore: "kwallet6" }); - }, - }); - - assert.equal(preference, "kwallet6"); - }); - - it("resolves the early linux Electron switches", () => { - const options = resolveEarlyLinuxElectronOptions({ - env: { - T3CODE_HOME: "/home/user/.t3-test", - XDG_CURRENT_DESKTOP: "niri", - VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", - }, - homeDirectory: "/home/user", - joinPath, - readFileString: (path) => { - assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json"); - return JSON.stringify({ linuxPasswordStore: "auto" }); - }, - }); - - assert.deepEqual(options, { - isDevelopment: true, - linuxWmClass: "t3code-dev", - linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop", - passwordStore: "gnome-libsecret", - }); - }); - - it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => { - const preference = resolveEarlyLinuxPasswordStorePreference({ - env: { - VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", - }, - homeDirectory: "/home/user", - joinPath, - readFileString: (path) => { - assert.equal(path, "/home/user/.t3/dev/desktop-settings.json"); - return JSON.stringify({ linuxPasswordStore: "kwallet" }); - }, - }); - - assert.equal(preference, "kwallet"); - }); - - it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => { - const preference = resolveEarlyLinuxPasswordStorePreference({ - env: { - T3CODE_HOME: " ", - VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", - }, - homeDirectory: "/home/user", - joinPath, - readFileString: (path) => { - assert.equal(path, "/home/user/.t3/dev/desktop-settings.json"); - return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" }); - }, - }); - - assert.equal(preference, "gnome-libsecret"); - }); - describe("resolveLinuxDisableFeaturesSwitch", () => { const hyprland = { XDG_CURRENT_DESKTOP: "Hyprland", XDG_SESSION_TYPE: "wayland" }; const releaseCommits: Record = { "0.48.0": "5ee35f914f921e5696030698e74fb5566a804768", "0.48.1": "29e2e59fdbab8ed2cc23a20e3c6043d5decb5cdc", - "0.49.0": "9958d297641b5c84dcff93f9039d80a5ad37ab00", - "0.50.0": "c4a4c341568944bd4fb9cd503558b2de602c0213", "0.50.1": "4e242d086e20b32951fdc0ebcbfb4d41b5be8dcc", }; const hyprctlVersion = @@ -150,18 +78,15 @@ describe("DesktopEarlyElectronStartup", () => { readHyprctlVersionJson: hyprctlVersion("0.48.1"), }; - it.each(["0.48.0", "0.48.1", "0.49.0", "0.50.0", "0.50.1"])( - "disables the color manager on Hyprland %s", - (version) => { - assert.equal( - resolveLinuxDisableFeaturesSwitch({ - ...brokenHyprland, - readHyprctlVersionJson: hyprctlVersion(version), - }), - "WaylandWpColorManagerV1", - ); - }, - ); + it.each(["0.48.0", "0.50.1"])("disables the color manager on Hyprland %s", (version) => { + assert.equal( + resolveLinuxDisableFeaturesSwitch({ + ...brokenHyprland, + readHyprctlVersionJson: hyprctlVersion(version), + }), + "WaylandWpColorManagerV1", + ); + }); it.each([ { label: "case-insensitive desktop tokens", env: { XDG_CURRENT_DESKTOP: "foo:HYPRLAND" } }, @@ -176,70 +101,6 @@ describe("DesktopEarlyElectronStartup", () => { ); }); - it("keeps existing disabled features", () => { - assert.equal( - resolveLinuxDisableFeaturesSwitch({ - ...brokenHyprland, - disableFeatures: "Vulkan,WaylandWpColorManagerV1Extra", - }), - "Vulkan,WaylandWpColorManagerV1Extra,WaylandWpColorManagerV1", - ); - }); - - it.each([ - { label: "Hyprland 0.47.2", readHyprctlVersionJson: hyprctlVersion("0.47.2") }, - { label: "Hyprland 0.51.0", readHyprctlVersionJson: hyprctlVersion("0.51.0") }, - { label: "Hyprland 0.56.2", readHyprctlVersionJson: hyprctlVersion("0.56.2") }, - { label: "an unrecognized version", readHyprctlVersionJson: hyprctlVersion("1.0.0") }, - { - label: "a malformed version", - readHyprctlVersionJson: hyprctlVersion("0.48.not-a-version"), - }, - { label: "a two-part version", readHyprctlVersionJson: hyprctlVersion("0.48") }, - { label: "a prerelease version", readHyprctlVersionJson: hyprctlVersion("0.49.0-rc1") }, - { - label: "a development build after an affected release", - readHyprctlVersionJson: hyprctlVersion("0.50.1", { tag: "v0.50.1-87-g4e8875b5" }), - }, - { - label: "a later Nix build reporting an affected release tag", - readHyprctlVersionJson: hyprctlVersion("0.50.1", { - commit: "4e8875b5e9700c81ca4e169dc7b85bb5b3c8cb7a", - }), - }, - { - label: "an affected version with another release's commit", - readHyprctlVersionJson: hyprctlVersion("0.48.0", { commit: releaseCommits["0.48.1"] }), - }, - { label: "an unknown patch release", readHyprctlVersionJson: hyprctlVersion("0.50.2") }, - { - label: "missing commit metadata", - readHyprctlVersionJson: () => - JSON.stringify({ version: "0.48.1", tag: "v0.48.1", dirty: false }), - }, - { - label: "a build without git metadata", - readHyprctlVersionJson: hyprctlVersion("0.48.1", { tag: "" }), - }, - { - label: "a dirty build", - readHyprctlVersionJson: hyprctlVersion("0.48.1", { dirty: true }), - }, - { - label: "output without build metadata", - readHyprctlVersionJson: () => JSON.stringify({ version: "0.48.1" }), - }, - { label: "unparseable hyprctl output", readHyprctlVersionJson: () => "ok" }, - { - label: "a missing hyprctl", - readHyprctlVersionJson: () => { - throw new Error("spawnSync hyprctl ENOENT"); - }, - }, - ])("preserves color management for $label", (overrides) => { - assert.isNull(resolveLinuxDisableFeaturesSwitch({ ...brokenHyprland, ...overrides })); - }); - it.each([ { label: "a stale Hyprland signature in KDE", @@ -269,3 +130,70 @@ describe("DesktopEarlyElectronStartup", () => { }); }); }); + +describe("Linux device scale persistence failures", () => { + const input = { + env: { T3CODE_HOME: "/isolated" }, + homeDirectory: "/home/user", + joinPath: NodePath.posix.join, + }; + + it.each(["0", "Infinity", "garbage"])("ignores invalid persisted scale %j", (value) => { + const applied: Array<[string, string]> = []; + const writes: Array = []; + restoreEarlyLinuxDeviceScaleFactor({ + ...input, + commandLine: { + hasSwitch: () => false, + getSwitchValue: () => "", + appendSwitch: (name, scale) => applied.push([name, scale]), + }, + readFileString: () => value, + writeFileString: (_path, contents) => writes.push(contents), + }); + assert.deepEqual(applied, []); + assert.deepEqual(writes, []); + }); + + it("keeps startup available with default scaling when saved state cannot be read", () => { + const applied: Array<[string, string]> = []; + restoreEarlyLinuxDeviceScaleFactor({ + ...input, + commandLine: { + hasSwitch: () => false, + getSwitchValue: () => "", + appendSwitch: (name, value) => applied.push([name, value]), + }, + readFileString: () => { + throw new Error("ENOENT"); + }, + writeFileString: () => {}, + }); + assert.deepEqual(applied, []); + }); + + it("keeps an explicit scale when saving it fails, without falling back to saved state", () => { + const applied: Array<[string, string]> = []; + const reads: Array = []; + const writes: Array = []; + restoreEarlyLinuxDeviceScaleFactor({ + ...input, + commandLine: { + hasSwitch: () => true, + getSwitchValue: () => "1", + appendSwitch: (name, value) => applied.push([name, value]), + }, + readFileString: (path) => { + reads.push(path); + return "1.75"; + }, + writeFileString: (_path, value) => { + writes.push(value); + throw new Error("EACCES"); + }, + }); + assert.deepEqual(writes, ["1"]); + assert.deepEqual(reads, []); + assert.deepEqual(applied, []); + }); +}); diff --git a/apps/desktop/src/app/DesktopEarlyElectronStartup.ts b/apps/desktop/src/app/DesktopEarlyElectronStartup.ts index ad2947013771a..00a355bf49617 100644 --- a/apps/desktop/src/app/DesktopEarlyElectronStartup.ts +++ b/apps/desktop/src/app/DesktopEarlyElectronStartup.ts @@ -86,8 +86,7 @@ const WAYLAND_COLOR_MANAGER_FEATURE = "WaylandWpColorManagerV1"; const featureListNames = (value: string | null): ReadonlyArray => (value ?? "").split(",").flatMap((entry) => entry.trim().match(/^\*?([^<:]+)/)?.[1] ?? []); -// A stale HYPRLAND_INSTANCE_SIGNATURE is often inherited into other desktops, so only -// trust the session's desktop names. +// HYPRLAND_INSTANCE_SIGNATURE can be stale; trust only the session's desktop names. const isHyprlandSession = (env: NodeJS.ProcessEnv): boolean => (trimNonEmpty(env.XDG_CURRENT_DESKTOP) ?? trimNonEmpty(env.XDG_SESSION_DESKTOP) ?? "") .split(":") @@ -103,12 +102,8 @@ const HyprctlVersionJson = fromLenientJson( ); const decodeHyprctlVersionJson = Schema.decodeSync(HyprctlVersionJson); -// Hyprland 0.48.0 added wp-color-manager-v1 (hyprwm/Hyprland#9444) advertising -// FEATURE_SET_PRIMARIES while rejecting set_primaries outside debug mode, which Chromium -// treats as a fatal protocol error. 0.51.0 accepts them (hyprwm/Hyprland#11499). -// Only stock builds of these releases count. Matching the commit as well as the tag -// keeps later development builds that still report an old VERSION and tag (Nix -// synthesizes `v${VERSION}`) on the default. +// Hyprland 0.48.0 rejects advertised set_primaries (hyprwm/Hyprland#9444); 0.51.0 accepts it (hyprwm/Hyprland#11499). +// Check commits because dev and Nix builds can retain release versions and tags. const AFFECTED_HYPRLAND_RELEASE_COMMITS: ReadonlyMap = new Map([ ["0.48.0", "5ee35f914f921e5696030698e74fb5566a804768"], ["0.48.1", "29e2e59fdbab8ed2cc23a20e3c6043d5decb5cdc"], @@ -159,3 +154,43 @@ export function resolveEarlyLinuxElectronOptions( }), }; } + +/** Remember the explicit Chromium scale across AppImage updates, which drop launch arguments. */ +export function restoreEarlyLinuxDeviceScaleFactor( + input: EarlyDesktopSettingsInput & { + readonly commandLine: { + readonly hasSwitch: (name: string) => boolean; + readonly getSwitchValue: (name: string) => string; + readonly appendSwitch: (name: string, value: string) => void; + }; + readonly writeFileString: (path: string, value: string) => void; + }, +): void { + // Keep this separate from desktop-settings.json: the settings service rewrites + // that document, and Chromium needs the value before that service is available. + const path = input.joinPath( + resolveEarlyDesktopSettingsPath(input), + "..", + "linux-device-scale-factor", + ); + const switchName = "force-device-scale-factor"; + const isValid = (value: string) => + value.trim().length > 0 && Number.isFinite(Number(value)) && Number(value) > 0; + if (input.commandLine.hasSwitch(switchName)) { + const value = input.commandLine.getSwitchValue(switchName); + if (isValid(value)) { + try { + input.writeFileString(path, value); + } catch { + // A read-only state directory must not prevent startup with the explicit switch. + } + } + return; + } + try { + const value = input.readFileString(path).trim(); + if (isValid(value)) input.commandLine.appendSwitch(switchName, value); + } catch { + // First launch, missing state, or unreadable state: keep Chromium's default. + } +} diff --git a/apps/desktop/src/app/DesktopEnvironment.test.ts b/apps/desktop/src/app/DesktopEnvironment.test.ts index fb6c5a8b1afdb..200745f11136e 100644 --- a/apps/desktop/src/app/DesktopEnvironment.test.ts +++ b/apps/desktop/src/app/DesktopEnvironment.test.ts @@ -3,7 +3,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopConfig from "./DesktopConfig.ts"; @@ -39,86 +38,6 @@ const makeEnvironment = ( ) => DesktopEnvironment.DesktopEnvironment.pipe(Effect.provide(layerEnvironment(overrides, env))); describe("DesktopEnvironment", () => { - it.effect("derives state paths and development identity inside Effect", () => - Effect.gen(function* () { - const environment = yield* makeEnvironment( - {}, - { - T3CODE_HOME: " /tmp/t3 ", - T3CODE_COMMIT_HASH: " 0123456789abcdef ", - T3CODE_PORT: "4949", - VITE_DEV_SERVER_URL: "http://localhost:5173", - T3CODE_DEV_REMOTE_T3_SERVER_ENTRY_PATH: " /remote/server.mjs ", - T3CODE_OTLP_TRACES_URL: " http://127.0.0.1:4318/v1/traces ", - T3CODE_OTLP_METRICS_URL: " http://127.0.0.1:4318/v1/metrics ", - T3CODE_OTLP_LOGS_URL: " http://127.0.0.1:4318/v1/logs ", - T3CODE_OTLP_EXPORT_INTERVAL_MS: "2500", - T3CODE_OTLP_HEADERS: "authorization=Basic%20abc%3D%3D,x-tenant=t3", - T3CODE_OTLP_PROTOCOL: "http/protobuf", - }, - ); - - assert.equal(environment.isDevelopment, true); - assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support"); - assert.equal(environment.baseDir, "/tmp/t3"); - assert.equal(environment.stateDir, "/tmp/t3/userdata"); - assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json"); - assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json"); - assert.equal( - environment.savedEnvironmentRegistryPath, - "/tmp/t3/userdata/saved-environments.json", - ); - assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json"); - assert.equal(environment.logDir, "/tmp/t3/userdata/logs"); - assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts"); - assert.equal(environment.rootDir, "/repo"); - assert.equal(environment.appRoot, "/repo"); - assert.equal(environment.serverRoot, "/repo"); - assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs"); - assert.equal(environment.backendCwd, "/repo"); - assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev"); - assert.equal(environment.linuxWmClass, "t3code-dev"); - assert.equal(environment.linuxDesktopEntryName, "com.t3tools.T3Code.Development.desktop"); - assert.deepEqual( - Option.map(environment.devServerUrl, (url) => url.href), - Option.some("http://localhost:5173/"), - ); - assert.deepEqual(environment.devRemoteT3ServerEntryPath, Option.some("/remote/server.mjs")); - assert.deepEqual(environment.configuredBackendPort, Option.some(4949)); - assert.deepEqual(environment.commitHashOverride, Option.some("0123456789abcdef")); - assert.deepEqual(environment.otlpTracesUrl, Option.some("http://127.0.0.1:4318/v1/traces")); - assert.deepEqual(environment.otlpMetricsUrl, Option.some("http://127.0.0.1:4318/v1/metrics")); - assert.deepEqual(environment.otlpLogsUrl, Option.some("http://127.0.0.1:4318/v1/logs")); - assert.equal(environment.otlpExportIntervalMs, 2500); - assert.deepEqual( - environment.otlpHeaders, - Option.some({ - authorization: "Basic abc==", - "x-tenant": "t3", - }), - ); - assert.equal(environment.otlpProtocol, "http/protobuf"); - }), - ); - - it.effect("stores production state under userdata in an explicit home", () => - Effect.gen(function* () { - const environment = yield* makeEnvironment( - {}, - { - T3CODE_HOME: "/tmp/t3", - }, - ); - - assert.equal(environment.isDevelopment, false); - assert.equal(environment.stateDir, "/tmp/t3/userdata"); - assert.equal(environment.logDir, "/tmp/t3/userdata/logs"); - assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts"); - assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json"); - assert.equal(environment.otlpProtocol, "http/json"); - }), - ); - it.effect("uses the packaged Windows server sidecar as the backend root", () => Effect.gen(function* () { const environment = yield* makeEnvironment({ @@ -141,19 +60,6 @@ describe("DesktopEnvironment", () => { }), ); - it.effect("uses the stable desktop entry as the packaged Linux portal identity", () => - Effect.gen(function* () { - const environment = yield* makeEnvironment({ - platform: "linux", - isPackaged: true, - appPath: "/tmp/.mount_t3code/resources/app.asar", - resourcesPath: "/tmp/.mount_t3code/resources", - }); - - assert.equal(environment.linuxDesktopEntryName, "com.t3tools.T3Code.desktop"); - }), - ); - it.effect("keeps implicit development state separate from production state", () => Effect.gen(function* () { const development = yield* makeEnvironment( @@ -166,38 +72,4 @@ describe("DesktopEnvironment", () => { assert.equal(production.stateDir, "/Users/alice/.t3/userdata"); }), ); - - it.effect("uses a configured app user model id override", () => - Effect.gen(function* () { - const environment = yield* makeEnvironment( - {}, - { - T3CODE_DESKTOP_APP_USER_MODEL_ID: " com.t3tools.t3code.dev.local ", - VITE_DEV_SERVER_URL: "http://localhost:5173", - }, - ); - - assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev.local"); - }), - ); - - it.effect("resolves picker defaults without nullish sentinels", () => - Effect.gen(function* () { - const environment = yield* makeEnvironment(); - - assert.deepEqual(environment.resolvePickFolderDefaultPath(null), Option.none()); - assert.deepEqual( - environment.resolvePickFolderDefaultPath({ initialPath: " " }), - Option.none(), - ); - assert.deepEqual( - environment.resolvePickFolderDefaultPath({ initialPath: "~" }), - Option.some("/Users/alice"), - ); - assert.deepEqual( - environment.resolvePickFolderDefaultPath({ initialPath: "~/project" }), - Option.some("/Users/alice/project"), - ); - }), - ); }); diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index ecf08255feb3f..1066198b8f610 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -77,6 +77,7 @@ export class DesktopEnvironment extends Context.Service< readonly linuxDesktopEntryName: string; readonly linuxWmClass: string; readonly linuxApplicationsDir: string; + readonly desktopLauncherPath: Option.Option; readonly appImagePath: Option.Option; readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings; readonly runtimeInfo: DesktopRuntimeInfo; @@ -233,6 +234,7 @@ const make = Effect.fn("desktop.environment.make")(function* ( linuxDesktopEntryName: resolveLinuxDesktopEntryName(isDevelopment), linuxWmClass: isDevelopment ? "t3code-dev" : "t3code", linuxApplicationsDir, + desktopLauncherPath: config.desktopLauncherPath, appImagePath: config.appImagePath, defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion), runtimeInfo: resolveDesktopRuntimeInfo({ diff --git a/apps/desktop/src/app/DesktopLegacyLocalStorage.ts b/apps/desktop/src/app/DesktopLegacyLocalStorage.ts index 9deba23899222..90043d9398a2c 100644 --- a/apps/desktop/src/app/DesktopLegacyLocalStorage.ts +++ b/apps/desktop/src/app/DesktopLegacyLocalStorage.ts @@ -10,10 +10,7 @@ import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import { readChromiumLocalStorage } from "./chromiumLocalStorage.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; -/** - * The V1 profile is only read, never opened by Chromium, so this works while V1 - * is still running. - */ +/** Reads the V1 profile without opening it in Chromium, even while V1 runs. */ export class DesktopLegacyLocalStorage extends Context.Service< DesktopLegacyLocalStorage, { @@ -34,8 +31,8 @@ const make = Effect.gen(function* () { const markerPath = yield* Ref.make(Option.none()); /** Newest file mtime in a directory; appending to a log leaves the directory's own mtime alone. */ - const newestFileMtime = (directory: string) => - Effect.gen(function* () { + const newestFileMtime = Effect.fn("DesktopLegacyLocalStorage.newestFileMtime")( + function* (directory: string) { let newest = 0; for (const name of yield* fs.readDirectory(directory)) { const info = yield* fs.stat(path.join(directory, name)).pipe(Effect.option); @@ -47,7 +44,9 @@ const make = Effect.gen(function* () { newest = Math.max(newest, mtime); } return newest; - }).pipe(Effect.option); + }, + (effect, _directory) => effect.pipe(Effect.option), + ); const findV1LocalStorage = Effect.gen(function* () { let newest: { readonly directory: string; readonly mtime: number } | null = null; diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index f9f38dea3dd46..6a6e991fc6b4b 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -3,6 +3,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; +import * as TestClock from "effect/testing/TestClock"; import type * as Electron from "electron"; @@ -18,6 +19,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts"; function layerElectronApp( appListeners: Map void>, quit: Effect.Effect = Effect.void, + exit: (code: number) => Effect.Effect = () => Effect.void, ) { const registerListener = (eventName: string, listener: (...args: readonly unknown[]) => void) => Effect.acquireRelease( @@ -37,7 +39,7 @@ function layerElectronApp( whenReady: Effect.void, requestSingleInstanceLock: Effect.succeed(true), quit, - exit: () => Effect.void, + exit, relaunch: () => Effect.void, setPath: () => Effect.void, setName: () => Effect.void, @@ -221,6 +223,60 @@ describe("DesktopLifecycle", () => { }), ); + it.effect("exits on a repeated quit only once shutdown has stalled", () => + Effect.gen(function* () { + const appListeners = new Map void>(); + const exitCodes: number[] = []; + const exit = (code: number) => + Effect.sync(() => { + exitCodes.push(code); + }); + const layerEnvironment = Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + platform: "darwin", + isDevelopment: false, + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const layer = DesktopLifecycle.layer.pipe( + Layer.provideMerge(layerElectronApp(appListeners, Effect.void, exit)), + Layer.provideMerge(layerElectronTheme), + Layer.provideMerge(layerElectronWindow()), + Layer.provideMerge(layerDesktopWindow()), + Layer.provideMerge(layerEnvironment), + // Nothing marks this shutdown complete, so it stays pending. + Layer.provideMerge(DesktopShutdown.layer), + Layer.provideMerge(DesktopState.layer), + ); + + yield* Effect.scoped( + Effect.gen(function* () { + const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; + yield* lifecycle.register; + + let prevented = 0; + const event = { + preventDefault: () => { + prevented += 1; + }, + } as Electron.Event; + appListeners.get("before-quit")?.(event); + appListeners.get("before-quit")?.(event); + yield* TestClock.adjust("9999 millis"); + appListeners.get("before-quit")?.(event); + assert.deepEqual( + exitCodes, + [], + "a repeat before the threshold must not cut shutdown short", + ); + + yield* TestClock.adjust("1 millis"); + appListeners.get("before-quit")?.(event); + + assert.deepEqual(exitCodes, [0]); + assert.equal(prevented, 4); + }), + ).pipe(Effect.provide(layer)); + }), + ); + it.effect("ignores app activation while quitting", () => Effect.gen(function* () { const appListeners = new Map void>(); diff --git a/apps/desktop/src/app/DesktopLifecycle.ts b/apps/desktop/src/app/DesktopLifecycle.ts index 924341781aa6b..93347949e00fa 100644 --- a/apps/desktop/src/app/DesktopLifecycle.ts +++ b/apps/desktop/src/app/DesktopLifecycle.ts @@ -1,4 +1,6 @@ +import * as Clock from "effect/Clock"; 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 Ref from "effect/Ref"; @@ -94,15 +96,50 @@ const requestDesktopShutdownAndWait = Effect.fn("desktop.lifecycle.requestShutdo }, ); +interface QuitState { + phase: "running" | "waiting" | "allowed"; + waitingSinceNanos: bigint; +} + +// Longer than a backend's stop budget (SIGTERM, 5s grace, SIGKILL, 1s wait), +// so a double Cmd-Q at the start of a normal quit cannot cut the backend stop +// short and orphan it. +const SHUTDOWN_STALL_THRESHOLD = Duration.seconds(10); + +const startWaitingForShutdown = Effect.fn("desktop.lifecycle.startWaitingForShutdown")(function* ( + quit: QuitState, +) { + quit.phase = "waiting"; + quit.waitingSinceNanos = yield* Clock.monotonicTimeNanos; +}); + +// While a quit waits on shutdown, `quitting` makes activation open nothing. If +// that shutdown stalls, a repeated Quit or SIGTERM is the user's only way out +// short of SIGKILL. +const exitIfShutdownStalled = Effect.fn("desktop.lifecycle.exitIfShutdownStalled")(function* ( + quit: QuitState, + source: string, +) { + const pendingMs = Number( + ((yield* Clock.monotonicTimeNanos) - quit.waitingSinceNanos) / 1_000_000n, + ); + if (pendingMs < Duration.toMillis(SHUTDOWN_STALL_THRESHOLD)) { + yield* logLifecycleInfo("quit already in progress", { source, pendingMs }); + return; + } + yield* logLifecycleError("desktop shutdown stalled; exiting without it", { source, pendingMs }); + const electronApp = yield* ElectronApp.ElectronApp; + yield* electronApp.exit(0); +}); + function handleBeforeQuit( event: Electron.Event, runEffect: ( effect: Effect.Effect, ) => Promise, - allowQuit: () => boolean, - markQuitAllowed: () => void, + quit: QuitState, ): void { - if (allowQuit()) { + if (quit.phase === "allowed") { void runEffect( Effect.gen(function* () { const state = yield* DesktopState.DesktopState; @@ -114,10 +151,15 @@ function handleBeforeQuit( } event.preventDefault(); + if (quit.phase === "waiting") { + void runEffect(exitIfShutdownStalled(quit, "before-quit")); + return; + } void runEffect( Effect.gen(function* () { const state = yield* DesktopState.DesktopState; const electronWindow = yield* ElectronWindow.ElectronWindow; + yield* startWaitingForShutdown(quit); yield* Ref.set(state.quitting, true); yield* logLifecycleInfo("before-quit received"); yield* requestDesktopShutdownAndWait( @@ -129,7 +171,7 @@ function handleBeforeQuit( ); }).pipe(Effect.withSpan("desktop.lifecycle.beforeQuit")), ).finally(() => { - markQuitAllowed(); + quit.phase = "allowed"; void runEffect( Effect.gen(function* () { const electronApp = yield* ElectronApp.ElectronApp; @@ -144,7 +186,12 @@ function quitFromSignal( runEffect: ( effect: Effect.Effect, ) => Promise, + quit: QuitState, ): void { + if (quit.phase === "waiting") { + void runEffect(exitIfShutdownStalled(quit, signal)); + return; + } void runEffect( Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ signal }); @@ -152,14 +199,16 @@ function quitFromSignal( const state = yield* DesktopState.DesktopState; const wasQuitting = yield* Ref.getAndSet(state.quitting, true); if (wasQuitting) return; + yield* startWaitingForShutdown(quit); yield* logLifecycleInfo("process signal received", { signal }); yield* requestDesktopShutdownAndWait(); + quit.phase = "allowed"; yield* electronApp.quit; }).pipe(Effect.withSpan("desktop.lifecycle.processSignal")), ); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = DesktopLifecycle.of({ relaunch: Effect.fn("desktop.lifecycle.relaunch")(function* (reason) { const electronApp = yield* ElectronApp.ElectronApp; @@ -196,8 +245,7 @@ export const make = DesktopLifecycle.of({ const environment = yield* DesktopEnvironment.DesktopEnvironment; const context = yield* Effect.context(); const runEffect = Effect.runPromiseWith(context); - let quitAllowed = false; - let updaterQuitAllowed = false; + const quit: QuitState = { phase: "running", waitingSinceNanos: 0n }; yield* electronTheme.onUpdated(() => { void runEffect( desktopWindow.syncAppearance.pipe(Effect.withSpan("desktop.lifecycle.themeUpdated")), @@ -207,7 +255,7 @@ export const make = DesktopLifecycle.of({ // Electron's updater owns the remaining quit/install/relaunch sequence. // Cancelling the following app "before-quit" event breaks that sequence, // most visibly on macOS where the native updater performs the relaunch. - updaterQuitAllowed = true; + quit.phase = "allowed"; // This event is synchronous and the updater's quit proceeds as soon as // the listener returns, so a forked destroyAll would race the quit // and windows could still be open when the process exits (visible on @@ -223,14 +271,7 @@ export const make = DesktopLifecycle.of({ ); }); yield* electronApp.on("before-quit", (event: Electron.Event) => { - handleBeforeQuit( - event, - runEffect, - () => quitAllowed || updaterQuitAllowed, - () => { - quitAllowed = true; - }, - ); + handleBeforeQuit(event, runEffect, quit); }); yield* electronApp.on("activate", () => { void runEffect( @@ -255,10 +296,10 @@ export const make = DesktopLifecycle.of({ if (environment.platform !== "win32") { yield* addScopedListener(process, "SIGINT", () => { - quitFromSignal("SIGINT", runEffect); + quitFromSignal("SIGINT", runEffect, quit); }); yield* addScopedListener(process, "SIGTERM", () => { - quitFromSignal("SIGTERM", runEffect); + quitFromSignal("SIGTERM", runEffect, quit); }); } }).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 e6900a03b7d2e..feedbbd580074 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts @@ -2,7 +2,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; 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 Option from "effect/Option"; @@ -10,7 +9,6 @@ import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; @@ -33,6 +31,7 @@ const makeEnvironment = (path: Path.Path, overrides: Record = { linuxDesktopEntryName: "com.t3tools.T3Code.desktop", linuxWmClass: "t3code", linuxApplicationsDir: "/home/alice/.local/share/applications", + desktopLauncherPath: Option.none(), appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"), path, ...overrides, @@ -179,33 +178,6 @@ describe("DesktopLinuxUrlHandler", () => { assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png"); }); - it("carries structured context on registration errors", () => { - const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({ - step: "write-desktop-entry", - scheme: "t3code", - desktopEntryPath: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop", - cause: new Error("boom"), - }); - assert.equal( - writeError.message, - "Failed to register the t3code:// URL handler (step: write-desktop-entry).", - ); - assert.equal( - writeError.desktopEntryPath, - "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop", - ); - - const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({ - step: "set-default-handler", - scheme: "t3code", - exitCode: 4, - }); - assert.equal( - exitError.message, - "Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).", - ); - }); - it.effect( "writes the handler entry, refreshes the MIME cache, and claims the scheme default", () => { @@ -222,7 +194,7 @@ describe("DesktopLinuxUrlHandler", () => { ); assert.include( recorded.files[0]?.content, - 'Exec="/home/alice/Applications/T3-Code.AppImage" %U', + "Exec=/home/alice/Applications/T3-Code.AppImage %U", ); assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;"); assert.deepEqual(recorded.commands, [ @@ -247,11 +219,28 @@ describe("DesktopLinuxUrlHandler", () => { assert.include( recorded.files[0]?.content, - `Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`, + DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({ + displayName: "T3 Code (Alpha)", + execTarget: process.execPath, + scheme: "t3code", + iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png", + }), ); }); }); + it.effect("launches a distribution package through its configured launcher", () => { + const recorded = emptyRecording(); + + return Effect.gen(function* () { + yield* runRegister(recorded, { + environment: { desktopLauncherPath: Option.some("/opt/T3 Code/t3code") }, + }); + + assert.include(recorded.files[0]?.content, 'Exec="/opt/T3 Code/t3code" %U'); + }); + }); + it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => { const recorded = emptyRecording(); @@ -369,26 +358,6 @@ describe("DesktopLinuxUrlHandler", () => { assert.deepEqual(writeFailed.commands, []); }); }); - - it.effect("continues to xdg-mime when the desktop MIME cache refresh stalls", () => - Effect.gen(function* () { - const recorded = emptyRecording(); - const started = yield* Deferred.make(); - const registration = yield* runRegister(recorded, { - updateDesktopDatabaseStalled: true, - updateDesktopDatabaseStarted: started, - }).pipe(Effect.forkChild); - - yield* Deferred.await(started); - yield* TestClock.adjust("5 seconds"); - yield* Fiber.join(registration); - - assert.deepEqual( - recorded.commands.map(({ command }) => command), - ["update-desktop-database", "xdg-mime"], - ); - }), - ); }); interface ThemeIconRun { @@ -501,9 +470,7 @@ const themeIconFixture = (source: Uint8Array) => const hicolorDir = path.join(root, "icons", "hicolor"); const appsDir = path.join(hicolorDir, "256x256", "apps"); const cachePath = path.join(hicolorDir, "icon-theme.cache"); - // A fixed time in the past, in whole seconds as fs.utimes expects. const pastSeconds = 1_600_000_000; - // An existing cache that predates any installed icon. const seedCache = Effect.gen(function* () { yield* fileSystem.makeDirectory(appsDir, { recursive: true }); yield* fileSystem.writeFile(cachePath, new Uint8Array([0])); @@ -591,7 +558,6 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { commands: [], onIconCacheRefresh: fixture.rewriteCache, }; - // A cache stamped later than the new icons, as after a clock correction. const future = fixture.pastSeconds + 10 * 365 * 24 * 60 * 60; yield* fileSystem.utimes(fixture.cachePath, future, future); @@ -648,33 +614,4 @@ it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => { ); }).pipe(Effect.scoped), ); - - it.effect("continues to xdg-mime when the icon cache refresh stalls", () => - Effect.gen(function* () { - const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3])); - yield* fixture.seedCache; - const started = yield* Deferred.make(); - const iconCacheOptions: Array> = []; - const run: ThemeIconRun = { - root: fixture.root, - commands: [], - iconCacheOptions, - iconCacheStalled: true, - iconCacheStarted: started, - }; - - const registration = yield* registerWithRealFileSystem(run).pipe(Effect.forkChild); - yield* Deferred.await(started); - yield* TestClock.adjust("5 seconds"); - yield* Fiber.join(registration); - - assert.deepEqual( - run.commands.map(({ command }) => command), - ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"], - ); - // Without a forced kill, releasing a helper that ignores SIGTERM after - // the timeout would still wait for it to exit. - assert.equal(iconCacheOptions[0]?.forceKillAfter, "1 second"); - }).pipe(Effect.scoped), - ); }); diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts index 08cd1d47c08dc..dd38acbc3894e 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts @@ -12,12 +12,7 @@ import * as DesktopAssets from "./DesktopAssets.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import { makeComponentLogger } from "./DesktopObservability.ts"; -// Linux ships as an AppImage, so the .desktop entry users end up with is -// created by whatever integration tool they use (AppImageLauncher names it -// appimagekit_-….desktop) and its filename is not under our control. -// Electron's app.setAsDefaultProtocolClient resolves the desktop id from -// setDesktopName, which cannot match those files — so the browser keeps -// prompting "Choose an application" for every OAuth callback. +// AppImage integrators choose the .desktop filename, so setDesktopName cannot identify it for protocol registration. const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler"); export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError()( @@ -62,9 +57,7 @@ const escapeDesktopEntryString = (value: string): string => .replaceAll("\r", "\\r") .replaceAll("\t", "\\t"); -// Exec values are unescaped twice by implementations: first the general -// string-value rules, then the Exec quoting rules — so writing composes the -// layers in reverse. +// Exec values undergo general unescaping then Exec unquoting; escape in reverse order. export function escapeDesktopEntryExecArgument(value: string): string { const quoted = value .replaceAll("\\", () => "\\\\") @@ -75,6 +68,12 @@ export function escapeDesktopEntryExecArgument(value: string): string { return escapeDesktopEntryString(`"${quoted}"`); } +// Legacy xdg-open looks up the first Exec word without unquoting it. +const escapeUrlHandlerExecTarget = (value: string): string => + /[ \t\n"'\\><~|&;$*?#()`]/.test(value) + ? escapeDesktopEntryExecArgument(value) + : escapeDesktopEntryString(value.replaceAll("%", "%%")); + // The AppImage integration entry owns the window identity. This // hidden URL-only entry must not compete with it for StartupWMClass matching. export function renderUrlHandlerDesktopEntry(input: { @@ -87,7 +86,7 @@ export function renderUrlHandlerDesktopEntry(input: { "[Desktop Entry]", "Type=Application", `Name=${escapeDesktopEntryString(input.displayName)}`, - `Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`, + `Exec=${escapeUrlHandlerExecTarget(input.execTarget)} %U`, ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]), "Terminal=false", "NoDisplay=true", @@ -97,9 +96,7 @@ export function renderUrlHandlerDesktopEntry(input: { ].join("\n"); } -// Some docks and bars look the Wayland app id up in the icon theme when no -// visible desktop entry matches the window, for example an AppImage run without -// integration. Theme lookups are case-sensitive, so install both spellings. +// Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive. const LINUX_THEME_ICON_SIZE = "256x256"; function linuxThemeIconNames(desktopEntryName: string): readonly string[] { @@ -117,7 +114,7 @@ export class DesktopLinuxUrlHandler extends Context.Service< } >()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; @@ -135,17 +132,21 @@ export const make = Effect.gen(function* () { const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps"); const writeDesktopEntry = Effect.gen(function* () { + // Distribution packages that run on a shared Electron set + // T3CODE_DESKTOP_LAUNCHER_PATH, because process.execPath is that Electron. // Inside the mounted AppImage, process.execPath points at a transient // /tmp/.mount_* path — the handler must launch the AppImage itself. - const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath); + const execTarget = environment.desktopLauncherPath.pipe( + Option.orElse(() => environment.appImagePath), + Option.getOrElse(() => process.execPath), + ); const content = renderUrlHandlerDesktopEntry({ displayName: environment.displayName, execTarget, scheme, ...(environment.isPackaged ? { iconPath } : {}), }); - // Pre-ready setup normally wrote this already. Avoid truncating a valid - // entry while the portal may be reading it during startup. + // Avoid truncating the pre-ready entry while the portal may be reading it. const existing = yield* fileSystem .readFileString(desktopEntryPath) .pipe(Effect.orElseSucceed(() => null)); @@ -229,10 +230,8 @@ export const make = Effect.gen(function* () { yield* fileSystem.writeFile(target, icon); changed = true; } - // Only keep an existing cache current. Creating one would leave GTK reading - // a cache that other tools installing user icons do not update. An icon - // newer than the cache also retries a refresh that failed on an earlier - // launch. + // Creating a cache would leave GTK reading stale icons from other installers. + // A newer icon retries a refresh that failed on an earlier launch. const cachePath = environment.path.join(hicolorDir, "icon-theme.cache"); const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option); if (Option.isNone(cachedAt)) return; @@ -307,10 +306,7 @@ export const make = Effect.gen(function* () { yield* installThemeIcons; yield* updateDesktopDatabase.pipe( - // Some MIME implementations, including GIO, use mimeinfo.cache to verify - // that a desktop entry is associated with a scheme. Cache refresh is - // independently best-effort so a missing update-desktop-database executable - // does not prevent xdg-mime from recording the requested default. + // GIO verifies scheme associations through mimeinfo.cache. A missing cache updater must not block xdg-mime. Effect.catch((error) => logWarning("desktop MIME cache refresh failed", { applicationsDir: environment.linuxApplicationsDir, diff --git a/apps/desktop/src/app/DesktopObservability.test.ts b/apps/desktop/src/app/DesktopObservability.test.ts index ef462f19a29b0..6ddb31cb6eaac 100644 --- a/apps/desktop/src/app/DesktopObservability.test.ts +++ b/apps/desktop/src/app/DesktopObservability.test.ts @@ -1,4 +1,5 @@ import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import desktopPackageJson from "../../package.json" with { type: "json" }; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -118,76 +119,6 @@ const writeObservabilitySettings = Effect.fn(function* ( }); describe("DesktopObservability", () => { - it("advances a retained output offset instead of repeatedly copying a full head chunk", () => { - const maxBufferedBytes = 1024 * 1024; - const initial = DesktopObservability.appendBoundedOutputChunk( - { - runId: "test-run", - startDetails: "pid=123", - chunks: [], - byteLength: 0, - }, - "stderr", - new Uint8Array(maxBufferedBytes), - ); - const initialBackingBuffer = initial.chunks[0]?.chunk.buffer; - - const next = DesktopObservability.appendBoundedOutputChunk(initial, "stderr", Uint8Array.of(1)); - - assert.equal(next.chunks[0]?.chunk.buffer, initialBackingBuffer); - assert.equal(next.chunks[0]?.offset, 1); - assert.equal(next.byteLength, maxBufferedBytes); - }); - - it.effect("persists desktop Effect logs as span events in desktop.trace.ndjson", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir); - const tracePath = yield* Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - return environment.path.join(environment.logDir, "desktop.trace.ndjson"); - }).pipe(Effect.provide(layerEnvironment)); - const logPath = yield* Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - return environment.path.join(environment.logDir, "desktop-main.log"); - }).pipe(Effect.provide(layerEnvironment)); - - yield* Effect.scoped( - Effect.gen(function* () { - yield* Effect.annotateCurrentSpan({ "desktop.test": true }); - yield* Effect.logInfo("desktop trace event"); - }).pipe( - Effect.withSpan("desktop-observability-test"), - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - const records = (yield* fileSystem.readFileString(tracePath)) - .trim() - .split("\n") - .filter((line) => line.length > 0) - .map((line) => decodeTraceRecordLine(line)); - const record = records.find((entry) => entry.name === "desktop-observability-test"); - - assert.notEqual(record, undefined); - if (!record) { - return; - } - assert.equal(record.attributes["desktop.test"], true); - assert.equal( - record.events.some((event) => event.name === "desktop trace event"), - true, - ); - assert.isFalse(yield* fileSystem.exists(logPath)); - }).pipe( - Effect.scoped, - Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)), - ), - ); - it.effect("buffers backend child output and persists it only when a failure is reported", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -350,189 +281,22 @@ describe("DesktopObservability", () => { ), ); - it.effect("bounds the number of retained backend child output chunks", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-output-chunks-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir, false); - const logPath = yield* Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - return environment.path.join(environment.logDir, "server-child.log"); - }).pipe(Effect.provide(layerEnvironment)); - - yield* Effect.scoped( - Effect.gen(function* () { - const factory = yield* DesktopObservability.DesktopBackendOutputLogFactory; - const outputLog = yield* factory.forInstance("primary"); - yield* outputLog.beginSession({ details: "pid=123" }); - for (let index = 0; index < 300; index += 1) { - yield* outputLog.writeOutputChunk("stderr", Uint8Array.of(index % 128)); - } - yield* outputLog.persistFailure({ details: "code=1" }); - }).pipe( - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - const lines = (yield* fileSystem.readFileString(logPath)).trimEnd().split("\n"); - assert.equal(lines.length, 258); - }).pipe( - Effect.scoped, - Effect.provide(Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, layerEmptyEnv)), - ), - ); - - it.effect("exports main process log records to the configured logs endpoint", () => { - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir, true, { - T3CODE_OTLP_LOGS_URL: "https://collector.example.com/v1/logs", - T3CODE_OTLP_HEADERS: "x-scope=desktop", - }); - const tracePath = yield* Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - return environment.path.join(environment.logDir, "desktop.trace.ndjson"); - }).pipe(Effect.provide(layerEnvironment)); - - yield* Effect.scoped( - Effect.logInfo("desktop log export").pipe( - Effect.withSpan("desktop-log-export-test"), - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - assert.lengthOf(requests, 1); - const [request] = requests; - assert.strictEqual(request?.url, "https://collector.example.com/v1/logs"); - assert.include(request?.body ?? "", "desktop log export"); - assert.include(request?.body ?? "", "service.runtime"); - assert.strictEqual(request?.headers["x-scope"], "desktop"); - - const record = (yield* fileSystem.readFileString(tracePath)) - .trim() - .split("\n") - .filter((line) => line.length > 0) - .map((line) => decodeTraceRecordLine(line)) - .find((entry) => entry.name === "desktop-log-export-test"); - assert.notEqual(record, undefined); - assert.lengthOf(record?.events ?? [], 0); - }).pipe( - Effect.scoped, - Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)), - ); - }); - - it.effect("exports to an OTEL endpoint over Settings, with its own headers and protocol", () => { - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir, true, { - T3CODE_OTLP_HEADERS: "x-scope=desktop", - }); - yield* writeObservabilitySettings(layerEnvironment, { - otlpLogsUrl: "https://settings.example.com/v1/logs", - }); - - yield* Effect.scoped( - Effect.logInfo("desktop otel export").pipe( - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - assert.lengthOf(requests, 1); - const [request] = requests; - assert.strictEqual(request?.url, "https://collector.example.com/v1/logs"); - assert.strictEqual(request?.headers["x-otel"], "desktop"); - assert.strictEqual(request?.headers["x-scope"], undefined); - assert.strictEqual(request?.headers["content-type"], "application/json"); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - layerCollector(requests), - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - OTEL_EXPORTER_OTLP_ENDPOINT: "https://collector.example.com", - OTEL_EXPORTER_OTLP_HEADERS: "x-otel=desktop", - OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "http/json", - }, - }), - ), - ), - ), - ); - }); - - it.effect("keeps its service name while OTEL resource attributes add dimensions", () => { - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir, true, { - T3CODE_OTLP_LOGS_URL: "https://collector.example.com/v1/logs", - }); - - yield* Effect.scoped( - Effect.logInfo("desktop service name").pipe( - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - assert.lengthOf(requests, 1); - const body = requests[0]?.body ?? ""; - assert.include(body, '"stringValue":"t3code-desktop"'); - assert.include(body, "deployment.environment.name"); - assert.include(body, '"key":"service.namespace","value":{"stringValue":"t3code"}'); - assert.notInclude(body, "renamed"); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - layerCollector(requests), - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - OTEL_SERVICE_NAME: "renamed", - OTEL_RESOURCE_ATTRIBUTES: - "service.name=renamed,service.namespace=renamed,deployment.environment.name=development", - }, - }), - ), - ), - ), - ); - }); - - it.effect("exports nothing to Settings for logs an unusable OTEL endpoint claimed", () => { + it.effect("stops every export when the OpenTelemetry SDK is disabled", () => { const requests: Array = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-observability-test-", }); - const layerEnvironment = layerEnvironmentFor(baseDir, true, { - T3CODE_OTLP_HEADERS: "x-scope=desktop", - }); + const layerEnvironment = layerEnvironmentFor(baseDir); yield* writeObservabilitySettings(layerEnvironment, { + otlpTracesUrl: "https://settings.example.com/v1/traces", otlpLogsUrl: "https://settings.example.com/v1/logs", }); yield* Effect.scoped( - Effect.logInfo("desktop otel off").pipe( + Effect.logInfo("desktop log stays local when disabled").pipe( + Effect.withSpan("desktop-disabled-test"), Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), ), ); @@ -544,50 +308,13 @@ describe("DesktopObservability", () => { Layer.mergeAll( NodeServices.layer, layerCollector(requests), - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - OTEL_EXPORTER_OTLP_ENDPOINT: "https://collector.example.com", - OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "grpc", - }, - }), - ), - ), - ), - ); - }); - - it.effect("exports kill switch warnings through the configured logger", () => { - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir, true, { - T3CODE_OTLP_LOGS_URL: "https://collector.example.com/v1/logs", - }); - - yield* Effect.scoped( - Effect.void.pipe( - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - assert.include(requests[0]?.body ?? "", "OTEL_SDK_DISABLED=1 was read as false"); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - layerCollector(requests), - ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "1" } })), + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })), ), ), ); }); - it.effect("reads every signal endpoint from Settings when the environment names none", () => { + it.effect("reports the app's own version for an unpackaged desktop run", () => { const requests: Array = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -596,90 +323,23 @@ describe("DesktopObservability", () => { }); const layerEnvironment = layerEnvironmentFor(baseDir); yield* writeObservabilitySettings(layerEnvironment, { - otlpTracesUrl: "https://settings.example.com/v1/traces", otlpLogsUrl: "https://settings.example.com/v1/logs", - otlpMetricsUrl: "https://settings.example.com/v1/metrics", }); yield* Effect.scoped( - Effect.logInfo("desktop log export from settings").pipe( - Effect.withSpan("desktop-settings-export-test"), + Effect.logInfo("desktop resource under test").pipe( Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), ), ); - assert.deepEqual(requests.map((request) => request.url).toSorted(), [ - "https://settings.example.com/v1/logs", - "https://settings.example.com/v1/traces", - ]); - assert.include( - requests.find((request) => request.url.endsWith("/v1/logs"))?.body ?? "", - "desktop log export from settings", - ); + const body = requests.map((request) => request.body).join("\n"); assert.include( - requests.find((request) => request.url.endsWith("/v1/traces"))?.body ?? "", - "desktop-settings-export-test", + body, + `"key":"service.version","value":{"stringValue":"${desktopPackageJson.version}"}`, ); }).pipe( Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)), ); }); - - it.effect("stays off the network when no endpoint is configured", () => { - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - - yield* Effect.scoped( - Effect.logInfo("desktop log stays local").pipe( - Effect.withSpan("desktop-offline-test"), - Effect.provide( - DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironmentFor(baseDir))), - ), - ), - ); - - assert.lengthOf(requests, 0); - }).pipe( - Effect.scoped, - Effect.provide(Layer.mergeAll(NodeServices.layer, layerCollector(requests), layerEmptyEnv)), - ); - }); - - it.effect("stops every export when the OpenTelemetry SDK is disabled", () => { - const requests: Array = []; - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-observability-test-", - }); - const layerEnvironment = layerEnvironmentFor(baseDir); - yield* writeObservabilitySettings(layerEnvironment, { - otlpTracesUrl: "https://settings.example.com/v1/traces", - otlpLogsUrl: "https://settings.example.com/v1/logs", - }); - - yield* Effect.scoped( - Effect.logInfo("desktop log stays local when disabled").pipe( - Effect.withSpan("desktop-disabled-test"), - Effect.provide(DesktopObservability.layer.pipe(Layer.provideMerge(layerEnvironment))), - ), - ); - - assert.lengthOf(requests, 0); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - layerCollector(requests), - ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })), - ), - ), - ); - }); }); diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts index 299db7019dd7a..6baf2c4117f9d 100644 --- a/apps/desktop/src/app/DesktopObservability.ts +++ b/apps/desktop/src/app/DesktopObservability.ts @@ -29,6 +29,8 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import * as Tracer from "effect/Tracer"; import { OtlpExporter, OtlpLogger, OtlpTracer } from "effect/observability"; +import desktopPackageJson from "../../package.json" with { type: "json" }; + import * as DesktopEnvironment from "./DesktopEnvironment.ts"; const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024; @@ -150,7 +152,7 @@ interface BackendOutputSession { readonly byteLength: number; } -export function appendBoundedOutputChunk( +function appendBoundedOutputChunk( session: BackendOutputSession, streamName: "stdout" | "stderr", chunk: Uint8Array, @@ -366,19 +368,19 @@ const resolveOtlpEndpoints = Effect.gen(function* () { otel, "traces", { url: Option.getOrUndefined(environment.otlpTracesUrl), export: signalExport }, - persisted.otlpTracesUrl, + { bootstrapUrl: undefined, settingsUrl: persisted.otlpTracesUrl }, ), metrics: OtelEnvironment.resolveSignalEndpoint( otel, "metrics", { url: Option.getOrUndefined(environment.otlpMetricsUrl), export: signalExport }, - persisted.otlpMetricsUrl, + { bootstrapUrl: undefined, settingsUrl: persisted.otlpMetricsUrl }, ), logs: OtelEnvironment.resolveSignalEndpoint( otel, "logs", { url: Option.getOrUndefined(environment.otlpLogsUrl), export: signalExport }, - persisted.otlpLogsUrl, + { bootstrapUrl: undefined, settingsUrl: persisted.otlpLogsUrl }, ), warnings: otel.warnings, resourceAttributes: otel.resourceAttributes, @@ -426,8 +428,7 @@ const backendLogFilePathForInstance = ( environment: DesktopEnvironment.DesktopEnvironment["Service"], id: string, ): string => { - // Primary keeps the historical "server-child.log" path so ops scripts - // and packaged-build log inspection still find it where it always lived. + // Keep the primary log path stable for ops scripts and packaged-build inspection. if (id === PRIMARY_BACKEND_LOG_INSTANCE_ID) { return environment.path.join(environment.logDir, "server-child.log"); } @@ -435,8 +436,7 @@ const backendLogFilePathForInstance = ( return environment.path.join(environment.logDir, `server-child-${sanitized}.log`); }; -// Cacheable by resolved file path so two ids that sanitize to the same filename -// share a single RotatingLogFileWriter (no race on currentSize tracking). +// IDs sharing a sanitized filename must share a writer to avoid currentSize races. const makeBackendOutputSinkForInstance = ( environment: DesktopEnvironment.DesktopEnvironment["Service"], id: string, @@ -597,7 +597,8 @@ const layerTelemetry = Layer.unwrap( const endpoints = yield* resolveOtlpEndpoints; const resource = { serviceName: "t3code-desktop", - serviceVersion: environment.appVersion, + // Unpackaged runs launch a script, so Electron reports its own version. + serviceVersion: environment.isPackaged ? environment.appVersion : desktopPackageJson.version, attributes: { "service.namespace": "t3code", "service.runtime": "desktop", @@ -606,16 +607,7 @@ const layerTelemetry = Layer.unwrap( }, }; - // `Logger.layer` writes the whole logger set rather than adding to it, so - // every logger the main process wants has to be named in this one call. - // Splitting the OTLP logger back out into a layer of its own silently - // drops either it or the console output. - // Swapping `Logger.tracerLogger` out for the OTLP logger matches the - // server: both reach a collector, but the tracer logger covers only - // messages logged inside a recorded span and files them under traces, - // while the OTLP logger carries every message as a log record stamped - // with its trace and span ids. Keeping both would export every in-span - // message twice. + // Logger.layer replaces the logger set. tracerLogger would duplicate OTLP in-span messages. const layerLogger = Logger.layer( endpoints.logs === undefined ? [Logger.consolePretty(), Logger.tracerLogger] diff --git a/apps/desktop/src/app/DesktopPreReadyFileSystem.test.ts b/apps/desktop/src/app/DesktopPreReadyFileSystem.test.ts index 542f6b9875943..e76c29eee1e2c 100644 --- a/apps/desktop/src/app/DesktopPreReadyFileSystem.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyFileSystem.test.ts @@ -4,7 +4,6 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; import * as DesktopPreReadyFileSystem from "./DesktopPreReadyFileSystem.ts"; import * as DesktopUserData from "./DesktopUserData.ts"; @@ -17,21 +16,6 @@ const resolveWindowsUserData = (appDataDirectory: string) => }).pipe(Effect.provide(DesktopPreReadyFileSystem.layer)); it.layer(NodeServices.layer)("DesktopPreReadyFileSystem", (it) => { - it.effect("migrates the legacy Windows profile state", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-pre-ready-fs-" }); - yield* fileSystem.makeDirectory(path.join(root, "T3 Code (Alpha)")); - yield* fileSystem.writeFileString(path.join(root, "T3 Code (Alpha)", "Local State"), "keys"); - - const userData = yield* resolveWindowsUserData(root); - - assert.equal(userData, path.join(root, "t3code-v2")); - assert.equal(yield* fileSystem.readFileString(path.join(userData, "Local State")), "keys"); - }), - ); - it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32" || process.getuid?.() === 0)( "fails instead of treating an unreadable profile as missing", () => diff --git a/apps/desktop/src/app/DesktopPreReadyFileSystem.ts b/apps/desktop/src/app/DesktopPreReadyFileSystem.ts index 5af13f94413f5..6a7473e2f1b1a 100644 --- a/apps/desktop/src/app/DesktopPreReadyFileSystem.ts +++ b/apps/desktop/src/app/DesktopPreReadyFileSystem.ts @@ -32,9 +32,7 @@ const syncFs = (method: string, path: string, run: () => A) => }), }); -/** - * @public Service construction is part of the canonical Effect module API. - */ +/** @public */ export const make = FileSystem.makeNoop({ exists: (path) => syncFs("exists", path, () => { diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index dd15f879fd8ee..f2b176ee3761f 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -15,6 +15,7 @@ const { writeFileSyncMock, copyFileSyncMock, execFileSyncMock, + readFileSyncMock, } = vi.hoisted(() => ({ appendSwitchMock: vi.fn(), getSwitchValueMock: vi.fn(), @@ -25,6 +26,7 @@ const { writeFileSyncMock: vi.fn(), copyFileSyncMock: vi.fn(), execFileSyncMock: vi.fn(), + readFileSyncMock: vi.fn(), })); vi.mock("electron", () => ({ @@ -45,7 +47,7 @@ vi.mock("electron", () => ({ })); vi.mock("node:fs", () => ({ - readFileSync: () => "{}", + readFileSync: readFileSyncMock, mkdirSync: mkdirSyncMock, writeFileSync: writeFileSyncMock, copyFileSync: copyFileSyncMock, @@ -68,73 +70,51 @@ describe("DesktopPreReadyPlatform", () => { writeFileSyncMock.mockReset(); copyFileSyncMock.mockReset(); execFileSyncMock.mockReset(); + readFileSyncMock.mockReset().mockReturnValue("{}"); }); - it.effect("preserves an explicit Linux password-store switch", () => { - hasSwitchMock.mockImplementation((switchName) => switchName === "password-store"); - getSwitchValueMock.mockReturnValue(" basic "); + it.effect("persists Linux scaling synchronously across relaunches and settings rewrites", () => { + vi.stubEnv("T3CODE_HOME", "/isolated"); + vi.stubEnv("VITE_DEV_SERVER_URL", ""); + const settingsPath = "/isolated/userdata/desktop-settings.json"; + const files = new Map([[settingsPath, "{}"]]); + const commandLine = new Map(); + readFileSyncMock.mockImplementation((path: string) => { + const contents = files.get(path); + if (contents === undefined) throw new Error("ENOENT"); + return contents; + }); + writeFileSyncMock.mockImplementation((path: string, contents: string) => { + files.set(path, contents); + }); + hasSwitchMock.mockImplementation((name: string) => commandLine.has(name)); + getSwitchValueMock.mockImplementation((name: string) => commandLine.get(name) ?? ""); + appendSwitchMock.mockImplementation((name: string, value: string) => { + commandLine.set(name, value); + }); + const launch = Effect.gen(function* () { + const startup = Promise.resolve().then(() => commandLine.get("force-device-scale-factor")); + yield* DesktopPreReadyPlatform.make; + return yield* Effect.promise(() => startup); + }); return Effect.gen(function* () { - const options = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions; + for (const explicitScale of ["1.75", "1"]) { + commandLine.clear(); + commandLine.set("force-device-scale-factor", explicitScale); + appendSwitchMock.mockClear(); + assert.equal(yield* launch, explicitScale); + assert.isFalse( + appendSwitchMock.mock.calls.some(([name]) => name === "force-device-scale-factor"), + ); - assert.equal(options.linuxPasswordStoreCommandLine, "basic"); - assert.isFalse(appendSwitchMock.mock.calls.some(([name]) => name === "password-store")); + // The settings service discards fields it does not own when rewriting its document. + files.set(settingsPath, JSON.stringify({ linuxPasswordStore: "basic" })); + commandLine.clear(); + assert.equal(yield* launch, explicitScale); + } }).pipe( - Effect.provide( - DesktopPreReadyPlatform.layer.pipe( - Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), - ), - ), - ); - }); - - it.effect.each([ - { - label: "merges the color-manager fallback into disabled features on Hyprland 0.48.1", - switches: { "ozone-platform": "wayland", "disable-features": "Vulkan" }, - hyprlandVersion: "0.48.1", - hyprlandCommit: "29e2e59fdbab8ed2cc23a20e3c6043d5decb5cdc", - expected: [["disable-features", "Vulkan,WaylandWpColorManagerV1"]], - }, - { - label: "preserves color management on Hyprland 0.51.0", - switches: { "ozone-platform": "wayland", "disable-features": "Vulkan" }, - hyprlandVersion: "0.51.0", - hyprlandCommit: "0123456789abcdef0123456789abcdef01234567", - expected: [], - }, - { - label: "preserves color management when Electron resolved X11", - switches: { "ozone-platform": "x11", "disable-features": "Vulkan" }, - hyprlandVersion: "0.48.1", - hyprlandCommit: "29e2e59fdbab8ed2cc23a20e3c6043d5decb5cdc", - expected: [], - }, - ])("$label", ({ switches, hyprlandVersion, hyprlandCommit, expected }) => { - vi.stubEnv("XDG_CURRENT_DESKTOP", "Hyprland"); - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - const commandLine = new Map(Object.entries(switches)); - hasSwitchMock.mockImplementation((switchName: string) => commandLine.has(switchName)); - getSwitchValueMock.mockImplementation( - (switchName: string) => commandLine.get(switchName) ?? "", - ); - execFileSyncMock.mockReturnValue( - JSON.stringify({ - commit: hyprlandCommit, - version: hyprlandVersion, - dirty: false, - tag: `v${hyprlandVersion}`, - }), - ); - - return DesktopPreReadyPlatform.make.pipe( Effect.provideService(HostProcess.Platform, "linux"), - Effect.map(() => { - const featureSwitches = appendSwitchMock.mock.calls.filter(([name]) => - ["disable-features", "enable-features", "ozone-platform"].includes(name), - ); - assert.deepEqual(featureSwitches, expected); - }), Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), ); }); @@ -174,7 +154,7 @@ describe("DesktopPreReadyPlatform", () => { ); const identity = yield* Effect.promise(() => portalIdentity); assert.equal(identity.desktopName, "com.t3tools.T3Code.desktop"); - assert.include(identity.desktopEntry ?? "", 'Exec="/Applications/current.AppImage" %U'); + assert.include(identity.desktopEntry ?? "", "Exec=/Applications/current.AppImage %U"); assert.include(identity.desktopEntry ?? "", "Name=T3 Code (Beta)"); assert.include(identity.desktopEntry ?? "", "MimeType=x-scheme-handler/t3code;"); assert.include( @@ -186,30 +166,26 @@ describe("DesktopPreReadyPlatform", () => { ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); }); - it.effect("keeps startup available when the early desktop entry cannot be written", () => { + it.effect("points the early portal entry at a configured distribution launcher", () => { + vi.stubEnv("VITE_DEV_SERVER_URL", ""); + vi.stubEnv("XDG_DATA_HOME", "/xdg"); + vi.stubEnv("APPIMAGE", "/Applications/current.AppImage"); + vi.stubEnv("T3CODE_DESKTOP_LAUNCHER_PATH", " /opt/T3 Code/t3code "); getSwitchValueMock.mockReturnValue(""); - mkdirSyncMock.mockImplementation(() => { - throw new Error("read-only filesystem"); - }); - return DesktopPreReadyPlatform.make.pipe( - Effect.provideService(HostProcess.Platform, "linux"), - Effect.asVoid, - ); - }); - - it.effect("still prepares the portal entry when the bundled icon cannot be copied", () => { - getSwitchValueMock.mockReturnValue(""); - copyFileSyncMock.mockImplementation(() => { - throw new Error("missing bundled icon"); - }); - return Effect.gen(function* () { - yield* DesktopPreReadyPlatform.make; - const contents = writeFileSyncMock.mock.calls[0]?.[1]; - assert.include(contents, "MimeType=x-scheme-handler/t3code;"); - assert.include(contents, "Icon="); - assert.equal(setDesktopNameMock.mock.calls.length, 1); - }).pipe(Effect.provideService(HostProcess.Platform, "linux")); + return Effect.scoped( + Effect.gen(function* () { + yield* Layer.build( + DesktopPreReadyPlatform.layer.pipe( + Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + ), + ); + const entry = writeFileSyncMock.mock.calls.find( + ([path]) => path === "/xdg/applications/com.t3tools.T3Code.desktop", + )?.[1]; + assert.include(entry, 'Exec="/opt/T3 Code/t3code" %U'); + }), + ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); }); it.effect( diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index a90246c73b3b7..8bef7366e378a 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -49,7 +49,7 @@ export class DesktopPreReadyElectronOptions extends Context.Service< } >()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const homeDirectory = yield* HostProcess.HomeDirectory; @@ -62,6 +62,17 @@ export const make = Effect.gen(function* () { platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess(homeDirectory) : null; if (linux !== null) { + DesktopEarlyElectronStartup.restoreEarlyLinuxDeviceScaleFactor({ + env: process.env, + homeDirectory, + joinPath: NodePath.posix.join, + commandLine: Electron.app.commandLine, + readFileString: (path) => NodeFS.readFileSync(path, "utf8"), + writeFileString: (path, value) => { + NodeFS.mkdirSync(NodePath.posix.dirname(path), { recursive: true }); + NodeFS.writeFileSync(path, value, "utf8"); + }, + }); // The portal also requires a valid desktop entry. An AppImage update may // have removed the executable referenced by the previous launch's entry. try { @@ -98,15 +109,17 @@ export const make = Effect.gen(function* () { isDevelopment: linux.isDevelopment, appVersion: Electron.app.getVersion(), }).displayName, - execTarget: process.env.APPIMAGE?.trim() || process.execPath, + execTarget: + process.env.T3CODE_DESKTOP_LAUNCHER_PATH?.trim() || + process.env.APPIMAGE?.trim() || + process.execPath, scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment), ...(iconPath === undefined ? {} : { iconPath }), }), "utf8", ); } catch {} - // Chromium caches its portal registration during startup. Set the identity - // before any asynchronous work can initialize it with Electron's default. + // Chromium caches portal identity; set it before any asynchronous initialization. Electron.app.setDesktopName(linux.linuxDesktopEntryName); Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass); if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) { @@ -135,8 +148,7 @@ export const make = Effect.gen(function* () { }); }).pipe(Effect.withSpan("desktop.electron.configureBeforeReady")); -// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot -// observe app readiness before scheme privileges and command-line switches exist. +// Complete scheme privileges and switches before later layers can observe app readiness. export const layer = Layer.mergeAll( ElectronProtocol.layerSchemePrivileges, Layer.effect(DesktopPreReadyElectronOptions, make), diff --git a/apps/desktop/src/app/DesktopUserData.test.ts b/apps/desktop/src/app/DesktopUserData.test.ts index 41e497463a0d7..78bab4085627b 100644 --- a/apps/desktop/src/app/DesktopUserData.test.ts +++ b/apps/desktop/src/app/DesktopUserData.test.ts @@ -3,40 +3,9 @@ import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; import { resolveUserDataPath } from "./DesktopUserData.ts"; -it.effect("identifies a failed source read and preserves its cause", () => { - const sourceState = "/profiles/t3code/Local State"; - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFileString", - pathOrDescriptor: sourceState, - }); - return Effect.gen(function* () { - const error = yield* resolveUserDataPath({ - appDataDirectory: "/profiles", - isDevelopment: false, - platform: "win32", - }).pipe(Effect.flip); - assert.equal(error.operation, "read"); - assert.equal(error.resourcePath, sourceState); - assert.equal(error.category, "PermissionDenied"); - assert.strictEqual(error.cause, cause); - }).pipe( - Effect.provideService( - FileSystem.FileSystem, - FileSystem.makeNoop({ - exists: (path) => Effect.succeed(path === sourceState), - readFileString: () => Effect.fail(cause), - }), - ), - Effect.provide(NodeServices.layer), - ); -}); - it.effect.each(["t3code", "T3 Code (Alpha)"])( "preserves Windows credential keys from %s without copying browser databases", (sourceName) => diff --git a/apps/desktop/src/app/DesktopWebLinks.test.ts b/apps/desktop/src/app/DesktopWebLinks.test.ts index 8c97b5fe83561..9e87cfb7a9c02 100644 --- a/apps/desktop/src/app/DesktopWebLinks.test.ts +++ b/apps/desktop/src/app/DesktopWebLinks.test.ts @@ -36,22 +36,6 @@ const makeWindow = () => { }; describe("DesktopWebLinks", () => { - it("treats only http and https as web links", () => { - assert.isTrue(DesktopWebLinks.isWebLink("https://example.com/")); - assert.isTrue(DesktopWebLinks.isWebLink("http://localhost:3000/a?b=1")); - assert.isFalse(DesktopWebLinks.isWebLink("t3code://app/welcome")); - assert.isFalse(DesktopWebLinks.isWebLink("mailto:hello@example.com")); - assert.isFalse(DesktopWebLinks.isWebLink("not a url")); - }); - - it("opens HTML files the way a browser does, and nothing else by path", () => { - assert.isTrue(DesktopWebLinks.isWebPageFile("/Users/me/report.html")); - assert.isTrue(DesktopWebLinks.isWebPageFile("/tmp/page.HTM")); - assert.isTrue(DesktopWebLinks.isWebPageFile("/tmp/page.xhtml")); - assert.isFalse(DesktopWebLinks.isWebPageFile("/tmp/notes.md")); - assert.isFalse(DesktopWebLinks.isWebPageFile("/tmp/html")); - }); - it.effect("holds links until the renderer listens, then delivers them in order", () => { const { sent, revealed, layer } = makeWindow(); return Effect.gen(function* () { diff --git a/apps/desktop/src/app/chromiumLocalStorage.ts b/apps/desktop/src/app/chromiumLocalStorage.ts index 98de2e91eb063..51beceb9e463f 100644 --- a/apps/desktop/src/app/chromiumLocalStorage.ts +++ b/apps/desktop/src/app/chromiumLocalStorage.ts @@ -4,12 +4,7 @@ import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; -/** - * It reads the database files directly and never takes LevelDB's lock, so it - * works while another app version has the profile open. Live files come from - * the MANIFEST that CURRENT names, and the newest sequence number wins, which - * is how LevelDB itself resolves overwrites and deletions. - */ +/** Read without LevelDB's lock so another app can keep the profile open. */ const LOG_BLOCK_SIZE = 32 * 1024; const LOG_HEADER_SIZE = 7; @@ -145,11 +140,7 @@ function decompressSnappy(input: Uint8Array): Uint8Array { return output; } -/** - * Like LevelDB's own reader, a corrupt record or zero padding skips the rest of - * its block, since a reused log keeps appending after a torn write, and a - * record cut off by the end of the file ends the log. - */ +/** Corruption skips the remaining block; a truncated final record ends the log, matching LevelDB recovery. */ function readLogRecords(bytes: Uint8Array): Uint8Array[] { const records: Uint8Array[] = []; let pending: Uint8Array[] | null = null; @@ -422,9 +413,7 @@ export const readChromiumLocalStorage = Effect.fn("desktop.chromiumLocalStorage. }).pipe(wrap); } - // A flush while another process has the database open can move entries - // from a log we read into a table our MANIFEST copy predates. Fail so the - // caller retries rather than import a snapshot missing those entries. + // Concurrent flushes can move entries beyond this MANIFEST snapshot; detect changes so the caller retries. const currentAfter = textDecoderUtf8.decode(yield* readFile("CURRENT").pipe(wrap)).trim(); const manifestAfter = yield* fs.stat(path.join(directory, current)).pipe(wrap); if (currentAfter !== current || Number(manifestAfter.size) !== manifest.length) { diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index c0ef57ae993ac..8d70ab4c4791f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -5,12 +5,9 @@ import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Logger from "effect/Logger"; import * as ManagedRuntime from "effect/ManagedRuntime"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; -import * as Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; @@ -22,22 +19,6 @@ import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts"; -const PersistedServerObservabilitySettingsDocument = Schema.Struct({ - observability: Schema.Struct({ - otlpTracesUrl: Schema.String, - otlpMetricsUrl: Schema.String, - otlpLogsUrl: Schema.String, - }), -}); - -const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect( - Schema.fromJsonString(PersistedServerObservabilitySettingsDocument), -); - -const isDesktopBackendObservabilitySettingsReadError = Schema.is( - DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError, -); - const layerShellEnvironment = (prepared = true) => Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, { installIntoProcess: Effect.succeed(prepared), @@ -333,44 +314,6 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("only the local primary bootstrap claims the prepared shell environment", () => - withHarness( - Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - - const primary = yield* configuration.resolvePrimary; - const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null }); - - assert.equal(primary.bootstrap.shellEnvironmentPrepared, true); - assert.isUndefined(wsl.bootstrap.shellEnvironmentPrepared); - }), - ), - ); - - it.effect("keeps server hydration enabled when desktop preparation failed", () => - withHarness( - Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const primary = yield* configuration.resolvePrimary; - assert.equal(primary.bootstrap.shellEnvironmentPrepared, false); - }), - false, - ), - ); - - it.effect("resolveWsl reuses the primary's bootstrap token", () => - withHarness( - Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - - const primary = yield* configuration.resolvePrimary; - const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null }); - - assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken); - }), - ), - ); - it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -551,6 +494,7 @@ describe("DesktopBackendConfiguration", () => { archiveHash: "b".repeat(64), wsl: () => ({ prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }), + invalidateRuntime: () => Effect.die("failed staging must not invalidate a runtime"), ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; @@ -615,42 +559,6 @@ describe("DesktopBackendConfiguration", () => { ); }); - it.effect("resolveWsl keeps the staged runtime when the mounted tree fails too", () => { - const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache"; - const invalidatedRuntimeIds: string[] = []; - return withPackagedWslHarness( - { - archiveHash: "d".repeat(64), - wsl: () => ({ - prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }), - invalidateRuntime: (_distro, runtimeId) => - Effect.sync(() => { - invalidatedRuntimeIds.push(runtimeId); - }), - probeRuntime: () => ({ - ok: false, - reason: "unsupported CPU architecture or incompatible system libraries", - }), - ensureNodePty: () => ({ - ok: false, - reason: "mounted tree is broken in some other way", - fatal: true, - }), - }), - }, - () => - Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" }); - const failure = Option.getOrThrow(config.preflightFailure); - - assert.isTrue(failure.fatal); - assert.include(failure.reason, "unsupported CPU architecture"); - assert.deepEqual(invalidatedRuntimeIds, []); - }), - ); - }); - it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => { const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache"; const invalidatedRuntimeIds: string[] = []; @@ -770,226 +678,6 @@ describe("DesktopBackendConfiguration", () => { ), ); - it.effect("resolvePrimary surfaces persisted backend observability endpoints", () => - withHarness( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - - yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), { - recursive: true, - }); - yield* fileSystem.writeFileString( - environment.serverSettingsPath, - yield* encodePersistedServerObservabilitySettingsDocument({ - observability: { - otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ", - otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ", - otlpLogsUrl: " http://127.0.0.1:4318/v1/logs ", - }, - }), - ); - - const config = yield* configuration.resolvePrimary; - assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces"); - assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics"); - assert.equal(config.bootstrap.otlpLogsUrl, "http://127.0.0.1:4318/v1/logs"); - }), - ), - ); - - it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () => - withHarness( - Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolvePrimary; - - assert.isUndefined(config.bootstrap.otlpTracesUrl); - assert.isUndefined(config.bootstrap.otlpMetricsUrl); - assert.isUndefined(config.bootstrap.otlpLogsUrl); - }), - ), - ); - - it.effect("resolveWsl carries environment-configured observability endpoints", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); - - assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces"); - assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics"); - assert.equal(config.bootstrap.otlpLogsUrl, "http://127.0.0.1:4318/v1/logs"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), - getDistroIp: () => Option.some("172.27.0.99"), - }), - ), - Layer.provideMerge( - layerEnvironment(baseDir, { - platform: "win32", - otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ", - otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ", - otlpLogsUrl: " http://127.0.0.1:4318/v1/logs ", - }), - ), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("environment observability endpoints win over the persisted settings file", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - - yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), { - recursive: true, - }); - yield* fileSystem.writeFileString( - environment.serverSettingsPath, - yield* encodePersistedServerObservabilitySettingsDocument({ - observability: { - otlpTracesUrl: "http://persisted:4318/v1/traces", - otlpMetricsUrl: "http://persisted:4318/v1/metrics", - otlpLogsUrl: "http://persisted:4318/v1/logs", - }, - }), - ); - - const config = yield* configuration.resolvePrimary; - assert.equal(config.bootstrap.otlpLogsUrl, "http://env:4318/v1/logs"); - assert.equal(config.bootstrap.otlpTracesUrl, "http://persisted:4318/v1/traces"); - assert.equal(config.bootstrap.otlpMetricsUrl, "http://persisted:4318/v1/metrics"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest()), - Layer.provideMerge( - layerEnvironment(baseDir, { otlpLogsUrl: "http://env:4318/v1/logs" }), - ), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("logs structured context when persisted observability settings cannot be read", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - const settingsPath = path.join(baseDir, "userdata", "settings.json"); - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFileString", - pathOrDescriptor: settingsPath, - }); - const messages: Array = []; - const logger = Logger.make(({ message }) => { - messages.push(message); - }); - const layerFailingFileSystem = Layer.succeed( - FileSystem.FileSystem, - FileSystem.makeNoop({ - readFileString: () => Effect.fail(cause), - }), - ); - - const config = yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - return yield* configuration.resolvePrimary; - }).pipe( - Effect.provide( - Layer.mergeAll( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest()), - Layer.provideMerge(layerEnvironment(baseDir)), - Layer.provideMerge(layerFailingFileSystem), - ), - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - ); - - assert.isUndefined(config.bootstrap.otlpTracesUrl); - assert.isUndefined(config.bootstrap.otlpMetricsUrl); - assert.isUndefined(config.bootstrap.otlpLogsUrl); - - const error = messages - .flatMap((message) => (Array.isArray(message) ? message : [message])) - .find(isDesktopBackendObservabilitySettingsReadError); - assert.isDefined(error); - assert.equal(error.settingsPath, settingsPath); - assert.equal(error.cause, cause); - assert.equal( - error.message, - `Failed to read persisted backend observability settings at ${settingsPath}.`, - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolvePrimary; - assert.equal(config.captureOutput, true); - assert.notInclude(config.args, "--require"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest()), - Layer.provideMerge( - layerEnvironment(baseDir, { - isPackaged: false, - devServerUrl: "http://127.0.0.1:5733", - }), - ), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("resolveWsl carries the kill switch into the distro", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1038,71 +726,6 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect( - "resolveWsl carries the standard OTLP endpoint, headers, and protocol into the distro", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - const standard = { - OTEL_EXPORTER_OTLP_ENDPOINT: "https://collector.example.com:4318/base?api_key=secret", - OTEL_EXPORTER_OTLP_LOGS_HEADERS: "authorization=Bearer%20token", - T3CODE_OTLP_TRACES_URL: "http://t3.example.com:4318/v1/traces", - }; - const previousWslEnv = process.env.WSLENV; - const ambientOtel = Object.entries(process.env).filter( - ([name]) => name.startsWith("OTEL_") || name.startsWith("T3CODE_OTLP_"), - ); - try { - for (const [name] of ambientOtel) delete process.env[name]; - delete process.env.WSLENV; - Object.assign(process.env, standard); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); - - assert.equal( - config.env.OTEL_EXPORTER_OTLP_ENDPOINT, - "https://collector.example.com:4318/base?api_key=secret", - ); - assert.equal( - config.env.OTEL_EXPORTER_OTLP_LOGS_HEADERS, - "authorization=Bearer%20token", - ); - const wslEnv = (config.env.WSLENV ?? "").split(":"); - assert.include(wslEnv, "OTEL_EXPORTER_OTLP_ENDPOINT"); - assert.include(wslEnv, "OTEL_EXPORTER_OTLP_LOGS_HEADERS"); - assert.equal(config.env.T3CODE_OTLP_TRACES_URL, "http://t3.example.com:4318/v1/traces"); - assert.include(wslEnv, "T3CODE_OTLP_TRACES_URL"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), - getDistroIp: () => Option.some("172.27.0.99"), - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), - ), - ), - ); - } finally { - for (const name of Object.keys(standard)) delete process.env[name]; - restoreEnv("WSLENV", previousWslEnv); - for (const [name, value] of ambientOtel) restoreEnv(name, value); - } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1250,42 +873,6 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("resolveWsl keeps a transient distro-list failure retryable", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" }); - const failure = Option.getOrThrow(config.preflightFailure); - - assert.isFalse(failure.fatal); - assert.equal(failure.retryLimit, 12); - assert.include(failure.reason, "timed out"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({ - reason: "wsl.exe --list --verbose timed out", - }), - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("resolveWsl marks a missing packaged server entry as fatal", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1319,113 +906,6 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" }); - const failure = Option.getOrThrow(config.preflightFailure); - - assert.isFalse(failure.fatal); - assert.equal(failure.retryLimit, 12); - assert.include(failure.reason, "could not be extracted"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge( - DesktopWslServerTree.layerTest({ - result: { - ok: false, - reason: "WSL server files could not be extracted", - fatal: false, - }, - }), - ), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - distros: [{ name: "Ubuntu", isDefault: true, version: 2 }], - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" }); - const failure = Option.getOrThrow(config.preflightFailure); - - assert.isTrue(failure.fatal); - assert.include(failure.reason, "Removed-Distro"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - distros: [{ name: "Ubuntu", isDefault: true, version: 2 }], - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const label = yield* configuration.resolvePrimaryLabel; - assert.equal(label, "WSL (Ubuntu)"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: true, - wslOnly: true, - wslDistro: "Ubuntu", - }), - ), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("prefers the external packaged resource monitor over the copy inside the asar", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1475,93 +955,6 @@ describe("DesktopBackendConfiguration", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("prefers the release resource monitor when both development builds exist", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - const dirname = path.join(baseDir, "apps/desktop/src"); - const releaseMonitorPath = path.join( - baseDir, - "native/resource-monitor/target/release/t3-resource-monitor", - ); - const debugMonitorPath = path.join( - baseDir, - "native/resource-monitor/target/debug/t3-resource-monitor", - ); - yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true }); - yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true }); - yield* fileSystem.writeFileString(releaseMonitorPath, "release"); - yield* fileSystem.writeFileString(debugMonitorPath, "debug"); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolvePrimary; - assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest()), - Layer.provideMerge( - layerEnvironment(baseDir, { - dirname, - devServerUrl: "http://127.0.0.1:5733", - isPackaged: false, - }), - ), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () => - withHarness( - Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const label = yield* configuration.resolvePrimaryLabel; - assert.equal(label, "Local environment"); - }), - ), - ); - - it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-backend-config-test-", - }); - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const label = yield* configuration.resolvePrimaryLabel; - assert.equal(label, "Windows"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: true, - wslOnly: true, - wslDistro: "Ubuntu", - }), - ), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), - ), - ), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => { // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it. const runtime = ManagedRuntime.make( diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index d9ff98279718f..06b4c6b59816d 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -81,8 +81,7 @@ const DESKTOP_BACKEND_ENV_NAMES = [ "T3CODE_TAILSCALE_SERVE_PORT", ] as const; -// Env vars that the WSL backend needs but Windows process.env won't forward -// across the wsl.exe boundary without WSLENV. +// Windows forwards these variables into WSL only through WSLENV. const WSL_FORWARDED_ENV_NAMES = [ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", @@ -92,9 +91,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "OTEL_SDK_DISABLED", "T3CODE_OTLP_HEADERS", "T3CODE_OTLP_PROTOCOL", - // Forwarded without a WSLENV flag, so the values arrive untranslated. The - // server prefers an OTEL endpoint over the bootstrap envelope, so the T3 URLs - // travel as variables to keep winning inside the distro as they do on Windows. + // Untranslated T3 URLs must override bootstrap endpoints inside WSL, as they do on Windows. "T3CODE_OTLP_TRACES_URL", "T3CODE_OTLP_METRICS_URL", "T3CODE_OTLP_LOGS_URL", @@ -145,10 +142,7 @@ const mergeWslEnv = ( const additions = forwardedEnvNames.filter((name) => !seenNames.has(name)); - // Preserve the user's WSLENV exactly as Windows handed it to us — empty - // "::" segments and duplicate entries are harmless no-ops to WSL and not - // ours to normalize — and only append the secrets we need to forward - // across the wsl.exe boundary. + // Preserve empty segments and duplicates in the user's WSLENV; only append required variables. const parts = [existing, ...additions].filter((part) => part.length > 0); return parts.length > 0 ? parts.join(":") : undefined; }; @@ -253,10 +247,7 @@ type WslPreflightRuntime = } | { readonly kind: "node-script"; - // Absolute path to the node binary the preflight validated after the - // shared remote resolver repaired PATH. The launch must use this exact - // path so it doesn't fall through to a different/old node than the one - // node-pty was probed with. + // Launch the exact Node path probed with node-pty, even if later PATH lookup would resolve another version. readonly nodePath: string; readonly linuxEntryPath: string; }; @@ -386,7 +377,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const); }); - let stagedFailure: { readonly runtimeId: string; readonly reason: string } | undefined; + let stagedFailure: { readonly runtimeId?: string; readonly reason: string } | undefined; const failedStaged = (failure: { readonly reason: string }) => ({ _tag: "Failed", @@ -397,8 +388,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f if (input.runtimeArchive !== null) { const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); if (runtime.ok) { - // The staged runtime supplies its own Node and node-pty. Provider PATH - // discovery must not require either dependency for runtime readiness. + // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. const stagedProbe = yield* wslEnv.probeRuntime(runningDistro, runtime.linuxAppRoot); if (stagedProbe.ok) { yield* wslServerTree.cleanupLegacy; @@ -417,6 +407,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f ); stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason }; } else { + stagedFailure = { reason: runtime.reason }; yield* Effect.logWarning( "Could not stage the WSL runtime; launching from the mounted server tree instead.", { reason: runtime.reason }, @@ -437,16 +428,13 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f nodePtyOptions, ); if (!nodePtyResult.ok) { - // Substituting the staged verdict for a transient mounted failure would - // turn a retryable failure into a fatal one, ending the WSL attempt (and, - // in wsl-only mode, persisting Windows) before the slow /mnt path had a - // chance to answer and clear the bad cache. + // Only substitute a staged failure for a fatal mounted failure; transient /mnt failures must remain retryable. return stagedFailure && nodePtyResult.fatal ? failedStaged(stagedFailure) : failedNodePty(nodePtyResult); } - if (stagedFailure) { + if (stagedFailure?.runtimeId) { yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId); } @@ -463,16 +451,12 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f } as const; }); -// In WSL2 mirrored mode the distro's eth0 IP equals the host's, which is the -// signature we use to detect that mode and switch the renderer URL to loopback. +// In WSL2 mirrored mode, eth0 matches a host IP; use loopback for the renderer. const isLocalHostIpv4 = (ip: string): boolean => { const interfaces = NodeOS.networkInterfaces(); for (const list of Object.values(interfaces)) { if (!list) continue; for (const entry of list) { - // os.networkInterfaces() reports IPv4 `family` as the string "IPv4" on - // the Node build Electron ships (41 / Node 22, verified), but some Node - // builds report the numeric 4. const family = String(entry.family); if ((family === "IPv4" || family === "4") && entry.address === ip) return true; } @@ -519,7 +503,6 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv host: backendExposure.bindHost, desktopBootstrapToken: input.bootstrapToken, desktopBootstrapSecret: input.bootstrapSecret, - // Failed Windows probes leave server hydration enabled for another attempt. shellEnvironmentPrepared: input.shellEnvironmentPrepared, tailscaleServeEnabled: backendExposure.tailscaleServeEnabled, tailscaleServePort: backendExposure.tailscaleServePort, @@ -536,10 +519,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv return { executablePath: process.execPath, - // Packaged builds only, so a dev instance never shares the cache with the - // prod app it is often run from. `--require` rather than NODE_COMPILE_CACHE, - // so the setting does not leak into the provider and terminal processes - // the backend starts. + // Packaged builds have a separate cache; --require prevents cache settings leaking to provider subprocesses. args: [ ...(environment.isPackaged ? ["--require", environment.compileCachePath] : []), environment.backendEntryPath, @@ -580,25 +560,18 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const fileSystem = yield* FileSystem.FileSystem; - // wslhost forwarding is unreliable on some Windows hosts: the desktop's - // readiness probe and the renderer's saved-env-style fetch both saw "Failed - // to fetch" when the backend only bound to 127.0.0.1 inside WSL. Binding to - // 0.0.0.0 plus advertising the WSL IP as the renderer-visible URL avoids that - // dependency. + // wslhost loopback forwarding is unreliable on some Windows hosts; advertise the WSL IP instead. const wslBindHost = "0.0.0.0"; const bootstrap = { mode: "desktop" as const, noBrowser: true, port: input.port, - // Omit t3Home so the Linux backend uses its own home dir instead of - // the Windows-side baseDir (which would be a /mnt/c path and share - // the SQLite file with the primary). + // Omit t3Home to keep the Linux backend from sharing the primary's Windows SQLite file. host: wslBindHost, desktopBootstrapToken: input.bootstrapToken, desktopBootstrapSecret: input.bootstrapSecret, - // PortSchema rejects 0, so when tailscale serve is disabled we still need a - // valid number in this slot. + // PortSchema rejects 0 even when Tailscale Serve is disabled. tailscaleServeEnabled: false, tailscaleServePort: 443, ...buildObservabilityFragment(input.observabilitySettings), @@ -639,9 +612,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl allowBuild: !environment.isPackaged, }); - // Every operation after preflight uses the same concrete distro. In - // default-tracking mode this closes the race where the system default - // changes between probing and spawning the backend. + // Pin the preflight distro so a default change cannot race backend startup. const runningDistro = preflight._tag === "Ready" ? preflight.runningDistro : null; const distroForConfig = runningDistro ?? input.distro; @@ -684,8 +655,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl ...forwardedEnv, ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}), }, - // env is already a complete process.env minus T3CODE_HOME; pass it - // verbatim instead of letting the spawner re-merge process.env on top. + // env already excludes T3CODE_HOME; merging process.env would restore it. extendEnv: false, bootstrap, bootstrapDelivery: "stdin" as const, @@ -694,8 +664,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl ...(runningDistro !== null ? { runningDistro } : {}), }; - // Forward the dev-server URL as an explicit CLI flag so the WSL backend's - // config resolution lands in dev/ instead of userdata/. + // Explicit --dev-url keeps WSL state in dev/ rather than userdata/. const devUrlArgs = Option.match(environment.devServerUrl, { onNone: () => [] as ReadonlyArray, onSome: (url) => ["--dev-url", url.href], @@ -715,10 +684,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl } satisfies DesktopBackendManager.DesktopBackendStartConfig; } - // The WSL server spawns commands its providers reference by name — `npm`/`npx` - // for provider updates, and the installed CLIs themselves (e.g. `codex`). Those - // live on the user's login-shell PATH, which `wsl.exe --exec` does NOT put on - // the process PATH, so `npm install -g ...` fails with NotFound. + // wsl.exe --exec omits the login-shell PATH needed to find provider CLIs and npm. const runtime = preflight.runtime; const launchPath = runtime.kind === "executable" @@ -746,7 +712,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl } satisfies DesktopBackendManager.DesktopBackendStartConfig; }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; @@ -756,12 +722,7 @@ export const make = Effect.gen(function* () { const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree; const settings = yield* DesktopAppSettings.DesktopAppSettings; const crypto = yield* Crypto.Crypto; - // SynchronizedRef (not a plain Ref) so the read-generate-write is atomic. - // crypto.randomBytes is a yield point, and resolvePrimary + resolveWsl can - // resolve concurrently; with a plain Ref both could observe None, generate - // distinct secrets, and one would overwrite the other — leaving the two - // backends deriving mismatched tokens and breaking the shared-token invariant - // the renderer relies on. + // Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets. const secretRef = yield* SynchronizedRef.make(Option.none()); const getOrCreateBootstrapSecret = SynchronizedRef.modifyEffect(secretRef, (current) => Option.match(current, { @@ -832,18 +793,11 @@ export const make = Effect.gen(function* () { ); }); - // Dispatch happens at resolve time so toggling wsl-only between restarts - // is picked up on the next start cycle (the pool's primary instance is - // created once at layer init, but configResolve fires on each restart). + // Resolve on each restart so toggling wsl-only takes effect without recreating the pool. const describePrimary = Effect.gen(function* () { const persistedSettings = yield* settings.get; const wslRequested = persistedSettings.wslOnly && persistedSettings.wslBackendEnabled; - // Only honor wsl-only when WSL is actually usable. If the user - // persisted wsl-only but WSL has since become unavailable (wsl.exe - // removed, no distro), fall back to the Windows primary instead of - // looping forever on preflight failures: the Connections backend - // control is hidden while WSL is unavailable, so a stuck WSL primary - // would otherwise leave no in-app way back to Windows. + // When WSL is unavailable its controls are hidden; fall back to Windows to keep recovery possible. const useWsl = wslRequested && (yield* wslEnvironment.isAvailable); return { useWsl, wslRequested, distro: persistedSettings.wslDistro }; }); @@ -874,8 +828,9 @@ export const make = Effect.gen(function* () { } return distro ? `WSL (${distro})` : "WSL"; }).pipe(Effect.withSpan("desktop.backendConfiguration.resolvePrimaryLabel")), - resolveWsl: (input) => - Effect.gen(function* () { + // The span options depend on each request's port and distro. + resolveWsl: Effect.fnUntraced( + function* (input) { const shared = yield* sharedInputs; return yield* resolveWslStartConfig({ ...shared, ...input }).pipe( Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), @@ -883,11 +838,14 @@ export const make = Effect.gen(function* () { Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree), Effect.provideService(FileSystem.FileSystem, fileSystem), ); - }).pipe( - Effect.withSpan("desktop.backendConfiguration.resolveWsl", { - attributes: { port: input.port, distro: input.distro ?? null }, - }), - ), + }, + (effect, input) => + effect.pipe( + Effect.withSpan("desktop.backendConfiguration.resolveWsl", { + attributes: { port: input.port, distro: input.distro ?? null }, + }), + ), + ), }); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 8cc1a9fc6433d..7b15346a754e2 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -24,8 +24,6 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as DesktopBackendManager from "./DesktopBackendManager.ts"; -import * as DesktopApp from "../app/DesktopApp.ts"; -import * as DesktopBackendPool from "./DesktopBackendPool.ts"; import * as DesktopObservability from "../app/DesktopObservability.ts"; import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts"; import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts"; @@ -34,7 +32,6 @@ import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; const decodeDesktopBackendBootstrap = Schema.decodeEffect( Schema.fromJsonString(DesktopBackendBootstrap), ); -const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError); const encodeDesktopTelemetryControl = Schema.encodeSync( Schema.fromJsonString(DesktopTelemetryControlMessage), ); @@ -274,258 +271,27 @@ describe("DesktopBackendManager", () => { ), ); - it.effect("preserves the readiness timeout cause and process context", () => - Effect.gen(function* () { - const requested = yield* Deferred.make(); - const layer = Layer.merge( - TestClock.layer(), - layerHttpClient((request) => - Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)), - ), - ); - - yield* Effect.gen(function* () { - const readiness = yield* DesktopBackendManager.waitForHttpReady({ - executablePath: baseConfig.executablePath, - entryPath: baseConfig.entryPath, - cwd: baseConfig.cwd, - httpBaseUrl: baseConfig.httpBaseUrl, - timeout: Duration.millis(50), - }).pipe(Effect.flip, Effect.forkChild); - - const request = yield* Deferred.await(requested); - assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment"); - - yield* TestClock.adjust(Duration.millis(50)); - const error = yield* Fiber.join(readiness); - - assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError); - assert.equal(error.executablePath, "/electron"); - assert.equal(error.entryPath, "/server/bin.mjs"); - assert.equal(error.cwd, "/server"); - assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/"); - assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment"); - assert.equal(error.timeoutMs, 50); - assert.isDefined(error.cause); - assert.equal( - error.message, - "Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.", - ); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("reports bootstrap encoding failures with stable process context", () => - Effect.gen(function* () { - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")), - ); - const error = yield* DesktopBackendManager.runBackendProcess({ - ...baseConfig, - desktopTelemetryStream: Stream.empty, - bootstrap: { - ...baseConfig.bootstrap, - port: 0, - }, - }).pipe( - Effect.flip, - Effect.scoped, - Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), - ); - - if (error._tag !== "BackendProcessBootstrapEncodeError") { - return assert.fail(`Expected bootstrap encode error, received ${error._tag}`); - } - assert.equal(error.executablePath, "/electron"); - assert.equal(error.entryPath, "/server/bin.mjs"); - assert.equal(error.cwd, "/server"); - assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/"); - assert.isDefined(error.cause); - assert.equal( - error.message, - "Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.", - ); - assert.isTrue(isBackendProcessError(error)); - }), - ); - - it.effect("preserves spawn failures without deriving their message from the cause", () => - Effect.gen(function* () { - const spawnCause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "ChildProcessSpawner", - method: "spawn", - pathOrDescriptor: baseConfig.executablePath, - description: "low-level detail that must not become the public message", - }); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.fail(spawnCause)), - ); - const error = yield* DesktopBackendManager.runBackendProcess({ - ...baseConfig, - desktopTelemetryStream: Stream.empty, - }).pipe( - Effect.flip, - Effect.scoped, - Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), - ); - - if (error._tag !== "BackendProcessSpawnError") { - return assert.fail(`Expected backend spawn error, received ${error._tag}`); - } - assert.equal(error.executablePath, "/electron"); - assert.equal(error.entryPath, "/server/bin.mjs"); - assert.equal(error.cwd, "/server"); - assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/"); - assert.strictEqual(error.cause, spawnCause); - assert.equal( - error.message, - "Failed to spawn desktop backend entry /server/bin.mjs with /electron.", - ); - assert.notInclude(error.message, spawnCause.message); - assert.isTrue(isBackendProcessError(error)); - }), - ); - - it.effect("preserves exit-status failures without copying their detail into the message", () => + it.effect("reports a SIGKILL exit without an exit code", () => Effect.gen(function* () { const exitCause = PlatformError.systemError({ - _tag: "PermissionDenied", + _tag: "Unknown", module: "ChildProcess", method: "exitCode", - description: "exit-status-secret-sentinel", - }); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - exitCode: Effect.fail(exitCause), - }), - ), - ), - ); - const error = yield* DesktopBackendManager.runBackendProcess({ - ...baseConfig, - desktopTelemetryStream: Stream.empty, - }).pipe( - Effect.flip, - Effect.scoped, - Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient)), - ); - - if (error._tag !== "BackendProcessExitStatusError") { - return assert.fail(`Expected backend exit-status error, received ${error._tag}`); - } - assert.equal(error.pid, 123); - assert.equal(error.executablePath, "/electron"); - assert.equal(error.entryPath, "/server/bin.mjs"); - assert.equal(error.cwd, "/server"); - assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/"); - assert.strictEqual(error.cause, exitCause); - assert.equal(error.message, "Failed to read the exit status of desktop backend process 123."); - assert.notInclude(error.message, "exit-status-secret-sentinel"); - assert.isTrue(isBackendProcessError(error)); - }), - ); - - it.effect("reports output stream failures with process and stream context", () => - Effect.gen(function* () { - const outputCause = PlatformError.systemError({ - _tag: "BadResource", - module: "ChildProcess", - method: "stdout", - description: "output-stream-secret-sentinel", + cause: new Error("Process interrupted due to receipt of signal: 'SIGKILL'"), }); - const reported = yield* Deferred.make(); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - stdout: Stream.fail(outputCause), - exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }), - ), - ), - ); - - const exit = yield* DesktopBackendManager.runBackendProcess({ - ...baseConfig, - desktopTelemetryStream: Stream.empty, - onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid), - }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient))); - const error = yield* Deferred.await(reported); - - assert.equal(exit.code.pipe(Option.getOrUndefined), 0); - if (error._tag !== "BackendProcessOutputReadError") { - return assert.fail(`Expected output read error, received ${error._tag}`); - } - assert.equal(error.executablePath, "/electron"); - assert.equal(error.entryPath, "/server/bin.mjs"); - assert.equal(error.cwd, "/server"); - assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/"); - assert.equal(error.pid, 123); - assert.equal(error.streamName, "stdout"); - assert.strictEqual(error.cause, outputCause); - assert.equal(error.message, "Failed to read stdout from desktop backend process 123."); - assert.notInclude(error.message, "output-stream-secret-sentinel"); - }), - ); - - it.effect("reports output handler failures separately from stream read failures", () => - Effect.gen(function* () { - const chunk = new TextEncoder().encode("backend output"); - const nextChunk = new TextEncoder().encode("still draining"); - const outputCause = new Error("output-handler-secret-sentinel"); - const reported = yield* Deferred.make(); - const drained = yield* Deferred.make(); - let outputCount = 0; const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - stdout: Stream.make(chunk, nextChunk), - exitCode: Deferred.await(drained).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }), - ), + Effect.succeed(makeProcess({ exitCode: Effect.fail(exitCause) })), ), ); const exit = yield* DesktopBackendManager.runBackendProcess({ ...baseConfig, desktopTelemetryStream: Stream.empty, - onOutput: () => { - outputCount += 1; - return outputCount === 1 - ? Effect.fail(outputCause) - : Deferred.succeed(drained, void 0).pipe(Effect.asVoid); - }, - onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid), }).pipe(Effect.scoped, Effect.provide(Layer.merge(layerSpawner, layerHealthyHttpClient))); - const error = yield* Deferred.await(reported); - assert.equal(exit.code.pipe(Option.getOrUndefined), 0); - if (error._tag !== "BackendProcessOutputHandlingError") { - return assert.fail(`Expected output handling error, received ${error._tag}`); - } - assert.equal(error.executablePath, "/electron"); - assert.equal(error.entryPath, "/server/bin.mjs"); - assert.equal(error.cwd, "/server"); - assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/"); - assert.equal(error.pid, 123); - assert.equal(error.streamName, "stdout"); - assert.equal(error.chunkByteLength, chunk.byteLength); - assert.strictEqual(error.cause, outputCause); - assert.equal( - error.message, - `Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`, - ); - assert.notInclude(error.message, "output-handler-secret-sentinel"); - assert.equal(outputCount, 2); + assert.deepEqual(exit, { code: Option.none(), reason: "killed by SIGKILL" }); }), ); @@ -607,195 +373,6 @@ describe("DesktopBackendManager", () => { ), ); - it.effect("drains trailing child output before persisting an unexpected exit", () => - Effect.scoped( - Effect.gen(function* () { - const persistedOutput = yield* Deferred.make>(); - const outputDrainStarted = yield* Deferred.make(); - const outputChunks = yield* Ref.make>([]); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - stdout: Stream.fromEffect( - Deferred.succeed(outputDrainStarted, void 0).pipe( - Effect.andThen(Effect.sleep(Duration.seconds(1))), - Effect.as(new TextEncoder().encode("trailing output\n")), - ), - ), - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), - }), - ), - ), - ); - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - backendOutputLog: { - writeOutputChunk: (_streamName, chunk) => - Ref.update(outputChunks, (current) => [...current, new TextDecoder().decode(chunk)]), - persistFailure: () => - Ref.get(outputChunks).pipe( - Effect.flatMap((chunks) => Deferred.succeed(persistedOutput, chunks)), - Effect.asVoid, - ), - }, - }); - - yield* instance.start; - yield* Deferred.await(outputDrainStarted); - yield* TestClock.adjust(Duration.seconds(1)); - - assert.deepEqual(yield* Deferred.await(persistedOutput), ["trailing output\n"]); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("retries HTTP readiness before reporting the backend ready", () => - Effect.scoped( - Effect.gen(function* () { - const requestUrls: Array = []; - const prunedRuntimes: Array<[string | null, string]> = []; - const statuses = [503, 200]; - let readyCount = 0; - const firstRequest = yield* Deferred.make(); - const backendReady = yield* Deferred.make(); - const processExit = yield* Deferred.make(); - const pruneComplete = yield* Deferred.make(); - const exited = yield* Queue.unbounded(); - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - exitCode: Deferred.await(processExit).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - }), - ), - ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - config: { - ...baseConfig, - runningDistro: "Ubuntu", - wslRuntimeId: "1.2.3-x64", - }, - pruneRuntimes: (distro, runtimeId) => - Effect.sync(() => { - prunedRuntimes.push([distro, runtimeId]); - }).pipe(Effect.andThen(Deferred.succeed(pruneComplete, void 0)), Effect.asVoid), - httpClientLayer: layerHttpClient((request) => - Effect.gen(function* () { - const status = statuses.shift(); - assert.isDefined(status); - requestUrls.push(request.url); - yield* Deferred.succeed(firstRequest, void 0); - return responseForRequest(request, status); - }), - ), - onReady: Effect.sync(() => { - readyCount += 1; - }).pipe(Effect.andThen(Deferred.succeed(backendReady, void 0)), Effect.asVoid), - backendOutputLog: { - persistFailure: () => Queue.offer(exited, void 0).pipe(Effect.asVoid), - }, - }); - - yield* instance.start; - yield* Deferred.await(firstRequest); - - assert.equal(readyCount, 0); - assert.deepEqual(prunedRuntimes, []); - assert.deepEqual(requestUrls, ["http://127.0.0.1:3773/.well-known/t3/environment"]); - - yield* TestClock.adjust(Duration.millis(100)); - yield* Deferred.await(backendReady); - yield* Deferred.await(pruneComplete); - yield* Deferred.succeed(processExit, void 0); - yield* Queue.take(exited); - - assert.equal(readyCount, 1); - assert.deepEqual(prunedRuntimes, [["Ubuntu", "1.2.3-x64"]]); - assert.deepEqual(requestUrls, [ - "http://127.0.0.1:3773/.well-known/t3/environment", - "http://127.0.0.1:3773/.well-known/t3/environment", - ]); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect( - "re-probes readiness after the first budget expires while the backend is still alive", - () => - Effect.scoped( - Effect.gen(function* () { - const requestUrls: Array = []; - let requestCount = 0; - let readyCount = 0; - let readinessTimeoutCount = 0; - const firstProbe = yield* Deferred.make(); - const childExit = yield* Deferred.make(); - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - exitCode: Deferred.await(childExit).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - }), - ), - ), - ); - - const layerHttp = layerHttpClient((request) => - Effect.gen(function* () { - requestCount += 1; - requestUrls.push(request.url); - yield* Deferred.succeed(firstProbe, void 0); - return responseForRequest(request, requestCount <= 2 ? 503 : 200); - }), - ); - - const runFiber = yield* DesktopBackendManager.runBackendProcess({ - ...baseConfig, - desktopTelemetryStream: Stream.empty, - readinessTimeout: Duration.millis(50), - onReady: () => - Effect.sync(() => { - readyCount += 1; - }), - onReadinessFailure: () => - Effect.sync(() => { - readinessTimeoutCount += 1; - }), - }).pipe(Effect.provide(Layer.merge(layerSpawner, layerHttp)), Effect.forkChild); - - yield* Deferred.await(firstProbe); - assert.equal(readyCount, 0); - assert.equal(readinessTimeoutCount, 0); - - yield* TestClock.adjust(Duration.millis(50)); - assert.equal(readinessTimeoutCount, 1); - assert.equal(readyCount, 0); - - yield* TestClock.adjust(Duration.millis(100)); - assert.equal(readinessTimeoutCount, 2); - assert.equal(readyCount, 1); - assert.equal(requestUrls.length, 3); - - yield* Deferred.succeed(childExit, void 0); - assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 0); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - it.effect("starts the configured backend and closes the scoped process on stop", () => Effect.scoped( Effect.gen(function* () { @@ -966,254 +543,27 @@ describe("DesktopBackendManager", () => { ), ); - it.effect("retries config resolution after a start request during stop teardown", () => + it.effect("reports state-directory ownership once without scheduling another backend", () => Effect.scoped( Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - const teardownStarted = yield* Deferred.make(); - const finishTeardown = yield* Deferred.make(); - const configAttempts = yield* Ref.make(0); let startCount = 0; - - const configFailure = PlatformError.systemError({ - _tag: "Unknown", - module: "DesktopBackendManager", - method: "configResolve", - description: "transient configuration failure", - }); - 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, + 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), ), - ); - } 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 configResolve = Ref.updateAndGet(configAttempts, (attempt) => attempt + 1).pipe( - Effect.flatMap((attempt) => - attempt === 2 ? Effect.fail(configFailure) : Effect.succeed(baseConfig), + }); + }), + ), ), - ); - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - configResolve, httpClientLayer: layerHttpClient(() => Effect.never), - }); - - 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; - yield* Deferred.succeed(finishTeardown, undefined); - yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second")); - - const pendingRestart = yield* instance.snapshot; - assert.equal(pendingRestart.desiredRunning, true); - assert.equal(pendingRestart.restartScheduled, true); - - yield* TestClock.adjust(Duration.seconds(2)); - - assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2); - assert.equal(yield* Ref.get(configAttempts), 3); - assert.equal((yield* instance.snapshot).desiredRunning, true); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("keeps a timed-out run active until its process exits", () => - Effect.scoped( - 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 instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - }); - - yield* instance.start; - assert.equal(yield* Queue.take(starts), 1); - - const stopFiber = yield* instance - .stop({ timeout: Duration.millis(100) }) - .pipe(Effect.forkChild); - yield* Deferred.await(teardownStarted).pipe(Effect.timeout("1 second")); - yield* instance.start; - yield* TestClock.adjust(Duration.millis(100)); - yield* Fiber.join(stopFiber).pipe(Effect.timeout("1 second")); - - assert.equal(startCount, 1); - const timedOut = yield* instance.snapshot; - assert.equal(timedOut.desiredRunning, true); - assert.deepEqual(timedOut.activePid, Option.some(123)); - - yield* Deferred.succeed(finishTeardown, undefined); - yield* TestClock.adjust(Duration.millis(500)); - - assert.equal(yield* Queue.take(starts).pipe(Effect.timeout("1 second")), 2); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("does not notify shutdown before the first start has prior state", () => - Effect.scoped( - Effect.gen(function* () { - let shutdownCount = 0; - const closed = yield* Deferred.make(); - const startedPids = yield* Queue.unbounded(); - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - yield* Queue.offer(startedPids, 123); - const close = Deferred.succeed(closed, void 0).pipe(Effect.asVoid); - return makeProcess({ - exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - kill: () => close, - }); - }), - ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - onShutdown: Effect.sync(() => { - shutdownCount += 1; - }), - }); - - yield* instance.start; - assert.equal(yield* Queue.take(startedPids), 123); - assert.equal(shutdownCount, 0); - }), - ), - ); - - it.effect("restarts an unexpectedly exited backend with the Effect clock", () => - Effect.scoped( - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - const failures = yield* Queue.unbounded(); - let startCount = 0; - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.sync(() => { - startCount += 1; - return makeProcess({ - exitCode: Queue.offer(starts, startCount).pipe( - Effect.as(ChildProcessSpawner.ExitCode(1)), - ), - }); - }), - ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - backendOutputLog: { - persistFailure: ({ details }) => Queue.offer(failures, details).pipe(Effect.asVoid), - }, - }); - - yield* instance.start; - - assert.equal(yield* Queue.take(starts), 1); - assert.equal(yield* Queue.take(failures), "pid=123 code=1"); - - yield* TestClock.adjust(Duration.millis(499)); - assert.equal(yield* Queue.size(starts), 0); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal(yield* Queue.take(starts), 2); - - yield* TestClock.adjust(Duration.millis(999)); - assert.equal(yield* Queue.size(starts), 0); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal(yield* Queue.take(starts), 3); - }).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), - ), - }); - }), - ), - ), - httpClientLayer: layerHttpClient(() => Effect.never), - onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid), + onStateDirOwned: Deferred.succeed(refused, undefined).pipe(Effect.asVoid), }); yield* instance.start; yield* Deferred.await(refused); @@ -1225,361 +575,4 @@ describe("DesktopBackendManager", () => { }).pipe(Effect.provide(TestClock.layer())), ), ); - - it.effect("does not notify shutdown when a scheduled restart starts from non-ready state", () => - Effect.scoped( - Effect.gen(function* () { - let shutdownCount = 0; - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - config: { - ...baseConfig, - preflightFailure: Option.some({ reason: "preflight failed", fatal: false }), - }, - onShutdown: Effect.sync(() => { - shutdownCount += 1; - }), - }); - - yield* instance.start; - assert.equal(shutdownCount, 0); - - yield* TestClock.adjust(Duration.millis(500)); - assert.equal(shutdownCount, 0); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("surfaces a fatal preflight failure once and stops looping after the cap", () => - Effect.scoped( - Effect.gen(function* () { - const failures: string[] = []; - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - config: { - ...baseConfig, - preflightFailure: Option.some({ reason: "Node.js not found", fatal: true }), - }, - onPreflightFailed: (failure) => - Effect.sync(() => { - failures.push(failure.reason); - }).pipe(Effect.as(false)), - }); - - yield* instance.start; - assert.deepEqual(failures, []); - - yield* TestClock.adjust(Duration.millis(500)); - yield* TestClock.adjust(Duration.seconds(1)); - yield* TestClock.adjust(Duration.seconds(2)); - yield* TestClock.adjust(Duration.seconds(4)); - assert.deepEqual(failures, ["Node.js not found"]); - - yield* TestClock.adjust(Duration.seconds(8)); - yield* TestClock.adjust(Duration.seconds(30)); - assert.deepEqual(failures, ["Node.js not found"]); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("can be started again after a fatal preflight cap once config recovers", () => - Effect.scoped( - Effect.gen(function* () { - const failing = yield* Ref.make(true); - const starts = yield* Queue.unbounded(); - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Queue.offer(starts, 123).pipe( - Effect.as( - makeProcess({ - exitCode: Effect.never, - }), - ), - ), - ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - configResolve: Ref.get(failing).pipe( - Effect.map((isFailing) => - isFailing - ? { - ...baseConfig, - preflightFailure: Option.some({ - reason: "Node.js not found", - fatal: true, - }), - } - : baseConfig, - ), - ), - }); - - yield* instance.start; - yield* TestClock.adjust(Duration.millis(500)); - yield* TestClock.adjust(Duration.seconds(1)); - yield* TestClock.adjust(Duration.seconds(2)); - yield* TestClock.adjust(Duration.seconds(4)); - yield* TestClock.adjust(Duration.seconds(8)); - - const parked = yield* instance.snapshot; - assert.equal(parked.desiredRunning, false); - assert.equal(parked.ready, false); - assert.isTrue(Option.isNone(parked.activePid)); - assert.equal(parked.restartScheduled, false); - assert.equal(yield* Queue.size(starts), 0); - - yield* Ref.set(failing, false); - yield* instance.start; - - assert.equal(yield* Queue.take(starts), 123); - const running = yield* instance.snapshot; - assert.equal(running.desiredRunning, true); - assert.deepEqual(running.activePid, Option.some(123)); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("keeps retrying a transient (non-fatal) preflight failure without surfacing", () => - Effect.scoped( - Effect.gen(function* () { - const failures: string[] = []; - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - config: { - ...baseConfig, - preflightFailure: Option.some({ reason: "wslpath conversion failed", fatal: false }), - }, - onPreflightFailed: (failure) => - Effect.sync(() => { - failures.push(failure.reason); - }).pipe(Effect.as(false)), - }); - - yield* instance.start; - - yield* TestClock.adjust(Duration.minutes(2)); - assert.deepEqual(failures, []); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("surfaces a bounded transient preflight failure after its retry limit", () => - Effect.scoped( - Effect.gen(function* () { - const failures: string[] = []; - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - config: { - ...baseConfig, - preflightFailure: Option.some({ - reason: "WSL toolchain probe timed out", - fatal: false, - retryLimit: 3, - }), - }, - onPreflightFailed: (failure) => - Effect.sync(() => { - failures.push(failure.reason); - }).pipe(Effect.as(false)), - }); - - yield* instance.start; - yield* TestClock.adjust(Duration.millis(500)); - assert.deepEqual(failures, []); - - yield* TestClock.adjust(Duration.seconds(1)); - assert.deepEqual(failures, ["WSL toolchain probe timed out"]); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("cancels a scheduled restart when start is requested manually", () => - Effect.scoped( - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - const secondClosed = yield* Deferred.make(); - let startCount = 0; - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - startCount += 1; - yield* Queue.offer(starts, startCount); - - if (startCount === 1) { - return makeProcess({ - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), - }); - } - - const scope = yield* Scope.Scope; - const close = Deferred.succeed(secondClosed, void 0).pipe(Effect.asVoid); - yield* Scope.addFinalizer(scope, close); - return makeProcess({ - exitCode: Deferred.await(secondClosed).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - kill: () => close, - }); - }), - ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - }); - - yield* instance.start; - - assert.equal(yield* Queue.take(starts), 1); - let restartScheduled = false; - while (!restartScheduled) { - restartScheduled = (yield* instance.snapshot).restartScheduled; - if (!restartScheduled) { - yield* Effect.yieldNow; - } - } - - yield* instance.start; - assert.equal(yield* Queue.take(starts), 2); - - yield* instance.stop(); - yield* TestClock.adjust(Duration.millis(500)); - - assert.equal(yield* Queue.size(starts), 0); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("does not restart after stop cancels a scheduled restart", () => - Effect.scoped( - Effect.gen(function* () { - const starts = yield* Queue.unbounded(); - let startCount = 0; - - const layerSpawner = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.sync(() => { - startCount += 1; - return makeProcess({ - exitCode: Queue.offer(starts, startCount).pipe( - Effect.as(ChildProcessSpawner.ExitCode(1)), - ), - }); - }), - ), - ); - - const instance = yield* makeTestInstance({ - spawnerLayer: layerSpawner, - httpClientLayer: layerHttpClient(() => Effect.never), - }); - - yield* instance.start; - assert.equal(yield* Queue.take(starts), 1); - - let restartScheduled = false; - while (!restartScheduled) { - restartScheduled = (yield* instance.snapshot).restartScheduled; - if (!restartScheduled) { - yield* Effect.yieldNow; - } - } - - yield* instance.stop(); - yield* TestClock.adjust(Duration.millis(500)); - - assert.equal(yield* Queue.size(starts), 0); - assert.equal((yield* instance.snapshot).desiredRunning, false); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); - - it.effect("stopAllPoolInstances bounds the quit finalizer when backends hang", () => - Effect.scoped( - Effect.gen(function* () { - const teardownStarted = yield* Queue.unbounded(); - const teardownFinished = yield* Queue.unbounded(); - const allowTeardown = yield* Deferred.make(); - - const makeInstance = (name: string) => - makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const scope = yield* Scope.Scope; - yield* Scope.addFinalizer( - scope, - Queue.offer(teardownStarted, name).pipe( - Effect.andThen(Deferred.await(allowTeardown)), - Effect.andThen(Queue.offer(teardownFinished, name)), - Effect.asVoid, - ), - ); - return makeProcess({ exitCode: Effect.never }); - }), - ), - ), - httpClientLayer: layerHttpClient(() => Effect.never), - }); - - const instance1 = yield* makeInstance("instance1"); - const instance2 = yield* makeInstance("instance2"); - - yield* instance1.start; - yield* instance2.start; - - const layerMockPool = Layer.succeed(DesktopBackendPool.DesktopBackendPool, { - list: Effect.succeed([instance1, instance2]), - get: () => Effect.succeedNone, - primary: Effect.die(new Error("primary not implemented")), - register: () => Effect.die(new Error("register not implemented")), - unregister: () => Effect.die(new Error("unregister not implemented")), - }); - - const quitFiber = yield* Effect.scoped( - Effect.addFinalizer(() => DesktopApp.stopAllPoolInstances()), - ).pipe(Effect.provide(layerMockPool), Effect.forkChild); - - const started = yield* Queue.takeN(teardownStarted, 2); - assert.deepEqual(started.toSorted(), ["instance1", "instance2"]); - - yield* TestClock.adjust(Duration.seconds(5)); - yield* Fiber.join(quitFiber); - assert.equal(yield* Queue.size(teardownFinished), 0); - - yield* Deferred.succeed(allowTeardown, undefined); - const finished = yield* Queue.takeN(teardownFinished, 2); - assert.deepEqual(finished.toSorted(), ["instance1", "instance2"]); - }).pipe(Effect.provide(TestClock.layer())), - ), - ); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 8d2a3f1c4912f..007f7369365a2 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -37,8 +37,7 @@ const MAX_PREFLIGHT_FAILURE_ATTEMPTS = 5; const DEFAULT_BACKEND_READINESS_TIMEOUT = Duration.minutes(1); const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100); const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1); -// Same as the service launcher. A killed backend leaves its agents running, -// and a busy one needs a few seconds to stop every provider session. +// Match the service launcher's grace period so backends can stop provider sessions. const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5); const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5); const BACKEND_READINESS_PATH = "/.well-known/t3/environment"; @@ -63,9 +62,7 @@ export type DesktopBackendBootstrapDelivery = "fd3" | "stdin"; export interface DesktopBackendStartConfig extends BackendProcessContext { readonly args: ReadonlyArray; readonly env: Record; - // When true the spawner merges the desktop process.env on top of `env`; - // when false `env` is passed verbatim. WSL mode opts out so a leaking - // T3CODE_HOME can't pin the WSL backend to /mnt/c/...\.t3. + /** False passes env verbatim, preventing the Windows T3CODE_HOME from leaking into WSL. */ readonly extendEnv: boolean; readonly bootstrap: DesktopBackendBootstrapValue; readonly bootstrapDelivery: DesktopBackendBootstrapDelivery; @@ -234,11 +231,7 @@ export interface BackendInstanceSpec { readonly id: BackendInstanceId; readonly label: Effect.Effect; readonly configResolve: Effect.Effect; - // Receives the *resolved* httpBaseUrl of the run that just became - // ready. The window service uses this to decide what URL to load - // (the WSL backend reports its distro IP, the Windows backend reports - // 127.0.0.1). Splitting this off from configResolve avoids races - // between "fired onReady" and "currentConfig already advanced". + /** Receives the ready run's resolved URL; reading current config could race a subsequent restart. */ readonly onReady?: (httpBaseUrl: URL) => Effect.Effect; readonly onShutdown?: () => Effect.Effect; readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect; @@ -312,7 +305,7 @@ const closeRun = ( ); }; -export const waitForHttpReady = ( +const waitForHttpReady = ( options: BackendProcessContext & { readonly timeout: Duration.Duration }, ): Effect.Effect => { const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl); @@ -431,16 +424,12 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( cwd: options.cwd, env: options.env, extendEnv: options.extendEnv, - // In Electron main, process.execPath points to the Electron binary. - // Run the child in Node mode so this backend process does not become a GUI app instance. stdin: options.bootstrapDelivery === "stdin" ? bootstrapStream : "ignore", stdout: options.captureOutput ? "pipe" : "inherit", stderr: options.captureOutput ? "pipe" : "inherit", killSignal: "SIGTERM", forceKillAfter: DEFAULT_BACKEND_TERMINATE_GRACE, - // wsl.exe drops additional file descriptors when forwarding to the Linux - // side, so the WSL spawn path delivers the bootstrap envelope via stdin - // (`--bootstrap-fd 0`) instead. + // wsl.exe drops extra file descriptors; deliver its bootstrap via stdin. ...(options.bootstrapDelivery === "fd3" ? { additionalFds } : {}), }); @@ -542,12 +531,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( ).pipe(Effect.forkScoped), ); } - // Probe readiness in a loop while the backend process is still alive instead - // of giving up after the first budget. A slow cold boot (the WSL bundle - // loading across /mnt/c, or a first launch right after an update) can exceed - // the initial readiness budget while the backend is about to come up moments - // later; a one-shot probe left the app stuck on "Connecting to WSL…" forever - // even though the backend kept running and became healthy. + // Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive. const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() => waitForHttpReady({ executablePath: options.executablePath, @@ -568,8 +552,22 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped); const exit = yield* handle.exitCode.pipe( - Effect.mapError( - (cause) => + Effect.map((exitCode) => ({ + code: Option.some(exitCode), + reason: `code=${exitCode}`, + })), + Effect.catch((cause) => { + // Effect's Node spawner exposes signal exits only through this cause message. + const signal = + cause.cause instanceof Error + ? /^Process interrupted due to receipt of signal: '(SIG[A-Z0-9]+)'$/.exec( + cause.cause.message, + )?.[1] + : undefined; + if (signal !== undefined) { + return Effect.succeed({ code: Option.none(), reason: `killed by ${signal}` }); + } + return Effect.fail( new BackendProcessExitStatusError({ executablePath: options.executablePath, entryPath: options.entryPath, @@ -578,7 +576,8 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( pid: Number(handle.pid), cause, }), - ), + ); + }), Effect.exit, ); yield* options.onExitObserved?.() ?? Effect.void; @@ -592,11 +591,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( if (Exit.isFailure(exit)) { return yield* Effect.failCause(exit.cause); } - const exitCode = exit.value; - return { - code: Option.some(exitCode), - reason: `code=${exitCode}`, - } satisfies BackendProcessExit; + return exit.value; }); export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( @@ -1103,20 +1098,25 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( }); }); - const waitForReady = (timeout: Duration.Duration): Effect.Effect => - Effect.gen(function* () { + const waitForReady: (timeout: Duration.Duration) => Effect.Effect = Effect.fn( + "DesktopBackendManager.waitForReady", + )( + function* (_timeout: Duration.Duration) { const current = yield* Ref.get(state); if (!current.desiredRunning) return { done: true, ready: false }; return current.ready ? { done: true, ready: true } : { done: false, ready: false }; - }).pipe( - Effect.repeat({ - until: (status) => status.done, - schedule: Schedule.spaced(Duration.millis(100)), - }), - Effect.map((status) => status.ready), - Effect.timeoutOption(timeout), - Effect.map(Option.getOrElse(() => false)), - ); + }, + (effect, timeout) => + effect.pipe( + Effect.repeat({ + until: (status) => status.done, + schedule: Schedule.spaced(Duration.millis(100)), + }), + Effect.map((status) => status.ready), + Effect.timeoutOption(timeout), + Effect.map(Option.getOrElse(() => false)), + ), + ); yield* Effect.addFinalizer(() => stop()); diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index ed6fab28503c3..0583e8df21705 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -1,5 +1,4 @@ import { assert, describe, it } from "@effect/vitest"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -19,29 +18,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts"; import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendPool from "./DesktopBackendPool.ts"; -import type { DesktopBackendSnapshot, DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; - -function makeStubInstance( - id: DesktopBackendPool.BackendInstanceId, - label: string, -): DesktopBackendPool.DesktopBackendInstance { - const snapshot: DesktopBackendSnapshot = { - desiredRunning: false, - ready: false, - activePid: Option.none(), - restartAttempt: 0, - restartScheduled: false, - }; - return { - id, - label: Effect.succeed(label), - start: Effect.void, - stop: () => Effect.void, - currentConfig: Effect.succeed(Option.none()), - snapshot: Effect.succeed(snapshot), - waitForReady: (_timeout: Duration.Duration) => Effect.succeed(false), - }; -} +import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; function layerPool(labelRef: Ref.Ref): Layer.Layer { return DesktopBackendPool.layer.pipe( @@ -111,49 +88,47 @@ function layerPool(labelRef: Ref.Ref): Layer.Layer { - it.effect("layerTest exposes registered instances by id", () => - Effect.gen(function* () { - const pool = yield* DesktopBackendPool.DesktopBackendPool; - const fetchedPrimary = yield* pool.get(DesktopBackendPool.PRIMARY_INSTANCE_ID); - const fetchedWsl = yield* pool.get(DesktopBackendPool.BackendInstanceId("wsl:ubuntu")); - const fetchedMissing = yield* pool.get(DesktopBackendPool.BackendInstanceId("missing")); - const all = yield* pool.list; - const resolvedPrimary = yield* pool.primary; - - assert.equal(yield* Option.getOrThrow(fetchedPrimary).label, "Windows"); - assert.equal(yield* Option.getOrThrow(fetchedWsl).label, "WSL (Ubuntu)"); - assert.isTrue(Option.isNone(fetchedMissing)); - assert.lengthOf(all, 2); - assert.equal(resolvedPrimary.id, DesktopBackendPool.PRIMARY_INSTANCE_ID); - }).pipe( - Effect.provide( - DesktopBackendPool.layerTest([ - makeStubInstance(DesktopBackendPool.PRIMARY_INSTANCE_ID, "Windows"), - makeStubInstance(DesktopBackendPool.BackendInstanceId("wsl:ubuntu"), "WSL (Ubuntu)"), - ]), - ), - ), - ); - - it.effect("layerTest dies when no instances are supplied", () => - Effect.exit( - DesktopBackendPool.DesktopBackendPool.pipe(Effect.provide(DesktopBackendPool.layerTest([]))), - ).pipe(Effect.map((exit) => assert.equal(exit._tag, "Failure"))), - ); - - it.effect("resolves the primary label lazily after pool layer construction", () => + it.effect("unregister stops the registered instance", () => Effect.scoped( Effect.gen(function* () { - const labelRef = yield* Ref.make("Windows"); - const pool = yield* DesktopBackendPool.DesktopBackendPool.pipe( - Effect.provide(layerPool(labelRef)), - ); - const primary = yield* pool.primary; + 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({ + executablePath: "/electron", + args: [], + entryPath: "/server/bin.mjs", + cwd: "/server", + env: {}, + bootstrap: { + mode: "desktop", + noBrowser: true, + port: 3774, + t3Home: "/tmp/t3", + host: "127.0.0.1", + desktopBootstrapToken: "token", + tailscaleServeEnabled: false, + tailscaleServePort: 443, + }, + bootstrapDelivery: "fd3", + extendEnv: true, + httpBaseUrl: new URL("http://127.0.0.1:3774"), + captureOutput: false, + preflightFailure: Option.some({ reason: "WSL starting", fatal: false }), + } satisfies DesktopBackendStartConfig), + }); + yield* instance.start; + assert.equal((yield* instance.snapshot).restartScheduled, true); - yield* Ref.set(labelRef, "WSL (Ubuntu)"); + yield* pool.unregister(id); - assert.equal(yield* primary.label, "WSL (Ubuntu)"); - }), + 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/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 13c85ac58fdcc..7b2f685190761 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -106,16 +106,11 @@ export const layer = Layer.effect( const electronDialog = yield* ElectronDialog.ElectronDialog; const electronApp = yield* ElectronApp.ElectronApp; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; - // Without this, instance scopes are orphaned: they only close via explicit unregister() calls, - // so on app shutdown the WSL backend child process gets hard-killed by the OS instead of - // receiving the graceful SIGTERM + grace period the instance's stop finalizer would otherwise - // run. + // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends. const layerScope = yield* Scope.Scope; const factoryContext = yield* Effect.context(); - // Fatal configuration failures persist the Windows fallback. Bounded - // transport failures use an in-memory fallback for this launch so the app - // opens without overwriting the user's WSL preference. + // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference. const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")( function* (failure: DesktopBackendManager.PreflightFailure) { const { reason, fatal } = failure; @@ -139,9 +134,8 @@ export const layer = Layer.effect( "WSL backend couldn't start", `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Connections once the WSL distro is fixed.`, ); - // Clearing wslBackendEnabled alone would leave a stale wslOnly:true that silently re-traps - // the user in wsl-only mode the next time they enable WSL. If the persisted write fails, - // keep this process recoverable by applying the fallback to in-memory settings. + // Clear wslOnly too so enabling WSL cannot restore a failed mode. + // Keep the in-memory fallback if persistence fails. yield* appSettings.applyWslWindowsFallback.pipe( Effect.catch((error) => logBackendPoolWarning( @@ -158,14 +152,10 @@ export const layer = Layer.effect( const primary = yield* DesktopBackendManager.makeBackendInstance({ id: DesktopBackendManager.PRIMARY_INSTANCE_ID, - // Keep this lazy. The pool layer is initialized before startup loads - // persisted desktop settings, so resolving the primary label here would - // permanently capture DEFAULT_DESKTOP_SETTINGS and mislabel WSL-only - // primaries as Windows. + // Resolve lazily: startup loads persisted settings after pool initialization. label: configuration.resolvePrimaryLabel, configResolve: configuration.resolvePrimary, - // Window creation errors propagating out of handleBackendReady must not block the readiness - // callback (that would prevent restartAttempt from being reset), so we absorb them here. + // Absorb window errors so readiness can reset restartAttempt. onReady: (httpBaseUrl) => desktopWindow.handleBackendReady(httpBaseUrl).pipe( Effect.catch((error) => @@ -180,7 +170,7 @@ export const layer = Layer.effect( electronDialog .showErrorBox( "This T3 home is unavailable", - "Another T3 Code server, such as the background service, is using this data directory. Stop that server and reopen T3 Code, or set a separate T3CODE_HOME and pair with the running server.", + "Another T3 Code server, such as the background service, is using this data directory, or an older background service is set up for it. Stop that server or try `t3 update`. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command. Then reopen T3 Code. You can also set a separate T3CODE_HOME and pair with the running server.", ) .pipe(Effect.andThen(electronApp.quit)), }); @@ -219,12 +209,11 @@ export const layer = Layer.effect( ] as const); } return Effect.gen(function* () { - // Provide the captured factory services first, then the child scope - // last so instance finalizers are owned by the unregisterable scope. + // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers. const instanceScope = yield* Scope.fork(layerScope, "sequential"); const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe( - Effect.provide(factoryContext), Scope.provide(instanceScope), + Effect.provide(factoryContext), ); const next = new Map(current); next.set(spec.id, { @@ -247,61 +236,59 @@ export const layer = Layer.effect( ), ); - const unregister: DesktopBackendPool["Service"]["unregister"] = (id) => - Effect.gen(function* () { - if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) { - return yield* new DesktopBackendPoolCannotUnregisterPrimaryError(); - } - const done = yield* Deferred.make(); - const action = yield* SynchronizedRef.modifyEffect( - instancesRef, - ( - current, - ): Effect.Effect< - readonly [UnregisterAction, ReadonlyMap] - > => { - const entry = current.get(id); - if (entry === undefined) { - return Effect.succeed([{ _tag: "Absent" } as const, current] as const); - } - if (entry._tag === "Closing") { - return Effect.succeed([ - { _tag: "Wait", done: entry.done } as const, - current, - ] as const); - } - const next = new Map(current); - next.set(id, { _tag: "Closing", done }); - return Effect.succeed([ - { _tag: "Close", entry } as const, - next as ReadonlyMap, - ] as const); - }, - ); - - if (action._tag === "Absent") return; - if (action._tag === "Wait") { - yield* Deferred.await(action.done); - return; - } - - const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => { - const closing = current.get(id); - if (closing?._tag !== "Closing" || closing.done !== done) { - return Effect.succeed([undefined, current] as const); + const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn( + "DesktopBackendPool.unregister", + )(function* (id) { + if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) { + return yield* new DesktopBackendPoolCannotUnregisterPrimaryError(); + } + const done = yield* Deferred.make(); + const action = yield* SynchronizedRef.modifyEffect( + instancesRef, + ( + current, + ): Effect.Effect< + readonly [UnregisterAction, ReadonlyMap] + > => { + const entry = current.get(id); + if (entry === undefined) { + return Effect.succeed([{ _tag: "Absent" } as const, current] as const); + } + if (entry._tag === "Closing") { + return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const); } const next = new Map(current); - next.delete(id); + next.set(id, { _tag: "Closing", done }); return Effect.succeed([ - undefined, + { _tag: "Close", entry } as const, next as ReadonlyMap, ] as const); - }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid); - yield* Option.match(action.entry.scope, { - onNone: () => Effect.void, - onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore), - }).pipe(Effect.ensuring(finish)); - }); + }, + ); + + if (action._tag === "Absent") return; + if (action._tag === "Wait") { + yield* Deferred.await(action.done); + return; + } + + const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => { + const closing = current.get(id); + if (closing?._tag !== "Closing" || closing.done !== done) { + return Effect.succeed([undefined, current] as const); + } + const next = new Map(current); + next.delete(id); + return Effect.succeed([ + undefined, + next as ReadonlyMap, + ] as const); + }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid); + yield* Option.match(action.entry.scope, { + onNone: () => Effect.void, + onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore), + }).pipe(Effect.ensuring(finish)); + }); return DesktopBackendPool.of({ get: (id) => diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index 900afce9b860a..348d3a7050f70 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -195,21 +195,6 @@ describe("DesktopLocalEnvironmentAuth", () => { return { auth, requestCount }; }); - it.effect("retries a backend that is still starting", () => - Effect.gen(function* () { - const { auth, requestCount } = yield* makeExchange( - 2, - () => new Response("", { status: 503 }), - ); - - const fiber = yield* auth.getBearerToken.pipe(Effect.forkChild); - yield* TestClock.adjust(Duration.seconds(1)); - - assert.strictEqual(yield* Fiber.join(fiber), "desktop-bearer-token"); - assert.strictEqual(yield* Ref.get(requestCount), 3); - }).pipe(Effect.provide(TestClock.layer())), - ); - it.effect("does not retry a rejected bootstrap credential", () => Effect.gen(function* () { const { auth, requestCount } = yield* makeExchange(1, () => diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index 4d95dd075cf3e..6481bfd64c897 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -63,7 +63,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service< } >()("@t3tools/desktop/backend/DesktopLocalEnvironmentAuth") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const pool = yield* DesktopBackendPool.DesktopBackendPool; const httpClient = yield* HttpClient.HttpClient; @@ -85,9 +85,7 @@ export const make = Effect.gen(function* () { return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); } const config = configOption.value; - // A backend launched with the desktop secret accepts the current - // window's token, not the one frozen into its launch config; this - // exchange can run long after launch (e.g. after a suspend). + // Secret-authenticated backends accept the current window token; the launch token may be stale. const secret = config.bootstrap.desktopBootstrapSecret; const credential = secret === undefined diff --git a/apps/desktop/src/backend/DesktopNetworkInterfaces.test.ts b/apps/desktop/src/backend/DesktopNetworkInterfaces.test.ts deleted file mode 100644 index 679d19a53d0a3..0000000000000 --- a/apps/desktop/src/backend/DesktopNetworkInterfaces.test.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Cause from "effect/Cause"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import { beforeEach, vi } from "vite-plus/test"; - -const { networkInterfacesMock } = vi.hoisted(() => ({ - networkInterfacesMock: vi.fn(), -})); - -vi.mock("node:os", () => ({ - networkInterfaces: networkInterfacesMock, -})); - -import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts"; - -const layerTest = DesktopNetworkInterfaces.layer.pipe( - Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), -); - -describe("DesktopNetworkInterfaces", () => { - beforeEach(() => { - networkInterfacesMock.mockReset(); - }); - - it.effect("reads network interfaces through the service", () => { - const interfaces = { - en0: [ - { - address: "192.168.1.10", - family: "IPv4", - internal: false, - }, - ], - }; - networkInterfacesMock.mockReturnValueOnce(interfaces); - - return Effect.gen(function* () { - const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces; - assert.strictEqual(yield* service.read, interfaces); - }).pipe(Effect.provide(layerTest)); - }); - - it.effect("preserves network interface read failures as structured defects", () => { - const cause = new Error("network interface probe failed"); - networkInterfacesMock.mockImplementationOnce(() => { - throw cause; - }); - - return Effect.gen(function* () { - const service = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces; - const exit = yield* Effect.exit(service.read); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, DesktopNetworkInterfaces.DesktopNetworkInterfacesReadError); - assert.equal(error.platform, "linux"); - assert.strictEqual(error.cause, cause); - assert.equal(error.message, "Failed to read desktop network interfaces on linux."); - } - }).pipe(Effect.provide(layerTest)); - }); -}); diff --git a/apps/desktop/src/backend/DesktopServerExposure.test.ts b/apps/desktop/src/backend/DesktopServerExposure.test.ts index d1ebf2e0fa820..f53cde3e451d7 100644 --- a/apps/desktop/src/backend/DesktopServerExposure.test.ts +++ b/apps/desktop/src/backend/DesktopServerExposure.test.ts @@ -40,36 +40,32 @@ const tailnetNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces = { ], }; -function layerMockSpawner(statusJson = "{}") { +function layerMockSpawner(statusJson: string | (() => string) = "{}", onSpawn?: () => void) { return Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => - Effect.succeed( - ChildProcessSpawner.makeHandle({ + Effect.sync(() => { + onSpawn?.(); + return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), isRunning: Effect.succeed(false), kill: () => Effect.void, unref: Effect.succeed(Effect.void), stdin: Sink.drain, - stdout: Stream.make(encoder.encode(statusJson)), + stdout: Stream.make( + encoder.encode(typeof statusJson === "string" ? statusJson : statusJson()), + ), stderr: Stream.empty, all: Stream.empty, getInputFd: () => Sink.drain, getOutputFd: () => Stream.empty, - }), - ), + }); + }), ), ); } -function layerDieOnSpawn() { - return Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected tailscale spawn")), - ); -} - function layerEnvironmentFor(baseDir: string, env: Record = {}) { return DesktopEnvironment.layer({ dirname: "/repo/apps/desktop/src", @@ -146,6 +142,34 @@ const withHarness = ( }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); describe("DesktopServerExposure", () => { + it.effect("uses cached Tailscale identity to exclude another VPN's pairing address", () => { + let statusReads = 0; + return withHarness( + { + ...lanNetworkInterfaces, + pvpnksintrf1: [{ address: "100.85.0.1", family: "IPv4", internal: false }], + vpn0: [{ address: "100.74.126.34", family: "IPv4", internal: false }], + }, + Effect.gen(function* () { + const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; + yield* serverExposure.configureFromSettings({ port: 4173 }); + yield* serverExposure.setMode("network-accessible"); + + const endpoints = yield* serverExposure.getAdvertisedEndpoints; + assert.deepEqual( + endpoints.map((endpoint) => endpoint.httpBaseUrl), + ["http://127.0.0.1:4173/", "http://192.168.1.20:4173/", "http://100.74.126.34:4173/"], + ); + assert.deepEqual(yield* serverExposure.getAdvertisedEndpoints, endpoints); + assert.equal(statusReads, 1); + }), + {}, + layerMockSpawner(`{"Self":{"TailscaleIPs":["100.74.126.34"]}}`, () => { + statusReads += 1; + }), + ); + }); + it.effect("falls back to local-only without losing the requested network preference", () => withHarness( emptyNetworkInterfaces, @@ -167,20 +191,6 @@ describe("DesktopServerExposure", () => { ), ); - it.effect("returns a typed error when network access is explicitly unavailable", () => - withHarness( - emptyNetworkInterfaces, - Effect.gen(function* () { - const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - yield* serverExposure.configureFromSettings({ port: 4173 }); - - const error = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip); - assert.ok(error._tag === "DesktopServerExposureNoNetworkAddressError"); - assert.equal(error.port, 4173); - }), - ), - ); - it.effect("persists network-accessible mode and updates backend binding state", () => withHarness( lanNetworkInterfaces, @@ -228,22 +238,6 @@ describe("DesktopServerExposure", () => { ), ); - it.effect("keeps a host bridge's LAN address ahead of later adapters", () => - withHarness( - { - vmbr0: [{ address: "192.168.1.30", family: "IPv4", internal: false }], - enx00e04c680001: [{ address: "192.168.42.10", family: "IPv4", internal: false }], - }, - Effect.gen(function* () { - const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - yield* serverExposure.configureFromSettings({ port: 4173 }); - - const change = yield* serverExposure.setMode("network-accessible"); - assert.equal(change.state.advertisedHost, "192.168.1.30"); - }), - ), - ); - it.effect("persists tailscale serve preferences atomically and reports no-op updates", () => withHarness( emptyNetworkInterfaces, @@ -275,71 +269,6 @@ describe("DesktopServerExposure", () => { ), ); - it.effect("preserves persistence request context and the settings failure chain", () => { - const diskFailure = new Error("disk exploded"); - const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({ - operation: "replace-settings-file", - path: "/tmp/desktop-settings.json", - cause: diskFailure, - }); - const layerSettings = Layer.succeed(DesktopAppSettings.DesktopAppSettings, { - get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS), - load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS), - setMainWindowBounds: () => Effect.die("unexpected main window bounds update"), - setServerExposureMode: () => Effect.fail(settingsFailure), - setTailscaleServe: () => Effect.fail(settingsFailure), - setUpdateChannel: () => Effect.die("unexpected update channel change"), - setWslBackendEnabled: () => Effect.die("unexpected WSL backend toggle"), - setWslDistro: () => Effect.die("unexpected WSL distro change"), - setWslOnly: () => Effect.die("unexpected WSL-only toggle"), - setLocalEnvironmentEnabled: () => Effect.die("unexpected local environment toggle"), - applyWslWindowsFallback: Effect.die("unexpected WSL Windows fallback"), - applyWslWindowsFallbackInMemory: Effect.die("unexpected WSL Windows fallback"), - } satisfies DesktopAppSettings.DesktopAppSettings["Service"]); - - return withHarness( - lanNetworkInterfaces, - Effect.gen(function* () { - const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - yield* serverExposure.configureFromSettings({ port: 4173 }); - - const modeError = yield* serverExposure.setMode("network-accessible").pipe(Effect.flip); - assert.instanceOf( - modeError, - DesktopServerExposure.DesktopServerExposureModePersistenceError, - ); - assert.equal(modeError.mode, "network-accessible"); - assert.strictEqual(modeError.cause, settingsFailure); - assert.strictEqual(modeError.cause.cause, diskFailure); - assert.equal( - modeError.message, - "Failed to persist desktop server exposure mode network-accessible.", - ); - assert.notInclude(modeError.message, diskFailure.message); - - const tailscaleError = yield* serverExposure - .setTailscaleServeEnabled({ enabled: true, port: 8443 }) - .pipe(Effect.flip); - assert.instanceOf( - tailscaleError, - DesktopServerExposure.DesktopTailscaleServePersistenceError, - ); - assert.equal(tailscaleError.enabled, true); - assert.equal(tailscaleError.port, 8443); - assert.strictEqual(tailscaleError.cause, settingsFailure); - assert.strictEqual(tailscaleError.cause.cause, diskFailure); - assert.equal( - tailscaleError.message, - "Failed to persist desktop Tailscale Serve settings (enabled: true, port: 8443).", - ); - assert.notInclude(tailscaleError.message, diskFailure.message); - }), - {}, - undefined, - layerSettings, - ); - }); - it.effect("keeps a Tailscale Serve change made while a mode change is saving", () => Effect.gen(function* () { const modeWriteStarted = yield* Deferred.make(); @@ -431,22 +360,64 @@ describe("DesktopServerExposure", () => { ), ); - it.effect("does not spawn the tailscale CLI while server exposure is local-only", () => - withHarness( - lanNetworkInterfaces, - Effect.gen(function* () { - const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - yield* serverExposure.configureFromSettings({ port: 4173 }); - - const endpoints = yield* serverExposure.getAdvertisedEndpoints; - assert.deepEqual( - endpoints.map((endpoint) => endpoint.httpBaseUrl), - ["http://127.0.0.1:4173/"], - ); - }), - {}, - layerDieOnSpawn(), - ), + it.effect( + "refreshes Tailscale status when addresses change and caches unchanged addresses", + () => { + const networkInterfaces: Record< + string, + readonly DesktopNetworkInterfaces.DesktopNetworkInterfaceInfo[] | undefined + > = { ...lanNetworkInterfaces }; + let statusJson = "{}"; + let statusReads = 0; + + return withHarness( + networkInterfaces, + Effect.gen(function* () { + const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; + yield* serverExposure.configureFromSettings({ port: 4173 }); + yield* serverExposure.setMode("network-accessible"); + + const initial = yield* serverExposure.getAdvertisedEndpoints; + assert.deepEqual( + initial.map((endpoint) => endpoint.httpBaseUrl), + ["http://127.0.0.1:4173/", "http://192.168.1.20:4173/"], + ); + assert.equal(statusReads, 1); + + for (const [address, dnsName] of [ + ["100.90.1.2", "desktop.tail.ts.net"], + ["100.90.1.3", "desktop.other-tail.ts.net"], + ] as const) { + networkInterfaces.vpn0 = [{ address, family: "IPv4", internal: false }]; + statusJson = JSON.stringify({ + Self: { DNSName: `${dnsName}.`, TailscaleIPs: [address] }, + }); + const previousReads = statusReads; + + const endpoints = yield* serverExposure.getAdvertisedEndpoints; + assert.deepEqual( + endpoints.map((endpoint) => endpoint.httpBaseUrl), + [ + "http://127.0.0.1:4173/", + "http://192.168.1.20:4173/", + `http://${address}:4173/`, + `https://${dnsName}/`, + ], + ); + assert.equal(statusReads, previousReads + 1); + assert.deepEqual(yield* serverExposure.getAdvertisedEndpoints, endpoints); + assert.equal(statusReads, previousReads + 1); + } + }), + {}, + layerMockSpawner( + () => statusJson, + () => { + statusReads += 1; + }, + ), + ); + }, ); it.effect("preserves explicit Tailscale exposure overrides", () => @@ -472,104 +443,4 @@ describe("DesktopServerExposure", () => { }, ), ); - - it.effect("advertises loopback, LAN, and configured manual endpoints from runtime state", () => - withHarness( - lanNetworkInterfaces, - Effect.gen(function* () { - const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - yield* serverExposure.configureFromSettings({ port: 3773 }); - yield* serverExposure.setMode("network-accessible"); - - const endpoints = yield* serverExposure.getAdvertisedEndpoints; - assert.deepEqual(endpoints, [ - { - id: "desktop-loopback:3773", - label: "This machine", - provider: { - id: "desktop-core", - label: "Desktop", - kind: "core", - isAddon: false, - }, - httpBaseUrl: "http://127.0.0.1:3773/", - wsBaseUrl: "ws://127.0.0.1:3773/", - reachability: "loopback", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-core", - status: "available", - description: "Loopback endpoint for this desktop app.", - }, - { - id: "desktop-lan:http://192.168.1.20:3773", - label: "Local network", - provider: { - id: "desktop-core", - label: "Desktop", - kind: "core", - isAddon: false, - }, - httpBaseUrl: "http://192.168.1.20:3773/", - wsBaseUrl: "ws://192.168.1.20:3773/", - reachability: "lan", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-core", - status: "available", - isDefault: true, - description: "Reachable from devices on the same network.", - }, - { - id: "manual:https://desktop.example.ts.net", - label: "Custom HTTPS", - provider: { - id: "manual", - label: "Manual", - kind: "manual", - isAddon: false, - }, - httpBaseUrl: "https://desktop.example.ts.net/", - wsBaseUrl: "wss://desktop.example.ts.net/", - reachability: "public", - compatibility: { - hostedHttpsApp: "compatible", - desktopApp: "compatible", - }, - source: "user", - status: "unknown", - description: "User-configured HTTPS endpoint for this desktop backend.", - }, - { - id: "manual:http://desktop.example.test:3773", - label: "Custom endpoint", - provider: { - id: "manual", - label: "Manual", - kind: "manual", - isAddon: false, - }, - httpBaseUrl: "http://desktop.example.test:3773/", - wsBaseUrl: "ws://desktop.example.test:3773/", - reachability: "public", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "user", - status: "unknown", - description: "User-configured endpoint for this desktop backend.", - }, - ]); - }), - { - T3CODE_DESKTOP_HTTPS_ENDPOINTS: - "https://desktop.example.ts.net,http://desktop.example.test:3773,not-a-url", - }, - ), - ); }); diff --git a/apps/desktop/src/backend/DesktopServerExposure.ts b/apps/desktop/src/backend/DesktopServerExposure.ts index d17d244eb1cd3..8d178c605c4a6 100644 --- a/apps/desktop/src/backend/DesktopServerExposure.ts +++ b/apps/desktop/src/backend/DesktopServerExposure.ts @@ -10,6 +10,7 @@ import { type DesktopServerExposureState, } from "@t3tools/contracts"; import { isTailscaleIpv4Address, readTailscaleStatus } from "@t3tools/tailscale"; +import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -70,15 +71,7 @@ const isUsableLanIpv4Address = (address: string): boolean => !address.startsWith("169.254.") && !isTailscaleIpv4Address(address); -/** - * Bridges, tunnels and VM adapters whose private address other devices on the - * LAN usually cannot reach: macOS's Thunderbolt Bridge (`bridge0`, which can - * keep a manual address while nothing is plugged in) and Internet Sharing - * bridges, VPN tunnels, and container or VM networks. Their addresses are only - * advertised when no other interface has one. Host bridges such as `br0`, - * Proxmox's `vmbr0` and Hyper-V's `vEthernet` external switches often carry - * the LAN address, so they are not listed. - */ +// Private bridges and VM adapters are fallbacks; host bridges can carry the real LAN address. const HOST_ONLY_INTERFACE = /^(bridge\d|utun|ipsec|ppp|tun|tap|wg|docker|br-|veth|virbr|vmnet|vboxnet|VirtualBox|VMware)/; @@ -416,12 +409,31 @@ function resolveRuntimeState(input: { }; } +const tailscaleIpv4AddressKey = ( + networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces, +): string => + [ + ...new Set( + Object.values(networkInterfaces) + .flatMap((addresses) => addresses ?? []) + .filter( + (address) => + !address.internal && + address.family === "IPv4" && + isTailscaleIpv4Address(address.address), + ) + .map((address) => address.address), + ), + ] + .toSorted() + .join(","); + const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): boolean => previous.port !== next.port || previous.bindHost !== next.bindHost || previous.localHttpUrl !== next.localHttpUrl; -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const config = yield* DesktopConfig.DesktopConfig; const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces; @@ -429,22 +441,20 @@ export const make = Effect.gen(function* () { const httpClient = yield* HttpClient.HttpClient; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; const stateRef = yield* Ref.make(initialRuntimeState()); - // Each change reads the runtime state, persists settings, then writes the - // state back. Run them one at a time so a change never writes over another - // with values it read before that change persisted. + // Serialize read-persist-write changes so stale runtime state cannot overwrite another update. const changePermit = yield* Semaphore.make(1); - // Cache the `tailscale status` spawn for the TTL. On macOS, the Mac App - // Store Tailscale CLI lives inside Tailscale's sandbox container, so each - // spawn re-triggers the "Other apps" TCC prompt. - const cachedReadMagicDnsName = yield* Effect.cachedWithTTL( - readTailscaleStatus.pipe( - Effect.map((status) => status.magicDnsName), - Effect.orElseSucceed(() => null), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - ), - TAILSCALE_STATUS_CACHE_TTL, - ); + // Key status by interface addresses so network changes bypass stale DNS and + // identity. Cache unchanged addresses to avoid repeated macOS TCC prompts. + const tailscaleStatusCache = yield* Cache.make({ + capacity: 1, + timeToLive: TAILSCALE_STATUS_CACHE_TTL, + lookup: (_addresses: string) => + readTailscaleStatus.pipe( + Effect.orElseSucceed(() => null), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), + ), + }); const readNetworkInterfaces = networkInterfaces.read; @@ -553,9 +563,7 @@ export const make = Effect.gen(function* () { customHttpsEndpointUrls: config.desktopHttpsEndpointUrls, }); - // Don't spawn the Tailscale CLI when the user hasn't opted into any - // network exposure. The spawn itself triggers a macOS "Other apps" - // TCC prompt on Mac App Store Tailscale builds. + // Spawning Mac App Store Tailscale can prompt for TCC access even when exposure is disabled. if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) { return coreEndpoints; } @@ -565,7 +573,10 @@ export const make = Effect.gen(function* () { serveEnabled: state.tailscaleServeEnabled, servePort: state.tailscaleServePort, networkInterfaces: currentNetworkInterfaces, - readMagicDnsName: cachedReadMagicDnsName, + readStatus: Cache.get( + tailscaleStatusCache, + tailscaleIpv4AddressKey(currentNetworkInterfaces), + ), }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), Effect.provideService(HttpClient.HttpClient, httpClient), diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts index 2c0055a0668d5..054655917cecc 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts @@ -4,10 +4,7 @@ import * as Layer from "effect/Layer"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; -import { - parseTailscaleMagicDnsName, - resolveTailscaleAdvertisedEndpoints, -} from "./tailscaleEndpointProvider.ts"; +import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts"; const layerUnusedTailscaleExternalServices = Layer.mergeAll( Layer.succeed( @@ -20,134 +17,66 @@ const layerUnusedTailscaleExternalServices = Layer.mergeAll( ), ); -describe("tailscale endpoint provider", () => { - it.effect("parses MagicDNS names from tailscale status", () => - Effect.gen(function* () { - const dnsName = yield* parseTailscaleMagicDnsName( - `{"Self":{"DNSName":"desktop.tail.ts.net."}}`, - ); - assert.equal(dnsName, "desktop.tail.ts.net"); - assert.equal(yield* parseTailscaleMagicDnsName("{}"), null); - const malformed = yield* Effect.result(parseTailscaleMagicDnsName("not-json")); - assert.isTrue(malformed._tag === "Failure"); - }), - ); +const protonAndTailscaleInterfaces = { + pvpnksintrf1: [{ address: "100.85.0.1", family: "IPv4", internal: false }], + tailscale0: [{ address: "100.74.126.34", family: "IPv4", internal: false }], +}; - it.effect("resolves Tailscale endpoints as add-on advertised endpoints", () => +describe("tailscale endpoint provider", () => { + it.effect("does not advertise Proton's CGNAT address as a Tailscale pairing endpoint", () => Effect.gen(function* () { const endpoints = yield* resolveTailscaleAdvertisedEndpoints({ port: 3773, - networkInterfaces: { - tailscale0: [ - { - address: "100.100.100.100", - family: "IPv4", - internal: false, - netmask: "255.192.0.0", - cidr: "100.100.100.100/10", - mac: "00:00:00:00:00:00", - }, - ], - }, - statusJson: `{"Self":{"DNSName":"desktop.tail.ts.net."}}`, + networkInterfaces: protonAndTailscaleInterfaces, + statusJson: `{"Self":{"TailscaleIPs":["100.74.126.34"]}}`, }); - assert.deepEqual(endpoints, [ - { - id: "tailscale-ip:http://100.100.100.100:3773", - label: "Tailscale IP", - provider: { - id: "tailscale", - label: "Tailscale", - kind: "private-network", - isAddon: true, - }, - httpBaseUrl: "http://100.100.100.100:3773/", - wsBaseUrl: "ws://100.100.100.100:3773/", - reachability: "private-network", - compatibility: { - hostedHttpsApp: "mixed-content-blocked", - desktopApp: "compatible", - }, - source: "desktop-addon", - status: "available", - description: "Reachable from devices on the same Tailnet.", - }, - { - id: "tailscale-magicdns:https://desktop.tail.ts.net/", - label: "Tailscale HTTPS", - provider: { - id: "tailscale", - label: "Tailscale", - kind: "private-network", - isAddon: true, - }, - httpBaseUrl: "https://desktop.tail.ts.net/", - wsBaseUrl: "wss://desktop.tail.ts.net/", - reachability: "private-network", - compatibility: { - hostedHttpsApp: "requires-configuration", - desktopApp: "compatible", - }, - source: "desktop-addon", - status: "unavailable", - description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.", - }, - ]); + assert.deepEqual( + endpoints.map((endpoint) => endpoint.httpBaseUrl), + ["http://100.74.126.34:3773/"], + ); }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), ); - it.effect("uses an injected magic DNS name reader instead of spawning tailscale", () => + it.effect("keeps native Tailscale interfaces with missing, malformed, or stale status", () => Effect.gen(function* () { - let readerCalls = 0; - const endpoints = yield* resolveTailscaleAdvertisedEndpoints({ - port: 3773, - networkInterfaces: {}, - readMagicDnsName: Effect.sync(() => { - readerCalls += 1; - return "desktop.tail.ts.net"; - }), - }); - assert.equal(readerCalls, 1); - assert.deepEqual( - endpoints.map((endpoint) => endpoint.httpBaseUrl), - ["https://desktop.tail.ts.net/"], - ); + for (const interfaceName of ["tailscale0", "Tailscale"]) { + for (const statusJson of [null, "not-json", `{"Self":{"TailscaleIPs":[]}}`]) { + const endpoints = yield* resolveTailscaleAdvertisedEndpoints({ + port: 3773, + networkInterfaces: { + pvpnksintrf1: protonAndTailscaleInterfaces.pvpnksintrf1, + [interfaceName]: protonAndTailscaleInterfaces.tailscale0, + }, + statusJson, + }); + assert.deepEqual( + endpoints.map((endpoint) => endpoint.httpBaseUrl), + ["http://100.74.126.34:3773/"], + ); + } + } }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), ); it.effect( - "marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", + "recognizes a macOS Tailscale tunnel by its IPv6 address when status is unavailable", () => Effect.gen(function* () { const endpoints = yield* resolveTailscaleAdvertisedEndpoints({ port: 3773, - networkInterfaces: {}, - statusJson: `{"Self":{"DNSName":"desktop.tail.ts.net."}}`, - serveEnabled: true, - probe: () => Effect.succeed(true), - }); - assert.deepEqual(endpoints, [ - { - id: "tailscale-magicdns:https://desktop.tail.ts.net/", - label: "Tailscale HTTPS", - provider: { - id: "tailscale", - label: "Tailscale", - kind: "private-network", - isAddon: true, - }, - httpBaseUrl: "https://desktop.tail.ts.net/", - wsBaseUrl: "wss://desktop.tail.ts.net/", - reachability: "private-network", - compatibility: { - hostedHttpsApp: "compatible", - desktopApp: "compatible", - }, - source: "desktop-addon", - status: "available", - description: "HTTPS endpoint served by Tailscale Serve.", + networkInterfaces: { + utun3: [{ address: "100.85.0.1", family: "IPv4", internal: false }], + utun4: [ + { address: "100.74.126.34", family: "IPv4", internal: false }, + { address: "fd7a:115c:a1e0::1234", family: "IPv6", internal: false }, + ], }, - ]); + statusJson: null, + }); + assert.deepEqual( + endpoints.map((endpoint) => endpoint.httpBaseUrl), + ["http://100.74.126.34:3773/"], + ); }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), ); }); diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.ts index 7dff0b61b372d..4b75afccdb5bc 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.ts @@ -3,9 +3,10 @@ import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/co import { buildTailscaleHttpsBaseUrl, isTailscaleIpv4Address, - parseTailscaleMagicDnsName, + parseTailscaleStatus, probeTailscaleHttpsEndpoint, readTailscaleStatus, + type TailscaleStatus, } from "@t3tools/tailscale"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; @@ -14,8 +15,6 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import type { NetworkInterfaces } from "./DesktopNetworkInterfaces.ts"; -export { parseTailscaleMagicDnsName } from "@t3tools/tailscale"; - const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { id: "tailscale", label: "Tailscale", @@ -26,17 +25,31 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { function resolveTailscaleIpAdvertisedEndpoints(input: { readonly port: number; readonly networkInterfaces: NetworkInterfaces; + readonly status: TailscaleStatus | null; }): readonly AdvertisedEndpoint[] { const seen = new Set(); const endpoints: AdvertisedEndpoint[] = []; - for (const interfaceAddresses of Object.values(input.networkInterfaces)) { + for (const [interfaceName, interfaceAddresses] of Object.entries(input.networkInterfaces)) { if (!interfaceAddresses) continue; + // CGNAT is shared with other VPNs; adapter identity works without current CLI status. + const isTailscaleInterface = + /^tailscale(?:\d+|ipv[46])?$/iu.test(interfaceName) || + interfaceAddresses.some( + (address) => + !address.internal && + address.family === "IPv6" && + /^fd7a:115c:a1e0:/iu.test(address.address), + ); + for (const address of interfaceAddresses) { if (address.internal) continue; if (address.family !== "IPv4") continue; if (!isTailscaleIpv4Address(address.address)) continue; + if (!isTailscaleInterface && !input.status?.tailnetIpv4Addresses.includes(address.address)) { + continue; + } if (seen.has(address.address)) continue; seen.add(address.address); @@ -105,8 +118,8 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd readonly servePort?: number; readonly networkInterfaces: NetworkInterfaces; readonly statusJson?: string | null; - readonly readMagicDnsName?: Effect.Effect< - string | null, + readonly readStatus?: Effect.Effect< + TailscaleStatus | null, never, ChildProcessSpawner.ChildProcessSpawner >; @@ -116,23 +129,17 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd never, ChildProcessSpawner.ChildProcessSpawner | HttpClient.HttpClient > { - const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input); - const readDnsName = - input.readMagicDnsName ?? - readTailscaleStatus.pipe( - Effect.map((status) => status.magicDnsName), - Effect.orElseSucceed((): string | null => null), - ); - const dnsName = + const readStatus = + input.readStatus ?? readTailscaleStatus.pipe(Effect.orElseSucceed(() => null)); + const status = input.statusJson === undefined - ? yield* readDnsName + ? yield* readStatus : input.statusJson - ? yield* parseTailscaleMagicDnsName(input.statusJson).pipe( - Effect.orElseSucceed(() => null), - ) + ? yield* parseTailscaleStatus(input.statusJson).pipe(Effect.orElseSucceed(() => null)) : null; + const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints({ ...input, status }); const magicDnsEndpoint = yield* resolveTailscaleMagicDnsAdvertisedEndpoint({ - dnsName, + dnsName: status?.magicDnsName ?? null, serveEnabled: input.serveEnabled === true, ...(input.servePort === undefined ? {} : { servePort: input.servePort }), ...(input.probe === undefined ? {} : { probe: input.probe }), diff --git a/apps/desktop/src/boot.ts b/apps/desktop/src/boot.ts index a8abdad9bbc60..f2524f246c664 100644 --- a/apps/desktop/src/boot.ts +++ b/apps/desktop/src/boot.ts @@ -1,4 +1,2 @@ -// Enables the compile cache before the main bundle loads, so the cache also -// covers main.cjs itself. require("./compileCache.cjs"); require("./main.cjs"); diff --git a/apps/desktop/src/compileCache.ts b/apps/desktop/src/compileCache.ts index da0fd66f5e582..abf8918df2af0 100644 --- a/apps/desktop/src/compileCache.ts +++ b/apps/desktop/src/compileCache.ts @@ -3,10 +3,8 @@ import * as NodeModule from "node:module"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; -// Linux uses the user's cache dir because /tmp is shared between users; the macOS and Windows -// temp dirs are already per user. Skipped under AppImage: it mounts the app at a new -// /tmp/.mount_* path each launch, and Node keys entries by path, so every launch would miss -// and leave another copy behind. +// Linux /tmp is shared; macOS and Windows temp dirs are per user. +// AppImage mounts change paths each launch, so Node's path-keyed cache would miss and accumulate copies. try { if (!process.env.APPIMAGE) { const cacheRoot = diff --git a/apps/desktop/src/electron/ElectronApp.test.ts b/apps/desktop/src/electron/ElectronApp.test.ts deleted file mode 100644 index 84f37b6f5f537..0000000000000 --- a/apps/desktop/src/electron/ElectronApp.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import { beforeEach, vi } from "vite-plus/test"; - -const { - appendSwitchMock, - autoUpdaterOnMock, - autoUpdaterRemoveListenerMock, - exitMock, - getAppPathMock, - getSystemLocaleMock, - getVersionMock, - onMock, - quitMock, - relaunchMock, - removeListenerMock, - removeSwitchMock, - setAboutPanelOptionsMock, - setAppUserModelIdMock, - setAsDefaultProtocolClientMock, - setDesktopNameMock, - setDockIconMock, - setNameMock, - setPathMock, - whenReadyMock, -} = vi.hoisted(() => ({ - appendSwitchMock: vi.fn(), - autoUpdaterOnMock: vi.fn(), - autoUpdaterRemoveListenerMock: vi.fn(), - exitMock: vi.fn(), - getAppPathMock: vi.fn(() => "/app"), - getSystemLocaleMock: vi.fn(() => "en-GB"), - getVersionMock: vi.fn(() => "1.2.3"), - onMock: vi.fn(), - quitMock: vi.fn(), - relaunchMock: vi.fn(), - removeListenerMock: vi.fn(), - removeSwitchMock: vi.fn(), - setAboutPanelOptionsMock: vi.fn(), - setAppUserModelIdMock: vi.fn(), - setAsDefaultProtocolClientMock: vi.fn(() => true), - setDesktopNameMock: vi.fn(), - setDockIconMock: vi.fn(), - setNameMock: vi.fn(), - setPathMock: vi.fn(), - whenReadyMock: vi.fn(() => Promise.resolve()), -})); - -vi.mock("electron", () => ({ - autoUpdater: { - on: autoUpdaterOnMock, - removeListener: autoUpdaterRemoveListenerMock, - }, - app: { - commandLine: { - appendSwitch: appendSwitchMock, - removeSwitch: removeSwitchMock, - }, - dock: { - setIcon: setDockIconMock, - }, - getAppPath: getAppPathMock, - getSystemLocale: getSystemLocaleMock, - getVersion: getVersionMock, - isPackaged: true, - name: "T3 Code", - on: onMock, - quit: quitMock, - relaunch: relaunchMock, - removeListener: removeListenerMock, - runningUnderARM64Translation: false, - setAboutPanelOptions: setAboutPanelOptionsMock, - setAsDefaultProtocolClient: setAsDefaultProtocolClientMock, - setAppUserModelId: setAppUserModelIdMock, - setDesktopName: setDesktopNameMock, - setName: setNameMock, - setPath: setPathMock, - whenReady: whenReadyMock, - exit: exitMock, - }, -})); - -import * as ElectronApp from "./ElectronApp.ts"; - -describe("ElectronApp", () => { - beforeEach(() => { - appendSwitchMock.mockClear(); - autoUpdaterOnMock.mockClear(); - autoUpdaterRemoveListenerMock.mockClear(); - exitMock.mockClear(); - onMock.mockClear(); - quitMock.mockClear(); - relaunchMock.mockClear(); - removeListenerMock.mockClear(); - removeSwitchMock.mockClear(); - setPathMock.mockClear(); - }); - - it.effect("reads app metadata through the service", () => - Effect.gen(function* () { - const electronApp = yield* ElectronApp.ElectronApp; - const metadata = yield* electronApp.metadata; - - assert.deepEqual(metadata, { - appVersion: "1.2.3", - appPath: "/app", - isPackaged: true, - resourcesPath: process.resourcesPath, - runningUnderArm64Translation: false, - }); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("reads the OS locale through the service", () => - Effect.gen(function* () { - const electronApp = yield* ElectronApp.ElectronApp; - - assert.strictEqual(yield* electronApp.systemLocale, "en-GB"); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("normalizes POSIX-style locale identifiers that Intl rejects", () => - Effect.gen(function* () { - getSystemLocaleMock.mockImplementationOnce(() => "en_GB"); - const electronApp = yield* ElectronApp.ElectronApp; - - assert.strictEqual(yield* electronApp.systemLocale, "en-GB"); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("reports which app metadata property failed", () => - Effect.gen(function* () { - const cause = new Error("version unavailable"); - getVersionMock.mockImplementationOnce(() => { - throw cause; - }); - - const electronApp = yield* ElectronApp.ElectronApp; - const error = yield* electronApp.metadata.pipe(Effect.flip); - - assert.instanceOf(error, ElectronApp.ElectronAppMetadataReadError); - assert.strictEqual(error.property, "app-version"); - assert.strictEqual(error.cause, cause); - assert.strictEqual( - error.message, - 'Failed to read Electron app metadata property "app-version".', - ); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("preserves Electron readiness failures", () => - Effect.gen(function* () { - const cause = new Error("ready failed"); - whenReadyMock.mockRejectedValueOnce(cause); - - const electronApp = yield* ElectronApp.ElectronApp; - const error = yield* electronApp.whenReady.pipe(Effect.flip); - - assert.instanceOf(error, ElectronApp.ElectronAppWhenReadyError); - assert.strictEqual(error.isPackaged, true); - assert.strictEqual(error.cause, cause); - assert.strictEqual( - error.message, - "Failed to wait for the Electron app to become ready (packaged: true).", - ); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("scopes app event listeners", () => - Effect.gen(function* () { - const listener = vi.fn(); - - yield* Effect.scoped( - Effect.gen(function* () { - const electronApp = yield* ElectronApp.ElectronApp; - yield* electronApp.on("activate", listener); - }), - ); - - assert.deepEqual(onMock.mock.calls, [["activate", listener]]); - assert.deepEqual(removeListenerMock.mock.calls, [["activate", listener]]); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("scopes native updater quit listeners", () => - Effect.gen(function* () { - const listener = vi.fn(); - - yield* Effect.scoped( - Effect.gen(function* () { - const electronApp = yield* ElectronApp.ElectronApp; - yield* electronApp.onBeforeQuitForUpdate(listener); - }), - ); - - assert.deepEqual(autoUpdaterOnMock.mock.calls, [["before-quit-for-update", listener]]); - assert.deepEqual(autoUpdaterRemoveListenerMock.mock.calls, [ - ["before-quit-for-update", listener], - ]); - }).pipe(Effect.provide(ElectronApp.layer)), - ); - - it.effect("removes command-line switches through the service", () => - Effect.gen(function* () { - const electronApp = yield* ElectronApp.ElectronApp; - yield* electronApp.removeCommandLineSwitch("password-store"); - - assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]); - }).pipe(Effect.provide(ElectronApp.layer)), - ); -}); diff --git a/apps/desktop/src/electron/ElectronApp.ts b/apps/desktop/src/electron/ElectronApp.ts index 0aae1148a4828..7190c70aedc21 100644 --- a/apps/desktop/src/electron/ElectronApp.ts +++ b/apps/desktop/src/electron/ElectronApp.ts @@ -43,12 +43,7 @@ export class ElectronApp extends Context.Service< { readonly metadata: Effect.Effect; readonly name: Effect.Effect; - /** - * The OS locale, read from the operating system rather than from Chromium's - * resolved application locale — the packaged app ships only the `en-US` - * locale pak, so `app.getLocale()` and the renderer's `Intl` default are - * pinned to `en-US` however the machine is configured. - */ + /** Packaged builds ship only en-US; app.getLocale() and Intl defaults do not reflect the OS locale. */ readonly systemLocale: Effect.Effect; readonly whenReady: Effect.Effect; readonly requestSingleInstanceLock: Effect.Effect; @@ -98,7 +93,7 @@ const addScopedAppListener = >( }), ).pipe(Effect.asVoid); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = ElectronApp.of({ metadata: Effect.gen(function* () { const appVersion = yield* Effect.try({ @@ -127,9 +122,7 @@ export const make = ElectronApp.of({ }; }), name: Effect.sync(() => Electron.app.name), - // macOS derives this from NSLocale, which uses POSIX-style identifiers - // (`en_GB`). `Intl` rejects those outright rather than normalizing them, so - // the tag is normalized here rather than in the renderer that consumes it. + // NSLocale returns en_GB-style tags; Intl requires hyphens. systemLocale: Effect.sync(() => Electron.app.getSystemLocale().replace(/_/g, "-")), whenReady: Effect.gen(function* () { const isPackaged = Electron.app.isPackaged; diff --git a/apps/desktop/src/electron/ElectronDialog.test.ts b/apps/desktop/src/electron/ElectronDialog.test.ts deleted file mode 100644 index 2ed5a1f2f913a..0000000000000 --- a/apps/desktop/src/electron/ElectronDialog.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import type { BrowserWindow } from "electron"; -import { beforeEach, vi } from "vite-plus/test"; - -import * as ElectronDialog from "./ElectronDialog.ts"; - -const { showMessageBoxMock, showOpenDialogMock, showErrorBoxMock } = vi.hoisted(() => ({ - showMessageBoxMock: vi.fn(), - showOpenDialogMock: vi.fn(), - showErrorBoxMock: vi.fn(), -})); - -vi.mock("electron", () => ({ - dialog: { - showMessageBox: showMessageBoxMock, - showOpenDialog: showOpenDialogMock, - showErrorBox: showErrorBoxMock, - }, -})); - -describe("ElectronDialog", () => { - beforeEach(() => { - showMessageBoxMock.mockReset(); - showOpenDialogMock.mockReset(); - showErrorBoxMock.mockReset(); - }); - - it.effect("preserves folder picker request context and cause", () => - Effect.gen(function* () { - const cause = new Error("folder picker failed"); - const owner = { id: 7 } as BrowserWindow; - showOpenDialogMock.mockRejectedValue(cause); - const dialog = yield* ElectronDialog.ElectronDialog; - - const error = yield* Effect.flip( - dialog.pickFolder({ - owner: Option.some(owner), - defaultPath: Option.some("/workspace"), - }), - ); - - assert.instanceOf(error, ElectronDialog.ElectronDialogPickFolderError); - assert.strictEqual(error.ownerWindowId, 7); - assert.strictEqual(error.defaultPath, "/workspace"); - assert.strictEqual(error.cause, cause); - assert.include(error.message, "window 7"); - assert.include(error.message, "/workspace"); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(ElectronDialog.layer)), - ); - - it.effect("opens a single-file picker when multiple selections are disabled", () => - Effect.gen(function* () { - showOpenDialogMock.mockResolvedValue({ - canceled: false, - filePaths: ["/pictures/icon.png"], - }); - const dialog = yield* ElectronDialog.ElectronDialog; - - const paths = yield* dialog.pickFiles({ - owner: Option.none(), - defaultPath: Option.some("/project"), - filters: [{ name: "Images", extensions: ["png"] }], - multiple: false, - }); - - assert.deepEqual(paths, ["/pictures/icon.png"]); - assert.deepEqual(showOpenDialogMock.mock.calls, [ - [ - { - defaultPath: "/project", - filters: [{ name: "Images", extensions: ["png"] }], - properties: ["openFile"], - }, - ], - ]); - }).pipe(Effect.provide(ElectronDialog.layer)), - ); - - it.effect("preserves message box request context and cause", () => - Effect.gen(function* () { - const cause = new Error("message box failed"); - showMessageBoxMock.mockRejectedValue(cause); - const dialog = yield* ElectronDialog.ElectronDialog; - - const error = yield* Effect.flip( - dialog.showMessageBox({ - type: "warning", - title: "Unsaved changes", - message: "Discard changes?", - detail: "This cannot be undone.", - buttons: ["Cancel", "Discard"], - }), - ); - - assert.instanceOf(error, ElectronDialog.ElectronDialogShowMessageBoxError); - assert.strictEqual(error.type, "warning"); - assert.strictEqual(error.titleLength, "Unsaved changes".length); - assert.strictEqual(error.messageLength, "Discard changes?".length); - assert.strictEqual(error.detailLength, "This cannot be undone.".length); - assert.strictEqual(error.buttonCount, 2); - assert.notProperty(error, "title"); - assert.notProperty(error, "dialogMessage"); - assert.notProperty(error, "dialogDetail"); - assert.notProperty(error, "buttons"); - assert.strictEqual(error.cause, cause); - assert.include(error.message, "warning"); - assert.notInclude(error.message, "Unsaved changes"); - assert.notInclude(error.message, "Discard changes?"); - assert.notInclude(error.message, "This cannot be undone."); - assert.notInclude(error.message, "Cancel"); - assert.notInclude(error.message, "Discard"); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(ElectronDialog.layer)), - ); - - it.effect("preserves error box request context and cause in the defect", () => - Effect.gen(function* () { - const cause = new Error("error box failed"); - showErrorBoxMock.mockImplementation(() => { - throw cause; - }); - const dialog = yield* ElectronDialog.ElectronDialog; - - const exit = yield* Effect.exit(dialog.showErrorBox("Startup failed", "Could not start.")); - - assert.isTrue(exit._tag === "Failure"); - if (exit._tag === "Success") return; - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronDialog.ElectronDialogShowErrorBoxError); - assert.strictEqual(error.titleLength, "Startup failed".length); - assert.strictEqual(error.contentLength, "Could not start.".length); - assert.notProperty(error, "title"); - assert.notProperty(error, "content"); - assert.strictEqual(error.cause, cause); - assert.notInclude(error.message, "Startup failed"); - assert.notInclude(error.message, "Could not start."); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(ElectronDialog.layer)), - ); -}); diff --git a/apps/desktop/src/electron/ElectronDialog.ts b/apps/desktop/src/electron/ElectronDialog.ts index b48953f117d38..8f0df22016169 100644 --- a/apps/desktop/src/electron/ElectronDialog.ts +++ b/apps/desktop/src/electron/ElectronDialog.ts @@ -104,7 +104,7 @@ export class ElectronDialog extends Context.Service< } >()("@t3tools/desktop/electron/ElectronDialog") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = ElectronDialog.of({ pickFolder: Effect.fn("desktop.electron.dialog.pickFolder")(function* (input) { const ownerWindowId = Option.match(input.owner, { diff --git a/apps/desktop/src/electron/ElectronMenu.test.ts b/apps/desktop/src/electron/ElectronMenu.test.ts deleted file mode 100644 index 320988051e5f1..0000000000000 --- a/apps/desktop/src/electron/ElectronMenu.test.ts +++ /dev/null @@ -1,257 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Cause from "effect/Cause"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import type * as Electron from "electron"; -import { beforeEach, vi } from "vite-plus/test"; - -const { buildFromTemplateMock, createFromNamedImageMock, setApplicationMenuMock } = vi.hoisted( - () => ({ - buildFromTemplateMock: vi.fn(), - createFromNamedImageMock: vi.fn(), - setApplicationMenuMock: vi.fn(), - }), -); - -vi.mock("electron", () => ({ - Menu: { - buildFromTemplate: buildFromTemplateMock, - setApplicationMenu: setApplicationMenuMock, - }, - nativeImage: { - createFromNamedImage: createFromNamedImageMock, - }, -})); - -import * as ElectronMenu from "./ElectronMenu.ts"; - -const layerTest = ElectronMenu.layer.pipe( - Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), -); - -const makeWindow = (zoomFactor = 1): Electron.BrowserWindow => - ({ - id: 7, - webContents: { getZoomFactor: () => zoomFactor }, - }) as unknown as Electron.BrowserWindow; - -describe("ElectronMenu", () => { - beforeEach(() => { - buildFromTemplateMock.mockReset(); - createFromNamedImageMock.mockReset(); - setApplicationMenuMock.mockReset(); - }); - - it.effect("returns none without building a menu when there are no valid items", () => - Effect.gen(function* () { - const electronMenu = yield* ElectronMenu.ElectronMenu; - const selectedItemId = yield* electronMenu.showContextMenu({ - window: {} as Electron.BrowserWindow, - items: [], - position: Option.none(), - }); - - assert.isTrue(Option.isNone(selectedItemId)); - assert.equal(buildFromTemplateMock.mock.calls.length, 0); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("resolves with the clicked leaf item id", () => - Effect.gen(function* () { - buildFromTemplateMock.mockImplementation( - (template: Electron.MenuItemConstructorOptions[]) => ({ - popup: () => { - const firstItem = template[0]; - assert.isDefined(firstItem); - const click = firstItem.click; - if (!click) { - throw new Error("Expected menu item to have a click handler."); - } - click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent); - }, - }), - ); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - const selectedItemId = yield* electronMenu.showContextMenu({ - window: makeWindow(), - items: [{ id: "copy", label: "Copy" }], - position: Option.none(), - }); - - assert.equal(Option.getOrNull(selectedItemId), "copy"); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("resolves with none when the menu closes without a click", () => - Effect.gen(function* () { - let popupOptions: Electron.PopupOptions | undefined; - buildFromTemplateMock.mockImplementation(() => ({ - popup: (options: Electron.PopupOptions) => { - popupOptions = options; - options.callback?.(); - }, - })); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - const selectedItemId = yield* electronMenu.showContextMenu({ - window: makeWindow(2), - items: [ - { id: "copy", label: "Copy" }, - { id: "delete", label: "Delete", destructive: true, separatorBefore: true }, - ], - position: Option.some({ x: 10.8, y: 20.2 }), - }); - - assert.isTrue(Option.isNone(selectedItemId)); - assert.equal(popupOptions?.x, 21); - assert.equal(popupOptions?.y, 40); - assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], { - label: "Copy", - enabled: true, - click: buildFromTemplateMock.mock.calls[0]?.[0][0].click, - }); - assert.deepEqual( - buildFromTemplateMock.mock.calls[0]?.[0].map( - (item: Electron.MenuItemConstructorOptions) => item.type ?? item.label, - ), - ["Copy", "separator", "Delete"], - ); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("keeps a preceding non-destructive action in the destructive section", () => - Effect.gen(function* () { - buildFromTemplateMock.mockImplementation(() => ({ - popup: (options: Electron.PopupOptions) => options.callback?.(), - })); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - yield* electronMenu.showContextMenu({ - window: makeWindow(), - items: [ - { id: "copy", label: "Copy" }, - { id: "archive", label: "Archive", separatorBefore: true }, - { id: "delete", label: "Delete", destructive: true }, - ], - position: Option.none(), - }); - - assert.deepEqual( - buildFromTemplateMock.mock.calls[0]?.[0].map( - (item: Electron.MenuItemConstructorOptions) => item.type ?? item.label, - ), - ["Copy", "separator", "Archive", "Delete"], - ); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("defers popupTemplate side effects until the returned Effect runs", () => - Effect.gen(function* () { - const popupMock = vi.fn(); - buildFromTemplateMock.mockImplementation(() => ({ popup: popupMock })); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - const frame = { routingId: 7 } as Electron.WebFrameMain; - const popup = electronMenu.popupTemplate({ - window: {} as Electron.BrowserWindow, - template: [{ label: "Copy" }], - frame, - }); - - assert.equal(buildFromTemplateMock.mock.calls.length, 0); - assert.equal(popupMock.mock.calls.length, 0); - - yield* popup; - - assert.equal(buildFromTemplateMock.mock.calls.length, 1); - assert.equal(popupMock.mock.calls.length, 1); - assert.strictEqual(popupMock.mock.calls[0]?.[0].frame, frame); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("preserves application-menu failures as structured defects", () => - Effect.gen(function* () { - const cause = new Error("application menu build failed"); - buildFromTemplateMock.mockImplementationOnce(() => { - throw cause; - }); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - const exit = yield* Effect.exit( - electronMenu.setApplicationMenu([{ label: "File" }, { label: "Edit" }]), - ); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError); - assert.equal(error.operation, "set-application-menu"); - assert.equal(error.platform, "linux"); - assert.isNull(error.windowId); - assert.equal(error.itemCount, 2); - assert.strictEqual(error.cause, cause); - assert.notInclude(error.message, cause.message); - } - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("preserves popup-template failures with window context", () => - Effect.gen(function* () { - const cause = new Error("popup failed"); - buildFromTemplateMock.mockReturnValueOnce({ - popup: () => { - throw cause; - }, - }); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - const exit = yield* Effect.exit( - electronMenu.popupTemplate({ - window: { id: 41 } as Electron.BrowserWindow, - template: [{ label: "Copy" }], - }), - ); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError); - assert.equal(error.operation, "popup-template"); - assert.equal(error.windowId, 41); - assert.equal(error.itemCount, 1); - assert.strictEqual(error.cause, cause); - } - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("preserves context-menu failures with normalized item context", () => - Effect.gen(function* () { - const cause = new Error("context menu build failed"); - buildFromTemplateMock.mockImplementationOnce(() => { - throw cause; - }); - - const electronMenu = yield* ElectronMenu.ElectronMenu; - const exit = yield* Effect.exit( - electronMenu.showContextMenu({ - window: { id: 42 } as Electron.BrowserWindow, - items: [{ id: "copy", label: "Copy" }], - position: Option.none(), - }), - ); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronMenu.ElectronMenuOperationError); - assert.equal(error.operation, "show-context-menu"); - assert.equal(error.windowId, 42); - assert.equal(error.itemCount, 1); - assert.strictEqual(error.cause, cause); - } - }).pipe(Effect.provide(layerTest)), - ); -}); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 352a5bc97a21a..a58eb0c743fb0 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -68,8 +68,7 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM continue; } - // Header items are decorative section labels for the web fallback only — - // Electron's native menu has no equivalent affordance, so we skip them. + // Native menus cannot display the web fallback's decorative headers. if (sourceItem.header === true) { continue; } @@ -97,9 +96,7 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM return normalizedItems; } -// Renderer positions arrive in CSS pixels; popup() expects window points, so -// page zoom must be factored in or menus drift proportionally to their -// distance from the window origin. +// popup() takes window points; renderer CSS coordinates must account for page zoom. const normalizePosition = ( position: Option.Option, zoomFactor: number, @@ -112,7 +109,7 @@ const normalizePosition = ( Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })), ); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; let destructiveMenuIconCache: Option.Option | undefined; diff --git a/apps/desktop/src/electron/ElectronPowerMonitor.ts b/apps/desktop/src/electron/ElectronPowerMonitor.ts index 4fb42dfdc9f47..41c36acf2250a 100644 --- a/apps/desktop/src/electron/ElectronPowerMonitor.ts +++ b/apps/desktop/src/electron/ElectronPowerMonitor.ts @@ -75,7 +75,7 @@ const onSpeedLimitChange: ElectronPowerMonitor["Service"]["onSpeedLimitChange"] ).pipe(Effect.asVoid); }; -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = ElectronPowerMonitor.of({ isOnBatteryPower: Effect.sync(() => Electron.powerMonitor.isOnBatteryPower()), getSystemIdleTime: Effect.sync(() => Electron.powerMonitor.getSystemIdleTime()), diff --git a/apps/desktop/src/electron/ElectronProtocol.test.ts b/apps/desktop/src/electron/ElectronProtocol.test.ts index 315f6b5510a0f..45d1771f26f07 100644 --- a/apps/desktop/src/electron/ElectronProtocol.test.ts +++ b/apps/desktop/src/electron/ElectronProtocol.test.ts @@ -1,11 +1,8 @@ import { assert, describe, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as TestClock from "effect/testing/TestClock"; import { beforeEach, vi } from "vite-plus/test"; const { handleMock, netFetchMock, unhandleMock } = vi.hoisted(() => ({ @@ -156,172 +153,4 @@ describe("ElectronProtocol", () => { assert.equal(netFetchMock.mock.calls.length, 0); }).pipe(Effect.provide(layerProtocol)), ); - - it.effect("retries transient renderer target failures", () => - Effect.gen(function* () { - let handler: ((request: Request) => Promise) | undefined; - handleMock.mockImplementation((_scheme, nextHandler) => { - handler = nextHandler; - }); - netFetchMock - .mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733")) - .mockResolvedValueOnce(new Response("ready")); - - const response = yield* Effect.scoped( - Effect.gen(function* () { - const protocol = yield* ElectronProtocol.ElectronProtocol; - yield* protocol.registerDesktopProtocol({ - scheme: "t3code-dev", - targetOrigin: new URL("http://127.0.0.1:5733/"), - clerkFrontendApiHostname: undefined, - }); - const fiber = yield* Effect.forkChild( - Effect.promise(() => handler!(new Request("t3code-dev://app/"))), - ); - yield* TestClock.adjust("50 millis"); - return yield* Fiber.join(fiber); - }), - ); - - assert.equal(yield* Effect.promise(() => response.text()), "ready"); - assert.equal(netFetchMock.mock.calls.length, 2); - }).pipe(Effect.provide(layerProtocol)), - ); - - it.effect("rejects with the last renderer target failure after 50ms and 150ms retries", () => - Effect.gen(function* () { - let handler: ((request: Request) => Promise) | undefined; - handleMock.mockImplementation((_scheme, nextHandler) => { - handler = nextHandler; - }); - const lastFailure = new Error("connect ECONNREFUSED 127.0.0.1:5733 (3)"); - netFetchMock - .mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733 (1)")) - .mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733 (2)")) - .mockRejectedValueOnce(lastFailure); - - const rejection = yield* Effect.scoped( - Effect.gen(function* () { - const protocol = yield* ElectronProtocol.ElectronProtocol; - yield* protocol.registerDesktopProtocol({ - scheme: "t3code-dev", - targetOrigin: new URL("http://127.0.0.1:5733/"), - clerkFrontendApiHostname: undefined, - }); - const fiber = yield* Effect.forkChild( - Effect.promise(() => - handler!(new Request("t3code-dev://app/")).then( - () => null, - (error: unknown) => error, - ), - ), - ); - yield* TestClock.adjust("49 millis"); - assert.equal(netFetchMock.mock.calls.length, 1); - yield* TestClock.adjust("1 millis"); - assert.equal(netFetchMock.mock.calls.length, 2); - yield* TestClock.adjust("149 millis"); - assert.equal(netFetchMock.mock.calls.length, 2); - yield* TestClock.adjust("1 millis"); - return yield* Fiber.join(fiber); - }), - ); - - assert.strictEqual(rejection, lastFailure); - assert.equal(netFetchMock.mock.calls.length, 3); - }).pipe(Effect.provide(layerProtocol)), - ); - - it.effect("preserves protocol registration failures", () => - Effect.gen(function* () { - const cause = new Error("protocol registration failed"); - handleMock.mockImplementationOnce(() => { - throw cause; - }); - - const protocol = yield* ElectronProtocol.ElectronProtocol; - const error = yield* Effect.scoped( - protocol.registerDesktopProtocol({ - scheme: "t3code-dev", - targetOrigin: new URL("http://127.0.0.1:3773/"), - clerkFrontendApiHostname: undefined, - }), - ).pipe(Effect.flip); - - assert.instanceOf(error, ElectronProtocol.ElectronProtocolRegistrationError); - assert.equal(error.scheme, "t3code-dev"); - assert.strictEqual(error.cause, cause); - assert.equal(error.message, 'Failed to register Electron protocol scheme "t3code-dev".'); - }).pipe(Effect.provide(layerProtocol)), - ); - - it.effect("preserves protocol unregistration failures", () => - Effect.gen(function* () { - const cause = new Error("protocol unregistration failed"); - unhandleMock.mockImplementationOnce(() => { - throw cause; - }); - - const protocol = yield* ElectronProtocol.ElectronProtocol; - const exit = yield* Effect.exit( - Effect.scoped( - protocol.registerDesktopProtocol({ - scheme: "t3code", - targetOrigin: new URL("http://127.0.0.1:3773/"), - clerkFrontendApiHostname: undefined, - }), - ), - ); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronProtocol.ElectronProtocolUnregistrationError); - assert.equal(error.scheme, "t3code"); - assert.strictEqual(error.cause, cause); - assert.equal(error.message, 'Failed to unregister Electron protocol scheme "t3code".'); - } - }).pipe(Effect.provide(layerProtocol)), - ); - - it("keeps executable sources host-restricted while allowing runtime network resources", () => { - const policy = ElectronProtocol.makeDesktopContentSecurityPolicy({ - scheme: "t3code", - targetOrigin: new URL("http://127.0.0.1:3773/"), - clerkFrontendApiHostname: "clerk.t3.codes", - }); - const directives = Object.fromEntries( - policy.split("; ").map((directive) => { - const [name, ...sources] = directive.split(" "); - return [name, sources]; - }), - ); - - assert.deepEqual(directives["script-src"], [ - "'self'", - "'unsafe-inline'", - "'wasm-unsafe-eval'", - "https://clerk.t3.codes", - "https://challenges.cloudflare.com", - ]); - assert.deepEqual(directives["connect-src"], [ - "'self'", - "blob:", - "http:", - "https:", - "ws:", - "wss:", - ]); - assert.deepEqual(directives["img-src"], [ - "'self'", - "t3code:", - "blob:", - "data:", - "http:", - "https:", - ]); - assert.deepEqual(directives["media-src"], ["'self'", "t3code:", "blob:", "http:", "https:"]); - assert.deepEqual(directives["frame-src"], ["'self'", "blob:", "http:", "https:"]); - assert.deepEqual(directives["font-src"], ["'self'", "t3code:", "data:"]); - }); }); diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 21cf8994800b2..d84b6f360c89e 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -66,7 +66,7 @@ export class ElectronProtocol extends Context.Service< } >()("@t3tools/desktop/electron/ElectronProtocol") {} -export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string { +function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrationInput): string { const clerkOrigin = input.clerkFrontendApiHostname ? `https://${input.clerkFrontendApiHostname}` : undefined; @@ -78,11 +78,8 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat "https://challenges.cloudflare.com", ]; - // The renderer connects directly to user-configured environments in addition to - // the build-configured Clerk, relay, and OTLP endpoints. Those environment - // origins are not known when this response policy is created, so restrict - // connections by the network schemes the client supports instead of by host. - // GLTFLoader fetches embedded textures through blob URLs after parsing the model. + // User-configured environment origins are unknown here, so allow supported network schemes. + // GLTFLoader fetches embedded textures through blob URLs. const connectSources = ["'self'", "blob:", "http:", "https:", "ws:", "wss:"]; return [ @@ -95,6 +92,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat `font-src 'self' ${input.scheme}: data:`, "worker-src 'self' blob:", "frame-src 'self' blob: http: https:", + "object-src 'self' blob: http: https:", "form-action 'self'", ].join("; "); } @@ -109,9 +107,7 @@ function withContentSecurityPolicy(response: Response, policy: string): Response }); } -/** - * Must run synchronously during process bootstrap, before Electron emits `ready`. - */ +// Must run synchronously before Electron emits ready. function registerDesktopSchemePrivilegesSync(): void { Electron.protocol.registerSchemesAsPrivileged([ { @@ -122,8 +118,7 @@ function registerDesktopSchemePrivilegesSync(): void { supportFetchAPI: true, corsEnabled: true, stream: true, - // Custom schemes skip Chromium's V8 code cache unless they opt in. - // Dev stays off: Vite serves changing code at stable URLs. + // Custom schemes must opt into V8 caching; dev URLs serve changing code. codeCache: true, }, }, @@ -245,7 +240,7 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* ( }); }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const registered = yield* Ref.make(false); const context = yield* Effect.context(); diff --git a/apps/desktop/src/electron/ElectronSafeStorage.ts b/apps/desktop/src/electron/ElectronSafeStorage.ts index cd01613d92fd0..0395d20e9bd38 100644 --- a/apps/desktop/src/electron/ElectronSafeStorage.ts +++ b/apps/desktop/src/electron/ElectronSafeStorage.ts @@ -65,7 +65,7 @@ export class ElectronSafeStorage extends Context.Service< } >()("@t3tools/desktop/electron/ElectronSafeStorage") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; diff --git a/apps/desktop/src/electron/ElectronShell.test.ts b/apps/desktop/src/electron/ElectronShell.test.ts index 580a8b95684db..0e72a46146e0a 100644 --- a/apps/desktop/src/electron/ElectronShell.test.ts +++ b/apps/desktop/src/electron/ElectronShell.test.ts @@ -24,84 +24,18 @@ describe("ElectronShell", () => { writeTextMock.mockReset(); }); - it.effect("opens safe external URLs", () => - Effect.gen(function* () { - openExternalMock.mockResolvedValue(undefined); - - const electronShell = yield* ElectronShell.ElectronShell; - const result = yield* electronShell.openExternal("https://example.com/path"); - - assert.equal(result, true); - assert.deepEqual(openExternalMock.mock.calls, [["https://example.com/path"]]); - }).pipe(Effect.provide(ElectronShell.layer)), - ); - - it.effect("copies text to the system clipboard", () => - Effect.gen(function* () { - writeTextMock.mockResolvedValue(undefined); - - const electronShell = yield* ElectronShell.ElectronShell; - yield* electronShell.copyText("https://example.com/path"); - - assert.deepEqual(writeTextMock.mock.calls, [["https://example.com/path"]]); - }).pipe(Effect.provide(ElectronShell.layer)), - ); - - it.effect("does not fail when the clipboard write rejects", () => - Effect.gen(function* () { - writeTextMock.mockRejectedValue(new Error("write failed")); - - const electronShell = yield* ElectronShell.ElectronShell; - yield* electronShell.copyText("https://example.com/path"); - - assert.deepEqual(writeTextMock.mock.calls, [["https://example.com/path"]]); - }).pipe(Effect.provide(ElectronShell.layer)), - ); - - it.effect("opens the Full Disk Access settings anchor", () => - Effect.gen(function* () { - openExternalMock.mockResolvedValue(undefined); - - const electronShell = yield* ElectronShell.ElectronShell; - const result = yield* electronShell.openSystemSettings("full-disk-access"); - - assert.equal(result, true); - assert.deepEqual(openExternalMock.mock.calls, [ - ["x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?Privacy_AllFiles"], - ]); - }).pipe(Effect.provide(ElectronShell.layer)), - ); - it.effect("opens remote SSH editor URLs", () => Effect.gen(function* () { openExternalMock.mockResolvedValue(undefined); const electronShell = yield* ElectronShell.ElectronShell; const result = yield* electronShell.openExternal( - "vscode://vscode-remote/ssh-remote+example.com/home/user/project", + "vscode://vscode-remote/ssh-remote+user%40example.com/home/user/project", ); assert.equal(result, true); assert.deepEqual(openExternalMock.mock.calls, [ - ["vscode://vscode-remote/ssh-remote+example.com/home/user/project"], - ]); - }).pipe(Effect.provide(ElectronShell.layer)), - ); - - it.effect("opens Zed's ssh deep link", () => - Effect.gen(function* () { - openExternalMock.mockResolvedValue(undefined); - - const electronShell = yield* ElectronShell.ElectronShell; - const results = yield* Effect.all([ - electronShell.openExternal("zed://ssh/example.com/home/user/project"), - electronShell.openExternal("zed://ssh/example.com/"), - ]); - - assert.deepEqual(results, [true, true]); - assert.deepEqual(openExternalMock.mock.calls, [ - ["zed://ssh/example.com/home/user/project"], - ["zed://ssh/example.com/"], + ["vscode://vscode-remote/ssh-remote+user%40example.com/home/user/project"], ]); }).pipe(Effect.provide(ElectronShell.layer)), ); @@ -111,7 +45,7 @@ describe("ElectronShell", () => { openExternalMock.mockResolvedValue(undefined); const url = - "jetbrains://gateway/ssh/environment?h=example.com&launchIde=true&ideHint=IU&projectHint=%2Fhome%2Fuser%2Fproject"; + "jetbrains://gateway/ssh/environment?h=example.com&launchIde=true&ideHint=IU&projectHint=%2Fhome%2Fuser%2Fproject&u=user"; const electronShell = yield* ElectronShell.ElectronShell; const result = yield* electronShell.openExternal(url); @@ -150,7 +84,7 @@ describe("ElectronShell", () => { electronShell.openExternal( "vscode://:secret@vscode-remote/ssh-remote+example.com/home/user/project", ), - electronShell.openExternal("zed://ssh/user@example.com/home/user/project"), + electronShell.openExternal("zed://ssh/user:secret@example.com/home/user/project"), electronShell.openExternal("jetbrains://user@gateway/ssh/environment?h=example.com"), ]); @@ -168,29 +102,4 @@ describe("ElectronShell", () => { assert.equal(openExternalMock.mock.calls.length, 0); }).pipe(Effect.provide(ElectronShell.layer)), ); - - it.effect("does not open non-remote editor URLs", () => - Effect.gen(function* () { - openExternalMock.mockResolvedValue(undefined); - - const electronShell = yield* ElectronShell.ElectronShell; - const result = yield* electronShell.openExternal( - "vscode://ms-python.python/some-command?argument=attacker", - ); - - assert.equal(result, false); - assert.equal(openExternalMock.mock.calls.length, 0); - }).pipe(Effect.provide(ElectronShell.layer)), - ); - - it.effect("returns false when Electron rejects openExternal", () => - Effect.gen(function* () { - openExternalMock.mockRejectedValue(new Error("open failed")); - - const electronShell = yield* ElectronShell.ElectronShell; - const result = yield* electronShell.openExternal("https://example.com/path"); - - assert.equal(result, false); - }).pipe(Effect.provide(ElectronShell.layer)), - ); }); diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts index d6832c79eb806..a72963c2e258a 100644 --- a/apps/desktop/src/electron/ElectronShell.ts +++ b/apps/desktop/src/electron/ElectronShell.ts @@ -11,9 +11,7 @@ import * as Option from "effect/Option"; import * as Electron from "electron"; -// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`, -// `zed://ssh//`, `jetbrains://gateway/ssh/environment?h=…`) must -// reach the OS handler; every other non-web scheme stays blocked. +// Remote editor deep links must reach the OS handler. const SAFE_WEB_PROTOCOLS = new Set(["http:", "https:"]); const REMOTE_EDITOR_PROTOCOLS = new Set( REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => { @@ -22,8 +20,8 @@ const REMOTE_EDITOR_PROTOCOLS = new Set( }), ); -// Zed's host sits in the first path segment, so it needs its own userinfo ban. -const ZED_SSH_PATHNAME = /^\/[^/@:]+\/.*$/; +// Zed embeds [user@]host in the path; reject passwords and ports there. +const ZED_SSH_PATHNAME = /^\/(?:[^/@:]+@)?[^/@:]+\/.*$/; const isRemoteEditorUrl = (url: URL) => REMOTE_EDITOR_PROTOCOLS.has(url.protocol) && @@ -63,7 +61,7 @@ export class ElectronShell extends Context.Service< } >()("@t3tools/desktop/electron/ElectronShell") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = ElectronShell.of({ openExternal: (rawUrl) => Option.match(parseSafeExternalUrl(rawUrl), { diff --git a/apps/desktop/src/electron/ElectronTheme.test.ts b/apps/desktop/src/electron/ElectronTheme.test.ts deleted file mode 100644 index b4028930af661..0000000000000 --- a/apps/desktop/src/electron/ElectronTheme.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import { beforeEach, vi } from "vite-plus/test"; - -const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({ - onMock: vi.fn(), - removeListenerMock: vi.fn(), - themeState: { - shouldUseDarkColors: true, - themeSource: "system", - setSourceError: null as unknown, - }, -})); - -vi.mock("electron", () => ({ - nativeTheme: { - get shouldUseDarkColors() { - return themeState.shouldUseDarkColors; - }, - set themeSource(value: string) { - if (themeState.setSourceError !== null) { - throw themeState.setSourceError; - } - themeState.themeSource = value; - }, - on: onMock, - removeListener: removeListenerMock, - }, -})); - -import * as ElectronTheme from "./ElectronTheme.ts"; - -describe("ElectronTheme", () => { - beforeEach(() => { - onMock.mockClear(); - removeListenerMock.mockClear(); - themeState.shouldUseDarkColors = true; - themeState.themeSource = "system"; - themeState.setSourceError = null; - }); - - it.effect("scopes native theme update listeners", () => - Effect.gen(function* () { - const listener = vi.fn(); - - yield* Effect.scoped( - Effect.gen(function* () { - const electronTheme = yield* ElectronTheme.ElectronTheme; - yield* electronTheme.onUpdated(listener); - }), - ); - - assert.deepEqual(onMock.mock.calls, [["updated", listener]]); - assert.deepEqual(removeListenerMock.mock.calls, [["updated", listener]]); - }).pipe(Effect.provide(ElectronTheme.layer)), - ); - - it.effect("preserves the requested source and cause when setting the theme fails", () => - Effect.gen(function* () { - const cause = new Error("theme source failed"); - themeState.setSourceError = cause; - const electronTheme = yield* ElectronTheme.ElectronTheme; - - const error = yield* Effect.flip(electronTheme.setSource("dark")); - - assert.instanceOf(error, ElectronTheme.ElectronThemeSetSourceError); - assert.strictEqual(error.source, "dark"); - assert.strictEqual(error.cause, cause); - assert.include(error.message, "dark"); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(ElectronTheme.layer)), - ); -}); diff --git a/apps/desktop/src/electron/ElectronTheme.ts b/apps/desktop/src/electron/ElectronTheme.ts index 42cac98d0f538..a84eedda13b4e 100644 --- a/apps/desktop/src/electron/ElectronTheme.ts +++ b/apps/desktop/src/electron/ElectronTheme.ts @@ -28,7 +28,7 @@ export class ElectronTheme extends Context.Service< } >()("@t3tools/desktop/electron/ElectronTheme") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = ElectronTheme.of({ shouldUseDarkColors: Effect.sync(() => Electron.nativeTheme.shouldUseDarkColors), setSource: (theme) => diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts deleted file mode 100644 index 1e005d26fdf5d..0000000000000 --- a/apps/desktop/src/electron/ElectronUpdater.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import { beforeEach, vi } from "vite-plus/test"; - -const { autoUpdaterMock } = vi.hoisted(() => ({ - autoUpdaterMock: { - allowDowngrade: false, - allowPrerelease: false, - autoDownload: true, - autoInstallOnAppQuit: true, - channel: "latest", - disableDifferentialDownload: false, - fullChangelog: false, - checkForUpdates: vi.fn(() => Promise.resolve(null)), - downloadUpdate: vi.fn(() => Promise.resolve([])), - on: vi.fn(), - quitAndInstall: vi.fn(), - removeListener: vi.fn(), - setFeedURL: vi.fn(), - }, -})); - -vi.mock("electron-updater", () => ({ - autoUpdater: autoUpdaterMock, -})); - -import * as ElectronUpdater from "./ElectronUpdater.ts"; - -describe("ElectronUpdater", () => { - beforeEach(() => { - autoUpdaterMock.allowDowngrade = false; - autoUpdaterMock.allowPrerelease = false; - autoUpdaterMock.autoDownload = true; - autoUpdaterMock.autoInstallOnAppQuit = true; - autoUpdaterMock.channel = "latest"; - autoUpdaterMock.disableDifferentialDownload = false; - autoUpdaterMock.fullChangelog = false; - autoUpdaterMock.checkForUpdates.mockClear(); - autoUpdaterMock.checkForUpdates.mockImplementation(() => Promise.resolve(null)); - autoUpdaterMock.downloadUpdate.mockClear(); - autoUpdaterMock.downloadUpdate.mockImplementation(() => Promise.resolve([])); - autoUpdaterMock.on.mockClear(); - autoUpdaterMock.quitAndInstall.mockClear(); - autoUpdaterMock.removeListener.mockClear(); - autoUpdaterMock.setFeedURL.mockClear(); - }); - - it.effect("scopes updater event listeners", () => - Effect.gen(function* () { - const listener = vi.fn(); - - yield* Effect.scoped( - Effect.gen(function* () { - const updater = yield* ElectronUpdater.ElectronUpdater; - yield* updater.on("update-available", listener); - }), - ); - - assert.deepEqual(autoUpdaterMock.on.mock.calls, [["update-available", listener]]); - assert.deepEqual(autoUpdaterMock.removeListener.mock.calls, [["update-available", listener]]); - }).pipe(Effect.provide(ElectronUpdater.layer)), - ); - - it.effect("wraps rejected update checks in the method-specific typed error", () => - Effect.gen(function* () { - const cause = new Error("network unavailable"); - autoUpdaterMock.checkForUpdates.mockImplementationOnce(() => Promise.reject(cause)); - const updater = yield* ElectronUpdater.ElectronUpdater; - autoUpdaterMock.channel = "beta"; - - const error = yield* updater.checkForUpdates.pipe(Effect.flip); - - assert.instanceOf(error, ElectronUpdater.ElectronUpdaterCheckForUpdatesError); - assert.equal(error.channel, "beta"); - assert.strictEqual(error.cause, cause); - assert.equal(error.message, "Electron updater failed to check for updates on channel beta."); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(ElectronUpdater.layer)), - ); - - it.effect("preserves the execution-time channel on download failures", () => - Effect.gen(function* () { - const cause = new Error("download unavailable"); - autoUpdaterMock.downloadUpdate.mockImplementationOnce(() => Promise.reject(cause)); - const updater = yield* ElectronUpdater.ElectronUpdater; - autoUpdaterMock.channel = "nightly"; - - const error = yield* updater.downloadUpdate.pipe(Effect.flip); - - assert.instanceOf(error, ElectronUpdater.ElectronUpdaterDownloadUpdateError); - assert.equal(error.channel, "nightly"); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - "Electron updater failed to download the update on channel nightly.", - ); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(ElectronUpdater.layer)), - ); - - it.effect("sets full changelog mode", () => - Effect.gen(function* () { - const updater = yield* ElectronUpdater.ElectronUpdater; - - yield* updater.setFullChangelog(true); - assert.equal(autoUpdaterMock.fullChangelog, true); - - yield* updater.setFullChangelog(false); - assert.equal(autoUpdaterMock.fullChangelog, false); - }).pipe(Effect.provide(ElectronUpdater.layer)), - ); - - it.effect("preserves quit-and-install flags and the execution-time channel", () => - Effect.gen(function* () { - const cause = new Error("quit and install failed"); - autoUpdaterMock.quitAndInstall.mockImplementationOnce(() => { - throw cause; - }); - const updater = yield* ElectronUpdater.ElectronUpdater; - autoUpdaterMock.channel = "alpha"; - - const error = yield* updater - .quitAndInstall({ isSilent: true, isForceRunAfter: false }) - .pipe(Effect.flip); - - assert.instanceOf(error, ElectronUpdater.ElectronUpdaterQuitAndInstallError); - assert.equal(error.channel, "alpha"); - assert.equal(error.isSilent, true); - assert.equal(error.isForceRunAfter, false); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - "Electron updater failed to quit and install the update on channel alpha (silent: true, force run after: false).", - ); - assert.notInclude(error.message, cause.message); - assert.deepEqual(autoUpdaterMock.quitAndInstall.mock.calls, [[true, false]]); - }).pipe(Effect.provide(ElectronUpdater.layer)), - ); -}); diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index e42ebc1003ab4..397044932607b 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -80,7 +80,7 @@ export class ElectronUpdater extends Context.Service< } >()("@t3tools/desktop/electron/ElectronUpdater") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = ElectronUpdater.of({ setFeedURL: (options) => Effect.suspend(() => { diff --git a/apps/desktop/src/electron/ElectronWindow.module.test.ts b/apps/desktop/src/electron/ElectronWindow.module.test.ts deleted file mode 100644 index f272f84b5d825..0000000000000 --- a/apps/desktop/src/electron/ElectronWindow.module.test.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { expect, it, vi } from "vite-plus/test"; - -vi.mock("@crowecawcaw/xa11y", () => { - throw new Error("Cannot find native binding"); -}); - -it("loads without an accessibility native binding", async () => { - await expect(import("./ElectronWindow.ts")).resolves.toBeDefined(); -}); diff --git a/apps/desktop/src/electron/ElectronWindow.test.ts b/apps/desktop/src/electron/ElectronWindow.test.ts index ef94312ed6f06..4f17ca7e33010 100644 --- a/apps/desktop/src/electron/ElectronWindow.test.ts +++ b/apps/desktop/src/electron/ElectronWindow.test.ts @@ -62,13 +62,6 @@ const layerTestFor = (platform: NodeJS.Platform) => const layerTest = layerTestFor("linux"); -function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) { - return { - id: input.id, - isDestroyed: vi.fn(() => input.destroyed), - } as unknown as Electron.BrowserWindow; -} - function makeWindowsRevealWindow() { return { id: 41, @@ -109,341 +102,6 @@ describe("ElectronWindow", () => { windowsForegroundCloseMock.mockReset(); }); - it.effect("preserves schema-safe creation context and the Electron cause", () => - Effect.gen(function* () { - const cause = new Error("native BrowserWindow construction failed"); - browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() { - throw cause; - }); - const options = { - title: "T3 Code", - width: 1100, - height: 780, - minWidth: 840, - minHeight: 620, - show: false, - modal: false, - frame: true, - transparent: false, - backgroundColor: "#101010", - icon: {} as Electron.NativeImage, - webPreferences: { - preload: "/tmp/preload.js", - partition: "persist:t3code-preview-test", - sandbox: true, - contextIsolation: true, - nodeIntegration: false, - webviewTag: true, - spellcheck: true, - }, - } satisfies Electron.BrowserWindowConstructorOptions; - const electronWindow = yield* ElectronWindow.ElectronWindow; - - const error = yield* electronWindow.create(options).pipe(Effect.flip); - - assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError); - assert.deepEqual(error.options, { - title: "T3 Code", - width: 1100, - height: 780, - minWidth: 840, - minHeight: 620, - show: false, - modal: false, - frame: true, - transparent: false, - backgroundColor: "#101010", - webPreferences: { - preload: "/tmp/preload.js", - partition: "persist:t3code-preview-test", - backgroundThrottling: null, - sandbox: true, - contextIsolation: true, - nodeIntegration: false, - webviewTag: true, - }, - }); - assert.isFalse("icon" in error.options); - assert.isFalse("spellcheck" in error.options.webPreferences); - assert.strictEqual(error.cause, cause); - assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).'); - assert.notInclude(error.message, cause.message); - assert.deepEqual(browserWindowMock.mock.calls, [[options]]); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("skips windows destroyed before appearance sync runs", () => - Effect.gen(function* () { - const liveWindow = makeBrowserWindow({ id: 1, destroyed: false }); - const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true }); - getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]); - - const syncedWindows: Electron.BrowserWindow[] = []; - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.syncAllAppearance((window) => - Effect.sync(() => { - syncedWindows.push(window); - }), - ); - - assert.deepEqual(syncedWindows, [liveWindow]); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("preserves window enumeration failures as structured defects", () => - Effect.gen(function* () { - const cause = new Error("window enumeration failed"); - getAllWindowsMock.mockImplementationOnce(() => { - throw cause; - }); - - const electronWindow = yield* ElectronWindow.ElectronWindow; - const exit = yield* Effect.exit(electronWindow.currentMainOrFirst); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError); - assert.equal(error.operation, "list-windows"); - assert.equal(error.platform, "linux"); - assert.isNull(error.windowId); - assert.isNull(error.channel); - assert.strictEqual(error.cause, cause); - assert.notInclude(error.message, cause.message); - } - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("preserves reveal failures with the target window", () => - Effect.gen(function* () { - const cause = new Error("window restore failed"); - const window = { - id: 41, - isDestroyed: vi.fn(() => false), - isMinimized: vi.fn(() => true), - restore: vi.fn(() => { - throw cause; - }), - } as unknown as Electron.BrowserWindow; - - const electronWindow = yield* ElectronWindow.ElectronWindow; - const exit = yield* Effect.exit(electronWindow.reveal(window)); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError); - assert.equal(error.operation, "reveal-window"); - assert.equal(error.windowId, 41); - assert.isNull(error.channel); - assert.strictEqual(error.cause, cause); - } - }).pipe(Effect.provide(layerTest)), - ); - - it.effect("uses native Windows activation without querying the foreground window", () => - Effect.gen(function* () { - const operations: Array = []; - appFocusMock.mockImplementation(() => operations.push("app-focus")); - activateWindowsForegroundMock.mockImplementation(async () => { - operations.push("native-activation"); - }); - const window = { - ...makeWindowsRevealWindow(), - show: vi.fn(() => operations.push("show")), - moveTop: vi.fn(() => operations.push("move-top")), - focus: vi.fn(() => operations.push("focus")), - } as unknown as Electron.BrowserWindow; - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window); - - yield* electronWindow.reveal(window); - - assert.deepEqual(operations, ["app-focus", "show", "move-top", "focus", "native-activation"]); - assert.lengthOf(loadWindowsForegroundApiMock.mock.calls, 0); - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("focuses the exact T3 window before activating from a shell-hosted app", () => - Effect.gen(function* () { - const operations: Array = []; - shellHostedForegroundMock.mockResolvedValue(true); - windowsForegroundFocusMock.mockImplementation(async () => { - operations.push("native-focus"); - return true; - }); - activateWindowsForegroundMock.mockImplementation(async () => { - operations.push("native-activation"); - }); - const window = { - ...makeWindowsRevealWindow(), - show: vi.fn(() => operations.push("show")), - moveTop: vi.fn(() => operations.push("move-top")), - focus: vi.fn(() => operations.push("focus")), - } as unknown as Electron.BrowserWindow; - appFocusMock.mockImplementation(() => operations.push("app-focus")); - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window); - - yield* electronWindow.reveal(window); - - assert.deepEqual(operations, [ - "app-focus", - "show", - "move-top", - "focus", - "native-focus", - "native-activation", - ]); - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 1); - assert.deepEqual(windowsForegroundFocusMock.mock.calls, [ - [ - { - windowId: 41, - processId: process.pid, - title: "T3 Code (Dev)", - bounds: { x: 100, y: 50, width: 1_200, height: 800 }, - contentBounds: { x: 108, y: 50, width: 1_184, height: 792 }, - }, - ], - ]); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("prepares the exact T3 window before a capture overlay", () => - Effect.gen(function* () { - windowsForegroundPrepareMock.mockResolvedValue(true); - const window = makeWindowsRevealWindow(); - const electronWindow = yield* ElectronWindow.ElectronWindow; - - const prepared = yield* electronWindow.prepareReveal( - window as unknown as Electron.BrowserWindow, - ); - - assert.isTrue(prepared); - assert.deepEqual(windowsForegroundPrepareMock.mock.calls, [ - [ - { - windowId: 41, - processId: process.pid, - title: "T3 Code (Dev)", - bounds: { x: 100, y: 50, width: 1_200, height: 800 }, - contentBounds: { x: 108, y: 50, width: 1_184, height: 792 }, - }, - ], - ]); - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0); - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 0); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect.each([4, 8])( - "skips the focus worker only when the foreground matches the %i-byte HWND", - (handleBytes) => - Effect.gen(function* () { - const window = makeWindowsRevealWindow(); - activateWindowsForegroundMock.mockRejectedValueOnce( - new Error("Windows initially refused foreground activation"), - ); - const hwnd = handleBytes === 4 ? 0xf123_4567n : 0x1_f123_4567n; - const handle = Buffer.alloc(handleBytes); - if (handleBytes === 4) handle.writeUInt32LE(Number(hwnd)); - else handle.writeBigUInt64LE(hwnd); - window.getNativeWindowHandle.mockReturnValue(handle); - foregroundWindowMock.mockReturnValue(hwnd); - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); - window.getTitle.mockClear(); - - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - - assert.lengthOf(foregroundWindowMock.mock.calls, 1); - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0); - assert.lengthOf(window.getTitle.mock.calls, 0); - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect.each([42n, 0n])( - "focuses through the worker when the foreground HWND is %s instead of the target", - (foreground) => - Effect.gen(function* () { - const window = makeWindowsRevealWindow(); - activateWindowsForegroundMock.mockRejectedValueOnce( - new Error("Windows initially refused foreground activation"), - ); - foregroundWindowMock.mockReturnValue(foreground); - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); - - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 1); - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("continues native focus when the foreground query fails", () => - Effect.gen(function* () { - const window = makeWindowsRevealWindow(); - activateWindowsForegroundMock.mockRejectedValueOnce( - new Error("Windows initially refused foreground activation"), - ); - loadWindowsForegroundApiMock.mockRejectedValue(new Error("Foreground query unavailable")); - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); - - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 1); - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("does not fail reveal when native focus rejects", () => - Effect.gen(function* () { - const window = makeWindowsRevealWindow(); - activateWindowsForegroundMock.mockRejectedValueOnce( - new Error("Windows initially refused foreground activation"), - ); - windowsForegroundFocusMock.mockRejectedValue(new Error("Focus rejected")); - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); - - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 1); - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 2); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("fails reveal when Windows refuses foreground activation", () => - Effect.gen(function* () { - const cause = new Error("Windows refused foreground activation"); - const window = makeWindowsRevealWindow(); - activateWindowsForegroundMock.mockRejectedValue(cause); - const electronWindow = yield* ElectronWindow.ElectronWindow; - yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); - - const exit = yield* Effect.exit( - electronWindow.reveal(window as unknown as Electron.BrowserWindow), - ); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError); - assert.equal(error.operation, "reveal-window"); - assert.strictEqual(error.cause, cause); - } - assert.deepEqual(activateWindowsForegroundMock.mock.calls, [ - [window.getNativeWindowHandle.mock.results[0]?.value], - [window.getNativeWindowHandle.mock.results[1]?.value], - ]); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - it.effect("cancels native focus when destroyed during the foreground query", () => Effect.gen(function* () { const window = makeWindowsRevealWindow(); @@ -474,35 +132,6 @@ describe("ElectronWindow", () => { }).pipe(Effect.provide(layerTestFor("win32"))), ); - it.effect("preserves message delivery failures with window and channel context", () => - Effect.gen(function* () { - const cause = new Error("renderer send failed"); - const window = { - id: 42, - isDestroyed: vi.fn(() => false), - webContents: { - send: vi.fn(() => { - throw cause; - }), - }, - } as unknown as Electron.BrowserWindow; - getAllWindowsMock.mockReturnValueOnce([window]); - - const electronWindow = yield* ElectronWindow.ElectronWindow; - const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true })); - - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError); - assert.equal(error.operation, "send-window-message"); - assert.equal(error.windowId, 42); - assert.equal(error.channel, "desktop:update"); - assert.strictEqual(error.cause, cause); - } - }).pipe(Effect.provide(layerTest)), - ); - it.effect("preserves destroy failures and continues with later windows", () => Effect.gen(function* () { const cause = new Error("window destroy failed"); @@ -533,50 +162,4 @@ describe("ElectronWindow", () => { assert.equal(vi.mocked(laterWindow.destroy).mock.calls.length, 1); }).pipe(Effect.provide(layerTest)), ); - it.effect("an ordinary reveal on Windows does not touch the Win32 foreground helpers", () => - Effect.gen(function* () { - const window = makeWindowsRevealWindow(); - const electronWindow = yield* ElectronWindow.ElectronWindow; - - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 0); - assert.lengthOf(windowsForegroundFocusMock.mock.calls, 0); - assert.lengthOf(shellHostedForegroundMock.mock.calls, 0); - assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 0); - assert.lengthOf(window.focus.mock.calls, 1); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("a capture reveal on Windows uses the Win32 path only once", () => - Effect.gen(function* () { - const window = makeWindowsRevealWindow(); - const electronWindow = yield* ElectronWindow.ElectronWindow; - - yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - yield* electronWindow.reveal(window as unknown as Electron.BrowserWindow); - - assert.lengthOf(activateWindowsForegroundMock.mock.calls, 1); - assert.lengthOf(window.focus.mock.calls, 2); - }).pipe(Effect.provide(layerTestFor("win32"))), - ); - - it.effect("starts the Windows focus worker lazily and closes it with the layer", () => - Effect.gen(function* () { - yield* ElectronWindow.ElectronWindow.pipe(Effect.provide(layerTestFor("win32"))); - assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 0); - assert.lengthOf(windowsForegroundCloseMock.mock.calls, 0); - - yield* Effect.gen(function* () { - const electronWindow = yield* ElectronWindow.ElectronWindow; - const window = makeWindowsRevealWindow() as unknown as Electron.BrowserWindow; - yield* electronWindow.prepareReveal(window); - yield* electronWindow.prepareReveal(window); - assert.lengthOf(startWindowsForegroundFocusThreadMock.mock.calls, 1); - assert.lengthOf(windowsForegroundCloseMock.mock.calls, 0); - }).pipe(Effect.provide(layerTestFor("win32"))); - assert.lengthOf(windowsForegroundCloseMock.mock.calls, 1); - }), - ); }); diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index a7ab05303f72c..60908ee90dc89 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -127,11 +127,10 @@ export class ElectronWindow extends Context.Service< } >()("@t3tools/desktop/electron/ElectronWindow") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; - // The focus worker loads a native accessibility module. Start it on the first - // capture reveal so users who never capture pay nothing at launch. + // Lazy-load native accessibility on capture reveal to avoid startup cost for other users. let windowsForegroundFocus: ReturnType | undefined; const ensureWindowsForegroundFocus = () => { windowsForegroundFocus ??= startWindowsForegroundFocusThread( @@ -324,8 +323,9 @@ export const make = Effect.gen(function* () { cause, }), }).pipe(Effect.orDie), - sendAll: (channel, ...args) => - Effect.gen(function* () { + sendAll: + /* Window broadcasts run for streamed updates; avoid a span per broadcast. */ + Effect.fnUntraced(function* (channel, ...args) { for (const window of yield* listWindows) { if (yield* isWindowDestroyed(window)) { continue; diff --git a/apps/desktop/src/electron/WindowsForeground.test.ts b/apps/desktop/src/electron/WindowsForeground.test.ts index 3ac4b408f3768..60975495976cf 100644 --- a/apps/desktop/src/electron/WindowsForeground.test.ts +++ b/apps/desktop/src/electron/WindowsForeground.test.ts @@ -3,7 +3,6 @@ import { vi } from "vite-plus/test"; import { activateWindowsForegroundWithApi, - isWindowsShellHostedForegroundWithApi, type WindowsForegroundApi, } from "./WindowsForeground.ts"; @@ -55,66 +54,10 @@ describe("Windows foreground activation", () => { assert.deepEqual(api.setForegroundWindow.mock.calls, [[41n]]); }); - it("does not disturb input queues when T3 is already foreground", () => { - const api = makeApi({ foregroundWindow: 41n }); - - assert.isTrue(activateWindowsForegroundWithApi(nativeHandle(41n), api)); - - assert.lengthOf(api.getCurrentThreadId.mock.calls, 0); - assert.lengthOf(api.attachThreadInput.mock.calls, 0); - assert.lengthOf(api.setForegroundWindow.mock.calls, 0); - }); - - it("does not attach a thread to itself", () => { - const api = makeApi({ currentThreadId: 20, foregroundThreadId: 20 }); - - assert.isTrue(activateWindowsForegroundWithApi(nativeHandle(41n), api)); - - assert.lengthOf(api.attachThreadInput.mock.calls, 0); - assert.deepEqual(api.setForegroundWindow.mock.calls, [[41n]]); - }); - - it("uses SetForegroundWindow's result as the activation receipt", () => { - const api = makeApi({ activated: false }); - - assert.isFalse(activateWindowsForegroundWithApi(nativeHandle(41n), api)); - - assert.deepEqual(api.attachThreadInput.mock.calls, [ - [10, 20, true], - [10, 20, false], - ]); - }); - - it("still asks Windows directly when the input queues cannot be attached", () => { - const api = makeApi({ attached: false }); - - assert.isTrue(activateWindowsForegroundWithApi(nativeHandle(41n), api)); - - assert.deepEqual(api.attachThreadInput.mock.calls, [[10, 20, true]]); - assert.deepEqual(api.setForegroundWindow.mock.calls, [[41n]]); - }); - it("rejects malformed native handles", () => { const api = makeApi({}); assert.throws(() => activateWindowsForegroundWithApi(Buffer.alloc(6), api)); assert.lengthOf(api.getForegroundWindow.mock.calls, 0); }); - - it("recognizes a shell-hosted foreground window", () => { - const api = makeApi({}); - api.getWindowClassName.mockReturnValue("ApplicationFrameWindow"); - - assert.isTrue(isWindowsShellHostedForegroundWithApi(api)); - assert.deepEqual(api.getWindowClassName.mock.calls, [[99n]]); - }); - - it("does not classify ordinary or missing foreground windows as shell-hosted", () => { - const ordinary = makeApi({}); - const missing = makeApi({ foregroundWindow: 0n }); - - assert.isFalse(isWindowsShellHostedForegroundWithApi(ordinary)); - assert.isFalse(isWindowsShellHostedForegroundWithApi(missing)); - assert.lengthOf(missing.getWindowClassName.mock.calls, 0); - }); }); diff --git a/apps/desktop/src/electron/WindowsForeground.ts b/apps/desktop/src/electron/WindowsForeground.ts index 47ecd7fd71f8a..a124697e15bf2 100644 --- a/apps/desktop/src/electron/WindowsForeground.ts +++ b/apps/desktop/src/electron/WindowsForeground.ts @@ -54,7 +54,7 @@ export function activateWindowsForegroundWithApi( } } -export function isWindowsShellHostedForegroundWithApi(api: WindowsForegroundApi): boolean { +function isWindowsShellHostedForegroundWithApi(api: WindowsForegroundApi): boolean { const foregroundWindow = api.getForegroundWindow(); return ( foregroundWindow !== 0n && diff --git a/apps/desktop/src/electron/WindowsForegroundFocusThread.test.ts b/apps/desktop/src/electron/WindowsForegroundFocusThread.test.ts index 46193ca2c3417..ac15b145e0c6a 100644 --- a/apps/desktop/src/electron/WindowsForegroundFocusThread.test.ts +++ b/apps/desktop/src/electron/WindowsForegroundFocusThread.test.ts @@ -68,33 +68,3 @@ it("fails pending focus when the helper exits", async () => { assert.lengthOf(workerConstructorMock.mock.calls, 2); thread.close(); }); - -it("replaces a timed-out helper before accepting more work", async () => { - vi.useFakeTimers(); - const replacement = makeWorker(); - workerConstructorMock.mockReturnValueOnce(worker).mockReturnValueOnce(replacement); - const thread = startWindowsForegroundFocusThread("focus.cjs"); - - try { - worker.emit("message", "ready"); - const focused = thread.focus(target); - await vi.advanceTimersByTimeAsync(1_000); - - assert.isFalse(await focused); - assert.lengthOf(worker.terminate.mock.calls, 1); - assert.lengthOf(workerConstructorMock.mock.calls, 2); - - replacement.emit("message", "ready"); - const prepared = thread.prepare(target); - assert.deepEqual(replacement.postMessage.mock.calls[0]?.[0], { - type: "prepare", - requestId: 2, - target, - }); - replacement.emit("message", { type: "result", requestId: 2, focused: true }); - assert.isTrue(await prepared); - } finally { - thread.close(); - vi.useRealTimers(); - } -}); diff --git a/apps/desktop/src/electron/WindowsForegroundFocusWorker.test.ts b/apps/desktop/src/electron/WindowsForegroundFocusWorker.test.ts deleted file mode 100644 index 4c07e4671fb2d..0000000000000 --- a/apps/desktop/src/electron/WindowsForegroundFocusWorker.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { assert, beforeEach, it, vi } from "vite-plus/test"; - -const { byPid, list, on, postMessage } = vi.hoisted(() => ({ - byPid: vi.fn(), - list: vi.fn(), - on: vi.fn(), - postMessage: vi.fn(), -})); - -vi.mock("node:worker_threads", () => ({ parentPort: { on, postMessage } })); -vi.mock("@crowecawcaw/xa11y", () => ({ App: { byPid, list } })); - -beforeEach(() => { - vi.resetModules(); - vi.resetAllMocks(); -}); - -it.each(["lookup", "children"])("falls back to enumeration after a failed %s", async (failure) => { - const error = new Error("Unavailable"); - if (failure === "lookup") byPid.mockRejectedValue(error); - else byPid.mockResolvedValue({ children: () => Promise.reject(error) }); - const bounds = { x: 0, y: 0, width: 800, height: 600 }; - const focus = vi.fn().mockResolvedValue(undefined); - list.mockResolvedValue([{ pid: 42, asElement: () => ({ name: "T3", bounds, focus }) }]); - await import("./WindowsForegroundFocusWorker.ts"); - await vi.dynamicImportSettled(); - const result = Promise.withResolvers(); - postMessage.mockImplementation(result.resolve); - on.mock.calls[0]![1]({ - type: "focus", - requestId: 1, - target: { windowId: 1, processId: 42, title: "T3", bounds, contentBounds: bounds }, - }); - assert.deepEqual(await result.promise, { type: "result", requestId: 1, focused: true }); - assert.lengthOf(focus.mock.calls, 1); -}); diff --git a/apps/desktop/src/ipc/DesktopIpc.test.ts b/apps/desktop/src/ipc/DesktopIpc.test.ts deleted file mode 100644 index e90491f1f4e7d..0000000000000 --- a/apps/desktop/src/ipc/DesktopIpc.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; -import * as Effect from "effect/Effect"; -import { vi } from "vite-plus/test"; - -import * as DesktopIpc from "./DesktopIpc.ts"; - -const invokeMethod: DesktopIpc.DesktopIpcMethod = { - channel: "desktop.test.invoke", - handler: () => Effect.void, -}; - -const syncMethod: DesktopIpc.DesktopSyncIpcMethod = { - channel: "desktop.test.sync", - handler: () => Effect.void, -}; - -function makeIpcMain( - overrides: Partial = {}, -): DesktopIpc.DesktopIpcMain { - return { - removeHandler: vi.fn(), - handle: vi.fn(), - removeAllListeners: vi.fn(), - on: vi.fn(), - ...overrides, - }; -} - -describe("DesktopIpc", () => { - it.effect("preserves invoke registration context and cause", () => - Effect.gen(function* () { - const cause = new Error("invoke registration failed"); - const ipcMain = makeIpcMain({ - handle: () => { - throw cause; - }, - }); - const ipc = DesktopIpc.make(ipcMain); - - const error = yield* Effect.flip(Effect.scoped(ipc.handle(invokeMethod))); - - assert.instanceOf(error, DesktopIpc.DesktopIpcRegistrationError); - assert.strictEqual(error.handlerKind, "invoke"); - assert.strictEqual(error.channel, invokeMethod.channel); - assert.strictEqual(error.cause, cause); - assert.include(error.message, "invoke"); - assert.include(error.message, invokeMethod.channel); - assert.notInclude(error.message, cause.message); - }), - ); - - it.effect("forwards the invoke sender to the method", () => - Effect.gen(function* () { - let listener: DesktopIpc.DesktopIpcHandleListener | undefined; - const ipc = DesktopIpc.make( - makeIpcMain({ - handle: (_channel, registered) => { - listener = registered; - }, - }), - ); - const sender = { sender: { id: 7 } }; - let received: DesktopIpc.DesktopIpcInvokeEvent | undefined; - - yield* Effect.scoped( - Effect.gen(function* () { - yield* ipc.handle({ - channel: "desktop.test.sender", - handler: (_raw, event) => - Effect.sync(() => { - received = event; - }), - }); - yield* Effect.promise(async () => listener!(sender, undefined)); - }), - ); - - assert.strictEqual(received, sender); - }), - ); - - it.effect("preserves sync unregistration context and cause in the finalizer defect", () => - Effect.gen(function* () { - const cause = new Error("sync unregistration failed"); - let removeCount = 0; - const ipcMain = makeIpcMain({ - removeAllListeners: () => { - removeCount += 1; - if (removeCount === 2) throw cause; - }, - }); - const ipc = DesktopIpc.make(ipcMain); - - const exit = yield* Effect.exit(Effect.scoped(ipc.handleSync(syncMethod))); - - assert.isTrue(exit._tag === "Failure"); - if (exit._tag === "Success") return; - const error = Cause.squash(exit.cause); - assert.instanceOf(error, DesktopIpc.DesktopIpcUnregistrationError); - assert.strictEqual(error.handlerKind, "sync"); - assert.strictEqual(error.channel, syncMethod.channel); - assert.strictEqual(error.cause, cause); - assert.notInclude(error.message, cause.message); - }), - ); -}); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index caed223e90e86..2d67aa56e6ccd 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -41,6 +41,7 @@ import { getAppBranding, getLocalEnvironmentBootstraps, getLocalEnvironmentBearerToken, + getRelayTelemetryEnabled, getSystemLocale, getWindowFullscreenState, openExternal, @@ -48,6 +49,7 @@ import { checkSystemPermission, pasteAsText, probeRemoteEditors, + revealWindow, pickFolder, pickProjectFavicon, pickThemeFiles, @@ -94,6 +96,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(takeLegacyLocalStorage); yield* ipc.handle(completeLegacyLocalStorage); yield* ipc.handleSync(getAppBranding); + yield* ipc.handleSync(getRelayTelemetryEnabled); yield* ipc.handleSync(getSystemLocale); yield* ipc.handleSync(getWindowFullscreenState); yield* ipc.handleSync(getLocalEnvironmentBootstraps); @@ -150,6 +153,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(openSystemSettings); yield* ipc.handle(checkSystemPermission); yield* ipc.handle(pasteAsText); + yield* ipc.handle(revealWindow); yield* ipc.handle(probeRemoteEditors); yield* ipc.handle(getUpdateState); yield* ipc.handle(setUpdateChannel); @@ -160,7 +164,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(installCliCommand); yield* ipc.handle(uninstallCliCommand); for (const previewMethod of PreviewIpc.methods) { - yield* ipc.handle(previewMethod); + // Explicit types preserve the error/service union of these heterogeneous preview methods. + yield* ipc.handle< + Effect.Error>, + Effect.Services> + >(previewMethod); } yield* ipc.handle(PreviewIpc.listBrowserImportSources); yield* ipc.handle(PreviewIpc.importBrowserCookies); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index a6b617385b578..9b11a2283a273 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -9,6 +9,7 @@ export const OPEN_SYSTEM_SETTINGS_CHANNEL = "desktop:open-system-settings"; export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors"; export const MENU_ACTION_CHANNEL = "desktop:menu-action"; export const PASTE_AS_TEXT_CHANNEL = "desktop:paste-as-text"; +export const REVEAL_WINDOW_CHANNEL = "desktop:reveal-window"; export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event"; export const WEB_LINK_OPEN_CHANNEL = "desktop:web-link-open"; export const WEB_LINK_READY_CHANNEL = "desktop:web-link-ready"; @@ -29,6 +30,7 @@ export const CLI_COMMAND_GET_STATE_CHANNEL = "desktop:cli-command-get-state"; export const CLI_COMMAND_INSTALL_CHANNEL = "desktop:cli-command-install"; export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall"; export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; +export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled"; export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale"; export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps"; export const GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:get-local-environment-enabled"; diff --git a/apps/desktop/src/ipc/methods/legacyLocalStorage.ts b/apps/desktop/src/ipc/methods/legacyLocalStorage.ts index 13f657e7812f8..a0c2fb27a5eac 100644 --- a/apps/desktop/src/ipc/methods/legacyLocalStorage.ts +++ b/apps/desktop/src/ipc/methods/legacyLocalStorage.ts @@ -22,8 +22,7 @@ export const completeLegacyLocalStorage = makeIpcMethod({ result: Schema.Void, handler: Effect.fn("desktop.ipc.legacyLocalStorage.complete")(function* (_, event) { const legacy = yield* DesktopLegacyLocalStorage.DesktopLegacyLocalStorage; - // Chromium writes localStorage to disk lazily; persist the merge before - // the marker stops later launches from retrying it. + // Flush Chromium's lazy writes before the marker prevents migration retries. if (event) Electron.webContents.fromId(event.sender.id)?.session.flushStorageData(); yield* legacy.complete; }), diff --git a/apps/desktop/src/ipc/methods/notificationBadge.test.ts b/apps/desktop/src/ipc/methods/notificationBadge.test.ts index 40d1df6a33662..7126b1cd31945 100644 --- a/apps/desktop/src/ipc/methods/notificationBadge.test.ts +++ b/apps/desktop/src/ipc/methods/notificationBadge.test.ts @@ -28,7 +28,7 @@ vi.mock("electron", () => ({ import * as ElectronApp from "../../electron/ElectronApp.ts"; import * as DesktopIpc from "../DesktopIpc.ts"; -import { applyNotificationBadge, installNotificationBadge } from "./notificationBadge.ts"; +import { installNotificationBadge } from "./notificationBadge.ts"; const badge = { count: 2, image: "data:image/png;base64,aGVsbG8=" }; @@ -42,51 +42,6 @@ beforeEach(() => { native.listeners.clear(); }); -it.each(["darwin", "linux"] as const)("sets and clears the native %s count", (platform) => { - applyNotificationBadge(platform, badge); - applyNotificationBadge(platform, { count: 0, image: null }); - expect(native.setBadgeCount.mock.calls).toEqual([[2], [0]]); - expect(native.createFromDataURL).not.toHaveBeenCalled(); -}); - -it("sets and clears the Windows taskbar overlay", () => { - applyNotificationBadge("win32", badge); - expect(native.setOverlayIcon).toHaveBeenLastCalledWith( - native.image, - "2 threads with new notifications", - ); - applyNotificationBadge("win32", { count: 0, image: null }); - expect(native.setOverlayIcon).toHaveBeenLastCalledWith(null, ""); -}); - -it.each(["win32", "darwin", "linux"] as const)( - "rejects a late positive count while %s is focused", - (platform) => { - native.getFocusedWindow.mockReturnValue({}); - applyNotificationBadge(platform, badge); - if (platform === "win32") expect(native.setOverlayIcon).toHaveBeenCalledWith(null, ""); - else expect(native.setBadgeCount).toHaveBeenCalledWith(0); - expect(native.createFromDataURL).not.toHaveBeenCalled(); - }, -); - -it("ignores destroyed windows and clears invalid images", () => { - native.isDestroyed.mockReturnValue(true); - applyNotificationBadge("win32", badge); - expect(native.setOverlayIcon).not.toHaveBeenCalled(); - native.isDestroyed.mockReturnValue(false); - native.image.isEmpty.mockReturnValue(true); - applyNotificationBadge("win32", badge); - expect(native.setOverlayIcon.mock.calls[0]?.[0]).toBeNull(); -}); - -it("keeps notifications working when the native badge API fails", () => { - native.setBadgeCount.mockImplementation(() => { - throw new Error("Unavailable"); - }); - expect(() => applyNotificationBadge("linux", badge)).not.toThrow(); -}); - it.effect("validates IPC and clears on native focus, quit, and disposal", () => Effect.gen(function* () { const handlers = new Map(); diff --git a/apps/desktop/src/ipc/methods/notificationBadge.ts b/apps/desktop/src/ipc/methods/notificationBadge.ts index 952745b4b7c6c..39eeeeeb1f308 100644 --- a/apps/desktop/src/ipc/methods/notificationBadge.ts +++ b/apps/desktop/src/ipc/methods/notificationBadge.ts @@ -17,7 +17,7 @@ const NotificationBadge = Schema.Struct({ ), }); -export function applyNotificationBadge( +function applyNotificationBadge( platform: NodeJS.Platform, { count, image }: typeof NotificationBadge.Type, ): void { diff --git a/apps/desktop/src/ipc/methods/preview.test.ts b/apps/desktop/src/ipc/methods/preview.test.ts index 225139c047413..802f2f3fb18b6 100644 --- a/apps/desktop/src/ipc/methods/preview.test.ts +++ b/apps/desktop/src/ipc/methods/preview.test.ts @@ -2,18 +2,17 @@ import { it as effectIt } from "@effect/vitest"; import { DEFAULT_BROWSER_PROFILE_ID, INCOGNITO_BROWSER_PROFILE_ID, - PreviewAutomationStatus, + PreviewCaptureFailure, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import * as PreviewManager from "../../preview/Manager.ts"; -import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts"; import * as PreviewIpc from "./preview.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; +import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; const { fromPartition } = vi.hoisted(() => ({ fromPartition: vi.fn(() => { @@ -33,16 +32,85 @@ vi.mock("electron", () => ({ }, })); +const decodeCaptureFailure = Schema.decodeUnknownEffect(PreviewCaptureFailure); + describe("preview IPC methods", () => { + const invokeCapture = ( + method: typeof PreviewIpc.startRecording | typeof PreviewIpc.captureScreenshot, + manager: Partial, + ) => + Effect.scoped( + Effect.gen(function* () { + let listener: DesktopIpc.DesktopIpcHandleListener | undefined; + const ipc = DesktopIpc.make({ + removeHandler: vi.fn(), + handle: (_channel, registered) => { + listener = registered; + }, + removeAllListeners: vi.fn(), + on: vi.fn(), + }); + yield* ipc.handle(method); + return yield* Effect.promise(async () => + structuredClone(await listener!({ sender: { id: 7 } }, { tabId: "capture-tab" })), + ); + }).pipe( + Effect.provideService( + PreviewManager.PreviewManager, + manager as PreviewManager.PreviewManager["Service"], + ), + Effect.provideService(DesktopClientSettings.DesktopClientSettings, { + get: Effect.succeedNone, + set: () => Effect.void, + }), + ), + ); + + effectIt.effect.each([ + { + cause: new Error("Current display surface not available for capture"), + reason: "capture-unavailable", + guidance: ["target tab", "unlocked", "display is on", "window is restored"], + }, + { + cause: new Cause.TimeoutError(), + reason: "capture-timeout", + guidance: ["timed out during capture-page"], + }, + { + cause: new Error("Current display surface not available for capture: private page data"), + reason: "capture-failed", + guidance: ["Preview capture failed during capture-page"], + }, + ])( + "transports a safe $reason screenshot diagnostic through registered IPC", + ({ cause, reason, guidance }) => + Effect.gen(function* () { + const result = yield* invokeCapture(PreviewIpc.captureScreenshot, { + captureScreenshot: (tabId) => + Effect.fail( + new PreviewManager.PreviewOperationError({ + operation: "captureScreenshot.capturePage", + tabId, + artifactPath: "/private/capture.png", + cause, + }), + ), + }); + expect(result).toEqual({ + _tag: "PreviewCaptureFailure", + reason, + stage: "capture-page", + }); + const failure = yield* decodeCaptureFailure(result); + for (const phrase of guidance) expect(failure.message).toContain(phrase); + }), + ); + beforeEach(() => { fromPartition.mockClear(); }); - it("does not access the Electron session while the module loads", async () => { - await expect(import("./preview.ts")).resolves.toBeDefined(); - expect(fromPartition).not.toHaveBeenCalled(); - }); - it("derives distinct partition scopes when identifiers contain the delimiter", () => { const first = PreviewIpc.resolvePartitionScope("a", "b::c"); const second = PreviewIpc.resolvePartitionScope("a::b", "c"); @@ -52,18 +120,6 @@ describe("preview IPC methods", () => { expect(first.scope).not.toBe(second.scope); }); - it("preserves lone surrogates without collapsing them to replacement characters", () => { - const highSurrogate = PreviewIpc.resolvePartitionScope("environment", "profile-\ud800"); - const lowSurrogate = PreviewIpc.resolvePartitionScope("environment", "profile-\udc00"); - const replacement = PreviewIpc.resolvePartitionScope("environment", "profile-�"); - - expect(highSurrogate.scope).toBe('["environment","profile-\\ud800"]'); - expect(lowSurrogate.scope).toBe('["environment","profile-\\udc00"]'); - expect(highSurrogate.scope).not.toBe(lowSurrogate.scope); - expect(highSurrogate.scope).not.toBe(replacement.scope); - expect(lowSurrogate.scope).not.toBe(replacement.scope); - }); - it("keeps the legacy default partition scope and incognito persistence", () => { expect(PreviewIpc.resolvePartitionScope("environment::legacy", undefined)).toEqual({ scope: "environment::legacy", @@ -80,67 +136,4 @@ describe("preview IPC methods", () => { namespace: "profile", }); }); - - effectIt.effect("targets imports at the same partition tuple as the renderer", () => { - const received: Array[0]> = - []; - const browserImport = BrowserImport.BrowserImport.of({ - listSources: Effect.succeed([]), - importCookies: (input) => - Effect.sync(() => { - received.push(input); - return { imported: 0, skipped: 0, skippedDomains: [] }; - }), - }); - const request = (environmentId: string, targetProfileId: string) => - PreviewIpc.importBrowserCookies.handler({ - environmentId, - sourceId: "helium", - sourceProfileDirectory: "Default", - targetProfileId, - }); - - return Effect.gen(function* () { - yield* request("a", "b"); - yield* request("a::b", DEFAULT_BROWSER_PROFILE_ID); - - expect(received[0]).toMatchObject(PreviewIpc.resolvePartitionScope("a", "b")); - expect(received[1]).toMatchObject( - PreviewIpc.resolvePartitionScope("a::b", DEFAULT_BROWSER_PROFILE_ID), - ); - expect(received[0]?.namespace).toBe("profile"); - expect(received[1]?.namespace).toBeUndefined(); - }).pipe(Effect.provideService(BrowserImport.BrowserImport, browserImport)); - }); - - effectIt.effect("rejects invalid webContents ids before resolving the preview service", () => - Effect.map( - PreviewIpc.registerWebview - .handler({ tabId: "tab-1", webContentsId: 0 }) - .pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit), - (exit) => { - expect(Exit.isFailure(exit)).toBe(true); - if (Exit.isSuccess(exit)) return; - const error = Cause.findErrorOption(exit.cause); - expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true); - expect(fromPartition).not.toHaveBeenCalled(); - }, - ), - ); - - it("keeps the public automation status tab id limit", () => { - const encode = Schema.encodeUnknownSync(PreviewAutomationStatus); - const tabId = "t".repeat(129); - - expect(() => - encode({ - available: false, - visible: true, - tabId, - url: null, - title: null, - loading: false, - }), - ).toThrow(); - }); }); diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 74c6f85043d7f..c6c2cd8fbdf9a 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -19,6 +19,7 @@ import { DesktopPreviewTabInputSchema, DesktopPreviewWebviewConfigSchema, PreviewAnnotationSubmissionResultSchema, + PreviewCaptureFailure, DEFAULT_BROWSER_PROFILE_ID, INCOGNITO_BROWSER_PROFILE_ID, PreviewForwardedShortcut, @@ -32,6 +33,7 @@ import * as NodeURL from "node:url"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts"; import * as PreviewManager from "../../preview/Manager.ts"; +import { normalizeCaptureFailure } from "../../preview/captureErrors.ts"; import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts"; import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts"; import * as IpcChannels from "../channels.ts"; @@ -59,7 +61,7 @@ export const installPreviewEventForwarding = Effect.fn( ); }); -export const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ +const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_FORWARDED_SHORTCUTS_CHANNEL, payload: Schema.Array(PreviewForwardedShortcut).check(Schema.isMaxLength(MAX_KEYBINDINGS_COUNT)), result: Schema.Void, @@ -69,7 +71,7 @@ export const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ }), }); -export const createTab = DesktopIpc.makeIpcMethod({ +const createTab = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, payload: DesktopPreviewCreateTabInputSchema, result: Schema.Void, @@ -84,7 +86,7 @@ export const createTab = DesktopIpc.makeIpcMethod({ }), }); -export const closeTab = DesktopIpc.makeIpcMethod({ +const closeTab = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, payload: DesktopPreviewTabInputSchema, result: Schema.Void, @@ -94,7 +96,7 @@ export const closeTab = DesktopIpc.makeIpcMethod({ }), }); -export const registerWebview = DesktopIpc.makeIpcMethod({ +const registerWebview = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, payload: DesktopPreviewRegisterWebviewInputSchema, result: Schema.Void, @@ -104,7 +106,7 @@ export const registerWebview = DesktopIpc.makeIpcMethod({ }), }); -export const navigate = DesktopIpc.makeIpcMethod({ +const navigate = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL, payload: DesktopPreviewNavigateInputSchema, result: Schema.Void, @@ -132,42 +134,42 @@ const tabMethod = ( }), }); -export const goBack = tabMethod( +const goBack = tabMethod( IpcChannels.PREVIEW_GO_BACK_CHANNEL, "desktop.ipc.preview.goBack", (manager, tabId) => manager.goBack(tabId), ); -export const goForward = tabMethod( +const goForward = tabMethod( IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, "desktop.ipc.preview.goForward", (manager, tabId) => manager.goForward(tabId), ); -export const refresh = tabMethod( +const refresh = tabMethod( IpcChannels.PREVIEW_REFRESH_CHANNEL, "desktop.ipc.preview.refresh", (manager, tabId) => manager.refresh(tabId), ); -export const zoomIn = tabMethod( +const zoomIn = tabMethod( IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, "desktop.ipc.preview.zoomIn", (manager, tabId) => manager.zoomIn(tabId), ); -export const zoomOut = tabMethod( +const zoomOut = tabMethod( IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, "desktop.ipc.preview.zoomOut", (manager, tabId) => manager.zoomOut(tabId), ); -export const resetZoom = tabMethod( +const resetZoom = tabMethod( IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, "desktop.ipc.preview.resetZoom", (manager, tabId) => manager.resetZoom(tabId), ); -export const hardReload = tabMethod( +const hardReload = tabMethod( IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, "desktop.ipc.preview.hardReload", (manager, tabId) => manager.hardReload(tabId), ); -export const setZoomFactor = DesktopIpc.makeIpcMethod({ +const setZoomFactor = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_ZOOM_FACTOR_CHANNEL, payload: DesktopPreviewSetZoomFactorInputSchema, result: Schema.Void, @@ -176,7 +178,7 @@ export const setZoomFactor = DesktopIpc.makeIpcMethod({ yield* manager.setZoomFactor(tabId, zoomFactor); }), }); -export const setColorScheme = DesktopIpc.makeIpcMethod({ +const setColorScheme = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, payload: DesktopPreviewSetColorSchemeInputSchema, result: Schema.Void, @@ -185,7 +187,7 @@ export const setColorScheme = DesktopIpc.makeIpcMethod({ yield* manager.setColorScheme(tabId, colorScheme); }), }); -export const setAudioMuted = DesktopIpc.makeIpcMethod({ +const setAudioMuted = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, payload: DesktopPreviewSetAudioMutedInputSchema, result: Schema.Void, @@ -194,12 +196,12 @@ export const setAudioMuted = DesktopIpc.makeIpcMethod({ yield* manager.setAudioMuted(tabId, audioMuted); }), }); -export const openDevTools = tabMethod( +const openDevTools = tabMethod( IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, "desktop.ipc.preview.openDevTools", (manager, tabId) => manager.openDevTools(tabId), ); -export const cancelPickElement = tabMethod( +const cancelPickElement = tabMethod( IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, "desktop.ipc.preview.cancelPickElement", (manager, tabId) => manager.cancelPickElement(tabId), @@ -207,7 +209,8 @@ export const cancelPickElement = tabMethod( export const startRecording = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_RECORDING_START_CHANNEL, payload: DesktopPreviewTabInputSchema, - result: Schema.Void, + // Void encodes any value as undefined, so the tagged failure must be tried first. + result: Schema.Union([PreviewCaptureFailure, Schema.Void]), handler: Effect.fn("desktop.ipc.preview.startRecording")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; const store = yield* DesktopClientSettings.DesktopClientSettings; @@ -216,26 +219,30 @@ export const startRecording = DesktopIpc.makeIpcMethod({ showKeyPresses: value.browserRecordingShowKeyPresses, showMousePresses: value.browserRecordingShowMousePresses, })); - yield* manager.startRecording(tabId, Option.getOrUndefined(options)); + return yield* manager + .startRecording(tabId, Option.getOrUndefined(options)) + .pipe( + Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "recording-start"))), + ); }), }); -export const stopRecording = tabMethod( +const stopRecording = tabMethod( IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, "desktop.ipc.preview.stopRecording", (manager, tabId) => manager.stopRecording(tabId), ); -export const openPictureInPicture = tabMethod( +const openPictureInPicture = tabMethod( IpcChannels.PREVIEW_PICTURE_IN_PICTURE_OPEN_CHANNEL, "desktop.ipc.preview.openPictureInPicture", (manager, tabId) => manager.openPictureInPicture(tabId), ); -export const closePictureInPicture = tabMethod( +const closePictureInPicture = tabMethod( IpcChannels.PREVIEW_PICTURE_IN_PICTURE_CLOSE_CHANNEL, "desktop.ipc.preview.closePictureInPicture", (manager, tabId) => manager.closePictureInPicture(tabId), ); -export const clearCookies = DesktopIpc.makeIpcMethod({ +const clearCookies = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL, payload: DesktopPreviewClearDataInputSchema, result: Schema.Void, @@ -245,7 +252,7 @@ export const clearCookies = DesktopIpc.makeIpcMethod({ }), }); -export const clearCache = DesktopIpc.makeIpcMethod({ +const clearCache = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL, payload: DesktopPreviewClearDataInputSchema, result: Schema.Void, @@ -255,11 +262,7 @@ export const clearCache = DesktopIpc.makeIpcMethod({ }), }); -/** - * The default profile keeps the bare environment id it used before profiles - * existed, so upgrading does not strand anyone's existing logins in an orphaned - * partition. - */ +/** Keep the default profile's bare environment id so existing logins retain their partition. */ export function resolvePartitionScope( environmentId: string, profileId: string | undefined, @@ -271,9 +274,7 @@ export function resolvePartitionScope( if (profileId === undefined || profileId === DEFAULT_BROWSER_PROFILE_ID) { return { scope: environmentId, persistent: true }; } - // JSON's tuple framing is injective for strings, including lone UTF-16 - // surrogates (which it escapes). URI encoding throws on those supported ids, - // while replacing them with U+FFFD would collapse distinct identities. + // JSON framing preserves lone UTF-16 surrogates; URI encoding throws and replacement would collide. return { scope: JSON.stringify([environmentId, profileId]), persistent: profileId !== INCOGNITO_BROWSER_PROFILE_ID, @@ -281,11 +282,7 @@ export function resolvePartitionScope( }; } -/** - * Clearing without a profile keeps the historical "everything" behaviour for - * an explicit all-profiles action; naming a profile confines it to that - * profile's partition so one profile's sign-out cannot reach the others. - */ +/** Omitting a profile clears every partition; a named profile clears only its own partition. */ const resolveClearPartitions = Effect.fn("desktop.ipc.preview.resolveClearPartitions")(function* ( manager: PreviewManager.PreviewManager["Service"], environmentId: string, @@ -293,24 +290,19 @@ const resolveClearPartitions = Effect.fn("desktop.ipc.preview.resolveClearPartit ) { if (profileId === undefined) return undefined; const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId); - // Loading the session is what puts the partition in the map the clear walks. - // Deriving the partition string alone leaves nothing to match, so clearing a - // profile with no tab open this run — after a restart, or when deleting a - // profile — would report success and delete nothing. + // getBrowserSession registers the partition; deriving its name alone leaves unopened profiles uncleared. yield* manager.getBrowserSession(scope, persistent, namespace); return [yield* manager.getBrowserPartition(scope, persistent, namespace)]; }); -export const getPreviewConfig = DesktopIpc.makeIpcMethod({ +const getPreviewConfig = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, payload: DesktopPreviewConfigInputSchema, result: DesktopPreviewWebviewConfigSchema, handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId, profileId }) { const manager = yield* PreviewManager.PreviewManager; const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId); - // Creating the session first is what installs the UA rewrite and permission - // handlers; a guest that attached to an untouched partition would run with - // Electron's default UA and Chromium's default permission behaviour. + // Session creation installs UA and permission handlers before a guest can attach. yield* manager.getBrowserSession(scope, persistent, namespace); return { partition: yield* manager.getBrowserPartition(scope, persistent, namespace), @@ -339,8 +331,6 @@ export const importBrowserCookies = DesktopIpc.makeIpcMethod({ ...importInput }) { const browserImport = yield* BrowserImport.BrowserImport; - // Derived in main from the same helper the webview config uses, so cookies - // land in exactly the partition the profile's tabs attach to. const { scope, persistent, namespace } = resolvePartitionScope( environmentId, importInput.targetProfileId, @@ -354,7 +344,7 @@ export const importBrowserCookies = DesktopIpc.makeIpcMethod({ }), }); -export const setAnnotationTheme = DesktopIpc.makeIpcMethod({ +const setAnnotationTheme = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, payload: DesktopPreviewAnnotationThemeInputSchema, result: Schema.Void, @@ -364,7 +354,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({ }), }); -export const pickElement = DesktopIpc.makeIpcMethod({ +const pickElement = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, payload: DesktopPreviewTabInputSchema, result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema), @@ -374,7 +364,7 @@ export const pickElement = DesktopIpc.makeIpcMethod({ }), }); -export const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({ +const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_ANNOTATION_SEND_ENABLED_CHANNEL, payload: DesktopPreviewAnnotationSendEnabledInputSchema, result: Schema.Void, @@ -390,14 +380,16 @@ export const setAnnotationSendEnabled = DesktopIpc.makeIpcMethod({ export const captureScreenshot = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, payload: DesktopPreviewTabInputSchema, - result: DesktopPreviewScreenshotArtifactSchema, + result: Schema.Union([DesktopPreviewScreenshotArtifactSchema, PreviewCaptureFailure]), handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager.captureScreenshot(tabId); + return yield* manager + .captureScreenshot(tabId) + .pipe(Effect.catch((error) => Effect.succeed(normalizeCaptureFailure(error, "screenshot")))); }), }); -export const revealArtifact = DesktopIpc.makeIpcMethod({ +const revealArtifact = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, payload: DesktopPreviewArtifactInputSchema, result: Schema.Void, @@ -407,7 +399,7 @@ export const revealArtifact = DesktopIpc.makeIpcMethod({ }), }); -export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({ +const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, payload: DesktopPreviewArtifactInputSchema, result: Schema.Void, @@ -417,7 +409,7 @@ export const copyArtifactToClipboard = DesktopIpc.makeIpcMethod({ }), }); -export const saveRecording = DesktopIpc.makeIpcMethod({ +const saveRecording = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, payload: DesktopPreviewRecordingSaveInputSchema, result: DesktopPreviewRecordingArtifactSchema, diff --git a/apps/desktop/src/ipc/methods/snapShot.test.ts b/apps/desktop/src/ipc/methods/snapShot.test.ts index 138bcbc36d302..7e1ae602f979d 100644 --- a/apps/desktop/src/ipc/methods/snapShot.test.ts +++ b/apps/desktop/src/ipc/methods/snapShot.test.ts @@ -1,22 +1,15 @@ import { assert, describe, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as ElectronDialog from "../../electron/ElectronDialog.ts"; import * as DesktopSnapShot from "../../snapShot/DesktopSnapShot.ts"; import { - checkSnapShotShortcut, - requestSnapShotPermissions, setupSnapShot, previewSnapShotConfig, applySnapShotConfig, - setSnapShotAnimationDestination, - setSnapShotShortcutSuppressed, - snapShotScreenFrame, snapShotRelativeFrame, } from "./snapShot.ts"; @@ -74,193 +67,6 @@ describe("window capture IPC", () => { ); }); - it.effect("cancelling custom file selection reads and writes nothing", () => { - let read = false; - return Effect.gen(function* () { - const preview = yield* previewSnapShotConfig.handler( - { operation: "install", chooseFile: true }, - { sender: { id: 7 } }, - ); - assert.isNull(preview); - assert.isFalse(read); - }).pipe( - Effect.provide( - Layer.mergeAll( - Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), - Layer.succeed(DesktopSnapShot.DesktopSnapShot, { - state: Effect.succeed({ - linuxBackend: "niri", - shortcutConfigPath: "/config/niri/config.kdl", - }), - previewConfig: () => - Effect.sync(() => { - read = true; - return configPreview; - }), - } as unknown as DesktopSnapShot.DesktopSnapShot["Service"]), - Layer.succeed(ElectronDialog.ElectronDialog, { - pickFiles: () => Effect.succeed([]), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - ), - ), - ); - }); - - it.effect("uses only the file returned by the native custom config picker", () => { - let path: string | undefined; - return Effect.gen(function* () { - yield* previewSnapShotConfig.handler( - { operation: "install", chooseFile: true }, - { sender: { id: 7 } }, - ); - assert.equal(path, "/chosen/config.kdl"); - }).pipe( - Effect.provide( - Layer.mergeAll( - Layer.succeed(ElectronWindow.ElectronWindow, { - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), - Layer.succeed(DesktopSnapShot.DesktopSnapShot, { - state: Effect.succeed({ linuxBackend: "niri" }), - previewConfig: (_: unknown, selected: string) => - Effect.sync(() => { - path = selected; - return configPreview; - }), - } as unknown as DesktopSnapShot.DesktopSnapShot["Service"]), - Layer.succeed(ElectronDialog.ElectronDialog, { - pickFiles: () => Effect.succeed(["/chosen/config.kdl"]), - } as unknown as ElectronDialog.ElectronDialog["Service"]), - ), - ), - ); - }); - - it("converts renderer viewport coordinates from the content origin using the window zoom", () => { - assert.deepEqual( - snapShotScreenFrame( - { x: 12, y: 20, width: 208, height: 112 }, - { x: 100, y: 80, width: 1_000, height: 700 }, - 1.25, - ), - { x: 115, y: 105, width: 260, height: 140 }, - ); - }); - - it.effect("forwards a trusted renderer animation destination in screen coordinates", () => { - let received: unknown; - const webContents = { id: 7, getZoomFactor: () => 1.25 }; - const layer = Layer.mergeAll( - Layer.succeed( - ElectronWindow.ElectronWindow, - ElectronWindow.ElectronWindow.of({ - main: Effect.succeedSome({ - getBounds: () => ({ x: 100, y: 80, width: 1_000, height: 700 }), - getContentBounds: () => ({ x: 100, y: 118, width: 1_000, height: 662 }), - webContents, - }), - } as ElectronWindow.ElectronWindow["Service"]), - ), - Layer.succeed( - DesktopSnapShot.DesktopSnapShot, - DesktopSnapShot.DesktopSnapShot.of({ - setAnimationDestination: (id: string, destination: unknown) => - Effect.sync(() => { - received = { id, destination }; - }), - } as unknown as DesktopSnapShot.DesktopSnapShot["Service"]), - ), - ); - - return Effect.gen(function* () { - yield* setSnapShotAnimationDestination.handler( - { - id: "12345678-1234-1234-1234-123456789abc", - viewportFrame: { x: 12, y: 20, width: 208, height: 112 }, - backgroundColor: "rgb(20, 20, 20)", - borderColor: "rgba(80, 80, 80, 0.8)", - borderWidth: 1, - cornerRadius: 8, - details: { - appName: "T3 Code", - windowTitle: "Capture animation", - appIconDataUrl: "data:image/png;base64,aWNvbg==", - }, - }, - { sender: webContents }, - ); - assert.deepEqual(received, { - id: "12345678-1234-1234-1234-123456789abc", - destination: { - relativeFrame: { x: 15 / 1000, y: 25 / 662, width: 260 / 1000, height: 140 / 662 }, - frame: { x: 115, y: 143, width: 260, height: 140 }, - backgroundColor: "rgb(20, 20, 20)", - borderColor: "rgba(80, 80, 80, 0.8)", - borderWidth: 1.25, - cornerRadius: 10, - scaleFactor: 1.25, - details: { - appName: "T3 Code", - windowTitle: "Capture animation", - appIconDataUrl: "data:image/png;base64,aWNvbg==", - }, - }, - }); - }).pipe(Effect.provide(layer)); - }); - - it.effect("forwards the accessibility permission preference from a trusted renderer", () => { - let includeAccessibility: boolean | undefined; - const webContents = { id: 7 }; - const layer = Layer.mergeAll( - Layer.succeed( - ElectronWindow.ElectronWindow, - ElectronWindow.ElectronWindow.of({ - main: Effect.succeedSome({ webContents }), - } as ElectronWindow.ElectronWindow["Service"]), - ), - Layer.succeed( - DesktopSnapShot.DesktopSnapShot, - DesktopSnapShot.DesktopSnapShot.of({ - requestPermissions: (include: boolean) => - Effect.sync(() => { - includeAccessibility = include; - }), - } as unknown as DesktopSnapShot.DesktopSnapShot["Service"]), - ), - ); - - return Effect.gen(function* () { - yield* requestSnapShotPermissions.handler(false, { sender: webContents }); - assert.isFalse(includeAccessibility); - }).pipe(Effect.provide(layer)); - }); - - it.effect("rejects an untrusted renderer at the IPC boundary", () => - Effect.gen(function* () { - const exit = yield* Effect.exit( - requestSnapShotPermissions.handler(false, { sender: { id: 8 } }), - ); - assert(Exit.isFailure(exit)); - const failure = Cause.findErrorOption(exit.cause); - assert(Option.isSome(failure)); - const error = failure.value; - - assert.equal((error as { readonly _tag: string })._tag, "SnapShotIpcUnauthorizedSenderError"); - assert.equal((error as Error).message, "Snapshot request was rejected."); - }).pipe( - Effect.provideService( - ElectronWindow.ElectronWindow, - ElectronWindow.ElectronWindow.of({ - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), - ), - Effect.provideService(DesktopSnapShot.DesktopSnapShot, null as never), - ), - ); - it.effect("allows capture setup only from the trusted main renderer", () => { const actions: string[] = []; return Effect.gen(function* () { @@ -287,56 +93,6 @@ describe("window capture IPC", () => { ), ); }); - - it.effect("checks shortcut availability for a trusted renderer", () => { - const layer = Layer.mergeAll( - Layer.succeed( - ElectronWindow.ElectronWindow, - ElectronWindow.ElectronWindow.of({ - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), - ), - Layer.succeed( - DesktopSnapShot.DesktopSnapShot, - DesktopSnapShot.DesktopSnapShot.of({ - checkShortcut: () => Effect.succeed({ available: true, message: null }), - } as unknown as DesktopSnapShot.DesktopSnapShot["Service"]), - ), - ); - - return Effect.gen(function* () { - const result = yield* checkSnapShotShortcut.handler( - { kind: "both-shift-keys" }, - { sender: { id: 7 } }, - ); - assert.deepEqual(result, { available: true, message: null }); - }).pipe(Effect.provide(layer)); - }); - it.effect("suppresses the active shortcut for a trusted renderer", () => { - let suppressed = false; - const layer = Layer.mergeAll( - Layer.succeed( - ElectronWindow.ElectronWindow, - ElectronWindow.ElectronWindow.of({ - main: Effect.succeedSome({ webContents: { id: 7 } }), - } as ElectronWindow.ElectronWindow["Service"]), - ), - Layer.succeed( - DesktopSnapShot.DesktopSnapShot, - DesktopSnapShot.DesktopSnapShot.of({ - setShortcutSuppressed: (next: boolean) => - Effect.sync(() => { - suppressed = next; - }), - } as unknown as DesktopSnapShot.DesktopSnapShot["Service"]), - ), - ); - - return Effect.gen(function* () { - yield* setSnapShotShortcutSuppressed.handler(true, { sender: { id: 7 } }); - assert.isTrue(suppressed); - }).pipe(Effect.provide(layer)); - }); }); it("normalizes Wayland attachment coordinates without trusting Electron's screen origin", () => { diff --git a/apps/desktop/src/ipc/methods/snapShot.ts b/apps/desktop/src/ipc/methods/snapShot.ts index 4b5e189c2089e..dff64081b70c6 100644 --- a/apps/desktop/src/ipc/methods/snapShot.ts +++ b/apps/desktop/src/ipc/methods/snapShot.ts @@ -45,7 +45,7 @@ const ensureTrustedSnapShotSender = Effect.fn("desktop.ipc.snapShot.ensureTruste }, ); -export function snapShotScreenFrame( +function snapShotScreenFrame( viewportFrame: DesktopSnapShotAnimationDestination["viewportFrame"], contentBounds: Electron.Rectangle, zoomFactor: number, diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.test.ts b/apps/desktop/src/ipc/methods/sshEnvironment.test.ts index 0ed188ca61b59..1b40db955fe6e 100644 --- a/apps/desktop/src/ipc/methods/sshEnvironment.test.ts +++ b/apps/desktop/src/ipc/methods/sshEnvironment.test.ts @@ -34,59 +34,6 @@ function layerHttpClient( } describe("SSH environment IPC", () => { - it.effect("fetches and decodes the remote environment descriptor", () => { - const requestUrls: string[] = []; - const layer = layerHttpClient((request) => - Effect.sync(() => { - requestUrls.push(request.url); - return jsonResponse(request, { - environmentId: "remote-env", - label: "Remote Devbox", - platform: { os: "linux", arch: "x64" }, - serverVersion: "1.2.3", - capabilities: { repositoryIdentity: true }, - }); - }), - ); - - return Effect.gen(function* () { - const descriptor = yield* fetchSshEnvironmentDescriptor.handler({ - httpBaseUrl: "http://127.0.0.1:41773/", - }); - - assert.deepEqual(descriptor, { - environmentId: "remote-env", - label: "Remote Devbox", - platform: { os: "linux", arch: "x64" }, - serverVersion: "1.2.3", - capabilities: { repositoryIdentity: true }, - }); - assert.deepEqual(requestUrls, ["http://127.0.0.1:41773/.well-known/t3/environment"]); - }).pipe(Effect.provide(layer)); - }); - - it.effect("wraps schema decode failures in a typed request error", () => { - const layer = layerHttpClient((request) => - Effect.succeed(jsonResponse(request, { environmentId: "remote-env" })), - ); - - return Effect.gen(function* () { - const exit = yield* Effect.exit( - fetchSshEnvironmentDescriptor.handler({ - httpBaseUrl: "http://127.0.0.1:41773/", - }), - ); - assert(Exit.isFailure(exit)); - const failure = Cause.findErrorOption(exit.cause); - assert(Option.isSome(failure)); - const error = failure.value; - - assert.instanceOf(error, DesktopSshEnvironmentRequestError); - assert.equal(error.operation, "fetch-environment-descriptor"); - assert.equal(error.cause instanceof SshHttpBridgeError, false); - }).pipe(Effect.provide(layer)); - }); - it.effect("rejects non-loopback HTTP endpoints before issuing a request", () => { let requestCount = 0; const layer = layerHttpClient((request) => diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.ts b/apps/desktop/src/ipc/methods/sshEnvironment.ts index e9535300104db..099b97ce7bf31 100644 --- a/apps/desktop/src/ipc/methods/sshEnvironment.ts +++ b/apps/desktop/src/ipc/methods/sshEnvironment.ts @@ -83,6 +83,7 @@ export class DesktopSshEnvironmentRequestError extends Data.TaggedError( readonly cause: DesktopSshEnvironmentRequestCause; readonly sshHttpStatus: number | null; }> { + // The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing. override get message() { const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `; return `${prefix}SSH remote API request failed during ${this.operation}.`; diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index d21f3cd605053..b5fe707f4caee 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -8,8 +8,6 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import { vi } from "vite-plus/test"; -import type * as Electron from "electron"; - const { focusedWebContents, ownerWindow } = vi.hoisted(() => ({ focusedWebContents: vi.fn(), ownerWindow: vi.fn(), @@ -22,14 +20,9 @@ vi.mock("electron", () => ({ import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts"; -import * as ElectronDialog from "../../electron/ElectronDialog.ts"; -import * as ElectronWindow from "../../electron/ElectronWindow.ts"; -import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import { getLocalEnvironmentBootstraps, - getWindowFullscreenState, - pasteAsText, - pickProjectFavicon, + getRelayTelemetryEnabled, probeRemoteEditors, } from "./window.ts"; @@ -86,23 +79,6 @@ const bootstrapsLayer = (instances: ReadonlyArray { - it.effect("publishes the concrete running distro without replacing the stable instance id", () => - Effect.gen(function* () { - const result = yield* getLocalEnvironmentBootstraps.handler(); - - assert.deepEqual(result, [ - { - id: "wsl:default", - label: "WSL (Ubuntu)", - runningDistro: "Ubuntu", - httpBaseUrl: "http://127.0.0.1:3774/", - wsBaseUrl: "ws://127.0.0.1:3774/", - bootstrapToken: "bootstrap-token", - }, - ]); - }).pipe(Effect.provide(bootstrapsLayer([defaultWslInstance]))), - ); - it.effect("hands out the current window's token to a backend launched with the secret", () => Effect.gen(function* () { const result = yield* getLocalEnvironmentBootstraps.handler(); @@ -197,119 +173,21 @@ describe("getLocalEnvironmentBootstraps", () => { }); }); -describe("getWindowFullscreenState", () => { - it.effect("reads the current native window state", () => { - const window = { isFullScreen: () => true } as Electron.BrowserWindow; - - return Effect.gen(function* () { - assert.isTrue(yield* getWindowFullscreenState.handler()); - }).pipe( - Effect.provide( - Layer.mock(ElectronWindow.ElectronWindow)({ - currentMainOrFirst: Effect.succeedSome(window), - }), - ), - ); - }); -}); - -describe("pasteAsText", () => { - it.effect( - "pastes into the focused guest only after the main renderer acknowledges the menu action", - () => { - const paste = vi.fn(); - const mainPaste = vi.fn(); - const window = { - webContents: { id: 42, paste: mainPaste }, - isDestroyed: () => false, - } as unknown as Electron.BrowserWindow; - focusedWebContents.mockReturnValue({ paste, isDestroyed: () => false }); - ownerWindow.mockReturnValue(window); - - return Effect.gen(function* () { - yield* pasteAsText.handler(undefined, { sender: { id: 42 } }); - assert.equal(paste.mock.calls.length, 1); - assert.equal(mainPaste.mock.calls.length, 0); - - yield* pasteAsText.handler(undefined, { sender: { id: 99 } }); - assert.equal(paste.mock.calls.length, 1); - ownerWindow.mockReturnValue({}); // A focused PiP/other BrowserWindow. - yield* pasteAsText.handler(undefined, { sender: { id: 42 } }); - assert.equal(paste.mock.calls.length, 1); - ownerWindow.mockReturnValue(null); // Detached contents. - yield* pasteAsText.handler(undefined, { sender: { id: 42 } }); - assert.equal(paste.mock.calls.length, 1); - ownerWindow.mockReturnValue(window); - focusedWebContents.mockReturnValue({ paste, isDestroyed: () => true }); - yield* pasteAsText.handler(undefined, { sender: { id: 42 } }); - assert.equal(paste.mock.calls.length, 1); - focusedWebContents.mockReturnValue(null); - yield* pasteAsText.handler(undefined, { sender: { id: 42 } }); - assert.equal(paste.mock.calls.length, 1); - }).pipe( - Effect.provide( - Layer.mock(ElectronWindow.ElectronWindow)({ - main: Effect.succeedSome(window), - }), - ), - ); - }, - ); -}); - -describe("pickProjectFavicon", () => { - const pickerLayer = ( - pickFiles: () => Effect.Effect>, - settings?: DesktopAppSettings.DesktopSettings, - ) => - Layer.mergeAll( - Layer.mock(ElectronDialog.ElectronDialog)({ pickFiles }), - Layer.mock(ElectronWindow.ElectronWindow)({ - focusedMainOrFirst: Effect.succeedNone, - }), - DesktopAppSettings.layerTest(settings), - ); - - it.effect("opens a single-image picker from the project directory", () => +describe("getRelayTelemetryEnabled", () => { + it.effect("reads the desktop host opt-out before returning the renderer policy", () => Effect.gen(function* () { - const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"])); - const result = yield* pickProjectFavicon - .handler("/project") - .pipe(Effect.provide(pickerLayer(pickFiles))); - - assert.strictEqual(result, "/pictures/icon.png"); - assert.deepEqual(pickFiles.mock.calls, [ - [ - { - owner: Option.none(), - defaultPath: Option.some("/project"), - multiple: false, - filters: [ - { - name: "Images", - extensions: ["avif", "gif", "ico", "jpeg", "jpg", "png", "svg", "webp", "icns"], - }, - ], - }, - ], - ]); - }), - ); - - it.effect("does not open a picker while the local environment is off", () => - Effect.gen(function* () { - const pickFiles = vi.fn(() => Effect.succeed(["/pictures/icon.png"])); - const result = yield* pickProjectFavicon.handler("/project").pipe( - Effect.provide( - pickerLayer(pickFiles, { - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - localEnvironmentEnabled: false, + assert.isFalse( + yield* getRelayTelemetryEnabled.handler().pipe( + Effect.provideService(HostProcess.Environment, { + T3CODE_TELEMETRY_ENABLED: "false", }), ), ); - - assert.strictEqual(result, null); - assert.strictEqual(pickFiles.mock.calls.length, 0); + assert.isTrue( + yield* getRelayTelemetryEnabled + .handler() + .pipe(Effect.provideService(HostProcess.Environment, {})), + ); }), ); }); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 6a2bfc7f1773d..f0d661b58bc9a 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -16,6 +16,7 @@ import { import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; @@ -71,6 +72,14 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ }), }); +export const getRelayTelemetryEnabled = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL, + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.window.getRelayTelemetryEnabled")(function* () { + return isRelayTracingEnabled(yield* HostProcess.Environment); + }), +}); + export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL, result: Schema.String, @@ -129,9 +138,7 @@ export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({ runningDistro, httpBaseUrl: httpBaseUrl.href, wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl), - // A backend launched with the desktop secret accepts whichever token the secret derives - // for the current window, so hand out that one rather than the token frozen into its - // launch config. + // Use the current window's derived token; the launch config's token may be stale. ...(bootstrap.desktopBootstrapSecret ? { bootstrapToken: yield* configuration.currentBootstrapToken } : bootstrap.desktopBootstrapToken @@ -185,9 +192,7 @@ export const pickFolder = DesktopIpc.makeIpcMethod({ targetId !== undefined && targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX); - // Fall back to the persisted wslDistro when the id is the - // "wsl:default" sentinel; the orchestrator uses the same fallback - // for the actual backend. + // Match the orchestrator's persisted distro fallback for wsl:default. const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null; const defaultPath = useWsl ? Option.fromNullishOr( @@ -352,6 +357,24 @@ export const pasteAsText = DesktopIpc.makeIpcMethod({ }), }); +export const revealWindow = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.REVEAL_WINDOW_CHANNEL, + payload: Schema.Undefined, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) { + const electronWindow = yield* ElectronWindow.ElectronWindow; + const window = yield* electronWindow.main; + if ( + event === undefined || + Option.isNone(window) || + window.value.webContents.id !== event.sender.id + ) { + return; + } + yield* electronWindow.reveal(window.value); + }), +}); + const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024; export const pickThemeFiles = DesktopIpc.makeIpcMethod({ diff --git a/apps/desktop/src/ipc/methods/wsl.test.ts b/apps/desktop/src/ipc/methods/wsl.test.ts index 644597eaf451d..af42c7264748d 100644 --- a/apps/desktop/src/ipc/methods/wsl.test.ts +++ b/apps/desktop/src/ipc/methods/wsl.test.ts @@ -17,7 +17,7 @@ import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts" import * as DesktopWindow from "../../window/DesktopWindow.ts"; import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts"; import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts"; -import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts"; +import { setWslBackendEnabled, setWslDistro, setWslOnly } from "./wsl.ts"; const decodeWslState = Schema.decodeUnknownEffect(DesktopWslStateSchema); @@ -84,73 +84,6 @@ const layerUnusedLifecycleRuntime = Layer.mergeAll( ); describe("WSL IPC", () => { - it.effect("does not probe WSL when local execution is disabled", () => - Effect.gen(function* () { - const wsl = yield* DesktopWslEnvironment.DesktopWslEnvironment; - const state = yield* getWslState.handler(undefined).pipe( - Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, { - ...wsl, - isAvailable: Effect.die("must not probe WSL"), - listDistros: Effect.die("must not enumerate distros"), - }), - Effect.flatMap(decodeWslState), - ); - assert.deepEqual(state, { - enabled: true, - distro: "Ubuntu", - available: false, - wslOnly: true, - distros: [], - preflightError: null, - }); - }).pipe( - Effect.provide( - Layer.mergeAll( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - localEnvironmentEnabled: false, - wslBackendEnabled: true, - wslDistro: "Ubuntu", - wslOnly: true, - }), - DesktopWslEnvironment.layerTest(), - layerWslBackend(), - ), - ), - ), - ); - - it.effect("stages dual-backend preferences before enabling without relaunching", () => { - const relaunchReasons: Array = []; - const layer = Layer.mergeAll( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: false, - wslOnly: true, - }), - DesktopWslEnvironment.layerTest({ isAvailable: true }), - layerWslBackend(), - layerLifecycle(relaunchReasons), - layerUnusedLifecycleRuntime, - ); - - return Effect.gen(function* () { - yield* invokeSetWslOnly(false); - yield* invokeSetWslDistro("Debian"); - const state = yield* invokeSetWslBackendEnabled(true); - - assert.deepEqual(state, { - enabled: true, - distro: "Debian", - available: true, - wslOnly: false, - distros: [], - preflightError: null, - }); - assert.deepEqual(relaunchReasons, []); - }).pipe(Effect.provide(layer)); - }); - it.effect("stages WSL-only preferences and relaunches only after enabling", () => { const relaunchReasons: Array = []; const layer = Layer.mergeAll( @@ -187,70 +120,6 @@ describe("WSL IPC", () => { }).pipe(Effect.provide(layer)); }); - it.effect("relaunches when enabling the WSL backend while wsl-only is already persisted", () => { - const relaunchReasons: Array = []; - let reconcileCount = 0; - const layer = Layer.mergeAll( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: false, - wslOnly: true, - }), - DesktopWslEnvironment.layerTest({ isAvailable: true }), - layerWslBackend({ - onReconcile: Effect.sync(() => { - reconcileCount += 1; - }), - }), - layerLifecycle(relaunchReasons), - layerUnusedLifecycleRuntime, - ); - - return Effect.gen(function* () { - const state = yield* invokeSetWslBackendEnabled(true); - - assert.deepEqual(state, { - enabled: true, - distro: null, - available: true, - wslOnly: true, - distros: [], - preflightError: null, - }); - assert.equal(reconcileCount, 0); - assert.deepEqual(relaunchReasons, ["wslBackendEnabled=true"]); - }).pipe(Effect.provide(layer)); - }); - - it.effect("reconciles in dual-backend mode without relaunching", () => { - const relaunchReasons: Array = []; - let reconcileCount = 0; - const layer = Layer.mergeAll( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: false, - wslOnly: false, - }), - DesktopWslEnvironment.layerTest({ isAvailable: true }), - layerWslBackend({ - onReconcile: Effect.sync(() => { - reconcileCount += 1; - }), - }), - layerLifecycle(relaunchReasons), - layerUnusedLifecycleRuntime, - ); - - return Effect.gen(function* () { - const state = yield* invokeSetWslBackendEnabled(true); - - assert.equal(state.enabled, true); - assert.equal(state.wslOnly, false); - assert.equal(reconcileCount, 1); - assert.deepEqual(relaunchReasons, []); - }).pipe(Effect.provide(layer)); - }); - it.effect("clears wsl-only before relaunching when disabling a WSL-only backend", () => { const relaunchReasons: Array = []; let reconcileCount = 0; @@ -289,33 +158,4 @@ describe("WSL IPC", () => { assert.deepEqual(relaunchReasons, ["wslBackendEnabled=false"]); }).pipe(Effect.provide(layer)); }); - - it.effect("clears dual-backend WSL without relaunching", () => { - const relaunchReasons: Array = []; - let reconcileCount = 0; - const layer = Layer.mergeAll( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: true, - wslOnly: false, - }), - DesktopWslEnvironment.layerTest({ isAvailable: true }), - layerWslBackend({ - onReconcile: Effect.sync(() => { - reconcileCount += 1; - }), - }), - layerLifecycle(relaunchReasons), - layerUnusedLifecycleRuntime, - ); - - return Effect.gen(function* () { - const state = yield* invokeSetWslBackendEnabled(false); - - assert.equal(state.enabled, false); - assert.equal(state.wslOnly, false); - assert.equal(reconcileCount, 1); - assert.deepEqual(relaunchReasons, []); - }).pipe(Effect.provide(layer)); - }); }); diff --git a/apps/desktop/src/ipc/methods/wsl.ts b/apps/desktop/src/ipc/methods/wsl.ts index 3c10f04512b4c..dac7550871460 100644 --- a/apps/desktop/src/ipc/methods/wsl.ts +++ b/apps/desktop/src/ipc/methods/wsl.ts @@ -22,8 +22,7 @@ const readWslState: Effect.Effect< const wslBackend = yield* DesktopWslBackend.DesktopWslBackend; const settings = yield* appSettings.get; const available = settings.localEnvironmentEnabled && (yield* wslEnvironment.isAvailable); - // Only enumerate distros when WSL is actually available — listDistros on a - // non-WSL host would spawn wsl.exe and hit the timeout for nothing. + // Listing distros on non-WSL hosts spawns wsl.exe only to time out. const distros = available ? yield* wslEnvironment.listDistros : []; const preflightError = yield* wslBackend.lastPreflightError; return { @@ -67,8 +66,7 @@ export const setWslBackendEnabled = makeIpcMethod({ yield* lifecycle.relaunch(`wslBackendEnabled=${enabled}`); return state; } - // Reconcile is idempotent and never fails; no need for a swap-style - // rollback when the WSL side has trouble coming up. + // Reconcile never fails, so no rollback is needed. yield* wslBackend.reconcile; return yield* readWslState; }), @@ -84,8 +82,7 @@ export const setWslDistro = makeIpcMethod({ const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const change = yield* appSettings.setWslDistro(distro); const settings = yield* appSettings.get; - // In active wsl-only mode the pool's primary IS the WSL backend, and its - // distro is captured when that backend starts, so relaunch to replace it. + // WSL-only primary backends capture their distro at startup; relaunch to change it. if (settings.wslBackendEnabled && settings.wslOnly && change.changed) { const state = yield* readWslState; yield* lifecycle.relaunch(`wslDistro=${distro ?? "default"}`); @@ -101,10 +98,7 @@ export const setWslOnly = makeIpcMethod({ payload: Schema.Boolean, result: DesktopWslStateSchema, handler: Effect.fn("desktop.ipc.wsl.setOnly")(function* (enabled) { - // wsl-only decides which backend the pool spins up as "primary", and that - // decision is captured once at layer init. A disabled WSL backend always - // leaves Windows primary active, so mode changes can be staged without a - // relaunch and applied by the subsequent enable call. + // The pool captures its primary at initialization; disabled WSL can stage mode changes until enable. const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const change = yield* appSettings.setWslOnly(enabled); diff --git a/apps/desktop/src/linuxSecretStorage.test.ts b/apps/desktop/src/linuxSecretStorage.test.ts index 157175e533324..ce7bc4004cf4c 100644 --- a/apps/desktop/src/linuxSecretStorage.test.ts +++ b/apps/desktop/src/linuxSecretStorage.test.ts @@ -1,37 +1,11 @@ import { describe, expect, it } from "vite-plus/test"; -import { - normalizeLinuxPasswordStorePreference, - resolveLinuxPasswordStoreSwitch, -} from "./linuxSecretStorage.ts"; +import { resolveLinuxPasswordStoreSwitch } from "./linuxSecretStorage.ts"; const autoSwitch = (env: NodeJS.ProcessEnv) => resolveLinuxPasswordStoreSwitch({ preference: "auto", env }); describe("linuxSecretStorage", () => { - it("preserves explicit supported password-store preferences", () => { - expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret"); - expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet"); - expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5"); - expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6"); - }); - - it("falls back to auto for missing or unsupported preferences", () => { - expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto"); - expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto"); - }); - - it("uses explicit preferences instead of the auto heuristic", () => { - for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) { - expect( - resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }), - ).toBe(preference); - expect( - resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }), - ).toBe(preference); - } - }); - it("leaves canonical KDE sessions to Electron's own wallet selection", () => { expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull(); expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull(); @@ -39,13 +13,6 @@ describe("linuxSecretStorage", () => { expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull(); }); - it("does not force a password-store for desktops Electron already recognizes", () => { - expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull(); - for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) { - expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull(); - } - }); - it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => { expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull(); expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull(); @@ -59,14 +26,12 @@ describe("linuxSecretStorage", () => { it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => { expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret"); - // Chromium stops at the first recognized value, so a later name cannot rescue the session. expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret"); expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret"); expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret"); }); it("does not treat lowercase desktop names as ones Electron recognizes", () => { - // Chromium matches these case-sensitively, so lowercase spellings reach basic text. expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret"); expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret"); expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe( diff --git a/apps/desktop/src/linuxSecretStorage.ts b/apps/desktop/src/linuxSecretStorage.ts index 81f891985b9d0..b6d41b43a6640 100644 --- a/apps/desktop/src/linuxSecretStorage.ts +++ b/apps/desktop/src/linuxSecretStorage.ts @@ -8,8 +8,7 @@ export type LinuxPasswordStoreSwitch = Exclude layerDesktopApplicationRuntime.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))), diff --git a/apps/desktop/src/permissions/MacPermissionHelper.test.ts b/apps/desktop/src/permissions/MacPermissionHelper.test.ts index e1160d9bbe381..0704f52254ef4 100644 --- a/apps/desktop/src/permissions/MacPermissionHelper.test.ts +++ b/apps/desktop/src/permissions/MacPermissionHelper.test.ts @@ -1,8 +1,6 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import * as Electron from "electron"; -import { MacPermissionHelper, macAppBundlePath } from "./MacPermissionHelper.ts"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; +import { MacPermissionHelper } from "./MacPermissionHelper.ts"; import type { SettingsWindow } from "./MacSettingsWindow.ts"; -import { MAC_PERMISSION_HELPER_CHANNEL } from "../ipc/channels.ts"; const mocks = vi.hoisted(() => ({ granted: false, @@ -110,193 +108,6 @@ afterEach(() => { const iconPaths = ["/bundle/prod-resources/icon.png"]; const open = () => helper.show("accessibility", "/bundle/mac-permission-preload.cjs", null, iconPaths); -function send(action: string, trusted = true) { - const window = windows.at(-1)!; - Electron.ipcMain.emit( - MAC_PERMISSION_HELPER_CHANNEL, - { - sender: trusted ? window.webContents : {}, - senderFrame: window.webContents.mainFrame, - }, - action, - ); -} - -describe("macAppBundlePath", () => { - it("resolves bundles with spaces and refuses non-bundle executables", () => { - expect(macAppBundlePath("/Applications/T3 Code.app/Contents/MacOS/T3 Code")).toBe( - "/Applications/T3 Code.app", - ); - expect(macAppBundlePath("/usr/local/bin/electron")).toBeUndefined(); - expect(macAppBundlePath("/Applications/T3 Code.app/other/MacOS/T3 Code")).toBeUndefined(); - }); -}); -it("drags the running app bundle only for the helper's own renderer", async () => { - await open(); - send("drag", false); - expect(mocks.startDrag).not.toHaveBeenCalled(); - send("drag"); - expect(mocks.createFromPath).toHaveBeenCalledWith("/bundle/prod-resources/icon.png"); - expect(mocks.startDrag).toHaveBeenCalledWith({ - file: "/Applications/T3 Code (Nightly).app", - icon: mocks.createFromPath.mock.results[0]!.value.resize(), - }); - send("finder"); - expect(mocks.showItemInFolder).toHaveBeenCalledWith("/Applications/T3 Code (Nightly).app"); -}); -it("rechecks permissions and releases resources when granted", async () => { - await open(); - mocks.granted = true; - await vi.advanceTimersByTimeAsync(1000); - expect(windows[0]!.destroyed).toBe(true); - expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0); - expect(vi.getTimerCount()).toBe(0); -}); -it("keeps only one helper and cleans up on dismissal", async () => { - await open(); - await helper.show("screen-recording", "/preload.cjs", null, iconPaths); - expect(windows[0]!.destroyed).toBe(true); - expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(1); - send("close"); - expect(windows[1]!.destroyed).toBe(true); - expect(vi.getTimerCount()).toBe(0); -}); -it("does not open for a permission already granted", async () => { - mocks.granted = true; - await open(); - expect(windows).toHaveLength(0); -}); -it("does not show a helper with a missing packaged icon", async () => { - mocks.createFromPath.mockReturnValueOnce({ isEmpty: () => true }); - await expect(open()).rejects.toThrow("packaged T3 Code icon is missing"); - expect(windows).toHaveLength(0); -}); -it("cleans up when the helper page fails to load", async () => { - mocks.loadURL.mockRejectedValueOnce(new Error("load failed")); - await expect(open()).rejects.toThrow("load failed"); - expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0); - expect(vi.getTimerCount()).toBe(0); -}); - -it("offers the Finder fallback when native dragging fails", async () => { - await open(); - mocks.startDrag.mockImplementationOnce(() => { - throw new Error("drag failed"); - }); - send("drag"); - expect(mocks.showItemInFolder).toHaveBeenCalledWith("/Applications/T3 Code (Nightly).app"); - expect(windows[0]!.destroyed).toBe(false); -}); - -it("returns focus to onboarding when the permission is granted", async () => { - const owner = new Electron.BrowserWindow({}); - await helper.show("screen-recording", "/preload.cjs", owner, iconPaths); - mocks.granted = true; - await vi.advanceTimersByTimeAsync(1000); - expect(owner.show).toHaveBeenCalledOnce(); - expect(owner.focus).toHaveBeenCalledOnce(); - expect(windows[1]!.destroyed).toBe(true); - expect(owner.listenerCount("closed")).toBe(0); -}); -it("closes the helper and stops checking when onboarding's window closes", async () => { - const owner = new Electron.BrowserWindow({}); - await helper.show("accessibility", "/preload.cjs", owner, iconPaths); - owner.destroy(); - expect(windows[1]!.destroyed).toBe(true); - expect(Electron.ipcMain.listenerCount(MAC_PERMISSION_HELPER_CHANNEL)).toBe(0); - expect(vi.getTimerCount()).toBe(0); -}); - -it("uses the packaged PNG when an earlier resource candidate is absent", async () => { - mocks.createFromPath.mockReturnValueOnce({ isEmpty: () => true }); - await helper.show("accessibility", "/preload.cjs", null, ["/missing/icon.png", ...iconPaths]); - send("drag"); - expect(mocks.startDrag).toHaveBeenCalled(); - expect(mocks.createFromPath).toHaveBeenLastCalledWith(iconPaths[0]); -}); - -it("docks inside Settings and hides when it is covered or closed", async () => { - await open(); - const window = windows[0]!; - const settings = { x: 367, y: 100, width: 723, height: 719, frontmost: true }; - mocks.settingsChanged!(settings); - expect(window.setBounds).toHaveBeenLastCalledWith( - { x: 599, y: 663, width: 475, height: 140 }, - false, - ); - expect(window.showInactive).toHaveBeenCalledOnce(); - mocks.settingsChanged!({ ...settings, x: -800, y: 200 }); - expect(window.setBounds).toHaveBeenLastCalledWith( - { x: -568, y: 763, width: 475, height: 140 }, - false, - ); - mocks.settingsChanged!({ ...settings, frontmost: false }); - expect(window.hide).toHaveBeenCalledOnce(); - mocks.settingsChanged!(null); - expect(window.destroyed).toBe(true); - helper.close(); - expect(mocks.stopTracking).toHaveBeenCalledOnce(); -}); - -it("returns to onboarding when the Settings window disappears", async () => { - const owner = new Electron.BrowserWindow({}); - owner.hide(); - await helper.show("accessibility", "/preload.cjs", owner, iconPaths); - mocks.settingsChanged!({ x: 100, y: 100, width: 723, height: 719, frontmost: true }); - mocks.settingsChanged!(null); - expect(owner.show).toHaveBeenCalledOnce(); - expect(owner.focus).toHaveBeenCalledOnce(); -}); -it("hides on tracking failure and resumes on a valid update", async () => { - await open(); - const state = { x: 100, y: 100, width: 723, height: 719, frontmost: true }; - mocks.settingsChanged!(state); - mocks.trackingFailed!(); - expect(windows[0]!.destroyed).toBe(false); - expect(windows[0]!.hide).toHaveBeenCalledOnce(); - mocks.settingsChanged!(state); - expect(windows[0]!.showInactive).toHaveBeenCalledTimes(2); -}); - -it("waits for an asynchronous Full Disk Access check and returns to the owner", async () => { - const owner = new Electron.BrowserWindow(); - const probe = vi.fn<() => Promise>().mockResolvedValue(false); - await helper.show( - "full-disk-access", - "/bundle/mac-permission-preload.cjs", - owner, - iconPaths, - probe, - ); - const pending = Promise.withResolvers(); - probe.mockReturnValue(pending.promise); - await vi.advanceTimersByTimeAsync(3000); - expect(probe).toHaveBeenCalledTimes(2); - expect(windows[1]!.destroyed).toBe(false); - pending.resolve(true); - await pending.promise; - expect(windows[1]!.destroyed).toBe(true); - expect(owner.focus).toHaveBeenCalledOnce(); - expect(vi.getTimerCount()).toBe(0); -}); - -it("keeps the helper open after a failed access check and retries", async () => { - const probe = vi.fn<() => Promise>().mockResolvedValue(false); - await helper.show( - "full-disk-access", - "/bundle/mac-permission-preload.cjs", - null, - iconPaths, - probe, - ); - probe.mockRejectedValueOnce(new Error("temporarily unavailable")); - await vi.advanceTimersByTimeAsync(1000); - expect(windows[0]!.destroyed).toBe(false); - probe.mockResolvedValue(true); - await vi.advanceTimersByTimeAsync(1000); - expect(windows[0]!.destroyed).toBe(true); -}); - it("does not reopen a superseded helper when its initial probe completes", async () => { const pending = Promise.withResolvers(); const first = helper.show( diff --git a/apps/desktop/src/permissions/MacPermissionHelper.ts b/apps/desktop/src/permissions/MacPermissionHelper.ts index dfc378cfd1c46..0b50e147785f7 100644 --- a/apps/desktop/src/permissions/MacPermissionHelper.ts +++ b/apps/desktop/src/permissions/MacPermissionHelper.ts @@ -18,7 +18,7 @@ const permissionGranted = (permission: MacPermission) => { return false; }; -export function macAppBundlePath(executable: string): string | undefined { +function macAppBundlePath(executable: string): string | undefined { return /^(.+\.app)\/Contents\/MacOS\/[^/]+$/.exec(executable)?.[1]; } @@ -88,8 +88,7 @@ export class MacPermissionHelper { const bundle = macAppBundlePath(Electron.app.getPath("exe")); if (!bundle) return; if (owner?.isDestroyed()) return; - // Finder's bundle-icon lookup can return the generic app icon for mounted artifacts. - // Use the same PNG that packaging uses to generate the app's macOS icon. + // Finder can return generic icons for mounted artifacts; use the packaging PNG. const appIcon = iconPaths .map((iconPath) => Electron.nativeImage.createFromPath(iconPath)) .find((image) => !image.isEmpty()); diff --git a/apps/desktop/src/permissions/MacSettingsWindow.test.ts b/apps/desktop/src/permissions/MacSettingsWindow.test.ts index 3071b00c32645..d07b4f5f9a76d 100644 --- a/apps/desktop/src/permissions/MacSettingsWindow.test.ts +++ b/apps/desktop/src/permissions/MacSettingsWindow.test.ts @@ -1,6 +1,6 @@ import * as NodeEvents from "node:events"; import { beforeEach, expect, it, vi } from "vite-plus/test"; -import { settingsHelperBounds, watchMacSettingsWindow } from "./MacSettingsWindow.ts"; +import { watchMacSettingsWindow } from "./MacSettingsWindow.ts"; const mocks = vi.hoisted(() => ({ spawn: vi.fn() })); vi.mock("node:child_process", () => ({ spawn: mocks.spawn })); @@ -15,17 +15,6 @@ beforeEach(() => { }); mocks.spawn.mockReturnValue(child); }); -it("places the helper inside small and large Settings windows across displays", () => { - for (const x of [-900, 20]) { - for (const width of [668, 1000]) { - const state = { x, y: 30, width, height: 700, frontmost: true }; - const helper = settingsHelperBounds(state); - expect(helper.x).toBeGreaterThanOrEqual(x + 216); - expect(helper.x + helper.width).toBeLessThanOrEqual(x + width - 16); - expect(helper.y + helper.height).toBe(714); - } - } -}); it("decodes partial updates and stops the one watcher process on disposal", () => { const changed = vi.fn(); const unavailable = vi.fn(); diff --git a/apps/desktop/src/permissions/MacSettingsWindow.ts b/apps/desktop/src/permissions/MacSettingsWindow.ts index f529d82b59413..e5acc09abbf92 100644 --- a/apps/desktop/src/permissions/MacSettingsWindow.ts +++ b/apps/desktop/src/permissions/MacSettingsWindow.ts @@ -15,9 +15,8 @@ const SettingsWindow = Schema.NullOr( export type SettingsWindow = typeof SettingsWindow.Type; const decodeSettingsWindow = Schema.decodeUnknownSync(Schema.fromJsonString(SettingsWindow)); -// Window bounds and owner PIDs are available before Screen Recording is granted. -// Use the bundle identifier rather than the localized app/window title. A single -// process avoids launching osascript repeatedly while the user moves Settings. +// Window bounds/PIDs need no Screen Recording grant. Match the bundle id to avoid localized titles. +// Keep one osascript process while Settings moves. const SETTINGS_WINDOW_SCRIPT = ` ObjC.import("CoreGraphics"); ObjC.import("AppKit"); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 2e046b7f238c8..4d57b30e2139a 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -46,8 +46,7 @@ try { const clientPlatform = process.platform; if (clientPlatform === "darwin") { - // Native window buttons do not scale with Chromium zoom. Keep their reserved - // space in native points, including when a zoomed page is reloaded. + // Native buttons ignore Chromium zoom; reserve native points even after reload. const syncWindowControlInset = () => { document.documentElement.style.setProperty( "--desktop-window-controls-inset", @@ -82,6 +81,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { } return result as ReturnType; }, + getRelayTelemetryEnabled: () => + ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL) === true, getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, setNotificationBadge: (badge) => @@ -96,6 +97,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.on(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler); return () => ipcRenderer.removeListener(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler); }, + revealWindow: () => ipcRenderer.invoke(IpcChannels.REVEAL_WINDOW_CHANNEL), getSystemLocale: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL); return typeof result === "string" ? result : null; @@ -250,6 +252,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { }, getWindowFullscreenState: () => ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true, + getWindowZoomFactor: () => webFrame.getZoomFactor(), onWindowFullscreenStateChange: (listener) => { const wrappedListener = (_event: Electron.IpcRendererEvent, fullscreen: unknown) => { if (typeof fullscreen !== "boolean") return; diff --git a/apps/desktop/src/preview/AnnotationIds.test.ts b/apps/desktop/src/preview/AnnotationIds.test.ts index 86eeccc92ab60..f1f4be518455c 100644 --- a/apps/desktop/src/preview/AnnotationIds.test.ts +++ b/apps/desktop/src/preview/AnnotationIds.test.ts @@ -4,8 +4,6 @@ import { createAnnotationIdSource } from "./AnnotationIds.ts"; describe("createAnnotationIdSource", () => { it("gives annotations picked on separate page loads distinct ids", () => { - // The picker preload runs afresh on every page load, while the composer - // keeps earlier annotations keyed by id. const firstLoad = createAnnotationIdSource(); firstLoad("element"); const firstAnnotation = firstLoad("annotation"); @@ -16,10 +14,4 @@ describe("createAnnotationIdSource", () => { expect(secondAnnotation).not.toBe(firstAnnotation); }); - - it("never repeats an id within one page load", () => { - const nextId = createAnnotationIdSource(); - const ids = Array.from({ length: 1_000 }, () => nextId("annotation")); - expect(new Set(ids).size).toBe(ids.length); - }); }); diff --git a/apps/desktop/src/preview/AnnotationIds.ts b/apps/desktop/src/preview/AnnotationIds.ts index 2262febdd1c15..082d6540a64d8 100644 --- a/apps/desktop/src/preview/AnnotationIds.ts +++ b/apps/desktop/src/preview/AnnotationIds.ts @@ -1,11 +1,4 @@ -/** - * Id source for picker annotations and their targets, one per page load. - * - * The composer keeps annotations keyed by id across preview reloads, and this - * preload restarts on every page load, so a bare counter reissues ids that a - * draft already holds. `getRandomValues` rather than `randomUUID`, because - * plain-http previews (LAN, tailnet) are not secure contexts. - */ +/** Per-load nonces avoid draft ID collisions; getRandomValues works on plain HTTP. */ export function createAnnotationIdSource(): (prefix: string) => string { const pageLoad = Array.from(crypto.getRandomValues(new Uint32Array(2)), (part) => part.toString(36), diff --git a/apps/desktop/src/preview/AnnotationKeyboard.test.ts b/apps/desktop/src/preview/AnnotationKeyboard.test.ts index 4124e548bec12..11fb9100e398f 100644 --- a/apps/desktop/src/preview/AnnotationKeyboard.test.ts +++ b/apps/desktop/src/preview/AnnotationKeyboard.test.ts @@ -14,24 +14,9 @@ const keyboardEvent = ( }); describe("resolveAnnotationSubmission", () => { - it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => { - expect(resolveAnnotationSubmission(keyboardEvent(), true)).toBe("attach"); - expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }), true)).toBe("send"); - expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }), true)).toBe("send"); - }); - it("leaves Shift+Enter and composition events available for editing", () => { expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }), true)).toBeNull(); expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }), true)).toBeNull(); expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }), true)).toBeNull(); }); - - it("keeps attach available while the send shortcut follows permission changes", () => { - const send = keyboardEvent({ ctrlKey: true }); - expect(resolveAnnotationSubmission(send, false)).toBeNull(); - expect(resolveAnnotationSubmission(keyboardEvent(), false)).toBe("attach"); - expect(resolveAnnotationSubmission(send, true)).toBe("send"); - expect(resolveAnnotationSubmission(send, false)).toBeNull(); - expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }), false)).toBeNull(); - }); }); diff --git a/apps/desktop/src/preview/AnnotationStyles.generated.ts b/apps/desktop/src/preview/AnnotationStyles.generated.ts index 53d83d584b32c..d02abc8ac6123 100644 --- a/apps/desktop/src/preview/AnnotationStyles.generated.ts +++ b/apps/desktop/src/preview/AnnotationStyles.generated.ts @@ -1,3 +1,3 @@ // Generated by scripts/build-preview-annotation-css.mjs. Do not edit. export const previewAnnotationStyles = - '/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', \'Noto Sans\', Arial, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring:where(:not(iframe)) {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.visible {\n visibility: visible;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: 0px;\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);\n}\n.h-8 {\n height: calc(var(--spacing) * 8);\n}\n.max-h-24 {\n max-height: calc(var(--spacing) * 24);\n}\n.max-h-\\[calc\\(100vh-16px\\)\\] {\n max-height: calc(100vh - 16px);\n}\n.max-h-\\[min\\(176px\\,calc\\(100vh-180px\\)\\)\\] {\n max-height: min(176px, calc(100vh - 180px));\n}\n.min-h-7 {\n min-height: calc(var(--spacing) * 7);\n}\n.min-h-8 {\n min-height: calc(var(--spacing) * 8);\n}\n.w-6 {\n width: calc(var(--spacing) * 6);\n}\n.w-8 {\n width: calc(var(--spacing) * 8);\n}\n.w-\\[min\\(360px\\,calc\\(100vw-16px\\)\\)\\] {\n width: min(360px, calc(100vw - 16px));\n}\n.w-full {\n width: 100%;\n}\n.max-w-70 {\n max-width: calc(var(--spacing) * 70);\n}\n.min-w-0 {\n min-width: 0px;\n}\n.flex-1 {\n flex: 1;\n}\n.shrink-0 {\n flex-shrink: 0;\n}\n.-translate-x-1\\/2 {\n --tw-translate-x: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.-translate-y-1\\/2 {\n --tw-translate-y: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.cursor-grab {\n cursor: grab;\n}\n.cursor-pointer {\n cursor: pointer;\n}\n.resize {\n resize: both;\n}\n.resize-none {\n resize: none;\n}\n.appearance-none {\n appearance: none;\n}\n.grid-cols-\\[22px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 22px minmax(0,1fr);\n}\n.grid-cols-\\[82px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 82px minmax(0,1fr);\n}\n.flex-col {\n flex-direction: column;\n}\n.items-center {\n align-items: center;\n}\n.items-start {\n align-items: flex-start;\n}\n.justify-center {\n justify-content: center;\n}\n.gap-0\\.5 {\n gap: calc(var(--spacing) * 0.5);\n}\n.gap-1 {\n gap: var(--spacing);\n}\n.gap-2 {\n gap: calc(var(--spacing) * 2);\n}\n.overflow-auto {\n overflow: auto;\n}\n.overflow-hidden {\n overflow: hidden;\n}\n.overflow-y-hidden {\n overflow-y: hidden;\n}\n.rounded-lg {\n border-radius: var(--t3-radius);\n}\n.rounded-md {\n border-radius: calc(var(--t3-radius) - 2px);\n}\n.rounded-xl {\n border-radius: calc(var(--t3-radius) + 4px);\n}\n.border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n}\n.border-0 {\n border-style: var(--tw-border-style);\n border-width: 0px;\n}\n.border-t {\n border-top-style: var(--tw-border-style);\n border-top-width: 1px;\n}\n.border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n}\n.border-border {\n border-color: var(--t3-border);\n}\n.border-input {\n border-color: var(--t3-input);\n}\n.border-primary {\n border-color: var(--t3-primary);\n}\n.border-transparent {\n border-color: transparent;\n}\n.border-b-transparent {\n border-bottom-color: transparent;\n}\n.bg-background {\n background-color: var(--t3-background);\n}\n.bg-muted {\n background-color: var(--t3-muted);\n}\n.bg-muted\\/40 {\n background-color: var(--t3-muted);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-muted) 40%, transparent);\n }\n}\n.bg-popover\\/95 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 95%, transparent);\n }\n}\n.bg-popover\\/96 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 96%, transparent);\n }\n}\n.bg-primary {\n background-color: var(--t3-primary);\n}\n.bg-primary\\/10 {\n background-color: var(--t3-primary);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-primary) 10%, transparent);\n }\n}\n.bg-transparent {\n background-color: transparent;\n}\n.p-0 {\n padding: 0px;\n}\n.p-1 {\n padding: var(--spacing);\n}\n.p-2 {\n padding: calc(var(--spacing) * 2);\n}\n.px-0 {\n padding-inline: 0px;\n}\n.px-1 {\n padding-inline: var(--spacing);\n}\n.px-2 {\n padding-inline: calc(var(--spacing) * 2);\n}\n.px-2\\.5 {\n padding-inline: calc(var(--spacing) * 2.5);\n}\n.px-3 {\n padding-inline: calc(var(--spacing) * 3);\n}\n.py-1 {\n padding-block: var(--spacing);\n}\n.py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n}\n.py-2 {\n padding-block: calc(var(--spacing) * 2);\n}\n.font-mono {\n font-family: var(--t3-font-mono);\n}\n.font-sans {\n font-family: var(--t3-font-sans);\n}\n.text-lg {\n font-size: var(--text-lg);\n line-height: var(--tw-leading, var(--text-lg--line-height));\n}\n.text-sm {\n font-size: var(--text-sm);\n line-height: var(--tw-leading, var(--text-sm--line-height));\n}\n.text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n}\n.leading-5 {\n --tw-leading: calc(var(--spacing) * 5);\n line-height: calc(var(--spacing) * 5);\n}\n.font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n}\n.font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n}\n.font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n}\n.text-foreground {\n color: var(--t3-foreground);\n}\n.text-muted-foreground {\n color: var(--t3-muted-foreground);\n}\n.text-popover-foreground {\n color: var(--t3-popover-foreground);\n}\n.text-primary {\n color: var(--t3-primary);\n}\n.text-primary-foreground {\n color: var(--t3-primary-foreground);\n}\n.shadow-2xl {\n --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-md {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-xs {\n --tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.05));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.ring-0 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.blur {\n --tw-blur: blur(8px);\n filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);\n}\n.backdrop-blur-xl {\n --tw-backdrop-blur: blur(var(--blur-xl));\n -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n}\n.outline-none {\n --tw-outline-style: none;\n outline-style: none;\n}\n.select-none {\n -webkit-user-select: none;\n user-select: none;\n}\n.placeholder\\:text-muted-foreground::placeholder {\n color: var(--t3-muted-foreground);\n}\n@media (hover: hover) {\n .hover\\:bg-accent:hover {\n background-color: var(--t3-accent);\n }\n .hover\\:bg-primary\\/90:hover {\n background-color: var(--t3-primary);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .hover\\:bg-primary\\/90:hover {\n background-color: color-mix(in oklab, var(--t3-primary) 90%, transparent);\n }\n }\n .hover\\:text-accent-foreground:hover {\n color: var(--t3-accent-foreground);\n }\n}\n.focus\\:border-b-primary:focus {\n border-bottom-color: var(--t3-primary);\n}\n.focus\\:ring-0:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.focus\\:outline-none:focus {\n --tw-outline-style: none;\n outline-style: none;\n}\n.disabled\\:pointer-events-none:disabled {\n pointer-events: none;\n}\n.disabled\\:opacity-60:disabled {\n opacity: 60%;\n}\n:host {\n --t3-font-sans: "DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,\n sans-serif;\n --t3-font-mono: "SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;\n --t3-radius: 0.625rem;\n --t3-background: white;\n --t3-foreground: oklch(0.269 0 0);\n --t3-popover: white;\n --t3-popover-foreground: oklch(0.269 0 0);\n --t3-primary: oklch(0.488 0.217 264);\n --t3-primary-foreground: white;\n --t3-muted: rgb(0 0 0 / 4%);\n --t3-muted-foreground: oklch(0.556 0 0);\n --t3-accent: rgb(0 0 0 / 4%);\n --t3-accent-foreground: oklch(0.269 0 0);\n --t3-border: rgb(0 0 0 / 8%);\n --t3-input: rgb(0 0 0 / 10%);\n --t3-ring: oklch(0.488 0.217 264);\n color: var(--t3-foreground);\n font-family: var(--t3-font-sans);\n}\n* {\n box-sizing: border-box;\n border-color: var(--t3-border);\n}\nbutton, input, select, textarea {\n font: inherit;\n}\nbutton:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {\n outline: 2px solid var(--t3-ring);\n @supports (color: color-mix(in lab, red, red)) {\n outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);\n }\n outline-offset: -2px;\n}\n@property --tw-translate-x {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-y {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-z {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-leading {\n syntax: "*";\n inherits: false;\n}\n@property --tw-font-weight {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-inset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-ring-inset {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-offset-width {\n syntax: "";\n inherits: false;\n initial-value: 0px;\n}\n@property --tw-ring-offset-color {\n syntax: "*";\n inherits: false;\n initial-value: #fff;\n}\n@property --tw-ring-offset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-sepia {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-drop-shadow-size {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-sepia {\n syntax: "*";\n inherits: false;\n}\n@layer properties {\n @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b)))) {\n *, ::before, ::after, ::backdrop {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-blur: initial;\n --tw-brightness: initial;\n --tw-contrast: initial;\n --tw-grayscale: initial;\n --tw-hue-rotate: initial;\n --tw-invert: initial;\n --tw-opacity: initial;\n --tw-saturate: initial;\n --tw-sepia: initial;\n --tw-drop-shadow: initial;\n --tw-drop-shadow-color: initial;\n --tw-drop-shadow-alpha: 100%;\n --tw-drop-shadow-size: initial;\n --tw-backdrop-blur: initial;\n --tw-backdrop-brightness: initial;\n --tw-backdrop-contrast: initial;\n --tw-backdrop-grayscale: initial;\n --tw-backdrop-hue-rotate: initial;\n --tw-backdrop-invert: initial;\n --tw-backdrop-opacity: initial;\n --tw-backdrop-saturate: initial;\n --tw-backdrop-sepia: initial;\n }\n }\n}\n'; + '/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', \'Noto Sans\', Arial, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring:where(:not(iframe)) {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.visible {\n visibility: visible;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: 0px;\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);\n}\n.h-8 {\n height: calc(var(--spacing) * 8);\n}\n.max-h-24 {\n max-height: calc(var(--spacing) * 24);\n}\n.max-h-\\[calc\\(100vh-16px\\)\\] {\n max-height: calc(100vh - 16px);\n}\n.max-h-\\[min\\(176px\\,calc\\(100vh-180px\\)\\)\\] {\n max-height: min(176px, calc(100vh - 180px));\n}\n.min-h-7 {\n min-height: calc(var(--spacing) * 7);\n}\n.min-h-8 {\n min-height: calc(var(--spacing) * 8);\n}\n.w-6 {\n width: calc(var(--spacing) * 6);\n}\n.w-8 {\n width: calc(var(--spacing) * 8);\n}\n.w-\\[min\\(360px\\,calc\\(100vw-16px\\)\\)\\] {\n width: min(360px, calc(100vw - 16px));\n}\n.w-full {\n width: 100%;\n}\n.max-w-70 {\n max-width: calc(var(--spacing) * 70);\n}\n.min-w-0 {\n min-width: 0px;\n}\n.flex-1 {\n flex: 1;\n}\n.shrink-0 {\n flex-shrink: 0;\n}\n.-translate-x-1\\/2 {\n --tw-translate-x: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.-translate-y-1\\/2 {\n --tw-translate-y: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.cursor-grab {\n cursor: grab;\n}\n.cursor-pointer {\n cursor: pointer;\n}\n.resize {\n resize: both;\n}\n.resize-none {\n resize: none;\n}\n.appearance-none {\n appearance: none;\n}\n.grid-cols-\\[22px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 22px minmax(0,1fr);\n}\n.grid-cols-\\[82px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 82px minmax(0,1fr);\n}\n.flex-col {\n flex-direction: column;\n}\n.items-center {\n align-items: center;\n}\n.items-start {\n align-items: flex-start;\n}\n.justify-center {\n justify-content: center;\n}\n.gap-0\\.5 {\n gap: calc(var(--spacing) * 0.5);\n}\n.gap-1 {\n gap: var(--spacing);\n}\n.gap-2 {\n gap: calc(var(--spacing) * 2);\n}\n.overflow-auto {\n overflow: auto;\n}\n.overflow-hidden {\n overflow: hidden;\n}\n.overflow-y-hidden {\n overflow-y: hidden;\n}\n.rounded-lg {\n border-radius: var(--t3-radius);\n}\n.rounded-md {\n border-radius: calc(var(--t3-radius) - 2px);\n}\n.rounded-xl {\n border-radius: calc(var(--t3-radius) + 4px);\n}\n.border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n}\n.border-0 {\n border-style: var(--tw-border-style);\n border-width: 0px;\n}\n.border-t {\n border-top-style: var(--tw-border-style);\n border-top-width: 1px;\n}\n.border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n}\n.border-border {\n border-color: var(--t3-border);\n}\n.border-input {\n border-color: var(--t3-input);\n}\n.border-primary {\n border-color: var(--t3-primary);\n}\n.border-transparent {\n border-color: transparent;\n}\n.border-b-transparent {\n border-bottom-color: transparent;\n}\n.bg-background {\n background-color: var(--t3-background);\n}\n.bg-muted {\n background-color: var(--t3-muted);\n}\n.bg-muted\\/40 {\n background-color: var(--t3-muted);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-muted) 40%, transparent);\n }\n}\n.bg-popover\\/95 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 95%, transparent);\n }\n}\n.bg-popover\\/96 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 96%, transparent);\n }\n}\n.bg-primary {\n background-color: var(--t3-primary);\n}\n.bg-primary\\/10 {\n background-color: var(--t3-primary);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-primary) 10%, transparent);\n }\n}\n.bg-transparent {\n background-color: transparent;\n}\n.p-0 {\n padding: 0px;\n}\n.p-1 {\n padding: var(--spacing);\n}\n.p-2 {\n padding: calc(var(--spacing) * 2);\n}\n.px-0 {\n padding-inline: 0px;\n}\n.px-1 {\n padding-inline: var(--spacing);\n}\n.px-2 {\n padding-inline: calc(var(--spacing) * 2);\n}\n.px-2\\.5 {\n padding-inline: calc(var(--spacing) * 2.5);\n}\n.px-3 {\n padding-inline: calc(var(--spacing) * 3);\n}\n.py-1 {\n padding-block: var(--spacing);\n}\n.py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n}\n.py-2 {\n padding-block: calc(var(--spacing) * 2);\n}\n.font-mono {\n font-family: var(--t3-font-mono);\n}\n.font-sans {\n font-family: var(--t3-font-sans);\n}\n.text-lg {\n font-size: var(--text-lg);\n line-height: var(--tw-leading, var(--text-lg--line-height));\n}\n.text-sm {\n font-size: var(--text-sm);\n line-height: var(--tw-leading, var(--text-sm--line-height));\n}\n.text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n}\n.leading-5 {\n --tw-leading: calc(var(--spacing) * 5);\n line-height: calc(var(--spacing) * 5);\n}\n.font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n}\n.font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n}\n.font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n}\n.text-foreground {\n color: var(--t3-foreground);\n}\n.text-muted-foreground {\n color: var(--t3-muted-foreground);\n}\n.text-popover-foreground {\n color: var(--t3-popover-foreground);\n}\n.text-primary {\n color: var(--t3-primary);\n}\n.text-primary-foreground {\n color: var(--t3-primary-foreground);\n}\n.shadow-2xl {\n --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-md {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-xs {\n --tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.05));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.ring-0 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.blur {\n --tw-blur: blur(8px);\n filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);\n}\n.backdrop-blur-xl {\n --tw-backdrop-blur: blur(var(--blur-xl));\n -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n}\n.outline-none {\n --tw-outline-style: none;\n outline-style: none;\n}\n.select-none {\n -webkit-user-select: none;\n user-select: none;\n}\n.placeholder\\:text-muted-foreground::placeholder {\n color: var(--t3-muted-foreground);\n}\n@media (hover: hover) {\n .hover\\:bg-accent:hover {\n background-color: var(--t3-accent);\n }\n .hover\\:bg-primary\\/90:hover {\n background-color: var(--t3-primary);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .hover\\:bg-primary\\/90:hover {\n background-color: color-mix(in oklab, var(--t3-primary) 90%, transparent);\n }\n }\n .hover\\:text-accent-foreground:hover {\n color: var(--t3-accent-foreground);\n }\n}\n.focus\\:border-b-primary:focus {\n border-bottom-color: var(--t3-primary);\n}\n.focus\\:ring-0:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.focus\\:outline-none:focus {\n --tw-outline-style: none;\n outline-style: none;\n}\n.disabled\\:pointer-events-none:disabled {\n pointer-events: none;\n}\n.disabled\\:opacity-60:disabled {\n opacity: 60%;\n}\n:host {\n --t3-font-sans: "DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,\n sans-serif;\n --t3-font-mono: "SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;\n --t3-radius: 0.625rem;\n --t3-background: white;\n --t3-foreground: oklch(0.269 0 0);\n --t3-popover: white;\n --t3-popover-foreground: oklch(0.269 0 0);\n --t3-primary: oklch(0.488 0.217 264);\n --t3-primary-foreground: white;\n --t3-muted: rgb(0 0 0 / 4%);\n --t3-muted-foreground: oklch(0.556 0 0);\n --t3-accent: rgb(0 0 0 / 4%);\n --t3-accent-foreground: oklch(0.269 0 0);\n --t3-border: rgb(0 0 0 / 8%);\n --t3-input: rgb(0 0 0 / 10%);\n --t3-ring: oklch(0.488 0.217 264);\n color: var(--t3-foreground);\n font-family: var(--t3-font-sans);\n}\n* {\n box-sizing: border-box;\n border-color: var(--t3-border);\n}\nbutton, input, select, textarea {\n font: inherit;\n}\nbutton:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {\n outline: 2px solid var(--t3-ring);\n @supports (color: color-mix(in lab, red, red)) {\n outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);\n }\n outline-offset: -2px;\n}\n@property --tw-translate-x {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-y {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-z {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-leading {\n syntax: "*";\n inherits: false;\n}\n@property --tw-font-weight {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-inset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-ring-inset {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-offset-width {\n syntax: "";\n inherits: false;\n initial-value: 0px;\n}\n@property --tw-ring-offset-color {\n syntax: "*";\n inherits: false;\n initial-value: #fff;\n}\n@property --tw-ring-offset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-sepia {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-drop-shadow-size {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-sepia {\n syntax: "*";\n inherits: false;\n}\n@layer properties {\n *, ::before, ::after, ::backdrop {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-blur: initial;\n --tw-brightness: initial;\n --tw-contrast: initial;\n --tw-grayscale: initial;\n --tw-hue-rotate: initial;\n --tw-invert: initial;\n --tw-opacity: initial;\n --tw-saturate: initial;\n --tw-sepia: initial;\n --tw-drop-shadow: initial;\n --tw-drop-shadow-color: initial;\n --tw-drop-shadow-alpha: 100%;\n --tw-drop-shadow-size: initial;\n --tw-backdrop-blur: initial;\n --tw-backdrop-brightness: initial;\n --tw-backdrop-contrast: initial;\n --tw-backdrop-grayscale: initial;\n --tw-backdrop-hue-rotate: initial;\n --tw-backdrop-invert: initial;\n --tw-backdrop-opacity: initial;\n --tw-backdrop-saturate: initial;\n --tw-backdrop-sepia: initial;\n }\n}\n'; diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts index 22e384834789f..c691ac15174d6 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts @@ -3,9 +3,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import * as Ref from "effect/Ref"; import * as BrowserSession from "../BrowserSession.ts"; import * as BrowserImport from "./BrowserImport.ts"; @@ -48,8 +46,6 @@ const withImporter = Effect.fnUntraced(function* () { const root = helium.userDataDirectory(context); if (root === undefined) throw new Error("Helium has no macOS user-data directory"); yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true }); - // The cookie database is what marks a source as installed, so a fixture - // without one is reported as absent before any other check runs. yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "db"); const importer = yield* BrowserImport.BrowserImport.pipe( @@ -98,8 +94,6 @@ describe("BrowserImport.importCookies", () => { Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const { importer, root } = yield* withImporter(); - // The lock Chromium leaves while it is running, dangling target and - // all. This must stop the import before it ever asks the keychain. yield* fileSystem.symlink("host-that-does-not-exist-1234", `${root}/SingletonLock`); const error = yield* importer @@ -120,31 +114,6 @@ describe("BrowserImport.importCookies", () => { }); describe("BrowserImport.writeCookies", () => { - it.effect("counts a rejected cookie and its domain as skipped", () => - Effect.gen(function* () { - let flushes = 0; - const result = yield* BrowserImport.writeCookies( - { - cookies: { - set: () => Promise.reject(new Error("fixture rejection")), - flushStore: () => { - flushes += 1; - return Promise.resolve(); - }, - }, - }, - { cookies: [cookie], undecryptable: 0, undecryptableHosts: [] }, - ); - - assert.deepEqual(result, { - imported: 0, - skipped: 1, - skippedDomains: ["rejected.example"], - }); - assert.equal(flushes, 0); - }), - ); - it.effect("flushes the store after writing, and reports success if the flush fails", () => Effect.gen(function* () { const events: Array = []; @@ -168,28 +137,4 @@ describe("BrowserImport.writeCookies", () => { assert.deepEqual(result, { imported: 2, skipped: 0, skippedDomains: [] }); }), ); - - it.effect("propagates interruption while writing a cookie", () => - Effect.gen(function* () { - const write = BrowserImport.writeCookies( - { - cookies: { - set: () => new Promise(() => {}), - flushStore: () => Promise.resolve(), - }, - }, - { cookies: [cookie], undecryptable: 0, undecryptableHosts: [] }, - ); - - const interrupted = yield* Ref.make(false); - const fiber = yield* write.pipe( - Effect.onInterrupt(() => Ref.set(interrupted, true)), - Effect.forkChild, - ); - yield* Effect.yieldNow; - yield* Fiber.interrupt(fiber); - - assert.isTrue(yield* Ref.get(interrupted)); - }), - ); }); diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts index e7f97eca26c02..c567b27411c0c 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts @@ -41,8 +41,7 @@ export class BrowserImportFailedError extends Schema.TaggedError 0) { yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe( Effect.tapError((error) => @@ -152,7 +147,7 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* ( return { imported, skipped, skippedDomains: [...skippedDomains].slice(0, 20) }; }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* BrowserImportMake() { const browserSession = yield* BrowserSession.BrowserSession; const platform = yield* HostProcess.Platform; @@ -200,19 +195,14 @@ export const make = Effect.gen(function* BrowserImportMake() { } if (platform === "darwin" && definition.engine === "chromium") { - // macOS attributes the Keychain prompt and the resulting ACL grant to the - // executable that asks, so record which one that was — in a packaged build - // it is the signed app, in dev whatever binary hosts the main process. + // macOS attributes Keychain prompts and ACL grants to the executable, which differs in dev and packaged builds. yield* Effect.logInfo("Reading browser cookie key from the keychain", { sourceId: definition.id, executablePath, }); } - // The profile directory arrives over IPC, so it is only honoured when the - // source itself reported it. Forwarding it unchecked would let `..` - // segments walk out of the browser's user-data directory and read any - // cookie database reachable on disk. + // IPC profile paths must match the source's listing to prevent traversal outside browser user-data. const sourceProfiles = yield* listSourceProfiles(definition, pathContext).pipe( Effect.provide(platformServices), ); @@ -226,8 +216,7 @@ export const make = Effect.gen(function* BrowserImportMake() { }); } - // The profile was listed against a database moments ago; resolve it again - // rather than assume a path, since a Chromium jar may sit under `Network/`. + // Re-resolve listed paths because Chromium jars may be under Network/. const databasePath = yield* resolveCookieDatabase( definition, pathContext, @@ -296,8 +285,7 @@ export const make = Effect.gen(function* BrowserImportMake() { ), ); - // Written one at a time rather than in parallel: Chromium's cookie store - // serialises writes anyway, and a rejected cookie should only cost itself. + // Chromium serializes writes; a rejected cookie should not prevent the others. return yield* writeCookies(session, result); }); diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts index eace39003e39d..e5aa05f268e43 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.test.ts @@ -38,26 +38,12 @@ const encryptWindowsV10 = (value: string | Buffer, key: Buffer): Uint8Array => { describe("cookieScope", () => { it("keeps a host-only cookie host-only", () => { - // Chromium stores a host-only cookie without a leading dot. Passing any - // `domain` to Electron makes it a domain cookie and re-adds the dot, which - // would expose the cookie to every subdomain it was never scoped to. expect(cookieScope("example.test", "/", true)).toEqual({ url: "https://example.test/", domain: undefined, }); }); - it("preserves a domain cookie's leading dot", () => { - expect(cookieScope(".example.test", "/app", true)).toEqual({ - url: "https://example.test/app", - domain: ".example.test", - }); - }); - - it("matches the scheme to the secure flag", () => { - expect(cookieScope("example.test", "/", false).url).toBe("http://example.test/"); - }); - it("brackets bare IPv6 hosts without duplicating existing brackets", () => { expect(cookieScope("::1", "/", false)).toEqual({ url: "http://[::1]/", @@ -299,8 +285,7 @@ describe("readChromiumCookieDatabase", () => { const filename = `${directory}/Cookies`; const cbcV10 = Buffer.from("0123456789abcdef"); const cbcV11 = Buffer.from("fedcba9876543210"); - // The key some Linux clients actually encrypted with (crbug.com/1195256): - // OSCrypt's derivation over an empty passphrase. + // Some Linux clients encrypted with an empty passphrase (crbug.com/1195256). const cbcEmpty = NodeCrypto.pbkdf2Sync("", "saltysalt", 1, 16, "sha1"); yield* Effect.gen(function* () { @@ -338,62 +323,6 @@ describe("readChromiumCookieDatabase", () => { }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); - it.effect("preserves arbitrary long encrypted values from pre-24 schemas", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3code-chromium-cookies-", - }); - const filename = `${directory}/Cookies`; - const key = Buffer.from("0123456789abcdef"); - const value = "x".repeat(32) + " legacy value"; - - yield* Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* sql`create table meta (key text primary key, value text not null)`; - yield* sql`insert into meta values ('version', 23)`; - yield* sql` - create table cookies ( - host_key text not null, name text not null, value text not null, - encrypted_value blob not null, path text not null, expires_utc integer not null, - is_secure integer not null, is_httponly integer not null, samesite integer not null, - top_frame_site_key text not null default '' - ) - `; - yield* sql`insert into cookies (host_key, name, value, encrypted_value, path, expires_utc, is_secure, is_httponly, samesite) values - ('legacy.example', 'legacy', '', ${encryptV10(value, key)}, '/', 0, 0, 0, 0)`; - }).pipe(Effect.provide(NodeSqliteClient.layer({ filename }))); - - const result = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin"); - expect(result.cookies[0]?.value).toBe(value); - expect(result.undecryptable).toBe(0); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - - it.effect("rejects a malformed text schema version", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3code-chromium-cookies-", - }); - const filename = `${directory}/Cookies`; - - yield* Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* sql`create table meta (key text primary key, value text not null)`; - yield* sql`insert into meta values ('version', 'not-a-version')`; - }).pipe(Effect.provide(NodeSqliteClient.layer({ filename }))); - - const error = yield* readChromiumCookieDatabase( - filename, - { cbcV10: Buffer.from("0123456789abcdef") }, - "darwin", - ).pipe(Effect.flip); - - expect(error._tag).toBe("SchemaError"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - it.effect("treats unversioned encrypted values as legacy plaintext on macOS and Linux", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -419,9 +348,6 @@ describe("readChromiumCookieDatabase", () => { ('legacy.example', 'legacy', '', ${Buffer.from("legacy cleartext")}, '/', 0, 0, 0, 0)`; }).pipe(Effect.provide(NodeSqliteClient.layer({ filename }))); - // Chromium's OSCrypt returns unprefixed data as-is on both platforms - // (os_crypt_mac.mm and os_crypt_linux.cc: "old data saved as clear - // text"), so neither counts it as undecryptable. const mac = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "darwin"); const linux = yield* readChromiumCookieDatabase(filename, { cbcV10: key }, "linux"); diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts index d5f7592b26068..63fef9fb3c808 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumCookies.ts @@ -73,12 +73,7 @@ const decodeSchemaVersion = Schema.decodeUnknownEffect( Schema.Tuple([Schema.Struct({ value: SchemaVersion })]), ); -/** - * Unspecified is imported as Electron's own `unspecified` rather than pinned to - * Lax, so the target browser applies its default just as the source did; - * anything unrecognised lands there too, since guessing "none" would widen a - * cookie's scope on import. - */ +/** Preserve unspecified SameSite; guessing no_restriction would widen cookie scope. */ const sameSiteFromColumn = (value: number): ImportedCookie["sameSite"] => { if (value === 0) return "no_restriction"; if (value === 1) return "lax"; @@ -86,21 +81,14 @@ const sameSiteFromColumn = (value: number): ImportedCookie["sameSite"] => { return "unspecified"; }; -/** - * The microsecond value overflows JavaScript's safe integer range and - * `node:sqlite` refuses to narrow it, so the division happens in SQL and this - * only ever sees seconds. - */ +/** Convert microseconds in SQL: node:sqlite refuses integers beyond JavaScript's safe range. */ const WEBKIT_EPOCH_OFFSET_SECONDS = 11_644_473_600; const toUnixSeconds = (webkitSeconds: number): number | undefined => { if (webkitSeconds <= 0) return undefined; return webkitSeconds - WEBKIT_EPOCH_OFFSET_SECONDS; }; -/** - * Chromium >= 127 prefixes the plaintext with SHA-256 of the host key, binding - * a cookie to its domain. - */ +// Chromium 127+ prefixes plaintext with the host-key SHA-256 to bind its domain. const stripDomainBinding = ( plaintext: Buffer, domain: string, @@ -161,17 +149,14 @@ export function decryptChromiumValue( const prefix = buffer.subarray(0, 3).toString("latin1"); const payload = buffer.subarray(3); - // Windows' legacy v10 format is AES-256-GCM. App-bound records use v20 and - // intentionally have no key here, so they fall through as undecryptable. + // Windows v10 uses AES-256-GCM; app-bound v20 records have no key here. if (platform === "win32") { return prefix === "v10" && keys.gcmV10 ? decryptGcm(payload, keys.gcmV10, domain, schemaVersion) : null; } - // Chromium retries a failed record with a key derived from an empty - // passphrase, because some Linux clients wrote data that way - // (crbug.com/1195256). + // Retry the empty-passphrase key used by some Linux clients (crbug.com/1195256). if (prefix === "v10") { if (!keys.cbcV10) return null; return ( diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumKeys.module.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumKeys.module.test.ts deleted file mode 100644 index 890d9e2715865..0000000000000 --- a/apps/desktop/src/preview/BrowserImport/ChromiumKeys.module.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { expect, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import { ChildProcessSpawner } from "effect/process"; -import { vi } from "vite-plus/test"; - -vi.mock("@napi-rs/keyring", () => { - throw new Error("Cannot find native binding"); -}); - -it.effect("reports an unavailable keychain when the macOS binding cannot load", () => - Effect.gen(function* () { - const { ChromiumKeyError, resolveChromiumKeys } = yield* Effect.promise( - () => import("./ChromiumKeys.ts"), - ); - const error = yield* resolveChromiumKeys({ - platform: "darwin", - keychainService: "Chrome Safe Storage", - keychainAccount: "Chrome", - linuxSecretApplication: undefined, - }).pipe(Effect.flip); - - expect(error).toBeInstanceOf(ChromiumKeyError); - expect(error.reason).toBe("keychainUnavailable"); - expect(error.cause).toBeInstanceOf(Error); - }).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("must not spawn")), - ), - ), -); diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumKeys.test.ts b/apps/desktop/src/preview/BrowserImport/ChromiumKeys.test.ts index cdeb67e0e8cc7..6fc5b7ae9faa1 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumKeys.test.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumKeys.test.ts @@ -96,14 +96,6 @@ describe("macOS Chromium secrets", () => { }).pipe(Effect.provide(layerNoProcesses)), ); - it.effect("reports a missing keychain entry", () => - Effect.gen(function* () { - getPassword.mockReturnValue(null); - const error = yield* resolveChromiumKeys(request).pipe(Effect.flip); - expect(error.reason).toBe("keychainItemMissing"); - }).pipe(Effect.provide(layerNoProcesses)), - ); - it.effect("preserves a denied keychain approval", () => Effect.gen(function* () { const denied = new Error("User denied access"); @@ -154,40 +146,6 @@ describe("Linux Chromium secrets", () => { ), ); - it.effect("looks up the browser's libsecret application attribute", () => { - let captured: CapturedCommand | undefined; - return Effect.gen(function* () { - const keys = yield* resolveChromiumKeys({ - platform: "linux", - keychainService: "ignored macOS service", - keychainAccount: "ignored macOS account", - linuxSecretApplication: "msedge", - }); - - expect(captured?.command).toBe("/bundled/browser-secret/t3-browser-secret"); - expect(captured?.args).toEqual(["msedge"]); - expect(captured?.options.stdin).toBe("ignore"); - expect(keys.cbcV10).toHaveLength(16); - expect(keys.cbcV11).toHaveLength(16); - }).pipe( - Effect.provide( - layerHelper({ stdout: "linux-secret", capture: (value) => (captured = value) }), - ), - ); - }); - - it.effect("reports an unavailable Secret Service backend as a read failure", () => - Effect.gen(function* () { - const error = yield* readLinuxSecret("chrome").pipe(Effect.flip); - expect(error).toBeInstanceOf(ChromiumKeyError); - expect(error.reason).toBe("keychainUnavailable"); - }).pipe( - Effect.provide( - layerHelper({ stderr: "Cannot autolaunch D-Bus without X11 $DISPLAY", exitCode: 1 }), - ), - ), - ); - it.effect("preserves trailing whitespace in the stored secret", () => Effect.gen(function* () { const secret = yield* readLinuxSecret("chrome"); @@ -240,51 +198,6 @@ describe("Linux Chromium secrets", () => { ); }, ); - - it.effect("does not discard a denied unlock prompt while resolving keys", () => - Effect.gen(function* () { - const error = yield* resolveChromiumKeys({ - platform: "linux", - keychainService: undefined, - keychainAccount: undefined, - linuxSecretApplication: "brave", - }).pipe(Effect.flip); - expect(error.reason).toBe("needsKeychainApproval"); - }).pipe(Effect.provide(layerHelper({ stderr: "Keyring is locked", exitCode: 3 }))), - ); - - it.effect("keeps the v10 fallback when the Secret Service backend is unavailable", () => - Effect.gen(function* () { - const keys = yield* resolveChromiumKeys({ - platform: "linux", - keychainService: undefined, - keychainAccount: undefined, - linuxSecretApplication: "chrome", - }); - expect(keys.cbcV10).toHaveLength(16); - expect(keys.cbcV11).toBeUndefined(); - }).pipe( - Effect.provide( - layerHelper({ - stderr: "Cannot autolaunch D-Bus without X11 $DISPLAY", - exitCode: 1, - }), - ), - ), - ); - - it.effect("keeps the v10 fallback when no matching v11 secret exists", () => - Effect.gen(function* () { - const keys = yield* resolveChromiumKeys({ - platform: "linux", - keychainService: undefined, - keychainAccount: undefined, - linuxSecretApplication: "vivaldi", - }); - expect(keys.cbcV10).toHaveLength(16); - expect(keys.cbcV11).toBeUndefined(); - }).pipe(Effect.provide(layerHelper({ exitCode: 2 }))), - ); }); describe("Windows Chromium secrets", () => { diff --git a/apps/desktop/src/preview/BrowserImport/ChromiumKeys.ts b/apps/desktop/src/preview/BrowserImport/ChromiumKeys.ts index 0d91ebe5a3746..bc9edcfe52a80 100644 --- a/apps/desktop/src/preview/BrowserImport/ChromiumKeys.ts +++ b/apps/desktop/src/preview/BrowserImport/ChromiumKeys.ts @@ -14,7 +14,6 @@ import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts"; const KEY_SALT = "saltysalt"; const KEY_LENGTH = 16; -/** macOS stretches the keychain secret; Linux uses a single iteration. */ const MAC_KEY_ITERATIONS = 1003; const LINUX_KEY_ITERATIONS = 1; /** Chromium's documented fallback passphrase when no Linux keyring is present. */ @@ -42,11 +41,7 @@ export interface ChromiumKeyMaterial { readonly cbcV10?: Buffer; readonly cbcV11?: Buffer; readonly cbcV11Error?: ChromiumKeyError; - /** - * AES-128-CBC from an empty passphrase. Some Linux clients wrote records - * with it (crbug.com/1195256), so Chromium — and this import — retry with it - * after a record's own key fails. - */ + /** Linux clients can encrypt with an empty passphrase; retry it on failure (crbug.com/1195256). */ readonly cbcEmpty?: Buffer; readonly gcmV10?: Buffer; } @@ -54,21 +49,12 @@ export interface ChromiumKeyMaterial { const derive = (passphrase: string, iterations: number) => NodeCrypto.pbkdf2Sync(passphrase, KEY_SALT, iterations, KEY_LENGTH, "sha1"); -/** - * Via the CLI the prompt says "security" and "Always Allow" grants trust to a - * tool every process on the machine can invoke; in-process it names this app - * and the grant belongs to it. - * - * Deliberately untimed: macOS answers this with a modal, and a timeout racing - * the user means the prompt can be approved while nothing is left listening, - * which reads as "approving did nothing". - */ +// In-process Keychain access attributes grants to this app. Keep modal prompts untimed to preserve their listener. const readKeychainSecret = Effect.fn("ChromiumKeys.readKeychainSecret")(function* ( service: string, account: string, ) { - // Only macOS cookie imports need this binding; loading it at startup can - // prevent the desktop from opening on platforms that never use it. + // Loading the macOS binding at startup can prevent other platforms from opening. const Keyring = yield* Effect.tryPromise({ try: () => import("@napi-rs/keyring"), catch: (cause) => new ChromiumKeyError({ reason: "keychainUnavailable", cause }), @@ -90,10 +76,7 @@ const readKeychainSecret = Effect.fn("ChromiumKeys.readKeychainSecret")(function return secret; }); -/** - * Its exit codes distinguish a missing key, denied access, and an unavailable - * keyring without parsing localized error messages. - */ +/** Exit codes distinguish missing keys, denied access, and unavailable keyrings without localized message parsing. */ export const readLinuxSecret = Effect.fn("ChromiumKeys.readLinuxSecret")(function* ( application: string, ) { @@ -267,13 +250,10 @@ export const resolveChromiumKeys = Effect.fn("ChromiumKeys.resolveChromiumKeys") } if (request.platform === "linux") { - // The fallback passphrase always applies to `v10` records; a keyring - // secret, when one is reachable, additionally unlocks `v11`. + // v10 always uses the fallback passphrase; a keyring secret additionally unlocks v11. const keyringSecret = request.linuxSecretApplication ? yield* readLinuxSecret(request.linuxSecretApplication).pipe( - // v10 remains importable when Secret Service is absent or does not - // contain a key. An explicit denial/lock/cancel remains a consent - // failure rather than being silently downgraded. + // Missing Secret Service or keys must not block v10; explicit denial, lock, or cancellation remains a consent failure. Effect.catchIf( (error) => error.reason !== "needsKeychainApproval", (error) => Effect.succeed(error), diff --git a/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts b/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts index 18bcd7581b4fc..402397d3fde60 100644 --- a/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts +++ b/apps/desktop/src/preview/BrowserImport/CookieDatabase.test.ts @@ -62,23 +62,4 @@ describe("snapshotCookieDatabase", () => { }), ), ); - - it.effect("removes a successful snapshot when its scope closes", () => - runNode( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const sourceDirectory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3code-cookie-cleanup-source-", - }); - const source = path.join(sourceDirectory, "Cookies"); - yield* Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - yield* sql`CREATE TABLE cookies(name TEXT NOT NULL)`; - }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: source }))); - const snapshot = yield* snapshotCookieDatabase(source).pipe(Effect.scoped); - expect(yield* fileSystem.exists(snapshot)).toBe(false); - }), - ), - ); }); diff --git a/apps/desktop/src/preview/BrowserImport/CookieDatabase.ts b/apps/desktop/src/preview/BrowserImport/CookieDatabase.ts index 2eb6cdbb5a17b..6c708e6023df2 100644 --- a/apps/desktop/src/preview/BrowserImport/CookieDatabase.ts +++ b/apps/desktop/src/preview/BrowserImport/CookieDatabase.ts @@ -9,11 +9,7 @@ export interface ImportedCookie { readonly url: string; readonly name: string; readonly value: string; - /** - * A host-only cookie leaves this undefined: Electron treats any `domain` it is given as marking a - * domain cookie and re-adds the dot, which would widen the cookie to every subdomain of the host - * it was scoped to, and rejects `__Host-` cookies, which require it to be absent. - */ + /** Leave host-only cookies undefined; Electron widens any supplied domain and rejects __Host- cookies with one. */ readonly domain: string | undefined; readonly path: string; readonly secure: boolean; @@ -47,10 +43,7 @@ export const cookieScope = ( export const bareHost = (host: string): string => (host.startsWith(".") ? host.slice(1) : host); -/** - * Both engines keep the file open with WAL while the browser runs, so reading in place can observe - * a torn write. Copying also guarantees we never open the browser's own file for writing. - */ +/** Copy before reading to avoid live WAL writes and never open the source browser database for writing. */ export const snapshotCookieDatabase = Effect.fn("CookieDatabase.snapshotCookieDatabase")(function* ( cookiePath: string, tempPrefix = "t3code-cookie-import-", diff --git a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts index 9f28387d4f140..be41318fa01e6 100644 --- a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.test.ts @@ -37,8 +37,6 @@ const writeFirefoxCookieDatabase = Effect.fnUntraced(function* ( rawSameSite?: number; originAttributes?: string; }>, - // Firefox stamps `PRAGMA user_version`; schema 16+ stores `expiry` in - // milliseconds, earlier ones in seconds. schemaVersion = 15, ) { const fileSystem = yield* FileSystem.FileSystem; @@ -46,7 +44,6 @@ const writeFirefoxCookieDatabase = Effect.fnUntraced(function* ( const file = `${directory}/cookies.sqlite`; const database = new NodeSqlite.DatabaseSync(file); database.exec(`pragma user_version = ${schemaVersion}`); - // Only schemas 10–14 have `rawSameSite`; the schema-15 migration dropped it. const hasRawSameSite = schemaVersion >= 10 && schemaVersion <= 14; database.exec( `create table moz_cookies ( @@ -87,8 +84,6 @@ describe("readFirefoxCookies", () => { it.effect("converts millisecond expiries from schema 16 and newer", () => run( Effect.gen(function* () { - // Firefox 129 (schema 16) migrated `expiry` to milliseconds; older - // profiles still hold seconds. Both must land as seconds for Electron. const row = { host: "example.test", name: "c", @@ -169,9 +164,6 @@ describe("readFirefoxCookies", () => { it.effect("keeps an unset SameSite unspecified instead of widening it to none", () => run( Effect.gen(function* () { - // nsICookie::SAMESITE_UNSET is 256, a cookie that carried no SameSite - // attribute. It is not SAMESITE_NONE (0), which is an explicit opt-in - // to cross-site use; importing it as "none" would widen its scope. const row = { host: "example.test", name: "c", @@ -198,8 +190,6 @@ describe("readFirefoxCookies", () => { it.effect("imports rows whose SameSite was never written", () => run( Effect.gen(function* () { - // Schema 9 added `sameSite` without a default, so rows from before the - // upgrade hold NULL. One such row must not fail the whole import. const row = { host: "example.test", name: "c", @@ -229,10 +219,6 @@ describe("readFirefoxCookies", () => { it.effect("applies the schema-15 rawSameSite rule to older databases", () => run( Effect.gen(function* () { - // Schemas 10–14 defaulted `sameSite` to Lax and kept the declared value - // in `rawSameSite`. Firefox's own migration to 15 turns "Lax by - // default, None declared" into Unset; an unmigrated database has to be - // read the same way or an undeclared cookie becomes an explicit Lax. const row = { host: "example.test", name: "c", @@ -276,9 +262,6 @@ describe("readFirefoxCookies", () => { sameSite: 1, }, { - // Same host, name and path as above: Firefox keeps these apart by - // container, Electron cannot, so importing both would hand the - // profile whichever one happened to be written last. host: "mail.test", name: "session", value: "work-container", @@ -340,8 +323,6 @@ describe("readFirefoxCookies", () => { describe("parseFirefoxProfiles", () => { it.effect("reads named profiles and ignores Install sections", () => Effect.gen(function* () { - // `Install*` sections name a default profile but do not describe one, so - // counting them would invent a profile whose directory does not exist. const parsed = yield* parsePosixFirefoxProfiles( [ "[Install4F96D1932A9F858E]", @@ -370,14 +351,6 @@ describe("parseFirefoxProfiles", () => { }), ); - it.effect("falls back to the path when a profile has no name", () => - Effect.gen(function* () { - expect( - yield* parsePosixFirefoxProfiles(["[Profile0]", "Path=Profiles/x.default"].join("\n")), - ).toEqual([{ directory: "Profiles/x.default", name: "Profiles/x.default" }]); - }), - ); - it.effect.each([ { platform: "Linux", root: "/home/user/.mozilla/firefox" }, { platform: "macOS", root: "/Users/user/Library/Application Support/Firefox" }, diff --git a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.ts b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.ts index 16ad488f5cc2f..a5fddb14d22df 100644 --- a/apps/desktop/src/preview/BrowserImport/FirefoxCookies.ts +++ b/apps/desktop/src/preview/BrowserImport/FirefoxCookies.ts @@ -17,23 +17,12 @@ export class FirefoxCookieReadError extends Schema.TaggedError= FIREFOX_RAW_SAMESITE_FIRST_SCHEMA && schemaVersion <= FIREFOX_RAW_SAMESITE_LAST_SCHEMA; - // Firefox isolates cookies per container and per private window via - // `originAttributes` (`^userContextId=2`, `^privateBrowsingId=1`); - // Electron has no equivalent, so importing them all would collapse - // several identities onto one host/name/path and hand the profile an - // arbitrary container's session. + // Electron cannot represent Firefox containers/private windows; importing them would collapse distinct sessions. const raw = hasRawSameSite ? yield* sql` select host, name, value, path, expiry, isSecure, isHttpOnly, sameSite, rawSameSite diff --git a/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts b/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts index fa369c8edc62d..7e92334c957de 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariCookies.test.ts @@ -11,7 +11,6 @@ import { parseBinaryCookies, readSafariCookies, safariAccessDenied, - safariAccessGranted, SafariCookieReadError, } from "./SafariCookies.ts"; @@ -138,17 +137,6 @@ describe("parseBinaryCookies", () => { }); }); - it("brackets IPv6 hosts in the cookie URL", () => { - const file = encodeBinaryCookies([ - { domain: "::1", name: "local", path: "/", value: "v", flags: 0, expiry: 0 }, - ]); - - expect(parseBinaryCookies(file)[0]).toMatchObject({ - url: "http://[::1]/", - domain: undefined, - }); - }); - it("reads cookies spread across multiple pages", () => { const first = encodeBinaryCookies([ { domain: "a.test", name: "one", path: "/", value: "1", flags: 0, expiry: 1 }, @@ -170,8 +158,6 @@ describe("parseBinaryCookies", () => { }); it("rejects a page that runs past the end of the file", () => { - // `Buffer.subarray` clamps rather than throwing, so an overlong first page - // swallows the second one's bytes and advances the cursor past the end. const first = encodeBinaryCookies([ { domain: "a.test", name: "one", path: "/", value: "1", flags: 0, expiry: 1 }, ]); @@ -191,34 +177,6 @@ describe("parseBinaryCookies", () => { ); }); - it("rejects a record whose declared size runs past its page", () => { - const valid = encodeBinaryCookies([ - { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 }, - ]); - const pageStart = 8 + 4; - const recordStart = pageStart + valid.readUInt32LE(pageStart + 8); - const corrupt = Buffer.from(valid); - corrupt.writeUInt32LE(0xffff, recordStart); - - expect(() => parseBinaryCookies(corrupt)).toThrow(SafariCookieReadError); - }); - - it("rejects records truncated inside the 56-byte header", () => { - const valid = encodeBinaryCookies([ - { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 }, - ]); - const pageStart = 8 + 4; - const recordStart = pageStart + valid.readUInt32LE(pageStart + 8); - - for (let size = 48; size < 56; size += 1) { - const corrupt = Buffer.from(valid); - corrupt.writeUInt32LE(size, recordStart); - expect(() => parseBinaryCookies(corrupt), `record size ${size}`).toThrow( - SafariCookieReadError, - ); - } - }); - it("rejects record offsets that point into the page header or an earlier record", () => { const valid = encodeBinaryCookies([ { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 }, @@ -238,22 +196,6 @@ describe("parseBinaryCookies", () => { expect(parseBinaryCookies(valid)).toHaveLength(2); }); - it("rejects string offsets that point into the record header", () => { - const valid = encodeBinaryCookies([ - { domain: "a.test", name: "n", path: "/", value: "v", expiry: 1_000, flags: 0 }, - ]); - const pageStart = 8 + 4; - const recordStart = pageStart + valid.readUInt32LE(pageStart + 8); - - for (const offsetField of [16, 20, 24, 28]) { - const corrupt = Buffer.from(valid); - corrupt.writeUInt32LE(55, recordStart + offsetField); - expect(() => parseBinaryCookies(corrupt), `offset field ${offsetField}`).toThrow( - SafariCookieReadError, - ); - } - }); - it("accepts the checksum and property-list trailer Safari writes", () => { const file = encodeBinaryCookies([ { domain: "a.test", name: "c", path: "/", value: "v", flags: 0, expiry: 0 }, @@ -266,53 +208,11 @@ describe("parseBinaryCookies", () => { expect(parseBinaryCookies(Buffer.concat([file, checksum]))).toHaveLength(1); expect(parseBinaryCookies(Buffer.concat([file, checksum, plistLength, plist]))).toHaveLength(1); }); - - it("rejects a jar whose page table stops short of its contents", () => { - const first = encodeBinaryCookies([ - { domain: "a.test", name: "c", path: "/", value: "v", flags: 0, expiry: 0 }, - ]); - const extraPage = encodeBinaryCookies([ - { domain: "b.test", name: "d", path: "/", value: "w", flags: 0, expiry: 0 }, - ]).subarray(12); - - expect(() => parseBinaryCookies(Buffer.concat([first, extraPage]))).toThrow( - SafariCookieReadError, - ); - const badLength = Buffer.alloc(4); - badLength.writeUInt32BE(99, 0); - expect(() => - parseBinaryCookies(Buffer.concat([first, Buffer.alloc(8), badLength, Buffer.from("x")])), - ).toThrow(SafariCookieReadError); - }); - - it("rejects a file that is not binarycookies", () => { - expect(() => parseBinaryCookies(Buffer.from("not a cookie jar"))).toThrow( - SafariCookieReadError, - ); - }); }); describe("readSafariCookies", () => { - it.effect("adds the cookie path and parser cause to malformed jar failures", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" }); - const jar = `${directory}/Cookies.binarycookies`; - yield* fileSystem.writeFileString(jar, "not a cookie jar"); - - const error = yield* readSafariCookies(jar).pipe(Effect.flip); - - assert.equal(error.reason, "readFailed"); - assert.equal(error.cookieDatabasePath, jar); - assert.instanceOf(error.cause, SafariCookieReadError); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - it.effect("reports a TCC denial as a permission the user can grant", () => Effect.gen(function* () { - // What Full Disk Access actually looks like: the file is there, the read - // is refused with EPERM. Effect tags that `Unknown`, not - // `PermissionDenied`, so the reader has to look at the errno. const denied = PlatformError.systemError({ _tag: "Unknown", module: "FileSystem", @@ -329,54 +229,9 @@ describe("readSafariCookies", () => { assert.equal(error.reason, "needsFullDiskAccess"); }), ); - - it.effect("reports an ordinary permission failure as a plain read failure", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" }); - const jar = `${directory}/Cookies.binarycookies`; - yield* fileSystem.writeFile(jar, new Uint8Array([0x63, 0x6f, 0x6f, 0x6b])); - yield* fileSystem.chmod(jar, 0o000); - - const error = yield* readSafariCookies(jar).pipe(Effect.flip); - - assert.equal(error.reason, "readFailed"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - - it.effect("reports a missing jar as a plain read failure", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-safari-" }); - - const error = yield* readSafariCookies(`${directory}/absent.binarycookies`).pipe(Effect.flip); - - assert.equal(error.reason, "readFailed"); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); }); describe("safariAccessDenied", () => { - const eperm = PlatformError.systemError({ - _tag: "Unknown", - module: "FileSystem", - method: "open", - pathOrDescriptor: "/protected/Cookies.binarycookies", - cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }), - }); - const denied = (error: PlatformError.PlatformError) => - FileSystem.layerNoop({ open: () => Effect.fail(error) }); - - it.effect("reports TCC's EPERM as a missing Full Disk Access grant", () => - Effect.gen(function* () { - assert.isTrue( - yield* safariAccessDenied("/protected/Cookies.binarycookies").pipe( - Effect.provide(denied(eperm)), - ), - ); - }), - ); - it.effect("does not read a readable jar, or any other failure, as denied", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -393,48 +248,7 @@ describe("isPermissionDenied", () => { const platformError = (reasonTag: string, code: string): PlatformError.PlatformError => ({ _tag: "PlatformError", reason: { _tag: reasonTag, cause: { code } } }) as never; - it("treats a TCC EPERM denial as permission denied", () => { - expect(isPermissionDenied(platformError("Unknown", "EPERM"))).toBe(true); - }); - it("does not send an ordinary EACCES failure to the Full Disk Access grant", () => { expect(isPermissionDenied(platformError("PermissionDenied", "EACCES"))).toBe(false); }); - - it("does not treat an unrelated failure as permission denied", () => { - expect(isPermissionDenied(platformError("Unknown", "EIO"))).toBe(false); - }); -}); - -describe("safariAccessGranted", () => { - it.effect("only reports a successful read-only open as granted", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-safari-permission-", - }); - const jar = `${directory}/Cookies.binarycookies`; - assert.isFalse(yield* safariAccessGranted(jar)); - yield* fileSystem.writeFileString(jar, "no cookie parsing needed"); - assert.isTrue(yield* safariAccessGranted(jar)); - yield* fileSystem.remove(jar); - assert.isFalse(yield* safariAccessGranted(jar)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - - it.effect("does not mistake TCC denial for a grant", () => - Effect.gen(function* () { - const denied = PlatformError.systemError({ - _tag: "Unknown", - module: "FileSystem", - method: "open", - cause: Object.assign(new Error("operation not permitted"), { code: "EPERM" }), - }); - assert.isFalse( - yield* safariAccessGranted("/protected/Cookies.binarycookies").pipe( - Effect.provide(FileSystem.layerNoop({ open: () => Effect.fail(denied) })), - ), - ); - }), - ); }); diff --git a/apps/desktop/src/preview/BrowserImport/SafariCookies.ts b/apps/desktop/src/preview/BrowserImport/SafariCookies.ts index 15f8de8d3a36e..118f9af1f776a 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariCookies.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariCookies.ts @@ -8,7 +8,6 @@ import { cookieScope, type ImportedCookie } from "./CookieDatabase.ts"; /** Safari's timestamps count seconds from 2001-01-01, not the UNIX epoch. */ const APPLE_EPOCH_OFFSET_SECONDS = 978_307_200; -/** `u32 0x00000100`, `u32le cookieCount`, then one `u32le` offset per cookie. */ const COOKIE_PAGE_HEADER_SIZE = 12; const COOKIE_RECORD_HEADER_SIZE = 56; @@ -46,10 +45,7 @@ export function parseBinaryCookies(buffer: Buffer): ReadonlyArray buffer.length) { throw new SafariCookieReadError({ reason: "readFailed" }); } @@ -74,9 +70,7 @@ export function parseBinaryCookies(buffer: Buffer): ReadonlyArray page.length) { throw new SafariCookieReadError({ reason: "readFailed" }); } - // Every record accepted so far, so a later offset cannot point back into - // one of them: the page header, the offset table, and earlier records are - // all bytes that would otherwise parse as a fabricated cookie. + // Reject offsets into the header, table, or earlier records to avoid fabricated cookies. const accepted: Array = []; for (let index = 0; index < cookieCount; index += 1) { const cookieStart = page.readUInt32LE(8 + index * 4); @@ -120,9 +114,6 @@ export function parseBinaryCookies(buffer: Buffer): ReadonlyArray 0 ? Math.floor(expiry) + APPLE_EPOCH_OFFSET_SECONDS : undefined; cookies.push({ - // Safari marks domain cookies with a leading dot like the other - // engines, so the shared scope rule applies: host-only cookies keep - // `domain` undefined, or Electron widens them to every subdomain. ...cookieScope(domain, path || "/", secure), name, value, @@ -130,17 +121,13 @@ export function parseBinaryCookies(buffer: Buffer): ReadonlyArray { - // TCC denies with EPERM, which Effect tags `Unknown` rather than - // `PermissionDenied` — so the errno is what identifies it. EACCES (and the - // `PermissionDenied` tag it maps to) is an ordinary POSIX permission or - // ACL failure that granting Full Disk Access cannot fix, so it stays a plain - // read failure rather than sending the user to a grant that won't help. + // TCC returns EPERM (Effect Unknown); EACCES is a POSIX denial that Full Disk Access cannot fix. const code = (error.reason as { cause?: { code?: unknown } }).cause?.code; return code === "EPERM"; }; -/** - * `stat` succeeds on the jar inside Safari's container even without Full Disk - * Access — that is what lets the listing find it — so presence alone cannot - * tell granted from denied. - * */ +/** stat succeeds without Full Disk Access, so presence alone does not prove readable cookies. */ export const safariAccessDenied = Effect.fnUntraced(function* (cookiePath: string) { const fileSystem = yield* FileSystem.FileSystem; return yield* fileSystem.open(cookiePath, { flag: "r" }).pipe( diff --git a/apps/desktop/src/preview/BrowserImport/SafariPermission.ts b/apps/desktop/src/preview/BrowserImport/SafariPermission.ts index 1bad2ec2b3572..8e1d2c3d62d4d 100644 --- a/apps/desktop/src/preview/BrowserImport/SafariPermission.ts +++ b/apps/desktop/src/preview/BrowserImport/SafariPermission.ts @@ -17,8 +17,7 @@ export const safariPermissionCheck = Effect.gen(function* () { if (!safari || context.platform !== "darwin") return false; const defaultJar = yield* resolveCookieDatabase(safari, context, "."); if (defaultJar !== undefined) return yield* safariAccessGranted(defaultJar); - // A Safari installation can have cookies only in a named profile. Rediscover - // those stores after a grant, since TCC may have hidden their metadata before. + // Rediscover named profiles after a grant; TCC may have hidden their metadata. const profiles = yield* listSourceProfiles(safari, context); for (const profile of profiles) { const jar = yield* resolveCookieDatabase(safari, context, profile.directory); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts index 30bf5a7fd9234..d0444d42e5021 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts @@ -7,10 +7,8 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; import * as Scope from "effect/Scope"; -import * as Stream from "effect/Stream"; -import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { ChildProcessSpawner } from "effect/process"; import * as NodeSqlite from "node:sqlite"; import type { BrowserImportPathContext } from "./Sources.ts"; @@ -18,13 +16,10 @@ import { BROWSER_IMPORT_SOURCES, chromiumProcessIsAlive, chromiumSingletonLockIsHeld, - cookieDatabaseCandidatePaths, firefoxSymlinkLockIsHeld, resolveCookieDatabase, isSourceInstalled, isSourceRunning, - isWindowsLockHeldError, - posixLockIsHeld, listSourceProfiles, sourcePathContext, windowsChromiumCookiesAreHeld, @@ -33,44 +28,6 @@ import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!; -describe("Linux Chromium secret applications", () => { - it("pins the libsecret application attribute for each supported fork", () => { - assert.deepEqual( - Object.fromEntries( - BROWSER_IMPORT_SOURCES.filter((source) => source.platforms.includes("linux")).map( - (source) => [source.id, source.linuxSecretApplication], - ), - ), - { - chrome: "chrome", - edge: "msedge", - brave: "brave", - vivaldi: "vivaldi", - opera: "opera", - helium: "chromium", - firefox: undefined, - }, - ); - }); -}); - -const platformError = (reasonTag: string): PlatformError.PlatformError => - ({ _tag: "PlatformError", reason: { _tag: reasonTag } }) as never; - -describe("Windows browser lock errors", () => { - it("treats sharing and lock violations reported as Busy as held", () => { - assert.isTrue(isWindowsLockHeldError(platformError("Busy"))); - }); - - it("does not treat access denied as proof of an active lock", () => { - assert.isFalse(isWindowsLockHeldError(platformError("PermissionDenied"))); - }); - - it("does not treat a missing lock file as held", () => { - assert.isFalse(isWindowsLockHeldError(platformError("NotFound"))); - }); -}); - const withSourceHome = Effect.fnUntraced(function* () { const fileSystem = yield* FileSystem.FileSystem; const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-sources-" }); @@ -119,69 +76,6 @@ const writeFirefoxCookieDatabase = ( database.close(); }); -describe("Helium on Linux", () => { - it.effect.skipIf(!symlinksSupported)("discovers its profiles and checks the user-data lock", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-helium-linux-" }); - const context = yield* sourcePathContext.pipe( - Effect.provideService(HostProcess.Environment, { HOME: home }), - Effect.provideService(HostProcess.Platform, "linux"), - ); - const root = `${home}/.config/net.imput.helium`; - yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true }); - yield* writeCookieDatabase(`${root}/Default/Cookies`, 3); - yield* fileSystem.writeFileString( - `${root}/Local State`, - '{"profile":{"info_cache":{"Default":{"name":"Personal"}}}}', - ); - - assert.include(helium.platforms, "linux"); - assert.isTrue(yield* isSourceInstalled(helium, context)); - assert.deepEqual(yield* listSourceProfiles(helium, context), [ - { directory: "Default", name: "Personal", cookieCount: 3 }, - ]); - assert.isFalse(yield* isSourceRunning(helium, context)); - yield* fileSystem.symlink("foreign-host-4242", `${root}/SingletonLock`); - assert.isTrue(yield* isSourceRunning(helium, context)); - }), - ), - ); -}); - -describe("Helium on Windows", () => { - it.effect("uses Helium's local app-data profile while other Chromium forks stay disabled", () => - run( - Effect.gen(function* () { - const context = yield* sourcePathContext.pipe( - Effect.provideService(HostProcess.Environment, { - USERPROFILE: "C:\\Users\\browser-user", - LOCALAPPDATA: "C:\\Users\\browser-user\\AppData\\Local", - }), - Effect.provideService(HostProcess.Platform, "win32"), - ); - - assert.include(helium.platforms, "win32"); - assert.equal( - helium.userDataDirectory(context), - context.path.join( - "C:\\Users\\browser-user\\AppData\\Local", - "imput", - "Helium", - "User Data", - ), - ); - for (const source of BROWSER_IMPORT_SOURCES) { - if (source.engine === "chromium" && source.id !== "helium") { - assert.notInclude(source.platforms, "win32"); - } - } - }), - ), - ); -}); - describe("isSourceRunning", () => { it.effect("uses the held cookie database as Chromium's Windows running signal", () => run( @@ -225,9 +119,6 @@ describe("isSourceRunning", () => { const context = yield* withSourceHome(); assert.isFalse(yield* isSourceRunning(helium, context)); - // Chromium points the lock at `-`, a target that never - // exists on disk. A check that follows the link reports a running - // browser as closed, letting an import read a live, mid-write database. yield* fileSystem.symlink( "host-that-does-not-exist-1234", `${userDataDirectory(context)}/SingletonLock`, @@ -237,32 +128,6 @@ describe("isSourceRunning", () => { }), ), ); - - it.effect.skipIf(!symlinksSupported)( - "uses the provided hostname to classify Chromium locks", - () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const paths = yield* withSourceHome(); - yield* fileSystem.symlink( - "lock-owner-99999999", - `${helium.userDataDirectory(paths)}/SingletonLock`, - ); - - assert.isTrue( - yield* isSourceRunning(helium, paths).pipe( - Effect.provideService(HostProcess.Hostname, "another-host"), - ), - ); - assert.isFalse( - yield* isSourceRunning(helium, paths).pipe( - Effect.provideService(HostProcess.Hostname, "lock-owner"), - ), - ); - }), - ), - ); }); describe("chromiumSingletonLockIsHeld", () => { @@ -280,12 +145,6 @@ describe("chromiumSingletonLockIsHeld", () => { }), ); - it.effect("keeps a live PID on the current host", () => - chromiumSingletonLockIsHeld("current-host-4321", "current-host", () => - Effect.succeed(true), - ).pipe(Effect.tap((held) => Effect.sync(() => assert.isTrue(held)))), - ); - it.effect("keeps foreign-host and malformed targets without probing a PID", () => Effect.gen(function* () { let probes = 0; @@ -347,9 +206,6 @@ describe("isSourceInstalled", () => { const context = yield* withSourceHome(); const root = userDataDirectory(context); - // Installers for native messaging hosts create an empty user-data - // directory for every Chromium fork they know about, so treating the - // directory as evidence lists browsers the user does not have. yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true }); assert.isFalse(yield* isSourceInstalled(helium, context)); @@ -367,81 +223,9 @@ describe("isSourceInstalled", () => { }), ), ); - - it.effect("detects a Chromium 127+ install with cookies under Network/", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const context = yield* withSourceHome(); - const root = userDataDirectory(context); - - yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true }); - yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "db"); - assert.isTrue(yield* isSourceInstalled(helium, context)); - }), - ), - ); - - it.effect.skipIf(!symlinksSupported)( - "follows cookie database symlinks when detecting profiles", - () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const context = yield* withSourceHome(); - const root = userDataDirectory(context); - yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true }); - yield* fileSystem.symlink("missing-cookies", `${root}/Default/Cookies`); - - assert.deepEqual(yield* listSourceProfiles(helium, context), []); - assert.isFalse(yield* isSourceInstalled(helium, context)); - - yield* fileSystem.writeFileString(`${root}/Default/missing-cookies`, "db"); - assert.deepEqual(yield* listSourceProfiles(helium, context), [ - { directory: "Default", name: "Default" }, - ]); - assert.isTrue(yield* isSourceInstalled(helium, context)); - }), - ), - ); }); describe("listSourceProfiles", () => { - it.effect("ignores a profile whose Cookies entry is not a file", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const paths = yield* withSourceHome(); - const root = helium.userDataDirectory(paths); - yield* fileSystem.makeDirectory(`${root}/Broken/Cookies`, { recursive: true }); - yield* fileSystem.makeDirectory(`${root}/Real`, { recursive: true }); - yield* fileSystem.writeFileString(`${root}/Real/Cookies`, "db"); - - assert.deepEqual(yield* listSourceProfiles(helium, paths), [ - { directory: "Real", name: "Real" }, - ]); - assert.isTrue(yield* isSourceInstalled(helium, paths)); - }), - ), - ); - - it.effect("discovers profiles by their cookie database when Local State is absent", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const context = yield* withSourceHome(); - const root = userDataDirectory(context); - yield* fileSystem.makeDirectory(`${root}/Profile 1`, { recursive: true }); - yield* fileSystem.writeFileString(`${root}/Profile 1/Cookies`, "db"); - yield* fileSystem.makeDirectory(`${root}/NativeMessagingHosts`, { recursive: true }); - - assert.deepEqual(yield* listSourceProfiles(helium, context), [ - { directory: "Profile 1", name: "Profile 1" }, - ]); - }), - ), - ); - it.effect("reads the profile names the browser shows", () => run( Effect.gen(function* () { @@ -477,72 +261,6 @@ describe("listSourceProfiles", () => { ), ); - it.effect("reports nothing when no directory holds a cookie database", () => - run( - Effect.gen(function* () { - const context = yield* withSourceHome(); - assert.deepEqual(yield* listSourceProfiles(helium, context), []); - }), - ), - ); - - it.effect("drops Firefox profiles that hold no cookie database", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const context = yield* withSourceHome(); - const root = firefox.userDataDirectory(context)!; - yield* fileSystem.makeDirectory(root, { recursive: true }); - yield* fileSystem.writeFileString( - `${root}/profiles.ini`, - `[Profile0] -Name=original -IsRelative=1 -Path=Profiles/abcd.default-release -Default=1 - -[Profile1] -Name=empty -IsRelative=1 -Path=Profiles/wxyz.empty -`, - ); - yield* fileSystem.makeDirectory(`${root}/Profiles/abcd.default-release`, { - recursive: true, - }); - yield* fileSystem.writeFileString( - `${root}/Profiles/abcd.default-release/cookies.sqlite`, - "db", - ); - yield* fileSystem.makeDirectory(`${root}/Profiles/wxyz.empty`, { recursive: true }); - - assert.deepEqual(yield* listSourceProfiles(firefox, context), [ - { directory: context.path.join("Profiles", "abcd.default-release"), name: "original" }, - ]); - }), - ), - ); - - it.effect("drops empty profiles when falling back to the Profiles/ scan", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const context = yield* withSourceHome(); - const root = firefox.userDataDirectory(context)!; - yield* fileSystem.makeDirectory(`${root}/Profiles/filled.default`, { recursive: true }); - yield* fileSystem.writeFileString(`${root}/Profiles/filled.default/cookies.sqlite`, "db"); - yield* fileSystem.makeDirectory(`${root}/Profiles/empty.default`, { recursive: true }); - - assert.deepEqual(yield* listSourceProfiles(firefox, context), [ - { - directory: context.path.join("Profiles", "filled.default"), - name: "filled.default", - }, - ]); - }), - ), - ); - it.effect("discovers profiles with cookies under Network/ (Chromium 127+)", () => run( Effect.gen(function* () { @@ -559,21 +277,6 @@ Path=Profiles/wxyz.empty ), ); - it.effect("counts a profile's cookies without decrypting them", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const paths = yield* withSourceHome(); - const root = helium.userDataDirectory(paths); - yield* fileSystem.makeDirectory(`${root}/Default`, { recursive: true }); - yield* writeCookieDatabase(`${root}/Default/Cookies`, 3); - - const [profile] = yield* listSourceProfiles(helium, paths); - assert.equal(profile?.cookieCount, 3); - }), - ), - ); - it.effect("falls through to the legacy database when Network/Cookies is a directory", () => run( Effect.gen(function* () { @@ -592,33 +295,12 @@ Path=Profiles/wxyz.empty }); describe("cookieDatabaseCandidatePaths", () => { - it.effect("prefers Network/Cookies and falls back to the legacy Cookies", () => - run( - Effect.gen(function* () { - const context = yield* withSourceHome(); - const profile = context.path.join( - context.home, - "Library", - "Application Support", - "net.imput.helium", - "Profile 1", - ); - assert.deepEqual(cookieDatabaseCandidatePaths(helium, context, "Profile 1"), [ - context.path.join(profile, "Network", "Cookies"), - context.path.join(profile, "Cookies"), - ]); - }), - ), - ); - it.effect("resolves the live Network/ jar over a leftover root Cookies", () => run( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const context = yield* withSourceHome(); const root = userDataDirectory(context); - // Chromium 96+ keeps sessions in Network/; a root Cookies left behind - // by the move is stale and must not be the one imported. yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true }); yield* fileSystem.writeFileString(`${root}/Default/Network/Cookies`, "live"); yield* fileSystem.writeFileString(`${root}/Default/Cookies`, "stale"); @@ -632,25 +314,6 @@ describe("cookieDatabaseCandidatePaths", () => { }), ), ); - - it.effect("returns only cookies.sqlite for Firefox", () => - run( - Effect.gen(function* () { - const path = yield* Path.Path; - const context = yield* sourcePathContext.pipe( - Effect.provideService(HostProcess.Environment, { HOME: "/tmp/test" }), - Effect.provideService(HostProcess.Platform, "darwin"), - ); - const candidates = cookieDatabaseCandidatePaths(firefox, context, "Profiles/abc.default"); - assert.deepEqual(candidates, [ - path.join( - "/tmp/test", - "Library/Application Support/Firefox/Profiles/abc.default/cookies.sqlite", - ), - ]); - }), - ), - ); }); const firefox = BROWSER_IMPORT_SOURCES.find((source) => source.id === "firefox")!; @@ -894,90 +557,19 @@ describe("isSourceRunning for Firefox", () => { yield* fileSystem.writeFileString(`${root}/lock`, ""); assert.isFalse(yield* isSourceRunning(firefox, context)); - // `.parentlock` is deliberately left on disk after a clean exit as a - // last-used marker, so an unlocked one is not evidence of a running - // browser — treating it as one blocked every import after first use. yield* fileSystem.writeFileString(`${profile}/.parentlock`, ""); assert.isFalse(yield* isSourceRunning(firefox, context)); - // The `lock` symlink is what Firefox removes on exit; a live pid in - // its target means the profile is held. yield* fileSystem.symlink(`127.0.0.1:+${process.pid}`, `${profile}/lock`); assert.isTrue(yield* isSourceRunning(firefox, context)); }), ), ); - it.effect("reports not-held when no interpreter can run the fcntl probe", () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-lock-" }); - const lock = `${directory}/.parentlock`; - yield* fileSystem.writeFileString(lock, ""); - assert.isFalse(yield* posixLockIsHeld(lock, ["/nonexistent/python3"])); - assert.isFalse(yield* posixLockIsHeld(lock, ["/usr/bin/false"])); - }), - ), - ); - - // Holds the lock with python3's fcntl, which does not exist on Windows. - it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( - "detects a live fcntl lock on .parentlock, as macOS Firefox leaves it", - () => - run( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" }); - const context = yield* sourcePathContext.pipe( - Effect.provideService(HostProcess.Environment, { HOME: home }), - Effect.provideService(HostProcess.Platform, "darwin"), - ); - const root = firefox.userDataDirectory(context)!; - const profile = `${root}/Profiles/abcd.default-release`; - yield* fileSystem.makeDirectory(profile, { recursive: true }); - yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db"); - const parentLock = `${profile}/.parentlock`; - yield* fileSystem.writeFileString(parentLock, ""); - - const holder = yield* spawner.spawn( - ChildProcess.make( - "python3", - [ - "-c", - "import fcntl,os,sys,time\n" + - "fd=os.open(sys.argv[1],os.O_WRONLY)\n" + - "fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)\n" + - "print('locked',flush=True)\n" + - "time.sleep(30)", - parentLock, - ], - { stdin: "ignore" }, - ), - ); - yield* holder.stdout.pipe( - Stream.decodeText(), - Stream.splitLines, - Stream.filter((line) => line.trim() === "locked"), - Stream.take(1), - Stream.runDrain, - ); - - assert.isTrue(yield* isSourceRunning(firefox, context)); - yield* holder.kill(); - }), - ), - ); - it.effect("reads a Firefox lock symlink's pid to tell live from crashed", () => Effect.gen(function* () { const alive = (pid: number) => Effect.succeed(pid === 4242); - // The resolver may hand Firefox any of the machine's addresses, not - // just 127.0.0.1 — 127.0.1.1 on Debian-style hosts, a LAN address - // elsewhere — so every local address counts as ours. const local = new Set(["127.0.0.1", "127.0.1.1", "192.168.1.20"]); - // Both the plain and the fcntl-marked (`+`) forms carry the pid. assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.0.1:4242", local, alive)); assert.isTrue(yield* firefoxSymlinkLockIsHeld("127.0.1.1:+4242", local, alive)); assert.isTrue(yield* firefoxSymlinkLockIsHeld("192.168.1.20:+4242", local, alive)); @@ -994,8 +586,7 @@ describe("isSourceRunning for Firefox", () => { const fileSystem = yield* FileSystem.FileSystem; const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-firefox-" }); const context = yield* sourcePathContext.pipe( - // Firefox's win32 root hangs off %APPDATA%; without it the root is - // undefined and the fixture would escape the sandbox into the repo. + // Without APPDATA, the Windows Firefox fixture would escape into the repo. Effect.provideService(HostProcess.Environment, { HOME: home, APPDATA: `${home}/AppData/Roaming`, @@ -1007,8 +598,6 @@ describe("isSourceRunning for Firefox", () => { yield* fileSystem.makeDirectory(profile, { recursive: true }); yield* fileSystem.writeFileString(`${profile}/cookies.sqlite`, "db"); - // On Windows, Firefox creates parent.lock as a regular file that - // persists after the process exits. yield* fileSystem.writeFileString(`${profile}/parent.lock`, ""); assert.isFalse(yield* isSourceRunning(firefox, context)); }), @@ -1016,18 +605,6 @@ describe("isSourceRunning for Firefox", () => { ); }); -describe("Windows user-data directories", () => { - it.effect("keeps app-bound Chromium forks unsupported on win32", () => - Effect.sync(() => { - for (const source of BROWSER_IMPORT_SOURCES) { - if (source.engine === "chromium" && source.id !== "helium") { - assert.notInclude(source.platforms, "win32"); - } - } - }), - ); -}); - describe("listSourceProfiles hardening", () => { it.effect("drops profile directories that are not a single plain segment", () => run( @@ -1139,16 +716,4 @@ describe("Safari profiles", () => { }), ), ); - - it.effect("keeps Safari without profiles available", () => - run( - Effect.gen(function* () { - const context = yield* withSourceHome(); - assert.deepEqual(yield* listSourceProfiles(safari, context), [ - { directory: ".", name: "Safari" }, - ]); - assert.isFalse(yield* isSourceInstalled(safari, context)); - }), - ), - ); }); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts index 59a89eadfa73e..0bf3df235f946 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.ts @@ -73,9 +73,7 @@ const chromiumSource = (input: { }); export const BROWSER_IMPORT_SOURCES: ReadonlyArray = [ - // No Chromium fork is importable on Windows: since Chrome 127 their cookies - // are encrypted to the browser's own identity (App-Bound Encryption), so no - // other process can read them. + // Chrome 127+ App-Bound Encryption prevents other processes from reading Windows Chromium cookies. chromiumSource({ id: "chrome", name: "Chrome", @@ -174,7 +172,7 @@ export const BROWSER_IMPORT_SOURCES: ReadonlyArray const CookieCountRow = Schema.Struct({ count: Schema.Number }); const decodeCookieCount = Schema.decodeUnknownEffect(Schema.Array(CookieCountRow)); -/** - * Firefox containers use identities Electron cannot represent, so its count - * uses the same default-container predicate as the reader. - */ +// Count only default-container cookies because Electron cannot represent Firefox containers. const countProfileCookies = Effect.fnUntraced(function* ( definition: BrowserImportSourceDefinition, context: BrowserImportPathContext, @@ -420,12 +409,7 @@ const listSourceProfilesInDirectory = Effect.fnUntraced(function* ( Effect.map((ini) => parseFirefoxProfiles(ini, context.path, root)), Effect.orElseSucceed(() => [] as ReadonlyArray), ); - // `profiles.ini` also lists profiles the installer created but the user - // never launched, which hold no cookie database and nothing to import. When - // none of the declared profiles has one, fall through to the scan rather - // than returning empty: `profiles.ini` can list stale or never-launched - // profiles while the cookies live in one it does not mention, and an empty - // answer here hides the browser entirely. + // Declared profiles may be stale or never launched; scan for unlisted stores if none has a cookie database. if (declared.length > 0) { const found = yield* Effect.forEach(declared, (profile) => Effect.forEach( @@ -460,11 +444,7 @@ const listSourceProfilesInDirectory = Effect.fnUntraced(function* ( const declared = yield* fileSystem.readFileString(context.path.join(root, "Local State")).pipe( Effect.flatMap(decodeLocalState), Effect.map((state) => Object.entries(state.profile?.info_cache ?? {})), - // The keys are directory names from the browser's own metadata file, which - // anything running as the user can write. Anything but a single plain - // segment is dropped: `..` or a path separator would otherwise be handed - // to `cookieDatabasePath` and read a database outside the user-data - // directory. + // Browser metadata is user-writable; reject traversal segments before resolving cookie database paths. Effect.map((entries) => entries.filter(([directory]) => isSafeProfileDirectory(directory))), Effect.map((entries) => entries.map(([directory, info]) => ({ directory, name: info.name?.trim() || directory })), @@ -490,11 +470,7 @@ const listSourceProfilesInDirectory = Effect.fnUntraced(function* ( ); }); -/** - * Include Firefox's Snap home alongside its native home. Snap profiles use - * absolute directories so cookie reads and lock checks keep pointing at the - * installation they came from, even when both installs use the same name. - */ +/** Keep Snap profile paths absolute so reads and locks distinguish native and Snap installations. */ export const listSourceProfiles = Effect.fn("BrowserImportSources.listSourceProfiles")(function* ( definition: BrowserImportSourceDefinition, context: BrowserImportPathContext, @@ -544,9 +520,7 @@ export const chromiumProcessIsAlive = ( signalProcess(pid, 0); return true; } catch (cause) { - // Only ESRCH positively proves the process is gone. Permission errors - // and unknown failures stay conservative so an active browser is never - // mistaken for a stale lock. + // Only ESRCH proves a stale lock; permission and unknown failures may still hide an active browser. return !( typeof cause === "object" && cause !== null && @@ -570,25 +544,18 @@ export const chromiumSingletonLockIsHeld = Effect.fnUntraced(function* ( if (!/^\d+$/.test(pidText)) return true; const pid = Number(pidText); if (!Number.isSafeInteger(pid) || pid <= 0) return true; - // A PID is meaningful only on this host. A foreign hostname can come from a - // shared home directory, and cannot safely be declared stale from here. + // Foreign-host PIDs may come from a shared home; never declare them stale here. if (host !== currentHost) return true; return yield* isProcessAlive(pid); }); /** Windows sharing and lock violations are translated by libuv to `Busy`. */ -export const isWindowsLockHeldError = (error: PlatformError.PlatformError): boolean => +const isWindowsLockHeldError = (error: PlatformError.PlatformError): boolean => error.reason._tag === "Busy"; -/** - * Whether a Windows `parent.lock` is actually held by a running process. It - * is opened with no sharing, so it persists on disk after the process exits - * and `stat` always succeeds; only trying to open it for write reveals an - * active holder, which surfaces as `Busy`. - */ +/** Windows leaves parent.lock after exit; only opening it for write reveals a live holder as Busy. */ const windowsLockIsHeld = Effect.fnUntraced(function* (lockPath: string) { - // Permission failures are distinct: they do not prove a browser owns the - // lock, so they must not hide the source as running. + // Permission failures do not prove a running browser owns the lock. const fileSystem = yield* FileSystem.FileSystem; return yield* fileSystem.open(lockPath, { flag: "r+" }).pipe( Effect.as(false), @@ -600,11 +567,7 @@ const windowsLockIsHeld = Effect.fnUntraced(function* (lockPath: string) { type WindowsLockProbe = (path: string) => Effect.Effect; -/** - * Chromium does not create its POSIX `SingletonLock` symlink on Windows. The - * live cookie database is opened without sharing instead, so probing each - * profile's current jar is the reliable running signal there. - */ +/** Windows Chromium locks cookie databases without sharing instead of creating POSIX SingletonLock symlinks. */ export const windowsChromiumCookiesAreHeld = Effect.fnUntraced(function* ( definition: BrowserImportSourceDefinition, context: BrowserImportPathContext, @@ -628,9 +591,7 @@ export const firefoxSymlinkLockIsHeld = Effect.fnUntraced(function* ( ) { const separator = target.lastIndexOf(":"); if (separator < 0) return true; - // The owner half is whatever Firefox's resolver returned for the machine's - // hostname — 127.0.0.1 when the lookup fails, but often 127.0.1.1 or a LAN - // address — so a pid is only meaningful when that address is one of ours. + // Firefox resolves the hostname to loopback or LAN addresses; only local owners' PIDs are meaningful. const owner = target.slice(0, separator); if (!localAddresses.has(owner)) return true; // A `+` marks an fcntl-holding owner; the pid follows either way. @@ -641,18 +602,10 @@ export const firefoxSymlinkLockIsHeld = Effect.fnUntraced(function* ( return yield* isProcessAlive(pid); }); -/** - * `/usr/bin/python3` is named absolutely first so a Dock-launched app with - * launchd's bare `PATH` still finds it without depending on the login-shell - * PATH merge; Linux distributions carry python3 on the default path. - */ +/** Dock launches have a bare PATH; try the absolute interpreter before relying on shell discovery. */ const FCNTL_PROBE_INTERPRETERS = ["/usr/bin/python3", "python3"] as const; -/** - * Anything else means the script never ran — most importantly Apple's - * `/usr/bin/python3` shim, which on a Mac without the Command Line Tools exits - * non-zero after printing an install prompt, without ever reaching our code. - */ +/** Apple's python3 shim can fail with an install prompt before the probe script runs. */ const FCNTL_PROBE_SCRIPT = "import fcntl,os,sys\n" + "fd=os.open(sys.argv[1],os.O_WRONLY)\n" + @@ -664,14 +617,11 @@ const FCNTL_PROBE_SCRIPT = " print('free')"; /** - * Anything else — no interpreter on any candidate path, or one that refused to - * run the script (Apple's shim without the developer tools) — is the probe - * being unavailable, not evidence about the lock. That case falls back to "not - * held" rather than "held": reporting every profile as locked forever would - * block Firefox import outright on such machines, and the SQLite snapshot - * already copes with a live database's WAL, as it does for every other engine. + * A missing or refusing interpreter (Apple's shim without developer tools) means + * the probe is unavailable, so report "not held": "held" would block Firefox import + * forever, and the SQLite snapshot already copes with a live WAL. */ -export const posixLockIsHeld = Effect.fnUntraced(function* ( +const posixLockIsHeld = Effect.fnUntraced(function* ( path: string, interpreters: ReadonlyArray = FCNTL_PROBE_INTERPRETERS, ) { @@ -699,12 +649,7 @@ export const posixLockIsHeld = Effect.fnUntraced(function* ( return false; }); -/** - * But `.parentlock` (macOS/Linux) and `parent.lock` (Windows) are regular files - * held with fcntl or a Windows handle and are *deliberately left on disk* after - * exit, as a last-used marker; treating them as proof of a running browser - * blocks every import after Firefox has been used once. - */ +/** Firefox leaves regular lock files after exit; test the lock, not file existence. */ const firefoxProfileIsHeld = Effect.fnUntraced(function* ( directory: string, context: BrowserImportPathContext, @@ -739,8 +684,7 @@ export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning") const fileSystem = yield* FileSystem.FileSystem; const root = definition.userDataDirectory(context); if (root === undefined) return false; - // Safari keeps no lock and writes its jar atomically, so a running instance - // is not a hazard there. + // Safari writes its jar atomically and needs no lock, even while running. if (definition.engine === "safari") return false; if (definition.engine !== "firefox") { if (context.platform === "win32") { @@ -766,18 +710,7 @@ export const isSourceRunning = Effect.fn("BrowserImportSources.isSourceRunning") return found.some(Boolean); }); -/** - * Keyed off the cookie database rather than the user-data directory, because - * that directory is not evidence the browser exists: installers for native - * messaging hosts create an empty one for every Chromium fork they know about, - * so a machine with only Chrome reports Edge, Brave, Vivaldi, Opera and Arc as - * present. - * - * Existence is checked without opening the file, which matters for Safari: TCC - * permits `stat` on the jar inside its container but refuses a read, so this - * still sees it and the user gets the Full Disk Access prompt rather than - * having Safari disappear. - */ +/** Require a cookie database; installers create empty directories. Safari stat needs no Full Disk Access. */ export const isSourceInstalled = Effect.fn("BrowserImportSources.isSourceInstalled")(function* ( definition: BrowserImportSourceDefinition, context: BrowserImportPathContext, diff --git a/apps/desktop/src/preview/BrowserSession.test.ts b/apps/desktop/src/preview/BrowserSession.test.ts index fc4c2dfc843a0..d9b797dd0451f 100644 --- a/apps/desktop/src/preview/BrowserSession.test.ts +++ b/apps/desktop/src/preview/BrowserSession.test.ts @@ -1,9 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as PlatformError from "effect/PlatformError"; import { beforeEach, vi } from "vite-plus/test"; const { fromPartition, sessions } = vi.hoisted(() => ({ @@ -87,8 +85,6 @@ describe("BrowserSession", () => { Effect.gen(function* () { const browserSessions = yield* BrowserSession.BrowserSession; - // TextEncoder folds a lone surrogate to U+FFFD, so without escaping these - // two supported ids would hash to one partition and share every cookie. const loneSurrogate = yield* browserSessions.getPartition("p\ud800"); const replacementChar = yield* browserSessions.getPartition("p\ufffd"); assert.notStrictEqual(loneSurrogate, replacementChar); @@ -118,13 +114,8 @@ describe("BrowserSession", () => { }).pipe(Effect.provide(layer)), ); - // A rewritten session UA — any variant, even ones that keep the Electron - // token — makes Cloudflare Turnstile loop with error 600010 (#5002), so the - // guest must end up with Electron's native User-Agent. it.effect("keeps the guest's effective User-Agent equal to Electron's native one", () => Effect.gen(function* () { - // Electron's real UA shape: app token, then Chrome, then Electron, then - // Safari — the token order and casing matter to any strip regex. const nativeUserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) T3Code(Alpha)/0.0.33 Chrome/146.0.7680.216 Electron/41.5.0 Safari/537.36"; fromPartition.mockReset(); @@ -180,7 +171,6 @@ describe("BrowserSession", () => { for (const permission of [ "clipboard-read", "clipboard-sanitized-write", - "notifications", "geolocation", "fullscreen", ]) { @@ -194,7 +184,7 @@ describe("BrowserSession", () => { // `clipboard-write` is not a real Electron permission — the async write API // uses `clipboard-sanitized-write` — so the stale name must not be granted, // and unrelated permissions stay denied. - for (const permission of ["clipboard-write", "midi"]) { + for (const permission of ["clipboard-write", "notifications", "midi"]) { assert.isFalse(requestAllows(permission), `request handler should deny ${permission}`); assert.isFalse( checkHandler(null, permission) as boolean, @@ -236,119 +226,6 @@ describe("BrowserSession", () => { }).pipe(Effect.provide(layer)), ); - it.effect("attaches the open-externally prompt to the window hosting the preview", () => - Effect.gen(function* () { - const browserSessions = yield* BrowserSession.BrowserSession; - const partition = yield* browserSessions.getPartition("scope-a"); - yield* browserSessions.getSession("scope-a"); - const requestHandler = - sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0]; - assert.isFunction(requestHandler); - - const hostWindow = { id: 7 } as unknown as Electron.BrowserWindow; - const host = { isDestroyed: () => false }; - const guest = { isDestroyed: () => false, hostWebContents: host }; - fromWebContents.mockImplementation((webContents) => - webContents === host ? hostWindow : null, - ); - showMessageBox.mockReset(); - showMessageBox.mockReturnValueOnce(1); - - yield* Effect.callback((resume) => { - requestHandler( - guest, - "openExternal", - (granted: boolean) => resume(Effect.succeed(granted)), - { - externalURL: "slack://open?team=T1", - }, - ); - }); - - assert.strictEqual(showMessageBox.mock.calls[0]?.[1], hostWindow); - }).pipe(Effect.provide(layer)), - ); - - it.effect("preserves partition scope and the platform failure chain", () => { - const nativeCause = new Error("native digest failed"); - const platformCause = PlatformError.systemError({ - _tag: "Unknown", - module: "Crypto", - method: "digest", - cause: nativeCause, - }); - const layerFailingCrypto = Layer.succeed( - Crypto.Crypto, - Crypto.make({ - randomBytes: (size) => new Uint8Array(size), - digest: () => Effect.fail(platformCause), - }), - ); - - return Effect.gen(function* () { - const browserSessions = yield* BrowserSession.BrowserSession; - const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip); - - assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError); - assert.equal(error.scope, "environment-a"); - assert.strictEqual(error.cause, platformCause); - assert.strictEqual(error.cause.reason.cause, nativeCause); - assert.equal( - error.message, - "Failed to derive a desktop preview browser partition for scope environment-a.", - ); - assert.notInclude(error.message, nativeCause.message); - }).pipe( - Effect.provide( - BrowserSession.layer.pipe(Layer.provide(Layer.merge(layerFailingCrypto, layerDialog))), - ), - ); - }); - - it.effect("preserves session scope, partition, and the Electron failure", () => - Effect.gen(function* () { - const cause = new Error("Electron session failed"); - fromPartition.mockImplementationOnce(() => { - throw cause; - }); - const browserSessions = yield* BrowserSession.BrowserSession; - const partition = yield* browserSessions.getPartition("environment-b"); - const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip); - - assert.instanceOf(error, BrowserSession.BrowserSessionCreationError); - assert.equal(error.scope, "environment-b"); - assert.equal(error.partition, partition); - assert.strictEqual(error.cause, cause); - assert.equal( - error.message, - `Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`, - ); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(layer)), - ); - - it.effect("clears storage and cache for every created session", () => - Effect.gen(function* () { - const browserSessions = yield* BrowserSession.BrowserSession; - yield* browserSessions.getSession("scope-a"); - yield* browserSessions.getSession("scope-b"); - - yield* browserSessions.clearCookies(); - yield* browserSessions.clearCache(); - - assert.strictEqual(sessions.size, 2); - for (const browserSession of sessions.values()) { - assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1); - assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [ - { - storages: ["cookies", "localstorage", "indexdb", "serviceworkers"], - }, - ]); - assert.strictEqual(browserSession.clearCache.mock.calls.length, 1); - } - }).pipe(Effect.provide(layer)), - ); - it.effect("clears a partition whose session has not been opened yet", () => Effect.gen(function* () { const browserSessions = yield* BrowserSession.BrowserSession; @@ -366,50 +243,4 @@ describe("BrowserSession", () => { assert.strictEqual(created.clearStorageData.mock.calls.length, 1); }).pipe(Effect.provide(layer)), ); - - it.effect("correlates clear failures while still attempting every session", () => - Effect.gen(function* () { - const browserSessions = yield* BrowserSession.BrowserSession; - yield* browserSessions.getSession("scope-a"); - yield* browserSessions.getSession("scope-b"); - const firstPartition = yield* browserSessions.getPartition("scope-a"); - const secondPartition = yield* browserSessions.getPartition("scope-b"); - const firstSession = sessions.get(firstPartition); - const secondSession = sessions.get(secondPartition); - assert.isDefined(firstSession); - assert.isDefined(secondSession); - - const storageCause = new Error("storage clear failed"); - secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause)); - const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip); - - assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError); - assert.equal(storageError.partition, secondPartition); - assert.strictEqual(storageError.cause, storageCause); - assert.equal( - storageError.message, - `Failed to clear desktop preview browser storage for partition ${secondPartition}.`, - ); - assert.notInclude(storageError.message, storageCause.message); - for (const browserSession of sessions.values()) { - assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1); - } - - const cacheCause = new Error("cache clear failed"); - firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause)); - const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip); - - assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError); - assert.equal(cacheError.partition, firstPartition); - assert.strictEqual(cacheError.cause, cacheCause); - assert.equal( - cacheError.message, - `Failed to clear the desktop preview browser cache for partition ${firstPartition}.`, - ); - assert.notInclude(cacheError.message, cacheCause.message); - for (const browserSession of sessions.values()) { - assert.strictEqual(browserSession.clearCache.mock.calls.length, 1); - } - }).pipe(Effect.provide(layer)), - ); }); diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.ts index 9f0b5edb10979..0f900d521b739 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -12,36 +12,21 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-"; -/** - * Incognito partitions deliberately omit the `persist:` prefix, which is what - * makes Chromium keep them in memory and discard them with the process. They - * still carry the product prefix so `isPartition` can admit them — the - * `will-attach-webview` gate rejects anything it does not recognise. - */ +/** Ephemeral partitions omit persist: but retain a product prefix so the webview gate recognizes them. */ const PREVIEW_EPHEMERAL_PARTITION_PREFIX = "t3code-preview-ephemeral-"; const PROFILE_PARTITION_MARKER = "profile-"; export type BrowserSessionPartitionNamespace = "profile"; -// `clipboard-sanitized-write` is the Electron permission behind -// `navigator.clipboard.writeText()` — note it is NOT `clipboard-write`, which -// is not a valid Electron permission name. Async clipboard writes are gated by -// the permission *check* handler (not only the request handler), so both -// handlers must allow it; otherwise built-in "Copy" buttons — e.g. the Next.js -// / Vercel error overlay — fail with `Failed to execute 'writeText' on -// 'Clipboard': Write permission denied`. +// Electron's clipboard API uses clipboard-sanitized-write and checks both permission handlers. const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet = new Set([ "clipboard-read", "clipboard-sanitized-write", - "notifications", "geolocation", - // `DesktopWindow` disables HTML fullscreen window resizing for the app window - // and every preview guest, so a page that goes fullscreen fills its own - // webview instead of taking over the whole T3 window. + // DesktopWindow confines HTML fullscreen to the guest's webview. "fullscreen", - // Deliberately NOT local-fonts: preview sessions run untrusted web content, - // and silently granting it would hand every page the user's installed-font - // fingerprint (and font file bytes via FontData.blob()). + // Deny local-fonts to untrusted previews: it exposes installed-font fingerprints and file bytes. + // Deny notifications: pages could impersonate T3 Code; app notifications use the default session. ]); const NEVER_EXTERNAL_PROTOCOLS: ReadonlySet = new Set([ @@ -165,12 +150,7 @@ const selectSessions = ( ([partition]) => partitions === undefined || partitions.includes(partition), ); -/** - * `TextEncoder` replaces a lone UTF-16 surrogate with U+FFFD, so `"p\ud800"` - * and `"p\ufffd"` would hash to the same partition and share cookies. Those - * are distinct, supported ids, so lone surrogates are escaped to `\uXXXX` - * first — and a literal backslash is doubled so the escape cannot be forged. - */ +/** Escape lone surrogates before UTF-8 hashing, which otherwise merges them with U+FFFD; escape backslashes too. */ const encodeScopeForDigest = (scope: string): Uint8Array => new TextEncoder().encode( scope @@ -181,10 +161,7 @@ const encodeScopeForDigest = (scope: string): Uint8Array => ), ); -/** - * A `` guest has no window of its own, so look it up through the page - * that embeds it. - */ +// Webview guests have no window; use their embedding page. const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined => { if (guest === null || guest.isDestroyed()) return undefined; const host = guest.hostWebContents ?? guest; @@ -192,18 +169,14 @@ const previewHostWindow = (guest: WebContents | null): BrowserWindow | undefined return BrowserWindow.fromWebContents(host) ?? undefined; }; -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* BrowserSessionMake() { const crypto = yield* Crypto.Crypto; const electronDialog = yield* ElectronDialog.ElectronDialog; const runFork = Effect.runForkWith(yield* Effect.context()); // One prompt at a time, so a page cannot stack dialogs by looping a deep link. let externalPromptOpen = false; - /** - * Electron grants an external-protocol navigation through the `openExternal` - * permission and then launches the OS handler itself. Ask first: previews run - * untrusted pages, and a silent grant would let any of them launch apps. - */ + /** Electron launches external protocols after granting openExternal; untrusted pages require confirmation. */ const confirmOpenExternal = ( requester: WebContents | null, rawUrl: string | undefined, @@ -275,11 +248,7 @@ export const make = Effect.gen(function* BrowserSessionMake() { return Effect.try({ try: () => { const browserSession = session.fromPartition(partition); - // The guest keeps Electron's native User-Agent. Rewriting it in any - // form — even variants that keep the Electron token — makes Cloudflare - // Turnstile fail its integrity check with error 600010 and recreate - // the challenge every few seconds, so logins behind it never complete - // (#5002). + // Rewriting Electron's native User-Agent makes Turnstile fail integrity checks with error 600010. browserSession.setPermissionRequestHandler( (webContents, permission, callback, details) => { if (permission === "openExternal") { diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts index 5932db57a8637..ec314d1f9d478 100644 --- a/apps/desktop/src/preview/CdpRelay.test.ts +++ b/apps/desktop/src/preview/CdpRelay.test.ts @@ -15,6 +15,7 @@ const makeTarget = ( }); // Each relay reply resolves after a few microtasks; one macrotask lets them all land. +// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time const settle = () => new Promise((resolve) => setImmediate(resolve)); describe("CDP relay", () => { @@ -103,7 +104,6 @@ describe("CDP relay", () => { expect(written).toEqual([]); relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); await settle(); - // Electron passes an empty session id for the page's own events. relay.event("Page.loadEventFired", { timestamp: 1 }, ""); relay.event("Runtime.consoleAPICalled", {}, "iframe-session"); expect(written.slice(-2)).toEqual([ diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts index 581b692882b30..82264cc4b870b 100644 --- a/apps/desktop/src/preview/CdpRelay.ts +++ b/apps/desktop/src/preview/CdpRelay.ts @@ -1,7 +1,4 @@ -/** - * Electron allows one debugger client per webContents, so the relay shares the - * attach the preview manager already holds. - */ +// Electron allows one debugger per webContents; share the manager's attachment. export interface CdpRelayTarget { readonly send: ( @@ -14,10 +11,7 @@ export interface CdpRelayTarget { readonly url: () => string; readonly title: () => string; readonly userAgent: () => string; - /** - * The desktop app and the server it launched share a disk, so the server's - * Playwright reads the file where it asked for it. - */ + /** The desktop and its server share a disk; download paths need no translation. */ readonly setDownloadDirectory: (directory: string | null) => void; } @@ -56,11 +50,7 @@ export function createCdpRelayConnection( ): CdpRelayConnection { const send = (message: Record) => write(JSON.stringify(message)); let attached = false; - /** - * Sessions this relay invented. Extra page sessions (Playwright's - * `newCDPSession`) all reach the one real debugger session, so each gets the - * page's events; other ids are the page's own child sessions, such as iframes. - */ + /** Relay-created page sessions share one real debugger; child frame sessions retain their own ids. */ const sessions = new Map([[PAGE_SESSION_ID, "page"]]); let sessionSequence = 0; const newSession = (kind: "browser" | "page") => { @@ -143,10 +133,7 @@ export function createCdpRelayConnection( const pageCommand = (command: CdpCommand): Promise => { const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId; - // The page itself is already running, but its child frames are not: - // Playwright auto-attaches with waitForDebuggerOnStart, so Chromium pauses - // every new cross-site iframe and worker until this reaches it. Swallowing - // it left sign-in checks and captchas, which run in such frames, frozen. + // Child frames/workers pause on auto-attach until resumed; only the main page can skip this command. if (command.method === "Runtime.runIfWaitingForDebugger" && child === undefined) { return Promise.resolve({}); } @@ -167,8 +154,7 @@ export function createCdpRelayConnection( ? browserCommand(command) : pageCommand(command); const route = command.sessionId === undefined ? {} : { sessionId: command.sessionId }; - // Replies leave as commands finish, as Chromium's do, so a slow command - // such as a screenshot never holds up the ones behind it. + // Reply as commands finish so slow commands cannot block later replies. void result.then( (value) => { const announce = diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 0d281c46f8605..50039c4e4b04e 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "@effect/vitest"; import { DesktopBrowserEvent } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as NodeEvents from "node:events"; @@ -15,32 +16,54 @@ const decodeCdpReply = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Struct({ id: Schema.Number })), ); const key = { threadId: "thread-1", tabId: "tab-1" }; +/** Sends a page command whose id the fake debugger records as it receives it. */ +const command = ( + host: DesktopBrowserHost.DesktopBrowserHost["Service"], + id: number, + method: string, +) => + host.handleCommandLine( + encodeJson({ + type: "cdp", + ...key, + message: encodeJson({ id, method, params: { id }, sessionId: "t3-preview-page" }), + }), + ); const makeDebuggee = () => { const emitter = new NodeEvents.EventEmitter(); const pending: Array<() => void> = []; + const sent: Array = []; + const sendWaiters: Array<() => void> = []; const debuggee = Object.assign(emitter, { - sendCommand: (method: string) => + sendCommand: (method: string, params?: { id?: number }) => new Promise((resolve) => { if (method === "Target.getTargetInfo") { resolve({ targetInfo: { targetId: "GUEST" } }); return; } + sent.push(params?.id); pending.push(() => resolve({ method })); + sendWaiters.shift()?.(); }), }); - const webContents = { + const webContents = Object.assign(new NodeEvents.EventEmitter(), { getURL: () => "http://localhost/", getTitle: () => "Page", getUserAgent: () => "Electron", - }; + }); return { tab: { webContents: webContents as unknown as Electron.WebContents, debugger: debuggee as unknown as Electron.Debugger, }, emit: (method: string, params: unknown) => emitter.emit("message", {}, method, params, ""), + navigate: () => webContents.emit("did-navigate"), + /** Ids of the commands the debugger received, in order. */ + sent, + nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), + releaseFirst: () => pending.shift()?.(), }; }; @@ -51,6 +74,25 @@ const takeEvents = (host: DesktopBrowserHost.DesktopBrowserHost["Service"], coun Effect.map((lines) => lines.map((line) => decodeEvent(new TextDecoder().decode(line)))), ); +/** + * 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. + */ +const watchReplies = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) => + 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, + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + return replies; + }); + describe("DesktopBrowserHost", () => { it.effect("announces tabs already attached to a backend that starts later", () => Effect.gen(function* () { @@ -82,7 +124,6 @@ describe("DesktopBrowserHost", () => { yield* host.handleCommandLine(encodeJson({ type: "release", ...key })); yield* command(2, "DOM.enable"); debuggee.release(); - yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve))); const [, reply] = yield* Fiber.join(reader); expect(reply).toMatchObject({ type: "cdp" }); @@ -90,6 +131,67 @@ describe("DesktopBrowserHost", () => { }).pipe(Effect.scoped), ); + it.effect("sends a page one screenshot at a time", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* command(host, 2, "Page.captureScreenshot"); + yield* command(host, 3, "DOM.enable"); + expect(debuggee.sent).toEqual([1, 3]); + + 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", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* command(host, 2, "Page.captureScreenshot"); + yield* command(host, 3, "Page.captureScreenshot"); + debuggee.navigate(); + expect(debuggee.sent).toEqual([1, 2]); + + // The superseded screenshot answering late must not start a third beside the second. + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(1); + expect(debuggee.sent).toEqual([1, 2]); + + 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", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* command(host, 2, "Page.captureScreenshot"); + yield* host.handleCommandLine(encodeJson({ type: "release", ...key })); + yield* command(host, 3, "Page.captureScreenshot"); + expect(debuggee.sent).toEqual([1]); + + const sent = debuggee.nextSend(); + debuggee.release(); + yield* Effect.promise(() => sent); + expect(debuggee.sent).toEqual([1, 3]); + }), + ); + it.effect("saves a server tab's download under its CDP guid where the server asked", () => Effect.gen(function* () { const host = yield* DesktopBrowserHost.make; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index cef42d4f35fc3..849ae658a8219 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -1,8 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off - Names download files on the shared disk. -/** - * The preview manager owns the tab's single debugger session and hands it here; - * the relay shares it. - */ +/** The manager owns the single debugger attachment; the relay shares it. */ import { DesktopBrowserCommand, DesktopBrowserEvent, @@ -43,6 +40,8 @@ interface AttachedTab { readonly key: DesktopBrowserTabKey; readonly debuggee: DesktopBrowserTabDebugger; relay: CdpRelayConnection | null; + screenshotTurn: object | null; + readonly waitingScreenshots: Array<() => void>; downloadDirectory: string | null; pendingDownloadGuid: string | null; agentInputAt: number; @@ -52,6 +51,7 @@ interface AttachedTab { params: unknown, sessionId: string, ) => void; + readonly onNewDocument: () => void; } export class DesktopBrowserHost extends Context.Service< @@ -84,15 +84,54 @@ export const make = Effect.gen(function* () { const tabs = new Map(); const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event)); + const nextScreenshot = (tab: AttachedTab) => { + tab.screenshotTurn = null; + tab.waitingScreenshots.shift()?.(); + }; + + /** + * Chromium below 157 crashes the whole app when a guest's renderer exits with a + * screenshot copy in flight (crbug.com/567321049). Overlapping screenshots make that + * far likelier, and one the server gave up on stays pending in Chromium, so each guest + * gets one at a time. One queued by a relay released since then is dropped unsent. + */ + const takeScreenshot = ( + tab: AttachedTab, + relay: CdpRelayConnection, + capture: () => Promise, + ) => + new Promise((resolve, reject) => { + const start = () => { + if (tab.relay !== relay) { + reject(new Error("The preview connection that asked for this screenshot closed.")); + nextScreenshot(tab); + return; + } + const turn = {}; + tab.screenshotTurn = turn; + capture() + .finally(() => { + if (tab.screenshotTurn === turn) nextScreenshot(tab); + }) + .then(resolve, reject); + }; + if (tab.screenshotTurn === null) start(); + else tab.waitingScreenshots.push(start); + }); + const relayFor = (tab: AttachedTab) => { if (tab.relay) return tab.relay; const { webContents, debugger: debuggee } = tab.debuggee; + const send = (method: string, params: Record, sessionId?: string) => + sessionId === undefined + ? sendPageCommand(webContents, debuggee, method, params) + : debuggee.sendCommand(method, params, sessionId); const relay: CdpRelayConnection = createCdpRelayConnection( { send: (method, params, sessionId) => - sessionId === undefined - ? sendPageCommand(webContents, debuggee, method, params) - : debuggee.sendCommand(method, params, sessionId), + method === "Page.captureScreenshot" + ? takeScreenshot(tab, relay, () => send(method, params, sessionId)) + : send(method, params, sessionId), targetId: () => debuggee .sendCommand("Target.getTargetInfo") @@ -114,10 +153,7 @@ export const make = Effect.gen(function* () { return relay; }; - /** - * Without a path Electron would open its Save dialog over the app for a file - * the agent asked for. CDP names the download just before this runs. - */ + // CDP supplies the path before this runs; otherwise Electron opens a Save dialog. const placeDownload = (source: Electron.WebContents, item: Electron.DownloadItem) => { const tab = [...tabs.values()].find( (candidate) => candidate.debuggee.webContents === source && candidate.downloadDirectory, @@ -133,7 +169,9 @@ export const make = Effect.gen(function* () { const tab = tabs.get(id); if (!tab) return; tabs.delete(id); + tab.relay = null; tab.debuggee.debugger.off("message", tab.onMessage); + tab.debuggee.webContents.off("did-navigate", tab.onNewDocument); emit({ type: "detached", ...key }); }; @@ -145,6 +183,8 @@ export const make = Effect.gen(function* () { key, debuggee, relay: null, + screenshotTurn: null, + waitingScreenshots: [], downloadDirectory: null, pendingDownloadGuid: null, agentInputAt: Number.NEGATIVE_INFINITY, @@ -155,9 +195,15 @@ export const make = Effect.gen(function* () { } tab.relay?.event(method, params, sessionId); }, + // A screenshot pending when the page loads a new document, a reload included, can + // stay unanswered. A crashed page lands here once it reloads, well after its renderer died. + onNewDocument: () => { + if (tab.screenshotTurn !== null) nextScreenshot(tab); + }, }; tabs.set(id, tab); debuggee.debugger.on("message", tab.onMessage); + debuggee.webContents.on("did-navigate", tab.onNewDocument); emit({ type: "attached", ...key }); }; diff --git a/apps/desktop/src/preview/FaviconCapture.test.ts b/apps/desktop/src/preview/FaviconCapture.test.ts index 8446116bcd4cb..2163dc002b703 100644 --- a/apps/desktop/src/preview/FaviconCapture.test.ts +++ b/apps/desktop/src/preview/FaviconCapture.test.ts @@ -140,102 +140,6 @@ function sourceJpegWithApp1Segments( return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]); } -function sourceJpegWithOrientationEntries( - width: number, - height: number, - orientations: ReadonlyArray, -): Buffer { - return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]); -} - -function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer { - const exif = sourceJpegExifSegment([6], { byteOrder }); - exif[10] = alias; - exif[11] = alias; - return sourceJpegWithApp1Segments(64, 32, [exif]); -} - -function sourceJpegExifWithSubIfd(options: { - readonly rootOrientation?: number; - readonly subIfdFirst?: boolean; - readonly subIfdOrientation: number; -}): Buffer { - const rootEntries = options.rootOrientation === undefined ? 1 : 2; - const rootIfdOffset = 14; - const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4; - const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4); - exif.write("Exif\0\0", 0, "binary"); - exif.write("II", 6, "ascii"); - exif.writeUInt16LE(42, 8); - exif.writeUInt32LE(8, 10); - exif.writeUInt16LE(rootEntries, rootIfdOffset); - - const writeOrientation = (offset: number, orientation: number) => { - exif.writeUInt16LE(0x0112, offset); - exif.writeUInt16LE(3, offset + 2); - exif.writeUInt32LE(1, offset + 4); - exif.writeUInt16LE(orientation, offset + 8); - }; - const writeSubIfdPointer = (offset: number) => { - exif.writeUInt16LE(0x8769, offset); - exif.writeUInt16LE(4, offset + 2); - exif.writeUInt32LE(1, offset + 4); - exif.writeUInt32LE(subIfdOffset - 6, offset + 8); - }; - - const firstRootEntryOffset = rootIfdOffset + 2; - if (options.rootOrientation === undefined) { - writeSubIfdPointer(firstRootEntryOffset); - } else if (options.subIfdFirst) { - writeSubIfdPointer(firstRootEntryOffset); - writeOrientation(firstRootEntryOffset + 12, options.rootOrientation); - } else { - writeOrientation(firstRootEntryOffset, options.rootOrientation); - writeSubIfdPointer(firstRootEntryOffset + 12); - } - - exif.writeUInt16LE(1, subIfdOffset); - writeOrientation(subIfdOffset + 2, options.subIfdOrientation); - return sourceJpegApp1Segment(exif); -} - -function sourceJpegExifWithSubIfdPointers(options: { - readonly pointerCount: number; - readonly subIfdEntries: number; -}): Buffer { - const { pointerCount, subIfdEntries } = options; - const rootIfdOffset = 14; - const rootEntries = pointerCount + 1; - const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4; - const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4); - exif.write("Exif\0\0", 0, "binary"); - exif.write("II", 6, "ascii"); - exif.writeUInt16LE(42, 8); - exif.writeUInt32LE(8, 10); - exif.writeUInt16LE(rootEntries, rootIfdOffset); - for (let index = 0; index < pointerCount; index += 1) { - const entryOffset = rootIfdOffset + 2 + index * 12; - exif.writeUInt16LE(0x8769, entryOffset); - exif.writeUInt16LE(4, entryOffset + 2); - exif.writeUInt32LE(1, entryOffset + 4); - exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8); - } - const orientationOffset = rootIfdOffset + 2 + pointerCount * 12; - exif.writeUInt16LE(0x0112, orientationOffset); - exif.writeUInt16LE(3, orientationOffset + 2); - exif.writeUInt32LE(1, orientationOffset + 4); - exif.writeUInt16LE(6, orientationOffset + 8); - - exif.writeUInt16LE(subIfdEntries, subIfdOffset); - for (let index = 0; index < subIfdEntries; index += 1) { - const entryOffset = subIfdOffset + 2 + index * 12; - exif.writeUInt16LE(1, entryOffset); - exif.writeUInt16LE(3, entryOffset + 2); - exif.writeUInt32LE(1, entryOffset + 4); - } - return sourceJpegApp1Segment(exif); -} - function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer { const rootIfdOffset = 14; const rootEntries = pointerCount + 1; @@ -288,13 +192,6 @@ function makeUnsafePng(): Buffer { return buffer; } -function sourcePng(width: number, height: number): Buffer { - const buffer = Buffer.from(SOURCE_PNG); - buffer.writeUInt32BE(width, 16); - buffer.writeUInt32BE(height, 20); - return buffer; -} - function makeUnsafeDib(): Buffer { const buffer = Buffer.alloc(40); buffer.writeUInt32LE(40, 0); @@ -328,40 +225,6 @@ function makeWebContents(options?: { }; } -const JPEG_LANDSCAPE_LAYOUT = { - draw: "context.drawImage(bitmap, 0, 8, 32, 16)", - resizeHeight: 16, - resizeWidth: 32, -} as const; -const JPEG_PORTRAIT_LAYOUT = { - draw: "context.drawImage(bitmap, 8, 0, 16, 32)", - resizeHeight: 32, - resizeWidth: 16, -} as const; - -async function expectJpegLayout( - source: Buffer, - layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT, -): Promise { - const { webContents } = makeWebContents({ - rasterize: async (code) => { - expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`); - expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`); - expect(code).toContain(layout.draw); - return PNG; - }, - }); - - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [`data:image/jpeg;base64,${source.toString("base64")}`], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "captured", dataUrl: PNG }); -} - describe("selectFaviconCandidates", () => { it("filters and deduplicates before applying the candidate cap", () => { const valid = Array.from( @@ -461,35 +324,6 @@ describe("captureFavicon", () => { expect(fetch).toHaveBeenCalledTimes(2); }); - it("cancels a rejected response body before trying the next candidate", async () => { - const cancel = vi.fn(); - const body = new ReadableStream({ - start(controller) { - controller.enqueue(new Uint8Array(1)); - }, - cancel, - }); - const { webContents, fetch } = makeWebContents({ - fetch: async (url) => - url.endsWith("first.png") - ? new Response(body, { status: 404 }) - : new Response(new Uint8Array(SOURCE_PNG), { - headers: { "content-type": "image/png" }, - }), - }); - - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: ["https://example.com/first.png", "https://example.com/second.png"], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "captured", dataUrl: PNG }); - expect(cancel).toHaveBeenCalledOnce(); - expect(fetch).toHaveBeenCalledTimes(2); - }); - it("stops a pending fetch when its capture is aborted", async () => { const controller = new AbortController(); const { webContents } = makeWebContents({ @@ -510,102 +344,6 @@ describe("captureFavicon", () => { expect(await capture).toEqual({ kind: "none" }); }); - it("ends candidate fallback when the overall capture deadline expires", async () => { - const timeoutController = new AbortController(); - const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal); - const { webContents, fetch } = makeWebContents({ - fetch: (url, init) => { - if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 })); - return new Promise((_resolve, reject) => { - init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { - once: true, - }); - }); - }, - }); - try { - const capture = captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [ - "https://example.com/first.png", - "https://example.com/second.png", - "https://example.com/third.png", - ], - signal: new AbortController().signal, - }); - await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2)); - timeoutController.abort(new DOMException("capture timed out", "TimeoutError")); - - expect(await capture).toEqual({ kind: "timed-out" }); - expect(fetch).toHaveBeenCalledTimes(2); - expect(timeout).toHaveBeenCalledOnce(); - } finally { - timeout.mockRestore(); - } - }); - - it("does not publish a rasterization that completes after the capture deadline", async () => { - const captureTimeoutController = new AbortController(); - const rasterTimeoutController = new AbortController(); - const timeout = vi - .spyOn(AbortSignal, "timeout") - .mockImplementation((milliseconds) => - milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal, - ); - let resolveRasterization!: (value: unknown) => void; - const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({ - rasterize: () => - new Promise((resolve) => { - resolveRasterization = resolve; - }), - }); - try { - const capture = captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [SOURCE_PNG_URL], - signal: new AbortController().signal, - }); - await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce()); - captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError")); - - expect(await capture).toEqual({ kind: "timed-out" }); - resolveRasterization(PNG); - } finally { - timeout.mockRestore(); - } - }); - - it("cancels a stalled response body when the capture deadline expires", async () => { - const timeoutController = new AbortController(); - const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal); - const cancel = vi.fn(); - const { webContents } = makeWebContents({ - fetch: async () => - new Response( - new ReadableStream({ - cancel, - }), - { headers: { "content-type": "image/png" } }, - ), - }); - try { - const capture = captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: ["https://example.com/favicon.png"], - signal: new AbortController().signal, - }); - timeoutController.abort(new DOMException("capture timed out", "TimeoutError")); - - expect(await capture).toEqual({ kind: "timed-out" }); - expect(cancel).toHaveBeenCalledOnce(); - } finally { - timeout.mockRestore(); - } - }); - it("rejects and cancels an oversized streamed response", async () => { const cancel = vi.fn(); const body = new ReadableStream({ @@ -631,178 +369,6 @@ describe("captureFavicon", () => { expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled(); }); - it("retains bounded compatibility with common favicon formats", async () => { - const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents(); - for (const [mime, buffer] of [ - ["image/gif", sourceGif(32, 32)], - ["image/jpeg", sourceJpeg(32, 32)], - ["image/webp", sourceWebp(32, 32)], - ["image/x-icon", sourceIco(SOURCE_PNG)], - ] as const) { - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [`data:${mime};base64,${buffer.toString("base64")}`], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "captured", dataUrl: PNG }); - } - expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4); - }); - - it.each([ - { - label: "landscape", - source: sourcePng(64, 32), - resizeWidth: 32, - resizeHeight: 16, - draw: "context.drawImage(bitmap, 0, 8, 32, 16)", - }, - { - label: "portrait", - source: sourcePng(32, 64), - resizeWidth: 16, - resizeHeight: 32, - draw: "context.drawImage(bitmap, 8, 0, 16, 32)", - }, - ])("preserves $label aspect ratio within the 32x32 output", async (testCase) => { - const { webContents } = makeWebContents({ - rasterize: async (code) => { - expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`); - expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`); - expect(code).toContain('resizeQuality: "high"'); - expect(code).toContain(testCase.draw); - return PNG; - }, - }); - - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "captured", dataUrl: PNG }); - }); - - it.each([ - ...[1, 2, 3, 4].map((orientation) => ({ - label: `keeps stored dimensions for orientation ${orientation}`, - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpeg(64, 32, orientation), - })), - ...[5, 6, 7, 8].map((orientation) => ({ - label: `uses display dimensions for orientation ${orientation}`, - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpeg(64, 32, orientation), - })), - { - label: "uses the first separate EXIF segment when it is transposed", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpeg(64, 32, [6, 1]), - }, - { - label: "uses the first separate EXIF segment when it is untransposed", - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpeg(64, 32, [1, 6]), - }, - { - label: "does not consult a later EXIF segment after an invalid orientation", - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpeg(64, 32, [9, 6]), - }, - { - label: "uses a later valid orientation in the same IFD", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithOrientationEntries(64, 32, [9, 6]), - }, - { - label: "skips a non-EXIF APP1 segment", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegApp1Segment(Buffer.from("not-exif")), - sourceJpegExifSegment([6]), - ]), - }, - { - label: "skips an empty EXIF APP1 segment", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")), - sourceJpegExifSegment([6]), - ]), - }, - { - label: "stops after a malformed qualifying EXIF APP1 segment", - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")), - sourceJpegExifSegment([6]), - ]), - }, - { - label: "ignores the EXIF padding byte", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]), - }, - { - label: "reads big-endian EXIF", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]), - }, - { - label: "matches Chromium for a nonstandard TIFF magic field", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]), - }, - { - label: "rejects a high-bit little-endian alias", - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpegWithEndianAlias(0xc9, "II"), - }, - { - label: "rejects a high-bit big-endian alias", - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpegWithEndianAlias(0xcd, "MM"), - }, - { - label: "reads an orientation from a SubIFD", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }), - ]), - }, - { - label: "uses a SubIFD orientation before a later root orientation", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegExifWithSubIfd({ - rootOrientation: 1, - subIfdFirst: true, - subIfdOrientation: 6, - }), - ]), - }, - { - label: "uses a root orientation before a later SubIFD orientation", - layout: JPEG_LANDSCAPE_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }), - ]), - }, - { - label: "memoizes repeated aliases to the same SubIFD", - layout: JPEG_PORTRAIT_LAYOUT, - source: sourceJpegWithApp1Segments(64, 32, [ - sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }), - ]), - }, - ])("matches Chromium JPEG layout: $label", async ({ source, layout }) => { - await expectJpegLayout(source, layout); - }); - it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => { const source = sourceJpegWithApp1Segments(64, 32, [ sourceJpegExifWithOverlappingSubIfds(32, 32), @@ -820,41 +386,6 @@ describe("captureFavicon", () => { expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled(); }); - it("rejects JPEGs with multiple frame headers before rasterization", async () => { - const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]); - const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents(); - - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "none" }); - expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled(); - }); - - it("rejects an unsafe PNG size before rasterization", async () => { - const buffer = makeUnsafePng(); - const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({ - fetch: async () => - new Response(new Uint8Array(buffer), { - headers: { "content-type": "image/png" }, - }), - }); - - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: ["https://example.com/favicon.png"], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "none" }); - expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled(); - }); - it.each([ ["GIF", "image/gif", sourceGif(4096, 4096)], ["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)], @@ -908,85 +439,6 @@ describe("captureFavicon", () => { expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled(); }); - it("ignores output that is not a bounded PNG data URL", async () => { - const { webContents } = makeWebContents({ - rasterize: async () => "data:image/svg+xml;base64,c3Zn", - }); - - expect( - await captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: [SOURCE_PNG_URL], - signal: new AbortController().signal, - }), - ).toEqual({ kind: "none" }); - }); - - it("waits for physical rasterization settlement after a logical timeout", async () => { - vi.useFakeTimers(); - try { - let resolveOld!: (value: unknown) => void; - let executions = 0; - const { webContents } = makeWebContents({ - rasterize: () => { - executions += 1; - return executions === 1 - ? new Promise((resolve) => { - resolveOld = resolve; - }) - : Promise.resolve(PNG); - }, - }); - const input = { - webContents, - pageUrl: "https://example.com/page", - candidates: [SOURCE_PNG_URL], - signal: new AbortController().signal, - }; - const timedOut = captureFavicon(input); - await vi.advanceTimersByTimeAsync(1_001); - expect(await timedOut).toEqual({ kind: "timed-out" }); - - const newer = captureFavicon(input); - await Promise.resolve(); - expect(executions).toBe(1); - resolveOld(PNG); - expect(await newer).toEqual({ kind: "captured", dataUrl: PNG }); - expect(executions).toBe(2); - } finally { - vi.useRealTimers(); - } - }); - - it("ends candidate fallback after a rasterization timeout", async () => { - vi.useFakeTimers(); - try { - let resolveRasterization!: (value: unknown) => void; - const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({ - rasterize: () => - new Promise((resolve) => { - resolveRasterization = resolve; - }), - }); - const capture = captureFavicon({ - webContents, - pageUrl: "https://example.com/page", - candidates: ["https://example.com/first.png", "https://example.com/second.png"], - signal: new AbortController().signal, - }); - - await vi.advanceTimersByTimeAsync(1_001); - - expect(await capture).toEqual({ kind: "timed-out" }); - expect(fetch).toHaveBeenCalledOnce(); - expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce(); - resolveRasterization(PNG); - } finally { - vi.useRealTimers(); - } - }); - it("coalesces queued rasterizations so only the latest pending capture launches", async () => { let resolveFirst!: (value: unknown) => void; let executions = 0; diff --git a/apps/desktop/src/preview/FaviconCapture.ts b/apps/desktop/src/preview/FaviconCapture.ts index a2b36d182a8f3..4716645c9defa 100644 --- a/apps/desktop/src/preview/FaviconCapture.ts +++ b/apps/desktop/src/preview/FaviconCapture.ts @@ -669,8 +669,7 @@ async function rasterizeFavicon( ); if (signal.aborted) onAbort(); }); - // The logical timeout does not cancel Electron's renderer work. Keep the - // gate closed until that physical execution actually settles. + // Logical timeouts leave renderer work running; keep the gate closed until it settles. const launchAllowed = execution.then( () => undefined, () => undefined, diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index d607b217262f7..b531182c92959 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -2,7 +2,6 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { sendPageCommand, toKeyboardInputEvents } from "./GuestInput.ts"; -/** A guest whose page reports `focusedDocument` for the focus probe. */ const makeGuest = ({ focused, focusedDocument = true, @@ -19,6 +18,8 @@ const makeGuest = ({ focusedFrame: focused ? {} : null, insertText: vi.fn(async () => {}), sendInputEvent: vi.fn(), + reload: vi.fn(), + reloadIgnoringCache: vi.fn(), }; return { webContents, @@ -41,17 +42,6 @@ describe("preview guest input", () => { expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything()); }); - it("uses CDP input while the guest holds focus, where it already reaches the page", async () => { - const guest = makeGuest({ focused: true }); - await guest.send("Input.insertText", { text: "x" }); - await guest.send("Input.dispatchKeyEvent", { type: "keyUp", key: "a" }); - expect(guest.sendCommand.mock.calls.map(([method]) => method)).toEqual([ - "Input.insertText", - "Input.dispatchKeyEvent", - ]); - expect(guest.webContents.insertText).not.toHaveBeenCalled(); - }); - it("refuses input when a cross-site frame holds the unfocused page's focus", async () => { const guest = makeGuest({ focused: false, focusedDocument: false }); await expect(guest.send("Input.insertText", { text: "secret" })).rejects.toThrow( @@ -59,35 +49,6 @@ describe("preview guest input", () => { ); expect(guest.webContents.insertText).not.toHaveBeenCalled(); }); - - it("clears a field with Cmd+A and Delete while unfocused, never touching the clipboard", async () => { - const guest = makeGuest({ focused: false }); - await guest.send("Input.dispatchKeyEvent", { - type: "rawKeyDown", - key: "a", - modifiers: 4, - commands: ["selectAll", "paste"], - }); - await guest.send("Input.dispatchKeyEvent", { type: "rawKeyDown", key: "Delete" }); - expect(guest.webContents.sendInputEvent.mock.calls.map(([event]) => event)).toEqual([ - { type: "rawKeyDown", keyCode: "a", modifiers: ["meta"] }, - { type: "rawKeyDown", keyCode: "Delete", modifiers: [] }, - ]); - const scripts = guest.sendCommand.mock.calls.map(([, params]) => params?.expression ?? ""); - expect(scripts.some((script) => script.includes('["selectAll"]'))).toBe(true); - expect(scripts.some((script) => script.includes("paste"))).toBe(false); - }); - - it("does not run other page commands through the guest's direct input", async () => { - const guest = makeGuest({ focused: false }); - await guest.send("Input.dispatchMouseEvent", { type: "mousePressed", x: 1, y: 1 }); - expect(guest.sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", { - type: "mousePressed", - x: 1, - y: 1, - }); - expect(guest.webContents.sendInputEvent).not.toHaveBeenCalled(); - }); }); describe("CDP key events as Electron input", () => { @@ -102,6 +63,7 @@ describe("CDP key events as Electron input", () => { ]); }); + // regression: #18556 agent typing in a preview tab landed in the app instead of the guest it("names arrows and function keys as Electron accelerators", () => { expect(toKeyboardInputEvents({ type: "keyUp", key: "ArrowLeft", modifiers: 3 })).toEqual([ { type: "keyUp", keyCode: "Left", modifiers: ["alt", "control"] }, diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 773d6b79873bc..42201b48ed61c 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -1,26 +1,12 @@ -/** - * Keyboard and text input for a preview tab's page that never lands outside it. - * - * Chromium sends a page's CDP key and text input to whichever frame holds focus - * in the window. A `` guest shares that focus with the app around it, - * so while a person works in the app, `Input.insertText` on the guest's own - * debugger types into the app's focused field. Such input goes through CDP only - * while the guest holds focus. Otherwise it goes straight to the guest's own - * widget, which nothing redirects. - */ +// CDP input follows shared window focus; send directly to unfocused guests to avoid typing into the app. -/** CDP input Chromium delivers to the window's focused frame rather than the page's. */ const FOCUS_ROUTED_INPUT = new Set([ "Input.insertText", "Input.dispatchKeyEvent", "Input.imeSetComposition", ]); -/** - * Page script: the document holding the page's focus, or null when a cross-site - * frame holds it. Electron's direct input reaches only the main frame's process, - * and `insertText` crashes the page when focus is in another one. - */ +/** Direct input reaches only the main-frame process; insertText crashes when a cross-site frame has focus. */ const FOCUSED_DOCUMENT = `(() => { let doc = document; for (;;) { @@ -31,11 +17,7 @@ const FOCUSED_DOCUMENT = `(() => { } })()`; -/** - * macOS editing commands a key press asks for (Cmd+A is `selectAll`), which - * Chromium runs only for CDP keys. Clipboard commands stay out: they would read - * or replace the person's clipboard. - */ +/** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */ const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]); const CROSS_SITE_FOCUS_MESSAGE = @@ -74,18 +56,13 @@ const MODIFIER_BITS = [ [8, "shift"], ] as const; -/** Electron's accelerator name for a DOM key value, or null when it has none. */ const keyCodeFor = (key: string) => { if ([...key].length === 1) return key; if (ARROW_KEYS[key]) return ARROW_KEYS[key]; return NAMED_KEYS.has(key) || /^F(?:[1-9]|1\d|2[0-4])$/u.test(key) ? key : null; }; -/** - * The Electron key events for one CDP `Input.dispatchKeyEvent`. Electron - * derives key, code, and a char's text from `keyCode`, so typed text travels - * as `char` events of its own. - */ +/** Electron derives text from keyCode, so typed text needs separate char events. */ export const toKeyboardInputEvents = ( params: Record, ): Array => { @@ -115,13 +92,19 @@ const evaluate = async (debuggee: Electron.Debugger, expression: string) => { return reply.result?.value; }; -/** Sends one command to the guest's page, keeping key and text input inside it. */ +/** Sends one command to the guest's page, keeping reloads and input inside it. */ export const sendPageCommand = async ( webContents: Electron.WebContents, debuggee: Electron.Debugger, method: string, params: Record, ): Promise => { + // Electron's debugger routes Page.reload on a webview to its embedder window. + if (method === "Page.reload") { + if (params["ignoreCache"] === true) webContents.reloadIgnoringCache(); + else webContents.reload(); + return {}; + } if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) { return debuggee.sendCommand(method, params); } diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 9fa089bf14cc8..85fa6115477a0 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -1,9 +1,9 @@ import { it as effectIt } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER } from "@t3tools/contracts"; import type { - DesktopPreviewRecordingFrame, DesktopPreviewRecordingInputEvent, + PreviewAnnotationPayload, + PreviewAnnotationRect, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { parseKeybindingShortcut } from "@t3tools/shared/keybindings"; @@ -32,11 +32,6 @@ import * as PreviewManager from "./Manager.ts"; import * as PreviewPasskeys from "./Passkeys.ts"; describe("fitPictureInPictureContentSize", () => { - it("preserves the PiP content area across aspect-ratio changes", () => { - expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 16 / 9)).toEqual([523, 294]); - expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 9 / 16)).toEqual([294, 523]); - }); - it("does not collapse toward the minimum size when orientation changes repeatedly", () => { const portrait = PreviewManager.fitPictureInPictureContentSize([523, 294], 9 / 16); const landscape = PreviewManager.fitPictureInPictureContentSize(portrait, 16 / 9); @@ -46,36 +41,6 @@ describe("fitPictureInPictureContentSize", () => { }); }); -describe("recordingFileExtension", () => { - it("derives the artifact extension from the recorder's actual mime type", () => { - expect(PreviewManager.recordingFileExtension("video/mp4;codecs=avc1.640028")).toBe("mp4"); - expect(PreviewManager.recordingFileExtension("video/webm;codecs=vp9")).toBe("webm"); - expect(PreviewManager.recordingFileExtension("video/x-matroska")).toBe("matroska"); - }); -}); - -describe("isPreviewRefreshShortcut", () => { - const input = (overrides: Partial = {}) => - ({ - type: "keyDown", - key: "r", - meta: true, - control: false, - shift: false, - alt: false, - ...overrides, - }) as Electron.Input; - - it("recognizes the platform refresh chord without matching modified variants", () => { - expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true); - expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe( - true, - ); - expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false); - expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false); - }); -}); - describe("isPreviewEditingShortcut", () => { const input = (platform: NodeJS.Platform, key: string, overrides: Partial = {}) => ({ @@ -88,42 +53,6 @@ describe("isPreviewEditingShortcut", () => { ...overrides, }) as Electron.Input; - it.each(["darwin", "linux", "win32"] as const)( - "allows native editing chords on %s without allowing host shortcuts", - (platform) => { - for (const key of ["a", "c", "v", "x", "z", "V"]) { - expect(PreviewManager.isPreviewEditingShortcut(input(platform, key), platform)).toBe(true); - } - const redo = - platform === "win32" ? input(platform, "y") : input(platform, "z", { shift: true }); - expect(PreviewManager.isPreviewEditingShortcut(redo, platform)).toBe(true); - expect( - PreviewManager.isPreviewEditingShortcut( - input(platform, "v", { shift: true, alt: platform === "darwin" }), - platform, - ), - ).toBe(true); - - for (const key of ["k", ",", "w", "j", "q", "+", "=", "-", "0", "r", "F12"]) { - expect(PreviewManager.isPreviewEditingShortcut(input(platform, key), platform)).toBe(false); - } - for (const modifiers of [ - { meta: false, control: false }, - { meta: true, control: true }, - { meta: platform !== "darwin", control: platform === "darwin" }, - { alt: true }, - { shift: true, alt: platform !== "darwin" }, - ]) { - expect( - PreviewManager.isPreviewEditingShortcut(input(platform, "v", modifiers), platform), - ).toBe(false); - } - expect( - PreviewManager.isPreviewEditingShortcut(input(platform, "a", { shift: true }), platform), - ).toBe(false); - }, - ); - it("recognizes macOS Paste and Match Style when Option changes the key to a symbol", () => { const pasteAndMatchStyle = input("darwin", "◊", { code: "KeyV", alt: true, shift: true }); expect(PreviewManager.isPreviewEditingShortcut(pasteAndMatchStyle, "darwin")).toBe(true); @@ -151,25 +80,13 @@ describe("previewWindowOpenAction", () => { }); it("opens a real window for scripted popups so the opener survives", () => { - // OAuth SDKs read a null `window.open()` as a blocked popup, and they need - // the opener alive to receive the credential back. expect(PreviewManager.previewWindowOpenAction(details({}))).toBe("popup"); expect( PreviewManager.previewWindowOpenAction(details({ url: "http://localhost:5173/auth" })), ).toBe("popup"); }); - it("opens target=_blank links as a new tab", () => { - expect(PreviewManager.previewWindowOpenAction(details({ disposition: "foreground-tab" }))).toBe( - "new-tab", - ); - expect(PreviewManager.previewWindowOpenAction(details({ disposition: "background-tab" }))).toBe( - "new-tab", - ); - }); - it("keeps a form POST with a body on the in-place path", () => { - // A new tab can only reopen the URL as a GET, which would drop the body. const postBody = { data: [], contentType: "application/x-www-form-urlencoded" }; expect( PreviewManager.previewWindowOpenAction({ @@ -180,9 +97,6 @@ describe("previewWindowOpenAction", () => { }); it("does not hand a window to schemes that cannot be hardened", () => { - // A popup skips the `will-attach-webview` hardening, so it only gets a window - // when its preferences can be overridden. Chromium copies the guest's - // preferences for `about:blank` and forbids overriding them. for (const url of [ "javascript:alert(1)", "file:///etc/passwd", @@ -194,8 +108,6 @@ describe("previewWindowOpenAction", () => { }); it("denies a blank window instead of blanking the opener", () => { - // MSAL opens `about:blank` first and falls back to a redirect on `null`; - // loading the blank page into the tab would destroy that fallback. for (const url of ["about:blank", ""]) { for (const disposition of ["new-window", "foreground-tab"] as const) { expect(PreviewManager.previewWindowOpenAction(details({ url, disposition }))).toBe("deny"); @@ -329,7 +241,6 @@ const withManager = ( interface TestCapturedPreviewImage { readonly toJPEG: () => Buffer; - /** Only fixtures that deliver picture-in-picture frames need pixels to fingerprint. */ readonly toBitmap?: () => Buffer; readonly getSize: () => { readonly width: number; readonly height: number }; } @@ -456,6 +367,7 @@ const makeSourcePng = (width = 1, height = 1): Buffer => { }; const makeFaviconWebContents = (options?: { + readonly changes?: ChangeSignal; readonly fetch?: (url: string, init?: RequestInit) => Promise; readonly id?: number; readonly rasterize?: (code: string) => Promise; @@ -466,16 +378,25 @@ const makeFaviconWebContents = (options?: { let currentUrl = options?.url ?? "http://localhost:3200/"; let destroyed = false; let loading = false; - const fetch = vi.fn( + const fetchImpl = options?.fetch ?? - (async () => - new Response(new Uint8Array(sourcePng), { - headers: { "content-type": "image/png" }, - })), - ); + (async () => + new Response(new Uint8Array(sourcePng), { + headers: { "content-type": "image/png" }, + })); + const fetch = vi.fn((url: string, init?: RequestInit) => { + const response = fetchImpl(url, init); + options?.changes?.notify(); + return response; + }); const executeJavaScriptInIsolatedWorld = vi.fn( - async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) => - options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON, + (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) => { + const result = options?.rasterize + ? options.rasterize(scripts[0]?.code ?? "") + : Promise.resolve(TEST_FAVICON); + options?.changes?.notify(); + return result; + }, ); const reload = vi.fn(); const loadURL = vi.fn(async (url: string) => { @@ -540,10 +461,33 @@ const makeFaviconWebContents = (options?: { }; }; -const settle = function* (until: () => boolean) { - for (let attempt = 0; attempt < 30 && !until(); attempt++) { - yield* Effect.promise(() => Promise.resolve()); - } +// Electron mocks and state subscribers call `notify`, so a wait re-checks its +// predicate exactly when the state it reads changes. +const makeChangeSignal = () => { + const waiters = new Set<() => void>(); + return { + notify: () => { + for (const wake of waiters) wake(); + }, + until: (predicate: () => boolean) => + Effect.callback((resume) => { + if (predicate()) return resume(Effect.void); + const wake = () => { + if (!predicate()) return; + waiters.delete(wake); + resume(Effect.void); + }; + waiters.add(wake); + return Effect.sync(() => void waiters.delete(wake)); + }), + }; +}; +type ChangeSignal = ReturnType; + +// Favicon captures run detached from the Electron listener, so asserting that +// one published nothing can only give its promise chain a fixed number of turns. +const flushMicrotasks = function* () { + for (let turn = 0; turn < 30; turn++) yield* Effect.promise(() => Promise.resolve()); }; const makeTestPictureInPictureWindow = (loadURL: () => Promise = async () => undefined) => { @@ -603,154 +547,6 @@ describe("PreviewManager", () => { webviewSend.mockClear(); }); - effectIt.effect("opens a target=_blank link as a new tab without navigating the opener", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); - const opened: Array<{ tabId: string; url: string; background: boolean }> = []; - yield* manager.subscribeOpenLinks((event) => Effect.sync(() => void opened.push(event))); - yield* manager.createTab("tab_links"); - yield* manager.registerWebview("tab_links", 42); - const openHandler = (preview.webContents as Electron.WebContents).setWindowOpenHandler as - | ReturnType - | undefined; - const handler = openHandler?.mock.lastCall?.[0] as ( - details: Partial, - ) => { action: string }; - - expect( - handler({ url: "https://github.com/issues/1", disposition: "foreground-tab" }), - ).toEqual({ action: "deny" }); - expect(handler({ url: "about:blank", disposition: "new-window" })).toEqual({ - action: "deny", - }); - handler({ url: "https://github.com/issues/2", disposition: "background-tab" }); - yield* settle(() => opened.length === 2); - - expect(preview.loadURL).not.toHaveBeenCalled(); - expect(opened).toEqual([ - { tabId: "tab_links", url: "https://github.com/issues/1", background: false }, - { tabId: "tab_links", url: "https://github.com/issues/2", background: true }, - ]); - }), - ), - ); - - effectIt.effect("keeps preview shortcuts out of the host window", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - const sendInputEvent = vi.fn(); - const hostWebContents = { sendInputEvent, isDestroyed: () => false }; - Object.assign(preview.webContents, { hostWebContents }); - fromId.mockReturnValue(preview.webContents); - yield* manager.setMainWindow({ - isDestroyed: () => false, - once: vi.fn(), - webContents: hostWebContents, - } as never); - yield* manager.createTab("tab_keys"); - yield* manager.registerWebview("tab_keys", 42); - - expect( - (preview.webContents as Electron.WebContents).setIgnoreMenuShortcuts, - ).toHaveBeenCalledWith(true); - const beforeInput = preview.listeners.get("before-input-event")!; - for (const control of [false, true]) { - for (const key of ["k", ",", "w", "j", "q", "+"]) { - for (const type of ["keyDown", "keyUp"]) { - const preventDefault = vi.fn(); - beforeInput( - { preventDefault } as never, - { type, key, meta: !control, control, shift: key === "j", alt: false } as never, - ); - yield* Effect.yieldNow; - expect(preventDefault).not.toHaveBeenCalled(); - expect( - (preview.webContents as Electron.WebContents).setIgnoreMenuShortcuts, - ).toHaveBeenLastCalledWith(true); - } - } - } - expect(sendInputEvent).not.toHaveBeenCalled(); - - const preventDefault = vi.fn(); - beforeInput( - { preventDefault } as never, - { - type: "keyDown", - key: "r", - meta: true, - control: false, - shift: false, - alt: false, - } as never, - ); - yield* Effect.yieldNow; - expect(preventDefault).toHaveBeenCalledOnce(); - expect(preview.reload).toHaveBeenCalledOnce(); - expect(sendInputEvent).not.toHaveBeenCalled(); - }), - ), - ); - - effectIt.effect.each([ - ["mod+shift+t", "view.reopenClosed"], - ["ctrl+alt+u", "sidebar.toggle"], - ] as const)( - "forwards only the configured command from the focused guest: %s", - ([chord, command]) => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - const send = vi.fn(); - Object.assign(preview.webContents, { - hostWebContents: { isDestroyed: () => false, send }, - }); - fromId.mockReturnValue(preview.webContents); - yield* manager.createTab("tab_reopen"); - yield* manager.registerWebview("tab_reopen", 42); - const shortcut = parseKeybindingShortcut(chord)!; - yield* manager.setForwardedShortcuts([{ command, shortcut }]); - const beforeInput = preview.listeners.get("before-input-event")!; - const input = { - type: "keyDown", - key: shortcut.key.toUpperCase(), - meta: shortcut.metaKey || shortcut.modKey, - control: shortcut.ctrlKey, - shift: shortcut.shiftKey, - alt: shortcut.altKey, - }; - const preventDefault = vi.fn(); - beforeInput({ preventDefault } as never, input as never); - expect(preventDefault).toHaveBeenCalledOnce(); - expect(send).toHaveBeenCalledExactlyOnceWith("desktop:menu-action", command); - for (const overrides of [ - { isAutoRepeat: true }, - { type: "keyUp" }, - { shift: !input.shift }, - { key: "x" }, - ]) { - preventDefault.mockClear(); - beforeInput({ preventDefault } as never, { ...input, ...overrides } as never); - expect(preventDefault).toHaveBeenCalledTimes("isAutoRepeat" in overrides ? 1 : 0); - expect(send).toHaveBeenCalledOnce(); - } - vi.mocked((preview.webContents as Electron.WebContents).isFocused).mockReturnValue(false); - preventDefault.mockClear(); - beforeInput({ preventDefault } as never, input as never); - expect(preventDefault).not.toHaveBeenCalled(); - expect(send).toHaveBeenCalledOnce(); - vi.mocked((preview.webContents as Electron.WebContents).isFocused).mockReturnValue(true); - yield* manager.setForwardedShortcuts([]); - beforeInput({ preventDefault } as never, input as never); - expect(preventDefault).not.toHaveBeenCalled(); - expect(send).toHaveBeenCalledOnce(); - }), - ), - ); - effectIt.effect.each([ ["linux", "ctrl+alt+[", "[", "BracketLeft", false], ["win32", "ctrl+alt+8", "[", "Digit8", false], @@ -795,52 +591,6 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("preserves focused browser editing in tabs and sign-in popups", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); - yield* manager.createTab("tab_editing"); - yield* manager.registerWebview("tab_editing", 42); - - const popup = makeFaviconWebContents({ id: 43 }); - preview.listeners.get("did-create-window")!({ webContents: popup.webContents } as never); - expect( - (popup.webContents as Electron.WebContents).setIgnoreMenuShortcuts, - ).toHaveBeenCalledWith(true); - - for (const browser of [preview, popup]) { - const contents = browser.webContents as Electron.WebContents; - const beforeInput = browser.listeners.get("before-input-event")!; - const preventDefault = vi.fn(); - const input = { - type: "keyDown", - key: "v", - meta: true, - control: false, - shift: false, - alt: false, - }; - beforeInput({ preventDefault } as never, input as never); - expect(contents.setIgnoreMenuShortcuts).toHaveBeenLastCalledWith(false); - beforeInput( - { preventDefault } as never, - { ...input, type: "keyUp", key: "Meta", meta: false } as never, - ); - expect(contents.setIgnoreMenuShortcuts).toHaveBeenLastCalledWith(false); - - beforeInput({ preventDefault } as never, { ...input, key: "w" } as never); - expect(contents.setIgnoreMenuShortcuts).toHaveBeenLastCalledWith(true); - - vi.mocked(contents.isFocused).mockReturnValue(false); - beforeInput({ preventDefault } as never, input as never); - expect(contents.setIgnoreMenuShortcuts).toHaveBeenLastCalledWith(true); - expect(preventDefault).not.toHaveBeenCalled(); - } - }), - ), - ); - effectIt.effect("keeps editing and forwarded shortcuts in whichever tab holds focus", () => withManager((manager) => Effect.gen(function* () { @@ -849,7 +599,6 @@ describe("PreviewManager", () => { const older = makeFaviconWebContents({ id: 42 }); const newer = makeFaviconWebContents({ id: 43 }); for (const tab of [older, newer]) Object.assign(tab.webContents, { hostWebContents: host }); - // Electron names one arbitrary guest here when several share a focused window. getFocusedWebContents.mockReturnValue(newer.webContents as never); fromId.mockReturnValue(older.webContents); yield* manager.createTab("tab_older"); @@ -875,7 +624,6 @@ describe("PreviewManager", () => { expect(preventDefault).toHaveBeenCalledOnce(); expect(send).toHaveBeenCalledExactlyOnceWith("desktop:menu-action", "view.reopenClosed"); - // The person types in the older tab, so keys reaching the newer one are an agent's. Object.assign(newer.webContents, { focusedFrame: null }); const agentInput = newer.listeners.get("before-input-event")!; const agentPreventDefault = vi.fn(); @@ -896,32 +644,6 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("rejects a destroyed webview during registration", () => - withManager((manager) => - Effect.gen(function* () { - const getType = vi.fn(() => "webview" as const); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => true, - getType, - } as never); - yield* manager.createTab("tab_destroyed_registration"); - - const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42)); - - expect(Exit.isFailure(exit)).toBe(true); - if (Exit.isFailure(exit)) { - expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({ - _tag: "PreviewWebContentsNotFoundError", - tabId: "tab_destroyed_registration", - webContentsId: 42, - }); - } - expect(getType).not.toHaveBeenCalled(); - }), - ), - ); - effectIt.effect("isolates failed state listeners and continues delivery", () => { const loggedErrors: Array = []; const logger = Logger.make(({ message }) => { @@ -1034,42 +756,9 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("detaches a destroyed webview instead of navigating it", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_destroyed_navigation"); - yield* manager.registerWebview("tab_destroyed_navigation", 42); - yield* manager.setColorScheme("tab_destroyed_navigation", "dark"); - preview.setDestroyed(true); - - yield* manager.navigate("tab_destroyed_navigation", "https://example.com/"); - - expect(preview.loadURL).not.toHaveBeenCalled(); - expect(preview.reload).not.toHaveBeenCalled(); - expect(preview.off).toHaveBeenCalled(); - expect(preview.debuggerOff).toHaveBeenCalled(); - expect(states.at(-1)).toMatchObject({ - webContentsId: null, - navStatus: { kind: "Loading", url: "https://example.com/" }, - }); - }), - ), - ); - effectIt.effect("detaches through the pinned debugger after the webview is destroyed", () => withManager((manager) => Effect.gen(function* () { - // Real Electron throws on any `wc.debugger` access once the - // WebContents is destroyed, so cleanup must go through the debugger - // reference captured at attach time (electron/electron#53376). let destroyed = false; let attached = false; const debuggerOff = vi.fn(); @@ -1170,46 +859,16 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("publishes a canonical favicon origin while the page is loading", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents({ - url: `http://localhost:3200/${"x".repeat(3_000)}`, - }); - preview.setLoading(true); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_loading"); - yield* manager.registerWebview("tab_favicon_loading", 42); - - preview.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - expect(states.at(-1)?.favicon).toMatchObject({ - dataUrl: TEST_FAVICON, - pageUrl: "http://localhost:3200", - }); - expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number)); - }), - ), - ); - effectIt.effect("shares an identical in-flight event and lets a changed event win", () => withManager((manager) => Effect.gen(function* () { + const changes = makeChangeSignal(); let resolveFirst!: (response: Response) => void; const firstResponse = new Promise((resolve) => { resolveFirst = resolve; }); const preview = makeFaviconWebContents({ + changes, fetch: (url) => url.endsWith("first.png") ? firstResponse @@ -1224,6 +883,7 @@ describe("PreviewManager", () => { yield* manager.subscribeStateChanges((_tabId, state) => Effect.sync(() => { states.push(state); + changes.notify(); }), ); yield* manager.createTab("tab_favicon_latest"); @@ -1232,15 +892,15 @@ describe("PreviewManager", () => { const faviconUpdated = preview.listeners.get("page-favicon-updated")!; faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never); faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never); - yield* settle(() => preview.fetch.mock.calls.length === 1); + yield* changes.until(() => preview.fetch.mock.calls.length === 1); faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never); - yield* settle(() => states.at(-1)?.favicon !== undefined); + yield* changes.until(() => states.at(-1)?.favicon !== undefined); resolveFirst( new Response(new Uint8Array(makeSourcePng()), { headers: { "content-type": "image/png" }, }), ); - yield* settle(() => false); + yield* flushMicrotasks(); expect(preview.fetch).toHaveBeenCalledTimes(2); expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1); @@ -1248,41 +908,13 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("allows an identical retry after an undecodable capture", () => - withManager((manager) => - Effect.gen(function* () { - let rasterizations = 0; - const preview = makeFaviconWebContents({ - rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON), - }); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_retry"); - yield* manager.registerWebview("tab_favicon_retry", 42); - const faviconUpdated = preview.listeners.get("page-favicon-updated")!; - - faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never); - yield* settle(() => rasterizations === 1); - yield* settle(() => false); - faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - expect(rasterizations).toBe(2); - expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON); - }), - ), - ); - effectIt.effect("does not publish a capture invalidated by navigation", () => withManager((manager) => Effect.gen(function* () { + const changes = makeChangeSignal(); let resolveFetch!: (response: Response) => void; const preview = makeFaviconWebContents({ + changes, fetch: () => new Promise((resolve) => { resolveFetch = resolve; @@ -1293,6 +925,7 @@ describe("PreviewManager", () => { yield* manager.subscribeStateChanges((_tabId, state) => Effect.sync(() => { states.push(state); + changes.notify(); }), ); yield* manager.createTab("tab_favicon_navigation"); @@ -1301,7 +934,7 @@ describe("PreviewManager", () => { {} as never, ["http://localhost:3200/favicon.png"] as never, ); - yield* settle(() => preview.fetch.mock.calls.length === 1); + yield* changes.until(() => preview.fetch.mock.calls.length === 1); preview.listeners.get("did-start-navigation")?.({ isMainFrame: true, isSameDocument: false, @@ -1312,569 +945,90 @@ describe("PreviewManager", () => { headers: { "content-type": "image/png" }, }), ); - yield* settle(() => false); + yield* flushMicrotasks(); expect(states.some((state) => state.favicon !== undefined)).toBe(false); }), ), ); - effectIt.effect("retains a favicon when reloading the current URL without a new event", () => + effectIt.effect("ignores an old capture that completes after webview replacement", () => withManager((manager) => Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); + const changes = makeChangeSignal(); + let resolveFetch!: (response: Response) => void; + const initial = makeFaviconWebContents({ + changes, + id: 42, + fetch: () => + new Promise((resolve) => { + resolveFetch = resolve; + }), + }); + const replacement = makeFaviconWebContents({ changes, id: 43 }); + fromId.mockImplementation((id?: number) => + id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null, + ); const states: PreviewManager.PreviewTabState[] = []; yield* manager.subscribeStateChanges((_tabId, state) => Effect.sync(() => { states.push(state); + changes.notify(); }), ); - yield* manager.createTab("tab_favicon_reload"); - yield* manager.registerWebview("tab_favicon_reload", 42); - preview.listeners.get("page-favicon-updated")?.( + yield* manager.createTab("tab_favicon_late_replace"); + yield* manager.registerWebview("tab_favicon_late_replace", 42); + initial.listeners.get("page-favicon-updated")?.( {} as never, ["http://localhost:3200/favicon.png"] as never, ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/"); + yield* changes.until(() => initial.fetch.mock.calls.length === 1); - expect(preview.reload).toHaveBeenCalledOnce(); - expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON); - }), - ), - ); - - effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); + yield* manager.registerWebview("tab_favicon_late_replace", 43); + resolveFetch( + new Response(new Uint8Array(makeSourcePng()), { + headers: { "content-type": "image/png" }, }), ); - yield* manager.createTab("tab_favicon_origin"); - yield* manager.registerWebview("tab_favicon_origin", 42); - preview.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - preview.setUrl("https://example.com/"); - preview.listeners.get("did-navigate")?.({} as never); - yield* settle(() => states.at(-1)?.navStatus.kind === "Success"); + yield* flushMicrotasks(); - expect(states.at(-1)?.favicon).toBeUndefined(); + expect(states.at(-1)?.webContentsId).toBe(43); + expect( + states.some((state) => state.webContentsId === 43 && state.favicon !== undefined), + ).toBe(false); }), ), ); - effectIt.effect( - "retains the previous document icon across a failed cross-origin navigation", - () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_failed_origin"); - yield* manager.registerWebview("tab_favicon_failed_origin", 42); - preview.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - preview.listeners.get("did-fail-load")?.( - {} as never, - -105 as never, - "Name not resolved" as never, - "https://unreachable.example/" as never, - true as never, - ); - yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed"); - expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON); - - preview.listeners.get("did-navigate")?.({} as never); - yield* settle(() => states.at(-1)?.navStatus.kind === "Success"); - expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON); - }), - ), - ); - - effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () => + effectIt.effect("treats a reused WebContents id as a new attachment", () => withManager((manager) => Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); + const changes = makeChangeSignal(); + const initial = makeFaviconWebContents({ changes, id: 42 }); + const replacement = makeFaviconWebContents({ changes, id: 42 }); + let active = initial.webContents; + fromId.mockImplementation(() => active); const states: PreviewManager.PreviewTabState[] = []; yield* manager.subscribeStateChanges((_tabId, state) => Effect.sync(() => { states.push(state); + changes.notify(); }), ); - yield* manager.createTab("tab_favicon_blank"); - yield* manager.registerWebview("tab_favicon_blank", 42); - preview.listeners.get("page-favicon-updated")?.( + yield* manager.createTab("tab_favicon_reused_id"); + yield* manager.registerWebview("tab_favicon_reused_id", 42); + initial.listeners.get("page-favicon-updated")?.( {} as never, ["http://localhost:3200/favicon.png"] as never, ); - yield* settle(() => states.at(-1)?.favicon !== undefined); + yield* changes.until(() => states.at(-1)?.favicon !== undefined); - preview.setUrl("about:blank"); - preview.listeners.get("did-navigate")?.({} as never); - yield* settle(() => states.at(-1)?.navStatus.kind === "Idle"); - expect(states.at(-1)?.favicon).toBeUndefined(); + active = replacement.webContents; + yield* manager.registerWebview("tab_favicon_reused_id", 42); - preview.setUrl("http://localhost:3200/"); - preview.listeners.get("did-navigate")?.({} as never); - yield* settle(() => states.at(-1)?.navStatus.kind === "Success"); expect(states.at(-1)?.favicon).toBeUndefined(); - }), - ), - ); - - effectIt.effect("clears a published favicon when a replacement webview attaches", () => - withManager((manager) => - Effect.gen(function* () { - const initial = makeFaviconWebContents({ id: 42 }); - const replacement = makeFaviconWebContents({ id: 43 }); - fromId.mockImplementation((id?: number) => { - if (id === 42) return initial.webContents; - if (id === 43) return replacement.webContents; - return null; - }); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_replace"); - yield* manager.registerWebview("tab_favicon_replace", 42); - initial.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - yield* manager.registerWebview("tab_favicon_replace", 43); - - expect(states.at(-1)?.webContentsId).toBe(43); - expect(states.at(-1)?.favicon).toBeUndefined(); - }), - ), - ); - - effectIt.effect("ignores an old capture that completes after webview replacement", () => - withManager((manager) => - Effect.gen(function* () { - let resolveFetch!: (response: Response) => void; - const initial = makeFaviconWebContents({ - id: 42, - fetch: () => - new Promise((resolve) => { - resolveFetch = resolve; - }), - }); - const replacement = makeFaviconWebContents({ id: 43 }); - fromId.mockImplementation((id?: number) => - id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null, - ); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_late_replace"); - yield* manager.registerWebview("tab_favicon_late_replace", 42); - initial.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => initial.fetch.mock.calls.length === 1); - - yield* manager.registerWebview("tab_favicon_late_replace", 43); - resolveFetch( - new Response(new Uint8Array(makeSourcePng()), { - headers: { "content-type": "image/png" }, - }), - ); - yield* settle(() => false); - - expect(states.at(-1)?.webContentsId).toBe(43); - expect( - states.some((state) => state.webContentsId === 43 && state.favicon !== undefined), - ).toBe(false); - }), - ), - ); - - effectIt.effect("treats a reused WebContents id as a new attachment", () => - withManager((manager) => - Effect.gen(function* () { - const initial = makeFaviconWebContents({ id: 42 }); - const replacement = makeFaviconWebContents({ id: 42 }); - let active = initial.webContents; - fromId.mockImplementation(() => active); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_reused_id"); - yield* manager.registerWebview("tab_favicon_reused_id", 42); - initial.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - active = replacement.webContents; - yield* manager.registerWebview("tab_favicon_reused_id", 42); - - expect(states.at(-1)?.favicon).toBeUndefined(); - expect(initial.off).toHaveBeenCalled(); - expect(replacement.listeners.has("page-favicon-updated")).toBe(true); - }), - ), - ); - - effectIt.effect("preserves a favicon when the active attachment registers again", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_favicon_reregister"); - yield* manager.registerWebview("tab_favicon_reregister", 42); - preview.listeners.get("page-favicon-updated")?.( - {} as never, - ["http://localhost:3200/favicon.png"] as never, - ); - yield* settle(() => states.at(-1)?.favicon !== undefined); - - yield* manager.registerWebview("tab_favicon_reregister", 42); - - expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON); - }), - ), - ); - - // The guest reports whatever zoom level Chromium handed it from the app - // window, so the tab's own zoom is the source of truth in both directions: - // asserted onto every guest, never read back off one. - effectIt.effect("keeps the tab's own zoom instead of the guest's reported zoom", () => - withManager((manager) => - Effect.gen(function* () { - let effectiveZoom = 0.9; - let zoomReadable = true; - let url = "https://example.com"; - const listeners = new Map void>(); - const setZoomFactor = vi.fn(); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => url, - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => { - if (!zoomReadable) throw new Error("zoom unavailable"); - return effectiveZoom; - }, - setZoomFactor, - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { - listeners.set(event, listener); - }), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_zoom"); - yield* manager.registerWebview("tab_zoom", 42); - - expect(states.at(-1)?.zoomFactor).toBe(1); - expect(setZoomFactor).toHaveBeenCalledWith(1); - - effectiveZoom = 0.8; - url = "https://example.com/after-app-zoom"; - listeners.get("did-navigate")?.(); - yield* Effect.yieldNow; - - expect(states.at(-1)?.navStatus).toEqual({ - kind: "Success", - url, - title: "Example", - }); - expect(states.at(-1)?.zoomFactor).toBe(1); - - yield* manager.zoomIn("tab_zoom"); - expect(setZoomFactor).toHaveBeenCalledWith(1.1); - expect(states.at(-1)?.zoomFactor).toBe(1.1); - - zoomReadable = false; - listeners.get("did-navigate")?.(); - yield* Effect.yieldNow; - - expect(states.at(-1)?.zoomFactor).toBe(1.1); - - const replacementSetZoomFactor = vi.fn(); - fromId.mockReturnValue({ - id: 43, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => url, - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor: replacementSetZoomFactor, - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - - yield* manager.registerWebview("tab_zoom", 43); - - expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.1); - expect(states.at(-1)?.zoomFactor).toBe(1.1); - }), - ), - ); - - // Zooming the app UI pushes the window's zoom level onto every guest, so the - // preview has to be put back at the zoom the user gave it. - effectIt.effect("re-applies each tab's own zoom when the app window zooms", () => - withManager((manager) => - Effect.gen(function* () { - const setZoomFactor = vi.fn(); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor, - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - - yield* manager.createTab("tab_reapply"); - yield* manager.registerWebview("tab_reapply", 42); - yield* manager.zoomIn("tab_reapply"); - setZoomFactor.mockClear(); - - yield* manager.reapplyZoom(); - - expect(setZoomFactor).toHaveBeenCalledTimes(1); - expect(setZoomFactor).toHaveBeenCalledWith(1.1); - }), - ), - ); - - effectIt.effect("re-asserts the tab's zoom when the active guest registers again", () => - withManager((manager) => - Effect.gen(function* () { - const setZoomFactor = vi.fn(); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor, - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - - yield* manager.createTab("tab_reregister_zoom"); - yield* manager.registerWebview("tab_reregister_zoom", 42); - yield* manager.zoomIn("tab_reregister_zoom"); - setZoomFactor.mockClear(); - const publishedBefore = states.length; - - yield* manager.registerWebview("tab_reregister_zoom", 42); - - expect(setZoomFactor).toHaveBeenCalledWith(1.1); - expect(states.length).toBe(publishedBefore); - expect(states.at(-1)?.zoomFactor).toBe(1.1); - }), - ), - ); - - effectIt.effect("re-applies opaque base and color scheme across webview swaps", () => - withManager((manager) => - Effect.gen(function* () { - const makeWebContents = (id: number) => { - const sendCommand = vi.fn(async () => undefined); - return { - sendCommand, - wc: { - id, - isDestroyed: () => false, - isDevToolsOpened: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand, - on: vi.fn(), - off: vi.fn(), - }, - } as never, - }; - }; - const first = makeWebContents(42); - fromId.mockReturnValue(first.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_scheme"); - yield* manager.registerWebview("tab_scheme", 42); - yield* Effect.yieldNow; - - // Guests start with a transparent base; dark-scheme pages need an opaque - // one or Chromium skips their dark canvas. - const opaqueBase = { - color: { r: 255, g: 255, b: 255, a: 1 }, - }; - expect(first.sendCommand).toHaveBeenCalledWith( - "Emulation.setDefaultBackgroundColorOverride", - opaqueBase, - ); - - yield* manager.setColorScheme("tab_scheme", "dark"); - - expect(first.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", { - features: [{ name: "prefers-color-scheme", value: "dark" }], - }); - expect(states.at(-1)?.colorScheme).toBe("dark"); - - const replacement = makeWebContents(43); - fromId.mockReturnValue(replacement.wc); - yield* manager.registerWebview("tab_scheme", 43); - yield* Effect.yieldNow; - - expect(replacement.sendCommand).toHaveBeenCalledWith( - "Emulation.setDefaultBackgroundColorOverride", - opaqueBase, - ); - expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", { - features: [{ name: "prefers-color-scheme", value: "dark" }], - }); - expect(states.at(-1)?.colorScheme).toBe("dark"); - - yield* manager.setColorScheme("tab_scheme", "system"); - - expect(replacement.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", { - features: [{ name: "prefers-color-scheme", value: "" }], - }); - expect(states.at(-1)?.colorScheme).toBe("system"); + expect(initial.off).toHaveBeenCalled(); + expect(replacement.listeners.has("page-favicon-updated")).toBe(true); }), ), ); @@ -1886,12 +1040,13 @@ describe("PreviewManager", () => { const sendCommand = vi.fn<(method: string, params?: unknown) => Promise>( async () => undefined, ); + const detachListeners = new Set<() => void>(); + let chromiumDetaches = 0; let destroyed = false; const wc = { id, isDestroyed: () => destroyed, isDevToolsOpened: () => { - // Electron throws from native methods once a WebContents is destroyed. if (destroyed) throw new TypeError("Object has been destroyed"); return false; }, @@ -1914,642 +1069,263 @@ describe("PreviewManager", () => { setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), debugger: { - isAttached: () => attach.mock.calls.length > detach.mock.calls.length, + isAttached: () => attach.mock.calls.length > detach.mock.calls.length + chromiumDetaches, attach, detach, sendCommand, - on: vi.fn(), - off: vi.fn(), - }, - }; - return { - wc: wc as unknown as Electron.WebContents, - attach, - detach, - sendCommand, - destroy: () => { - destroyed = true; - listeners.get("destroyed")?.(); - }, - }; - }; - - effectIt.effect("sets the opaque base as soon as a guest attaches", () => - withManager((manager) => - Effect.gen(function* () { - const claimed = makeAttachingGuest(44); - fromId.mockReturnValue(claimed.wc); - yield* manager.prepareWebview(claimed.wc); - expect(claimed.attach).toHaveBeenCalledTimes(1); - expect(claimed.sendCommand.mock.calls[0]).toEqual([ - "Emulation.setDefaultBackgroundColorOverride", - { color: { r: 255, g: 255, b: 255, a: 1 } }, - ]); - - yield* manager.createTab("tab_early"); - yield* manager.registerWebview("tab_early", 44); - yield* manager.setColorScheme("tab_early", "dark"); - expect(claimed.attach).toHaveBeenCalledTimes(1); - expect(claimed.sendCommand).toHaveBeenCalledWith("Emulation.setEmulatedMedia", { - features: [{ name: "prefers-color-scheme", value: "dark" }], - }); - - const unclaimed = makeAttachingGuest(45); - yield* manager.prepareWebview(unclaimed.wc); - expect(unclaimed.attach).toHaveBeenCalledTimes(1); - unclaimed.destroy(); - yield* Effect.yieldNow; - expect(unclaimed.detach).toHaveBeenCalledTimes(1); - expect(claimed.detach).not.toHaveBeenCalled(); - }), - ), - ); - - effectIt.effect("skips a guest destroyed while another guest's session opens", () => - withManager((manager) => - Effect.gen(function* () { - const slow = makeAttachingGuest(46); - let releaseSlow = () => {}; - const slowCommand = new Promise((resolve) => { - releaseSlow = resolve; - }); - slow.sendCommand.mockImplementation(() => slowCommand); - const queued = makeAttachingGuest(47); - - const slowFiber = yield* manager - .prepareWebview(slow.wc) - .pipe(Effect.forkChild({ startImmediately: true })); - const queuedFiber = yield* manager - .prepareWebview(queued.wc) - .pipe(Effect.forkChild({ startImmediately: true })); - queued.destroy(); - releaseSlow(); - - expect(Exit.isSuccess(yield* Fiber.await(slowFiber))).toBe(true); - expect(Exit.isSuccess(yield* Fiber.await(queuedFiber))).toBe(true); - expect(slow.attach).toHaveBeenCalledTimes(1); - expect(queued.attach).not.toHaveBeenCalled(); - }), - ), - ); - - const makeAudioWebContents = (id: number) => { - const listeners = new Map void>(); - const setAudioMuted = vi.fn(); - let audible = false; - let audibleAfterFirstRead = false; - let audibleReads = 0; - return { - setAudioMuted, - emitAudioState: (next: boolean) => { - audible = next; - listeners.get("audio-state-changed")?.({ audible: next } as never); - }, - /** - * Starts playing between the attach-time read and the post-attach - * reconcile, without a delivered event — the window in which - * audio-state-changed fires against a guest the tab does not own yet. - */ - startPlayingAfterFirstRead: () => { - audibleAfterFirstRead = true; - }, - wc: { - id, - isDestroyed: () => false, - isDevToolsOpened: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted, - isCurrentlyAudible: () => { - audibleReads += 1; - if (audibleAfterFirstRead && audibleReads > 1) return true; - return audible; + on: (event: string, listener: () => void) => { + if (event === "detach") detachListeners.add(listener); }, - loadURL: vi.fn(async () => undefined), - on: vi.fn((event: string, listener: (...args: never[]) => void) => { - listeners.set(event, listener); - }), - off: vi.fn((event: string) => { - listeners.delete(event); - }), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), + off: (event: string, listener: () => void) => { + if (event === "detach") detachListeners.delete(listener); }, - } as never, - }; - }; - - effectIt.effect("mutes the guest and re-applies the mute across webview swaps", () => - withManager((manager) => - Effect.gen(function* () { - const first = makeAudioWebContents(42); - fromId.mockReturnValue(first.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_audio"); - yield* manager.registerWebview("tab_audio", 42); - yield* Effect.yieldNow; - - expect(states.at(-1)?.audioMuted).toBe(false); - - yield* manager.setAudioMuted("tab_audio", true); - - expect(first.setAudioMuted).toHaveBeenCalledWith(true); - expect(states.at(-1)?.audioMuted).toBe(true); - - const replacement = makeAudioWebContents(43); - fromId.mockReturnValue(replacement.wc); - yield* manager.registerWebview("tab_audio", 43); - yield* Effect.yieldNow; - - expect(replacement.setAudioMuted).toHaveBeenCalledWith(true); - expect(states.at(-1)?.audioMuted).toBe(true); - - yield* manager.setAudioMuted("tab_audio", false); - - expect(replacement.setAudioMuted).toHaveBeenLastCalledWith(false); - expect(states.at(-1)?.audioMuted).toBe(false); - }), - ), - ); - - effectIt.effect("fails and rolls back when the guest refuses a mute", () => - withManager((manager) => - Effect.gen(function* () { - const guest = makeAudioWebContents(42); - fromId.mockReturnValue(guest.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_audio_fail"); - yield* manager.registerWebview("tab_audio_fail", 42); - yield* Effect.yieldNow; - - guest.setAudioMuted.mockImplementationOnce(() => { - throw new Error("guest refused"); - }); - const exit = yield* manager.setAudioMuted("tab_audio_fail", true).pipe(Effect.exit); - - expect(Exit.isFailure(exit)).toBe(true); - expect(states.at(-1)?.audioMuted).toBe(false); - }), - ), - ); - - effectIt.effect("still registers a guest that refuses the mute reassert", () => - withManager((manager) => - Effect.gen(function* () { - const first = makeAudioWebContents(42); - fromId.mockReturnValue(first.wc); - yield* manager.createTab("tab_audio_attach_fail"); - yield* manager.registerWebview("tab_audio_attach_fail", 42); - yield* Effect.yieldNow; - yield* manager.setAudioMuted("tab_audio_attach_fail", true); - - const replacement = makeAudioWebContents(43); - replacement.setAudioMuted.mockImplementationOnce(() => undefined); - replacement.setAudioMuted.mockImplementationOnce(() => { - throw new Error("guest went away"); - }); - fromId.mockReturnValue(replacement.wc); - - const exit = yield* manager.registerWebview("tab_audio_attach_fail", 43).pipe(Effect.exit); - expect(Exit.isSuccess(exit)).toBe(true); - }), - ), - ); - - effectIt.effect("reconciles audibility that changed while the guest attached", () => - withManager((manager) => - Effect.gen(function* () { - const guest = makeAudioWebContents(42); - guest.startPlayingAfterFirstRead(); - fromId.mockReturnValue(guest.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_audio_window"); - yield* manager.registerWebview("tab_audio_window", 42); - yield* Effect.yieldNow; - - // audio-state-changed for this transition was dropped: it fired before - // the tab owned the guest. Without a post-attach reconcile the icon - // stays wrong until the next real transition, which may never come. - expect(states.at(-1)?.audible).toBe(true); - }), - ), - ); - - effectIt.effect("publishes audibility transitions and drops repeats", () => - withManager((manager) => - Effect.gen(function* () { - const guest = makeAudioWebContents(42); - fromId.mockReturnValue(guest.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_audible"); - yield* manager.registerWebview("tab_audible", 42); - yield* Effect.yieldNow; - - expect(states.at(-1)?.audible).toBe(false); - - guest.emitAudioState(true); - yield* Effect.yieldNow; - expect(states.at(-1)?.audible).toBe(true); - - // Chromium re-emits per media element; only real transitions publish. - const publishedAfterFirst = states.length; - guest.emitAudioState(true); - yield* Effect.yieldNow; - expect(states.length).toBe(publishedAfterFirst); - - guest.emitAudioState(false); - yield* Effect.yieldNow; - expect(states.at(-1)?.audible).toBe(false); - expect(states.length).toBeGreaterThan(publishedAfterFirst); - }), - ), - ); - - effectIt.effect("ignores audio state from a replaced guest", () => - withManager((manager) => - Effect.gen(function* () { - const first = makeAudioWebContents(42); - fromId.mockReturnValue(first.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_audio_stale"); - yield* manager.registerWebview("tab_audio_stale", 42); - yield* Effect.yieldNow; - - const replacement = makeAudioWebContents(43); - fromId.mockReturnValue(replacement.wc); - yield* manager.registerWebview("tab_audio_stale", 43); - yield* Effect.yieldNow; - - const publishedBefore = states.length; - first.emitAudioState(true); - yield* Effect.yieldNow; - - expect(states.length).toBe(publishedBefore); - expect(states.at(-1)?.audible).toBe(false); - }), - ), - ); + }, + }; + /** Chromium dropping the debugger without a detach() call. */ + const chromiumDetach = () => { + chromiumDetaches += 1; + // Snapshot like an EventEmitter, so a listener added during emit waits for the next one. + for (const listener of Array.from(detachListeners)) listener(); + }; + return { + wc: wc as unknown as Electron.WebContents, + attach, + detach, + sendCommand, + chromiumDetach, + destroy: () => { + destroyed = true; + listeners.get("destroyed")?.(); + }, + }; + }; - effectIt.effect("carries mute and audibility across navigation", () => + effectIt.effect("reattaches a debugger that Chromium dropped on its own", () => withManager((manager) => Effect.gen(function* () { - const guest = makeAudioWebContents(42); + const guest = makeAttachingGuest(48); fromId.mockReturnValue(guest.wc); - const states: PreviewManager.PreviewTabState[] = []; - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.createTab("tab_audio_nav"); - yield* manager.registerWebview("tab_audio_nav", 42); - yield* Effect.yieldNow; - - yield* manager.setAudioMuted("tab_audio_nav", true); - guest.emitAudioState(true); + yield* manager.createTab("tab_detached"); + yield* manager.registerWebview("tab_detached", 48); yield* Effect.yieldNow; - expect(states.at(-1)?.audible).toBe(true); + expect(guest.attach).toHaveBeenCalledTimes(1); - yield* manager.navigate("tab_audio_nav", "https://example.com/next"); + guest.chromiumDetach(); yield* Effect.yieldNow; - - expect(states.at(-1)?.audioMuted).toBe(true); - expect(states.at(-1)?.audible).toBe(true); - - guest.emitAudioState(false); yield* Effect.yieldNow; - expect(states.at(-1)?.audible).toBe(false); + expect(guest.attach).toHaveBeenCalledTimes(2); }), ), ); - effectIt.effect("blocks late webview and capture starts during tab close", () => + effectIt.effect("skips a guest destroyed while another guest's session opens", () => withManager((manager) => Effect.gen(function* () { - const capturePage = vi.fn(async () => ({ - toJPEG: () => Buffer.from("close-race-frame"), - getSize: () => ({ width: 1280, height: 720 }), - })); - const firstWebContents = makeTestPreviewWebContents(capturePage, 42); - const replacementWebContents = makeTestPreviewWebContents(capturePage, 43); - const replacementListenerSpies = replacementWebContents as unknown as { - readonly on: ReturnType; - readonly off: ReturnType; - readonly ipc: { readonly off: ReturnType }; - }; - fromId.mockImplementation((id) => { - if (id === 42) return firstWebContents; - if (id === 43) return replacementWebContents; - return null; - }); - const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; + const slow = makeAttachingGuest(46); + let releaseSlow = () => {}; + const slowCommand = new Promise((resolve) => { + releaseSlow = resolve; }); + slow.sendCommand.mockImplementation(() => slowCommand); + const queued = makeAttachingGuest(47); - yield* manager.createTab("tab_close_register_race"); - yield* manager.registerWebview("tab_close_register_race", 42); - yield* manager.openPictureInPicture("tab_close_register_race"); - - const closeCleanupPaused = yield* Deferred.make(); - const continueCloseCleanup = yield* Deferred.make(); - yield* manager.subscribeStateChanges((_tabId, state) => - !state.pictureInPicture && state.webContentsId === 42 - ? Deferred.succeed(closeCleanupPaused, undefined).pipe( - Effect.andThen(Deferred.await(continueCloseCleanup)), - ) - : Effect.void, - ); - - const closeFiber = yield* manager - .closeTab("tab_close_register_race") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(closeCleanupPaused); - const recreateFiber = yield* manager - .createTab("tab_close_register_race") + const slowFiber = yield* manager + .prepareWebview(slow.wc) .pipe(Effect.forkChild({ startImmediately: true })); - const registrationFiber = yield* manager - .registerWebview("tab_close_register_race", 43) + const queuedFiber = yield* manager + .prepareWebview(queued.wc) .pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.yieldNow; - expect(replacementListenerSpies.on).not.toHaveBeenCalled(); - yield* manager.closeTab("tab_close_register_race"); - const recordingExit = yield* Effect.exit(manager.startRecording("tab_close_register_race")); - yield* Deferred.succeed(continueCloseCleanup, undefined); - yield* Fiber.join(closeFiber); - const recreated = yield* Fiber.join(recreateFiber); - const registrationExit = yield* Fiber.await(registrationFiber); + queued.destroy(); + releaseSlow(); - for (const exit of [registrationExit, recordingExit] as ReadonlyArray< - Exit.Exit - >) { - expect(Exit.isFailure(exit)).toBe(true); - if (Exit.isSuccess(exit)) continue; - expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({ - _tag: "PreviewTabNotFoundError", - tabId: "tab_close_register_race", - }); - } - expect(replacementListenerSpies.on).not.toHaveBeenCalled(); - expect(replacementListenerSpies.off).not.toHaveBeenCalled(); - expect(replacementListenerSpies.ipc.off).not.toHaveBeenCalled(); - expect(capturePage).toHaveBeenCalledOnce(); - expect(recreated.webContentsId).toBeNull(); + expect(Exit.isSuccess(yield* Fiber.await(slowFiber))).toBe(true); + expect(Exit.isSuccess(yield* Fiber.await(queuedFiber))).toBe(true); + expect(slow.attach).toHaveBeenCalledTimes(1); + expect(queued.attach).not.toHaveBeenCalled(); }), ), ); - effectIt.effect("keeps a main-frame load failure visible until a retry starts", () => + const makeAudioWebContents = (id: number) => { + const listeners = new Map void>(); + const setAudioMuted = vi.fn(); + let audible = false; + let audibleAfterFirstRead = false; + let audibleReads = 0; + return { + setAudioMuted, + emitAudioState: (next: boolean) => { + audible = next; + listeners.get("audio-state-changed")?.({ audible: next } as never); + }, + /** Simulate playback starting during attach before the tab owns the guest and can receive its events. */ + startPlayingAfterFirstRead: () => { + audibleAfterFirstRead = true; + }, + wc: { + id, + isDestroyed: () => false, + isDevToolsOpened: () => false, + getType: () => "webview", + getURL: () => "https://example.com", + getTitle: () => "Example", + isLoadingMainFrame: () => false, + getZoomFactor: () => 1, + setZoomFactor: vi.fn(), + setAudioMuted, + isCurrentlyAudible: () => { + audibleReads += 1; + if (audibleAfterFirstRead && audibleReads > 1) return true; + return audible; + }, + loadURL: vi.fn(async () => undefined), + on: vi.fn((event: string, listener: (...args: never[]) => void) => { + listeners.set(event, listener); + }), + off: vi.fn((event: string) => { + listeners.delete(event); + }), + ipc: { on: vi.fn(), off: vi.fn() }, + send: webviewSend, + navigationHistory: { canGoBack: () => false, canGoForward: () => false }, + setIgnoreMenuShortcuts: vi.fn(), + setWindowOpenHandler: vi.fn(), + debugger: { + isAttached: () => false, + attach: vi.fn(), + sendCommand: vi.fn(async () => undefined), + on: vi.fn(), + off: vi.fn(), + }, + } as never, + }; + }; + + effectIt.effect("reconciles audibility that changed while the guest attached", () => withManager((manager) => Effect.gen(function* () { - const url = "http://localhost:5733/"; - let loading = false; - const listeners = new Map void>(); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => url, - getTitle: () => "localhost:5733", - isLoadingMainFrame: () => loading, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn((event: string, listener: (...args: unknown[]) => void) => { - listeners.set(event, listener); - }), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - const statuses: PreviewManager.PreviewNavStatus[] = []; + const guest = makeAudioWebContents(42); + guest.startPlayingAfterFirstRead(); + fromId.mockReturnValue(guest.wc); + const states: PreviewManager.PreviewTabState[] = []; yield* manager.subscribeStateChanges((_tabId, state) => Effect.sync(() => { - statuses.push(state.navStatus); + states.push(state); }), ); - yield* manager.createTab("tab_failed"); - yield* manager.registerWebview("tab_failed", 42); - - listeners.get("did-fail-load")?.( - {}, - -105, - "ERR_NAME_NOT_RESOLVED", - "https://missing-frame.example/", - false, - ); - yield* Effect.yieldNow; - expect(statuses.at(-1)?.kind).toBe("Success"); - - loading = true; - listeners.get("did-start-loading")?.(); - yield* Effect.yieldNow; - expect(statuses.at(-1)?.kind).toBe("Loading"); - - loading = false; - listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true); - listeners.get("did-stop-loading")?.(); - listeners.get("page-title-updated")?.(); - yield* Effect.yieldNow; - expect(statuses.at(-1)).toEqual({ - kind: "LoadFailed", - url, - title: "localhost:5733", - code: -102, - description: "ERR_CONNECTION_REFUSED", - }); - - loading = true; - listeners.get("did-start-loading")?.(); - yield* Effect.yieldNow; - expect(statuses.at(-1)?.kind).toBe("Loading"); - - loading = false; - listeners.get("did-stop-loading")?.(); - yield* Effect.yieldNow; - expect(statuses.at(-1)?.kind).toBe("Success"); - - listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true); - yield* Effect.yieldNow; - expect(statuses.at(-1)?.kind).toBe("LoadFailed"); - - listeners.get("did-navigate")?.(); + yield* manager.createTab("tab_audio_window"); + yield* manager.registerWebview("tab_audio_window", 42); yield* Effect.yieldNow; - expect(statuses.at(-1)?.kind).toBe("Success"); - }), - ), - ); - - effectIt.effect("ignores a late cross-origin iframe load once the page has loaded", () => - withManager((manager) => - Effect.gen(function* () { - const preview = makeFaviconWebContents(); - Object.assign(preview.webContents, { isLoading: () => true }); - fromId.mockReturnValue(preview.webContents); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => void states.push(state)), - ); - yield* manager.createTab("tab_iframe"); - yield* manager.registerWebview("tab_iframe", 42); - preview.listeners.get("did-start-loading")?.(); - preview.listeners.get("did-stop-loading")?.(); - yield* settle(() => states.length > 2); - expect(states.at(-1)?.navStatus.kind).toBe("Success"); + expect(states.at(-1)?.audible).toBe(true); }), ), ); - effectIt.effect("captures a PNG screenshot into browser artifacts", () => + effectIt.effect("ignores audio state from a replaced guest", () => withManager((manager) => Effect.gen(function* () { - const png = Buffer.from("preview-png"); - const capturePage = vi.fn(async () => ({ toPNG: () => png })); - const listeners = new Map void>(); - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com:8443/path?query=value", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn((event: string, listener: (...args: never[]) => void) => { - listeners.set(event, listener); - }), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - capturePage, - } as never); - - yield* manager.createTab("tab_1"); - yield* manager.registerWebview("tab_1", 42); + const first = makeAudioWebContents(42); + fromId.mockReturnValue(first.wc); + const states: PreviewManager.PreviewTabState[] = []; - expect(webviewSend).toHaveBeenCalledWith( - "preview:annotation-theme", - expect.objectContaining({ - colorScheme: "light", - primary: "oklch(0.488 0.217 264)", + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + states.push(state); }), ); + yield* manager.createTab("tab_audio_stale"); + yield* manager.registerWebview("tab_audio_stale", 42); + yield* Effect.yieldNow; - const artifact = yield* manager.captureScreenshot("tab_1"); + const replacement = makeAudioWebContents(43); + fromId.mockReturnValue(replacement.wc); + yield* manager.registerWebview("tab_audio_stale", 43); + yield* Effect.yieldNow; - expect(capturePage).toHaveBeenCalledOnce(); - expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts"); - expect(writeFile).toHaveBeenCalledWith(artifact.path, png); - expect(artifact).toMatchObject({ - tabId: "tab_1", - mimeType: "image/png", - sizeBytes: png.byteLength, + const publishedBefore = states.length; + first.emitAudioState(true); + yield* Effect.yieldNow; + + expect(states.length).toBe(publishedBefore); + expect(states.at(-1)?.audible).toBe(false); + }), + ), + ); + + effectIt.effect("blocks late webview and capture starts during tab close", () => + withManager((manager) => + Effect.gen(function* () { + const capturePage = vi.fn(async () => ({ + toJPEG: () => Buffer.from("close-race-frame"), + getSize: () => ({ width: 1280, height: 720 }), + })); + const firstWebContents = makeTestPreviewWebContents(capturePage, 42); + const replacementWebContents = makeTestPreviewWebContents(capturePage, 43); + const replacementListenerSpies = replacementWebContents as unknown as { + readonly on: ReturnType; + readonly off: ReturnType; + readonly ipc: { readonly off: ReturnType }; + }; + fromId.mockImplementation((id) => { + if (id === 42) return firstWebContents; + if (id === 43) return replacementWebContents; + return null; + }); + const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); + browserWindowConstructor.mockImplementation(function () { + return pictureInPictureWindow; }); - expect(artifact.path).toMatch( - /\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/, - ); - // Chromium reports UnknownVizError while a hidden guest warms its - // first compositor frame, so transient failures are retried. - capturePage.mockClear(); - capturePage.mockRejectedValueOnce(new Error("UnknownVizError")); - capturePage.mockRejectedValueOnce(new Error("UnknownVizError")); - const retriedFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe( - Effect.forkChild({ startImmediately: true }), - ); - yield* TestClock.adjust(1_000); - const retriedExit = yield* Fiber.join(retriedFiber); - expect(Exit.isSuccess(retriedExit)).toBe(true); - expect(capturePage).toHaveBeenCalledTimes(3); - - capturePage.mockClear(); - const captureCause = new Error("capture failed"); - capturePage.mockRejectedValue(captureCause); - const failingFiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe( - Effect.forkChild({ startImmediately: true }), + yield* manager.createTab("tab_close_register_race"); + yield* manager.registerWebview("tab_close_register_race", 42); + yield* manager.openPictureInPicture("tab_close_register_race"); + + const closeCleanupPaused = yield* Deferred.make(); + const continueCloseCleanup = yield* Deferred.make(); + yield* manager.subscribeStateChanges((_tabId, state) => + !state.pictureInPicture && state.webContentsId === 42 + ? Deferred.succeed(closeCleanupPaused, undefined).pipe( + Effect.andThen(Deferred.await(continueCloseCleanup)), + ) + : Effect.void, ); - yield* TestClock.adjust(1_000); - const exit = yield* Fiber.join(failingFiber); - expect(Exit.isFailure(exit)).toBe(true); - expect(capturePage).toHaveBeenCalledTimes(3); - if (Exit.isSuccess(exit)) return; - const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); - expect(error).toMatchObject({ - _tag: "PreviewOperationError", - operation: "captureScreenshot.capturePage", - tabId: "tab_1", - webContentsId: 42, - cause: captureCause, - }); + + const closeFiber = yield* manager + .closeTab("tab_close_register_race") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(closeCleanupPaused); + const recreateFiber = yield* manager + .createTab("tab_close_register_race") + .pipe(Effect.forkChild({ startImmediately: true })); + const registrationFiber = yield* manager + .registerWebview("tab_close_register_race", 43) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + expect(replacementListenerSpies.on).not.toHaveBeenCalled(); + yield* manager.closeTab("tab_close_register_race"); + const recordingExit = yield* Effect.exit(manager.startRecording("tab_close_register_race")); + yield* Deferred.succeed(continueCloseCleanup, undefined); + yield* Fiber.join(closeFiber); + const recreated = yield* Fiber.join(recreateFiber); + const registrationExit = yield* Fiber.await(registrationFiber); + + for (const exit of [registrationExit, recordingExit] as ReadonlyArray< + Exit.Exit + >) { + expect(Exit.isFailure(exit)).toBe(true); + if (Exit.isSuccess(exit)) continue; + expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({ + _tag: "PreviewTabNotFoundError", + tabId: "tab_close_register_race", + }); + } + expect(replacementListenerSpies.on).not.toHaveBeenCalled(); + expect(replacementListenerSpies.off).not.toHaveBeenCalled(); + expect(replacementListenerSpies.ipc.off).not.toHaveBeenCalled(); + expect(capturePage).toHaveBeenCalledOnce(); + expect(recreated.webContentsId).toBeNull(); }), ), ); @@ -2571,7 +1347,6 @@ describe("PreviewManager", () => { fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); yield* manager.createTab("tab_1"); yield* manager.registerWebview("tab_1", 42); - // it.effect keeps TestClock fixed until explicitly advanced. const first = yield* manager.captureScreenshot("tab_1"); const second = yield* manager.captureScreenshot("tab_1"); @@ -2685,75 +1460,73 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("rolls back window throttling when a recorded guest cannot be unthrottled", () => + effectIt.effect("keeps frame capture closed when a replacement is destroyed during cleanup", () => withManager((manager) => Effect.gen(function* () { - const setWindowBackgroundThrottling = vi.fn(); + const windowEvents = new Map void>(); + const host = makeTestHostWebContents(); const capturePage = vi.fn(async () => ({ toJPEG: () => Buffer.from("recording-frame"), getSize: () => ({ width: 1280, height: 720 }), })); - const wc = makeTestPreviewWebContents(capturePage); - fromId.mockReturnValue(wc); - - yield* manager.createTab("tab_guest_throttling_failure"); - yield* manager.registerWebview("tab_guest_throttling_failure", 42); + const guest = makeTestPreviewWebContents(capturePage, 42, host); + fromId.mockReturnValue(guest); + yield* manager.createTab("tab_shutdown"); + yield* manager.registerWebview("tab_shutdown", 42); yield* manager.setMainWindow({ isDestroyed: () => false, - once: vi.fn(), - webContents: { setBackgroundThrottling: setWindowBackgroundThrottling }, + once: (event: string, listener: () => void) => windowEvents.set(event, listener), + webContents: { setBackgroundThrottling: vi.fn() }, } as never); - - wc.setBackgroundThrottling.mockImplementationOnce(() => { - throw new Error("guest throttling update failed"); + yield* manager.startRecording("tab_shutdown"); + const pip = makeTestPictureInPictureWindow(); + browserWindowConstructor.mockImplementation(function () { + return pip.pictureInPictureWindow; }); - const failedStart = yield* Effect.exit( - manager.startRecording("tab_guest_throttling_failure"), + yield* manager.openPictureInPicture("tab_shutdown"); + const capturesBeforeClose = capturePage.mock.calls.length; + const cleanupStarted = yield* Deferred.make(); + const releaseCleanup = yield* Deferred.make(); + yield* manager.subscribeStateChanges((_tabId, state) => + state.pictureInPicture + ? Effect.void + : Deferred.succeed(cleanupStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseCleanup)), + ), ); - expect(Exit.isFailure(failedStart)).toBe(true); - expect(setWindowBackgroundThrottling.mock.calls).toEqual([[false], [true]]); - expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false]]); - - yield* manager.startRecording("tab_guest_throttling_failure"); - yield* manager.stopRecording("tab_guest_throttling_failure"); - expect(setWindowBackgroundThrottling.mock.calls).toEqual([ - [false], - [true], - [false], - [true], - ]); - expect(wc.setBackgroundThrottling.mock.calls).toEqual([[false], [false], [true]]); - }), - ), - ); - - effectIt.effect("does not publish a replacement window when capture reconciliation fails", () => - withManager((manager) => - Effect.gen(function* () { - const setBackgroundThrottling = vi.fn(() => { - throw new Error("replacement throttling update failed"); - }); - const capturePage = vi.fn(async () => ({ - toJPEG: () => Buffer.from("recording-frame"), - getSize: () => ({ width: 1280, height: 720 }), - })); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - yield* manager.createTab("tab_capture_replacement_failure"); - yield* manager.registerWebview("tab_capture_replacement_failure", 42); - yield* manager.startRecording("tab_capture_replacement_failure"); - - const failedReplacement = yield* Effect.exit( - manager.setMainWindow({ - isDestroyed: () => false, + windowEvents.get("closed")!(); + yield* Deferred.await(cleanupStarted); + let destroyed = false; + const replacement = yield* manager + .setMainWindow({ + isDestroyed: () => destroyed, once: vi.fn(), - webContents: { setBackgroundThrottling }, - } as never), - ); - expect(Exit.isFailure(failedReplacement)).toBe(true); + webContents: { setBackgroundThrottling: vi.fn() }, + } as never) + .pipe(Effect.forkChild({ startImmediately: true })); + try { + expect(replacement.pollUnsafe()).toBeUndefined(); + destroyed = true; + } finally { + yield* Deferred.succeed(releaseCleanup, undefined); + } + yield* Fiber.join(replacement); - yield* manager.stopRecording("tab_capture_replacement_failure"); - expect(setBackgroundThrottling.mock.calls).toEqual([[false]]); + const restart = yield* Effect.exit(manager.startRecording("tab_shutdown")); + expect(Exit.isFailure(restart)).toBe(true); + if (Exit.isFailure(restart)) { + expect(Option.getOrThrow(Cause.findErrorOption(restart.cause))).toMatchObject({ + _tag: "PreviewMainWindowClosedError", + tabId: "tab_shutdown", + }); + } + expect(capturePage).toHaveBeenCalledTimes(capturesBeforeClose); + expect(pip.pictureInPictureWindow.isDestroyed()).toBe(true); + expect(guest.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + const grants: Array<{ video?: unknown }> = []; + host.displayMediaHandler()?.({ frame: host.mainFrame }, (value) => grants.push(value)); + expect(grants).toEqual([{}]); }), ), ); @@ -2939,36 +1712,6 @@ describe("PreviewManager", () => { }).pipe(Effect.provide(managerLayer()), Effect.scoped), ); - effectIt.effect("stops capture retries when the tab swaps during the retry delay", () => - withManager((manager) => - Effect.gen(function* () { - const capturePage = vi.fn(async () => ({ - toPNG: () => Buffer.from("png"), - toJPEG: () => Buffer.from("jpeg"), - getSize: () => ({ width: 100, height: 80 }), - })); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 42)); - yield* manager.createTab("tab_1"); - yield* manager.registerWebview("tab_1", 42); - - capturePage.mockRejectedValueOnce(new Error("UnknownVizError")); - const fiber = yield* Effect.exit(manager.captureScreenshot("tab_1")).pipe( - Effect.forkChild({ startImmediately: true }), - ); - yield* TestClock.adjust(60); - expect(capturePage).toHaveBeenCalledTimes(1); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage, 43)); - yield* manager.registerWebview("tab_1", 43); - yield* TestClock.adjust(1_000); - const exit = yield* Fiber.join(fiber); - - expect(Exit.isFailure(exit)).toBe(true); - expect(capturePage).toHaveBeenCalledTimes(1); - expect(writeFile).not.toHaveBeenCalled(); - }), - ), - ); - effectIt.effect("discards a screenshot that resolves after its guest is replaced", () => withManager((manager) => Effect.gen(function* () { @@ -3097,95 +1840,6 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("requests display media with a fresh renderer gesture", () => - withManager((manager) => - Effect.gen(function* () { - const { host, takeGrant } = yield* setupRecordingRaceTabs(manager); - - yield* manager.startRecording("tab_race_a"); - - expect(host.executeJavaScript).toHaveBeenCalledWith( - expect.stringContaining(DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER), - true, - ); - expect(host.executeJavaScript).toHaveBeenCalledWith( - expect.stringContaining("tab_race_a"), - true, - ); - takeGrant(); - yield* manager.stopRecording("tab_race_a"); - }), - ), - ); - - effectIt.live("settles both starts when two tabs race for the capture stream", () => - withManager((manager) => - Effect.gen(function* () { - const { host, grants, takeGrant } = yield* setupRecordingRaceTabs(manager); - - const exits = yield* Effect.all( - [ - Effect.exit(manager.startRecording("tab_race_a")), - Effect.exit(manager.startRecording("tab_race_b")), - ], - { concurrency: 2 }, - ); - - const [exitA, exitB] = exits; - expect(exits.filter(Exit.isSuccess)).toHaveLength(1); - const loserExit = Exit.isSuccess(exitA) ? exitB : exitA; - if (Exit.isSuccess(loserExit)) return; - expect(Option.getOrThrow(Cause.findErrorOption(loserExit.cause))).toMatchObject({ - _tag: "PreviewRecordingArmConflictError", - }); - - takeGrant(); - expect(grants).toEqual([{ video: { routingId: Exit.isSuccess(exitA) ? 41 : 42 } }]); - expect(host.session.setDisplayMediaRequestHandler).toHaveBeenCalledOnce(); - }), - ), - ); - - effectIt.effect("releases an armed slot that the renderer never redeemed", () => - withManager((manager) => - Effect.gen(function* () { - const { grants, takeGrant } = yield* setupRecordingRaceTabs(manager); - - yield* manager.startRecording("tab_race_a"); - const blocked = yield* Effect.exit(manager.startRecording("tab_race_b")); - if (Exit.isSuccess(blocked)) throw new Error("expected the second tab to be refused"); - expect(Option.getOrThrow(Cause.findErrorOption(blocked.cause))).toMatchObject({ - _tag: "PreviewRecordingArmConflictError", - tabId: "tab_race_b", - armedTabId: "tab_race_a", - }); - - yield* TestClock.adjust(10_000); - yield* manager.startRecording("tab_race_b"); - takeGrant(); - expect(grants).toEqual([{ video: { routingId: 42 } }]); - - yield* manager.stopRecording("tab_race_a"); - yield* manager.stopRecording("tab_race_b"); - }), - ), - ); - - effectIt.effect("denies a display-media request that arrives after the arm went stale", () => - withManager((manager) => - Effect.gen(function* () { - const { grants, takeGrant } = yield* setupRecordingRaceTabs(manager); - - yield* manager.startRecording("tab_race_a"); - yield* TestClock.adjust(10_000); - takeGrant(); - expect(grants).toEqual([{}]); - - yield* manager.stopRecording("tab_race_a"); - }), - ), - ); - effectIt.effect("only lets the host frame that armed a recording claim its stream", () => withManager((manager) => Effect.gen(function* () { @@ -3210,96 +1864,9 @@ describe("PreviewManager", () => { destroy(41); yield* manager.startRecording("tab_race_b"); takeGrant(); - expect(grants).toEqual([{ video: { routingId: 42 } }]); - - yield* manager.stopRecording("tab_race_b"); - }), - ), - ); - - effectIt.effect( - "restores the native cursor when recording startup fails, then allows a retry", - () => - withManager((manager) => - Effect.gen(function* () { - const host = makeTestHostWebContents(); - host.executeJavaScript.mockResolvedValueOnce(false); - let cursorActive = false; - const cursorAtCapture: boolean[] = []; - const contents = Object.assign( - makeTestPreviewWebContents( - async () => { - cursorAtCapture.push(cursorActive); - return { - toJPEG: () => Buffer.from("frame"), - getSize: () => ({ width: 800, height: 600 }), - }; - }, - 42, - host, - ), - { - send: (channel: string, active: unknown) => { - if (channel === "preview:recording-cursor") cursorActive = active === true; - }, - }, - ); - fromId.mockReturnValue(contents as never); - yield* manager.createTab("tab_cursor"); - yield* manager.registerWebview("tab_cursor", 42); - const failed = yield* Effect.exit(manager.startRecording("tab_cursor")); - expect(Exit.isFailure(failed)).toBe(true); - expect(cursorAtCapture).toEqual([true]); - expect(cursorActive).toBe(false); - - yield* manager.startRecording("tab_cursor"); - expect(cursorAtCapture).toEqual([true, true]); - expect(cursorActive).toBe(true); - yield* manager.stopRecording("tab_cursor"); - expect(cursorActive).toBe(false); - }), - ), - ); - - effectIt.effect("restores the recording cursor after navigation only while recording", () => - withManager((manager) => - Effect.gen(function* () { - const listeners = new Map void>(); - let cursorActive = false; - let cursorUpdated: (() => void) | undefined; - let inputOptions: unknown; - const options = { showKeyPresses: true, showMousePresses: false }; - const contents = Object.assign( - makeTestPreviewWebContents(async () => ({ - toJPEG: () => Buffer.from("frame"), - getSize: () => ({ width: 800, height: 600 }), - })), - { - on: (event: string, listener: () => void) => listeners.set(event, listener), - send: (channel: string, active: unknown, recordingOptions: unknown) => { - if (channel !== "preview:recording-cursor") return; - cursorActive = active === true; - inputOptions = recordingOptions; - cursorUpdated?.(); - }, - }, - ); - fromId.mockReturnValue(contents as never); - yield* manager.createTab("tab_cursor_reload"); - yield* manager.registerWebview("tab_cursor_reload", 42); - yield* manager.startRecording("tab_cursor_reload", options); - for (const recording of [true, false]) { - if (!recording) yield* manager.stopRecording("tab_cursor_reload"); - cursorActive = false; - const restored = new Promise((resolve) => { - cursorUpdated = resolve; - }); - listeners.get("dom-ready")?.(); - yield* Effect.promise(() => restored); - cursorUpdated = undefined; - expect(cursorActive).toBe(recording); - expect(inputOptions).toEqual(recording ? options : undefined); - } + expect(grants).toEqual([{ video: { routingId: 42 } }]); + + yield* manager.stopRecording("tab_race_b"); }), ), ); @@ -3375,85 +1942,6 @@ describe("PreviewManager", () => { ), ); - effectIt.effect( - "releases queued STOP after stalled recording warmups and ignores late completion", - () => - withManager((manager) => - Effect.gen(function* () { - const warmupStarted = Promise.withResolvers(); - const firstWarmup = Promise.withResolvers(); - const lateWarmup = Promise.withResolvers(); - const capturePage = vi - .fn<() => Promise>() - .mockImplementationOnce(() => { - warmupStarted.resolve(); - return firstWarmup.promise; - }) - .mockImplementation(() => lateWarmup.promise); - const host = makeTestHostWebContents(); - const webContents = makeTestPreviewWebContents(capturePage, 42, host); - const windowThrottling = vi.fn(); - fromId.mockReturnValue(webContents); - yield* manager.createTab("tab_recording_stalled_warmup"); - yield* manager.registerWebview("tab_recording_stalled_warmup", 42); - yield* manager.setMainWindow({ - isDestroyed: () => false, - once: vi.fn(), - webContents: { setBackgroundThrottling: windowThrottling }, - } as never); - - const image = { - toJPEG: () => Buffer.from("late-recording-frame"), - getSize: () => ({ width: 1280, height: 720 }), - }; - try { - const start = yield* manager - .startRecording("tab_recording_stalled_warmup") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.promise(() => warmupStarted.promise); - let stopped = false; - const stop = yield* manager.stopRecording("tab_recording_stalled_warmup").pipe( - Effect.andThen( - Effect.sync(() => { - stopped = true; - }), - ), - Effect.forkChild({ startImmediately: true }), - ); - expect(webContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); - expect(windowThrottling.mock.calls).toEqual([[false]]); - yield* TestClock.adjust(1_000); - expect(stopped).toBe(false); - expect(host.executeJavaScript).not.toHaveBeenCalled(); - yield* TestClock.adjust(1_000); - expect(stopped).toBe(true); - yield* Fiber.join(start); - yield* Fiber.join(stop); - expect(capturePage).toHaveBeenCalledTimes(2); - expect(host.executeJavaScript).toHaveBeenCalledOnce(); - expect(webContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); - expect(windowThrottling.mock.calls).toEqual([[false], [true]]); - expect(webviewSend).toHaveBeenLastCalledWith("preview:recording-cursor", false); - - lateWarmup.resolve(image); - yield* TestClock.adjust(0); - const streams: Array<{ video?: unknown }> = []; - host.displayMediaHandler()?.({ frame: host.mainFrame }, (value) => streams.push(value)); - expect(streams).toEqual([{}]); - expect(capturePage).toHaveBeenCalledTimes(2); - expect(host.executeJavaScript).toHaveBeenCalledOnce(); - expect(webContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); - expect(windowThrottling.mock.calls).toEqual([[false], [true]]); - expect(webviewSend).toHaveBeenLastCalledWith("preview:recording-cursor", false); - } finally { - // Release stalled native calls after a failing assertion against unchanged base. - firstWarmup.resolve(image); - lateWarmup.resolve(image); - } - }), - ), - ); - effectIt.effect("continues native recording when the source warmup fails", () => withManager((manager) => Effect.gen(function* () { @@ -3505,428 +1993,41 @@ describe("PreviewManager", () => { }), ) .mockResolvedValue(capturedImage); - const initialWebContents = makeTestPreviewWebContents(capturePage, 42); - const replacementOn = vi.fn(); - const replacementWebContents = Object.assign(makeTestPreviewWebContents(capturePage, 43), { - on: replacementOn, - }); - fromId.mockImplementation((id) => { - if (id === 42) return initialWebContents; - if (id === 43) return replacementWebContents; - return null; - }); - - yield* manager.createTab("tab_recording_replacement_race"); - yield* manager.registerWebview("tab_recording_replacement_race", 42); - const start = yield* manager - .startRecording("tab_recording_replacement_race") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.promise(() => warmupStarted); - const replacement = yield* manager - .registerWebview("tab_recording_replacement_race", 43) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.yieldNow; - expect(replacementOn).not.toHaveBeenCalled(); - - finishWarmup(capturedImage); - yield* Fiber.join(start); - yield* Fiber.join(replacement); - expect(replacementOn).toHaveBeenCalled(); - expect(initialWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); - expect(replacementWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); - yield* manager.stopRecording("tab_recording_replacement_race"); - expect(initialWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); - expect(replacementWebContents.setBackgroundThrottling.mock.calls).toEqual([ - [false], - [true], - ]); - }), - ), - ); - - effectIt.effect("shares background frame capture between recording and picture-in-picture", () => - withManager((manager) => - Effect.gen(function* () { - const setBackgroundThrottling = vi.fn(); - const mainWindowWebContents = Object.assign(makeTestHostWebContents(), { - setBackgroundThrottling, - }); - const jpeg = Buffer.from("shared-preview-frame"); - const capturePage = vi.fn(async () => ({ - toJPEG: () => jpeg, - toBitmap: () => jpeg, - getSize: () => ({ width: 1280, height: 720 }), - })); - fromId.mockReturnValue({ - id: 42, - mainFrame: { routingId: 42 }, - hostWebContents: mainWindowWebContents, - executeJavaScript: vi.fn(async () => ({ width: 1280, height: 720 })), - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - setBackgroundThrottling: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - capturePage, - } as never); - - const pictureInPictureListeners = new Map void>(); - const pictureInPictureSend = vi.fn(); - const pictureInPictureWindow = { - isDestroyed: vi.fn(() => false), - once: vi.fn((event: string, listener: () => void) => { - pictureInPictureListeners.set(event, listener); - }), - setAlwaysOnTop: vi.fn(), - setVisibleOnAllWorkspaces: vi.fn(), - setAspectRatio: vi.fn(), - getContentSize: vi.fn(() => [480, 320] as [number, number]), - setContentSize: vi.fn(), - loadURL: vi.fn(async () => undefined), - showInactive: vi.fn(), - close: vi.fn(() => { - pictureInPictureListeners.get("closed")?.(); - }), - webContents: { - on: vi.fn(), - off: vi.fn(), - send: pictureInPictureSend, - }, - }; - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; - }); - const states: PreviewManager.PreviewTabState[] = []; - const recordingFrames: DesktopPreviewRecordingFrame[] = []; - - yield* manager.setMainWindow({ - isDestroyed: () => false, - once: vi.fn(), - webContents: mainWindowWebContents, - } as never); - - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - yield* manager.subscribeRecordingFrames((frame) => - Effect.sync(() => { - recordingFrames.push(frame); - }), - ); - yield* manager.createTab("tab_pip"); - yield* manager.registerWebview("tab_pip", 42); - yield* manager.openPictureInPicture("tab_pip"); - - expect(setBackgroundThrottling.mock.calls).toEqual([[false]]); - expect(browserWindowConstructor).toHaveBeenCalledWith( - expect.objectContaining({ - alwaysOnTop: true, - show: false, - skipTaskbar: true, - webPreferences: expect.objectContaining({ - preload: "/tmp/t3/desktop/preview-pip-preload.cjs", - backgroundThrottling: false, - }), - }), - ); - expect(pictureInPictureWindow.showInactive).toHaveBeenCalledOnce(); - expect(pictureInPictureWindow.setVisibleOnAllWorkspaces).toHaveBeenCalledWith(true, { - visibleOnFullScreen: true, - skipTransformProcessType: true, - }); - expect(pictureInPictureWindow.setAspectRatio.mock.calls).toEqual([[0], [1280 / 720]]); - expect(pictureInPictureWindow.setContentSize).toHaveBeenCalledWith(523, 294, false); - expect(pictureInPictureWindow.setAspectRatio.mock.invocationCallOrder[0]).toBeLessThan( - pictureInPictureWindow.setContentSize.mock.invocationCallOrder[0] ?? 0, - ); - expect(pictureInPictureWindow.setContentSize.mock.invocationCallOrder[0]).toBeLessThan( - pictureInPictureWindow.setAspectRatio.mock.invocationCallOrder[1] ?? 0, - ); - expect(pictureInPictureSend).toHaveBeenCalledWith( - "desktop:preview-pip-frame", - expect.objectContaining({ - tabId: "tab_pip", - data: jpeg.toString("base64"), - width: 1280, - height: 720, - }), - ); - expect(states.at(-1)?.pictureInPicture).toBe(true); - expect(capturePage).toHaveBeenCalledOnce(); - const pictureInPictureFramesBeforeRecording = pictureInPictureSend.mock.calls.length; - - yield* manager.startRecording("tab_pip"); - expect(capturePage).toHaveBeenCalledTimes(2); - expect(recordingFrames).toHaveLength(0); - - yield* TestClock.adjust(100); - expect(capturePage).toHaveBeenCalledTimes(3); - expect(pictureInPictureSend).toHaveBeenCalledTimes(pictureInPictureFramesBeforeRecording); - expect(recordingFrames).toHaveLength(0); - - yield* manager.stopRecording("tab_pip"); - expect(setBackgroundThrottling.mock.calls).toEqual([[false]]); - const framesBeforePictureInPictureOnlyTick = pictureInPictureSend.mock.calls.length; - yield* TestClock.adjust(100); - expect(capturePage).toHaveBeenCalledTimes(4); - expect(pictureInPictureSend.mock.calls.length).toBe(framesBeforePictureInPictureOnlyTick); - expect(recordingFrames).toHaveLength(0); - - setBackgroundThrottling.mockImplementationOnce(() => { - throw new Error("picture-in-picture throttling restore failed"); - }); - yield* manager.closePictureInPicture("tab_pip"); - expect(setBackgroundThrottling.mock.calls).toEqual([[false], [true], [true]]); - expect(pictureInPictureWindow.close).toHaveBeenCalledOnce(); - expect(states.at(-1)?.pictureInPicture).toBe(false); - const capturesAfterClose = capturePage.mock.calls.length; - yield* TestClock.adjust(200); - expect(capturePage).toHaveBeenCalledTimes(capturesAfterClose); - }), - ), - ); - - effectIt.effect("keeps picture-in-picture capture separate from recording warmup", () => - withManager((manager) => - Effect.gen(function* () { - const jpeg = Buffer.from("shared-preview-frame"); - const capturePage = vi.fn(async () => ({ - toJPEG: () => jpeg, - toBitmap: () => jpeg, - getSize: () => ({ width: 1280, height: 720 }), - })); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow(); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; - }); - const recordingFrames: DesktopPreviewRecordingFrame[] = []; - - yield* manager.subscribeRecordingFrames((frame) => - Effect.sync(() => { - recordingFrames.push(frame); - }), - ); - yield* manager.createTab("tab_recording_then_pip"); - yield* manager.registerWebview("tab_recording_then_pip", 42); - yield* manager.startRecording("tab_recording_then_pip"); - - expect(recordingFrames).toHaveLength(0); - expect(capturePage).toHaveBeenCalledOnce(); - yield* manager.openPictureInPicture("tab_recording_then_pip"); - expect(capturePage).toHaveBeenCalledTimes(2); - expect(send).toHaveBeenCalledOnce(); - - yield* TestClock.adjust(100); - - expect(capturePage).toHaveBeenCalledTimes(3); - expect(recordingFrames).toHaveLength(0); - expect(send).toHaveBeenCalledOnce(); - yield* manager.closePictureInPicture("tab_recording_then_pip"); - yield* manager.stopRecording("tab_recording_then_pip"); - }), - ), - ); - - effectIt.effect("stops frame capture when the native picture-in-picture window closes", () => - withManager((manager) => - Effect.gen(function* () { - const capturePage = vi.fn(async () => ({ - toJPEG: () => Buffer.from("native-close-preview-frame"), - getSize: () => ({ width: 1280, height: 720 }), - })); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - const { pictureInPictureWindow } = makeTestPictureInPictureWindow(); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; - }); - const states: PreviewManager.PreviewTabState[] = []; - yield* manager.subscribeStateChanges((_tabId, state) => - Effect.sync(() => { - states.push(state); - }), - ); - - yield* manager.createTab("tab_native_pip_close"); - yield* manager.registerWebview("tab_native_pip_close", 42); - yield* manager.openPictureInPicture("tab_native_pip_close"); - - pictureInPictureWindow.close(); - yield* settle(() => states.at(-1)?.pictureInPicture === false); - - expect(states.at(-1)?.pictureInPicture).toBe(false); - const capturesAfterClose = capturePage.mock.calls.length; - yield* TestClock.adjust(200); - expect(capturePage).toHaveBeenCalledTimes(capturesAfterClose); - }), - ), - ); - - effectIt.effect("retries an unchanged picture-in-picture frame after delivery fails", () => - withManager((manager) => - Effect.gen(function* () { - const jpeg = Buffer.from("retry-preview-frame"); - const capturePage = vi.fn(async () => ({ - toJPEG: () => jpeg, - toBitmap: () => jpeg, - getSize: () => ({ width: 1280, height: 720 }), - })); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow(); - send.mockImplementationOnce(() => { - throw new Error("picture-in-picture delivery failed"); - }); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; - }); - - yield* manager.createTab("tab_pip_delivery_retry"); - yield* manager.registerWebview("tab_pip_delivery_retry", 42); - yield* manager.openPictureInPicture("tab_pip_delivery_retry"); - expect(send).toHaveBeenCalledOnce(); - - yield* TestClock.adjust(100); - - expect(capturePage).toHaveBeenCalledTimes(2); - expect(send).toHaveBeenCalledTimes(2); - yield* manager.closePictureInPicture("tab_pip_delivery_retry"); - }), - ), - ); - - effectIt.effect("replays an unchanged picture-in-picture frame after its renderer reloads", () => - withManager((manager) => - Effect.gen(function* () { - const jpeg = Buffer.from("reloaded-preview-frame"); - const capturePage = vi.fn(async () => ({ - toJPEG: () => jpeg, - toBitmap: () => jpeg, - getSize: () => ({ width: 1280, height: 720 }), - })); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - const { pictureInPictureWindow, send, webContentsListeners } = - makeTestPictureInPictureWindow(); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; - }); - - yield* manager.createTab("tab_pip_reload"); - yield* manager.registerWebview("tab_pip_reload", 42); - yield* manager.openPictureInPicture("tab_pip_reload"); - expect(send).toHaveBeenCalledOnce(); - - webContentsListeners.get("did-finish-load")?.(); - yield* TestClock.adjust(100); - - expect(send).toHaveBeenCalledTimes(2); - yield* manager.closePictureInPicture("tab_pip_reload"); - }), - ), - ); - - effectIt.effect("encodes a picture-in-picture frame only when the page changes", () => - withManager((manager) => - Effect.gen(function* () { - let page = "static-page"; - let pixelsReadable = true; - const toJPEG = vi.fn((pixels: string) => Buffer.from(`jpeg:${pixels}`)); - const capturePage = vi.fn(async () => { - const pixels = page; - return { - toJPEG: () => toJPEG(pixels), - toBitmap: () => (pixelsReadable ? Buffer.from(pixels) : Buffer.alloc(0)), - getSize: () => ({ width: 1280, height: 720 }), - }; - }); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow(); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; - }); - - yield* manager.createTab("tab_pip_unchanged"); - yield* manager.registerWebview("tab_pip_unchanged", 42); - yield* manager.openPictureInPicture("tab_pip_unchanged"); - yield* TestClock.adjust(100); - - expect(capturePage).toHaveBeenCalledTimes(2); - expect(toJPEG).toHaveBeenCalledOnce(); - expect(send).toHaveBeenCalledOnce(); - - page = "changed-page"; - yield* TestClock.adjust(100); - - expect(toJPEG).toHaveBeenCalledTimes(2); - expect(send).toHaveBeenCalledTimes(2); - expect(send).toHaveBeenLastCalledWith( - "desktop:preview-pip-frame", - expect.objectContaining({ data: Buffer.from("jpeg:changed-page").toString("base64") }), - ); - - // A frame whose pixels cannot be read has no fingerprint and is still delivered. - pixelsReadable = false; - yield* TestClock.adjust(100); - - expect(toJPEG).toHaveBeenCalledTimes(3); - expect(send).toHaveBeenCalledTimes(3); - yield* manager.closePictureInPicture("tab_pip_unchanged"); - }), - ), - ); - - effectIt.effect("drops empty frames before picture-in-picture delivery", () => - withManager((manager) => - Effect.gen(function* () { - const validImage: TestCapturedPreviewImage = { - toJPEG: () => Buffer.from("valid-preview-frame"), - toBitmap: () => Buffer.from("valid-preview-frame"), - getSize: () => ({ width: 1280, height: 720 }), - }; - const capturePage = vi.fn(async () => validImage); - capturePage.mockResolvedValueOnce({ - toJPEG: () => Buffer.from("empty-preview-frame"), - getSize: () => ({ width: 0, height: 0 }), + const initialWebContents = makeTestPreviewWebContents(capturePage, 42); + const replacementOn = vi.fn(); + const replacementWebContents = Object.assign(makeTestPreviewWebContents(capturePage, 43), { + on: replacementOn, }); - fromId.mockReturnValue(makeTestPreviewWebContents(capturePage)); - const { pictureInPictureWindow, send } = makeTestPictureInPictureWindow(); - browserWindowConstructor.mockImplementation(function () { - return pictureInPictureWindow; + fromId.mockImplementation((id) => { + if (id === 42) return initialWebContents; + if (id === 43) return replacementWebContents; + return null; }); - yield* manager.createTab("tab_empty_frame"); - yield* manager.registerWebview("tab_empty_frame", 42); - yield* manager.openPictureInPicture("tab_empty_frame"); - - expect(capturePage).toHaveBeenCalledOnce(); - expect(pictureInPictureWindow.setAspectRatio).not.toHaveBeenCalled(); - expect(send).not.toHaveBeenCalled(); - - yield* TestClock.adjust(100); + yield* manager.createTab("tab_recording_replacement_race"); + yield* manager.registerWebview("tab_recording_replacement_race", 42); + const start = yield* manager + .startRecording("tab_recording_replacement_race") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.promise(() => warmupStarted); + const replacement = yield* manager + .registerWebview("tab_recording_replacement_race", 43) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + expect(replacementOn).not.toHaveBeenCalled(); - expect(pictureInPictureWindow.setAspectRatio.mock.calls).toEqual([[0], [1280 / 720]]); - expect(send).toHaveBeenCalledOnce(); - yield* manager.closePictureInPicture("tab_empty_frame"); + finishWarmup(capturedImage); + yield* Fiber.join(start); + yield* Fiber.join(replacement); + expect(replacementOn).toHaveBeenCalled(); + expect(initialWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); + expect(replacementWebContents.setBackgroundThrottling.mock.calls).toEqual([[false]]); + yield* manager.stopRecording("tab_recording_replacement_race"); + expect(initialWebContents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); + expect(replacementWebContents.setBackgroundThrottling.mock.calls).toEqual([ + [false], + [true], + ]); }), ), ); @@ -4252,287 +2353,172 @@ describe("PreviewManager", () => { ), ); - effectIt.effect("settles the pick when the annotation screenshot never arrives", () => - withManager((manager) => - Effect.gen(function* () { - let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined; - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - isFocused: () => true, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - once: vi.fn(), - off: vi.fn(), - capturePage: vi.fn(() => new Promise(() => {})), - ipc: { - on: vi.fn((channel: string, listener: typeof onPicked) => { - if (channel === "preview:element-picked") onPicked = listener; + describe("annotation screenshots", () => { + const captureAnnotation = ( + cropRect: PreviewAnnotationRect | null, + targets: Partial> = {}, + emptyImage?: "viewport" | "crop", + ) => + withManager((manager) => + Effect.gen(function* () { + let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined; + const crop = vi.fn((rect: Electron.Rectangle) => ({ + isEmpty: () => emptyImage === "crop", + getSize: () => + emptyImage === "crop" + ? { width: 0, height: 0 } + : { width: rect.width, height: rect.height }, + toDataURL: () => (emptyImage === "crop" ? "data:," : "data:image/png;base64,cropped"), + })); + const capturePage = vi.fn(async () => ({ + isEmpty: () => emptyImage === "viewport", + getSize: () => + emptyImage === "viewport" ? { width: 0, height: 0 } : { width: 2000, height: 1200 }, + toJPEG: () => Buffer.from("unused"), + toDataURL: () => (emptyImage === "viewport" ? "data:," : "data:image/png;base64,full"), + crop, + })); + fromId.mockReturnValue( + Object.assign(makeTestPreviewWebContents(capturePage), { + isFocused: () => true, + once: vi.fn(), + ipc: { + on: vi.fn((channel: string, listener: typeof onPicked) => { + if (channel === "preview:element-picked") onPicked = listener; + }), + off: vi.fn(), + removeListener: vi.fn(), + }, }), - off: vi.fn(), - removeListener: vi.fn(), - }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - - yield* manager.createTab("tab_1"); - yield* manager.registerWebview("tab_1", 42); - const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); - yield* Effect.yieldNow; + ); - yield* manager.setAnnotationSendEnabled("tab_1", true); - onPicked?.( - {}, - { - id: "annotation_1", - pageUrl: "https://example.com", - pageTitle: "Example", - comment: "Tighten this spacing", - elements: [], - regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }], - strokes: [], - styleChanges: [], - screenshot: null, - createdAt: "2026-06-11T00:00:00.000Z", - }, - null, - "send", - ); - yield* Effect.yieldNow; - expect(pick.pollUnsafe()).toBeUndefined(); + yield* manager.createTab("tab_1"); + yield* manager.registerWebview("tab_1", 42); + const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); + yield* Effect.yieldNow; + onPicked?.( + {}, + { + id: "annotation_1", + pageUrl: "https://example.com", + pageTitle: "Example", + comment: "Tighten this spacing", + elements: [], + regions: [], + strokes: [], + ...targets, + styleChanges: [], + screenshot: null, + createdAt: "2026-06-11T00:00:00.000Z", + }, + cropRect, + "attach", + 2, + ); - yield* TestClock.adjust("6 seconds"); - const result = yield* Fiber.join(pick); - expect(result?.annotation.screenshot).toBeNull(); - expect(result?.screenshotFailed).toBe(true); - expect(result?.submission).toBe("send"); - expect(webviewSend).toHaveBeenCalledWith("preview:annotation-captured"); - }), - ), - ); + const result = yield* Fiber.join(pick); + expect(capturePage).toHaveBeenCalledExactlyOnceWith(); + expect(result?.annotation.comment).toBe("Tighten this spacing"); + expect(result?.submission).toBe("attach"); + return { result, crop }; + }), + ); - effectIt.effect("crops the picked area out of a full-page capture at device scale", () => - withManager((manager) => + effectIt.effect("clips a partially visible selection to the captured viewport", () => Effect.gen(function* () { - let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined; - const crop = vi.fn((rect: Electron.Rectangle) => ({ - getSize: () => ({ width: rect.width, height: rect.height }), - toDataURL: () => "data:image/png;base64,cropped", - })); - const capturePage = vi.fn(async () => ({ - getSize: () => ({ width: 2000, height: 1200 }), - crop, - })); - fromId.mockReturnValue( - Object.assign(makeTestPreviewWebContents(capturePage as never), { - isFocused: () => true, - once: vi.fn(), - ipc: { - on: vi.fn((channel: string, listener: typeof onPicked) => { - if (channel === "preview:element-picked") onPicked = listener; - }), - off: vi.fn(), - removeListener: vi.fn(), - }, - }), - ); - - yield* manager.createTab("tab_1"); - yield* manager.registerWebview("tab_1", 42); - const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); - yield* Effect.yieldNow; - onPicked?.( - {}, - { - id: "annotation_1", - pageUrl: "https://example.com", - pageTitle: "Example", - comment: "Tighten this spacing", - elements: [], - regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }], - strokes: [], - styleChanges: [], - screenshot: null, - createdAt: "2026-06-11T00:00:00.000Z", - }, - { x: 5, y: 6, width: 20, height: 30 }, - "attach", - 2, + const { result, crop } = yield* captureAnnotation( + { x: -40, y: 570, width: 240, height: 110 }, + { regions: [{ id: "region_1", rect: { x: -20, y: 590, width: 200, height: 70 } }] }, ); - - const result = yield* Fiber.join(pick); - expect(capturePage).toHaveBeenCalledWith(); - expect(crop).toHaveBeenCalledWith({ x: 10, y: 12, width: 40, height: 60 }); + expect(crop).toHaveBeenCalledExactlyOnceWith({ x: 0, y: 1140, width: 400, height: 60 }); expect(result?.screenshotFailed).toBeUndefined(); - expect(result?.annotation.screenshot).toEqual({ + expect(result?.annotation.screenshot).toMatchObject({ dataUrl: "data:image/png;base64,cropped", - width: 40, + width: 400, height: 60, - cropRect: { x: 5, y: 6, width: 20, height: 30 }, }); }), - ), - ); + ); - effectIt.effect("a stale capture from a replaced pick never touches the next pick", () => - withManager((manager) => + effectIt.effect.each([ + { + name: "an offscreen crop without individual target bounds", + cropRect: { x: 1010, y: 40, width: 100, height: 70 }, + regions: [], + }, + { + name: "padding overlapping the viewport while its target is offscreen", + cropRect: { x: 40, y: -100, width: 240, height: 110 }, + regions: [{ id: "region_1", rect: { x: 60, y: -80, width: 200, height: 70 } }], + }, + { + name: "a union spanning the viewport with both targets offscreen", + cropRect: { x: -230, y: 40, width: 1460, height: 110 }, + regions: [ + { id: "region_1", rect: { x: -210, y: 60, width: 200, height: 70 } }, + { id: "region_2", rect: { x: 1010, y: 60, width: 200, height: 70 } }, + ], + }, + { + name: "an offscreen target when crop bounds are missing", + cropRect: null, + regions: [{ id: "region_1", rect: { x: 60, y: -80, width: 200, height: 70 } }], + }, + ])("does not attach $name", ({ cropRect, regions }) => Effect.gen(function* () { - let onPicked: ((event: unknown, ...args: unknown[]) => void) | undefined; - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - isFocused: () => true, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - once: vi.fn(), - off: vi.fn(), - capturePage: vi.fn(() => new Promise(() => {})), - ipc: { - on: vi.fn((channel: string, listener: typeof onPicked) => { - if (channel === "preview:element-picked") onPicked = listener; - }), - off: vi.fn(), - removeListener: vi.fn(), - }, - send: webviewSend, - navigationHistory: { canGoBack: () => false, canGoForward: () => false }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - const annotation = { - id: "annotation_1", - pageUrl: "https://example.com", - pageTitle: "Example", - comment: "Tighten this spacing", - elements: [], - regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }], - strokes: [], - styleChanges: [], - screenshot: null, - createdAt: "2026-06-11T00:00:00.000Z", - }; - - yield* manager.createTab("tab_1"); - yield* manager.registerWebview("tab_1", 42); - const firstPick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); - yield* Effect.yieldNow; - onPicked?.({}, annotation, null, "send"); - yield* Effect.yieldNow; - - const secondPick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); - yield* Effect.yieldNow; - expect(yield* Fiber.join(firstPick)).toBeNull(); - webviewSend.mockClear(); - - yield* TestClock.adjust("6 seconds"); - yield* Effect.yieldNow; - expect(webviewSend).not.toHaveBeenCalledWith("preview:annotation-captured"); - expect(secondPick.pollUnsafe()).toBeUndefined(); - - onPicked?.({}, { ...annotation, id: "annotation_2" }, null, "attach"); - yield* TestClock.adjust("6 seconds"); - const result = yield* Fiber.join(secondPick); - expect(result?.annotation.id).toBe("annotation_2"); - expect(result?.submission).toBe("attach"); + const { result, crop } = yield* captureAnnotation(cropRect, { regions }); + expect(crop).not.toHaveBeenCalled(); + expect(result?.annotation.screenshot).toBeNull(); + expect(result?.screenshotFailed).toBe(true); }), - ), - ); + ); - effectIt.effect("navigates the guest history when the thumb-button ipc fires", () => - withManager((manager) => + // regression: #18441 zero-area strokes on the viewport edge must still get a screenshot crop + effectIt.effect.each([ + { + name: "zero-width SVG line on the left edge", + rect: { x: 0, y: 60, width: 0, height: 70 }, + cropRect: { x: -20, y: 40, width: 40, height: 110 }, + expectedCrop: { x: 0, y: 80, width: 40, height: 220 }, + }, + { + name: "zero-height SVG line on the top edge", + rect: { x: 60, y: 0, width: 70, height: 0 }, + cropRect: { x: 40, y: -20, width: 110, height: 40 }, + expectedCrop: { x: 80, y: 0, width: 220, height: 40 }, + }, + ])("captures a stroked $name", ({ rect, cropRect, expectedCrop }) => Effect.gen(function* () { - let mouseNavigate: ((event: unknown, payload: unknown) => void) | undefined; - const goBack = vi.fn(); - const goForward = vi.fn(); - let canGoBack = true; - fromId.mockReturnValue({ - id: 42, - isDestroyed: () => false, - getType: () => "webview", - getURL: () => "https://example.com", - getTitle: () => "Example", - isLoadingMainFrame: () => false, - getZoomFactor: () => 1, - setZoomFactor: vi.fn(), - setAudioMuted: vi.fn(), - isCurrentlyAudible: () => false, - on: vi.fn(), - off: vi.fn(), - ipc: { - on: vi.fn((channel: string, listener: typeof mouseNavigate) => { - if (channel === "preview:mouse-navigate") mouseNavigate = listener; - }), - off: vi.fn(), - }, - send: webviewSend, - navigationHistory: { - canGoBack: () => canGoBack, - canGoForward: () => true, - goBack, - goForward, - }, - setIgnoreMenuShortcuts: vi.fn(), - setWindowOpenHandler: vi.fn(), - debugger: { - isAttached: () => false, - attach: vi.fn(), - sendCommand: vi.fn(async () => undefined), - on: vi.fn(), - off: vi.fn(), - }, - } as never); - - yield* manager.createTab("tab_nav"); - yield* manager.registerWebview("tab_nav", 42); - expect(mouseNavigate).toBeDefined(); - - mouseNavigate?.({}, { direction: "back" }); - yield* Effect.yieldNow; - expect(goBack).toHaveBeenCalledOnce(); - - mouseNavigate?.({}, { direction: "forward" }); - yield* Effect.yieldNow; - expect(goForward).toHaveBeenCalledOnce(); - - mouseNavigate?.({}, { direction: "sideways" }); - canGoBack = false; - mouseNavigate?.({}, { direction: "back" }); - yield* Effect.yieldNow; - expect(goBack).toHaveBeenCalledOnce(); + const { result, crop } = yield* captureAnnotation(cropRect, { + elements: [ + { + id: "element_1", + rect, + element: { + pageUrl: "https://example.com", + pageTitle: "Example", + tagName: "line", + selector: "svg > line", + htmlPreview: '', + componentName: null, + source: null, + stack: [], + styles: "stroke: black; stroke-width: 2px;", + pickedAt: "2026-06-11T00:00:00.000Z", + }, + }, + ], + }); + expect(crop).toHaveBeenCalledExactlyOnceWith(expectedCrop); + expect(result?.screenshotFailed).toBeUndefined(); + expect(result?.annotation.screenshot).toMatchObject({ + dataUrl: "data:image/png;base64,cropped", + width: expectedCrop.width, + height: expectedCrop.height, + }); }), - ), - ); + ); + }); effectIt.effect("reveals only files inside the configured browser artifact directory", () => withManager((manager) => @@ -4555,71 +2541,4 @@ describe("PreviewManager", () => { }), ), ); - - effectIt.effect("copies screenshot artifacts to the system clipboard", () => - withManager((manager) => - Effect.gen(function* () { - const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png"; - - yield* manager.copyArtifactToClipboard(artifactPath); - - expect(createFromPath).toHaveBeenCalledWith(artifactPath); - expect(clipboardItemConstructor).toHaveBeenCalledWith({ - "image/png": expect.any(Blob), - }); - expect(writeClipboard).toHaveBeenCalledOnce(); - const exit = yield* Effect.exit( - manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"), - ); - expect(Exit.isFailure(exit)).toBe(true); - if (Exit.isSuccess(exit)) return; - const error = Option.getOrThrow(Cause.findErrorOption(exit.cause)); - expect(error).toMatchObject({ - _tag: "PreviewArtifactPathOutsideDirectoryError", - artifactPath: "/tmp/t3/dev/settings.json", - artifactDirectory: "/tmp/t3/dev/browser-artifacts", - }); - expect("cause" in error).toBe(false); - - createFromPath.mockReturnValueOnce({ - isEmpty: () => true, - toPNG: () => Buffer.from("invalid"), - }); - const invalidImageExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath)); - expect(Exit.isFailure(invalidImageExit)).toBe(true); - if (Exit.isSuccess(invalidImageExit)) return; - expect(Option.getOrThrow(Cause.findErrorOption(invalidImageExit.cause))).toMatchObject({ - _tag: "PreviewArtifactImageLoadError", - artifactPath, - }); - - const writeCause = new Error("clipboard write failed"); - writeClipboard.mockRejectedValueOnce(writeCause); - const writeExit = yield* Effect.exit(manager.copyArtifactToClipboard(artifactPath)); - expect(Exit.isFailure(writeExit)).toBe(true); - if (Exit.isSuccess(writeExit)) return; - expect(Option.getOrThrow(Cause.findErrorOption(writeExit.cause))).toMatchObject({ - _tag: "PreviewOperationError", - operation: "copyArtifactToClipboard.write", - artifactPath, - cause: writeCause, - }); - }), - ), - ); -}); - -describe("PreviewOperationError", () => { - it("keeps timeline detail separate from its structured message", () => { - const cause = new Error("CDP command failed with an invalid node id"); - const error = new PreviewManager.PreviewOperationError({ - operation: "click.DOM.resolveNode", - tabId: "tab_1", - webContentsId: 42, - cause, - }); - - expect(error.message).not.toContain(cause.message); - expect(PreviewManager.PreviewOperationError.toTimelineMessage(error)).toBe(cause.message); - }); }); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 1890175c3a0c9..b9e0192ca8a7d 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -1,10 +1,3 @@ -/** - * Desktop side of the in-app browser preview. - * - * Hosts per-tab Chromium WebContents references (the actual - * elements live in the renderer; we only attach listeners and forward state - * here). Single layer-scoped browser session partition. - */ import * as NodeZlib from "node:zlib"; import { DesktopPreviewRecordingInputSchema, @@ -123,10 +116,7 @@ const ZOOM_EPSILON = 0.001; const RECORDING_ARM_GRACE_MS = 10_000; const PICTURE_IN_PICTURE_FRAME_INTERVAL_MS = Math.ceil(1_000 / 12); const PICTURE_IN_PICTURE_JPEG_QUALITY = 80; -/** - * Cold guests can reject capturePage with UnknownVizError or never settle it. - * Bound each attempt so snapshots release control even when Chromium stalls. - */ +// Cold guests can reject capturePage with UnknownVizError or stall; bound each attempt. const CAPTURE_PAGE_RETRY_ATTEMPTS = 3; const CAPTURE_PAGE_RETRY_DELAY_MS = 120; const CAPTURE_PAGE_ATTEMPT_TIMEOUT_MS = 1_000; @@ -206,7 +196,7 @@ export const fitPictureInPictureContentSize = ( return [Math.round(width), Math.round(height)]; }; -export const recordingFileExtension = (mimeType: string): string => { +const recordingFileExtension = (mimeType: string): string => { const subtype = mimeType.split(";", 1)[0]?.trim().toLowerCase().split("/")[1] ?? ""; const extension = subtype.replace(/^x-/, "").replace(/[^a-z0-9]/g, ""); return extension || "video"; @@ -270,24 +260,35 @@ const normalizeCaptureRect = (value: unknown): PreviewAnnotationRect | null => { ) { return null; } - return { - x: Math.max(0, Math.floor(x)), - y: Math.max(0, Math.floor(y)), - width: Math.max(1, Math.ceil(width)), - height: Math.max(1, Math.ceil(height)), - }; + return { x, y, width, height }; }; -/** - * Crops a full-page capture to a picked annotation. `cropRect` is in CSS px; - * the capture's pixels are CSS px × the guest's `devicePixelRatio`. - */ +// capturePage returns a 1x NativeImage containing device pixels, so crop() uses +// CSS coordinates scaled by the guest's devicePixelRatio (including page zoom). const cropAnnotationScreenshot = ( image: Electron.NativeImage, cropRect: PreviewAnnotationRect | null, devicePixelRatio: number, + targetRects: ReadonlyArray, ): PreviewAnnotationPayload["screenshot"] => { const full = image.getSize(); + if (full.width <= 0 || full.height <= 0) return null; + const scale = Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1; + // Padding or a union of offscreen targets can overlap an empty viewport area. + // A zero-width/height SVG line can still paint at the top or left edge. + if ( + targetRects.length > 0 && + !targetRects.some( + (rect) => + (rect.width > 0 || rect.height > 0) && + rect.x * scale < full.width && + rect.y * scale < full.height && + (rect.width === 0 ? rect.x >= 0 : rect.x + rect.width > 0) && + (rect.height === 0 ? rect.y >= 0 : rect.y + rect.height > 0), + ) + ) { + return null; + } if (!cropRect) { return { dataUrl: image.toDataURL(), @@ -296,35 +297,30 @@ const cropAnnotationScreenshot = ( cropRect: { x: 0, y: 0, width: full.width, height: full.height }, }; } - const scale = Number.isFinite(devicePixelRatio) && devicePixelRatio > 0 ? devicePixelRatio : 1; - const x = Math.min(full.width - 1, Math.max(0, Math.floor(cropRect.x * scale))); - const y = Math.min(full.height - 1, Math.max(0, Math.floor(cropRect.y * scale))); + const x = Math.max(0, Math.floor(cropRect.x * scale)); + const y = Math.max(0, Math.floor(cropRect.y * scale)); + const right = Math.min(full.width, Math.ceil((cropRect.x + cropRect.width) * scale)); + const bottom = Math.min(full.height, Math.ceil((cropRect.y + cropRect.height) * scale)); + // A target scrolled out of view has no pixels in this capture. Clamping its + // origin onto the edge would attach an unrelated strip as a successful crop. + if (right <= x || bottom <= y) return null; const cropped = image.crop({ x, y, - width: Math.max(1, Math.min(full.width - x, Math.ceil(cropRect.width * scale))), - height: Math.max(1, Math.min(full.height - y, Math.ceil(cropRect.height * scale))), + width: right - x, + height: bottom - y, }); const size = cropped.getSize(); + if (size.width <= 0 || size.height <= 0) return null; return { dataUrl: cropped.toDataURL(), width: size.width, height: size.height, cropRect }; }; -/** - * Electron converts `toBitmap()` output to sRGB by default. Captures on P3 Macs are - * P3, so that conversion costs more per tick than the JPEG encode the fingerprint - * replaces. An invalid target color space has no Skia color space, so `readPixels` - * copies the pixels without a color transform. The fingerprint only compares frames - * with each other, so color accuracy is irrelevant. - */ +// An invalid color space skips costly P3-to-sRGB conversion; fingerprints need no color accuracy. const FINGERPRINT_BITMAP_OPTIONS: Electron.ToBitmapOptions = { colorSpace: { primaries: "invalid", transfer: "invalid", matrix: "invalid", range: "invalid" }, }; -/** - * Identity of a captured frame: cheap enough to compute every tick, unlike a JPEG - * encode. Null when the pixels could not be read (Electron reports a failed - * `readPixels` as an empty buffer), so the caller treats the frame as changed. - */ +/** Empty readPixels results have no fingerprint and must be treated as changed frames. */ const fingerprintCapturedFrame = (image: Electron.NativeImage, size: Electron.Size) => { let bitmap: Buffer; try { @@ -405,10 +401,7 @@ interface PickSession { interface BrowserControlSession { readonly webContentsId: number; - // Electron's Debugger is GC-managed but registered with Chromium as a raw - // DevToolsAgentHostClient pointer; collecting it while attached crashes the - // browser process (electron/electron#53376). Detach must also go through - // this reference: `wc.debugger` throws once the WebContents is destroyed. + // Retain the attached Debugger to prevent GC crashes (electron/electron#53376); wc.debugger throws after destruction. readonly debugger: Electron.Debugger; readonly semaphore: Semaphore.Semaphore; readonly scope: Scope.Closeable; @@ -427,13 +420,7 @@ type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect type OpenLinkListener = (event: DesktopPreviewOpenLinkEvent) => Effect.Effect; -/** - * `about:blank` stays out: Chromium skips browser-side navigation for it, so the child copies - * the guest's `contextIsolation: false` preferences and Electron gives no way to override them. - * Deliberately not `ElectronShell.parseSafeExternalUrl`: that also admits - * `vscode://vscode-remote/...` deep links, which belong in `shell.openExternal` and not in a - * window spawned by a third-party page in the preview. - */ +// about:blank inherits relaxed guest preferences; external editor schemes must reach the OS handler. const POPUP_PROTOCOLS = new Set(["http:", "https:"]); const isPopupUrl = (rawUrl: string): boolean => { @@ -444,12 +431,7 @@ const isPopupUrl = (rawUrl: string): boolean => { } }; -/** - * A popup is not a webview attach, so the `will-attach-webview` hardening in `DesktopWindow` - * never sees it, and an unoverridden child would inherit the guest's relaxed posture: the - * picker preload needs `contextIsolation: false` to share `globalThis` with the previewed page, - * and no OAuth provider should get that. - */ +/** Popups bypass will-attach-webview hardening and would inherit the picker's contextIsolation:false. */ const POPUP_WINDOW_OPTIONS = { webPreferences: { contextIsolation: true, @@ -458,18 +440,13 @@ const POPUP_WINDOW_OPTIONS = { }, } satisfies Electron.BrowserWindowConstructorOptions; -/** - * `"popup"` opens a real window, which scripted popups need: denying them makes `window.open()` - * return `null` (OAuth SDKs report that as a blocked popup), and navigating the preview tab - * instead destroys the opener the popup has to `postMessage` its result back to. Schemes a - * popup cannot be hardened for keep loading in place, and so does a form POST with a body, - * which a new tab could only reopen as a GET. - */ +/** OAuth needs a surviving popup opener; unhardenable schemes and form POSTs must stay in place. */ export const previewWindowOpenAction = (details: { readonly url: string; readonly disposition: Electron.HandlerDetails["disposition"]; readonly postBody?: Electron.PostBody; }): "popup" | "new-tab" | "navigate" | "deny" => { + // MSAL redirects on a denied blank popup; navigating the tab would destroy that fallback. if (details.url === "" || details.url === "about:blank") return "deny"; if (!isPopupUrl(details.url)) return "navigate"; if (details.disposition === "new-window") return "popup"; @@ -479,7 +456,7 @@ export const previewWindowOpenAction = (details: { : "navigate"; }; -export const isPreviewRefreshShortcut = (input: Electron.Input): boolean => +const isPreviewRefreshShortcut = (input: Electron.Input): boolean => input.type === "keyDown" && input.key.toLowerCase() === "r" && (input.meta || input.control) && @@ -574,9 +551,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const pictureInPictureAspectRatiosRef = yield* Ref.make>(new Map()); const pictureInPictureMutationSemaphore = yield* Semaphore.make(1); const closingTabIdsRef = yield* Ref.make>(new Set()); - // Tab recording uses `setDisplayMediaRequestHandler` because Electron's legacy - // `getMediaSourceId` + `chromeMediaSource: "tab"` capture path was removed upstream - // (electron#44618) and now always rejects with NotAllowedError. + // Legacy tab capture is unsupported (electron/electron#44618); recording uses setDisplayMediaRequestHandler. let pendingRecording: PendingRecording | null = null; const displayMediaHandlerSessions = new WeakSet(); let frameCaptureWindowOpen = true; @@ -881,10 +856,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ] as const; }); - // emitIfCurrent, not emit: an event-driven writer such as syncTabAudible - // can commit between the modify above and here, and republishing this - // snapshot would roll the UI back to a value that writer will not send - // again because it suppresses unchanged audibility. + // syncTabAudible can commit after this update; emitIfCurrent prevents publishing a stale snapshot. if (Option.isSome(next)) { if (patch.controller !== undefined && next.value.webContentsId != null) { const capture = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId); @@ -901,11 +873,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } }); - /** - * Anything that applies zoom after an await goes through here: a snapshot taken before the - * await can be older than a zoom action that landed in between, and re-applying it would roll - * that action back. - */ + /** Read zoom after awaits so concurrent zoom actions cannot be rolled back by an older snapshot. */ const assertTabZoom = Effect.fn("PreviewManager.assertTabZoom")(function* (tabId: string) { const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); if (!tab || tab.webContentsId == null) return; @@ -916,11 +884,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ).pipe(Effect.ignore); }); - /** - * Mute counterpart to {@link assertTabZoom}: pushes the tab's committed mute - * onto whichever guest it currently owns, reading both at call time so an - * older snapshot can never roll back a mute action that landed after it. - */ + /** Read committed mute and current guest at call time so stale snapshots cannot roll back newer actions. */ const assertTabAudioMuted = Effect.fn("PreviewManager.assertTabAudioMuted")(function* ( tabId: string, ) { @@ -1023,13 +987,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function copy.delete(webContentsId); }), ]); - if (control) { - if (closedServerTab) browserHost.detach(closedServerTab); - for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) { - if (tab.webContentsId === webContentsId && tab.serverTab) browserHost.detach(tab.serverTab); + if (control) yield* releaseControlSession(control, closedServerTab); + }); + + // Closes a session already removed from `controlSessionsRef`. The server can + // only drive a tab while the desktop holds its debugger. + const releaseControlSession = Effect.fnUntraced(function* ( + control: BrowserControlSession, + closedServerTab?: PreviewTabState["serverTab"], + ) { + if (closedServerTab) browserHost.detach(closedServerTab); + for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) { + if (tab.webContentsId === control.webContentsId && tab.serverTab) { + browserHost.detach(tab.serverTab); } - yield* Scope.close(control.scope, Exit.void).pipe(Effect.ignore); } + yield* Scope.close(control.scope, Exit.void).pipe(Effect.ignore); }); const ensureControlSession = Effect.fn("PreviewManager.ensureControlSession")(function* ( @@ -1073,8 +1046,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const scope = yield* Scope.fork(parentScope, "sequential"); const wcDebugger = wc.debugger; const consoleReleases = yield* Queue.sliding(1); - // Console message eviction does not release the debugger's strong object handles. We - // keep text only, so release the whole group, including its object-id bookkeeping. + // Console eviction leaves strong debugger handles; release the group because we keep only text. yield* Effect.forkIn( Effect.forever( Queue.take(consoleReleases).pipe( @@ -1141,13 +1113,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const onMessage: BrowserControlSession["onMessage"] = (_event, method, params) => { runFork(handleDebuggerMessage(method, params)); }; - yield* Scope.addFinalizer( - scope, - attempt({ operation: "detachControlSession", webContentsId: wc.id }, () => { - wcDebugger.off("message", onMessage); - if (wcDebugger.isAttached()) wcDebugger.detach(); - }).pipe(Effect.ignore), - ); const control: BrowserControlSession = { webContentsId: wc.id, debugger: wcDebugger, @@ -1155,14 +1120,32 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function scope, onMessage, }; + // Electron emits `detach` when Chromium closes the debugger session on its + // own. The cached session would then fail every command until the webview + // is replaced. + let dropped = false; + const onDetach = () => { + dropped = true; + runFork(recoverDetachedControlSession(wc, control)); + }; + // The listener comes off before detach() so a detach this manager requested + // never looks like a dropped one. A dropped session has nothing left to + // detach: `wc.debugger` is shared, so detaching here would hit a successor. + yield* Scope.addFinalizer( + scope, + attempt({ operation: "detachControlSession", webContentsId: wc.id }, () => { + wcDebugger.off("message", onMessage); + wcDebugger.off("detach", onDetach); + if (!dropped && wcDebugger.isAttached()) wcDebugger.detach(); + }).pipe(Effect.ignore), + ); const initialize = Effect.fn("PreviewManager.initializeControlSession")(function* () { yield* attempt({ operation: "attachDebuggerListeners", webContentsId: wc.id }, () => { wcDebugger.on("message", onMessage); + wcDebugger.on("detach", onDetach); wcDebugger.attach("1.3"); }); - // Without this, dark-scheme pages with no background of their own (text/plain, e.g. - // .md files) render white text on white. Sent first because a document that paints - // before it arrives keeps the transparent base until its next load. + // Set an opaque base before first paint or background-less dark pages retain white-on-white text. yield* attemptPromise( { operation: "initializeDebugger.defaultBackground", webContentsId: wc.id }, () => @@ -1212,9 +1195,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const url = wc.getURL(); const title = wc.getTitle(); if (url === "" || url === "about:blank") return { kind: "Idle" }; - // Main frame only. `isLoading()` covers the whole frame tree, so a - // cross-origin iframe that loads after the page can leave it true with no - // later event to clear it, and the tab's loading bar never finishes. + // isLoading() includes late iframes whose completion may never clear the tab's loading bar. if (wc.isLoadingMainFrame()) return { kind: "Loading", url, title }; return { kind: "Success", url, title }; }; @@ -1253,9 +1234,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) { return [Option.none(), tabs] as const; } - // Electron emits did-stop-loading after did-fail-load. At that point the - // failed guest is no longer "loading", but it has not successfully - // navigated anywhere. + // did-stop-loading follows did-fail-load without proving successful navigation. const navStatus = preserveLoadFailure && current.navStatus.kind === "LoadFailed" && @@ -1273,9 +1252,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function navStatus, canGoBack, canGoForward, - // zoomFactor is deliberately not read back from the guest: Chromium - // reports the level it inherited from the app window, so mirroring it - // would turn an app zoom into the preview's own zoom. + // Guest zoom inherits app zoom; mirroring it would overwrite the tab's own setting. updatedAt, }; return [ @@ -1479,8 +1456,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }).pipe(Effect.ignore), ); }; - // Not getFocusedWebContents(): every guest of a focused window reports focus. - // An agent's keys reach a guest without a focused frame through GuestInput. + // Every guest of a focused window reports focus; GuestInput handles guests without a focused frame. const holdsKeyboardFocus = (contents: Electron.WebContents) => contents.isFocused() && contents.focusedFrame !== null; const syncMenuShortcuts = (contents: Electron.WebContents, input: Electron.Input): void => { @@ -1489,9 +1465,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function !isPreviewEditingShortcut(input, hostPlatform) || !holdsKeyboardFocus(contents), ); }; - // A popup opens with Electron's default handler, so the page inside it could - // otherwise spawn native windows without limit. Nothing in an OAuth flow - // opens a second popup, so the chain stops at the first one. + // Popups inherit Electron's unrestricted window handler; block nested popups to bound the chain. const windowCreated = (window: Electron.BrowserWindow): void => { window.webContents.setIgnoreMenuShortcuts(true); window.webContents.setWindowOpenHandler(() => ({ action: "deny" })); @@ -1626,6 +1600,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } yield* SynchronizedRef.modifyEffect(frameCaptureSessionsRef, (sessions) => Effect.gen(function* () { + // Cleanup or lock acquisition can outlive the replacement window. + if (window.isDestroyed()) return [undefined, sessions] as const; if (sessions.size > 0) { yield* setWindowBackgroundThrottling(window, false); } @@ -1832,15 +1808,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { return yield* new PreviewTabNotFoundError({ tabId }); } - // Always assert the tab's own zoom rather than reading the guest's: a guest - // attaching while the app UI is zoomed starts at the embedder's inherited - // zoom level, which is not the preview's zoom. Done before the guest is - // published so it never paints a frame at the inherited zoom. + // Restore the tab's zoom before publishing the guest so it never paints at inherited app zoom. yield* attempt({ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId }, () => wc.setZoomFactor(currentTab.zoomFactor), ); - // A replacement guest attaches unmuted, so reassert the tab's mute before it is published - // rather than letting it emit audio the user already silenced. + // Replacement guests start unmuted; restore mute before publishing them. yield* attempt({ operation: "registerWebview.restoreAudioMuted", tabId, webContentsId }, () => wc.setAudioMuted(currentTab.audioMuted), ); @@ -1894,16 +1866,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function return yield* new PreviewTabNotFoundError({ tabId }); } const { state: registered, pendingUrl } = registration.value; - // A zoom or mute action that landed while this attach was in flight - // addressed the guest this one replaced, so settle the new guest on the - // committed values. + // Concurrent actions targeted the previous guest; reconcile this one with committed zoom and mute. yield* assertTabZoom(tabId); yield* assertTabAudioMuted(tabId).pipe(Effect.ignore); runFork(restoreControlSession(tabId, wc)); yield* emitIfCurrent(tabId, registered); - // Transitions that fired before the tab owned this guest were dropped by - // syncTabAudible's ownership check, so re-read and reconcile through the - // same path the event uses. + // Ownership checks dropped pre-attach audibility events; reconcile through the event path. yield* syncTabAudible(tabId, wc, yield* readAudible); yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () => { wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme); @@ -1935,9 +1903,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); - // Called when a guest attaches to the window, before its first document paints. A tab opened - // straight to a URL often paints before the renderer gets to registerWebview, which would - // leave that page on the transparent base. + // URL tabs can paint before registerWebview; set the background at attach time. const prepareWebview = Effect.fn("PreviewManager.prepareWebview")(function* ( wc: Electron.WebContents, ) { @@ -1976,10 +1942,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function zoomFactor: current?.zoomFactor ?? DEFAULT_ZOOM_FACTOR, pictureInPicture: current?.pictureInPicture ?? false, colorScheme: current?.colorScheme ?? "system", - // Mute is user intent, and the old document keeps playing until loadURL - // actually replaces it, so clearing audibility here would drop the - // speaker with no transition left to restore it. Chromium reports the - // change when it happens. + // Keep audibility until Chromium replaces the document; clearing it here can lose the final transition. audioMuted: current?.audioMuted ?? false, audible: current?.audible ?? false, controller: current?.controller ?? "none", @@ -2137,8 +2100,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.off("destroyed", onDestroyed); wc.off("did-start-navigation", onNavigated); }).pipe(Effect.ignore); - // Only drop the slot while it is still ours. A newer session may - // already have swapped itself in before cancelling this one. + // A newer session may already own the slot when this one is cancelled. yield* Ref.update(pickSessionsRef, (sessions) => sessions.get(tabId) === session ? replaceMap(sessions, (copy) => { @@ -2198,13 +2160,20 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const submission = args[2] === "send" && annotationSendEnabled.get(tabId) === true ? "send" : "attach"; const devicePixelRatio = typeof args[3] === "number" ? args[3] : 1; + const targetRects = [ + ...payload.elements.map((target) => target.rect), + ...payload.regions.map((target) => target.rect), + ...payload.strokes.map((target) => target.bounds), + ]; runFork( capturePageWithRetry( { operation: "captureAnnotationScreenshot", tabId, webContentsId: wc.id }, tabId, wc, ).pipe( - Effect.map((image) => cropAnnotationScreenshot(image, cropRect, devicePixelRatio)), + Effect.map((image) => + cropAnnotationScreenshot(image, cropRect, devicePixelRatio, targetRects), + ), Effect.tapError((error) => Effect.logWarning("preview annotation screenshot failed").pipe( Effect.annotateLogs({ tabId, webContentsId: wc.id, error: error.message }), @@ -2223,9 +2192,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function : { annotation: { ...payload, screenshot }, submission }, }), Effect.flatMap((result) => { - // A capture that outlives its session must not touch the - // overlay: the preload tears down on the captured signal, and - // by now it may be running a newer pick. + // Late captures must not signal an overlay that may now belong to a newer pick. if (!claimSettle()) return Effect.void; return attempt( { operation: "pickElement.captureComplete", tabId, webContentsId: wc.id }, @@ -2244,10 +2211,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (event.isMainFrame) settle(null); }; const registerPickElement = Effect.fn("PreviewManager.registerPickElement")(function* () { - // Two picks on one tab can overlap. Swap this session in and cancel - // the previous holder in one step, so no third pick can slip into an - // empty slot in between and the session we push out still resumes - // its renderer. + // Atomically swap/cancel overlapping picks so another pick cannot claim a transient empty slot. const replaced = yield* Ref.modify(pickSessionsRef, (sessions) => [ sessions.get(tabId) ?? null, replaceMap(sessions, (copy) => { @@ -2255,9 +2219,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ]); if (replaced) yield* replaced.cancel; - // A newer pick may have cancelled this session while the previous - // one was torn down. Cleanup already ran, so attaching listeners now - // would leak them and start an overlay nobody is waiting on. + // A newer pick may cancel during teardown; do not leak listeners or start an abandoned overlay. if (settled) return; yield* attempt({ operation: "pickElement.register", tabId, webContentsId: wc.id }, () => { wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage); @@ -2305,9 +2267,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* update(tabId, { zoomFactor: next }); }); - // Emulated media lives on the CDP debugger session, not the WebContents, so - // it is lost whenever the session detaches (webview swap, DevTools - // open/close) and must be re-applied after every (re)attach. + // Media emulation belongs to the debugger session and must be restored after every reattach. const applyColorScheme = Effect.fn("PreviewManager.applyColorScheme")(function* ( tabId: string, wc: Electron.WebContents, @@ -2328,8 +2288,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function // The scheme is read after the session attaches so a concurrent setColorScheme is not // overwritten with a stale snapshot. - const restoreControlSession = (tabId: string, wc: Electron.WebContents) => - Effect.gen(function* () { + const restoreControlSession = Effect.fn("PreviewManager.restoreControlSession")( + function* (tabId: string, wc: Electron.WebContents) { const beforeAttach = (yield* SynchronizedRef.get(tabsRef)).get(tabId); if (beforeAttach?.webContentsId !== wc.id) return; const control = yield* ensureControlSession(wc); @@ -2354,7 +2314,33 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }), ); } - }).pipe(Effect.ignore); + }, + (effect, _tabId, _wc) => effect.pipe(Effect.ignore), + ); + + // Only the session that saw the detach is replaced: by the time the event is + // handled the guest may already hold a newer one, which must stay. + const recoverDetachedControlSession = Effect.fn("PreviewManager.recoverDetachedControlSession")( + function* (wc: Electron.WebContents, detached: BrowserControlSession) { + const removed = yield* SynchronizedRef.modify(controlSessionsRef, (sessions) => + sessions.get(wc.id) === detached + ? ([ + true, + replaceMap(sessions, (copy) => { + copy.delete(wc.id); + }), + ] as const) + : ([false, sessions] as const), + ); + if (!removed) return; + yield* releaseControlSession(detached); + if (wc.isDestroyed()) return; + const tabId = yield* tabIdForWebContents(wc.id); + if (tabId === null) return; + yield* restoreControlSession(tabId, wc); + }, + (recover) => Effect.ignore(recover), + ); const setColorScheme = Effect.fn("PreviewManager.setColorScheme")(function* ( tabId: string, @@ -2367,8 +2353,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (tab.colorScheme !== colorScheme) { yield* update(tabId, { colorScheme }); } - // Re-read after the update: registerWebview may have swapped the guest - // in the meantime and the override must land on the current one. + // registerWebview may swap guests during the update; apply to the current one. const webContentsId = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.webContentsId; if (webContentsId == null) return; const wc = webContents.fromId(webContentsId); @@ -2384,10 +2369,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (!tab) { return yield* new PreviewTabNotFoundError({ tabId }); } - // Commit and apply under the tab's lifecycle lock, then assert the - // committed value rather than this call's argument. Two overlapping toggles - // would otherwise be free to commit in one order and reach Chromium in the - // other, leaving the icon disagreeing with the guest. + // Serialize commit/apply, then read committed mute so concurrent toggles cannot reach Chromium out of order. yield* withTabLifecycleLock( tabId, Effect.gen(function* () { @@ -2396,8 +2378,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (committed) { yield* update(tabId, { audioMuted }); } - // Roll the commit back if Chromium refused: reporting success here - // would leave the tab drawn as muted while it keeps playing. + // Roll back rejected mute commits so the UI reflects actual playback. yield* assertTabAudioMuted(tabId).pipe( Effect.tapError(() => committed ? update(tabId, { audioMuted: previous }) : Effect.void, @@ -2509,9 +2490,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } const frameSession = (yield* SynchronizedRef.get(frameCaptureSessionsRef)).get(tabId); if (frameSession?.scope !== captureSession.scope) return; - // Fingerprint the raw pixels before encoding so an unchanged page skips the - // synchronous JPEG encode, the base64 copy and the IPC send. An unreadable - // frame has no fingerprint and is always delivered. + // Fingerprint before encoding so unchanged frames skip JPEG, base64, and IPC; unreadable frames must still be sent. const fingerprint = fingerprintCapturedFrame(image, size); const pictureInPicture = frameSession.consumers.has("picture-in-picture") && @@ -2866,8 +2845,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (hostPlatform === "darwin") { pictureInPictureWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, - // Electron otherwise temporarily transforms the entire app into - // a UIElement process, which removes the owning app from the Dock. + // Electron's temporary UIElement transformation would remove the app from the Dock. skipTransformProcessType: true, }); } @@ -3002,10 +2980,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (pendingRecording?.tabId === tabId) pendingRecording = null; }; - /** - * A display-media request carries no tab identity, so the slot is exclusive: a second tab - * arming before the first request lands would redirect the first renderer's stream. - */ + /** Display-media requests lack tab identity; only one tab may arm a recording to prevent stream redirection. */ const armPendingRecording = Effect.fn("PreviewManager.armPendingRecording")(function* ( tabId: string, wc: Electron.WebContents, @@ -3032,8 +3007,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function armedAtMillis: now, }; pendingRecording = armed; - // The handler callback is sync and cannot read a clock, so expiry is driven from here. - // Identity compare: a re-arm replaces the object, and this fiber must not clobber it. + // The synchronous callback cannot read a clock. Compare identity so expiry cannot clobber a re-arm. yield* Effect.forkIn( Effect.sleep(RECORDING_ARM_GRACE_MS).pipe( Effect.andThen( @@ -3046,8 +3020,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); - // Installed once per session: answers the renderer's `getDisplayMedia()` with the tab that - // `startRecording` armed, and denies anything else so pages cannot capture on their own. + // Only serve the tab armed by startRecording; pages must not capture independently. const installDisplayMediaRequestHandler = (session: Session) => { if (displayMediaHandlerSessions.has(session)) return; displayMediaHandlerSessions.add(session); @@ -3606,7 +3579,7 @@ export class PreviewManager extends Context.Service< } >()("@t3tools/desktop/preview/Manager/PreviewManager") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* PreviewManagerMake() { const environment = yield* DesktopEnvironment.DesktopEnvironment; const browserSession = yield* BrowserSession.BrowserSession; diff --git a/apps/desktop/src/preview/PasskeyBackendMac.ts b/apps/desktop/src/preview/PasskeyBackendMac.ts index ccdffa2a70c08..91cefaddc42f1 100644 --- a/apps/desktop/src/preview/PasskeyBackendMac.ts +++ b/apps/desktop/src/preview/PasskeyBackendMac.ts @@ -6,8 +6,7 @@ import type { PasskeyCeremonyResult } from "./PasskeyBridge.ts"; const ES256 = -7; -// WebAuthn rejects RP IDs that are public suffixes, private registries -// included, so one github.io site cannot mint passkeys for every other one. +// WebAuthn rejects public suffix RP IDs, including private registries such as github.io. const isPublicSuffix = (domain: string) => domain !== "localhost" && getPublicSuffix(domain, { allowPrivateDomains: true }) === domain; @@ -32,13 +31,10 @@ const toBase64Url = (value: BufferSource) => : new Uint8Array(value), ).toString("base64url"); -/** - * Needs Apple's managed browser entitlement in the signed build. - */ +/** Requires Apple's managed browser entitlement in the signed build. */ export const macPasskeyBackend: PasskeyBackend = { create: async (publicKey, context): Promise => { - // The native layer only converts P-256 keys and never settles for any - // other algorithm, so ES256 is the only one it may negotiate. + // The native layer only converts P-256 keys, so negotiate only ES256. const params: unknown = publicKey.pubKeyCredParams; if (params !== undefined && !Array.isArray(params)) return { success: false, error: "TypeError" }; @@ -56,8 +52,7 @@ export const macPasskeyBackend: PasskeyBackend = { options, ); if (!result.success) return { success: false, error: result.error }; - // The native layer reports parsed authenticator data as JSON and claims - // every credential is a synced platform passkey; neither is reliable. + // Native parsed authenticator JSON and synced-platform-passkey claims are unreliable. const authData = authenticatorDataFromAttestation( Buffer.from(result.data.attestationObject, "base64url"), ); @@ -79,8 +74,7 @@ export const macPasskeyBackend: PasskeyBackend = { options, ); if (!result.success) return { success: false, error: result.error }; - // The native layer applies the site's allow list to platform passkeys only, - // so a security key can answer with a credential the site did not ask for. + // Native allow lists cover only platform passkeys; security-key responses need checking here. const allowed = (Array.isArray(publicKey.allowCredentials) ? publicKey.allowCredentials : []) .filter((credential) => credential?.type === "public-key" && isBufferSource(credential.id)) .map((credential) => toBase64Url(credential.id)); diff --git a/apps/desktop/src/preview/PasskeyBridge.test.ts b/apps/desktop/src/preview/PasskeyBridge.test.ts index 8cbaad7f38dce..998a9298baf3c 100644 --- a/apps/desktop/src/preview/PasskeyBridge.test.ts +++ b/apps/desktop/src/preview/PasskeyBridge.test.ts @@ -16,17 +16,6 @@ const assertionData = { extensions: { prf: { results: { first: base64Url([9]) } } }, }; -const attestationData = { - credentialId: base64Url([1, 2, 3]), - clientDataJSON: base64Url([4]), - attestationObject: base64Url([10]), - authData: base64Url([11]), - publicKey: base64Url([12]), - publicKeyAlgorithm: -7, - transports: [], - extensions: { credProps: { rk: true } }, -}; - const creationOptions: PublicKeyCredentialCreationOptions = { challenge: new Uint8Array([1]), rp: { name: "Example" }, @@ -38,10 +27,6 @@ const illegalInvocation = (): never => { throw new TypeError("Illegal invocation"); }; -/** - * Installs the bridge over fresh stand-ins for the page's DOM classes. Like - * Chromium's, their getters only work on objects the browser created itself. - */ const install = (respond: (channel: string) => unknown) => { const nativeCreate = vi.fn(async () => "native-create"); const nativeGet = vi.fn(async () => "native-get"); @@ -144,62 +129,6 @@ describe("installPasskeyBridge", () => { }); }); - it("returns registrations with their attestation and public key", async () => { - const { invoke, credentials, FakeAttestationResponse } = install(() => ({ - success: true, - data: attestationData, - })); - - const credential = (await credentials.create({ - publicKey: creationOptions, - })) as PublicKeyCredential; - - assert.strictEqual(invoke.mock.calls[0]?.[0], PASSKEY_CREATE_CHANNEL); - const response = credential.response as AuthenticatorAttestationResponse; - assert.instanceOf(response, FakeAttestationResponse); - assert.isNull(credential.authenticatorAttachment); - assert.deepStrictEqual(bytesOf(response.attestationObject), [10]); - assert.deepStrictEqual(bytesOf(response.getAuthenticatorData()), [11]); - assert.deepStrictEqual(bytesOf(response.getPublicKey()), [12]); - assert.strictEqual(response.getPublicKeyAlgorithm(), -7); - assert.deepStrictEqual(credential.getClientExtensionResults(), { credProps: { rk: true } }); - assert.deepStrictEqual(credential.toJSON(), { - id: attestationData.credentialId, - rawId: attestationData.credentialId, - type: "public-key", - response: { - clientDataJSON: attestationData.clientDataJSON, - attestationObject: attestationData.attestationObject, - authenticatorData: attestationData.authData, - transports: [], - publicKey: attestationData.publicKey, - publicKeyAlgorithm: -7, - }, - clientExtensionResults: { credProps: { rk: true } }, - }); - }); - - it("leaves autofill and non-passkey requests to Chromium", async () => { - const { invoke, credentials, nativeCreate, nativeGet } = install(() => ({ - success: true, - data: assertionData, - })); - - await credentials.get({ - mediation: "conditional", - publicKey: { challenge: new Uint8Array([1]) }, - }); - await credentials.get({ password: true } as CredentialRequestOptions); - const upgrade = { mediation: "conditional", publicKey: creationOptions } as const; - await credentials.create(upgrade); - await credentials.create({ password: {} } as CredentialCreationOptions); - assert.strictEqual(invoke.mock.calls.length, 0); - assert.strictEqual(nativeGet.mock.calls.length, 2); - assert.strictEqual(nativeCreate.mock.calls.length, 2); - assert.isFalse(await PublicKeyCredential.isConditionalMediationAvailable()); - assert.isTrue(await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()); - }); - it("rejects with the WebAuthn error the ceremony ended with", async () => { const { credentials } = install((channel) => ({ success: false, @@ -216,18 +145,6 @@ describe("installPasskeyBridge", () => { assert.instanceOf(fetched, TypeError); }); - it("refuses when the main process has no handler for the page", async () => { - const { credentials } = install(() => { - throw new Error("Error invoking remote method 'preview:passkey-get': No handler registered"); - }); - - const error = await credentials - .get({ publicKey: { challenge: new Uint8Array([1]) } }) - .catch((caught: unknown) => caught); - assert.instanceOf(error, DOMException); - assert.strictEqual((error as DOMException).name, "NotAllowedError"); - }); - it("rejects as soon as the page aborts, without waiting on the system sheet", async () => { const { credentials } = install(() => new Promise(() => {})); const controller = new AbortController(); diff --git a/apps/desktop/src/preview/PasskeyBridge.ts b/apps/desktop/src/preview/PasskeyBridge.ts index fbb9fefa4aa5f..bc77b38c1cf0a 100644 --- a/apps/desktop/src/preview/PasskeyBridge.ts +++ b/apps/desktop/src/preview/PasskeyBridge.ts @@ -44,10 +44,7 @@ const ceremonyError = (name: string) => DOM_EXCEPTION_NAMES.has(name) ? name : "NotAllowedError", ); -/** - * Chromium ignores members it does not know, so functions and other uncloneable - * values drop out here instead of failing the whole ceremony. - */ +// Chromium drops unknown members; discard uncloneable values instead of failing the ceremony. const toCloneable = (value: unknown): unknown => { if (value instanceof ArrayBuffer) return value.slice(0); if (ArrayBuffer.isView(value)) { @@ -64,9 +61,7 @@ const toCloneable = (value: unknown): unknown => { return value; }; -// The objects below borrow the native prototypes so `instanceof` checks pass. -// Their own properties shadow the native getters, which only work on objects -// Chromium created itself. +// Shadow native getters: they reject objects Chromium did not create, even with the correct prototype. const withValues = (target: T, values: Record) => { for (const [key, value] of Object.entries(values)) { Object.defineProperty(target, key, { value, enumerable: true, configurable: true }); @@ -202,10 +197,7 @@ const credentialFromGetResult = (data: Extract signal.reason ?? new DOMException("The operation was aborted.", "AbortError"); -/** - * Conditional (autofill and automatic upgrade) requests stay native: the system - * sheet is modal and must not open on its own. - */ +/** Keep conditional requests native so autofill and upgrades cannot open a modal sheet unprompted. */ export function installPasskeyBridge(invoke: InvokePasskeyCeremony) { if (typeof CredentialsContainer === "undefined" || typeof PublicKeyCredential === "undefined") { return; diff --git a/apps/desktop/src/preview/Passkeys.test.ts b/apps/desktop/src/preview/Passkeys.test.ts index c6b8720314a3d..219c67fac5061 100644 --- a/apps/desktop/src/preview/Passkeys.test.ts +++ b/apps/desktop/src/preview/Passkeys.test.ts @@ -120,7 +120,6 @@ describe("PreviewPasskeys", () => { assert.isFalse(options.isPublicSuffix("example.com")); assert.isFalse(options.isPublicSuffix("localhost")); - // WebAuthn defaults the RP ID to the caller's own host. yield* call(PASSKEY_GET_CHANNEL, { challenge: new Uint8Array([1]) }); assert.strictEqual(webauthn.getCredential.mock.calls[1]?.[0].rpId, "accounts.example.com"); @@ -218,7 +217,6 @@ describe("PreviewPasskeys", () => { allowCredentials: [{ type: "public-key", id: new Uint8Array([1]) }], }; - // macOS applies the allow list to passkeys but not to security keys. webauthn.getCredential.mockResolvedValueOnce(assertion("Ag")); const other = yield* call(PASSKEY_GET_CHANNEL, publicKey); assert.deepStrictEqual(other, { success: false, error: "NotAllowedError" }); @@ -244,7 +242,6 @@ describe("PreviewPasskeys", () => { const lan = makeGuest("http://192.168.1.5:3000"); passkeys.attachGuest(lan.guest); assert.deepStrictEqual(yield* lan.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed); - // macOS refuses `*.localhost`, so the page hears no rather than a native error. const subdomain = makeGuest("http://app.localhost:3000"); passkeys.attachGuest(subdomain.guest); assert.deepStrictEqual(yield* subdomain.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed); @@ -257,9 +254,13 @@ describe("PreviewPasskeys", () => { page.state.focused = true; let finish: (value: unknown) => void = () => {}; - webauthn.getCredential.mockReturnValueOnce(new Promise((resolve) => (finish = resolve))); + const ceremonyStarted = Promise.withResolvers(); + webauthn.getCredential.mockImplementationOnce(() => { + ceremonyStarted.resolve(); + return new Promise((resolve) => (finish = resolve)); + }); const first = yield* Effect.forkChild(page.call(PASSKEY_GET_CHANNEL, publicKey)); - yield* Effect.promise(() => new Promise((resolve) => setImmediate(resolve))); + yield* Effect.promise(() => ceremonyStarted.promise); assert.deepStrictEqual(yield* page.call(PASSKEY_GET_CHANNEL, publicKey), notAllowed); page.mainFrame.origin = "https://other.example"; @@ -268,26 +269,6 @@ describe("PreviewPasskeys", () => { }).pipe(Effect.provide(bridgeLayer)), ); - it.effect("answers the page even when the native ceremony never settles", () => - Effect.gen(function* () { - const passkeys = yield* PreviewPasskeys.PreviewPasskeys; - const { guest, call } = makeGuest(); - passkeys.attachGuest(guest); - webauthn.getCredential.mockReturnValueOnce(new Promise(() => {})); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - - const pending = yield* Effect.forkChild( - call(PASSKEY_GET_CHANNEL, { challenge: new Uint8Array([1]), timeout: 1_000 }), - ); - yield* Effect.promise(() => vi.advanceTimersByTimeAsync(6_000)); - - assert.deepStrictEqual(yield* Fiber.join(pending), { - success: false, - error: "NotAllowedError", - }); - }).pipe(Effect.provide(bridgeLayer)), - ); - it.effect("turns each path on only for builds signed for it", () => Effect.gen(function* () { const entitled = yield* PreviewPasskeys.PreviewPasskeys.pipe( diff --git a/apps/desktop/src/preview/Passkeys.ts b/apps/desktop/src/preview/Passkeys.ts index 5456aaab6a8a2..34db1404aacb8 100644 --- a/apps/desktop/src/preview/Passkeys.ts +++ b/apps/desktop/src/preview/Passkeys.ts @@ -84,8 +84,7 @@ const chooseAccount = async (details: Electron.SelectWebauthnAccountDetails) => const NATIVE_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000; const NATIVE_MAX_TIMEOUT_MS = 60 * 60 * 1000; -// Mirrors the native layer's own clamp, plus a margin: it can leave a ceremony -// unsettled, and the page must still get an answer. +// Native ceremonies can remain unsettled; match its deadline clamp with a margin. const ceremonyDeadline = (timeout: unknown) => (typeof timeout === "number" && timeout > 0 ? Math.min(timeout, NATIVE_MAX_TIMEOUT_MS) @@ -99,9 +98,7 @@ const withDeadline = (ceremony: Promise, milliseconds: nu return Promise.race([ceremony, deadline]).finally(() => clearTimeout(timer)); }; -// Secure contexts only: https, or http on this machine. Chromium also trusts -// `*.localhost`, but the macOS layer refuses it, so it is turned away here -// instead of failing deeper with a less useful error. +// macOS refuses *.localhost even though Chromium trusts it. const isTrustworthyOrigin = (origin: string) => { if (!URL.canParse(origin)) return false; const { protocol, hostname } = new URL(origin); @@ -112,9 +109,7 @@ const isTrustworthyOrigin = (origin: string) => { ); }; -/** - * Windows needs none: Chromium already hands WebAuthn to Windows Hello there. - */ +// Chromium already delegates to Windows Hello. const backendFor = (platform: NodeJS.Platform): PasskeyBackend | undefined => platform === "darwin" ? macPasskeyBackend : undefined; @@ -168,9 +163,7 @@ const make = Effect.gen(function* () { // Only the guest's main frame runs the bridge preload. const frame = event.senderFrame; if (!frame || frame !== guest.mainFrame) return notAllowed; - // The page shares a JS world with the preload, so nothing it sends can - // be trusted for the origin. Read the committed origin before any await: - // the frame object outlives a navigation. + // The page shares the preload's JS world; read the frame's committed origin before any await/navigation. const origin = frame.origin; if (!isTrustworthyOrigin(origin) || ceremonyPending || !guest.isFocused()) { return notAllowed; diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index a1df630de4e94..4cb5987cdeb85 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -35,6 +35,7 @@ import { START_PICK_CHANNEL, } from "./GuestProtocol.ts"; const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui"; +const INPUT_LAYER_ATTRIBUTE = "data-t3code-annotation-input"; const Z_INDEX_OVERLAY = 2147483646; const PRIMARY = "var(--t3-primary)"; const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)"; @@ -196,11 +197,7 @@ const navigationDirectionForButton = (button: number): "back" | "forward" | null return null; }; -// Chromium routes thumb-button history navigation to the *focused* WebContents, -// so hovering this guest without focusing it sends the host app's router back -// instead of the preview. Suppress Chromium's default here and drive this tab's -// history explicitly so the buttons always navigate the browser the pointer is -// over — never the host app. +// 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(); @@ -252,15 +249,12 @@ function unionRects( const top = Math.min(...rects.map((rect) => rect.y)); const right = Math.max(...rects.map((rect) => rect.x + rect.width)); const bottom = Math.max(...rects.map((rect) => rect.y + rect.height)); - const x = Math.max(0, left - padding); - const y = Math.max(0, top - padding); - const maxWidth = Math.max(1, window.innerWidth - x); - const maxHeight = Math.max(1, window.innerHeight - y); + // Main clips to the captured viewport; clipping here would lose offscreen bounds. return { - x, - y, - width: Math.min(maxWidth, right - left + padding * 2), - height: Math.min(maxHeight, bottom - top + padding * 2), + x: left - padding, + y: top - padding, + width: right - left + padding * 2, + height: bottom - top + padding * 2, }; } @@ -271,7 +265,7 @@ function isAnnotationNode(element: Element): boolean { function pickFromPoint(clientX: number, clientY: number): Element | null { for (const candidate of document.elementsFromPoint(clientX, clientY)) { if (!(candidate instanceof Element)) continue; - if (isAnnotationNode(candidate)) continue; + if (isAnnotationNode(candidate) || candidate.hasAttribute(INPUT_LAYER_ATTRIBUTE)) continue; if (candidate === document.documentElement || candidate === document.body) continue; return candidate; } @@ -393,11 +387,7 @@ function toStackFrame(frame: { }; } -/** - * `getElementContext` walks the inspected page's React internals, and some pages leave it - * pending forever. Without a bound, the whole submit chain stalls and the overlay sits on - * "Capturing…". - */ +/** React-internals lookups can remain pending forever; bound them so submit cannot stall the overlay. */ function withCaptureTimeout(promise: Promise, millis: number): Promise { let timer: ReturnType | undefined; return Promise.race([ @@ -410,11 +400,7 @@ function withCaptureTimeout(promise: Promise, millis: number): Promise { const base = { pageUrl: location.href, @@ -639,7 +625,18 @@ function startAnnotation(sendEnabled: boolean): void { const strokes: PreviewAnnotationStrokeTarget[] = []; const styleChanges = new Map(); const toolButtons = new Map(); - let tool: AnnotationTool = "select"; + // Chromium draws a PDF in its own viewer frame, so pointer and key input over it + // never reaches this document. A transparent layer above the viewer catches the + // pointer and takes focus for Escape and the tool keys. A PDF has no elements to + // select, so it starts on Region. + const isPdf = document.contentType === "application/pdf"; + const inputLayer = isPdf ? document.createElement("div") : null; + if (inputLayer) { + inputLayer.setAttribute(INPUT_LAYER_ATTRIBUTE, ""); + inputLayer.tabIndex = -1; + inputLayer.style.cssText = `position:fixed;inset:0;z-index:${Z_INDEX_OVERLAY - 1};cursor:crosshair;outline:none`; + } + let tool: AnnotationTool = isPdf ? "marquee" : "select"; let dragStart: PreviewAnnotationPoint | null = null; let activeStroke: { target: PreviewAnnotationStrokeTarget; path: SVGPathElement } | null = null; let pendingCapture = false; @@ -1359,6 +1356,7 @@ function startAnnotation(sendEnabled: boolean): void { ipcRenderer.off(ANNOTATION_CAPTURED_CHANNEL, onCaptured); document.documentElement.removeAttribute("data-t3code-annotation-tool"); cursorStyle.remove(); + inputLayer?.remove(); host.remove(); activeSession = null; if (notifyMain) ipcRenderer.send(ELEMENT_PICKED_CHANNEL, null); @@ -1389,8 +1387,7 @@ function startAnnotation(sendEnabled: boolean): void { pendingCapture = true; submit.disabled = true; submit.textContent = "Capturing…"; - // The element context lookup can take up to its timeout, and the user can - // keep editing meanwhile; the annotation must describe what they submitted. + // Snapshot the submitted comment before context lookup lets the user edit it. const submittedComment = comment.value.trim(); const submittedRegions = [...regions]; const submittedStrokes = [...strokes]; @@ -1411,8 +1408,7 @@ function startAnnotation(sendEnabled: boolean): void { }), ) .then((elements) => { - // The overlay may have been cancelled or replaced while the capture - // ran. A late submit must not deliver into the next pick's listener. + // A late submit must not reach a replacement pick's listener. if (finished) return; const annotation: PreviewAnnotationPayload = { id: nextId("annotation"), @@ -1439,7 +1435,7 @@ function startAnnotation(sendEnabled: boolean): void { annotation, screenshotRect, submission === "send" && !sendEnabled ? "attach" : submission, - // Main crops a full-page capture, whose pixels are CSS px × this. + // Main crops a viewport capture, whose pixels are CSS px × this. window.devicePixelRatio, ); }) @@ -1451,8 +1447,7 @@ function startAnnotation(sendEnabled: boolean): void { root.addEventListener("keydown", (event) => { const submission = event.target === comment ? resolveAnnotationSubmission(event, sendEnabled) : null; - // Keep this in the bubble phase so editor inputs receive the event before - // it is isolated from listeners installed by the inspected page. + // Bubble phase lets editor inputs handle events before hiding them from the page. event.stopImmediatePropagation(); if (!submission) return; event.preventDefault(); @@ -1470,6 +1465,10 @@ function startAnnotation(sendEnabled: boolean): void { window.addEventListener("resize", repaint, { passive: true }); ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel); ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured); + if (inputLayer) { + document.documentElement.appendChild(inputLayer); + inputLayer.focus({ preventScroll: true }); + } document.documentElement.appendChild(host); rootResizeObserver.observe(document.documentElement); refreshToolButtons(); diff --git a/apps/desktop/src/preview/PickedElementPayload.test.ts b/apps/desktop/src/preview/PickedElementPayload.test.ts index d7a967324771f..68f313783a275 100644 --- a/apps/desktop/src/preview/PickedElementPayload.test.ts +++ b/apps/desktop/src/preview/PickedElementPayload.test.ts @@ -31,76 +31,6 @@ function validPayload(overrides?: Record): Record { - it("accepts a complete, well-typed payload", () => { - expect(isPickedElementPayload(validPayload())).toBe(true); - }); - - it("accepts nullable string fields when null", () => { - expect( - isPickedElementPayload( - validPayload({ pageTitle: null, selector: null, componentName: null, source: null }), - ), - ).toBe(true); - }); - - it("accepts an empty stack array", () => { - expect(isPickedElementPayload(validPayload({ stack: [] }))).toBe(true); - }); - - it("accepts stack frames with null fields", () => { - expect( - isPickedElementPayload( - validPayload({ - stack: [ - { - functionName: null, - fileName: null, - lineNumber: null, - columnNumber: null, - }, - ], - }), - ), - ).toBe(true); - }); - - it("rejects null and primitive inputs", () => { - expect(isPickedElementPayload(null)).toBe(false); - expect(isPickedElementPayload(undefined)).toBe(false); - expect(isPickedElementPayload("string")).toBe(false); - expect(isPickedElementPayload(42)).toBe(false); - expect(isPickedElementPayload([])).toBe(false); - }); - - it.each<[string, Record]>([ - ["missing pageUrl", validPayload({ pageUrl: undefined })], - ["wrong-type pageUrl", validPayload({ pageUrl: 123 })], - ["missing tagName", validPayload({ tagName: undefined })], - ["missing htmlPreview", validPayload({ htmlPreview: undefined })], - ["missing styles", validPayload({ styles: undefined })], - ["missing pickedAt", validPayload({ pickedAt: undefined })], - ["wrong-type pageTitle", validPayload({ pageTitle: 99 })], - ["wrong-type selector", validPayload({ selector: 99 })], - ["wrong-type componentName", validPayload({ componentName: 99 })], - ])("rejects payloads with %s", (_label, value) => { - expect(isPickedElementPayload(value)).toBe(false); - }); - - it("rejects malformed source frames", () => { - expect( - isPickedElementPayload( - validPayload({ - source: { - functionName: 0, - fileName: null, - lineNumber: null, - columnNumber: null, - }, - }), - ), - ).toBe(false); - }); - it("rejects non-finite numeric line/column numbers", () => { expect( isPickedElementPayload( @@ -127,11 +57,6 @@ describe("isPickedElementPayload", () => { ), ).toBe(false); }); - - it("rejects malformed stack arrays", () => { - expect(isPickedElementPayload(validPayload({ stack: "not-an-array" }))).toBe(false); - expect(isPickedElementPayload(validPayload({ stack: [{ bogus: true }] }))).toBe(false); - }); }); function validAnnotation(overrides?: Record): Record { @@ -176,26 +101,9 @@ function validAnnotation(overrides?: Record): Record { - it("accepts a structured annotation draft before screenshot capture", () => { - expect(isPreviewAnnotationPayload(validAnnotation())).toBe(true); - }); - it("rejects screenshots supplied by the guest preload", () => { expect(isPreviewAnnotationPayload(validAnnotation({ screenshot: { dataUrl: "bad" } }))).toBe( false, ); }); - - it("rejects malformed geometry and nested element payloads", () => { - expect( - isPreviewAnnotationPayload( - validAnnotation({ regions: [{ id: "region_1", rect: { x: 0, y: 0, width: "wide" } }] }), - ), - ).toBe(false); - expect( - isPreviewAnnotationPayload( - validAnnotation({ elements: [{ id: "element_1", element: {}, rect: {} }] }), - ), - ).toBe(false); - }); }); diff --git a/apps/desktop/src/preview/RecordingCursor.ts b/apps/desktop/src/preview/RecordingCursor.ts index 4524b0d017b61..5b9fb3c13bc37 100644 --- a/apps/desktop/src/preview/RecordingCursor.ts +++ b/apps/desktop/src/preview/RecordingCursor.ts @@ -11,11 +11,7 @@ import { type RecordingKeyPress, } from "./RecordingInput.ts"; -/** - * Chromium's capture cursor uses native window bounds, which do not follow a - * webview's CSS placement or scale. Draw it in the guest's coordinate space - * while recording, and make the native cursor transparent to avoid two cursors. - */ +/** Draw in guest coordinates; Chromium's native cursor ignores webview CSS placement/scale. Hide it to avoid duplicates. */ export function installRecordingCursor( document: Document, window: Window, diff --git a/apps/desktop/src/preview/RecordingInput.test.ts b/apps/desktop/src/preview/RecordingInput.test.ts index 062685ec29342..0f4f93fb36bf3 100644 --- a/apps/desktop/src/preview/RecordingInput.test.ts +++ b/apps/desktop/src/preview/RecordingInput.test.ts @@ -1,39 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import { recordingKeyLabel, recordingKeysAreSensitive } from "./RecordingInput.ts"; - -const key = ( - value: string, - modifiers: Partial<{ - metaKey: boolean; - ctrlKey: boolean; - altKey: boolean; - shiftKey: boolean; - }> = {}, -) => ({ - key: value, - metaKey: false, - ctrlKey: false, - altKey: false, - shiftKey: false, - ...modifiers, -}); - -describe("recording key labels", () => { - it("formats macOS and other-platform shortcuts", () => { - expect(recordingKeyLabel(key("c", { metaKey: true }), true)).toBe("⌘C"); - expect(recordingKeyLabel(key("c", { ctrlKey: true }), false)).toBe("Ctrl + C"); - expect(recordingKeyLabel(key("Tab", { altKey: true, shiftKey: true }), true)).toBe("⌥⇧⇥"); - }); - it("shows held modifiers once and labels navigation keys", () => { - expect(recordingKeyLabel(key("Meta", { metaKey: true }), true)).toBe("⌘"); - expect(recordingKeyLabel(key("Shift", { shiftKey: true }), false)).toBe("Shift"); - expect(recordingKeyLabel(key("ArrowLeft"), true)).toBe("←"); - expect(recordingKeyLabel(key(" "), false)).toBe("Space"); - }); - it.each(["Dead", "Unidentified", "Process", ""])("excludes composition key %s", (value) => { - expect(recordingKeyLabel(key(value), true)).toBeNull(); - }); -}); +import { recordingKeysAreSensitive } from "./RecordingInput.ts"; describe("recording key privacy", () => { const field = (type: string) => ({ tagName: "INPUT", getAttribute: () => type }); diff --git a/apps/desktop/src/preview/WebviewPreferences.test.ts b/apps/desktop/src/preview/WebviewPreferences.test.ts index 94681b3e046fe..572a290e2b669 100644 --- a/apps/desktop/src/preview/WebviewPreferences.test.ts +++ b/apps/desktop/src/preview/WebviewPreferences.test.ts @@ -6,7 +6,6 @@ function parseWebPreferences(input: string): Record { const out: Record = {}; for (const pair of input.split(",")) { if (pair !== pair.trim()) { - // Electron's parser doesn't trim; surface the bug as undefined-key. out[pair] = pair.split("=")[1]; continue; } @@ -20,34 +19,13 @@ function parseWebPreferences(input: string): Record { describe("PREVIEW_WEBVIEW_PREFERENCES", () => { const parsed = parseWebPreferences(PREVIEW_WEBVIEW_PREFERENCES); - it("contains exactly the three security-critical keys", () => { - expect(Object.keys(parsed).toSorted()).toEqual( - ["contextIsolation", "nodeIntegration", "sandbox"].toSorted(), - ); - }); - it("uses canonical JS-boolean string literals (not yes/no, on/off, 1/0)", () => { - // `value="no"` is a TRUTHY string when assigned to webPreferences.X — so - // `contextIsolation="no"` would silently leave isolation ENABLED. Lock - // the values to `"true"` / `"false"` so the parser does the right thing. for (const value of Object.values(parsed)) { expect(value).toMatch(/^(true|false)$/); } }); - it("disables context isolation (so react-grab can see the page's React DevTools hook)", () => { - expect(parsed["contextIsolation"]).toBe("false"); - }); - it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => { expect(parsed["sandbox"]).toBe("true"); }); - - it("disables nodeIntegration (defense in depth — page never gets Node)", () => { - expect(parsed["nodeIntegration"]).toBe("false"); - }); - - it("contains no whitespace (Electron's parser does not trim)", () => { - expect(PREVIEW_WEBVIEW_PREFERENCES).not.toMatch(/\s/); - }); }); diff --git a/apps/desktop/src/preview/WebviewPreferences.ts b/apps/desktop/src/preview/WebviewPreferences.ts index 4236b78293ab1..4dc9d9aa6b732 100644 --- a/apps/desktop/src/preview/WebviewPreferences.ts +++ b/apps/desktop/src/preview/WebviewPreferences.ts @@ -1,9 +1,3 @@ -/** - * - `sandbox=true`: keeps the OS-level renderer sandbox enabled. Critical - * when paired with `contextIsolation=false` — without sandbox, the preload - * has full Node access (`require`, `fs`, `child_process`, ...) and that - * `require` would land on the page's shared `globalThis`, giving any - * third-party page in the preview full Node + IPC access to the host. - */ +/** sandbox:true is required with contextIsolation:false or the shared page global would expose Node and IPC. */ export const PREVIEW_WEBVIEW_PREFERENCES = "contextIsolation=false,sandbox=true,nodeIntegration=false"; diff --git a/apps/desktop/src/preview/captureErrors.ts b/apps/desktop/src/preview/captureErrors.ts new file mode 100644 index 0000000000000..1284cc7d99b9f --- /dev/null +++ b/apps/desktop/src/preview/captureErrors.ts @@ -0,0 +1,38 @@ +import { PreviewCaptureFailure } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import type { PreviewManagerError } from "./Manager.ts"; + +/** Classify before Electron replaces a rejected IPC Error with its message. */ +export function normalizeCaptureFailure( + error: PreviewManagerError, + stage: PreviewCaptureFailure["stage"], +): PreviewCaptureFailure { + let reason: PreviewCaptureFailure["reason"] = "capture-failed"; + switch (error._tag) { + case "PreviewTabNotFoundError": + case "PreviewWebContentsNotFoundError": + case "PreviewMainWindowClosedError": + reason = "renderer-unavailable"; + break; + case "PreviewWebviewNotInitializedError": + case "PreviewRecordingCaptureUnavailableError": + reason = "capture-unavailable"; + break; + case "PreviewRecordingArmConflictError": + reason = "recording-conflict"; + break; + case "PreviewOperationError": + if (error.operation === "captureScreenshot.capturePage") { + stage = "capture-page"; + if ( + error.cause instanceof Error && + error.cause.message === "Current display surface not available for capture" + ) { + reason = "capture-unavailable"; + } + } + if (Cause.isTimeoutError(error.cause)) reason = "capture-timeout"; + break; + } + return new PreviewCaptureFailure({ reason, stage }); +} diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index a98aa96079e67..832a774577149 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -3,7 +3,6 @@ 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 Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as DesktopConfig from "../app/DesktopConfig.ts"; @@ -109,124 +108,6 @@ describe("DesktopSettings", () => { }), ), ); - it.effect("loads defaults when no settings file exists", () => - withSettings( - Effect.gen(function* () { - const settings = yield* DesktopAppSettings.DesktopAppSettings; - assert.deepEqual(yield* settings.load, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS); - assert.deepEqual(yield* settings.get, DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS); - }), - ), - ); - - it("defaults packaged nightly builds to the nightly update channel", () => { - assert.deepEqual( - DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"), - { - linuxPasswordStore: "auto", - localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, - serverExposureMode: "local-only", - tailscaleServeEnabled: false, - tailscaleServePort: 443, - updateChannel: "nightly", - updateChannelConfiguredByUser: false, - wslBackendEnabled: false, - wslOnly: false, - wslDistro: null, - } satisfies DesktopAppSettings.DesktopSettings, - ); - }); - - it.effect("loads persisted settings and applies semantic updates", () => - withSettings( - Effect.gen(function* () { - const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* writeSettingsPatch({ - linuxPasswordStore: "gnome-libsecret", - serverExposureMode: "network-accessible", - tailscaleServeEnabled: true, - tailscaleServePort: 8443, - updateChannel: "latest", - updateChannelConfiguredByUser: true, - }); - - assert.deepEqual(yield* settings.load, { - linuxPasswordStore: "gnome-libsecret", - localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, - serverExposureMode: "network-accessible", - tailscaleServeEnabled: true, - tailscaleServePort: 8443, - updateChannel: "latest", - updateChannelConfiguredByUser: true, - wslBackendEnabled: false, - wslOnly: false, - wslDistro: null, - } satisfies DesktopAppSettings.DesktopSettings); - - const exposure = yield* settings.setServerExposureMode("local-only"); - assert.isTrue(exposure.changed); - assert.equal(exposure.settings.serverExposureMode, "local-only"); - - const tailscale = yield* settings.setTailscaleServe({ - enabled: true, - port: Option.some(9443), - }); - assert.isTrue(tailscale.changed); - assert.equal(tailscale.settings.tailscaleServePort, 9443); - - const updateChannel = yield* settings.setUpdateChannel("nightly"); - assert.isTrue(updateChannel.changed); - assert.equal(updateChannel.settings.updateChannel, "nightly"); - assert.equal(updateChannel.settings.updateChannelConfiguredByUser, true); - }), - ), - ); - - it.effect("reports the failed desktop settings write operation and path", () => - withSettings( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* fileSystem.makeDirectory(environment.desktopSettingsPath, { recursive: true }); - - const error = yield* settings.setServerExposureMode("network-accessible").pipe(Effect.flip); - assert.instanceOf(error, DesktopAppSettings.DesktopSettingsWriteError); - assert.equal(error.operation, "replace-settings-file"); - assert.equal(error.path, environment.desktopSettingsPath); - assert.exists(error.cause); - assert.equal( - error.message, - `Desktop settings write failed during replace-settings-file at ${environment.desktopSettingsPath}.`, - ); - }), - ), - ); - - it.effect("does not persist no-op semantic updates", () => - withSettings( - Effect.gen(function* () { - const settings = yield* DesktopAppSettings.DesktopAppSettings; - - const exposure = yield* settings.setServerExposureMode("local-only"); - assert.isFalse(exposure.changed); - - const tailscale = yield* settings.setTailscaleServe({ - enabled: false, - port: Option.none(), - }); - assert.isFalse(tailscale.changed); - - const updateChannel = yield* settings.setUpdateChannel("latest"); - assert.isFalse(updateChannel.changed); - assert.equal(updateChannel.settings.updateChannelConfiguredByUser, false); - }), - ), - ); it.effect("falls back to defaults when the settings file is malformed", () => withSettings( @@ -296,45 +177,6 @@ describe("DesktopSettings", () => { ), ); - it.effect( - "normalizes unsupported linux password-store values without dropping other settings", - () => - 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, - `{ - "linuxPasswordStore": "unsupported-store", - "serverExposureMode": "network-accessible", - "tailscaleServeEnabled": true, - "tailscaleServePort": 8443, - "updateChannel": "nightly", - "updateChannelConfiguredByUser": true - }\n`, - ); - - assert.deepEqual(yield* settings.load, { - linuxPasswordStore: "auto", - localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, - serverExposureMode: "network-accessible", - tailscaleServeEnabled: true, - tailscaleServePort: 8443, - updateChannel: "nightly", - updateChannelConfiguredByUser: true, - wslBackendEnabled: false, - wslOnly: false, - wslDistro: null, - } satisfies DesktopAppSettings.DesktopSettings); - }), - ), - ); - it.effect("persists sparse desktop settings documents", () => withSettings( Effect.gen(function* () { @@ -442,33 +284,6 @@ describe("DesktopSettings", () => { ), ); - it.effect("normalizes invalid persisted Tailscale Serve ports", () => - withSettings( - Effect.gen(function* () { - const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* writeSettingsPatch({ - tailscaleServeEnabled: true, - tailscaleServePort: 0, - }); - - assert.deepEqual(yield* settings.load, { - linuxPasswordStore: "auto", - localEnvironmentEnabled: true, - mainWindowBounds: null, - mainWindowMaximized: false, - serverExposureMode: "local-only", - tailscaleServeEnabled: true, - tailscaleServePort: 443, - updateChannel: "latest", - updateChannelConfiguredByUser: false, - wslBackendEnabled: false, - wslOnly: false, - wslDistro: null, - } satisfies DesktopAppSettings.DesktopSettings); - }), - ), - ); - it.effect("persists wsl backend toggle and normalizes invalid distro names", () => withSettings( Effect.gen(function* () { @@ -543,19 +358,4 @@ describe("DesktopSettings", () => { }), ), ); - - it.effect("drops invalid persisted wsl distro values on load", () => - withSettings( - Effect.gen(function* () { - const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* writeSettingsPatch({ - wslBackendEnabled: true, - wslDistro: "bad/name", - }); - const loaded = yield* settings.load; - assert.equal(loaded.wslBackendEnabled, true); - assert.equal(loaded.wslDistro, null); - }), - ), - ); }); diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index 1c131681295fa..433e8127a5098 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -37,8 +37,7 @@ export interface DesktopSettings { readonly updateChannelConfiguredByUser: boolean; readonly wslBackendEnabled: boolean; readonly wslDistro: string | null; - // Changing this requires a desktop restart because the pool's primary spec is - // chosen once at layer init. + // Requires restart because the pool chooses its primary spec at layer initialization. readonly wslOnly: boolean; } @@ -466,7 +465,6 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp }); /** @public */ -/** @public Service construction is part of the canonical Effect module API. */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts b/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts deleted file mode 100644 index 41ba53cf1d43b..0000000000000 --- a/apps/desktop/src/settings/DesktopClientSettings.diagnostics.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -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 Logger from "effect/Logger"; -import * as Option from "effect/Option"; -import * as PlatformError from "effect/PlatformError"; -import * as References from "effect/References"; - -import * as DesktopConfig from "../app/DesktopConfig.ts"; -import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; -import * as DesktopClientSettings from "./DesktopClientSettings.ts"; - -interface LogRecord { - readonly message: unknown; - readonly annotations: Readonly>; -} - -const baseDir = "/virtual-home"; - -function layer(fileSystemLayer: Layer.Layer) { - const layerEnvironment = DesktopEnvironment.layer({ - dirname: "/repo/apps/desktop/src", - homeDirectory: baseDir, - platform: "darwin", - processArch: "x64", - appVersion: "1.2.3", - appPath: "/repo", - isPackaged: true, - resourcesPath: "/missing/resources", - runningUnderArm64Translation: false, - }).pipe( - Layer.provide( - Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), - ), - ); - - return DesktopClientSettings.layer.pipe( - Layer.provideMerge(Layer.mergeAll(layerEnvironment, NodeServices.layer, fileSystemLayer)), - ); -} - -const readWithLogs = (fileSystemLayer: Layer.Layer) => { - const records: Array = []; - const logger = Logger.make(({ fiber, message }) => { - records.push({ - message, - annotations: { ...fiber.getRef(References.CurrentLogAnnotations) }, - }); - }); - - return Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const settings = yield* DesktopClientSettings.DesktopClientSettings; - return { - result: yield* Effect.result(settings.get), - settingsPath: environment.clientSettingsPath, - records, - }; - }).pipe( - Effect.provide( - Layer.mergeAll(layer(fileSystemLayer), Logger.layer([logger], { mergeWithExisting: false })), - ), - ); -}; - -describe("DesktopClientSettings diagnostics", () => { - it.effect("treats a missing settings file as expected without warning", () => - Effect.gen(function* () { - const result = yield* readWithLogs(FileSystem.layerNoop({})); - - if (result.result._tag !== "Success") return assert.fail("expected a successful read"); - assert.isTrue(Option.isNone(result.result.success)); - assert.deepEqual(result.records, []); - }), - ); - - it.effect("reports non-missing filesystem failures and logs the settings path", () => { - const permissionError = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFileString", - pathOrDescriptor: `${baseDir}/userdata/client-settings.json`, - }); - - return Effect.gen(function* () { - const result = yield* readWithLogs( - FileSystem.layerNoop({ - readFileString: () => Effect.fail(permissionError), - }), - ); - - if (result.result._tag !== "Failure") return assert.fail("expected a read failure"); - assert.instanceOf( - result.result.failure, - DesktopClientSettings.DesktopClientSettingsReadError, - ); - assert.strictEqual(result.result.failure.cause, permissionError); - assert.equal(result.records.length, 1); - assert.deepEqual(result.records[0]?.message, [ - "Could not read desktop client settings.", - permissionError, - ]); - assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath); - }); - }); - - it.effect("reports malformed settings documents and logs the settings path", () => - Effect.gen(function* () { - const result = yield* readWithLogs( - FileSystem.layerNoop({ - readFileString: () => Effect.succeed("{not-json"), - }), - ); - - if (result.result._tag !== "Failure") return assert.fail("expected a decode failure"); - assert.instanceOf( - result.result.failure, - DesktopClientSettings.DesktopClientSettingsReadError, - ); - assert.equal(result.result.failure.operation, "decode-document"); - assert.equal(result.records.length, 1); - const message = result.records[0]?.message; - if (!Array.isArray(message)) { - return assert.fail("expected structured warning arguments"); - } - assert.equal(message[0], "Could not decode desktop client settings."); - const schemaError = message[1]; - if (schemaError === null || typeof schemaError !== "object") { - return assert.fail("expected the schema error in the warning"); - } - assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError"); - assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath); - }), - ); -}); diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 75ff38f32260f..51c3d31daae85 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -75,9 +75,6 @@ const clientSettings: ClientSettings = { }; const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema)); -const decodeRecordJson = Schema.decodeEffect( - Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)), -); function layer(baseDir: string) { const layerEnvironment = DesktopEnvironment.layer({ dirname: "/repo/apps/desktop/src", @@ -113,42 +110,6 @@ const withClientSettings = ( }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); describe("DesktopClientSettings", () => { - it.effect("returns none when no client settings file exists", () => - withClientSettings( - Effect.gen(function* () { - const settings = yield* DesktopClientSettings.DesktopClientSettings; - assert.isTrue(Option.isNone(yield* settings.get)); - }), - ), - ); - - it.effect("persists and reloads client settings", () => - withClientSettings( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const settings = yield* DesktopClientSettings.DesktopClientSettings; - yield* settings.set(clientSettings); - - assert.deepEqual(yield* settings.get, Option.some(clientSettings)); - assert.deepEqual( - yield* decodeClientSettingsJson( - yield* fileSystem.readFileString(environment.clientSettingsPath), - ), - clientSettings, - ); - assert.isFalse( - Object.hasOwn( - yield* decodeRecordJson( - yield* fileSystem.readFileString(environment.clientSettingsPath), - ), - "settings", - ), - ); - }), - ), - ); - it.effect("saves through a symlinked client settings file without replacing the link", () => withClientSettings( Effect.gen(function* () { @@ -228,29 +189,6 @@ describe("DesktopClientSettings", () => { ), ); - it.effect("reports the failed client settings write operation and path", () => - withClientSettings( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const settings = yield* DesktopClientSettings.DesktopClientSettings; - yield* fileSystem.makeDirectory(environment.clientSettingsPath, { recursive: true }); - - const error = yield* settings.set(clientSettings).pipe(Effect.flip); - assert.instanceOf(error, DesktopClientSettings.DesktopClientSettingsWriteError); - assert.equal(error.operation, "replace-settings-file"); - assert.equal(error.path, environment.clientSettingsPath); - assert.instanceOf(error.cause, PlatformError.PlatformError); - assert.isString(error.cause.stack); - assert.equal( - error.message, - `Desktop client settings write failed during replace-settings-file at ${environment.clientSettingsPath}.`, - ); - assert.notInclude(error.message, error.cause.message); - }), - ), - ); - it.effect("loads lenient direct client settings documents", () => withClientSettings( Effect.gen(function* () { @@ -300,23 +238,8 @@ describe("DesktopClientSettings", () => { ), ); - it.effect("loads defaults from empty client settings documents", () => - withClientSettings( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const settings = yield* DesktopClientSettings.DesktopClientSettings; - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(environment.clientSettingsPath, "{}\n"); - - assert.deepEqual(yield* settings.get, Option.some(yield* decodeClientSettingsJson("{}"))); - }), - ), - ); - it.effect.each([ { label: "malformed JSON", contents: "{not-json" }, - { label: "invalid direct settings", contents: '{"fontSizeCode":"large"}' }, { label: "invalid legacy settings", contents: '{"settings":{"fontSizeCode":"large"}}' }, ])("reports $label without treating the settings file as absent", (document) => withClientSettings( diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts index 27ec38f46c59c..0001548f4534f 100644 --- a/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts +++ b/apps/desktop/src/settings/DesktopSavedEnvironments.test.ts @@ -4,10 +4,8 @@ import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/co import * as Effect from "effect/Effect"; import * as Base64 from "effect/encoding/Base64"; import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as DesktopConfig from "../app/DesktopConfig.ts"; @@ -155,17 +153,6 @@ const withSavedEnvironments = ( }).pipe(Effect.provide(NodeServices.layer), Effect.scoped); describe("DesktopSavedEnvironments", () => { - it.effect("reads saved environment metadata", () => - withSavedEnvironments( - Effect.gen(function* () { - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* seedSavedEnvironmentRegistry(); - - assert.deepEqual(yield* savedEnvironments.getRegistry, [savedRegistryRecord]); - }), - ), - ); - it.effect("loads lenient saved environment registry documents", () => withSavedEnvironments( Effect.gen(function* () { @@ -216,30 +203,6 @@ describe("DesktopSavedEnvironments", () => { ), ); - it.effect("reports invalid saved secret encoding without exposing the secret", () => - withSavedEnvironments( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* seedSavedEnvironmentRegistry("%%%"); - - const error = yield* savedEnvironments - .getSecret(savedRegistryRecord.environmentId) - .pipe(Effect.flip); - assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentSecretDecodeError); - assert.equal(error.environmentId, savedRegistryRecord.environmentId); - assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath); - assert.equal(error.field, "encryptedBearerToken"); - assert.exists(error.cause); - assert.equal( - error.message, - `Failed to decode encryptedBearerToken for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`, - ); - assert.notInclude(error.message, "%%%"); - }), - ), - ); - it.effect("returns no secret while encryption is unavailable", () => withSavedEnvironments( Effect.gen(function* () { @@ -254,114 +217,4 @@ describe("DesktopSavedEnvironments", () => { { availableSecretStorage: false }, ), ); - - it.effect("adds saved-environment context to safe storage availability failures", () => { - const cause = new Error("safe storage unavailable"); - return withSavedEnvironments( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* seedSavedEnvironmentRegistry(Base64.encode(textEncoder.encode("enc:bearer-token"))); - - const error = yield* savedEnvironments - .getSecret(savedRegistryRecord.environmentId) - .pipe(Effect.flip); - - assert.instanceOf( - error, - DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError, - ); - assert.equal(error.operation, "check-encryption-availability"); - assert.equal(error.environmentId, savedRegistryRecord.environmentId); - assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath); - assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError); - const availabilityError = - error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError; - assert.strictEqual(availabilityError.cause, cause); - assert.equal( - error.message, - `Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`, - ); - assert.notEqual(error.message, availabilityError.message); - }), - { availabilityError: cause }, - ); - }); - - it.effect("treats empty saved environment documents as empty", () => - withSavedEnvironments( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{}\n"); - - assert.deepEqual(yield* savedEnvironments.getRegistry, []); - assert.isTrue( - Option.isNone(yield* savedEnvironments.getSecret(savedRegistryRecord.environmentId)), - ); - }), - ), - ); - - it.effect("surfaces malformed saved environment documents", () => - withSavedEnvironments( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const fileSystem = yield* FileSystem.FileSystem; - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments; - yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); - yield* fileSystem.writeFileString(environment.savedEnvironmentRegistryPath, "{not-json"); - - const registryError = yield* savedEnvironments.getRegistry.pipe(Effect.flip); - assert.instanceOf( - registryError, - DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError, - ); - assert.equal(registryError.registryPath, environment.savedEnvironmentRegistryPath); - assert.exists(registryError.cause); - const secretError = yield* savedEnvironments - .getSecret(savedRegistryRecord.environmentId) - .pipe(Effect.flip); - assert.instanceOf( - secretError, - DesktopSavedEnvironments.DesktopSavedEnvironmentsDocumentDecodeError, - ); - }), - ), - ); - - it.effect("reports saved environment filesystem reads separately from document decoding", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const baseFileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({ - prefix: "t3-desktop-saved-environments-test-", - }); - const registryPath = path.join(baseDir, "userdata", "saved-environments.json"); - const permissionError = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFileString", - pathOrDescriptor: registryPath, - }); - const layerFileSystem = Layer.succeed( - FileSystem.FileSystem, - FileSystem.makeNoop({ - readFileString: () => Effect.fail(permissionError), - }), - ); - const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments.pipe( - Effect.provide(layer(baseDir, undefined, layerFileSystem)), - ); - - const error = yield* savedEnvironments.getRegistry.pipe(Effect.flip); - assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsReadError); - assert.equal(error.registryPath, registryPath); - assert.strictEqual(error.cause, permissionError); - assert.equal(error.message, `Failed to read desktop saved environments at ${registryPath}.`); - assert.notEqual(error.message, permissionError.message); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); }); diff --git a/apps/desktop/src/settings/DesktopSavedEnvironments.ts b/apps/desktop/src/settings/DesktopSavedEnvironments.ts index 248fb9b6f8482..cccc0585024af 100644 --- a/apps/desktop/src/settings/DesktopSavedEnvironments.ts +++ b/apps/desktop/src/settings/DesktopSavedEnvironments.ts @@ -221,7 +221,7 @@ function decodeSecretBytes( ); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index aee5a0bc81b54..9d12ed5a07fe6 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -1,10 +1,10 @@ +// @effect-diagnostics nodeBuiltinImport:off -- The process fixture runs real shell commands with isolated config files. import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as PlatformError from "effect/PlatformError"; -import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; @@ -19,10 +19,6 @@ vi.mock("node:os", { spy: true }); const textEncoder = new TextEncoder(); -const isDesktopShellEnvironmentCommandError = Schema.is( - DesktopShellEnvironment.DesktopShellEnvironmentCommandError, -); - function envOutput(values: Readonly>): string { return Object.entries(values) .flatMap(([name, value]) => [ @@ -145,52 +141,6 @@ describe("DesktopShellEnvironment", () => { }), ); - it.effect.each(["darwin", "linux"] as const)( - "uses the account shell when SHELL is missing on %s", - (platform) => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { PATH: "/usr/bin" }; - const commands: string[] = []; - - yield* runShellEnvironment({ - env, - platform, - userShell: "/usr/local/bin/fish", - handler: (command) => { - if (command._tag !== "StandardCommand") return ""; - commands.push(command.command); - return envOutput({ PATH: "/home/test/.local/bin:/usr/bin" }); - }, - }); - - assert.deepEqual(commands, ["/usr/local/bin/fish"]); - assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin"); - }), - ); - - it.effect("tries the account shell before the platform fallback when SHELL has no PATH", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { SHELL: "/bin/missing", PATH: "/usr/bin" }; - const commands: string[] = []; - - yield* runShellEnvironment({ - env, - platform: "linux", - userShell: "/usr/local/bin/fish", - handler: (command) => { - if (command._tag !== "StandardCommand") return ""; - commands.push(command.command); - return command.command === "/usr/local/bin/fish" - ? envOutput({ PATH: "/home/test/.local/bin:/usr/bin" }) - : ""; - }, - }); - - assert.deepEqual(commands, ["/bin/missing", "/usr/local/bin/fish"]); - assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin"); - }), - ); - it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { @@ -220,72 +170,6 @@ describe("DesktopShellEnvironment", () => { }), ); - it.effect("preserves inherited POSIX values when present", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - SSH_AUTH_SOCK: "/tmp/inherited.sock", - }; - - yield* runShellEnvironment({ - env, - platform: "darwin", - handler: () => - envOutput({ - PATH: "/opt/homebrew/bin:/usr/bin", - SSH_AUTH_SOCK: "/tmp/login-shell.sock", - }), - }); - - assert.equal(env.PATH, "/opt/homebrew/bin:/usr/bin"); - assert.equal(env.SSH_AUTH_SOCK, "/tmp/inherited.sock"); - }), - ); - - it.effect("hydrates the locale from the login shell on macOS", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - }; - - yield* runShellEnvironment({ - env, - platform: "darwin", - handler: () => - envOutput({ - PATH: "/opt/homebrew/bin:/usr/bin", - LANG: "de_DE.UTF-8", - }), - }); - - assert.equal(env.LANG, "de_DE.UTF-8"); - }), - ); - - it.effect("preserves an inherited locale over the login shell on macOS", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - LANG: "en_US.UTF-8", - }; - - yield* runShellEnvironment({ - env, - platform: "darwin", - handler: () => - envOutput({ - PATH: "/opt/homebrew/bin:/usr/bin", - LANG: "de_DE.UTF-8", - }), - }); - - assert.equal(env.LANG, "en_US.UTF-8"); - }), - ); - it.effect("does not mix login-shell locale categories into an inherited locale", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { @@ -328,47 +212,6 @@ describe("DesktopShellEnvironment", () => { }), ); - it.effect("does not apply the locale fallback on linux", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - }; - - yield* runShellEnvironment({ - env, - platform: "linux", - handler: () => envOutput({ PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin" }), - }); - - assert.equal(env.LANG, undefined); - }), - ); - - it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - }; - - yield* runShellEnvironment({ - env, - platform: "linux", - handler: () => - envOutput({ - PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin", - SSH_AUTH_SOCK: "/tmp/secretive.sock", - T3CODE_TELEMETRY_ENABLED: "false", - }), - }); - - assert.equal(env.PATH, "/home/linuxbrew/.linuxbrew/bin:/usr/bin"); - assert.equal(env.SSH_AUTH_SOCK, "/tmp/secretive.sock"); - assert.equal(env.T3CODE_TELEMETRY_ENABLED, "false"); - }), - ); - it.effect("hydrates missing CA trust variables from the login shell", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { @@ -556,66 +399,4 @@ describe("DesktopShellEnvironment", () => { assert.equal(env.XDG_SESSION_TYPE, "wayland"); }), ); - - it.effect("overrides stale dbus session addresses from the login shell", () => - Effect.gen(function* () { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/zsh", - PATH: "/usr/bin", - DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus", - }; - - yield* runShellEnvironment({ - env, - platform: "linux", - handler: () => - envOutput({ - PATH: "/usr/bin", - DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus", - }), - }); - - assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus"); - }), - ); - - it.effect("logs command failures with safe probe context and the exact cause", () => { - const env: NodeJS.ProcessEnv = { - SHELL: "/bin/bash", - PATH: "/usr/bin", - }; - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "ChildProcess", - method: "spawn", - pathOrDescriptor: "/bin/bash", - }); - const messages: Array = []; - const logger = Logger.make(({ message }) => { - messages.push(message); - }); - - return runShellEnvironment({ - env, - platform: "linux", - handler: () => "", - failure: cause, - }).pipe( - Effect.andThen( - Effect.sync(() => { - const errors = messages - .flatMap((message) => (Array.isArray(message) ? message : [message])) - .filter(isDesktopShellEnvironmentCommandError); - assert.lengthOf(errors, 1); - assert.equal(errors[0]?.probe, "login-shell"); - assert.equal(errors[0]?.executable, "bash"); - assert.equal(errors[0]?.argumentCount, 2); - assert.notProperty(errors[0] ?? {}, "args"); - assert.equal(errors[0]?.cause, cause); - assert.notInclude(errors[0]?.message ?? "", cause.message); - }), - ), - Effect.provide(Logger.layer([logger], { mergeWithExisting: false })), - ); - }); }); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 8fa8a60b2e62b..c80fe9b87cd6a 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -1,4 +1,8 @@ -import { listLoginShellCandidates, setWindowsPath } from "@t3tools/shared/shell"; +import { + buildEnvironmentCaptureCommand, + listLoginShellCandidates, + setWindowsPath, +} from "@t3tools/shared/shell"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -199,17 +203,6 @@ const logShellEnvironmentCommandError = ( }), ); -const capturePosixEnvironmentCommand = (names: ReadonlyArray) => - names - .map((name) => { - return [ - `printf '%s\\n' '${startMarker(name)}'`, - `printenv ${name} || true`, - `printf '%s\\n' '${endMarker(name)}'`, - ].join("; "); - }) - .join("; "); - const captureWindowsEnvironmentCommand = (names: ReadonlyArray) => [ "$ErrorActionPreference = 'Stop'", @@ -320,7 +313,7 @@ const readLoginShellEnvironment = ( : runCommandOutput({ probe: "login-shell", command: shell, - args: ["-ilc", capturePosixEnvironmentCommand(names)], + args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)], timeout: LOGIN_SHELL_TIMEOUT, }).pipe(Effect.map((output) => extractEnvironment(output, names))); @@ -367,11 +360,6 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin function* ( config: ShellEnvironmentConfig, ): Effect.fn.Return { - // Concurrent, not sequential: these two probes are independent (only their - // results are combined below) and each spawns its own PowerShell. Run in - // series they sit at offset 0 of desktop.startup, before anything else, and - // launch traces measured them at 2718ms then 2066ms — the entire 4.8s - // startup span, of which desktop.bootstrap is ~30ms. const [noProfile, profile] = yield* Effect.all( [ readWindowsEnvironment(["PATH"], { loadProfile: false }), @@ -439,9 +427,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "XDG_SESSION_TYPE", - // mise's record of the PATH entries it added. It must travel with the - // shell's PATH, or `mise x` can rebuild PATH behind a same-named wrapper - // (`exec mise x claude -- claude`) that then re-runs itself forever. + // Forward mise's PATH delta too, or mise x can rebuild PATH into a recursive same-named wrapper. "__MISE_DIFF", ] as const; for (const name of shellPreferredEnvNames) { @@ -459,9 +445,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "XDG_DATA_HOME", "XDG_RUNTIME_DIR", "WAYLAND_DISPLAY", - // CA trust set in the shell profile. Without it, a Node or OpenSSL build - // that has no bundled roots (a shared-OpenSSL node on PATH) cannot verify - // TLS, so provider updaters and agents fail to reach their registries. + // Shell CA settings are required by Node/OpenSSL builds without bundled roots for registry TLS. "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", @@ -472,8 +456,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix } } - // Locale variables form one precedence group: LC_ALL can override an inherited - // LANG or LC_CTYPE, so only hydrate the group when the process has none of them. + // Hydrate locale variables together; inherited LC_ALL can override LANG or LC_CTYPE. if ( config.platform === "darwin" && LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name]))) @@ -485,11 +468,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix } } - // GUI launches inherit no locale from launchd, so spawned agents land in the C - // locale and pbcopy decodes their UTF-8 output as MacRoman. Older supported - // macOS releases do not provide C.UTF-8, so set only LC_CTYPE to a UTF-8 locale - // available on those releases. Leaving LANG unset keeps C-stable collation and - // formatting, so output parsing is unaffected. + // launchd lacks locale; UTF-8 LC_CTYPE fixes pbcopy's MacRoman decoding without changing C formatting or collation. if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) { config.env.LC_CTYPE = FALLBACK_LC_CTYPE; } @@ -529,7 +508,7 @@ const installShellEnvironment = ( return Effect.succeed(false); }; -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/snapShot/ActiveWindow.test.ts b/apps/desktop/src/snapShot/ActiveWindow.test.ts deleted file mode 100644 index ddc760cbb9d09..0000000000000 --- a/apps/desktop/src/snapShot/ActiveWindow.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { assert, beforeEach, it, vi } from "vite-plus/test"; - -const { execFileMock, loadWindowsForegroundApiMock } = vi.hoisted(() => ({ - execFileMock: vi.fn(), - loadWindowsForegroundApiMock: vi.fn(), -})); - -vi.mock("node:child_process", () => ({ execFile: execFileMock })); -vi.mock("../electron/WindowsForeground.ts", () => ({ - loadWindowsForegroundApi: loadWindowsForegroundApiMock, -})); - -import { activeWindow } from "./ActiveWindow.ts"; - -beforeEach(() => { - execFileMock.mockReset(); - loadWindowsForegroundApiMock.mockReset(); -}); - -function stubMacLookup(stdout: string) { - execFileMock.mockImplementation( - ( - _file: string, - _args: ReadonlyArray, - _options: unknown, - callback: (error: Error | null, stdout: string) => void, - ) => callback(null, stdout), - ); -} - -it("parses the frontmost macOS window from the osascript lookup", async () => { - stubMacLookup( - JSON.stringify({ - id: 42, - title: "main.ts", - bounds: { x: 10, y: 20, width: 800, height: 600 }, - owner: { - name: "Editor", - processId: 123, - path: "/Applications/Editor.app", - bundleId: "com.example.editor", - }, - }) + "\n", - ); - - const window = await activeWindow("darwin"); - - assert.deepEqual(window, { - platform: "macos", - id: 42, - title: "main.ts", - bounds: { x: 10, y: 20, width: 800, height: 600 }, - owner: { - name: "Editor", - processId: 123, - path: "/Applications/Editor.app", - bundleId: "com.example.editor", - }, - }); - const [file, args] = execFileMock.mock.calls[0]!; - assert.strictEqual(file, "/usr/bin/osascript"); - assert.deepEqual(args.slice(0, 3), ["-l", "JavaScript", "-e"]); - assert.lengthOf(loadWindowsForegroundApiMock.mock.calls, 0); -}); - -it("omits an empty macOS bundle identifier", async () => { - stubMacLookup( - JSON.stringify({ - id: 7, - title: "", - bounds: { x: 0, y: 0, width: 1, height: 1 }, - owner: { name: "cli", processId: 9, path: "", bundleId: "" }, - }), - ); - - const window = await activeWindow("darwin"); - - assert.deepEqual(window?.owner, { name: "cli", processId: 9, path: "" }); -}); - -it("resolves undefined when macOS has no frontmost window", async () => { - stubMacLookup("\n"); - - assert.isUndefined(await activeWindow("darwin")); -}); - -it("composes the Windows foreground window from Win32 calls", async () => { - const api = { - getForegroundWindow: vi.fn(() => 0x1_f123_4567n), - getWindowRect: vi.fn(() => ({ x: 10, y: 20, width: 800, height: 600 })), - getWindowThreadAndProcessId: vi.fn(() => ({ threadId: 5, processId: 123 })), - getProcessImagePath: vi.fn(() => "C:\\Program Files\\Editor\\editor.exe"), - getWindowText: vi.fn(() => "main.ts - Editor"), - }; - loadWindowsForegroundApiMock.mockResolvedValue(api); - - const window = await activeWindow("win32"); - - assert.deepEqual(window, { - platform: "windows", - id: 0x1_f123_4567, - title: "main.ts - Editor", - bounds: { x: 10, y: 20, width: 800, height: 600 }, - owner: { name: "editor.exe", processId: 123, path: "C:\\Program Files\\Editor\\editor.exe" }, - }); - assert.deepEqual(api.getWindowRect.mock.calls, [[0x1_f123_4567n]]); - assert.deepEqual(api.getProcessImagePath.mock.calls, [[123]]); - assert.lengthOf(execFileMock.mock.calls, 0); -}); - -it("resolves undefined when Windows reports no foreground window", async () => { - const api = { - getForegroundWindow: vi.fn(() => 0n), - getWindowRect: vi.fn(), - getWindowThreadAndProcessId: vi.fn(), - getProcessImagePath: vi.fn(), - getWindowText: vi.fn(), - }; - loadWindowsForegroundApiMock.mockResolvedValue(api); - - assert.isUndefined(await activeWindow("win32")); - assert.lengthOf(api.getWindowRect.mock.calls, 0); -}); - -it("resolves undefined on other platforms without querying the OS", async () => { - assert.isUndefined(await activeWindow("linux")); - assert.lengthOf(execFileMock.mock.calls, 0); - assert.lengthOf(loadWindowsForegroundApiMock.mock.calls, 0); -}); diff --git a/apps/desktop/src/snapShot/ActiveWindow.ts b/apps/desktop/src/snapShot/ActiveWindow.ts index f62669a39bf36..20f56cc19442c 100644 --- a/apps/desktop/src/snapShot/ActiveWindow.ts +++ b/apps/desktop/src/snapShot/ActiveWindow.ts @@ -6,10 +6,7 @@ import * as Schema from "effect/Schema"; import { loadWindowsForegroundApi } from "../electron/WindowsForeground.ts"; -/** - * `id` is the CGWindowNumber on macOS and the HWND on Windows, which is what - * the capture backends key on. - */ +/** id is CGWindowNumber on macOS or HWND on Windows, matching the capture backend. */ export type ActiveWindow = { readonly platform: "macos" | "windows"; readonly id: number; diff --git a/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts b/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts index ea6e176b82047..e2a3b913e6487 100644 --- a/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts +++ b/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts @@ -2,10 +2,8 @@ import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeOS from "node:os"; -import * as NodeChildProcess from "node:child_process"; -import * as NodeUtil from "node:util"; import { afterEach, beforeEach, expect, it as test, vi } from "vite-plus/test"; -import { CaptureShortcutConfig, niriCaptureConfigPath } from "./CaptureShortcutConfig.ts"; +import { CaptureShortcutConfig } from "./CaptureShortcutConfig.ts"; import { captureConfigBinding } from "./captureConfigEdit.ts"; // oxlint-disable-next-line t3code/no-global-process-runtime -- Test collection checks the host before starting these Linux-native filesystem tests. @@ -50,12 +48,6 @@ it("reads without writing, then applies only the approved diff with a backup", a expect(tools.validateNiri).toHaveBeenCalledOnce(); await expect(setup.apply(preview.id, "niri")).rejects.toThrow("expired"); }); -it("refuses apply without a preview or for the wrong desktop", async () => { - await expect(setup.apply("invented", "niri")).rejects.toThrow("expired"); - const preview = await setup.preview(target(), install); - await expect(setup.apply(preview.id, "hyprland")).rejects.toThrow("expired"); - expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before); -}); it("rechecks Hyprland conflicts before writing", async () => { const hypr = { ...target(), @@ -80,11 +72,6 @@ it("notices an optional include created while the diff is open", async () => { await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since"); expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.before); }); -it("invalidates an earlier proposal when another config is opened", async () => { - const first = await setup.preview(target(), install); - await setup.preview(target(), { ...install, shortcut: "Ctrl+Alt+Y" }); - await expect(setup.apply(first.id, "niri")).rejects.toThrow("expired"); -}); it("does not overwrite edits made after preview", async () => { const preview = await setup.preview(target(), install); await NodeFSP.appendFile(path, "// edited elsewhere\n"); @@ -243,52 +230,6 @@ it("detects conflicts in included Niri configs without changing either file", as await expect(setup.preview(target(), install)).rejects.toThrow("already used"); expect((await NodeFSP.readdir(directory)).sort()).toEqual(["config.kdl", "keys.kdl"]); }); -it("detects included config changes before applying", async () => { - await NodeFSP.appendFile(path, 'include "keys.kdl"\n'); - const included = NodePath.join(directory, "keys.kdl"); - await NodeFSP.writeFile(included, "binds { Ctrl+Alt+Q { quit; } }"); - const preview = await setup.preview(target(), install); - await NodeFSP.writeFile(included, "binds { Ctrl+Shift+2 { quit; } }"); - await expect(setup.apply(preview.id, "niri")).rejects.toThrow("changed since"); -}); -it("rejects a conflict from another Hyprland config or dynamic Lua bind", async () => { - const hypr = { - ...target(), - desktop: "hyprland" as const, - path: NodePath.join(directory, "bindings.lua"), - }; - await NodeFSP.writeFile(hypr.path, "-- user bindings\n"); - tools.hyprlandBindings.mockResolvedValue([ - { modmask: 5, key: "2", dispatcher: "__lua", arg: "92" }, - ]); - await expect(setup.preview(hypr, install)).rejects.toThrow("already used"); - expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe("-- user bindings\n"); -}); -it("reloads Hyprland after apply, but not after read", async () => { - const hypr = { - ...target(), - desktop: "hyprland" as const, - path: NodePath.join(directory, "hyprland.conf"), - }; - await NodeFSP.writeFile(hypr.path, "# preferences\n"); - const preview = await setup.preview(hypr, install); - expect(tools.reloadHyprland).not.toHaveBeenCalled(); - await setup.apply(preview.id, "hyprland"); - expect(tools.reloadHyprland).toHaveBeenCalledOnce(); -}); -it("reports reload failure separately from a successfully saved config", async () => { - const hypr = { - ...target(), - desktop: "hyprland" as const, - path: NodePath.join(directory, "hyprland.conf"), - }; - await NodeFSP.writeFile(hypr.path, "# preferences\n"); - const preview = await setup.preview(hypr, install); - tools.reloadHyprland.mockRejectedValue(new Error("Compositor stopped")); - const result = await setup.apply(preview.id, "hyprland"); - expect(result.warning).toContain("Config saved"); - expect(await NodeFSP.readFile(hypr.path, "utf8")).toBe(preview.after); -}); it("does not edit Omarchy's shipped defaults", async () => { const defaults = NodePath.join(directory, "omarchy", "default", "hypr"); await NodeFSP.mkdir(defaults, { recursive: true }); @@ -298,46 +239,3 @@ it("does not edit Omarchy's shipped defaults", async () => { setup.preview({ ...target(), desktop: "hyprland", path: file }, install), ).rejects.toThrow("not system or Omarchy"); }); -it("honors NIRI_CONFIG and XDG_CONFIG_HOME", () => { - expect( - niriCaptureConfigPath("/home/test", { - NIRI_CONFIG: "/custom/test.kdl", - XDG_CONFIG_HOME: "/config", - }), - ).toBe("/custom/test.kdl"); - expect(niriCaptureConfigPath("/home/test", { XDG_CONFIG_HOME: "/config" })).toBe( - "/config/niri/config.kdl", - ); - expect(niriCaptureConfigPath("/home/test", {})).toBe("/home/test/.config/niri/config.kdl"); -}); -it("preserves a UTF-8 BOM through preview and apply", async () => { - await NodeFSP.writeFile(path, "\uFEFFbinds {}\r\n"); - const preview = await setup.preview(target(), install); - await setup.apply(preview.id, "niri"); - expect((await NodeFSP.readFile(path)).subarray(0, 3)).toEqual(Buffer.from([0xef, 0xbb, 0xbf])); -}); -it("the installed Niri parser accepts the generated edit and its relative includes", async (context) => { - try { - await NodeUtil.promisify(NodeChildProcess.execFile)("niri", ["--version"]); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - context.skip(); - return; - } - throw error; - } - await NodeFSP.appendFile(path, 'include "keys.kdl"\n'); - await NodeFSP.writeFile( - NodePath.join(directory, "keys.kdl"), - "binds {\n Ctrl+Alt+Q { quit; }\n}\n", - ); - const checked = new CaptureShortcutConfig(NodeOS.homedir(), { - ...tools, - validateNiri: async (file) => { - await NodeUtil.promisify(NodeChildProcess.execFile)("niri", ["validate", "--config", file]); - }, - }); - const preview = await checked.preview(target(), install); - await checked.apply(preview.id, "niri"); - expect(await NodeFSP.readFile(path, "utf8")).toBe(preview.after); -}); diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index aa56fede5e992..dc3aa093f9cf6 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -11,7 +11,6 @@ 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 Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; @@ -476,12 +475,7 @@ const decodePendingMetadata = Schema.decodeUnknownEffect( Schema.fromJsonString(DesktopPendingSnapShot), ); -import { - SnapShotTransition, - snapShotAnimationDurationMs, - snapShotAnimationDisplayBounds, - snapShotAnimationOverlayBounds, -} from "./SnapShotTransition.ts"; +import { SnapShotTransition, snapShotAnimationDisplayBounds } from "./SnapShotTransition.ts"; const layerTest = ( platform: NodeJS.Platform, fileSystemOverrides: Parameters[0] = {}, @@ -498,6 +492,7 @@ const layerTest = ( DesktopEnvironment.DesktopEnvironment, DesktopEnvironment.DesktopEnvironment.of({ platform, + displayName: "T3 Code (Dev)", stateDir: "/state", linuxDesktopEntryName: "com.t3tools.T3Code.desktop", appRoot: "/repo", @@ -759,115 +754,67 @@ function concurrentCaptureFixture(platform: NodeJS.Platform, animations: boolean }; } -it.effect("rejects desktop config changes outside Niri or Hyprland", () => - Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const previewError = yield* service - .previewConfig({ operation: "install", chooseFile: false }) - .pipe(Effect.flip); - const applyError = yield* service.applyConfig("unapproved-preview").pipe(Effect.flip); - assert.equal(previewError.action, "preview-config"); - assert.equal(applyError.action, "apply-config"); - for (const error of [previewError, applyError]) { - assert.equal(error.reason, "unsupported-session"); - assert.equal(error.message, "Config setup requires a Niri or Hyprland session."); - } - }), - ).pipe(Effect.provide(layerTest("win32"))), -); - -it.effect("reads and acknowledges queued captures through Effect services", () => { - const captureId = "12345678-1234-1234-1234-123456789abc"; - const captureDirectory = "/state/snap-shots"; - const metadataPath = captureDirectory + "/" + captureId + ".json"; - const imagePath = captureDirectory + "/" + captureId + ".png"; - const removed: Array = []; - const metadata = JSON.stringify({ - id: captureId, - name: "window.png", - mimeType: "image/png", - sizeBytes: 3, - source: { - kind: "snap-shot", - capturedAt: "2026-08-24T11:00:00.000Z", - appName: "Editor", - windowTitle: "main.ts", - }, - }); - const layer = layerTest("linux", { - readDirectory: () => Effect.succeed([captureId + ".json", "invalid.json"]), - readFileString: (filePath) => Effect.succeed(filePath === metadataPath ? metadata : "invalid"), - readFile: () => Effect.succeed(new Uint8Array([1, 2, 3])), - remove: (filePath) => - Effect.sync(() => { - removed.push(filePath); - }), - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const pending = yield* service.listPending; - assert.deepEqual( - pending.map((capture) => capture.id), - [captureId], - ); - - const capture = yield* service.read(captureId); - assert.strictEqual(capture.dataUrl, "data:image/png;base64,AQID"); - - yield* service.acknowledge(captureId); - assert.deepEqual(removed.sort(), [imagePath, metadataPath].sort()); - }), - ).pipe(Effect.provide(layer)); -}); +it.effect.each(["darwin", "win32"] as const)( + "drops shortcut bursts during flight and accepts a fresh capture after landing on %s", + (platform) => { + const fixture = concurrentCaptureFixture(platform, true); + fixture.releaseAll(); + const flying = Promise.withResolvers(); + const heldFlights: Array<() => void> = []; + const push = heldFlights.push.bind(heldFlights); + vi.spyOn(heldFlights, "push").mockImplementation((...resolvers) => { + const count = push(...resolvers); + flying.resolve(); + return count; + }); + transitionScriptState.heldFlights = heldFlights; + return Effect.scoped( + Effect.gen(function* () { + const service = yield* DesktopSnapShot.make; + yield* service.configure(fixture.settings); + yield* Effect.promise(fixture.trigger); + const firstId = fixture.readyIds[0]!; + const landing = yield* service + .setAnimationDestination(firstId, { + frame: { x: 100, y: 400, width: 208, height: 112 }, + backgroundColor: "#fff", + borderColor: "#ccc", + borderWidth: 1, + cornerRadius: 8, + scaleFactor: 1, + }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.promise(() => flying.promise); + const overlayCount = flashWindows.length; + + for (let repeat = 0; repeat < 20; repeat++) { + yield* TestClock.adjust("200 millis"); + yield* Effect.promise(fixture.trigger); + } + assert.equal(fixture.state.snapshots, 1); + assert.lengthOf(fixture.readyIds, 1); + assert.lengthOf(flashWindows, overlayCount); + assert.isTrue(flashWindows.every((window) => !window.destroyed)); -it.effect("captures the active Windows window without enumerating desktop sources", () => { - const png = Buffer.from([1, 2, 3]); - const active = { - platform: "windows", - id: 42, - title: "Untitled - Paint", - owner: { name: "Paint.exe", processId: 123, path: "C:\\Windows\\System32\\mspaint.exe" }, - bounds: { x: 10, y: 20, width: 800, height: 600 }, - } as const; - activeWindowMock.mockReset().mockResolvedValue(active); - accessibilityByPidMock.mockReset().mockResolvedValue({ children: async () => [] }); - regionCaptureMock.mockReset().mockResolvedValue({ width: 800, height: 600, png }); - getSourcesMock.mockReset(); - getFileIconMock.mockReset().mockResolvedValue(fakeIcon("file")); - const writtenFiles: Array<[string, Uint8Array]> = []; - let metadata = ""; - const layer = layerTest("win32", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: (path, bytes) => - Effect.sync(() => { - writtenFiles.push([path, bytes]); - }), - writeFileString: (_, text) => - Effect.sync(() => { - metadata = text; + for (const finish of heldFlights) finish(); + yield* Fiber.join(landing); + yield* Effect.promise(fixture.trigger); + assert.equal(fixture.state.snapshots, 2); + assert.lengthOf(fixture.readyIds, 2); + assert.isTrue(fixture.second.oldOverlaysCleared); }), - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings()); - yield* service.capture; - - assert.deepEqual(regionCaptureMock.mock.calls, [[active.bounds]]); - assert.lengthOf(getSourcesMock.mock.calls, 0); - assert.deepEqual(getFileIconMock.mock.calls, [[active.owner.path, { size: "normal" }]]); - assert.deepEqual(writtenFiles[0]?.[1], png); - const saved = yield* decodePendingMetadata(metadata); - assert.equal(saved.source.appName, "Paint"); - assert.match(saved.source.appIconDataUrl ?? "", /base64,file:/); - }), - ).pipe(Effect.provide(layer)); -}); + ).pipe( + Effect.provide(fixture.layer), + Effect.ensuring( + Effect.sync(() => { + for (const finish of heldFlights) finish(); + transitionScriptState.heldFlights = null; + fixture.reset(); + }), + ), + ); + }, +); it.effect.each([ { length: 1_000, suffix: "", expectedLength: 1_000 }, @@ -923,174 +870,6 @@ it.effect.each([ }, ); -it.effect.each(["win32", "darwin", "linux"] as const)( - "captures the foreground window in place from the shortcut on %s", - (platform) => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - registerShortcutMock.mockReset().mockReturnValue(true); - mediaAccessStatusMock.mockReturnValue("granted"); - animationSettingsMock.mockReturnValue({ - prefersReducedMotion: false, - shouldRenderRichAnimation: true, - }); - const bounds = { x: 10, y: 20, width: 800, height: 600 }; - const t3 = { - id: 42, - title: "T3 Code", - appIdentifier: "com.t3tools.T3Code.desktop", - owner: { name: "T3 Code", processId: 123 }, - bounds, - png: Buffer.from([1, 2, 3]), - }; - focusedWindowMock.mockReturnValue({ - getBounds: () => bounds, - getTitle: () => t3.title, - isDestroyed: () => false, - isMinimized: () => false, - isVisible: () => true, - show: vi.fn(), - restore: vi.fn(), - }); - const images: Uint8Array[] = []; - activeWindowMock.mockReset().mockResolvedValue({ - ...t3, - platform: platform === "darwin" ? "macos" : "windows", - }); - regionCaptureMock.mockReset().mockResolvedValue({ - width: bounds.width, - height: bounds.height, - png: t3.png, - }); - macCaptureMock.mockReset().mockImplementation(async () => { - images.push(t3.png); - return { source: { name: t3.title }, png: t3.png }; - }); - const activate = vi.fn<(title: string) => Promise>().mockResolvedValue(undefined); - linuxCaptureMock.mockResolvedValueOnce({ - png: t3.png, - window: { - title: t3.title, - appName: t3.owner.name, - appIdentifier: t3.appIdentifier, - processId: t3.owner.processId, - bounds, - }, - feedback: { - animationStarted: true, - activate, - animateTo: async () => undefined, - complete: async () => undefined, - close: () => undefined, - }, - }); - const readAccessibility = accessibilityProcessReadMock.getMockImplementation()!; - accessibilityProcessReadMock.mockImplementation(({ active }) => ({ - started: Promise.resolve(), - result: Promise.resolve({ accessibleText: `Window from process ${active.owner.processId}` }), - })); - let metadata = ""; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure( - enabledSettings({ - snapShotFlash: false, - snapShotShortcut: { - key: "2", - ctrlKey: true, - shiftKey: true, - altKey: false, - metaKey: false, - modKey: false, - }, - }), - ); - const trigger = - platform === "linux" - ? portalShortcutInstances.at(-1)!.onCapture - : registerShortcutMock.mock.calls.at(-1)![1]; - yield* Effect.promise(trigger); - - const saved = yield* decodePendingMetadata(metadata); - assert.equal(saved.source.windowTitle, t3.title); - assert.equal(saved.source.appName, t3.owner.name); - assert.equal(saved.source.accessibleText, `Window from process ${t3.owner.processId}`); - assert.deepEqual(images, [t3.png]); - assert.equal(prepareCaptureRevealMock.mock.calls.length, platform === "win32" ? 1 : 0); - if (platform === "linux") { - assert.equal(saved.source.appIdentifier, t3.appIdentifier); - assert.deepEqual(activate.mock.calls, [[t3.title]]); - } - }), - ).pipe( - Effect.provide( - layerTest(platform, { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: (_, bytes) => - Effect.sync(() => { - images.push(bytes); - }), - writeFileString: (_, text) => - Effect.sync(() => { - metadata = text; - }), - }), - ), - Effect.ensuring( - Effect.sync(() => { - focusedWindowMock.mockReset(); - linuxCaptureMock.mockReset().mockResolvedValue(undefined); - accessibilityProcessReadMock.mockReset().mockImplementation(readAccessibility); - mediaAccessStatusMock.mockReturnValue("not-determined"); - animationSettingsMock.mockReturnValue({ - prefersReducedMotion: true, - shouldRenderRichAnimation: false, - }); - vi.unstubAllEnvs(); - }), - ), - ); - }, -); - -it.effect.each(["win32", "darwin", "linux"] as const)( - "ignores shortcut repeats for 200 ms without delaying the first capture on %s", - (platform) => { - const fixture = concurrentCaptureFixture(platform, false); - fixture.releaseAll(); - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(fixture.settings); - yield* service.setShortcutSuppressed(true); - yield* Effect.promise(fixture.trigger); - assert.equal(fixture.state.snapshots, 0); - yield* service.setShortcutSuppressed(false); - yield* Effect.promise(fixture.trigger); - assert.equal(fixture.state.snapshots, 1); - assert.lengthOf(fixture.readyIds, 1); - - yield* Effect.promise(fixture.trigger); - yield* TestClock.adjust("199 millis"); - yield* Effect.promise(fixture.trigger); - assert.equal(fixture.state.snapshots, 1); - assert.lengthOf(fixture.readyIds, 1); - - yield* TestClock.adjust("1 millis"); - yield* Effect.promise(fixture.trigger); - assert.equal(fixture.state.snapshots, 2); - assert.lengthOf(fixture.readyIds, 2); - - yield* service.capture; - assert.equal(fixture.state.snapshots, 3); - assert.lengthOf(fixture.readyIds, 3); - }), - ).pipe(Effect.provide(fixture.layer), Effect.ensuring(Effect.sync(fixture.reset))); - }, -); - it.effect.each([ { platform: "win32", animations: true }, { platform: "darwin", animations: false }, @@ -1204,41 +983,6 @@ it.effect.each(["succeeds", "fails"] as const)( }, ); -it.effect("keeps newer native feedback when older accessibility persistence fails", () => { - const fixture = concurrentCaptureFixture("linux", true); - fixture.state.failFirstPersistence = true; - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(fixture.settings); - fixture.first.pixels.resolve(); - const first = yield* Effect.promise(fixture.trigger).pipe( - Effect.forkChild({ startImmediately: true }), - ); - yield* Effect.promise(() => fixture.first.handoff.promise); - yield* TestClock.adjust("200 millis"); - fixture.second.pixels.resolve(); - const second = yield* Effect.promise(fixture.trigger).pipe( - Effect.forkChild({ startImmediately: true }), - ); - yield* Effect.promise(() => fixture.second.handoff.promise); - fixture.first.context.resolve({ accessibleText: "Discord accessibility" }); - yield* Fiber.join(first); - - assert.lengthOf(fixture.readyIds, 0); - assert.lengthOf(fixture.second.feedback.close.mock.calls, 0); - assert.lengthOf(fixture.second.feedback.complete.mock.calls, 0); - fixture.second.context.resolve({ accessibleText: "Explorer accessibility" }); - yield* Fiber.join(second); - assert.lengthOf(fixture.readyIds, 1); - const newer = yield* service.read(fixture.readyIds[0]!); - assert.equal(newer.source.windowTitle, fixture.second.title); - yield* service.acknowledge(fixture.readyIds[0]!); - assert.lengthOf(fixture.second.feedback.complete.mock.calls, 1); - }).pipe(Effect.ensuring(Effect.sync(fixture.releaseAll))), - ).pipe(Effect.provide(fixture.layer), Effect.ensuring(Effect.sync(fixture.reset))); -}); - it.effect("matches Windows accessibility windows on a scaled display", () => { const png = Buffer.from([1, 2, 3]); const active = { @@ -1304,94 +1048,6 @@ it.effect("matches Windows accessibility windows on a scaled display", () => { ); }); -it.effect("skips accessibility capture when the setting is disabled", () => { - const png = Buffer.from([1, 2, 3]); - const active = { - platform: "windows", - id: 42, - title: "Editor", - owner: { name: "Editor", processId: 123 }, - bounds: { x: 10, y: 20, width: 800, height: 600 }, - } as const; - activeWindowMock.mockReset().mockResolvedValue(active); - regionCaptureMock.mockReset().mockResolvedValue({ width: 800, height: 600, png }); - accessibilityProcessWarmMock.mockClear(); - accessibilityProcessReadMock.mockClear(); - accessibilityByPidMock.mockClear(); - const layer = layerTest("win32", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: () => Effect.void, - writeFileString: () => Effect.void, - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings({ snapShotIncludeAccessibility: false })); - yield* service.capture; - - assert.lengthOf(accessibilityProcessWarmMock.mock.calls, 0); - assert.lengthOf(accessibilityProcessReadMock.mock.calls, 0); - assert.lengthOf(accessibilityByPidMock.mock.calls, 0); - }), - ).pipe(Effect.provide(layer)); -}); - -it.effect("keeps an accessibility helper warm only while capture data is enabled", () => { - accessibilityProcessWarmMock.mockClear(); - accessibilityProcessCoolMock.mockClear(); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure({ - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotIncludeAccessibility: true, - }); - - assert.lengthOf(accessibilityProcessWarmMock.mock.calls, 1); - assert.lengthOf(accessibilityProcessCoolMock.mock.calls, 0); - - yield* service.configure({ - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: false, - snapShotIncludeAccessibility: true, - }); - - assert.lengthOf(accessibilityProcessCoolMock.mock.calls, 1); - }), - ).pipe(Effect.provide(layerTest("win32"))); -}); - -it.effect("rejects X11 capture without registering shortcuts or loading capture backends", () => { - vi.stubEnv("XDG_SESSION_TYPE", "x11"); - vi.stubEnv("WAYLAND_DISPLAY", ""); - linuxCaptureMock.mockClear(); - activeWindowMock.mockClear(); - registerShortcutMock.mockClear(); - shortcutProcesses.length = 0; - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure({ ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true }); - const state = yield* service.state; - assert.equal(state.mode, "unavailable"); - assert.include(state.message, "Wayland"); - const result = yield* Effect.flip(service.capture); - assert.equal(result.operation, "unsupported"); - assert.lengthOf(registerShortcutMock.mock.calls, 0); - assert.lengthOf(shortcutProcesses, 0); - assert.lengthOf(linuxCaptureMock.mock.calls, 0); - assert.lengthOf(activeWindowMock.mock.calls, 0); - }), - ).pipe( - Effect.provide(layerTest("linux")), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - it.effect.each(["gnome", "niri", "kde", "hyprland"] as const)( "persists %s text without inventing AT-SPI screen coordinates", (backend) => { @@ -1489,509 +1145,6 @@ it.effect.each(["gnome", "niri", "kde", "hyprland"] as const)( }, ); -it.effect("persists a window capture from a portal activation without a setup test", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - linuxCaptureMock.mockClear().mockResolvedValueOnce({ - png: Buffer.from([1, 2, 3]), - window: { - title: "Shortcut capture", - appName: "Text Editor", - appIdentifier: "org.kde.kwrite", - processId: 123, - bounds: { x: 0, y: 0, width: 700, height: 520 }, - }, - }); - let metadata = ""; - const writes: Uint8Array[] = []; - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure({ - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotIncludeAccessibility: false, - snapShotShortcut: { - key: "2", - ctrlKey: true, - shiftKey: true, - altKey: false, - metaKey: false, - modKey: false, - }, - }); - yield* Effect.promise(portalShortcutInstances[0]!.onCapture); - assert.lengthOf(linuxCaptureMock.mock.calls, 1); - assert.deepEqual(writes, [Buffer.from([1, 2, 3])]); - const saved = yield* decodePendingMetadata(metadata); - assert.equal(saved.source.windowTitle, "Shortcut capture"); - assert.equal(saved.source.appIdentifier, "org.kde.kwrite"); - const state = yield* service.state; - assert.isTrue(state.shortcutVerified); - assert.isNull(state.message); - const portal = portalShortcutInstances[0]!; - portal.state = { - shortcutRegistered: false, - shortcutPending: false, - shortcutMessage: "Permission revoked", - }; - portal.onStateChanged(); - const revoked = yield* service.state; - assert.isFalse(revoked.shortcutVerified); - assert.isFalse(revoked.shortcutRegistered); - }), - ).pipe( - Effect.provide( - layerTest("linux", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: (_, bytes) => - Effect.sync(() => { - writes.push(bytes); - }), - writeFileString: (_, text) => - Effect.sync(() => { - metadata = text; - }), - }), - ), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - -it.effect("does not fall back to the picker when an automatic Wayland capture fails", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - linuxCaptureMock.mockRejectedValueOnce(new Error("Capture denied")); - getSourcesMock.mockClear(); - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings()); - const failure = yield* Effect.flip(service.capture); - assert.equal(failure.operation, "capture"); - assert.lengthOf(getSourcesMock.mock.calls, 0); - }), - ).pipe( - Effect.provide( - layerTest("linux", { - makeDirectory: () => Effect.void, - remove: () => Effect.void, - }), - ), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - -it.effect( - "logs a GNOME activation failure and completes the shell flight before acknowledging the image", - () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - const order: string[] = []; - const activationFailure = new Error("Activation failed"); - const logs: Array = []; - const logger = Logger.make(({ message }) => logs.push(message)); - const feedback = { - animationStarted: true, - activate: async () => { - order.push("activate"); - throw activationFailure; - }, - animateTo: async () => { - order.push("land"); - }, - complete: async () => { - order.push("complete"); - }, - close: () => { - order.push("close"); - }, - }; - linuxCaptureMock.mockImplementationOnce(async () => { - order.push("snapshot"); - return { png: Buffer.from([1, 2, 3]), feedback }; - }); - focusedWindowMock.mockReturnValue(undefined); - const destination = { - getBounds: () => ({ x: 0, y: 0, width: 1000, height: 800 }), - getTitle: () => "T3 Code", - isDestroyed: () => false, - isVisible: () => true, - isMinimized: () => false, - }; - allWindowsMock.mockReturnValue([destination]); - let saved = ""; - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings()); - yield* service.capture; - assert.deepEqual(order, ["snapshot", "activate"]); - const warning = logs.find( - (message) => - Array.isArray(message) && - message[0] === "The compositor could not activate T3 Code after the snapshot", - ); - assert.strictEqual(Array.isArray(warning) ? warning[1] : undefined, activationFailure); - const pending = yield* decodePendingMetadata(saved); - yield* service.setAnimationDestination(pending.id, { - frame: { x: 0, y: 0, width: 10, height: 10 }, - relativeFrame: { x: 0.1, y: 0.8, width: 0.2, height: 0.1 }, - backgroundColor: "white", - borderColor: "black", - borderWidth: 1, - cornerRadius: 8, - scaleFactor: 1, - }); - yield* service.acknowledge(pending.id); - assert.deepEqual(order, ["snapshot", "activate", "land", "complete", "delete", "delete"]); - }), - ).pipe( - Effect.provide( - Layer.mergeAll( - layerTest("linux", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: () => Effect.void, - writeFileString: (_, value) => - Effect.sync(() => { - saved = value; - }), - remove: () => - Effect.sync(() => { - order.push("delete"); - }), - }), - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - Effect.ensuring( - Effect.sync(() => { - allWindowsMock.mockReturnValue([]); - vi.unstubAllEnvs(); - }), - ), - ); - }, -); - -it.effect("does not read unverified accessibility context for a Wayland portal capture", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - const png = Buffer.from([1, 2, 3]); - accessibilityForegroundMock.mockReset(); - getSourcesMock.mockReset().mockResolvedValue([ - { - id: "window:42:0", - name: "Untitled", - thumbnail: { isEmpty: () => false, toPNG: () => png }, - }, - ]); - const layer = layerTest("linux", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: () => Effect.void, - writeFileString: () => Effect.void, - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings()); - yield* service.capture; - - assert.lengthOf(accessibilityForegroundMock.mock.calls, 0); - }), - ).pipe(Effect.provide(layer), Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); -}); - -it.effect("uses display-local macOS capture surfaces across the source and main displays", () => { - const png = Buffer.from([1, 2, 3]); - const active = { - platform: "macos", - id: 42, - title: "Terminal", - owner: { name: "Terminal", processId: 123 }, - bounds: { x: 10, y: 20, width: 800, height: 600 }, - } as const; - activeWindowMock.mockReset().mockResolvedValue(active); - accessibilityByPidMock.mockReset().mockResolvedValue({ children: async () => [] }); - macCaptureMock.mockReset().mockResolvedValue({ - source: { name: "Terminal" }, - png, - }); - animationSettingsMock.mockReturnValueOnce({ - prefersReducedMotion: false, - shouldRenderRichAnimation: true, - }); - focusedWindowMock.mockReturnValue({ - getBounds: () => ({ x: -1_600, y: 100, width: 1_200, height: 800 }), - isDestroyed: () => false, - }); - flashWindows.length = 0; - const layer = layerTest("darwin", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFileString: () => Effect.void, - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings()); - yield* service.capture; - - const transitionWindows = flashWindows.filter((window) => window.kind === "browser"); - assert.deepEqual( - transitionWindows.map((window) => window.bounds), - [ - { x: 0, y: -200, width: 1_440, height: 900 }, - { x: -1_920, y: 0, width: 1_920, height: 1_080 }, - ], - ); - for (const transitionWindow of transitionWindows) { - assert.deepEqual(transitionWindow.alwaysOnTopCalls, [[true, "pop-up-menu"]]); - } - }), - ).pipe(Effect.provide(layer), Effect.ensuring(Effect.sync(() => focusedWindowMock.mockReset()))); -}); - -it.effect.each(["ready", "failed"] as const)( - "shows the Windows transition only once its snapshot decode is %s", - (outcome) => { - const png = Buffer.from([1, 2, 3]); - activeWindowMock.mockReset().mockResolvedValue({ - platform: "windows", - id: 42, - title: "Editor", - owner: { name: "Editor", processId: 123 }, - bounds: { x: 10, y: 20, width: 800, height: 600 }, - }); - regionCaptureMock.mockReset().mockResolvedValue({ width: 800, height: 600, png }); - animationSettingsMock.mockReturnValueOnce({ - prefersReducedMotion: false, - shouldRenderRichAnimation: true, - }); - const decoding = Promise.withResolvers(); - const decoded = Promise.withResolvers(); - transitionSnapshotMock.mockImplementation(() => { - decoding.resolve(); - return decoded.promise; - }); - focusedWindowMock.mockReturnValue({ - getBounds: () => ({ x: 100, y: 50, width: 1_200, height: 800 }), - isDestroyed: () => false, - }); - transitionShowMock.mockClear(); - flashWindows.length = 0; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure( - enabledSettings({ snapShotIncludeAccessibility: false, snapShotFlash: false }), - ); - const capture = yield* service.capture.pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.promise(() => decoding.promise); - assert.lengthOf(transitionShowMock.mock.calls, 0); - - if (outcome === "ready") decoded.resolve(); - else decoded.reject(new Error("Snapshot decode failed")); - yield* Fiber.join(capture); - - if (outcome === "ready") { - assert.isNotEmpty(transitionShowMock.mock.calls); - } else { - assert.lengthOf(transitionShowMock.mock.calls, 0); - assert.isTrue(flashWindows.every((window) => window.destroyed)); - } - }), - ).pipe( - Effect.provide( - layerTest("win32", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFile: () => Effect.void, - writeFileString: () => Effect.void, - }), - ), - Effect.ensuring( - Effect.sync(() => { - decoded.resolve(); - focusedWindowMock.mockReset(); - }), - ), - ); - }, -); - -it.effect("uses the unfocused main window for a macOS cross-display transition", () => { - const png = Buffer.from([1, 2, 3]); - const active = { - platform: "macos", - id: 42, - title: "Terminal", - owner: { name: "Terminal", processId: 123 }, - bounds: { x: 10, y: 20, width: 800, height: 600 }, - } as const; - activeWindowMock.mockReset().mockResolvedValue(active); - accessibilityByPidMock.mockReset().mockResolvedValue({ children: async () => [] }); - macCaptureMock.mockReset().mockResolvedValue({ source: { name: "Terminal" }, png }); - animationSettingsMock.mockReturnValueOnce({ - prefersReducedMotion: false, - shouldRenderRichAnimation: true, - }); - focusedWindowMock.mockReturnValue(undefined); - allWindowsMock.mockReturnValue([ - { - getBounds: () => ({ x: -1_600, y: 100, width: 1_200, height: 800 }), - isDestroyed: () => false, - }, - ]); - flashWindows.length = 0; - const layer = layerTest("darwin", { - makeDirectory: () => Effect.void, - rename: () => Effect.void, - writeFileString: () => Effect.void, - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(enabledSettings()); - yield* service.capture; - - assert.deepEqual( - flashWindows.filter((window) => window.kind === "browser").map((window) => window.bounds), - [ - { x: 0, y: -200, width: 1_440, height: 900 }, - { x: -1_920, y: 0, width: 1_920, height: 1_080 }, - ], - ); - }), - ).pipe( - Effect.provide(layer), - Effect.ensuring( - Effect.sync(() => { - focusedWindowMock.mockReset(); - allWindowsMock.mockReset(); - }), - ), - ); -}); - -function fakeIcon(label: string, empty = false): Electron.NativeImage { - return { - isEmpty: () => empty, - resize: ({ width, height, quality }) => ({ - toDataURL: (options) => - "data:image/png;base64," + - label + - ":" + - width + - "x" + - height + - ":" + - quality + - "@" + - options?.scaleFactor, - }), - } as Electron.NativeImage; -} - -it.each([ - ["OS app", fakeIcon("file"), fakeIcon("captured"), "file"], - ["captured app", fakeIcon("file", true), fakeIcon("captured"), "captured"], -])("exports the %s icon at high density", (_source, fileIcon, capturedIcon, expectedLabel) => { - const dataUrl = DesktopSnapShot.snapShotIconDataUrl(fileIcon, capturedIcon); - - assert.strictEqual(dataUrl, "data:image/png;base64," + expectedLabel + ":64x64:best@2"); -}); - -const activeEditor = { - owner: { path: "/Applications/Editor.app" }, -} as Parameters[1]; - -it.each([ - [ - "a failed thumbnail on darwin", - "darwin" as const, - () => thumbnailFromPathMock.mockRejectedValue(new Error("no thumbnail")), - ], - ["other platforms", "win32" as const, () => {}], -])( - "requests the file icon at a size supported on macOS after %s", - async (_case, platform, arrange) => { - getFileIconMock.mockReset(); - thumbnailFromPathMock.mockReset(); - arrange(); - getFileIconMock.mockResolvedValue(fakeIcon("file")); - - const dataUrl = await DesktopSnapShot.iconDataUrl( - { appIcon: fakeIcon("captured") }, - activeEditor, - platform, - ); - - assert.deepEqual(getFileIconMock.mock.calls, [ - ["/Applications/Editor.app", { size: "normal" }], - ]); - assert.strictEqual(dataUrl, "data:image/png;base64,file:64x64:best@2"); - }, -); - -it("uses the primary display for portal flash feedback", () => { - assert.deepEqual(DesktopSnapShot.snapShotFlashBounds(undefined, "linux"), { - x: 0, - y: 0, - width: 1_440, - height: 900, - }); -}); - -it("uses the operating system animation policy", () => { - assert.isTrue( - DesktopSnapShot.shouldAnimateSnapShot({ - prefersReducedMotion: false, - shouldRenderRichAnimation: true, - }), - ); - assert.isFalse( - DesktopSnapShot.shouldAnimateSnapShot({ - prefersReducedMotion: true, - shouldRenderRichAnimation: true, - }), - ); -}); - -it("scales transition timing with travel distance", () => { - const source = { x: 0, y: 0, width: 200, height: 100 }; - assert.strictEqual(snapShotAnimationDurationMs(source, source), 280); - const near = snapShotAnimationDurationMs(source, { - x: 100, - y: 0, - width: 200, - height: 100, - }); - const far = snapShotAnimationDurationMs(source, { - x: 1_000, - y: 0, - width: 200, - height: 100, - }); - - assert.isAtLeast(near, 280); - assert.isBelow(far, 570); - assert.isAbove(far, near); -}); - -it("bounds the transition surface to its displays", () => { - assert.deepEqual( - snapShotAnimationOverlayBounds([ - { bounds: { x: -1_920, y: 0, width: 1_920, height: 1_080 } }, - { bounds: { x: 0, y: -200, width: 1_440, height: 900 } }, - ]), - { x: -1_920, y: -200, width: 3_360, height: 1_280 }, - ); -}); - it("covers straddling captures and intervening monitors without spanning unrelated displays", () => { const displays = [ { bounds: { x: -1_920, y: 0, width: 1_920, height: 1_080 } }, @@ -2014,88 +1167,6 @@ it("covers straddling captures and intervening monitors without spanning unrelat ); }); -it("keeps cross-display handoff surfaces local to each display", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ - boundOverlayToCaptureDisplays: true, - }); - - try { - await transition.begin( - "capture-1", - { x: -1_800, y: 50, width: 900, height: 600 }, - "data:image/png;base64,", - false, - { x: 100, y: 50, width: 1_000, height: 700 }, - ); - transition.animateTo("capture-1", { - frame: { x: 600, y: 400, width: 208, height: 112 }, - backgroundColor: "#fff", - borderColor: "#ccc", - borderWidth: 1, - cornerRadius: 8, - scaleFactor: 1, - }); - await transition.waitForLanding("capture-1"); - - assert.deepEqual( - flashWindows.map((window) => window.bounds), - [ - { x: -1_920, y: 0, width: 1_920, height: 1_080 }, - { x: 0, y: -200, width: 1_440, height: 900 }, - ], - ); - for (const window of flashWindows) { - assert.strictEqual(window.resizeCount, 0); - } - } finally { - transition.dispose(); - } -}); - -it("adds a newly selected destination display without resizing existing surfaces", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ boundOverlayToCaptureDisplays: true }); - const snapshot = "data:image/png;base64,captured-window"; - - try { - await transition.begin( - "capture-1", - { x: -1_800, y: 50, width: 900, height: 600 }, - snapshot, - false, - { x: -1_600, y: 100, width: 1_000, height: 700 }, - ); - assert.lengthOf(flashWindows, 1); - const initialWindow = flashWindows[0]; - - transition.animateTo("capture-1", { - frame: { x: 600, y: 400, width: 208, height: 112 }, - backgroundColor: "#fff", - borderColor: "#ccc", - borderWidth: 1, - cornerRadius: 8, - scaleFactor: 1, - }); - await transition.waitForLanding("capture-1"); - - assert.strictEqual(flashWindows[0], initialWindow); - assert.deepEqual( - flashWindows.map((window) => window.bounds), - [ - { x: -1_920, y: 0, width: 1_920, height: 1_080 }, - { x: 0, y: -200, width: 1_440, height: 900 }, - ], - ); - for (const window of flashWindows) { - assert.strictEqual(window.resizeCount, 0); - assert.strictEqual(window.showCount, 1); - } - } finally { - transition.dispose(); - } -}); - it("cancels a late display while its snapshot is still decoding", async () => { flashWindows.length = 0; const transition = new SnapShotTransition({ boundOverlayToCaptureDisplays: true }); @@ -2139,52 +1210,6 @@ it("cancels a late display while its snapshot is still decoding", async () => { } }); -it("waits for every initial compositor frame before completing capture feedback", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ - boundOverlayToCaptureDisplays: true, - waitForCompositorFrame: true, - }); - const frames = [Promise.withResolvers(), Promise.withResolvers()]; - const readingFrames = Promise.withResolvers(); - let frameIndex = 0; - let ready = false; - transitionCapturePageMock.mockImplementation(() => { - const frame = frames[frameIndex++]!; - if (frameIndex === frames.length) readingFrames.resolve(); - return frame.promise; - }); - - try { - const begin = transition - .begin( - "capture-1", - { x: -1_800, y: 50, width: 900, height: 600 }, - "data:image/png;base64,", - true, - { x: 100, y: 50, width: 1_000, height: 700 }, - ) - .then(() => { - ready = true; - }); - await readingFrames.promise; - frames[0]!.resolve(); - await frames[0]!.promise; - - assert.isFalse(ready); - for (const window of flashWindows) { - assert.strictEqual(window.showCount, 1); - } - frames[1]!.resolve(); - await begin; - - assert.isTrue(ready); - } finally { - for (const frame of frames) frame.resolve(); - transition.dispose(); - } -}); - it("does not flash a dismissed overlay after its initial compositor receipt arrives", async () => { flashWindows.length = 0; const transition = new SnapShotTransition({ waitForCompositorFrame: true }); @@ -2203,163 +1228,37 @@ it("does not flash a dismissed overlay after its initial compositor receipt arri true, ); await readingFrame.promise; + assert.isFalse(transition.isAnimating); transition.dismiss("capture-1"); + assert.isFalse(transition.isAnimating); frame.resolve(); await begin; - for (const window of flashWindows) { - assert.isTrue(window.destroyed); - } - } finally { - frame.resolve(); - transition.dispose(); - } -}); - -it("waits for every display's prepared compositor frame before starting any flight", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ - boundOverlayToCaptureDisplays: true, - waitForCompositorFrame: true, - }); - const frames = [Promise.withResolvers(), Promise.withResolvers()]; - const readingFrames = Promise.withResolvers(); - let frameIndex = 0; - try { - await transition.begin( - "capture-1", - { x: -1_800, y: 50, width: 900, height: 600 }, - "data:image/png;base64,", - false, - { x: 100, y: 50, width: 1_000, height: 700 }, - ); - transitionCapturePageMock.mockImplementation(() => { - const frame = frames[frameIndex++]!; - if (frameIndex === frames.length) readingFrames.resolve(); - return frame.promise; - }); - transition.animateTo("capture-1", { - frame: { x: 600, y: 400, width: 208, height: 112 }, - backgroundColor: "#fff", - borderColor: "#ccc", - borderWidth: 1, - cornerRadius: 8, - scaleFactor: 1, - }); - const landing = transition.waitForLanding("capture-1"); - await readingFrames.promise; - frames[0]!.resolve(); - await new Promise((resolve) => setImmediate(resolve)); - - for (const window of flashWindows) { - assert.deepEqual(window.capturedRegions, [ - { x: 0, y: 0, width: 1, height: 1 }, - { x: 0, y: 0, width: 1, height: 1 }, - ]); - } - - frames[1]!.resolve(); - await landing; - } finally { - for (const frame of frames) frame.resolve(); - transition.dispose(); - } -}); - -it("does not start a dismissed transition after its compositor receipt arrives", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ waitForCompositorFrame: true }); - const readingFrame = Promise.withResolvers(); - const frame = Promise.withResolvers(); - try { - await transition.begin( - "capture-1", - { x: 100, y: 50, width: 900, height: 600 }, - "data:image/png;base64,", - false, - ); - transitionCapturePageMock.mockImplementation(() => { - readingFrame.resolve(); - return frame.promise; - }); - transition.animateTo("capture-1", { - frame: { x: 600, y: 400, width: 208, height: 112 }, - backgroundColor: "#fff", - borderColor: "#ccc", - borderWidth: 1, - cornerRadius: 8, - scaleFactor: 1, - }); - const landing = transition.waitForLanding("capture-1"); - await readingFrame.promise; - transition.dismiss("capture-1"); - frame.resolve(); - await landing; - - assert.isTrue(flashWindows[0]?.destroyed); - } finally { - frame.resolve(); - transition.dispose(); - } -}); - -it("keeps flying on the destination display when the capture display fails", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ - boundOverlayToCaptureDisplays: true, - }); - - try { - await transition.begin( - "capture-1", - { x: -1_800, y: 50, width: 900, height: 600 }, - "data:image/png;base64,", - false, - { x: 100, y: 50, width: 1_000, height: 700 }, - ); - transitionScriptState.rejectFlight = true; - transitionScriptState.heldFlights = []; - transition.animateTo("capture-1", { - frame: { x: 600, y: 400, width: 208, height: 112 }, - backgroundColor: "#fff", - borderColor: "#ccc", - borderWidth: 1, - cornerRadius: 8, - scaleFactor: 1, - }); - - let landed = false; - const landing = transition.waitForLanding("capture-1").then(() => { - landed = true; - }); - await new Promise((resolve) => setImmediate(resolve)); - - assert.lengthOf(transitionScriptState.heldFlights, 1); - assert.isFalse(landed); - - for (const release of transitionScriptState.heldFlights) release(); - await landing; + for (const window of flashWindows) { + assert.isTrue(window.destroyed); + } } finally { - transitionScriptState.rejectFlight = false; - transitionScriptState.heldFlights = null; + frame.resolve(); transition.dispose(); } }); -it("keeps same-display motion inside one stable surface", async () => { +it("does not start a dismissed transition after its compositor receipt arrives", async () => { flashWindows.length = 0; - const transition = new SnapShotTransition({ - boundOverlayToCaptureDisplays: true, - }); - + const transition = new SnapShotTransition({ waitForCompositorFrame: true }); + const readingFrame = Promise.withResolvers(); + const frame = Promise.withResolvers(); try { await transition.begin( "capture-1", { x: 100, y: 50, width: 900, height: 600 }, "data:image/png;base64,", false, - { x: 200, y: 100, width: 1_000, height: 700 }, ); + transitionCapturePageMock.mockImplementation(() => { + readingFrame.resolve(); + return frame.promise; + }); transition.animateTo("capture-1", { frame: { x: 600, y: 400, width: 208, height: 112 }, backgroundColor: "#fff", @@ -2368,36 +1267,17 @@ it("keeps same-display motion inside one stable surface", async () => { cornerRadius: 8, scaleFactor: 1, }); - await transition.waitForLanding("capture-1"); - - assert.deepEqual(flashWindows[0]?.bounds, { - x: 0, - y: -200, - width: 1_440, - height: 900, - }); - assert.strictEqual(flashWindows[0]?.resizeCount, 0); - } finally { - transition.dispose(); - } -}); - -it("keeps the Windows transition above the revealed main window", async () => { - flashWindows.length = 0; - const transition = new SnapShotTransition({ - alwaysOnTopLevel: "pop-up-menu", - }); - - try { - await transition.begin( - "capture-1", - { x: 100, y: 50, width: 900, height: 600 }, - "data:image/png;base64,", - false, - ); + const landing = transition.waitForLanding("capture-1"); + await readingFrame.promise; + assert.isTrue(transition.isAnimating); + transition.dismiss("capture-1"); + assert.isFalse(transition.isAnimating); + frame.resolve(); + await landing; - assert.deepEqual(flashWindows[0]?.alwaysOnTopCalls, [[true, "pop-up-menu"]]); + assert.isTrue(flashWindows[0]?.destroyed); } finally { + frame.resolve(); transition.dispose(); } }); @@ -2424,6 +1304,7 @@ it("does not let a failed transition fail landing or capture completion", async }); await transition.waitForLanding("capture-1"); + assert.isFalse(transition.isAnimating); await transition.complete("capture-1"); assert.isTrue(flashWindows[0]?.destroyed); @@ -2433,15 +1314,6 @@ it("does not let a failed transition fail landing or capture completion", async } }); -it("bounds source thumbnails for large windows", () => { - assert.deepEqual( - DesktopSnapShot.snapShotThumbnailSize({ - bounds: { x: 0, y: 0, width: 6_000, height: 4_000 }, - } as Parameters[0]), - { width: 2_560, height: 1_600 }, - ); -}); - it.each(["client", "frame"] as const)( "maps KDE %s accessibility coordinates into the decorated screenshot", async (rootArea) => { @@ -2582,8 +1454,6 @@ it.each(["darwin", "win32"] as const)( it.each([ ["darwin", "", "value", 650], - ["win32", "", "value", 650], - ["linux", "x11", "value", 650], ["linux", "wayland", "value", 650], ["darwin", "", "name", 100], ] as const)( @@ -2656,6 +1526,69 @@ it.each([ } }); +it.each([ + ["com.google.Chrome", "Google Chrome – Profile"], + ["org.chromium.Chromium", "Chromium"], +])("reads macOS %s page context with an accessibility title suffix", async (bundleId, suffix) => { + const title = "Issues · pingdotgg/t3code"; + const bounds = { x: 0, y: 33, width: 1470, height: 857 }; + const window = { + role: "window", + name: `${title} - ${suffix}`, + bounds, + tree: async () => ({ name: title, children: [{ name: "New issue", children: [] }] }), + children: async () => [{ role: "button", name: "New issue", bounds, children: async () => [] }], + }; + accessibilityByPidMock.mockReset().mockImplementation(async (pid: number) => ({ + children: async () => (pid === 42 ? [window] : []), + })); + + const context = await readAccessibleWindowContext( + { title, bounds, owner: { processId: 42, bundleId } }, + "darwin", + title, + ); + + assert.equal(context?.accessibleText, `${title}\nNew issue`); + assert.equal(context?.accessibility?.format, "element-tree"); + assert.equal( + context?.accessibility?.format === "element-tree" + ? context.accessibility.root.children[0]?.name + : undefined, + "New issue", + ); +}); + +it("does not borrow another Chrome process context when the captured PID has no windows", async () => { + const title = "Issues · pingdotgg/t3code"; + const bounds = { x: 0, y: 33, width: 1470, height: 857 }; + const otherWindow = { + role: "window", + name: `${title} - Google Chrome – Profile`, + bounds, + tree: async () => ({ + name: title, + children: [{ name: "Other process private text", children: [] }], + }), + children: async () => [], + }; + accessibilityByPidMock.mockReset().mockResolvedValue({ + pid: 42, + children: async () => [], + }); + accessibilityListMock.mockResolvedValue([ + { pid: 43, bundleId: "com.google.Chrome", children: async () => [otherWindow] }, + ]); + + assert.isUndefined( + await readAccessibleWindowContext( + { title, bounds, owner: { processId: 42, bundleId: "com.google.Chrome" } }, + "darwin", + title, + ), + ); +}); + it("reads Flatpak app text from the AT-SPI proxy when the compositor PID misses", async () => { vi.stubEnv("XDG_SESSION_TYPE", "wayland"); const bounds = { x: 0, y: 0, width: 1_920, height: 1_048 }; @@ -2790,99 +1723,6 @@ it("does not guess GTK4 app text when two unnamed PID windows share the captured } }); -it.each([20, 1_350, 2_999])( - "includes accessibility text as soon as a %d ms read completes", - async (duration) => { - vi.useFakeTimers(); - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - const tree = Promise.withResolvers<{ value: string; children: Array }>(); - const started = Promise.withResolvers(); - accessibilityByPidMock.mockReset().mockResolvedValue({ - children: async () => [ - { - name: "Mozilla Firefox", - bounds: { x: 0, y: 0, width: 1_373, height: 928 }, - tree: () => { - started.resolve(); - return tree.promise; - }, - }, - ], - }); - - try { - const result = readAccessibleWindowText( - { - title: "Mozilla Firefox", - owner: { processId: 42 }, - bounds: { x: 67, y: 32, width: 1_373, height: 928 }, - }, - "linux", - "Mozilla Firefox", - ); - await started.promise; - await vi.advanceTimersByTimeAsync(duration); - tree.resolve({ value: "Firefox page text", children: [] }); - - assert.strictEqual(await result, "Firefox page text"); - assert.strictEqual(vi.getTimerCount(), 0); - } finally { - tree.resolve({ value: "", children: [] }); - await vi.advanceTimersByTimeAsync(0); - vi.useRealTimers(); - vi.unstubAllEnvs(); - } - }, -); - -it("falls back to completed flat text when rich traversal reaches the deadline", async () => { - vi.useFakeTimers(); - const richChildren = Promise.withResolvers>(); - const richStarted = Promise.withResolvers(); - accessibilityByPidMock.mockReset().mockResolvedValue({ - children: async () => [ - { - role: "window", - name: "Editor", - bounds: { x: 0, y: 0, width: 800, height: 600 }, - tree: async () => ({ value: "Complete flat text", children: [] }), - children: () => { - richStarted.resolve(); - return richChildren.promise; - }, - }, - ], - }); - - try { - const result = readAccessibleWindowContext( - { - title: "Editor", - owner: { processId: 42 }, - bounds: { x: 0, y: 0, width: 800, height: 600 }, - }, - "darwin", - "Editor", - { width: 1_600, height: 1_200 }, - ); - await richStarted.promise; - await vi.advanceTimersByTimeAsync(3_000); - - assert.deepEqual(await result, { - accessibleText: "Complete flat text", - accessibility: { - format: "flat-text", - text: "Complete flat text", - truncated: false, - }, - }); - } finally { - richChildren.resolve([]); - await vi.advanceTimersByTimeAsync(0); - vi.useRealTimers(); - } -}); - it("keeps a truncated element tree when the flat text read fails", async () => { const bounds = { x: 0, y: 0, width: 800, height: 600 }; accessibilityByPidMock.mockReset().mockResolvedValue({ @@ -2892,256 +1732,33 @@ it("keeps a truncated element tree when the flat text read fails", async () => { name: "Editor", bounds, tree: async () => { - throw new Error("Text read failed"); - }, - children: async () => [ - { - role: "text_area", - value: "x".repeat(8_001), - bounds: { x: 10, y: 50, width: 700, height: 500 }, - children: async () => [], - }, - ], - }, - ], - }); - - const result = await readAccessibleWindowContext( - { title: "Editor", bounds, owner: { processId: 123 } }, - "darwin", - "Editor", - ); - assert.equal(result?.accessibility?.format, "element-tree"); - assert.isTrue(result?.accessibility?.truncated); - assert.deepEqual( - result?.accessibility?.format === "element-tree" - ? result.accessibility.root.children[0]?.bounds - : undefined, - { x: 10, y: 50, width: 700, height: 500 }, - ); -}); - -it("keeps a truncated tree when flat text would not recover any text", async () => { - const bounds = { x: 0, y: 0, width: 800, height: 600 }; - accessibilityByPidMock.mockReset().mockResolvedValue({ - children: async () => [ - { - role: "window", - name: "Editor", - bounds, - tree: async () => ({ name: "Editor", children: [{ name: "Help", children: [] }] }), - children: async () => [ - { - role: "button", - name: "Help", - description: "Help text ".repeat(250), - bounds, - children: async () => [], - }, - ], - }, - ], - }); - - const result = await readAccessibleWindowContext( - { title: "Editor", bounds, owner: { processId: 123 } }, - "darwin", - "Editor", - ); - assert.equal(result?.accessibility?.format, "element-tree"); - assert.isTrue(result?.accessibility?.truncated); - assert.include( - result?.accessibility?.format === "element-tree" - ? result.accessibility.root.children[0]?.description - : undefined, - "Help text", - ); -}); - -it("times out after three seconds without overlapping the outstanding accessibility read", async () => { - vi.useFakeTimers(); - accessibilityByPidMock.mockReset(); - const read = Promise.withResolvers<{ children: () => Promise> }>(); - const started = Promise.withResolvers(); - accessibilityByPidMock.mockImplementationOnce(() => { - started.resolve(); - return read.promise; - }); - const active = { - title: "main.ts", - owner: { processId: 42 }, - bounds: { x: 0, y: 0, width: 800, height: 600 }, - } satisfies SnapShotAccessibility.AccessibleWindowIdentity; - - try { - const first = readAccessibleWindowText(active, "darwin", "main.ts"); - let settled = false; - void first.then(() => { - settled = true; - }); - await started.promise; - await vi.advanceTimersByTimeAsync(2_999); - assert.isFalse(settled); - await vi.advanceTimersByTimeAsync(1); - assert.isUndefined(await first); - assert.strictEqual(vi.getTimerCount(), 0); - assert.isUndefined(await readAccessibleWindowText(active, "darwin", "main.ts")); - assert.strictEqual(accessibilityByPidMock.mock.calls.length, 1); - - read.resolve({ children: async () => [] }); - await vi.advanceTimersByTimeAsync(0); - accessibilityByPidMock.mockResolvedValueOnce({ children: async () => [] }); - assert.isUndefined(await readAccessibleWindowText(active, "darwin", "main.ts")); - assert.strictEqual(accessibilityByPidMock.mock.calls.length, 2); - } finally { - read.resolve({ children: async () => [] }); - await vi.advanceTimersByTimeAsync(0); - vi.useRealTimers(); - } -}); - -it("uses native opacity for a short-lived flash", async () => { - vi.useFakeTimers(); - flashWindows.length = 0; - const flash = new DesktopSnapShot.SnapShotFlash(); - const bounds = { x: 10, y: 20, width: 800, height: 600 }; - - try { - await flash.showAnimated(bounds); - - assert.lengthOf(flashWindows, 1); - assert.strictEqual(flashWindows[0]?.kind, "base"); - assert.strictEqual(flashWindows[0]?.options.transparent, false); - assert.strictEqual(flashWindows[0]?.loadCount, 0); - assert.deepEqual(flashWindows[0]?.bounds, bounds); - assert.strictEqual(flashWindows[0]?.showCount, 1); - assert.lengthOf(flashWindows[0]?.scripts ?? [], 0); - await vi.advanceTimersByTimeAsync(180); - assert.isTrue(flashWindows[0]?.destroyed); - assert.isAbove(flashWindows[0]?.opacities.length ?? 0, 1); - assert.strictEqual(vi.getTimerCount(), 0); - } finally { - vi.useRealTimers(); - } -}); - -it.effect("does not request permissions or create the flash during desktop startup", () => { - flashWindows.length = 0; - accessibilityTrustedMock.mockReset().mockReturnValue(false); - mediaAccessStatusMock.mockReset().mockReturnValue("not-determined"); - getSourcesMock.mockReset().mockResolvedValue([]); - openExternalMock.mockClear(); - const settings = { - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotFlash: true, - }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.initialize; - assert.lengthOf(flashWindows, 0); - assert.deepEqual(accessibilityTrustedMock.mock.calls, [[false]]); - assert.lengthOf(getSourcesMock.mock.calls, 0); - assert.lengthOf(openExternalMock.mock.calls, 0); - }), - ).pipe(Effect.provide(layerTest("darwin", {}, Option.some(settings)))); -}); - -it.effect("keeps snapshots disabled when client settings cannot be read at startup", () => { - const readError = new DesktopClientSettings.DesktopClientSettingsReadError({ - operation: "read-file", - path: "/state/client-settings.json", - cause: new Error("unavailable"), - }); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.initialize; - assert.isFalse((yield* service.state).shortcutRegistered); - }), - ).pipe(Effect.provide(layerTest("win32", {}, Option.none(), Effect.fail(readError)))); -}); - -it.effect("does not request macOS permissions while synchronizing enabled settings", () => { - accessibilityTrustedMock.mockReset().mockReturnValue(false); - mediaAccessStatusMock.mockReset().mockReturnValue("not-determined"); - getSourcesMock.mockReset().mockResolvedValue([]); - openExternalMock.mockClear(); - const settings = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - - assert.deepEqual(accessibilityTrustedMock.mock.calls, [[false]]); - assert.lengthOf(getSourcesMock.mock.calls, 0); - assert.lengthOf(openExternalMock.mock.calls, 0); - }), - ).pipe(Effect.provide(layerTest("darwin"))); -}); - -it.effect("requests macOS permissions only for an explicit enable action", () => { - accessibilityTrustedMock.mockReset().mockReturnValue(false); - mediaAccessStatusMock.mockReset().mockReturnValue("not-determined"); - getSourcesMock.mockReset().mockResolvedValue([]); - openExternalMock.mockClear(); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.requestPermissions(true); - - assert.deepEqual(accessibilityTrustedMock.mock.calls, [[true]]); - assert.lengthOf(getSourcesMock.mock.calls, 1); - assert.lengthOf(openExternalMock.mock.calls, 1); - }), - ).pipe(Effect.provide(layerTest("darwin"))); -}); - -it.effect("does not request macOS accessibility permission when capture data is disabled", () => { - accessibilityTrustedMock.mockReset().mockReturnValue(false); - mediaAccessStatusMock.mockReset().mockReturnValue("not-determined"); - getSourcesMock.mockReset().mockResolvedValue([]); - openExternalMock.mockClear(); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.requestPermissions(false); - - assert.lengthOf(accessibilityTrustedMock.mock.calls, 0); - assert.lengthOf(getSourcesMock.mock.calls, 1); - assert.lengthOf(openExternalMock.mock.calls, 1); - }), - ).pipe(Effect.provide(layerTest("darwin"))); -}); - -it.effect("reports macOS permission status and requests each permission on its own", () => { - accessibilityTrustedMock.mockReset().mockReturnValue(false); - mediaAccessStatusMock.mockReset().mockReturnValue("granted"); - getSourcesMock.mockReset().mockResolvedValue([]); - openExternalMock.mockClear(); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const state = yield* service.state; - assert.deepEqual(state.macPermissions, { screenRecording: true, accessibility: false }); - - yield* service.setup("allow-accessibility"); - assert.deepEqual(accessibilityTrustedMock.mock.calls.at(-1), [true]); - assert.lengthOf(getSourcesMock.mock.calls, 0); + throw new Error("Text read failed"); + }, + children: async () => [ + { + role: "text_area", + value: "x".repeat(8_001), + bounds: { x: 10, y: 50, width: 700, height: 500 }, + children: async () => [], + }, + ], + }, + ], + }); - mediaAccessStatusMock.mockReturnValue("not-determined"); - yield* service.setup("allow-screen-recording"); - assert.lengthOf(getSourcesMock.mock.calls, 1); - assert.lengthOf(openExternalMock.mock.calls, 1); - }), - ).pipe(Effect.provide(layerTest("darwin"))); + const result = await readAccessibleWindowContext( + { title: "Editor", bounds, owner: { processId: 123 } }, + "darwin", + "Editor", + ); + assert.equal(result?.accessibility?.format, "element-tree"); + assert.isTrue(result?.accessibility?.truncated); + assert.deepEqual( + result?.accessibility?.format === "element-tree" + ? result.accessibility.root.children[0]?.bounds + : undefined, + { x: 10, y: 50, width: 700, height: 500 }, + ); }); it.effect("flags revoked macOS permissions on read and re-registers once they return", () => { @@ -3184,112 +1801,6 @@ it.effect("flags revoked macOS permissions on read and re-registers once they re ).pipe(Effect.provide(layerTest("darwin"))); }); -it.effect("rejects macOS permission actions off macOS and omits macPermissions there", () => { - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const state = yield* service.state; - assert.isUndefined(state.macPermissions); - assert.isTrue(state.windows); - const error = yield* service.setup("allow-screen-recording").pipe(Effect.flip); - assert.equal(error.reason, "unsupported-session"); - }), - ).pipe(Effect.provide(layerTest("win32"))); -}); - -it.effect("registers macOS capture without accessibility permission when data is disabled", () => { - accessibilityTrustedMock.mockReset().mockReturnValue(false); - mediaAccessStatusMock.mockReset().mockReturnValue("granted"); - registerShortcutMock.mockReset().mockReturnValue(true); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure({ - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotIncludeAccessibility: false, - }); - - assert.lengthOf(accessibilityTrustedMock.mock.calls, 0); - assert.isTrue((yield* service.state).shortcutRegistered); - }), - ).pipe(Effect.provide(layerTest("darwin"))); -}); - -it.effect("starts the Shift listener outside the Electron main process", () => { - shortcutForkArgs.length = 0; - shortcutForkOptions.length = 0; - shortcutProcesses.length = 0; - const settings = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - const state = yield* service.state; - - assert.isTrue(state.shortcutRegistered); - assert.lengthOf(shortcutProcesses, 1); - assert.deepEqual(shortcutForkArgs[0], ["shift"]); - assert.strictEqual(shortcutForkOptions[0]?.env?.ELECTRON_RUN_AS_NODE, "1"); - - shortcutProcesses[0]?.emit("exit", 1); - yield* Effect.promise(() => new Promise((resolve) => queueMicrotask(resolve))); - assert.isFalse((yield* service.state).shortcutRegistered); - }), - ).pipe(Effect.provide(layerTest("win32"))); -}); - -it.effect("passes the configured modifier pair to the listener process", () => { - shortcutForkArgs.length = 0; - shortcutProcesses.length = 0; - const settings = { - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotShortcut: { kind: "modifier-pair", modifier: "meta" }, - } satisfies ClientSettings; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - const state = yield* service.state; - - assert.isTrue(state.shortcutRegistered); - assert.deepEqual(shortcutForkArgs[0], ["meta"]); - }), - ).pipe(Effect.provide(layerTest("win32"))); -}); - -it.effect("registers a configured key chord instead of the Shift listener", () => { - registerShortcutMock.mockReset().mockReturnValue(true); - shortcutProcesses.length = 0; - const settings = { - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotShortcut: { - key: "k", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: true, - modKey: false, - }, - }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - - assert.isTrue((yield* service.state).shortcutRegistered); - assert.strictEqual(registerShortcutMock.mock.calls[0]?.[0], "Control+Alt+K"); - assert.lengthOf(shortcutProcesses, 0); - }), - ).pipe(Effect.provide(layerTest("win32"))); -}); - it.effect("an unrelated client-setting change keeps the registered shortcut", () => { registerShortcutMock.mockReset().mockReturnValue(true); unregisterShortcutMock.mockReset(); @@ -3349,133 +1860,6 @@ it.effect("capture fails closed while snapshots are disabled", () => { ).pipe(Effect.provide(layerTest("win32"))); }); -it.effect("keeps shortcut registration errors off the capture status", () => { - registerShortcutMock.mockReset().mockReturnValue(false); - const settings = { - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotShortcut: { - key: "k", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: true, - modKey: false, - }, - }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - - const state = yield* service.state; - assert.isNull(state.message); - assert.equal( - state.shortcutMessage, - "This shortcut is already used by the system or another app.", - ); - }), - ).pipe(Effect.provide(layerTest("win32"))); -}); - -it.effect("uses an external Niri shortcut without registering an Electron accelerator", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - vi.stubEnv("XDG_CURRENT_DESKTOP", "niri"); - vi.stubEnv("NIRI_SOCKET", "/test/niri.sock"); - registerShortcutMock.mockReset(); - niriShortcutStopMock.mockReset(); - niriShortcutMock.mockReset().mockResolvedValue(niriShortcutStopMock); - const settings = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true }; - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - const state = yield* service.state; - assert.isFalse(state.shortcutRegistered); - assert.include(state.shortcutBinding, "gdbus"); - assert.match(state.shortcutBinding ?? "", /^Ctrl\+Shift\+2 repeat=false \{/); - assert.include(state.shortcutMessage, "Niri config"); - assert.isTrue(state.shortcutActionRegistered); - assert.lengthOf(registerShortcutMock.mock.calls, 0); - assert.lengthOf(niriShortcutMock.mock.calls, 1); - assert.isFalse((yield* service.checkShortcut(settings.snapShotShortcut)).available); - yield* Effect.promise(async () => { - await niriShortcutMock.mock.calls[0]![1](); - }); - assert.isTrue((yield* service.state).shortcutVerified); - yield* service.configure({ ...settings, snapShotEnabled: false }); - assert.lengthOf(niriShortcutStopMock.mock.calls, 1); - assert.isUndefined((yield* service.state).shortcutBinding); - }), - ).pipe( - Effect.provide(layerTest("linux")), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - -it.effect("defers ordinary Wayland shortcut registration until settings are applied", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - registerShortcutMock.mockReset().mockReturnValue(false); - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const conflict = yield* service.checkShortcut({ - key: "c", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: false, - modKey: false, - }); - const available = yield* service.checkShortcut({ - key: "2", - metaKey: false, - ctrlKey: true, - shiftKey: true, - altKey: false, - modKey: false, - }); - assert.isFalse(conflict.available); - assert.isTrue(available.available); - assert.match(available.message ?? "", /desktop will confirm/); - - const pair = yield* service.checkShortcut({ - kind: "modifier-pair", - modifier: "meta", - }); - assert.isFalse(pair.available); - assert.match(pair.message ?? "", /Modifier-pair shortcuts aren't available/); - assert.lengthOf(registerShortcutMock.mock.calls, 0); - }), - ).pipe( - Effect.provide(layerTest("linux")), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - -it.effect.each(["GNOME", "KDE", "niri", "Hyprland"] as const)( - "identifies %s in setup even when its capability check fails", - (desktop) => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - vi.stubEnv("XDG_CURRENT_DESKTOP", desktop); - linuxBackendMock.mockRejectedValueOnce(new Error("Capability check failed")); - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const state = yield* service.state; - assert.equal(state.linuxDesktop, desktop.toLowerCase()); - assert.equal(state.message, "Capability check failed"); - assert.isFalse(state.shortcutVerified); - }), - ).pipe( - Effect.provide(layerTest("linux")), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); - }, -); - it.effect( "keeps saved preferences but rechecks access and shortcut delivery after changing desktops", () => { @@ -3550,85 +1934,6 @@ it.effect( }, ); -it.effect("does not register a Wayland modifier-pair shortcut when enabled", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - registerShortcutMock.mockReset().mockReturnValue(true); - const settings = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - - const state = yield* service.state; - assert.lengthOf(registerShortcutMock.mock.calls, 0); - assert.isFalse(state.shortcutRegistered); - assert.deepEqual(state.shortcut, DEFAULT_CLIENT_SETTINGS.snapShotShortcut); - assert.match(state.shortcutMessage ?? "", /Modifier-pair shortcuts aren't available/); - }), - ).pipe( - Effect.provide(layerTest("linux")), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - -it.effect("exposes pending portal permission and then the real assigned shortcut", () => { - vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - registerShortcutMock.mockReset().mockReturnValue(true); - nextPortalState.value = { - shortcutRegistered: false, - shortcutPending: true, - shortcutMessage: "Waiting for permission", - }; - const shortcut = { - key: "2", - metaKey: false, - ctrlKey: true, - shiftKey: true, - altKey: false, - modKey: false, - } as const; - const settings = { - ...DEFAULT_CLIENT_SETTINGS, - snapShotEnabled: true, - snapShotShortcut: shortcut, - }; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure(settings); - - const state = yield* service.state; - assert.lengthOf(registerShortcutMock.mock.calls, 0); - assert.isFalse(state.shortcutRegistered); - assert.isTrue(state.shortcutPending); - assert.deepEqual(state.shortcut, shortcut); - assert.equal(state.shortcutMessage, "Waiting for permission"); - - portalShortcutInstances[0]!.state = { - shortcutRegistered: true, - shortcutPending: false, - shortcutLabel: "Ctrl+Shift+7", - shortcutMessage: null, - }; - assert.equal((yield* service.state).shortcutLabel, "Ctrl+Shift+7"); - assert.isTrue((yield* service.state).shortcutRegistered); - portalShortcutInstances[0]!.state = { - shortcutRegistered: false, - shortcutPending: false, - shortcutMessage: "Permission denied", - }; - const failed = yield* service.state; - assert.isFalse(failed.shortcutRegistered); - assert.equal(failed.shortcutMessage, "Permission denied"); - }), - ).pipe( - Effect.provide(layerTest("linux")), - Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs())), - ); -}); - it.effect("verifies only native shortcut delivery and captures normally", () => { vi.stubEnv("XDG_SESSION_TYPE", "wayland"); vi.stubEnv("XDG_CURRENT_DESKTOP", "test-desktop"); @@ -3785,58 +2090,6 @@ it.effect( }, ); -it.effect("advises about the system menu for a meta pair on Windows", () => - Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const result = yield* service.checkShortcut({ kind: "modifier-pair", modifier: "meta" }); - assert.isTrue(result.available); - assert.match(result.message ?? "", /Super \+ Super is observed/); - assert.match(result.message ?? "", /system's own menu/); - }), - ).pipe(Effect.provide(layerTest("win32"))), -); - -it.effect("probes macOS modifier pairs with the flags poller", () => { - spawnedPollers.length = 0; - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const result = yield* service.checkShortcut({ kind: "both-shift-keys" }); - assert.isTrue(result.available); - assert.match(result.message ?? "", /Shift \+ Shift is observed/); - assert.notMatch(result.message ?? "", /Input Monitoring/); - assert.lengthOf(spawnedPollers, 1); - assert.deepEqual(spawnedPollers[0]?.args.slice(-2), ["2", "4"]); - assert.strictEqual(spawnedPollers[0]?.kill.mock.calls.length, 1); - }), - ).pipe(Effect.provide(layerTest("darwin"))); -}); - -it.effect("registers macOS modifier pairs through the flags poller", () => { - spawnedPollers.length = 0; - shortcutProcesses.length = 0; - accessibilityTrustedMock.mockReturnValue(true); - mediaAccessStatusMock.mockReturnValue("granted"); - const settings = { - ...DEFAULT_CLIENT_SETTINGS, - snapShotShortcut: { kind: "modifier-pair", modifier: "meta" }, - } satisfies ClientSettings; - - return Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - yield* service.configure({ ...settings, snapShotEnabled: true }); - const state = yield* service.state; - - assert.lengthOf(shortcutProcesses, 0); - assert.lengthOf(spawnedPollers, 1); - assert.deepEqual(spawnedPollers[0]?.args.slice(-2), ["8", "16"]); - assert.isTrue(state.shortcutRegistered); - }), - ).pipe(Effect.provide(layerTest("darwin"))); -}); - it.effect("waits to apply settings while permissions are pending", () => { accessibilityTrustedMock.mockReturnValue(true); mediaAccessStatusMock.mockReturnValueOnce("not-determined").mockReturnValue("granted"); @@ -3893,6 +2146,10 @@ it.effect.each([false, true])( if (fails) { const error = yield* service.setup("test-mac-capture").pipe(Effect.flip); assert.equal(error.reason, "setup-failed"); + assert.equal( + error.message, + 'Could not capture a test snapshot. Capturing the window failed. macOS grants Screen Recording and Accessibility to each app separately. In System Settings, open Privacy & Security and check that "T3 Code (Dev)" is allowed for both.', + ); } else yield* service.setup("test-mac-capture"); assert.equal(macCaptureMock.mock.calls.length, 1); assert.equal(macCaptureMock.mock.calls[0]?.[0], active); @@ -3916,13 +2173,3 @@ it.effect.each([false, true])( ); }, ); - -it.effect("rejects macOS test capture on other platforms", () => - Effect.scoped( - Effect.gen(function* () { - const service = yield* DesktopSnapShot.make; - const error = yield* service.setup("test-mac-capture").pipe(Effect.flip); - assert.equal(error.reason, "unsupported-session"); - }), - ).pipe(Effect.provide(layerTest("win32"))), -); diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index 68026f6b81917..e2f1c6e82a366 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -30,6 +30,7 @@ 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 Predicate from "effect/Predicate"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; @@ -210,10 +211,35 @@ export class DesktopSnapShotSetupError extends Schema.TaggedError, "prefersReducedMotion" | "shouldRenderRichAnimation" @@ -250,11 +284,11 @@ function captureMode(platform: NodeJS.Platform): DesktopSnapShotState["mode"] { return platform === "darwin" || platform === "win32" ? "direct" : "unavailable"; } -export function shouldAnimateSnapShot(settings: SnapShotSystemAnimationSettings): boolean { +function shouldAnimateSnapShot(settings: SnapShotSystemAnimationSettings): boolean { return settings.shouldRenderRichAnimation && !settings.prefersReducedMotion; } -export function snapShotThumbnailSize(active: ActiveWindow | undefined): Electron.Size { +function snapShotThumbnailSize(active: ActiveWindow | undefined): Electron.Size { if (!active) return { width: 2_560, height: 1_600 }; return { width: Math.min(Math.max(active.bounds.width, 1), MAX_CAPTURE_WIDTH), @@ -262,7 +296,7 @@ export function snapShotThumbnailSize(active: ActiveWindow | undefined): Electro }; } -export function snapShotIconDataUrl( +function snapShotIconDataUrl( ...icons: ReadonlyArray ): string | undefined { const icon = icons.find((candidate): candidate is Electron.NativeImage => @@ -285,7 +319,7 @@ async function appFileIcon( return Electron.app.getFileIcon(path, { size: "normal" }).catch(() => undefined); } -export async function iconDataUrl( +async function iconDataUrl( source: { readonly appIcon?: Electron.NativeImage | null }, active: ActiveWindow | undefined, platform: NodeJS.Platform, @@ -626,7 +660,7 @@ export class SnapShotFlash { } } -export function snapShotFlashBounds( +function snapShotFlashBounds( active: ActiveWindow | undefined, platform: NodeJS.Platform, ): Electron.Rectangle { @@ -864,8 +898,7 @@ export const make = Effect.gen(function* () { const imageTempPath = path.join(captureDirectory, `${id}.tmp.png`); return yield* Effect.gen(function* () { - // Retire feedback before reading screen pixels, so a rapid capture cannot - // photograph the previous capture's overlay. + // Retire feedback before capture so rapid captures cannot photograph the previous overlay. closeLinuxFeedback(); flash.dispose(); transition.dispose(); @@ -994,7 +1027,8 @@ export const make = Effect.gen(function* () { }).pipe(Effect.withSpan("desktop.snapShot.capture")); const captureFromShortcut = Effect.gen(function* () { - if (shortcutSuppressed) return; + // Repeated shortcuts must not replace a capture during its flight. + if (shortcutSuppressed || transition.isAnimating) return; shortcutVerified = true; const now = yield* Clock.currentTimeNanos; if (lastShortcutAt !== undefined && now - lastShortcutAt < SHORTCUT_COOLDOWN_NS) return; @@ -1099,9 +1133,7 @@ export const make = Effect.gen(function* () { transition.dispose(); closeLinuxFeedback(); } - // Every client-settings save lands here. Only the fields that decide which - // shortcut listener runs may tear it down; a font-size change must not - // uninstall a global keyboard hook or drop an approved portal session. + // Unrelated settings saves must not uninstall the keyboard hook or drop an approved portal session. const shortcutInputsChanged = settings.snapShotEnabled !== previousSettings.snapShotEnabled || settings.snapShotIncludeAccessibility !== previousSettings.snapShotIncludeAccessibility || @@ -1325,23 +1357,50 @@ export const make = Effect.gen(function* () { return yield* new DesktopSnapShotSetupError({ action, reason: "unsupported-session" }); yield* Effect.scoped( Effect.gen(function* () { - const directory = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-snapshot-test-", - }); - yield* Effect.tryPromise(async () => { - const active = await activeWindow("darwin"); - if (!active) throw new Error("No window is available to test capture."); - await captureMacWindowSnapshot( - active, - path.join(directory, "test.png"), - snapShotThumbnailSize(active), + const directory = yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3-snapshot-test-" }) + .pipe( + Effect.mapError( + (cause) => new DesktopSnapShotSetupError({ action, reason: "setup-failed", cause }), + ), ); + const active = yield* Effect.tryPromise({ + try: () => activeWindow("darwin"), + catch: (cause) => + new DesktopSnapShotSetupError({ + action, + reason: "setup-failed", + step: "find-window", + ...macCommandFailure(cause), + appName: environment.displayName, + cause, + }), + }); + if (!active) + return yield* new DesktopSnapShotSetupError({ + action, + reason: "setup-failed", + step: "find-window", + status: "missing", + }); + yield* Effect.tryPromise({ + try: () => + captureMacWindowSnapshot( + active, + path.join(directory, "test.png"), + snapShotThumbnailSize(active), + ), + catch: (cause) => + new DesktopSnapShotSetupError({ + action, + reason: "setup-failed", + step: "capture-window", + ...macCommandFailure(cause), + appName: environment.displayName, + cause, + }), }); }), - ).pipe( - Effect.mapError( - (cause) => new DesktopSnapShotSetupError({ action, reason: "setup-failed", cause }), - ), ); return; } else if (action === "install-kde-helper" || action === "remove-kde-helper") { @@ -1640,8 +1699,8 @@ export const make = Effect.gen(function* () { ), Effect.mapError((cause) => new DesktopSnapShotError({ operation: "list-pending", cause })), ), - read: (id) => - Effect.gen(function* () { + read: Effect.fn("DesktopSnapShot.read")( + function* (id) { const metadata = yield* fileSystem .readFileString(path.join(captureDirectory, `${id}.json`)) .pipe(Effect.flatMap(decodePendingCaptureJson)); @@ -1650,11 +1709,14 @@ export const make = Effect.gen(function* () { ...metadata, dataUrl: `data:image/png;base64,${Base64.encode(png)}`, }; - }).pipe( - Effect.mapError( - (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }), + }, + (effect, id) => + effect.pipe( + Effect.mapError( + (cause) => new DesktopSnapShotError({ operation: "read", captureId: id, cause }), + ), ), - ), + ), setAnimationDestination: (id, destination) => Effect.promise(async () => { if (linuxFeedback?.id === id && destination.relativeFrame) { diff --git a/apps/desktop/src/snapShot/GnomeCaptureSetup.test.ts b/apps/desktop/src/snapShot/GnomeCaptureSetup.test.ts index af2052c6a03aa..fd0bfdfd15dd5 100644 --- a/apps/desktop/src/snapShot/GnomeCaptureSetup.test.ts +++ b/apps/desktop/src/snapShot/GnomeCaptureSetup.test.ts @@ -5,11 +5,7 @@ import * as NodePath from "node:path"; import * as NodeEvents from "node:events"; import type { Message, MessageBus } from "dbus-next"; import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; -import { - GnomeCaptureSetup, - installGnomeCaptureBundle, - isGnomeCaptureSession, -} from "./GnomeCaptureSetup.ts"; +import { GnomeCaptureSetup, installGnomeCaptureBundle } from "./GnomeCaptureSetup.ts"; import { GNOME_CAPTURE_FILES, GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts"; let dataHome: string; @@ -117,13 +113,9 @@ it("refuses to replace symlinks or downgrade a newer extension", async () => { }); it.each([ - [{}, "not-installed"], - [{ state: 2, version: 3 }, "disabled"], [{ state: 1, version: 3 }, "enabled"], - [{ state: 1, version: 1 }, "update-required"], [{ state: 1, version: 2, shell: "51.0" }, "update-required"], [{ state: 2, version: 3, enabled: false }, "extensions-disabled"], - [{ state: 3, version: 3, error: "Load failed" }, "error"], [{ shell: "52.0" }, "unsupported"], ] as const)("reports GNOME setup state %j", async (options, status) => { const { setup, call } = fixture(options); @@ -147,31 +139,6 @@ it("requires login for local installs and updates until the new version is loade setup.close(); }); -it("installs only on explicit action without invoking remote installation", async () => { - const { setup, call } = fixture(); - await setup.perform("install-extension"); - expect(await NodeFSP.readdir(installedPath())).toHaveLength(GNOME_CAPTURE_FILES.length); - expect( - call.mock.calls.every(([message]) => ["GetAll", "GetExtensionInfo"].includes(message.member)), - ).toBe(true); - setup.close(); -}); - -it("enables and disables only the capture UUID", async () => { - const { setup, call } = fixture({ state: 2, version: 3 }); - await setup.perform("enable-extension"); - await setup.perform("disable-extension"); - for (const member of ["EnableExtension", "DisableExtension"]) { - expect(call.mock.calls.find(([message]) => message.member === member)?.[0]).toMatchObject({ - destination: "org.gnome.Shell", - path: "/org/gnome/Shell", - signature: "s", - body: [GNOME_CAPTURE_UUID], - }); - } - setup.close(); -}); - it("never changes the global user-extensions preference", async () => { const { setup, call } = fixture({ state: 2, version: 3, enabled: false }); await expect(setup.perform("enable-extension")).rejects.toThrow("GNOME has disabled"); @@ -186,9 +153,3 @@ it("surfaces desktop rejection and disconnect as actionable failures", async () expect(await setup.state()).toEqual({ status: "error", message: "Session bus disconnected" }); setup.close(); }); - -it("does not offer host extension installation in another desktop or sandbox", () => { - expect(isGnomeCaptureSession({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBe(true); - expect(isGnomeCaptureSession({ XDG_CURRENT_DESKTOP: "niri", GDMSESSION: "gnome" })).toBe(false); - expect(isGnomeCaptureSession({ XDG_CURRENT_DESKTOP: "GNOME", FLATPAK_ID: "com.t3" })).toBe(false); -}); diff --git a/apps/desktop/src/snapShot/GnomeCaptureSetup.ts b/apps/desktop/src/snapShot/GnomeCaptureSetup.ts index cc4ada0d57ab0..5979bf3b000c7 100644 --- a/apps/desktop/src/snapShot/GnomeCaptureSetup.ts +++ b/apps/desktop/src/snapShot/GnomeCaptureSetup.ts @@ -7,7 +7,6 @@ import * as Schema from "effect/Schema"; import type { DesktopCaptureExtensionState } from "@t3tools/contracts"; import { GNOME_CAPTURE_FILES, GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts"; -export { isGnomeCaptureSession } from "./linuxCaptureSession.ts"; const SHELL = "org.gnome.Shell"; const SHELL_PATH = "/org/gnome/Shell"; diff --git a/apps/desktop/src/snapShot/HyprlandSnapShot.test.ts b/apps/desktop/src/snapShot/HyprlandSnapShot.test.ts index fe55319ecea4b..525e57b34938b 100644 --- a/apps/desktop/src/snapShot/HyprlandSnapShot.test.ts +++ b/apps/desktop/src/snapShot/HyprlandSnapShot.test.ts @@ -17,7 +17,6 @@ import { captureHyprlandWindow, hyprlandCaptureExecutable, hyprlandCaptureShortcut, - isHyprlandCaptureSession, } from "./HyprlandSnapShot.ts"; let directory: string; @@ -67,22 +66,6 @@ beforeEach(async () => { afterEach(async () => { await NodeFSP.rm(directory, { recursive: true, force: true }); }); - -it("does not select Hyprland from a stale socket environment or sandbox", () => { - expect(isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe(true); - expect( - isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "KDE", HYPRLAND_INSTANCE_SIGNATURE: "old" }), - ).toBe(false); - expect(isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "Hyprland", FLATPAK_ID: "app" })).toBe( - false, - ); - expect(isHyprlandCaptureSession({ XDG_CURRENT_DESKTOP: "Hyprland", SNAP: "app" })).toBe(false); -}); -it("discovery neither installs a helper nor requests a screenshot", async () => { - expect((await setup.state()).status).toBe("not-installed"); - expect(execute).not.toHaveBeenCalled(); - await expect(NodeFSP.stat(paths.dataHome)).rejects.toMatchObject({ code: "ENOENT" }); -}); it("installs offline at a stable executable path and probes only capabilities", async () => { await setup.perform("install-hyprland-helper"); expect((await NodeFSP.stat(hyprlandCaptureExecutable(paths))).mode & 0o777).toBe(0o755); diff --git a/apps/desktop/src/snapShot/KdeSnapShot.test.ts b/apps/desktop/src/snapShot/KdeSnapShot.test.ts index 2093be868e67e..199af10e8ff96 100644 --- a/apps/desktop/src/snapShot/KdeSnapShot.test.ts +++ b/apps/desktop/src/snapShot/KdeSnapShot.test.ts @@ -13,13 +13,7 @@ vi.mock("electron", () => ({ createFromBuffer: () => ({ isEmpty: () => false, getSize: () => ({ width: 2, height: 1 }) }), }, })); -import { - KdeCaptureSetup, - captureKdeWindow, - isKdeCaptureSession, - kdeCaptureDesktopEntry, - kdeCapturePaths, -} from "./KdeSnapShot.ts"; +import { KdeCaptureSetup, captureKdeWindow, kdeCapturePaths } from "./KdeSnapShot.ts"; let directory: string; let paths: { bundle: string; dataHome: string }; @@ -73,48 +67,6 @@ afterEach(async () => { await NodeFSP.rm(directory, { recursive: true, force: true }); }); -it("detects KDE only outside a sandbox", () => { - expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "KDE" })).toBe(true); - expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "GNOME" })).toBe(false); - expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "KDE", FLATPAK_ID: "app" })).toBe(false); - expect(isKdeCaptureSession({ XDG_CURRENT_DESKTOP: "KDE", SNAP: "/snap/app" })).toBe(false); -}); - -it("does not install or request screenshots during initial discovery", async () => { - expect((await setup.state()).status).toBe("not-installed"); - expect(execute).not.toHaveBeenCalled(); - await expect(NodeFSP.stat(paths.dataHome)).rejects.toMatchObject({ code: "ENOENT" }); -}); - -it("installs offline at a stable path and verifies permissions using the installed identity", async () => { - await setup.perform("install-kde-helper"); - const { executable, desktop } = kdeCapturePaths(paths); - expect(await NodeFSP.readFile(executable, "utf8")).toBe("bundled executable"); - expect((await NodeFSP.stat(executable)).mode & 0o777).toBe(0o755); - expect(await NodeFSP.readFile(desktop, "utf8")).toBe(kdeCaptureDesktopEntry(executable)); - expect(kdeCaptureDesktopEntry(executable)).toContain(`Exec="${executable}" check`); - expect((await setup.state()).status).toBe("ready"); - expect((await setup.state()).feedbackAvailable).toBe(true); - expect(execute.mock.calls.map(([file, args]) => [file, args])).toEqual([ - ["kbuildsycoca6", ["--noincremental"]], - [ - "systemd-run", - [ - "--user", - "--quiet", - "--wait", - "--collect", - "--pipe", - "--service-type=exec", - "kbuildsycoca6", - "--noincremental", - ], - ], - [executable, ["check"]], - [executable, ["check"]], - ]); -}); - it("does not mistake installed files for KDE authorization, or fall back to a picker on denial", async () => { await setup.perform("install-kde-helper"); denial = true; diff --git a/apps/desktop/src/snapShot/KdeSnapShot.ts b/apps/desktop/src/snapShot/KdeSnapShot.ts index 5a90aa818fac8..50d9e700ee51e 100644 --- a/apps/desktop/src/snapShot/KdeSnapShot.ts +++ b/apps/desktop/src/snapShot/KdeSnapShot.ts @@ -29,7 +29,7 @@ export function kdeCapturePaths(paths: KdeCapturePaths) { }; } -export function kdeCaptureDesktopEntry(executable: string): string { +function kdeCaptureDesktopEntry(executable: string): string { return [ "[Desktop Entry]", "Type=Application", @@ -182,8 +182,7 @@ export class KdeCaptureSetup { } // KService must see the new desktop entry before KWin checks the executable. await run("kbuildsycoca6", ["--noincremental"]); - // AppImages change XDG search paths, and KService caches are also locale-specific. - // Refresh Plasma's cache in its session environment, not just the app's cache. + // AppImage search paths and locale affect KService caches; refresh in Plasma's session environment. await run("systemd-run", [ "--user", "--quiet", diff --git a/apps/desktop/src/snapShot/LinuxSnapShot.dbus.test.ts b/apps/desktop/src/snapShot/LinuxSnapShot.dbus.test.ts deleted file mode 100644 index 1cb75134ad07c..0000000000000 --- a/apps/desktop/src/snapShot/LinuxSnapShot.dbus.test.ts +++ /dev/null @@ -1,280 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- Isolated D-Bus integration fixture, never the user's session bus. -import * as NodeChildProcess from "node:child_process"; -import * as NodeEvents from "node:events"; -import * as NodeFSP from "node:fs/promises"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import * as NodeReadline from "node:readline"; -import * as NodeURL from "node:url"; -import { Message, NameFlag, Variant, sessionBus, type MessageBus } from "dbus-next"; -import { expect, it, vi } from "vite-plus/test"; - -vi.mock("electron", () => ({ - nativeImage: { - createFromBuffer: () => ({ - isEmpty: () => false, - getSize: () => ({ width: 800, height: 600 }), - }), - }, -})); -import { LinuxCaptureConnection } from "./LinuxSnapShot.ts"; -import { startNiriCaptureShortcut } from "./NiriCaptureShortcut.ts"; -import { GnomeCaptureSetup } from "./GnomeCaptureSetup.ts"; -import { GNOME_CAPTURE_UUID } from "./gnomeCaptureBundle.ts"; - -const hasDbus = - NodeChildProcess.spawnSync("dbus-daemon", ["--version"]).status === 0 && - NodeChildProcess.spawnSync("gdbus", ["help"]).status === 0; - -it.runIf(hasDbus)("captures through real D-Bus marshalling on a private bus", async () => { - const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-private-dbus-")); - let daemon: NodeChildProcess.ChildProcess | undefined; - let server: MessageBus | undefined; - const clients: LinuxCaptureConnection[] = []; - let stopNiriShortcut: (() => void) | undefined; - try { - vi.stubEnv("XDG_CURRENT_DESKTOP", "GNOME"); - vi.stubEnv("FLATPAK_ID", ""); - vi.stubEnv("SNAP", ""); - daemon = NodeChildProcess.spawn( - "dbus-daemon", - [ - "--session", - "--nofork", - "--nopidfile", - "--print-address", - `--address=unix:path=${NodePath.join(directory, "bus")}`, - ], - { stdio: ["ignore", "pipe", "pipe"] }, - ); - const lines = NodeReadline.createInterface({ input: daemon.stdout! }); - const [address] = await Promise.race([ - NodeEvents.EventEmitter.once(lines, "line"), - NodeEvents.EventEmitter.once(daemon, "exit").then(() => { - throw new Error("Private D-Bus daemon failed to start."); - }), - ]); - lines.close(); - server = sessionBus({ busAddress: String(address) }); - server.on("error", () => undefined); - await server.requestName("org.freedesktop.portal.Desktop", NameFlag.DO_NOT_QUEUE); - await server.requestName("org.gnome.Shell.Extensions.T3SnapShot", NameFlag.DO_NOT_QUEUE); - await server.requestName("org.gnome.Shell", NameFlag.DO_NOT_QUEUE); - await server.requestName("org.kde.KWin.ScreenShot2", NameFlag.DO_NOT_QUEUE); - const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]); - const imagePath = NodePath.join(directory, "image.png"); - await NodeFSP.writeFile(imagePath, png); - let portalVersion = 3; - let extensionVersion = 1; - let feedbackArgs: unknown[] | undefined; - let activateTitle: unknown; - let animateFrame: unknown[] | undefined; - let target: unknown; - let clientName: string | undefined; - let shellExtensionState = 2; - server.addMethodHandler((message: Message) => { - if (message.member === "Register") { - server!.send(Message.newMethodReturn(message)); - } else if (message.member === "GetAll") { - const properties = - message.body[0] === "org.gnome.Shell.Extensions" - ? { - ShellVersion: new Variant("s", "50.0"), - UserExtensionsEnabled: new Variant("b", true), - } - : message.body[0] === "org.kde.KWin.ScreenShot2" - ? { Version: new Variant("u", 5) } - : message.body[0] === "org.freedesktop.portal.Screenshot" - ? { - version: new Variant("u", portalVersion), - AvailableTargets: new Variant("u", 8), - } - : { Version: new Variant("u", extensionVersion) }; - server!.send(Message.newMethodReturn(message, "a{sv}", [properties])); - } else if (message.member === "GetExtensionInfo") { - server!.send( - Message.newMethodReturn(message, "a{sv}", [ - { state: new Variant("d", shellExtensionState), version: new Variant("d", 3) }, - ]), - ); - } else if (message.member === "EnableExtension" || message.member === "DisableExtension") { - expect(message.body).toEqual([GNOME_CAPTURE_UUID]); - shellExtensionState = message.member === "EnableExtension" ? 1 : 2; - server!.send(Message.newMethodReturn(message, "b", [true])); - } else if (message.member === "Screenshot") { - const options = message.body[1] as Record>; - target = options.target?.value; - const path = `/org/freedesktop/portal/desktop/request/${message.sender.slice(1).replaceAll(".", "_")}/${options.handle_token?.value}`; - // The real transport also has to handle Response before the method reply. - const signal = Message.newSignal( - path, - "org.freedesktop.portal.Request", - "Response", - "ua{sv}", - [0, { uri: new Variant("s", NodeURL.pathToFileURL(imagePath).href) }], - ); - signal.destination = message.sender; - server!.send(signal); - server!.send(Message.newMethodReturn(message, "o", [path])); - } else if (message.member === "Activate") { - activateTitle = message.body[0]; - server!.send(Message.newMethodReturn(message)); - } else if (message.member === "Animate") { - animateFrame = message.body; - server!.send(Message.newMethodReturn(message)); - } else if (message.member === "Capture" || message.member === "CaptureWithFeedback") { - const feedback = message.member === "CaptureWithFeedback"; - if (feedback) feedbackArgs = message.body; - clientName = message.sender; - server!.send( - Message.newMethodReturn(message, feedback ? "aysb" : "ays", [ - png, - JSON.stringify({ - title: "Editor", - appName: "Editor", - appIdentifier: "editor.desktop", - processId: 42, - bounds: { x: 0, y: 0, width: 800, height: 600 }, - }), - ...(feedback ? [true] : []), - ]), - ); - } else return false; - return true; - }); - const connect = () => { - const client = new LinuxCaptureConnection(sessionBus({ busAddress: String(address) })); - clients.push(client); - return client; - }; - const setup = new GnomeCaptureSetup( - { - bundle: NodePath.resolve(import.meta.dirname, "../../gnome-extension"), - dataHome: directory, - }, - sessionBus({ busAddress: String(address) }), - ); - try { - expect((await setup.state()).status).toBe("disabled"); - await setup.perform("enable-extension"); - expect((await setup.state()).status).toBe("enabled"); - await setup.perform("disable-extension"); - expect((await setup.state()).status).toBe("disabled"); - } finally { - setup.close(); - } - const portal = connect(); - expect(await portal.backend("com.t3tools.T3Code")).toBe("screenshot-portal"); - expect(await portal.capturePortal()).toEqual({ png }); - expect(target).toBe(8); - portalVersion = 2; - const extension = connect(); - expect(await extension.backend("com.t3tools.T3Code")).toBe("gnome-extension"); - expect(await extension.captureExtension("com.t3tools.T3Code")).toMatchObject({ - png, - window: { processId: 42 }, - }); - const owner = await server.call( - new Message({ - destination: "org.freedesktop.DBus", - path: "/org/freedesktop/DBus", - interface: "org.freedesktop.DBus", - member: "GetNameOwner", - signature: "s", - body: ["com.t3tools.T3Code.SnapShot"], - }), - ); - expect(owner?.body[0]).toBe(clientName); - extension.close(); - extensionVersion = 2; - const updated = connect(); - expect(await updated.backend("com.t3tools.T3Code")).toBe("gnome-extension"); - const snapshot = await updated.captureExtension("com.t3tools.T3Code", { - flash: true, - animate: true, - }); - expect(snapshot.feedback?.animationStarted).toBe(true); - await snapshot.feedback!.activate("T3 Code"); - await snapshot.feedback!.animateTo({ x: 0.1, y: 0.8, width: 0.2, height: 0.1 }); - await snapshot.feedback!.complete(); - expect(feedbackArgs).toEqual([true, true]); - expect(activateTitle).toBe("T3 Code"); - expect(animateFrame).toEqual([0.1, 0.8, 0.2, 0.1]); - vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE"); - const kde = connect(); - expect(await kde.backend("com.t3tools.T3Code")).toBe("kde"); - expect(kde.feedbackAvailable).toBe(false); - kde.close(); - const triggered = vi.fn(); - const failed = vi.fn(); - const niriBus = sessionBus({ busAddress: String(address) }); - stopNiriShortcut = await startNiriCaptureShortcut( - "com.t3tools.T3Code.NiriTest", - triggered, - failed, - niriBus, - ); - const command = [ - "call", - "--session", - "--dest", - "com.t3tools.T3Code.NiriTest.SnapShot", - "--object-path", - "/com/t3tools/SnapShot", - "--method", - "com.t3tools.SnapShot.Capture", - ]; - await new Promise((resolve, reject) => { - NodeChildProcess.execFile( - "gdbus", - command, - { - env: { ...process.env, DBUS_SESSION_BUS_ADDRESS: String(address) }, - timeout: 3_000, - }, - (error) => (error ? reject(error) : resolve()), - ); - }); - expect(triggered).toHaveBeenCalledOnce(); - expect(failed).not.toHaveBeenCalled(); - const invalid = server.call( - new Message({ - destination: "com.t3tools.T3Code.NiriTest.SnapShot", - path: "/com/t3tools/SnapShot", - interface: "com.t3tools.SnapShot", - member: "Capture", - signature: "s", - body: ["not allowed"], - }), - ); - await expect(invalid).rejects.toThrow("Capture takes no arguments"); - expect(triggered).toHaveBeenCalledOnce(); - await expect( - startNiriCaptureShortcut( - "com.t3tools.T3Code.NiriTest", - triggered, - failed, - sessionBus({ busAddress: String(address) }), - ), - ).rejects.toThrow("already owns"); - stopNiriShortcut(); - const restarted = await startNiriCaptureShortcut( - "com.t3tools.T3Code.NiriTest", - triggered, - failed, - sessionBus({ busAddress: String(address) }), - ); - restarted(); - } finally { - vi.unstubAllEnvs(); - stopNiriShortcut?.(); - for (const client of clients) client.close(); - server?.disconnect(); - if (daemon && daemon.exitCode === null) { - const exited = NodeEvents.EventEmitter.once(daemon, "exit"); - daemon.kill("SIGTERM"); - await exited; - } - await NodeFSP.rm(directory, { recursive: true }); - } -}); diff --git a/apps/desktop/src/snapShot/LinuxSnapShot.test.ts b/apps/desktop/src/snapShot/LinuxSnapShot.test.ts index 0ea9c08f935c0..49aa4dd721774 100644 --- a/apps/desktop/src/snapShot/LinuxSnapShot.test.ts +++ b/apps/desktop/src/snapShot/LinuxSnapShot.test.ts @@ -33,12 +33,7 @@ vi.mock("electron", () => ({ }, })); -import { - captureLinuxWindow, - getLinuxCaptureSupport, - readPortalPng, - resizeLinuxCapture, -} from "./LinuxSnapShot.ts"; +import { captureLinuxWindow, getLinuxCaptureSupport, readPortalPng } from "./LinuxSnapShot.ts"; const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0]); const appId = "com.t3tools.T3Code"; @@ -207,19 +202,6 @@ it("uses the standard path when KWin's native capability is missing, but not whe bus.kdeError = new DBusError("org.freedesktop.DBus.Error.AccessDenied", "Denied"); await expect(getLinuxCaptureSupport(appId)).rejects.toThrow("Denied"); }); - -it("does not fall through to the picker when KDE needs helper setup", async () => { - vi.stubEnv("XDG_CURRENT_DESKTOP", "KDE"); - await expect(captureLinuxWindow(appId)).rejects.toThrow("KDE capture setup"); - expect(bus.calls.some((call) => call.member === "Screenshot")).toBe(false); - expect(bus.disconnect).toHaveBeenCalledOnce(); -}); -it("selects Hyprland without probing a different desktop or falling back on missing setup", async () => { - vi.stubEnv("XDG_CURRENT_DESKTOP", "Hyprland"); - expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("hyprland"); - await expect(captureLinuxWindow(appId)).rejects.toThrow("Hyprland capture setup"); - expect(bus.calls).toEqual([]); -}); afterEach(async () => { vi.useRealTimers(); vi.unstubAllEnvs(); @@ -246,18 +228,6 @@ it.each([ }, ); -it.each([1, 2])( - "reports feedback separately from capture support for extension v%s", - async (version) => { - bus.portalVersion = 2; - bus.extensionVersion = version; - expect(await getLinuxCaptureSupport(appId)).toEqual({ - linuxBackend: "gnome-extension", - linuxFeedbackAvailable: version === 2, - }); - }, -); - it("retains the authenticated connection until the compositor flight has landed", async () => { bus.portalVersion = 2; bus.extensionVersion = 2; @@ -294,19 +264,6 @@ it("keeps capture working with v1 and does not request unavailable effects", asy expect(bus.disconnect).toHaveBeenCalledOnce(); }); -it("can activate without animation, and expires a renderer-abandoned capture", async () => { - vi.useFakeTimers(); - bus.portalVersion = 2; - bus.extensionVersion = 2; - const snapshot = await captureLinuxWindow(appId, { flash: false, animate: false }); - expect(snapshot!.feedback!.animationStarted).toBe(false); - bus.activationError = new Error("No window"); - await expect(snapshot!.feedback!.activate("T3 Code")).rejects.toThrow("No window"); - expect(snapshot!.png).toEqual(png); - await vi.advanceTimersByTimeAsync(15_000); - expect(bus.disconnect).toHaveBeenCalledOnce(); -}); - it.each([false, true])( "accepts an early Response with a changed request path: %s", async (differentHandle) => { @@ -338,52 +295,6 @@ it.each([1, 2])( }, ); -it("does not downgrade a failed screenshot request", async () => { - bus.screenshotError = new DBusError("org.freedesktop.DBus.Error.AccessDenied", "Denied"); - await expect(captureLinuxWindow(appId)).rejects.toThrow("Denied"); - expect(bus.send).toHaveBeenCalledWith(expect.objectContaining({ member: "Close" })); - expect(bus.disconnect).toHaveBeenCalledOnce(); -}); - -it.each([false, true])( - "times out and closes requests, ignoring forged responses: %s", - async (wrongSender) => { - vi.useFakeTimers(); - bus.sendResponse = wrongSender; - bus.wrongSender = wrongSender; - const capture = expect(captureLinuxWindow(appId)).rejects.toThrow("timed out"); - await vi.advanceTimersByTimeAsync(120_001); - await capture; - expect(bus.send).toHaveBeenCalledWith(expect.objectContaining({ member: "Close" })); - expect(bus.listenerCount("message")).toBe(0); - expect(bus.disconnect).toHaveBeenCalledOnce(); - }, -); - -it("uses the GNOME extension and preserves its window identity", async () => { - bus.portalVersion = 2; - bus.extensionVersion = 1; - expect(await captureLinuxWindow(appId)).toEqual({ png, window: metadata }); - expect(bus.requestName).toHaveBeenCalledWith(`${appId}.SnapShot`, expect.any(Number)); - expect(bus.calls.some((call) => call.member === "Screenshot")).toBe(false); -}); - -it("fails instead of opening a picker after an extension denial", async () => { - bus.portalVersion = 2; - bus.extensionVersion = 1; - bus.extensionError = new Error("Locked session"); - await expect(captureLinuxWindow(appId)).rejects.toThrow("Locked session"); - expect(bus.disconnect).toHaveBeenCalledOnce(); -}); - -it("allows the picker only when both automatic backends are absent", async () => { - bus.portalVersion = 2; - expect(await captureLinuxWindow(appId)).toBeUndefined(); - expect(bus.calls.some((call) => call.member === "Screenshot" || call.member === "Capture")).toBe( - false, - ); -}); - it("tolerates an older portal without Registry, but not registration denial", async () => { bus.registryError = new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "Old portal"); expect((await getLinuxCaptureSupport(appId)).linuxBackend).toBe("screenshot-portal"); @@ -405,10 +316,3 @@ it("reads only local PNG files without removing the portal file", async () => { await NodeFSP.writeFile(NodePath.join(directory, "image.png"), "not a PNG"); await expect(readPortalPng(bus.uri)).rejects.toThrow("Invalid"); }); - -it("bounds large images without distorting their aspect ratio", () => { - imageSize.width = 4000; - imageSize.height = 2000; - resizeLinuxCapture(png); - expect(resize).toHaveBeenLastCalledWith({ width: 2560, height: 1280, quality: "best" }); -}); diff --git a/apps/desktop/src/snapShot/LinuxSnapShot.ts b/apps/desktop/src/snapShot/LinuxSnapShot.ts index 8603232e7e9fc..3d05c5eecceb8 100644 --- a/apps/desktop/src/snapShot/LinuxSnapShot.ts +++ b/apps/desktop/src/snapShot/LinuxSnapShot.ts @@ -17,7 +17,7 @@ import { import * as Schema from "effect/Schema"; import { isKdeCaptureSession, type KdeCapturePaths } from "./KdeSnapShot.ts"; import { isGnomeCaptureSession, readPortalPng, resizeLinuxCapture } from "./linuxCaptureSession.ts"; -export { readPortalPng, resizeLinuxCapture } from "./linuxCaptureSession.ts"; +export { readPortalPng } from "./linuxCaptureSession.ts"; import { isHyprlandCaptureSession, type HyprlandCapturePaths } from "./HyprlandSnapShot.ts"; const PORTAL = "org.freedesktop.portal.Desktop"; @@ -98,7 +98,7 @@ function unavailable(error: unknown): boolean { } /** One connection per operation: portal registration and request ownership stay together. */ -export class LinuxCaptureConnection { +class LinuxCaptureConnection { private readonly bus: MessageBus; private readonly disconnected: Promise; private uniqueName = ""; diff --git a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.test.ts b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.test.ts deleted file mode 100644 index 81889f9f07eb5..0000000000000 --- a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { describe, expect, it, vi } from "vite-plus/test"; - -const { spawnedPollers } = vi.hoisted(() => ({ - spawnedPollers: [] as Array<{ - command: string; - args: ReadonlyArray; - kill: ReturnType; - emitStderr: (text: string) => void; - emitExit: (code: number) => void; - }>, -})); - -vi.mock("node:child_process", () => ({ - spawn: (command: string, args: ReadonlyArray) => { - const stderrListeners: Array<(chunk: Buffer) => void> = []; - const onceListeners = new Map void>>(); - const record = { - command, - args, - kill: vi.fn(() => true), - emitStderr: (text: string) => { - for (const listener of stderrListeners) listener(Buffer.from(text)); - }, - emitExit: (code: number) => { - for (const listener of onceListeners.get("exit") ?? []) listener(code); - }, - }; - spawnedPollers.push(record); - const child = { - stderr: { - on: (_event: "data", listener: (chunk: Buffer) => void) => { - stderrListeners.push(listener); - return child; - }, - }, - once: (event: string, listener: (value?: unknown) => void) => { - onceListeners.set(event, [...(onceListeners.get(event) ?? []), listener]); - return child; - }, - kill: record.kill, - }; - return child; - }, -})); - -import { startMacModifierPairShortcutProcess } from "./MacModifierPairShortcutProcess.ts"; - -describe("macOS modifier pair poller", () => { - it("resolves on ready, triggers on lines, and kills on stop", async () => { - spawnedPollers.length = 0; - const onTrigger = vi.fn(); - const onFailure = vi.fn(); - const started = startMacModifierPairShortcutProcess("meta", onTrigger, onFailure); - const poller = spawnedPollers[0]!; - expect(poller.command).toBe("/usr/bin/osascript"); - expect(poller.args.slice(-2)).toEqual(["8", "16"]); - - poller.emitStderr("ready\ntrig"); - const stop = await started; - poller.emitStderr("ger\ntrigger\n"); - expect(onTrigger).toHaveBeenCalledTimes(2); - - stop(); - expect(poller.kill).toHaveBeenCalledOnce(); - poller.emitStderr("trigger\n"); - expect(onTrigger).toHaveBeenCalledTimes(2); - poller.emitExit(0); - expect(onFailure).not.toHaveBeenCalled(); - }); - - it("reports an unexpected exit after startup", async () => { - spawnedPollers.length = 0; - const onFailure = vi.fn(); - const started = startMacModifierPairShortcutProcess("shift", () => undefined, onFailure); - const poller = spawnedPollers[0]!; - poller.emitStderr("ready\n"); - await started; - - poller.emitExit(1); - expect(onFailure).toHaveBeenCalledOnce(); - }); - - it("rejects when the poller dies before it is ready", async () => { - spawnedPollers.length = 0; - const started = startMacModifierPairShortcutProcess( - "control", - () => undefined, - () => undefined, - ); - spawnedPollers[0]!.emitExit(1); - await expect(started).rejects.toThrow(/exited with code 1/); - }); -}); diff --git a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts index ad7b2e03c4954..117ffa652566b 100644 --- a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts +++ b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts @@ -11,8 +11,7 @@ const MAC_MODIFIER_PAIR_DEVICE_MASKS: Record ({ - createFromBufferMock: vi.fn(), - execFileMock: vi.fn(), - readFileMock: vi.fn(), - writeFileMock: vi.fn(), -})); - -vi.mock("node:child_process", () => ({ execFile: execFileMock })); -vi.mock("node:fs/promises", () => ({ readFile: readFileMock, writeFile: writeFileMock })); -vi.mock("electron", () => ({ nativeImage: { createFromBuffer: createFromBufferMock } })); - -import { captureMacWindowSnapshot, macSnapShotArguments } from "./MacSnapShot.ts"; - -beforeEach(() => { - execFileMock - .mockReset() - .mockImplementation( - ( - _path: string, - _args: ReadonlyArray, - _options: { readonly timeout: number }, - callback: (error: Error | null) => void, - ) => callback(null), - ); - readFileMock.mockReset(); - writeFileMock.mockReset(); - createFromBufferMock.mockReset().mockReturnValue({ - getSize: () => ({ width: 100, height: 80 }), - isEmpty: () => false, - }); -}); - -it("captures one macOS window directly as a silent shadowless PNG", async () => { - const png = Buffer.concat([ - Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), - Buffer.from("image"), - ]); - readFileMock.mockResolvedValue(png); - const active = { - id: 42, - title: "Editor", - owner: { name: "Code" }, - } as Parameters[0]; - - const capture = await captureMacWindowSnapshot(active, "/tmp/window.png", { - width: 100, - height: 80, - }); - - assert.deepEqual(execFileMock.mock.calls[0]?.slice(0, 3), [ - "/usr/sbin/screencapture", - macSnapShotArguments(42, "/tmp/window.png"), - { timeout: 15_000 }, - ]); - assert.deepEqual(readFileMock.mock.calls, [["/tmp/window.png"]]); - assert.lengthOf(writeFileMock.mock.calls, 0); - assert.strictEqual(capture.png, png); - assert.deepEqual(capture.source, { name: "Editor" }); -}); - -it("bounds Retina captures without changing their aspect ratio", async () => { - const capturedPng = Buffer.concat([ - Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), - Buffer.from("retina"), - ]); - const resizedPng = Buffer.from("bounded png"); - const resizeMock = vi.fn().mockReturnValue({ toPNG: () => resizedPng }); - readFileMock.mockResolvedValue(capturedPng); - createFromBufferMock.mockReturnValue({ - getSize: () => ({ width: 2_000, height: 1_200 }), - isEmpty: () => false, - resize: resizeMock, - }); - const active = { - id: 42, - title: "Editor", - owner: { name: "Code" }, - } as Parameters[0]; - - const capture = await captureMacWindowSnapshot(active, "/tmp/window.png", { - width: 1_000, - height: 1_000, - }); - - assert.deepEqual(resizeMock.mock.calls, [[{ width: 1_000, height: 600, quality: "best" }]]); - assert.deepEqual(writeFileMock.mock.calls, [["/tmp/window.png", resizedPng]]); - assert.strictEqual(capture.png, resizedPng); -}); - -it("rejects a successful command that did not produce a PNG", async () => { - readFileMock.mockResolvedValue(Buffer.from("not a png")); - const active = { - id: 42, - title: "", - owner: { name: "Code" }, - } as Parameters[0]; - - await expect( - captureMacWindowSnapshot(active, "/tmp/window.png", { width: 100, height: 80 }), - ).rejects.toThrow("macOS returned an invalid snapshot."); -}); diff --git a/apps/desktop/src/snapShot/MacSnapShot.ts b/apps/desktop/src/snapShot/MacSnapShot.ts index f56c35cb56e09..e987a8fe202ed 100644 --- a/apps/desktop/src/snapShot/MacSnapShot.ts +++ b/apps/desktop/src/snapShot/MacSnapShot.ts @@ -15,7 +15,7 @@ export type MacSnapShotSource = { readonly name: string; }; -export function macSnapShotArguments(windowId: number, outputPath: string): string[] { +function macSnapShotArguments(windowId: number, outputPath: string): string[] { return ["-l", String(windowId), "-o", "-x", "-t", "png", outputPath]; } diff --git a/apps/desktop/src/snapShot/NativeCaptureFeedback.test.ts b/apps/desktop/src/snapShot/NativeCaptureFeedback.test.ts index c0ca5dc877711..ee017fac4086e 100644 --- a/apps/desktop/src/snapShot/NativeCaptureFeedback.test.ts +++ b/apps/desktop/src/snapShot/NativeCaptureFeedback.test.ts @@ -69,36 +69,6 @@ it("waits for compositor readiness and landing, then waits for cleanup on acknow expect(vi.getTimerCount()).toBe(0); }); -it("doesn't claim a flight when the compositor disables motion; flash still works", async () => { - const starting = startNativeCaptureFeedback("/helper", "/private", options); - event({ event: "ready", animate: false }); - const feedback = (await starting)!; - expect(feedback.animationStarted).toBe(false); - await feedback.animateTo("Draft", { x: 0, y: 0, width: 1, height: 1 }); - expect(commands).toEqual([]); - const complete = feedback.complete(); - child.emit("close"); - await complete; -}); - -it("falls back on startup failure, malformed replies, and timeout without leaving timers", async () => { - const starting = startNativeCaptureFeedback("/helper", "/private", options); - child.stdout.write("not JSON\n"); - expect(commands).toEqual(['{"command":"close"}\n']); - await vi.advanceTimersByTimeAsync(1000); - expect(child.kill).toHaveBeenCalledOnce(); - child.emit("close"); - expect(await starting).toBeUndefined(); - expect(vi.getTimerCount()).toBe(0); -}); - -it("bounds a missing ready receipt and cancels an in-flight animation on compositor failure", async () => { - const timed = startNativeCaptureFeedback("/helper", "/private", options); - await vi.advanceTimersByTimeAsync(2000); - child.emit("close"); - expect(await timed).toBeUndefined(); -}); - it("releases waiters if the overlay closes during flight", async () => { const starting = startNativeCaptureFeedback("/helper", "/private", options); event({ event: "ready", animate: true }); diff --git a/apps/desktop/src/snapShot/NiriSnapShot.test.ts b/apps/desktop/src/snapShot/NiriSnapShot.test.ts index 313d335d38860..21c89e540506c 100644 --- a/apps/desktop/src/snapShot/NiriSnapShot.test.ts +++ b/apps/desktop/src/snapShot/NiriSnapShot.test.ts @@ -67,7 +67,6 @@ beforeEach(async () => { send(event, { ScreenshotCaptured: { path: "/another-app.png" } }); send(event, { ScreenshotCaptured: { path: screenshot.path } }); } - // The event may beat the command reply. send(socket, { Ok: "Handled" }); } else send(socket, { Ok: "Handled" }); }; @@ -227,16 +226,6 @@ it("fails promptly when Niri disconnects", async () => { await expect(checkNiriCaptureSupport(socketPath)).rejects.toThrow("disconnected"); }); -it("bounds requests even when the compositor never answers", async () => { - vi.useFakeTimers(); - const received = Promise.withResolvers(); - handler = async () => received.resolve(); - const result = expect(checkNiriCaptureSupport(socketPath)).rejects.toThrow("timed out"); - await received.promise; - await vi.advanceTimersByTimeAsync(5_000); - await result; -}); - it("does not use stale, relative, or sandboxed Niri sockets", () => { expect(niriSocketPath()).toBe(socketPath); expect(niriSocketPath({ XDG_CURRENT_DESKTOP: "GNOME", NIRI_SOCKET: socketPath })).toBeUndefined(); diff --git a/apps/desktop/src/snapShot/PortalCaptureShortcut.dbus.test.ts b/apps/desktop/src/snapShot/PortalCaptureShortcut.dbus.test.ts deleted file mode 100644 index acd9a29b32209..0000000000000 --- a/apps/desktop/src/snapShot/PortalCaptureShortcut.dbus.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- Private D-Bus integration fixture, never the user's session bus. -import * as NodeChildProcess from "node:child_process"; -import * as NodeEvents from "node:events"; -import * as NodeFSP from "node:fs/promises"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import * as NodeReadline from "node:readline"; -import { Message, NameFlag, Variant, sessionBus, type MessageBus } from "dbus-next"; -import { expect, it, vi } from "vite-plus/test"; -import { PortalCaptureShortcut } from "./PortalCaptureShortcut.ts"; - -it.runIf(NodeChildProcess.spawnSync("dbus-daemon", ["--version"]).status === 0)( - "registers, rebinds saved keys, receives activations, and replaces sessions over real D-Bus", - async () => { - const dir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-shortcut-dbus-")); - let daemon: NodeChildProcess.ChildProcess | undefined; - let server: MessageBus | undefined; - const clients: PortalCaptureShortcut[] = []; - try { - vi.stubEnv("FLATPAK_ID", ""); - vi.stubEnv("SNAP", ""); - daemon = NodeChildProcess.spawn( - "dbus-daemon", - [ - "--session", - "--nofork", - "--nopidfile", - "--print-address", - `--address=unix:path=${NodePath.join(dir, "bus")}`, - ], - { stdio: ["ignore", "pipe", "pipe"] }, - ); - const lines = NodeReadline.createInterface({ input: daemon.stdout! }); - const [address] = await Promise.race([ - NodeEvents.EventEmitter.once(lines, "line"), - NodeEvents.EventEmitter.once(daemon, "exit").then(() => { - throw new Error("Private bus failed to start"); - }), - ]); - lines.close(); - const connect = () => sessionBus({ busAddress: String(address) }); - server = connect(); - server.on("error", () => undefined); - await server.requestName("org.freedesktop.portal.Desktop", NameFlag.DO_NOT_QUEUE); - const root = "/org/freedesktop/portal/desktop"; - const iface = "org.freedesktop.portal.GlobalShortcuts"; - const sessions = new Map(); - const bindings = new Map(); - const identities = new Set(); - const closed = new Set(); - const closeWaiters = new Map void>(); - let bindCount = 0; - server.addMethodHandler((message: Message) => { - if (message.member === "Register") { - expect(message.body[0]).toBe("com.t3tools.T3Code"); - identities.add(message.sender); - server!.send(Message.newMethodReturn(message)); - } else if (message.member === "Get") { - server!.send(Message.newMethodReturn(message, "v", [new Variant("u", 2)])); - } else if (message.member === "Close") { - closed.add(message.path); - closeWaiters.get(message.path)?.(); - } else if (["CreateSession", "BindShortcuts"].includes(message.member)) { - expect(identities.has(message.sender)).toBe(true); - const options = message.body.at(-1) as Record>; - const sender = message.sender.slice(1).replaceAll(".", "_"); - const handle = `${root}/request/${sender}/${options.handle_token!.value}`; - let results: Record>; - if (message.member === "CreateSession") { - const session = `${root}/session/${sender}/${options.session_handle_token!.value}`; - sessions.set(message.sender, session); - results = { session_handle: new Variant("s", session) }; - } else { - bindCount++; - const shortcuts = message.body[1] as Array< - [string, { preferred_trigger: Variant }] - >; - expect(shortcuts).toHaveLength(1); - const [id, properties] = shortcuts[0]!; - expect(properties.preferred_trigger.signature).toBe("s"); - bindings.set(message.sender, id); - const bound = [ - [ - id, - { - description: new Variant("s", "Capture a window"), - trigger_description: new Variant("s", properties.preferred_trigger.value), - }, - ], - ]; - results = { shortcuts: new Variant("a(sa{sv})", bound) }; - } - const response = Message.newSignal( - handle, - "org.freedesktop.portal.Request", - "Response", - "ua{sv}", - [0, results], - ); - response.destination = message.sender; - server!.send(response); - server!.send(Message.newMethodReturn(message, "o", [handle])); - } else return false; - return true; - }); - - const shortcut = { - key: "2", - modKey: true, - ctrlKey: false, - shiftKey: true, - altKey: false, - metaKey: false, - }; - const start = (key = "2") => { - const received = Promise.withResolvers(); - const capture = vi.fn(() => received.resolve()); - const client = new PortalCaptureShortcut( - "com.t3tools.T3Code", - { ...shortcut, key }, - capture, - () => {}, - connect(), - ); - clients.push(client); - return { client, capture, received: received.promise }; - }; - const activate = (sender: string) => { - const signal = Message.newSignal(root, iface, "Activated", "osta{sv}", [ - sessions.get(sender), - bindings.get(sender), - 123, - {}, - ]); - signal.destination = sender; - server!.send(signal); - }; - const first = start(); - await first.client.ready; - expect(first.client.state.shortcutRegistered).toBe(true); - const firstSender = [...bindings.keys()][0]!; - activate(firstSender); - await first.received; - expect(first.capture).toHaveBeenCalledOnce(); - const sessionClosed = new Promise((resolve) => - closeWaiters.set(sessions.get(firstSender)!, resolve), - ); - first.client.close(); - await sessionClosed; - expect(closed.has(sessions.get(firstSender)!)).toBe(true); - - const restoredClient = start(); - await restoredClient.client.ready; - expect(restoredClient.client.state.shortcutRegistered).toBe(true); - expect(bindCount).toBe(2); - expect([...bindings.values()][1]).toBe(bindings.get(firstSender)); - const next = start("8"); - await next.client.ready; - expect(next.client.state.shortcutLabel).toBe("CTRL+SHIFT+8"); - expect(bindCount).toBe(3); - const lastSender = [...bindings.keys()].at(-1)!; - expect(bindings.get(lastSender)).not.toBe(bindings.get(firstSender)); - activate(lastSender); - await next.received; - expect(next.capture).toHaveBeenCalledOnce(); - } finally { - clients.forEach((client) => client.close()); - server?.disconnect(); - if (daemon && daemon.exitCode === null) { - const exited = NodeEvents.EventEmitter.once(daemon, "exit"); - daemon.kill(); - await exited; - } - vi.unstubAllEnvs(); - await NodeFSP.rm(dir, { recursive: true, force: true }); - } - }, -); diff --git a/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts b/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts index eb20a4a041eef..35c007e35dc0e 100644 --- a/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts +++ b/apps/desktop/src/snapShot/PortalCaptureShortcut.test.ts @@ -158,24 +158,6 @@ it("accepts Hyprland's action-only binding without claiming the keys are reserve expect(client.state.shortcutActionRegistered).toBe(false); }); -it("keeps the Hyprland action ID stable regardless of a saved key chord", async () => { - const first = start(new FakeBus(), chord, true); - const second = start(new FakeBus(), { ...chord, key: "7" }, true); - await Promise.all([first.client.ready, second.client.ready]); - expect(first.bus.boundId).toBe(second.bus.boundId); -}); - -it("does not accept an empty trigger as approval on other desktops", async () => { - const bus = new FakeBus(); - bus.actualLabel = ""; - const { client, capture } = start(bus); - await client.ready; - expect(client.state.shortcutRegistered).toBe(false); - expect(client.state.shortcutActionRegistered).not.toBe(true); - bus.activate(); - expect(capture).not.toHaveBeenCalled(); -}); - it.each([ ["2", "CTRL+SHIFT+2"], ["f12", "CTRL+SHIFT+F12"], @@ -309,23 +291,6 @@ it("treats a remembered empty binding as unassigned, then observes desktop-side expect(capture).toHaveBeenCalledOnce(); }); -it("guides users to manual desktop settings when the portal cannot open them", async () => { - const bus = new FakeBus(); - bus.version = 1; - bus.bindStatus = 1; - const { client } = start(bus); - await client.ready; - expect(client.hasSession).toBe(true); - expect(client.state.shortcutCanRetry).toBe(false); - expect(client.state.shortcutMessage).toBe( - "Shortcut permission wasn't granted. Allow T3 Code in your desktop's shortcut settings.", - ); - await expect(client.configure()).rejects.toThrow("Open your desktop's shortcut settings"); - expect(bus.calls.some((message) => message.member === "ConfigureShortcuts")).toBe(false); - client.close(); - expect(client.hasSession).toBe(false); -}); - it("captures on older portals without offering an unsupported permission dialog", async () => { const bus = new FakeBus(); bus.version = 1; @@ -361,21 +326,6 @@ it("closes an outstanding consent request and ignores its late response", async expect(bus.disconnect).toHaveBeenCalledOnce(); }); -it("bounds unanswered consent and cleans up the pending request", async () => { - vi.useFakeTimers(); - const bus = new FakeBus(); - bus.autoBind = false; - const binding = NodeEvents.EventEmitter.once(bus, "bind"); - const { client } = start(bus); - await binding; - await vi.advanceTimersByTimeAsync(120_000); - await client.ready; - expect(client.state.shortcutPending).toBe(false); - expect(client.state.shortcutMessage).toContain("timed out"); - expect(bus.disconnect).toHaveBeenCalledOnce(); - expect(vi.getTimerCount()).toBe(0); -}); - it("handles a disappearing portal without keeping a false registered state", async () => { const { bus, client } = start(); await client.ready; diff --git a/apps/desktop/src/snapShot/RegionSnapShot.test.ts b/apps/desktop/src/snapShot/RegionSnapShot.test.ts index 0d6381bb3f28e..24b233b465d53 100644 --- a/apps/desktop/src/snapShot/RegionSnapShot.test.ts +++ b/apps/desktop/src/snapShot/RegionSnapShot.test.ts @@ -1,7 +1,6 @@ import type * as Electron from "electron"; import { assert, beforeEach, expect, it, vi } from "vite-plus/test"; -import type { ActiveWindow } from "./ActiveWindow.ts"; import type { RegionSnapShotChild, RegionSnapShotProcess } from "./RegionSnapShot.ts"; const { createFromBufferMock, resizeMock } = vi.hoisted(() => ({ @@ -13,59 +12,13 @@ vi.mock("electron", () => ({ nativeImage: { createFromBuffer: createFromBufferMock }, })); -import { - captureRegionWindowSnapshot, - makeRegionSnapShotPool, - startRegionSnapShotProcess, -} from "./RegionSnapShot.ts"; +import { makeRegionSnapShotPool, startRegionSnapShotProcess } from "./RegionSnapShot.ts"; beforeEach(() => { vi.clearAllMocks(); createFromBufferMock.mockReturnValue({ resize: resizeMock }); }); -const active = { - title: "Editor", - owner: { name: "Editor", processId: 123 }, - bounds: { x: 10, y: 20, width: 800, height: 600 }, -} as ActiveWindow; - -it("returns a small capture's PNG untouched", async () => { - const png = Buffer.from([1, 2, 3]); - const capture = vi.fn(async () => ({ width: 400, height: 300, png })); - const region = { x: 5, y: 10, width: 400, height: 300 }; - - const result = await captureRegionWindowSnapshot({ capture }, active, region, region); - - assert.deepEqual(capture.mock.calls, [[region]]); - assert.strictEqual(result.png, png); - assert.deepEqual(result.source, { name: "Editor" }); - assert.lengthOf(createFromBufferMock.mock.calls, 0); -}); - -it.each([ - { width: 600, height: 400, expected: { width: 240, height: 160 } }, - { width: 400, height: 600, expected: { width: 107, height: 160 } }, - { width: 600, height: 1, expected: { width: 256, height: 1 } }, -])( - "bounds $width x $height physical pixels before encoding", - async ({ width, height, expected }) => { - const png = Buffer.from([1, 2, 3]); - const resizedPng = Buffer.from([4, 5, 6]); - const capture = vi.fn(async () => ({ width, height, png })); - resizeMock.mockReturnValue({ toPNG: () => resizedPng }); - - const result = await captureRegionWindowSnapshot({ capture }, active, active.bounds, { - width: 256, - height: 160, - }); - - assert.deepEqual(createFromBufferMock.mock.calls, [[png]]); - assert.deepEqual(resizeMock.mock.calls, [[{ ...expected, quality: "best" }]]); - assert.strictEqual(result.png, resizedPng); - }, -); - function fakeChild() { const messageListeners: Array<(message: unknown) => void> = []; const exitListeners: Array<() => void> = []; @@ -92,37 +45,6 @@ function fakeChild() { const region = { x: 0, y: 0, width: 2, height: 1 }; -it("resolves the decoded capture once the child is ready and replies", async () => { - const fake = fakeChild(); - const fork = vi.fn(() => fake.child); - const png = Buffer.from([9, 8, 7]); - const child = startRegionSnapShotProcess("worker.cjs", fork); - assert.deepEqual(fork.mock.calls, [["worker.cjs"]]); - assert.isTrue(child.alive); - - const capture = child.capture(region); - await Promise.resolve(); - assert.lengthOf(fake.send.mock.calls, 0); - fake.emit("ready"); - await vi.waitFor(() => assert.deepEqual(fake.send.mock.calls, [[{ region }]])); - fake.emit({ type: "result", width: 2, height: 1, png: png.toString("base64") }); - - assert.deepEqual(await capture, { width: 2, height: 1, png }); - assert.isFalse(child.alive); - assert.lengthOf(fake.kill.mock.calls, 1); -}); - -it("rejects with the child's error message", async () => { - const fake = fakeChild(); - const child = startRegionSnapShotProcess("worker.cjs", () => fake.child); - const capture = child.capture(region); - fake.emit("ready"); - fake.emit({ type: "error", message: "Screen capture failed" }); - - await expect(capture).rejects.toThrow("Screen capture failed"); - assert.isFalse(child.alive); -}); - it("rejects when the child exits before replying", async () => { const fake = fakeChild(); const child = startRegionSnapShotProcess("worker.cjs", () => fake.child); @@ -133,19 +55,6 @@ it("rejects when the child exits before replying", async () => { await expect(capture).rejects.toThrow(/helper exited/); }); -it("serves a single capture per child", async () => { - const fake = fakeChild(); - const child = startRegionSnapShotProcess("worker.cjs", () => fake.child); - const first = child.capture(region); - fake.emit("ready"); - await vi.waitFor(() => assert.lengthOf(fake.send.mock.calls, 1)); - fake.emit({ type: "result", width: 1, height: 1, png: Buffer.from([1]).toString("base64") }); - await first; - - await expect(child.capture(region)).rejects.toThrow(/already used/); - assert.lengthOf(fake.send.mock.calls, 1); -}); - it("cancels a pending capture on close and kills the child", async () => { const fake = fakeChild(); const child = startRegionSnapShotProcess("worker.cjs", () => fake.child); @@ -159,31 +68,6 @@ it("cancels a pending capture on close and kills the child", async () => { assert.lengthOf(fake.send.mock.calls, 0); }); -it("reports an unavailable helper when the child cannot be forked", async () => { - const child = startRegionSnapShotProcess("worker.cjs", () => { - throw new Error("fork failed"); - }); - - assert.isFalse(child.alive); - await expect(child.capture(region)).rejects.toThrow(/unavailable/); -}); - -it("times out a stalled capture", async () => { - vi.useFakeTimers(); - try { - const fake = fakeChild(); - const child = startRegionSnapShotProcess("worker.cjs", () => fake.child); - const failure = expect(child.capture(region)).rejects.toThrow(/timed out/); - fake.emit("ready"); - await vi.advanceTimersByTimeAsync(15_000); - - await failure; - assert.lengthOf(fake.kill.mock.calls, 1); - } finally { - vi.useRealTimers(); - } -}); - function fakeProcess() { const result = Promise.withResolvers<{ width: number; height: number; png: Buffer }>(); void result.promise.catch(() => undefined); @@ -221,41 +105,6 @@ function fakePool() { return { pool: makeRegionSnapShotPool("worker.cjs", start), processes, start }; } -it("warms one standby child and keeps it while alive", () => { - const { pool, start } = fakePool(); - - pool.warm(); - pool.warm(); - - assert.deepEqual(start.mock.calls, [["worker.cjs"]]); -}); - -it("captures with the standby child and warms a replacement afterwards", async () => { - const { pool, processes, start } = fakePool(); - pool.warm(); - const shot = { width: 1, height: 1, png: Buffer.from([1]) }; - - const capture = pool.capture(region); - assert.deepEqual(processes[0]!.capture.mock.calls, [[region]]); - assert.lengthOf(start.mock.calls, 1); - processes[0]!.resolve(shot); - - assert.deepEqual(await capture, shot); - assert.lengthOf(start.mock.calls, 2); - assert.lengthOf(processes[1]!.capture.mock.calls, 0); -}); - -it("starts a child on demand when no standby is warm", async () => { - const { pool, processes, start } = fakePool(); - const shot = { width: 1, height: 1, png: Buffer.from([1]) }; - - const capture = pool.capture(region); - assert.lengthOf(start.mock.calls, 1); - processes[0]!.resolve(shot); - - assert.deepEqual(await capture, shot); -}); - it("rejects a second capture while one is in flight", async () => { const { pool, processes } = fakePool(); const first = pool.capture(region); @@ -267,17 +116,6 @@ it("rejects a second capture while one is in flight", async () => { await first; }); -it("cools the standby child", () => { - const { pool, processes, start } = fakePool(); - pool.warm(); - - pool.cool(); - - assert.lengthOf(processes[0]!.close.mock.calls, 1); - pool.warm(); - assert.lengthOf(start.mock.calls, 2); -}); - it("closes the standby and the in-flight child", async () => { const { pool, processes } = fakePool(); pool.warm(); diff --git a/apps/desktop/src/snapShot/RegionSnapShotWorker.ts b/apps/desktop/src/snapShot/RegionSnapShotWorker.ts index 374745c96e60c..f0ac7b9c1bba2 100644 --- a/apps/desktop/src/snapShot/RegionSnapShotWorker.ts +++ b/apps/desktop/src/snapShot/RegionSnapShotWorker.ts @@ -1,5 +1,4 @@ -// Runs in a forked Node-mode child so the native screenshot call cannot crash -// or stall the main process. +// Isolate native screenshot crashes and stalls in a Node-mode child. import type { RegionSnapShotRequest, RegionSnapShotResult } from "./RegionSnapShot.ts"; process.once("disconnect", () => process.exit(0)); diff --git a/apps/desktop/src/snapShot/SnapShotAccessibility.ts b/apps/desktop/src/snapShot/SnapShotAccessibility.ts index b0a0fe7b959cb..9021c8904e3fe 100644 --- a/apps/desktop/src/snapShot/SnapShotAccessibility.ts +++ b/apps/desktop/src/snapShot/SnapShotAccessibility.ts @@ -20,7 +20,7 @@ export type AccessibleWindowIdentity = { readonly title: string; readonly bounds: Electron.Rectangle; readonly clientBounds?: Electron.Rectangle; - readonly owner: { readonly processId: number }; + readonly owner: { readonly processId: number; readonly bundleId?: string }; readonly accessibilityBoundsReliable?: boolean; }; @@ -134,6 +134,8 @@ async function readCapturedWindowAccessibility( sourceTitle, bounds: active.bounds, clientBounds: active.clientBounds, + platform, + bundleId: pidWindows.length > 0 ? active.owner.bundleId : undefined, }; const window = findAccessibleWindow( pidWindows.length > 0 || foreground !== undefined ? pidWindows : await windowsFromAppList(App), @@ -170,8 +172,7 @@ async function readCapturedWindowAccessibility( .catch(() => { progress.flatComplete = true; }); - // A decorated screenshot contains more than the accessibility client area. Keep its - // frame origin/scale so element coordinates include the actual decoration offset. + // Preserve the screenshot frame origin and scale so accessibility coordinates include decorations. const sourceBounds = matchMode === "wayland" && active.clientBounds ? active.bounds diff --git a/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.test.ts b/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.test.ts index 6edfa017584a2..e4e80c6c4db64 100644 --- a/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.test.ts +++ b/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.test.ts @@ -1,6 +1,5 @@ import { assert, beforeEach, it } from "@effect/vitest"; import * as NodeEvents from "node:events"; -import * as NodeProcess from "node:process"; import { vi } from "vite-plus/test"; const forkMock = vi.hoisted(() => @@ -62,42 +61,6 @@ it("returns immediately when accessibility crashes before the screenshot is read assert.isUndefined(await read.result); }); -it("returns accessibility extracted by the helper", async () => { - const process = startSnapShotAccessibilityProcess("accessibility.cjs"); - const read = process.read(request); - const context = { accessibleText: "Meeting controls" }; - worker.emit("message", "ready"); - worker.emit("message", "started"); - worker.emit("message", { type: "result", context }); - - await read.started; - assert.deepEqual(await read.result, context); - assert.strictEqual(forkMock.mock.calls[0]?.[2]?.env?.ELECTRON_RUN_AS_NODE, "1"); - assert.strictEqual(forkMock.mock.calls[0]?.[2]?.execPath, NodeProcess.execPath); -}); - -it("hands a warm helper to the capture and prewarms its replacement", async () => { - const warmWorker = makeWorker(); - const replacementWorker = makeWorker(); - forkMock.mockReset().mockReturnValueOnce(warmWorker).mockReturnValueOnce(replacementWorker); - const pool = makeSnapShotAccessibilityProcessPool("accessibility.cjs"); - - pool.warm(); - warmWorker.emit("message", "ready"); - const read = pool.read(request); - - assert.lengthOf(forkMock.mock.calls, 2); - assert.deepEqual(warmWorker.send.mock.calls[0]?.[0], request); - assert.lengthOf(replacementWorker.send.mock.calls, 0); - - warmWorker.emit("message", "started"); - warmWorker.emit("message", { type: "result", context: { accessibleText: "Ready" } }); - assert.deepEqual(await read.result, { accessibleText: "Ready" }); - - pool.close(); - assert.lengthOf(replacementWorker.kill.mock.calls, 1); -}); - it("replaces a warm helper that exits before capture", async () => { const exitedWorker = makeWorker(); const captureWorker = makeWorker(); @@ -121,21 +84,3 @@ it("replaces a warm helper that exits before capture", async () => { assert.deepEqual(captureWorker.send.mock.calls[0]?.[0], request); pool.close(); }); - -it("allows cold startup to exceed the request-start budget", async () => { - vi.useFakeTimers(); - const process = startSnapShotAccessibilityProcess("accessibility.cjs"); - try { - const read = process.read(request); - await vi.advanceTimersByTimeAsync(1_500); - assert.lengthOf(worker.kill.mock.calls, 0); - worker.emit("message", "ready"); - assert.deepEqual(worker.send.mock.calls[0]?.[0], request); - worker.emit("message", "started"); - worker.emit("message", { type: "result", context: { accessibleText: "Ready" } }); - assert.deepEqual(await read.result, { accessibleText: "Ready" }); - } finally { - process.close(); - vi.useRealTimers(); - } -}); diff --git a/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.ts b/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.ts index dd1474b885052..542e3f13c08dc 100644 --- a/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.ts +++ b/apps/desktop/src/snapShot/SnapShotAccessibilityProcess.ts @@ -49,8 +49,7 @@ export function startSnapShotAccessibilityProcess(workerPath: string): Accessibi let worker: NodeChildProcess.ChildProcess; try { worker = NodeChildProcess.fork(workerPath, ["read"], { - // Electron defaults to its Helper executable on macOS, which does not - // share the main app's Accessibility grant checked during setup. + // Electron's default macOS Helper executable lacks the main app's Accessibility grant. execPath: process.execPath, env: { ...process.env, diff --git a/apps/desktop/src/snapShot/SnapShotTransition.ts b/apps/desktop/src/snapShot/SnapShotTransition.ts index d1cd732ec4aca..4b6ce04a1bf27 100644 --- a/apps/desktop/src/snapShot/SnapShotTransition.ts +++ b/apps/desktop/src/snapShot/SnapShotTransition.ts @@ -26,7 +26,7 @@ export type SnapShotAnimationDestination = { readonly details?: SnapShotAnimationDetails | undefined; }; -export function snapShotAnimationDurationMs( +function snapShotAnimationDurationMs( source: Electron.Rectangle, target: Electron.Rectangle, ): number { @@ -52,6 +52,7 @@ type ActiveTransition = { details?: SnapShotAnimationDetails | undefined; timer?: Fiber.Fiber | undefined; flight?: Promise | undefined; + landed?: boolean | undefined; }; type SnapShotTransitionOptions = { @@ -63,7 +64,7 @@ type SnapShotTransitionOptions = { | undefined; }; -export function snapShotAnimationOverlayBounds( +function snapShotAnimationOverlayBounds( displays: ReadonlyArray>, ): Electron.Rectangle { const firstDisplay = displays[0]; @@ -206,6 +207,10 @@ export class SnapShotTransition { private readonly alwaysOnTopLevel: SnapShotTransitionOptions["alwaysOnTopLevel"]; private readonly showWindow: (window: Electron.BaseWindow) => void; + get isAnimating(): boolean { + return this.active?.flight !== undefined && !this.active.landed; + } + constructor(options: SnapShotTransitionOptions = {}) { this.boundOverlayToCaptureDisplays = options.boundOverlayToCaptureDisplays ?? false; this.waitForCompositorFrame = options.waitForCompositorFrame ?? false; @@ -305,8 +310,7 @@ export class SnapShotTransition { } } if (this.waitForCompositorFrame) { - // Cover the source with a composited snapshot before the caller reveals T3. - // Decoding and renderer animation frames alone can leave a transparent gap. + // Renderer frames alone can leave a transparent gap; composite the snapshot before revealing T3. await Promise.all( overlays.map(async (overlay) => { if (this.active !== active || overlay.window.isDestroyed()) return; @@ -350,7 +354,9 @@ export class SnapShotTransition { } return; } - active.flight = this.runFlight(active, destination); + active.flight = this.runFlight(active, destination).finally(() => { + active.landed = true; + }); } private async runFlight( @@ -401,8 +407,7 @@ export class SnapShotTransition { ); if (this.active !== active || overlay.window.isDestroyed()) return; if (this.waitForCompositorFrame) { - // Read back one pixel after preparation to flush queued compositor work - // before the animation clock starts on any of the display surfaces. + // Read back one pixel to flush compositor work before starting any display's animation clock. await overlay.window.webContents.capturePage({ x: 0, y: 0, width: 1, height: 1 }); } return overlay; diff --git a/apps/desktop/src/snapShot/WindowsCaptureFeedback.test.ts b/apps/desktop/src/snapShot/WindowsCaptureFeedback.test.ts index 4a319d7ac36a7..aa56de0908970 100644 --- a/apps/desktop/src/snapShot/WindowsCaptureFeedback.test.ts +++ b/apps/desktop/src/snapShot/WindowsCaptureFeedback.test.ts @@ -33,29 +33,3 @@ it("disables Chromium window animation only while showing the capture overlay", expect(flagsDuringShow).toEqual([["unrelated-switch", animationSwitch]]); expect([...switches]).toEqual(["unrelated-switch"]); }); - -it("preserves an animation switch supplied before capture", () => { - switches.add(animationSwitch); - const flagsDuringShow: string[][] = []; - - showWindowsCaptureOverlay(overlay(() => flagsDuringShow.push([...switches]))); - - expect(flagsDuringShow).toEqual([["unrelated-switch", animationSwitch]]); - expect([...switches]).toEqual(["unrelated-switch", animationSwitch]); -}); - -it.each([false, true])( - "restores the original switch state when showing throws (preexisting: %s)", - (preexisting) => { - if (preexisting) switches.add(animationSwitch); - const original = [...switches]; - const failure = new Error("Overlay was destroyed"); - const window = overlay(() => { - expect(switches.has(animationSwitch)).toBe(true); - throw failure; - }); - - expect(() => showWindowsCaptureOverlay(window)).toThrow(failure); - expect([...switches]).toEqual(original); - }, -); diff --git a/apps/desktop/src/snapShot/WindowsCaptureFeedback.ts b/apps/desktop/src/snapShot/WindowsCaptureFeedback.ts index eb02eb7a03d13..ca4165626b260 100644 --- a/apps/desktop/src/snapShot/WindowsCaptureFeedback.ts +++ b/apps/desktop/src/snapShot/WindowsCaptureFeedback.ts @@ -4,8 +4,7 @@ const WINDOW_ANIMATIONS_DISABLED = "wm-window-animations-disabled"; /** Show capture feedback without Aura's extra 200 ms fade/scale on transparent windows. */ export function showWindowsCaptureOverlay(window: Electron.BaseWindow): void { - // Chromium reads this switch synchronously inside Show(). Restore it before returning - // so other windows and CSS animations keep their normal behavior. + // Show() reads the switch synchronously; restore it before other windows or animations can be affected. const alreadyDisabled = Electron.app.commandLine.hasSwitch(WINDOW_ANIMATIONS_DISABLED); if (!alreadyDisabled) Electron.app.commandLine.appendSwitch(WINDOW_ANIMATIONS_DISABLED); try { diff --git a/apps/desktop/src/snapShot/captureConfigEdit.test.ts b/apps/desktop/src/snapShot/captureConfigEdit.test.ts index 6d57d35ee8b66..9db407be961d2 100644 --- a/apps/desktop/src/snapShot/captureConfigEdit.test.ts +++ b/apps/desktop/src/snapShot/captureConfigEdit.test.ts @@ -39,14 +39,6 @@ describe("Niri capture config edits", () => { `\uFEFFbinds {\r\n ${binding}\r\n}\r\n`, ); }); - it("preserves Unicode spacing around nodes and line continuations", () => { - const spaces = - "\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000"; - const before = `binds${spaces}\\${spaces}\n{\n}\n`; - expect(editCaptureConfig(before, "niri", app, "install").after).toBe( - before.replace("}\n", ` ${binding}\n}\n`), - ); - }); it("does not duplicate an existing binding, including a custom chord", () => { const before = `binds {\n ${binding.replace("Ctrl+Shift+2", "Alt+Ctrl+Y")}\n}\n`; const result = editCaptureConfig(before, "niri", app, "install"); @@ -68,11 +60,6 @@ describe("Niri capture config edits", () => { expect(niriConfigConflict(before, app, "Ctrl+Shift+2")).toBe(true); expect(() => editCaptureConfig(before, "niri", app, "install")).toThrow("already used"); }); - it("does not count a slash-dash-disabled key as occupied", () => { - expect(niriConfigConflict("binds { /- Ctrl+Shift+2 { quit; }; }", app, "Ctrl+Shift+2")).toBe( - false, - ); - }); it.each(["binds {", "binds {}\nbinds {}", "/* unfinished", 'spawn "unfinished'])( "fails safely for malformed structure: %s", (source) => { @@ -115,10 +102,6 @@ describe("Hyprland capture config edits", () => { editCaptureConfig("bind = SHIFT CTRL, 2, exec, kitty\n", "hyprland", app, "install"), ).toThrow("already used"); }); - it("leaves commented bindings alone", () => { - const before = "# bind = CTRL SHIFT, 2, global, com.t3tools.T3Code:capture-window\n"; - expect(editCaptureConfig(before, "hyprland", app, "remove").after).toBe(before); - }); it.each([ "return {}", '--[[\nhl.bind("CTRL + SHIFT + 2", hl.dsp.global("com.t3tools.T3Code:capture-window"))\n]]', diff --git a/apps/desktop/src/snapShot/linuxCaptureSession.ts b/apps/desktop/src/snapShot/linuxCaptureSession.ts index c35fee18db45e..59fe40b7c5212 100644 --- a/apps/desktop/src/snapShot/linuxCaptureSession.ts +++ b/apps/desktop/src/snapShot/linuxCaptureSession.ts @@ -4,8 +4,7 @@ import * as NodeURL from "node:url"; import type { SnapShotKeyChord } from "@t3tools/contracts"; import { nativeImage } from "electron"; -// Linux helpers that need no D-Bus. Keep this module free of dbus-next so the main -// process can answer "which desktop is this" and read a PNG without loading it. +// Keep dbus-next out of desktop detection and PNG reads in the main process. export const HYPRLAND_CAPTURE_ACTION = "capture-window"; export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot"; diff --git a/apps/desktop/src/snapShot/snapShot.test.ts b/apps/desktop/src/snapShot/snapShot.test.ts index ea52e877b93f5..26ae8fbf9ebe9 100644 --- a/apps/desktop/src/snapShot/snapShot.test.ts +++ b/apps/desktop/src/snapShot/snapShot.test.ts @@ -1,58 +1,19 @@ import { it as effectIt } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; -import { describe, expect, it, vi } from "vite-plus/test"; +import { describe, expect, it } from "vite-plus/test"; import { accessibleWindowElementTree, accessibleWindowText, - capturedImageBounds, compactAccessibilityTree, findAccessibleWindow, findCaptureSource, hideAndWaitForBlur, isWaylandSession, - snapShotShortcutRegistrationFailureMessage, - snapShotShortcutSystemConflict, - toElectronAccelerator, } from "./snapShot.ts"; -import { DesktopSnapShotError } from "./DesktopSnapShot.ts"; - -describe("window capture errors", () => { - it.each([ - ["unsupported", "SnapShots are not supported here."], - ["disabled", "Enable SnapShots in Settings first."], - ["no-window-selected", "No window was selected."], - ["window-unavailable", "The active window is not available for capture."], - ["capture", "Could not capture the active window."], - ] as const)("keeps %s failures user-facing", (operation, message) => { - expect(new DesktopSnapShotError({ operation }).message).toBe(message); - }); -}); describe("accessibleWindowText", () => { - it("keeps unique names and values in tree order", () => { - expect( - accessibleWindowText( - { - name: "Settings", - children: [ - { - name: "General", - children: [], - }, - { - name: "Name", - value: "Bilal", - children: [], - }, - ], - }, - 100, - ), - ).toBe("Settings\nGeneral\nName\nBilal"); - }); - it("caps large text without splitting a surrogate pair", () => { expect( accessibleWindowText( @@ -263,23 +224,6 @@ describe("accessibleWindowElementTree", () => { expect(tree?.root.children.length).toBeLessThan(10); expect(JSON.stringify(tree).length).toBeLessThanOrEqual(32_000); }); - - it.each(["name", "value", "description"] as const)( - "reports clipped %s text in partial trees", - async (field) => { - const tree = await accessibleWindowElementTree( - { - role: "window", - children: async () => [{ role: "text_area", [field]: "x".repeat(8_001) }], - }, - { x: 0, y: 0, width: 800, height: 600 }, - { width: 800, height: 600 }, - ); - - expect(tree?.truncated).toBe(true); - expect(tree?.root.children[0]?.[field]?.length).toBeLessThan(8_001); - }, - ); }); describe("compactAccessibilityTree", () => { @@ -304,33 +248,63 @@ describe("compactAccessibilityTree", () => { }); }); -describe("capturedImageBounds", () => { - it("clips locations to the attached image", () => { - expect( - capturedImageBounds( - { x: 50, y: 150, width: 200, height: 200 }, - { x: 100, y: 200, width: 800, height: 600 }, - { width: 1_600, height: 1_200 }, - ), - ).toEqual({ x: 0, y: 0, width: 300, height: 300 }); +describe("findAccessibleWindow", () => { + const captured = { + title: "Editor", + bounds: { x: 100, y: 200, width: 800, height: 600 }, + }; + + const chromeCapture = { + title: "Issues · pingdotgg/t3code", + bounds: captured.bounds, + platform: "darwin" as const, + bundleId: "com.google.Chrome", + }; + const chromeWindow = { + name: `${chromeCapture.title} - Google Chrome – Profile`, + bounds: chromeCapture.bounds, + active: true, + }; + + it("uses a browser suffix only when no exact title matches", () => { + const exact = { name: chromeCapture.title, bounds: chromeCapture.bounds }; + expect(findAccessibleWindow([chromeWindow, exact], chromeCapture)).toBe(exact); + expect(findAccessibleWindow([chromeWindow], chromeCapture)).toBe(chromeWindow); }); - it("returns null when an accessibility provider omits a location", () => { + it("rejects browser suffix matches with wrong bounds, page titles, or ambiguous windows", () => { expect( - capturedImageBounds( - null, - { x: 0, y: 0, width: 800, height: 600 }, - { width: 800, height: 600 }, + findAccessibleWindow( + [{ ...chromeWindow, bounds: { ...chromeWindow.bounds, x: 0 } }], + chromeCapture, ), - ).toBeNull(); + ).toBeUndefined(); + expect( + findAccessibleWindow([chromeWindow, { ...chromeWindow, active: false }], chromeCapture), + ).toBeUndefined(); + expect( + findAccessibleWindow([chromeWindow], { ...chromeCapture, title: "Issues" }), + ).toBeUndefined(); + expect( + findAccessibleWindow([chromeWindow], { + ...chromeCapture, + title: `${chromeCapture.title} - Google Chrome`, + }), + ).toBeUndefined(); }); -}); -describe("findAccessibleWindow", () => { - const captured = { - title: "Editor", - bounds: { x: 100, y: 200, width: 800, height: 600 }, - }; + it("keeps strict titles outside macOS Chrome and Chromium", () => { + for (const identity of [ + { platform: "linux" as const, bundleId: "com.google.Chrome" }, + { platform: "win32" as const, bundleId: "com.google.Chrome" }, + { platform: "darwin" as const, bundleId: "com.example.Editor" }, + { platform: "darwin" as const, bundleId: undefined }, + ]) { + expect( + findAccessibleWindow([chromeWindow], { ...chromeCapture, ...identity }), + ).toBeUndefined(); + } + }); it("matches one window by its captured bounds", () => { const windows = [ @@ -341,17 +315,6 @@ describe("findAccessibleWindow", () => { expect(findAccessibleWindow(windows, captured)).toBe(windows[1]); }); - it("uses the matched source title when macOS omits the active title", () => { - const windows = [{ name: "Editor", bounds: captured.bounds }]; - expect( - findAccessibleWindow(windows, { - ...captured, - title: "", - sourceTitle: "Editor", - }), - ).toBe(windows[0]); - }); - it("uses the captured source title when the active title changed", () => { const windows = [{ name: "Editor — saved", bounds: captured.bounds }]; @@ -382,15 +345,6 @@ describe("findAccessibleWindow", () => { ).toBeUndefined(); }); - it("does not use a title match when the bounds differ", () => { - expect( - findAccessibleWindow( - [{ name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 600 } }], - captured, - ), - ).toBeUndefined(); - }); - it("matches a Wayland window whose accessibility provider omits its screen position", () => { const captured = { title: "hello world (Draft) - Text Editor", @@ -440,24 +394,6 @@ describe("findAccessibleWindow", () => { expect(findAccessibleWindow(windows, captured, "wayland")).toBe(windows[1]); }); - it.each([ - { name: "Private", bounds: { x: 0, y: 0, width: 800, height: 600 } }, - { name: "Editor", bounds: { x: 0, y: 0, width: 400, height: 600 } }, - { name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 300 } }, - { name: "Editor", bounds: null }, - ])("rejects an unverified Wayland window: %j", (window) => { - expect(findAccessibleWindow([window], captured, "wayland")).toBeUndefined(); - }); - - it("rejects ambiguous Wayland windows even when one reports the captured screen position", () => { - const windows = [ - { name: "Editor", bounds: captured.bounds }, - { name: "Editor", bounds: { x: 0, y: 0, width: 800, height: 600 } }, - ]; - - expect(findAccessibleWindow(windows, captured, "wayland")).toBeUndefined(); - }); - it("does not match an untitled Wayland window by size alone", () => { const windows = [{ name: "", bounds: captured.bounds }]; @@ -473,17 +409,6 @@ describe("findAccessibleWindow", () => { expect(findAccessibleWindow(windows, captured, "wayland")).toBeUndefined(); }); - it("rejects ambiguous PID-scoped untitled windows even when bounds match", () => { - const windows = [ - { name: null, bounds: captured.bounds }, - { name: "", bounds: { ...captured.bounds, x: 0, y: 0 } }, - ]; - - expect( - findAccessibleWindow(windows, captured, "wayland", { allowUntitledUniqueBounds: true }), - ).toBeUndefined(); - }); - it("does not fall back to a differently titled PID-scoped window with matching bounds", () => { const windows = [{ name: "Preferences", bounds: captured.bounds }]; @@ -503,17 +428,6 @@ describe("findAccessibleWindow", () => { ).toBeUndefined(); }); - it.each(["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])( - "ignores a leading Wayland title spinner frame %s", - (frame) => { - const windows = [{ name: `${frame} t3code`, bounds: captured.bounds }]; - - expect(findAccessibleWindow(windows, { ...captured, title: "⠋ t3code" }, "wayland")).toBe( - windows[0], - ); - }, - ); - it.each([ ["⠋ t3code", "t3code"], ["t3code", "⠙ t3code"], @@ -534,36 +448,6 @@ describe("findAccessibleWindow", () => { findAccessibleWindow([{ name, bounds: captured.bounds }], { ...captured, title }, "wayland"), ).toBeUndefined(); }); - - it("rejects matching spinners when the window sizes differ", () => { - expect( - findAccessibleWindow( - [{ name: "⠙ t3code", bounds: { ...captured.bounds, width: 400 } }], - { ...captured, title: "⠋ t3code" }, - "wayland", - ), - ).toBeUndefined(); - }); - - it("rejects ambiguous normalized titles even if one matches the captured spinner exactly", () => { - const windows = [ - { name: "⠋ t3code", bounds: captured.bounds }, - { name: "⠙ t3code", bounds: captured.bounds }, - ]; - - expect( - findAccessibleWindow(windows, { ...captured, title: "⠋ t3code" }, "wayland"), - ).toBeUndefined(); - }); - - it("keeps exact title matching outside Wayland", () => { - expect( - findAccessibleWindow([{ name: "⠙ t3code", bounds: captured.bounds }], { - ...captured, - title: "⠋ t3code", - }), - ).toBeUndefined(); - }); }); describe("hideAndWaitForBlur", () => { @@ -586,67 +470,6 @@ describe("hideAndWaitForBlur", () => { await hidden; expect(settled).toBe(true); }); - - it("rejects when the hidden window never blurs", async () => { - vi.useFakeTimers(); - try { - let rejected = false; - const hidden = hideAndWaitForBlur({ - hide: () => undefined, - once: () => undefined, - removeListener: () => undefined, - }).catch(() => { - rejected = true; - }); - - await vi.advanceTimersByTimeAsync(1_000); - expect(rejected).toBe(true); - await hidden; - } finally { - vi.useRealTimers(); - } - }); -}); - -describe("toElectronAccelerator", () => { - it("converts the default portable shortcut", () => { - expect( - toElectronAccelerator({ - key: "2", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }), - ).toBe("CommandOrControl+Shift+2"); - }); - - it("maps the portable meta key to Super", () => { - expect( - toElectronAccelerator({ - key: "k", - metaKey: true, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: false, - }), - ).toBe("Super+K"); - }); - - it("normalizes Electron key names", () => { - expect( - toElectronAccelerator({ - key: "ArrowUp", - metaKey: false, - ctrlKey: true, - shiftKey: false, - altKey: true, - modKey: false, - }), - ).toBe("Control+Alt+Up"); - }); }); describe("findCaptureSource", () => { @@ -690,15 +513,6 @@ describe("findCaptureSource", () => { }); describe("isWaylandSession", () => { - it.each([ - ["linux", { XDG_SESSION_TYPE: "wayland" }, true], - ["linux", { WAYLAND_DISPLAY: "wayland-0" }, true], - ["linux", { XDG_SESSION_TYPE: "x11" }, false], - ["darwin", { XDG_SESSION_TYPE: "wayland", WAYLAND_DISPLAY: "wayland-0" }, false], - ] as const)("detects %s session %o as portal=%s", (platform, environment, expected) => { - expect(isWaylandSession(platform, environment)).toBe(expected); - }); - effectIt.effect( "falls back to a live runtime directory socket when session variables are stripped", () => @@ -743,74 +557,3 @@ describe("isWaylandSession", () => { }), ); }); - -describe("snapShotShortcutRegistrationFailureMessage", () => { - it("distinguishes a modifier listener failure from a reserved key chord", () => { - expect( - snapShotShortcutRegistrationFailureMessage({ kind: "both-shift-keys" }, "darwin"), - ).toMatch(/Shift \+ Shift is not available/); - expect( - snapShotShortcutRegistrationFailureMessage( - { kind: "modifier-pair", modifier: "meta" }, - "darwin", - ), - ).toMatch(/Command \+ Command is not available/); - expect( - snapShotShortcutRegistrationFailureMessage( - { kind: "modifier-pair", modifier: "meta" }, - "linux", - ), - ).toMatch(/Super \+ Super is not available/); - expect( - snapShotShortcutRegistrationFailureMessage( - { - key: "2", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }, - "darwin", - ), - ).toMatch(/already used/); - }); -}); - -describe("snapShotShortcutSystemConflict", () => { - it("blocks shortcuts that would break typing or common app actions", () => { - expect( - snapShotShortcutSystemConflict({ - key: "s", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: false, - }), - ).toMatch(/typing/); - expect( - snapShotShortcutSystemConflict({ - key: "c", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }), - ).toMatch(/Copy/); - }); - - it("allows a specific multi-modifier shortcut", () => { - expect( - snapShotShortcutSystemConflict({ - key: "2", - metaKey: false, - ctrlKey: false, - shiftKey: true, - altKey: false, - modKey: true, - }), - ).toBeNull(); - }); -}); diff --git a/apps/desktop/src/snapShot/snapShot.ts b/apps/desktop/src/snapShot/snapShot.ts index 0c85a01484253..28bd301c557e6 100644 --- a/apps/desktop/src/snapShot/snapShot.ts +++ b/apps/desktop/src/snapShot/snapShot.ts @@ -168,7 +168,7 @@ export function boundedSnapShotString( return candidate.slice(0, end).trimEnd(); } -export function capturedImageBounds( +function capturedImageBounds( bounds: WindowBounds | null | undefined, sourceBounds: WindowBounds, imageSize: CapturedImageSize, @@ -477,6 +477,8 @@ export function findAccessibleWindow< readonly sourceTitle?: string; readonly bounds: WindowBounds; readonly clientBounds?: WindowBounds | undefined; + readonly platform?: NodeJS.Platform; + readonly bundleId?: string | undefined; }, matchMode: "screen-bounds" | "wayland" = "screen-bounds", options: { readonly allowUntitledUniqueBounds?: boolean } = {}, @@ -515,9 +517,10 @@ export function findAccessibleWindow< const activeMatches = matches.filter((window) => safeProperty(() => window.active) === true); if (activeMatches.length === 1) return activeMatches[0]; if (matches.length > 1) return undefined; + const browserMatch = findBrowserTitleMatch(windows, titles, captured, matchMode, matchesBounds); + if (browserMatch) return browserMatch; } - // GTK4/libadwaita often exposes the frame as an unnamed group. A PID-scoped - // lookup can accept the one window whose bounds match; size-only guesses cannot. + // GTK4 frames may be unnamed; accept only a PID-scoped unique bounds match, never size alone. if (!options.allowUntitledUniqueBounds) return undefined; const boundsMatches = windows.filter( (window) => normalizeTitle(window.name ?? "") === "" && matchesBounds(window), @@ -525,6 +528,37 @@ export function findAccessibleWindow< return boundsMatches.length === 1 ? boundsMatches[0] : undefined; } +// Chrome's macOS AX title can append the browser and profile to the captured page title. +function findBrowserTitleMatch( + windows: readonly T[], + titles: ReadonlySet, + captured: { readonly platform?: NodeJS.Platform; readonly bundleId?: string | undefined }, + matchMode: "screen-bounds" | "wayland", + matchesBounds: (window: T) => boolean, +): T | undefined { + if (captured.platform !== "darwin" || matchMode !== "screen-bounds") return undefined; + const browserName = /^com\.google\.Chrome(?:\.(?:beta|dev|canary))?$/.test( + captured.bundleId ?? "", + ) + ? "Google Chrome" + : captured.bundleId === "org.chromium.Chromium" + ? "Chromium" + : undefined; + if (!browserName) return undefined; + const browserMatches = windows.filter((window) => { + if (!matchesBounds(window)) return false; + const name = window.name?.trim() ?? ""; + return [...titles].some((title) => { + const prefix = `${title} - ${browserName}`; + return ( + name === prefix || + (name.startsWith(prefix) && /^ [–—-] \S.*$/u.test(name.slice(prefix.length))) + ); + }); + }); + return browserMatches.length === 1 ? browserMatches[0] : undefined; +} + const ELECTRON_KEY_NAMES: Readonly> = { " ": "Space", "+": "Plus", diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts deleted file mode 100644 index 1fe2b86aae7b9..0000000000000 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, describe, it } from "@effect/vitest"; -import * as NetService from "@t3tools/shared/Net"; -import { SshPasswordPromptError } from "@t3tools/ssh/errors"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; - -import * as DesktopSshEnvironment from "./DesktopSshEnvironment.ts"; -import * as DesktopSshPasswordPrompts from "./DesktopSshPasswordPrompts.ts"; - -function makeTempHomeDir() { - return Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - return yield* fs.makeTempDirectoryScoped({ prefix: "t3-ssh-env-test-" }); - }); -} - -describe("sshEnvironment", () => { - it("keeps prompt presentation diagnostics distinct from the legacy wrapper message", () => { - const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({ - requestId: "prompt-1", - destination: "devbox", - operation: "send-prompt-request", - cause: new Error("renderer send failed"), - }); - - assert.equal(cause.message, "Failed to present SSH password prompt for devbox."); - assert.equal( - DesktopSshEnvironment.toSshPasswordPromptError(cause).message, - "T3 Code window is not available for SSH authentication.", - ); - }); - - it("treats password prompt timeouts as cancellable authentication prompts", () => { - assert.equal( - DesktopSshEnvironment.isDesktopSshPasswordPromptCancellation( - new SshPasswordPromptError({ - message: "SSH authentication timed out for devbox.", - cause: new DesktopSshPasswordPrompts.DesktopSshPromptTimedOutError({ - requestId: "prompt-1", - destination: "devbox", - }), - }), - ), - true, - ); - }); - - it.effect("wires desktop host discovery through the ssh package runtime", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const homeDir = yield* makeTempHomeDir(); - const sshDir = path.join(homeDir, ".ssh"); - yield* fs.makeDirectory(path.join(sshDir, "config.d"), { recursive: true }); - yield* fs.writeFileString( - path.join(sshDir, "config"), - ["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"), - ); - yield* fs.writeFileString( - path.join(sshDir, "config.d", "team.conf"), - [ - "Host staging", - " HostName staging.example.com", - "Host *", - " ServerAliveInterval 30", - "", - ].join("\n"), - ); - yield* fs.writeFileString( - path.join(sshDir, "known_hosts"), - [ - "known.example.com ssh-ed25519 AAAA", - "|1|hashed|entry ssh-ed25519 AAAA", - "[bastion.example.com]:2222 ssh-ed25519 AAAA", - "", - ].join("\n"), - ); - - const sshEnvironment = yield* DesktopSshEnvironment.DesktopSshEnvironment; - const hosts = yield* sshEnvironment.discoverHosts({ homeDir }); - assert.deepEqual(hosts, [ - { - alias: "bastion.example.com", - hostname: "bastion.example.com", - username: null, - port: null, - source: "known-hosts", - }, - { - alias: "devbox", - hostname: "devbox", - username: null, - port: null, - source: "ssh-config", - }, - { - alias: "known.example.com", - hostname: "known.example.com", - username: null, - port: null, - source: "known-hosts", - }, - { - alias: "staging", - hostname: "staging", - username: null, - port: null, - source: "ssh-config", - }, - ]); - }).pipe( - Effect.provide( - DesktopSshEnvironment.layer().pipe( - Layer.provideMerge( - Layer.succeed(DesktopSshPasswordPrompts.DesktopSshPasswordPrompts, { - request: () => Effect.die("unexpected password prompt request"), - resolve: () => Effect.die("unexpected password prompt resolution"), - }), - ), - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge(NodeHttpClient.layerUndici), - Layer.provideMerge(NetService.layer), - ), - ), - Effect.scoped, - ), - ); -}); diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 08dd48b718f93..eac148ae4d0f3 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -87,7 +87,7 @@ function unexpectedPasswordPromptError(error: never): never { throw new Error(`Unhandled desktop SSH password prompt error: ${String(error)}`); } -export function toSshPasswordPromptError( +function toSshPasswordPromptError( cause: DesktopSshPasswordPrompts.DesktopSshPasswordPromptRequestError, ): SshPasswordPromptError { let message: string; @@ -125,7 +125,7 @@ const makePasswordPrompt = ( prompts.request(request).pipe(Effect.mapError(toSshPasswordPromptError)), }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const manager = yield* SshTunnel.SshEnvironmentManager; const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts; diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts index dc46278a11504..b86cc275df230 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.test.ts @@ -1,6 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -144,59 +143,6 @@ describe("DesktopSshPasswordPrompts", () => { }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); }); - it.effect("times out pending renderer prompts with a typed error", () => { - const testWindow = makeTestWindow(); - - return Effect.gen(function* () { - const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts; - const fiber = yield* prompts - .request({ - destination: "devbox", - username: null, - prompt: "Enter the SSH password.", - attempt: 1, - }) - .pipe(Effect.forkScoped); - - yield* Effect.yieldNow; - yield* TestClock.adjust(Duration.millis(1_000)); - const error = yield* Fiber.join(fiber).pipe(Effect.flip); - assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptTimedOutError); - assert.equal(error.destination, "devbox"); - }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); - }); - - it.effect("cleans up a prompt that fails during renderer delivery", () => { - const cause = new Error("renderer unavailable"); - const testWindow = makeTestWindow({ sendError: cause }); - - return Effect.gen(function* () { - const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts; - const error = yield* prompts - .request({ - destination: "devbox", - username: "julius", - prompt: "Enter the SSH password.", - attempt: 1, - }) - .pipe(Effect.flip); - - assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError); - assert.equal(error.operation, "send-prompt-request"); - assert.equal(error.destination, "devbox"); - const requestId = error.requestId; - if (requestId === null) { - assert.fail("renderer delivery failures must retain their request id"); - } - assert.equal(testWindow.closedListenerCount(), 0); - - const resolveError = yield* prompts - .resolve({ requestId, password: "secret" }) - .pipe(Effect.flip); - assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError); - }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); - }); - it.effect("keeps a submitted password when a later presentation step fails", () => { const testWindow = makeTestWindow({ isMinimizedError: new Error("failed to read minimized state"), @@ -225,25 +171,4 @@ describe("DesktopSshPasswordPrompts", () => { assert.equal(testWindow.closedListenerCount(), 0); }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); }); - - it.effect("classifies a failed initial window availability check", () => { - const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") }); - - return Effect.gen(function* () { - const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts; - const error = yield* prompts - .request({ - destination: "devbox", - username: "julius", - prompt: "Enter the SSH password.", - attempt: 1, - }) - .pipe(Effect.flip); - - assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError); - assert.equal(error.operation, "check-window-before-request"); - assert.equal(error.requestId, null); - assert.deepEqual(testWindow.sentMessages, []); - }).pipe(Effect.provide(layer(testWindow.window)), Effect.scoped); - }); }); diff --git a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts index 296b81339e80e..7442282aa15ad 100644 --- a/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts +++ b/apps/desktop/src/ssh/DesktopSshPasswordPrompts.ts @@ -218,7 +218,7 @@ const failPending = ( error: DesktopSshPasswordPromptRequestError, ) => Deferred.fail(pending.deferred, error).pipe(Effect.asVoid); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* ( options: DesktopSshPasswordPromptsOptions = {}, ) { diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index 5e59973901c1a..f3f0163401ab2 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -1,18 +1,13 @@ -import { DesktopHostTelemetryMessage } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; 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"; -import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import type * as Electron from "electron"; @@ -96,396 +91,6 @@ describe("DesktopTelemetryPublisher", () => { assert.isDefined(closeFiber.pollUnsafe()); }), ); - - it.effect("publishes Electron metrics and event-driven power state over NDJSON", () => - Effect.gen(function* () { - const onBattery = yield* Ref.make(false); - const systemIdleState = yield* Ref.make("active"); - let beforeSystemIdleState: Effect.Effect = Effect.void; - let metricsReadCount = 0; - const recordedMetrics: ReadonlyArray[] = []; - const simpleListeners = new Map void>(); - let thermalListener: ((state: ElectronPowerMonitor.ElectronThermalState) => void) | null = - null; - let speedLimitListener: ((limit: number) => void) | null = null; - const metrics = [ - { - pid: 4_242, - type: "Browser", - creationTime: 1_000.75, - name: "electron", - cpu: { - percentCPUUsage: 12.5, - cumulativeCPUUsage: 3.25, - idleWakeupsPerSecond: 7, - }, - memory: { - workingSetSize: 2_048, - peakWorkingSetSize: 4_096, - }, - } as Electron.ProcessMetric, - ]; - const layerPower = Layer.succeed( - ElectronPowerMonitor.ElectronPowerMonitor, - ElectronPowerMonitor.ElectronPowerMonitor.of({ - isOnBatteryPower: Ref.get(onBattery), - getSystemIdleTime: Effect.succeed(5), - getSystemIdleState: () => - beforeSystemIdleState.pipe(Effect.andThen(Ref.get(systemIdleState))), - getCurrentThermalState: Effect.succeed("nominal"), - onSimpleEvent: (eventName, listener) => - Effect.sync(() => { - simpleListeners.set(eventName, listener); - }), - onThermalStateChange: (listener) => - Effect.sync(() => { - thermalListener = listener; - }), - onSpeedLimitChange: (listener) => - Effect.sync(() => { - speedLimitListener = listener; - }), - }), - ); - const layer = DesktopTelemetryPublisher.layer.pipe( - Layer.provide( - Layer.mergeAll( - layerElectronApp(metrics, () => { - metricsReadCount += 1; - }), - layerPower, - Layer.succeed(DesktopRendererHistory.DesktopRendererHistory, { - register: () => Effect.void, - shutdown: Effect.void, - recordMetrics: (sample) => - Effect.sync(() => { - recordedMetrics.push(sample); - }), - }), - ), - ), - ); - - yield* Effect.gen(function* () { - const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher; - const encoded = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect); - const decoder = new TextDecoder(); - const decodeMessage = Schema.decodeUnknownEffect( - Schema.fromJsonString(DesktopHostTelemetryMessage), - ); - const messages = yield* Effect.forEach(encoded, (bytes) => - decodeMessage(decoder.decode(bytes).trim()), - ); - - const hello = messages[0]; - if (hello?.type !== "desktopTelemetryHello") { - return assert.fail("Expected the first telemetry message to be the hello."); - } - assert.equal(hello.electronPid, process.pid); - const initialSnapshot = messages[1]; - if (initialSnapshot?.type !== "desktopTelemetry") { - return assert.fail("Expected the second telemetry message to be a snapshot."); - } - assert.deepEqual(initialSnapshot.electronProcesses, []); - assert.equal(initialSnapshot.electronPid, process.pid); - assert.equal(metricsReadCount, 1); - assert.deepEqual(recordedMetrics, [metrics]); - - const nextSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe(Effect.forkChild); - yield* Effect.yieldNow; - yield* publisher.handleControlForSource("primary-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }); - const demandedSnapshot = Option.getOrThrow(yield* Fiber.join(nextSnapshotFiber)); - assert.equal(demandedSnapshot.electronProcesses[0]?.pid, 4_242); - assert.equal(demandedSnapshot.electronProcesses[0]?.creationTimeMs, 1_001); - assert.equal(demandedSnapshot.electronProcesses[0]?.cpuPercent, 12.5); - assert.equal(demandedSnapshot.electronProcesses[0]?.workingSetBytes, 2_048 * 1_024); - assert.equal(metricsReadCount, 2); - assert.deepEqual(recordedMetrics, [metrics, metrics]); - yield* publisher.handleControlForSource("secondary-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }); - yield* publisher.handleControlForSource("primary-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: false, - }); - yield* publisher.handleControlForSource("old-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }); - yield* publisher.handleControlForSource("secondary-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: false, - }); - yield* Effect.all( - [ - publisher.removeControlSource("old-backend"), - publisher.handleControlForSource("replacement-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }), - ], - { concurrency: "unbounded", discard: true }, - ); - - const batterySnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - simpleListeners.get("on-battery")?.(); - const batterySnapshot = Option.getOrThrow(yield* Fiber.join(batterySnapshotFiber)); - assert.equal(batterySnapshot.power.onBattery, "true"); - yield* Ref.set(onBattery, true); - - const metricsAfterBatteryEvent = metricsReadCount; - yield* TestClock.adjust(Duration.millis(4_999)); - assert.equal(metricsReadCount, metricsAfterBatteryEvent); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal(metricsReadCount, metricsAfterBatteryEvent + 1); - assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "true"); - - yield* Ref.set(onBattery, false); - const metricsBeforePolledAc = metricsReadCount; - yield* TestClock.adjust(Duration.seconds(5)); - assert.equal(metricsReadCount, metricsBeforePolledAc + 1); - assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.onBattery, "false"); - yield* TestClock.adjust(Duration.seconds(1)); - assert.equal(metricsReadCount, metricsBeforePolledAc + 2); - - const suspendedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - simpleListeners.get("suspend")?.(); - const suspendedSnapshot = Option.getOrThrow(yield* Fiber.join(suspendedSnapshotFiber)); - assert.isTrue(suspendedSnapshot.power.suspended); - - const constrainedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - thermalListener?.("serious"); - const constrainedSnapshot = Option.getOrThrow(yield* Fiber.join(constrainedSnapshotFiber)); - assert.equal(constrainedSnapshot.power.thermalState, "serious"); - assert.isTrue(constrainedSnapshot.power.suspended); - - const metricsAfterThermalEvent = metricsReadCount; - const recoveredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* TestClock.adjust(Duration.millis(14_999)); - assert.equal(metricsReadCount, metricsAfterThermalEvent); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal(metricsReadCount, metricsAfterThermalEvent + 1); - const recoveredSnapshot = Option.getOrThrow(yield* Fiber.join(recoveredSnapshotFiber)); - assert.isFalse(recoveredSnapshot.power.suspended); - - const speedLimitSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - speedLimitListener?.(65); - const speedLimitSnapshot = Option.getOrThrow(yield* Fiber.join(speedLimitSnapshotFiber)); - assert.equal(Option.getOrNull(speedLimitSnapshot.speedLimitPercent), 65); - - const encodedSpeedLimit = yield* publisher.encoded.pipe(Stream.take(2), Stream.runCollect); - const decodedSpeedLimit = yield* decodeMessage(decoder.decode(encodedSpeedLimit[1]).trim()); - if (decodedSpeedLimit.type !== "desktopTelemetry") { - return assert.fail("Expected the encoded telemetry message to be a snapshot."); - } - assert.equal(Option.getOrNull(decodedSpeedLimit.speedLimitPercent), 65); - assert.equal(decodedSpeedLimit.electronProcesses[0]?.pid, 4_242); - assert.equal(decodedSpeedLimit.electronProcesses[0]?.creationTimeMs, 1_001); - - const metricsBeforeSecondaryOnlySample = metricsReadCount; - yield* TestClock.adjust(Duration.seconds(15)); - assert.equal(metricsReadCount, metricsBeforeSecondaryOnlySample + 1); - assert.equal( - (yield* publisher.latest).pipe(Option.getOrThrow).electronProcesses[0]?.pid, - 4_242, - ); - - const stoppedSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - yield* publisher.handleControlForSource("replacement-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: false, - }); - const stoppedSnapshot = Option.getOrThrow(yield* Fiber.join(stoppedSnapshotFiber)); - assert.deepEqual(stoppedSnapshot.electronProcesses, []); - const metricsAfterStopping = metricsReadCount; - const configuredSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - yield* publisher.handleControlForSource("primary-backend", { - version: 1, - type: "setHostPowerIntervals", - activeIntervalMs: 7_000, - idleIntervalMs: 11_000, - }); - const configuredSequence = Option.getOrThrow( - yield* Fiber.join(configuredSnapshotFiber), - ).sequence; - - yield* TestClock.adjust(Duration.millis(6_999)); - assert.equal( - (yield* publisher.latest).pipe(Option.getOrThrow).sequence, - configuredSequence, - ); - assert.equal(metricsReadCount, metricsAfterStopping + 1); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal( - (yield* publisher.latest).pipe(Option.getOrThrow).sequence, - configuredSequence + 1, - ); - assert.equal(metricsReadCount, metricsAfterStopping + 2); - - yield* Ref.set(systemIdleState, "locked"); - yield* TestClock.adjust(Duration.seconds(7)); - const lockedSequence = (yield* publisher.latest).pipe(Option.getOrThrow).sequence; - assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).power.locked, "true"); - yield* TestClock.adjust(Duration.millis(10_999)); - assert.equal((yield* publisher.latest).pipe(Option.getOrThrow).sequence, lockedSequence); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal( - (yield* publisher.latest).pipe(Option.getOrThrow).sequence, - lockedSequence + 1, - ); - - yield* Ref.set(systemIdleState, "active"); - yield* TestClock.adjust(Duration.seconds(11)); - const unlockedSnapshot = (yield* publisher.latest).pipe(Option.getOrThrow); - assert.equal(unlockedSnapshot.power.locked, "false"); - assert.equal(unlockedSnapshot.power.idle, "false"); - - yield* TestClock.adjust(Duration.millis(6_999)); - assert.equal( - (yield* publisher.latest).pipe(Option.getOrThrow).sequence, - unlockedSnapshot.sequence, - ); - yield* TestClock.adjust(Duration.millis(1)); - assert.equal( - (yield* publisher.latest).pipe(Option.getOrThrow).sequence, - unlockedSnapshot.sequence + 1, - ); - - const pollStarted = yield* Deferred.make(); - const releasePoll = yield* Deferred.make(); - beforeSystemIdleState = Deferred.succeed(pollStarted, undefined).pipe( - Effect.andThen(Deferred.await(releasePoll)), - ); - const concurrentEventSnapshotFiber = yield* Stream.runHead(publisher.changes).pipe( - Effect.forkChild, - ); - yield* Effect.yieldNow; - yield* publisher.handleControlForSource("primary-backend", { - version: 1, - type: "setDiagnosticsDemand", - enabled: true, - }); - yield* Deferred.await(pollStarted); - simpleListeners.get("lock-screen")?.(); - thermalListener?.("critical"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Deferred.succeed(releasePoll, undefined); - - const concurrentEventSnapshot = Option.getOrThrow( - yield* Fiber.join(concurrentEventSnapshotFiber), - ); - assert.equal(concurrentEventSnapshot.power.locked, "true"); - assert.equal(concurrentEventSnapshot.power.thermalState, "critical"); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("routes requestDesktopUpdate control messages and replays update reports", () => - Effect.gen(function* () { - const layerPower = Layer.succeed( - ElectronPowerMonitor.ElectronPowerMonitor, - ElectronPowerMonitor.ElectronPowerMonitor.of({ - isOnBatteryPower: Effect.succeed(false), - getSystemIdleTime: Effect.succeed(0), - getSystemIdleState: () => Effect.succeed("active"), - getCurrentThermalState: Effect.succeed("nominal"), - onSimpleEvent: () => Effect.void, - onThermalStateChange: () => Effect.void, - onSpeedLimitChange: () => Effect.void, - }), - ); - const layer = DesktopTelemetryPublisher.layer.pipe( - Layer.provide(Layer.mergeAll(layerElectronApp([]), layerPower, layerHistory)), - ); - - yield* Effect.gen(function* () { - const publisher = yield* DesktopTelemetryPublisher.DesktopTelemetryPublisher; - - const requestFiber = yield* Stream.runHead(publisher.updateRequests).pipe(Effect.forkChild); - yield* Effect.yieldNow; - yield* publisher.handleControlForSource("test", { - version: 1, - type: "requestDesktopUpdate", - requestId: "req-9", - }); - const received = yield* Fiber.join(requestFiber); - assert.equal(Option.getOrThrow(received).requestId, "req-9"); - - const report = { - version: 1, - type: "desktopUpdateStatus", - outcome: "up-to-date", - state: { - enabled: true, - status: "up-to-date", - channel: "latest", - currentVersion: "1.2.3", - hostArch: "arm64", - appArch: "arm64", - runningUnderArm64Translation: false, - availableVersion: null, - downloadedVersion: null, - releaseNotes: [], - downloadPercent: null, - checkedAt: null, - message: null, - errorContext: null, - canRetry: false, - omittedReleaseCount: 0, - }, - } as const; - yield* publisher.publishUpdateReport(report); - - const decoder = new TextDecoder(); - const decodeMessage = Schema.decodeUnknownEffect( - Schema.fromJsonString(DesktopHostTelemetryMessage), - ); - const replayed = yield* publisher.encoded.pipe( - Stream.mapEffect((bytes) => decodeMessage(decoder.decode(bytes).trim())), - Stream.filter((message) => message.type === "desktopUpdateStatus"), - Stream.runHead, - ); - const replayedReport = Option.getOrThrow(replayed); - if (replayedReport.type !== "desktopUpdateStatus") { - return assert.fail("Expected a desktop update status report."); - } - assert.equal(replayedReport.outcome, "up-to-date"); - assert.equal(replayedReport.state.currentVersion, "1.2.3"); - }).pipe(Effect.provide(layer)); - }), - ); }); describe("DesktopRendererHistory", () => { diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts index 1155a2b15b0ce..8800c4f428331 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts @@ -141,7 +141,7 @@ function sampleInterval( return LIVE_SAMPLE_INTERVAL; } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () { const electronApp = yield* ElectronApp.ElectronApp; const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor; @@ -199,96 +199,98 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () { ), ).pipe(Effect.forkScoped); - const sampleOnce = (allowSuspendRecovery: boolean) => - Effect.gen(function* () { - const sampledAt = yield* DateTime.now; - const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt); - const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0; - const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all( - [ - Ref.get(powerState), - powerMonitor.getSystemIdleTime, - powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS), - powerMonitor.isOnBatteryPower, - electronApp.getAppMetrics, - ], - { concurrency: "unbounded" }, - ); - // One Electron sampler preserves the shared CPU measurement interval. - yield* rendererHistory.recordMetrics(metrics); - const polledLocked = - systemIdleState === "unknown" - ? currentPower.locked - : booleanState(systemIdleState === "locked"); - const polledOnBattery = booleanState(onBattery); - const observedPower = yield* Ref.modify(powerState, (latestPower) => { - const preserveEventLocked = - latestPower.lockedEventPending || - latestPower.locked !== currentPower.locked || - latestPower.lockedEventPending !== currentPower.lockedEventPending; - const preserveEventOnBattery = - latestPower.onBatteryEventPending || - latestPower.onBattery !== currentPower.onBattery || - latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending; - const preserveEventSuspended = - latestPower.suspendedEventPending || - latestPower.suspended !== currentPower.suspended || - latestPower.suspendedEventPending !== currentPower.suspendedEventPending; - const next: PowerState = { - ...latestPower, - idle: idleState(systemIdleState), - locked: preserveEventLocked ? latestPower.locked : polledLocked, - lockedEventPending: - latestPower.lockedEventPending && - (systemIdleState === "unknown" || polledLocked !== latestPower.locked), - suspended: - allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended, - suspendedEventPending: false, - onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery, - onBatteryEventPending: - latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery, + const sampleOnce = + /* Periodic telemetry sampling should not generate its own tracing traffic. */ + Effect.fnUntraced( + function* (allowSuspendRecovery: boolean) { + const sampledAt = yield* DateTime.now; + const sampledAtUnixMs = DateTime.toEpochMillis(sampledAt); + const demand = (yield* Ref.get(diagnosticsDemandSources)).size > 0; + const [currentPower, idleSeconds, systemIdleState, onBattery, metrics] = yield* Effect.all( + [ + Ref.get(powerState), + powerMonitor.getSystemIdleTime, + powerMonitor.getSystemIdleState(IDLE_THRESHOLD_SECONDS), + powerMonitor.isOnBatteryPower, + electronApp.getAppMetrics, + ], + { concurrency: "unbounded" }, + ); + // One Electron sampler preserves the shared CPU measurement interval. + yield* rendererHistory.recordMetrics(metrics); + const polledLocked = + systemIdleState === "unknown" + ? currentPower.locked + : booleanState(systemIdleState === "locked"); + const polledOnBattery = booleanState(onBattery); + const observedPower = yield* Ref.modify(powerState, (latestPower) => { + const preserveEventLocked = + latestPower.lockedEventPending || + latestPower.locked !== currentPower.locked || + latestPower.lockedEventPending !== currentPower.lockedEventPending; + const preserveEventOnBattery = + latestPower.onBatteryEventPending || + latestPower.onBattery !== currentPower.onBattery || + latestPower.onBatteryEventPending !== currentPower.onBatteryEventPending; + const preserveEventSuspended = + latestPower.suspendedEventPending || + latestPower.suspended !== currentPower.suspended || + latestPower.suspendedEventPending !== currentPower.suspendedEventPending; + const next: PowerState = { + ...latestPower, + idle: idleState(systemIdleState), + locked: preserveEventLocked ? latestPower.locked : polledLocked, + lockedEventPending: + latestPower.lockedEventPending && + (systemIdleState === "unknown" || polledLocked !== latestPower.locked), + suspended: + allowSuspendRecovery && !preserveEventSuspended ? false : latestPower.suspended, + suspendedEventPending: false, + onBattery: preserveEventOnBattery ? latestPower.onBattery : polledOnBattery, + onBatteryEventPending: + latestPower.onBatteryEventPending && polledOnBattery !== latestPower.onBattery, + }; + return [next, next] as const; + }); + const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]); + const snapshot: DesktopHostTelemetrySnapshot = { + version: 1, + type: "desktopTelemetry", + sequence: nextSequence, + sampledAtUnixMs, + electronPid: process.pid, + power: { + source: "electron-main", + idle: observedPower.idle, + idleSeconds, + locked: observedPower.locked, + suspended: observedPower.suspended, + onBattery: observedPower.onBattery, + lowPowerMode: "unknown", + thermalState: observedPower.thermalState, + stale: false, + updatedAt: sampledAt, + }, + speedLimitPercent: observedPower.speedLimitPercent, + electronProcesses: (demand ? metrics : []).map((metric) => ({ + pid: metric.pid, + creationTimeMs: Math.max(0, Math.round(metric.creationTime)), + type: metric.type, + ...(metric.name === undefined ? {} : { name: metric.name }), + ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }), + cpuPercent: metric.cpu.percentCPUUsage, + ...(metric.cpu.cumulativeCPUUsage === undefined + ? {} + : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }), + idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond, + workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)), + peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)), + })), }; - return [next, next] as const; - }); - const nextSequence = yield* Ref.modify(sequence, (current) => [current + 1, current + 1]); - const snapshot: DesktopHostTelemetrySnapshot = { - version: 1, - type: "desktopTelemetry", - sequence: nextSequence, - sampledAtUnixMs, - electronPid: process.pid, - power: { - source: "electron-main", - idle: observedPower.idle, - idleSeconds, - locked: observedPower.locked, - suspended: observedPower.suspended, - onBattery: observedPower.onBattery, - lowPowerMode: "unknown", - thermalState: observedPower.thermalState, - stale: false, - updatedAt: sampledAt, - }, - speedLimitPercent: observedPower.speedLimitPercent, - electronProcesses: (demand ? metrics : []).map((metric) => ({ - pid: metric.pid, - creationTimeMs: Math.max(0, Math.round(metric.creationTime)), - type: metric.type, - ...(metric.name === undefined ? {} : { name: metric.name }), - ...(metric.serviceName === undefined ? {} : { serviceName: metric.serviceName }), - cpuPercent: metric.cpu.percentCPUUsage, - ...(metric.cpu.cumulativeCPUUsage === undefined - ? {} - : { cumulativeCpuSeconds: metric.cpu.cumulativeCPUUsage }), - idleWakeupsPerSecond: metric.cpu.idleWakeupsPerSecond, - workingSetBytes: Math.max(0, Math.round(metric.memory.workingSetSize * 1024)), - peakWorkingSetBytes: Math.max(0, Math.round(metric.memory.peakWorkingSetSize * 1024)), - })), - }; - yield* Ref.set(latest, Option.some(snapshot)); - yield* PubSub.publish(changes, snapshot); - }).pipe( + yield* Ref.set(latest, Option.some(snapshot)); + yield* PubSub.publish(changes, snapshot); + }, Effect.catchCauseIf( (cause) => !Cause.hasInterrupts(cause), (cause) => diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts index 1fc0a9e39be5d..253a015d8ec9e 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.test.ts @@ -22,9 +22,7 @@ import * as DesktopRemoteUpdates from "./DesktopRemoteUpdates.ts"; import * as DesktopUpdates from "./DesktopUpdates.ts"; import { makeHarness } from "./updatesTestHarness.ts"; -// The remote flow hops between the test runtime's fibers and the updater's -// runPromise-driven event handlers, so settling needs real microtask turns, -// not just fiber yields. +// Updater runPromise handlers need real microtasks between test-runtime fiber yields. const settle = Effect.gen(function* () { for (let i = 0; i < 20; i += 1) { yield* Effect.yieldNow; @@ -326,8 +324,6 @@ describe("DesktopRemoteUpdates", () => { }); it.effect("retries a download refused while the check still holds the reservation", () => { - // electron-updater emits update-available from inside checkForUpdates, - // before the check action releases its reservation. const releaseCheck = Deferred.makeUnsafe(); const harness = makeHarness({ checkForUpdates: Deferred.await(releaseCheck) }); @@ -359,9 +355,6 @@ describe("DesktopRemoteUpdates", () => { }); it.effect("waits for the download reservation before reporting prepared", () => { - // update-downloaded fires from inside downloadUpdate. If the flow - // reported "installing" right then, install would be refused for the - // held reservation after the irrevocable terminal already went out. const releaseDownload = Deferred.makeUnsafe(); const harness = makeHarness({ downloadUpdate: Deferred.await(releaseDownload) }); @@ -484,69 +477,6 @@ describe("DesktopRemoteUpdates", () => { ); }); - it.effect("fails a prepared install when its background check stays blocked", () => { - const backgroundCheckStarted = Deferred.makeUnsafe(); - const releaseBackgroundCheck = Deferred.makeUnsafe(); - let checks = 0; - const harness = makeHarness({ - checkForUpdates: Effect.suspend(() => { - checks += 1; - return checks === 2 - ? Deferred.succeed(backgroundCheckStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseBackgroundCheck)), - ) - : Effect.void; - }), - }); - - return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) => - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* Queue.offer(requests, request("req-blocked-background-check")); - yield* settle; - harness.emit("update-available", { version: "1.2.4" }); - yield* settle; - harness.emit("update-downloaded", { version: "1.2.4" }); - yield* settle; - - const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild); - yield* Deferred.await(backgroundCheckStarted); - const commit = { - version: 1, - type: "commitDesktopUpdate", - requestId: "req-blocked-background-check", - } as const; - yield* Queue.offer(commits, commit); - yield* settle; - yield* TestClock.adjust(Duration.seconds(91)); - yield* settle; - - assert.equal(harness.quitAndInstalls(), 0); - assert.deepEqual( - terminalReports(reports) - .filter((report) => report.requestId === "req-blocked-background-check") - .map((report) => report.outcome), - ["ready-to-install", "failed"], - ); - - harness.emit("update-downloaded", { version: "1.2.4" }); - yield* Deferred.succeed(releaseBackgroundCheck, undefined); - yield* Fiber.join(backgroundCheck); - yield* settle; - assert.equal(harness.quitAndInstalls(), 0); - - yield* Queue.offer(commits, commit); - yield* settle; - assert.deepEqual( - terminalReports(reports) - .filter((report) => report.requestId === "req-blocked-background-check") - .map((report) => report.outcome), - ["ready-to-install", "failed", "failed"], - ); - }), - ); - }); - it.effect("rejects a new preparation while an install commit is active", () => { const installStarted = Deferred.makeUnsafe(); const releaseInstall = Deferred.makeUnsafe(); @@ -640,32 +570,6 @@ describe("DesktopRemoteUpdates", () => { ); }); - it.effect("keeps every queued cancellation until its request starts", () => { - const harness = makeHarness(); - - return runRemoteUpdatesTest(harness, ({ requests, cancellations }) => - Effect.gen(function* () { - for (let index = 0; index < 40; index += 1) { - yield* Queue.offer(cancellations, { - version: 1, - type: "cancelDesktopUpdate", - requestId: `req-queued-cancel-${index}`, - }); - } - yield* settle; - for (let index = 0; index < 40; index += 1) { - yield* Queue.offer(requests, request(`req-queued-cancel-${index}`)); - } - yield* settle; - assert.equal(harness.checkCount(), 0); - - yield* Queue.offer(requests, request("req-after-queued-cancels")); - yield* settle; - assert.equal(harness.checkCount(), 1); - }), - ); - }); - it.effect("does not install after cancellation wins the commit claim", () => { const harness = makeHarness(); @@ -757,34 +661,6 @@ describe("DesktopRemoteUpdates", () => { ); }); - it.effect("expires an uncommitted preparation", () => { - const harness = makeHarness(); - - return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) => - Effect.gen(function* () { - yield* Queue.offer(requests, request("req-stale")); - yield* settle; - harness.emit("update-available", { version: "1.2.4" }); - yield* settle; - harness.emit("update-downloaded", { version: "1.2.4" }); - yield* settle; - - yield* TestClock.setTime(Duration.toMillis(Duration.minutes(6))); - yield* Queue.offer(commits, { - version: 1, - type: "commitDesktopUpdate", - requestId: "req-stale", - }); - yield* settle; - - const outcomes = terminalReports(reports) - .filter((report) => report.requestId === "req-stale") - .map((report) => report.outcome); - assert.deepEqual(outcomes, ["ready-to-install", "failed"]); - }), - ); - }); - it.effect("reports up-to-date without installing when there is no update", () => { const harness = makeHarness(); @@ -803,24 +679,4 @@ describe("DesktopRemoteUpdates", () => { }), ); }); - - it.effect("fails fast with the disabled reason when updates are off", () => { - const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } }); - - return runRemoteUpdatesTest(harness, ({ reports, requests }) => - Effect.gen(function* () { - yield* Queue.offer(requests, request("req-3")); - yield* settle; - - const terminals = terminalReports(reports); - assert.equal(terminals.length, 1); - assert.equal(terminals[0]?.outcome, "failed"); - assert.equal( - terminals[0]?.reason, - "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.", - ); - assert.equal(harness.quitAndInstalls(), 0); - }), - ); - }); }); diff --git a/apps/desktop/src/updates/DesktopRemoteUpdates.ts b/apps/desktop/src/updates/DesktopRemoteUpdates.ts index 716a73c199aa6..cb606d8fbd253 100644 --- a/apps/desktop/src/updates/DesktopRemoteUpdates.ts +++ b/apps/desktop/src/updates/DesktopRemoteUpdates.ts @@ -175,11 +175,7 @@ export const listen: Effect.Effect< const { latest, changes } = yield* updates.subscribe; const disabledReason = Option.getOrNull(yield* updates.disabledReason); let attempts: RemoteDesktopUpdateAttempts = { checks: 0, downloads: 0 }; - // A state event can land while the action that produced it still holds - // the reservation (e.g. "available" before the check releases), so a - // forked action can be refused with no later state event to retry on. - // Rejected actions re-enqueue their state here after a short pause so - // the step runs again once the reservation is free. + // State events can precede reservation release; re-enqueue refused actions so they retry after release. const retries = yield* Queue.unbounded(); const retryLater = (state: DesktopUpdateState) => Effect.sleep(ACTION_RETRY_DELAY).pipe( @@ -188,84 +184,85 @@ export const listen: Effect.Effect< Effect.forkScoped, ); - const step = (state: DesktopUpdateState): Effect.Effect => - Effect.gen(function* () { - const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason); - switch (next.action) { - case "wait": - return false; - case "check": - attempts = { ...attempts, checks: attempts.checks + 1 }; - yield* updates.check("remote-update").pipe( - Effect.flatMap((result) => { - if (result.checked) return Effect.void; - attempts = { ...attempts, checks: attempts.checks - 1 }; - return retryLater(state); - }), - Effect.forkScoped, - ); + const step = Effect.fn("DesktopRemoteUpdates.step")(function* ( + state: DesktopUpdateState, + ): Effect.fn.Return { + const next = nextRemoteDesktopUpdateStep(state, attempts, disabledReason); + switch (next.action) { + case "wait": + return false; + case "check": + attempts = { ...attempts, checks: attempts.checks + 1 }; + yield* updates.check("remote-update").pipe( + Effect.flatMap((result) => { + if (result.checked) return Effect.void; + attempts = { ...attempts, checks: attempts.checks - 1 }; + return retryLater(state); + }), + Effect.forkScoped, + ); + return false; + case "download": + attempts = { ...attempts, downloads: attempts.downloads + 1 }; + yield* updates.download.pipe( + Effect.flatMap((result) => { + if (result.accepted) return Effect.void; + attempts = { ...attempts, downloads: attempts.downloads - 1 }; + return retryLater(state); + }), + Effect.forkScoped, + ); + return false; + case "install": { + // The download event fires before its action releases the + // updater reservation. Wait until the prepared install can + // be committed by the client in a separate RPC. + if (yield* updates.isActionActive) { + yield* retryLater(state); return false; - case "download": - attempts = { ...attempts, downloads: attempts.downloads + 1 }; - yield* updates.download.pipe( - Effect.flatMap((result) => { - if (result.accepted) return Effect.void; - attempts = { ...attempts, downloads: attempts.downloads - 1 }; - return retryLater(state); - }), - Effect.forkScoped, - ); - return false; - case "install": { - // The download event fires before its action releases the - // updater reservation. Wait until the prepared install can - // be committed by the client in a separate RPC. - if (yield* updates.isActionActive) { - yield* retryLater(state); - return false; - } - if (state.downloadedVersion === null) { - yield* publishReport( - state, - { - outcome: "failed", - reason: "The desktop app lost the downloaded update.", - }, - request.requestId, - ); - return true; - } - yield* Ref.set( - preparedUpdateRef, - Option.some({ - requestId: request.requestId, - downloadedVersion: state.downloadedVersion, - status: "prepared", - expiresAt: - (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL), - }), - ); - yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId); - yield* logInfo("remote update prepared", { requestId: request.requestId }); - return true; } - case "done": + if (state.downloadedVersion === null) { yield* publishReport( state, { - outcome: next.outcome, - ...(next.reason === undefined ? {} : { reason: next.reason }), + outcome: "failed", + reason: "The desktop app lost the downloaded update.", }, request.requestId, ); - yield* logInfo("remote update finished", { - requestId: request.requestId, - outcome: next.outcome, - reason: next.reason ?? null, - }); return true; + } + yield* Ref.set( + preparedUpdateRef, + Option.some({ + requestId: request.requestId, + downloadedVersion: state.downloadedVersion, + status: "prepared", + expiresAt: + (yield* Clock.currentTimeMillis) + Duration.toMillis(PREPARED_UPDATE_TTL), + }), + ); + yield* publishReport(state, { outcome: "ready-to-install" }, request.requestId); + yield* logInfo("remote update prepared", { requestId: request.requestId }); + return true; } - }); + case "done": + yield* publishReport( + state, + { + outcome: next.outcome, + ...(next.reason === undefined ? {} : { reason: next.reason }), + }, + request.requestId, + ); + yield* logInfo("remote update finished", { + requestId: request.requestId, + outcome: next.outcome, + reason: next.reason ?? null, + }); + return true; + } + }); yield* Effect.raceFirst( Effect.gen(function* () { @@ -415,11 +412,7 @@ export const listen: Effect.Effect< result.state.downloadedVersion === claim.prepared.downloadedVersion && (yield* updates.isInstallActive) ) { - // Another install (local, or an earlier remote request) already owns - // the shutdown and will relaunch the app on the same downloaded - // version. This commit joins it: no failure marker, and the client - // proves the handoff the same way, by transport loss then the - // target version on reconnect. + // Join the existing install; reconnect and target-version checks prove its handoff. yield* logInfo("remote update commit joining an in-progress install", { requestId: commit.requestId, }); @@ -432,9 +425,7 @@ export const listen: Effect.Effect< } return; } - // A successful install tears down this backend. Do not send a success - // marker from the old process: transport loss followed by the target - // version is the only proof that the handoff succeeded. + // Installation kills this backend; only transport loss followed by the target version proves handoff. }).pipe( Effect.ensuring(clearActiveRequest(commit.requestId)), Effect.catchCause((cause) => diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 2a0d1d4530923..d2f24143fc209 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -2,7 +2,6 @@ import { assert, describe, it } from "@effect/vitest"; import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -22,72 +21,6 @@ import * as DesktopUpdates from "./DesktopUpdates.ts"; import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts"; describe("DesktopUpdates", () => { - it("preserves complete causes for update poller and event failures", () => { - const cause = Cause.combine( - Cause.fail(new Error("updater failed")), - Cause.die(new Error("updater defect")), - ); - const pollerError = new DesktopUpdates.DesktopUpdatePollerError({ - poller: "startup", - cause, - }); - const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({ - event: "download-progress", - cause, - }); - const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({ - operation: "download", - cause, - }); - const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({ - action: "install", - cause, - }); - - assert.strictEqual(pollerError.cause, cause); - assert.equal(pollerError.poller, "startup"); - assert.equal(pollerError.message, "Desktop update startup poller failed."); - assert.strictEqual(eventError.cause, cause); - assert.equal(eventError.event, "download-progress"); - assert.equal(eventError.message, "Failed to handle desktop update download-progress event."); - assert.strictEqual(reportedError.cause, cause); - assert.equal(reportedError.operation, "download"); - assert.equal(reportedError.message, "Desktop updater download operation reported an error."); - assert.strictEqual(unexpectedActionError.cause, cause); - assert.equal(unexpectedActionError.action, "install"); - assert.equal( - unexpectedActionError.message, - "Desktop update install action failed unexpectedly.", - ); - }); - - it.effect("configures the updater and runs startup checks on the test clock", () => { - const harness = makeHarness(); - - return Effect.gen(function* () { - yield* Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - const state = yield* updates.getState; - assert.equal(state.enabled, true); - assert.equal(state.status, "idle"); - assert.deepEqual(harness.feedUrls(), [ - { provider: "generic", url: "http://localhost:4141" }, - ]); - assert.equal(harness.listenerCount(), 6); - assert.equal(harness.checkCount(), 0); - - yield* TestClock.adjust(Duration.millis(15_000)); - assert.equal(harness.checkCount(), 1); - }), - ); - - assert.equal(harness.listenerCount(), 0); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); - it.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () => Effect.gen(function* () { const linuxState = (packageType: string | undefined) => @@ -107,103 +40,27 @@ describe("DesktopUpdates", () => { }), ); - it.effect("subscribe delivers the latest state plus subsequent changes", () => { - const harness = makeHarness(); - - return Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - const { latest, changes } = yield* updates.subscribe; - assert.equal(latest.status, "idle"); - - const nextState = yield* Stream.runHead(changes).pipe(Effect.forkChild); - yield* flushCallbacks; - harness.emit("update-available", { version: "1.2.4" }); - yield* flushCallbacks; - - const observed = yield* Fiber.join(nextState); - assert.equal(Option.getOrThrow(observed).status, "available"); - assert.equal(Option.getOrThrow(observed).availableVersion, "1.2.4"); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); - - it.effect("updates and broadcasts state from updater events", () => { - const harness = makeHarness(); - - return Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - harness.emit("update-available", { version: "1.2.4" }); - yield* flushCallbacks; - - const state = yield* updates.getState; - assert.equal(state.status, "available"); - assert.equal(state.availableVersion, "1.2.4"); - assert.isNotNull(state.checkedAt); - assert.equal(harness.sentStates.at(-1)?.status, "available"); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); - - it.effect("enables nightly full changelog release notes and broadcasts summaries", () => { - const harness = makeHarness(); + it.effect("keeps the disabled reason available after configuration and channel changes", () => { + const harness = makeHarness({ env: { T3CODE_DISABLE_AUTO_UPDATE: "true" } }); + const reason = "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting."; return Effect.scoped( Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; yield* updates.configure; - yield* updates.setChannel("nightly"); - assert.equal(harness.fullChangelog(), true); + const configured = yield* updates.getState; + assert.equal(configured.message, reason); - harness.emit("update-available", { - version: "1.2.4-nightly.20260709.766", - releaseNotes: [ - { - version: "1.2.4-nightly.20260709.766", - note: `

What's Changed

Full Changelog

`, - }, - { - version: "1.2.4-nightly.20260709.765", - note: "- [codex] Upgrade Clerk stack by @juliusmarminge in #3821", - }, - { version: "1.2.4-nightly.20260709.764", note: "- Change 764" }, - { version: "1.2.4-nightly.20260709.763", note: "- Change 763" }, - { version: "1.2.4-nightly.20260709.762", note: "- Change 762" }, - { version: "1.2.4-nightly.20260709.761", note: "- Change 761" }, - { version: "1.2.4-nightly.20260709.760", note: "- Change 760" }, - ], - }); - yield* flushCallbacks; - - const state = yield* updates.getState; - assert.equal(state.status, "available"); - assert.deepEqual(state.releaseNotes, [ - { - version: "1.2.4-nightly.20260709.766", - items: ["feat(client): persist offline environment data by @juliusmarminge in #3795"], - totalItems: 1, - }, - { - version: "1.2.4-nightly.20260709.765", - items: ["[codex] Upgrade Clerk stack by @juliusmarminge in #3821"], - totalItems: 1, - }, - { version: "1.2.4-nightly.20260709.764", items: ["Change 764"], totalItems: 1 }, - { version: "1.2.4-nightly.20260709.763", items: ["Change 763"], totalItems: 1 }, - { version: "1.2.4-nightly.20260709.762", items: ["Change 762"], totalItems: 1 }, - { version: "1.2.4-nightly.20260709.761", items: ["Change 761"], totalItems: 1 }, - ]); - assert.equal(state.omittedReleaseCount, 1); - assert.deepEqual(harness.sentStates.at(-1)?.releaseNotes, state.releaseNotes); - assert.equal(harness.sentStates.at(-1)?.omittedReleaseCount, 1); + const changed = yield* updates.setChannel("nightly"); + assert.equal(changed.channel, "nightly"); + assert.equal(changed.enabled, false); + assert.equal(changed.status, "disabled"); + assert.equal(changed.message, reason); + assert.equal(harness.sentStates.at(-1)?.message, reason); + assert.equal(harness.checkCount(), 0); }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + ).pipe(Effect.provide(harness.layer)); }); it.effect("checks for newer releases after an update has been downloaded", () => { @@ -283,39 +140,6 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); - it.effect("preserves a queued installer when the feed offers another channel", () => { - const harness = makeHarness(); - - return Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - harness.emit("update-available", { - version: "1.2.4", - releaseNotes: "## What's changed\n- fix: queued update", - }); - yield* flushCallbacks; - harness.emit("update-downloaded", { version: "1.2.4" }); - yield* flushCallbacks; - - yield* updates.check("poll"); - harness.emit("update-available", { version: "1.2.5-nightly.20260710.1" }); - yield* flushCallbacks; - - const state = yield* updates.getState; - assert.equal(state.status, "downloaded"); - assert.equal(state.availableVersion, "1.2.4"); - assert.equal(state.downloadedVersion, "1.2.4"); - assert.deepEqual(state.releaseNotes, [ - { version: "1.2.4", items: ["fix: queued update"], totalItems: 1 }, - ]); - assert.equal(state.omittedReleaseCount, 0); - assert.equal(state.downloadPercent, 100); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); - it.effect( "rejects install while a refresh check is in progress and releases the reservation", () => @@ -385,28 +209,6 @@ describe("DesktopUpdates", () => { }), ); - it.effect("keeps raw updater event failures out of update state", () => { - const harness = makeHarness(); - const cause = new Error( - "request failed for https://user:secret@example.com/update?token=secret", - ); - - return Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - harness.emit("error", cause); - yield* flushCallbacks; - - const state = yield* updates.getState; - assert.equal(state.status, "error"); - assert.equal(state.message, "Desktop updater background operation reported an error."); - assert.notInclude(state.message ?? "", "secret"); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); - it.effect("preserves a queued installer after a background updater error", () => { const harness = makeHarness(); @@ -484,49 +286,6 @@ describe("DesktopUpdates", () => { ); }); - it.effect("logs the redacted cause of an updater error event", () => { - const harness = makeHarness(); - const cause = Object.assign(new Error("404 Not Found\nHeaders: authorization=secret"), { - code: "ERR_UPDATER_CHANNEL_FILE_NOT_FOUND", - }); - const loggedAnnotations: Array> = []; - const logger = Logger.make(({ fiber }) => { - const annotations = fiber.getRef(References.CurrentLogAnnotations); - if (annotations.errorTag === "DesktopUpdaterReportedError") { - loggedAnnotations.push(annotations); - } - }); - - return Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - harness.emit("error", cause); - yield* flushCallbacks; - - const loggedAnnotation = loggedAnnotations.at(-1); - assert.isDefined(loggedAnnotation); - assert.equal(loggedAnnotation.operation, "background"); - assert.equal( - loggedAnnotation.cause, - "Error [ERR_UPDATER_CHANNEL_FILE_NOT_FOUND]: 404 Not Found", - ); - assert.notInclude(JSON.stringify(loggedAnnotations), "secret"); - const state = yield* updates.getState; - assert.equal(state.message, "Desktop updater background operation reported an error."); - }), - ).pipe( - Effect.provide( - Layer.mergeAll( - TestClock.layer(), - harness.layer, - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - ); - }); - it.effect("recovers download state after an unexpected setup failure", () => { let disableDifferentialCalls = 0; const harness = makeHarness({ @@ -698,6 +457,7 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + // regression: #19291 an install that did apply was still flagged as not applied it.effect("does not flag an install that applied", () => { const harness = makeHarness({ installRecord: JSON.stringify({ fromVersion: "1.2.2", targetVersion: "1.2.3" }), @@ -898,29 +658,6 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); - it.effect("recovers when quitAndInstall reports failure through an updater event", () => { - const harness = makeHarness(); - - return Effect.scoped( - Effect.gen(function* () { - const desktopState = yield* DesktopState.DesktopState; - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - harness.emit("update-downloaded", { version: "1.2.4" }); - yield* flushCallbacks; - - yield* updates.install; - assert.deepEqual(harness.installSteps, ["quitAndInstall"]); - harness.emit("error", new Error("native installer refused")); - yield* flushCallbacks; - - assert.isFalse(yield* Ref.get(desktopState.quitting)); - assert.deepEqual(harness.installSteps, ["quitAndInstall", "startBackend"]); - assert.equal((yield* updates.getState).errorContext, "install"); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); - it.effect("rejects a prepared install when the downloaded version changed", () => { const harness = makeHarness(); @@ -976,40 +713,6 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); - it.effect("fails channel changes with a typed error while a check is in progress", () => - Effect.gen(function* () { - const checkStarted = yield* Deferred.make(); - const releaseCheck = yield* Deferred.make(); - const harness = makeHarness({ - checkForUpdates: Deferred.succeed(checkStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseCheck)), - ), - }); - - yield* Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - const checkFiber = yield* updates.check("manual").pipe(Effect.forkScoped); - yield* Deferred.await(checkStarted); - - const exit = yield* Effect.exit(updates.setChannel("nightly")); - assert.equal(exit._tag, "Failure"); - if (exit._tag === "Failure") { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError); - assert.equal(error.action, "check"); - assert.equal(error.requestedChannel, "nightly"); - } - - yield* Deferred.succeed(releaseCheck, undefined); - yield* Fiber.join(checkFiber); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }), - ); - it.effect("rejects checks while an update channel change is being persisted", () => Effect.gen(function* () { const channelChangeStarted = yield* Deferred.make(); @@ -1041,52 +744,9 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }), ); - - it.effect("preserves settings failure context when an update channel cannot be persisted", () => { - const diskFailure = new Error("disk exploded"); - const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({ - operation: "replace-settings-file", - path: "/tmp/settings.json", - cause: diskFailure, - }); - const harness = makeHarness({ setUpdateChannelError: settingsFailure }); - - return Effect.scoped( - Effect.gen(function* () { - const updates = yield* DesktopUpdates.DesktopUpdates; - yield* updates.configure; - - const error = yield* updates.setChannel("nightly").pipe(Effect.flip); - - assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError); - assert.equal(error.channel, "nightly"); - assert.strictEqual(error.cause, settingsFailure); - assert.strictEqual(error.cause.cause, diskFailure); - assert.equal(error.message, "Failed to persist the nightly desktop update channel."); - assert.notInclude(error.message, diskFailure.message); - - const checkResult = yield* updates.check("manual"); - assert.isTrue(checkResult.checked); - assert.equal(harness.checkCount(), 1); - }), - ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); - }); }); describe("describeUpdateErrorCause", () => { - it("preserves network and nested failure reasons", () => { - const networkError = Object.assign(new Error("getaddrinfo ENOTFOUND updates.example.com"), { - code: "ENOTFOUND", - }); - const cause = new Error("fetch failed", { cause: networkError }); - - assert.equal( - DesktopUpdates.describeUpdateErrorCause(Cause.fail(cause)), - "Error: fetch failed; caused by Error [ENOTFOUND]: getaddrinfo ENOTFOUND updates.example.com", - ); - assert.include(DesktopUpdates.describeUpdateErrorCause(Cause.die(networkError)), "[ENOTFOUND]"); - }); - it("removes URLs, credentials, response bodies, and headers from summaries", () => { const messages = [ "Cannot download https://user:url-secret@example.com/update?token=query-secret, status 403", diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index b2d93f407ac76..5265d65523ba2 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -64,9 +64,7 @@ type AppUpdateYmlConfig = typeof AppUpdateYmlConfig.Type; const UpdateInfo = Schema.Struct({ version: Schema.String, - // Left unvalidated on purpose: a malformed release-notes payload must never - // fail the decode and block the update state transition. The shape is - // validated defensively in normalizeDesktopUpdateReleaseNotes. + // Malformed notes must not block update-state decoding; normalizeDesktopUpdateReleaseNotes validates separately. releaseNotes: Schema.optional(Schema.Unknown), }); @@ -273,13 +271,15 @@ function parseAppUpdateYml(raw: string): Effect.Effect, environment: DesktopEnvironment.DesktopEnvironment["Service"], ): DesktopUpdateState { + const enabled = Option.isNone(disabledReason); return { ...createInitialDesktopUpdateState(environment.appVersion, environment.runtimeInfo, channel), enabled, status: enabled ? "idle" : "disabled", + message: Option.getOrNull(disabledReason), }; } @@ -333,7 +333,7 @@ function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64"; } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const config = yield* DesktopConfig.DesktopConfig; const pool = yield* DesktopBackendPool.DesktopBackendPool; @@ -362,8 +362,7 @@ export const make = Effect.gen(function* () { ); const stateChanges = yield* PubSub.sliding(16); - // Makes ref writes + publishes atomic against subscribe, so a snapshot - // never overlaps with the first change a subscriber receives. + // Serialize writes and publishes against subscription so snapshots cannot overlap the first change. const stateMutex = yield* Semaphore.make(1); const emitState = Ref.get(updateStateRef).pipe( @@ -397,8 +396,7 @@ export const make = Effect.gen(function* () { ), ); - // The .deb carries electron-builder's resources/package-type marker. - // electron-updater reads the same file and installs updates with dpkg. + // electron-updater uses this marker to install .deb updates with dpkg. const isDebPackage = environment.platform === "linux" && environment.isPackaged ? yield* fileSystem @@ -468,8 +466,6 @@ export const make = Effect.gen(function* () { }); }); - const shouldEnableAutoUpdates = resolveDisabledReason.pipe(Effect.map(Option.isNone)); - const checkForUpdates = Effect.fn("desktop.updates.checkForUpdates")(function* ( reason: string, actionReservation: "acquire" | "held" = "acquire", @@ -597,8 +593,7 @@ export const make = Effect.gen(function* () { ), ); - // A failed or interrupted install brings no updated backend, so a later - // quit must release the tunnel. + // Failed or interrupted installs leave no replacement backend; later quits must release the tunnel. const removeUpdateRestartMarker = fileSystem .remove(updateRestartMarkerPath, { force: true }) .pipe(Effect.ignore); @@ -631,10 +626,10 @@ export const make = Effect.gen(function* () { ), ); - const baseUpdateState = (channel: DesktopUpdateChannel, enabled: boolean) => + const baseUpdateState = (channel: DesktopUpdateChannel, disabledReason: Option.Option) => Ref.get(notAppliedVersionRef).pipe( Effect.map((notAppliedVersion) => ({ - ...createBaseUpdateState(channel, enabled, environment), + ...createBaseUpdateState(channel, disabledReason, environment), ...Option.match(notAppliedVersion, { onNone: () => ({}), onSome: (version) => ({ notAppliedVersion: version }), @@ -742,11 +737,7 @@ export const make = Effect.gen(function* () { yield* writeUpdateRestartMarker; const { downloadedVersion } = yield* Ref.get(updateStateRef); if (downloadedVersion !== null) yield* writeInstallRecord(downloadedVersion); - // Stop every backend in the pool, not just the primary. With parallel - // WSL + Windows backends, leaving the WSL instance up means - // quitAndInstall's app.quit() exits before the pool's scope cascade - // has a chance to run its stop finalizer, so the WSL child gets - // hard-killed by the OS instead of receiving SIGTERM + grace. + // Stop pooled backends before quitAndInstall can outrun their scope finalizers. const instances = yield* pool.list; // stop clears desiredRunning, so retain the recovery set beforehand. const runningInstances = yield* Effect.filter(instances, (instance) => @@ -1056,9 +1047,9 @@ export const make = Effect.gen(function* () { } const settings = yield* desktopSettings.get; - const enabled = yield* shouldEnableAutoUpdates; - yield* setState(yield* baseUpdateState(settings.updateChannel, enabled)); - if (!enabled) { + const disabledReason = yield* resolveDisabledReason; + yield* setState(yield* baseUpdateState(settings.updateChannel, disabledReason)); + if (Option.isSome(disabledReason)) { return; } yield* Ref.set(updaterConfiguredRef, true); @@ -1127,10 +1118,10 @@ export const make = Effect.gen(function* () { ), ); - const enabled = yield* shouldEnableAutoUpdates; - yield* setState(yield* baseUpdateState(nextChannel, enabled)); + const disabledReason = yield* resolveDisabledReason; + yield* setState(yield* baseUpdateState(nextChannel, disabledReason)); - if (!enabled || !(yield* Ref.get(updaterConfiguredRef))) { + if (Option.isSome(disabledReason) || !(yield* Ref.get(updaterConfiguredRef))) { return yield* Ref.get(updateStateRef); } diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts index 57d185c0975e9..028e42fa6e3b7 100644 --- a/apps/desktop/src/updates/releaseNotes.test.ts +++ b/apps/desktop/src/updates/releaseNotes.test.ts @@ -80,29 +80,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { ]); }); - it("keeps per-version order and drops empty groups", () => { - const result = normalizeDesktopUpdateReleaseNotes( - [ - { version: "1.2.3", note: "- Newer release" }, - { version: "1.2.2", note: "Full changelog: https://example.com/compare/x...y" }, - { version: "1.2.1", note: "- Older release" }, - ], - "1.2.3", - "latest", - ); - - expect(result).toEqual({ - releaseNotes: [ - { version: "1.2.3", items: ["Newer release"], totalItems: 1 }, - { version: "1.2.1", items: ["Older release"], totalItems: 1 }, - ], - omittedReleaseCount: 0, - }); - }); - it("drops releases from other trains before grouping on nightly", () => { - // electron-updater's full changelog is "every version above the running - // one", and preview sorts above nightly, so the preview cuts come first. const releaseNotes = [ { version: "0.0.41-preview.20260914.1683", note: "- Maintainer test build" }, { version: "0.0.41-preview.20260913.1669", note: "- Maintainer test build" }, @@ -123,6 +101,7 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { expect(result.omittedReleaseCount).toBe(0); }); + // regression: #11753 prerelease entries leaked into a channel's update changelog it("keeps only stable releases on the latest channel", () => { const result = normalizeDesktopUpdateReleaseNotes( [ @@ -161,18 +140,6 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { expect(result.omittedReleaseCount).toBe(1); }); - it("decodes valid HTML entities", () => { - const result = normalizeDesktopUpdateReleaseNotes( - "- Fix & polish 😀", - "1.0.0", - "latest", - ); - expect(result).toEqual({ - releaseNotes: [{ version: "1.0.0", items: ["Fix & polish 😀"], totalItems: 1 }], - omittedReleaseCount: 0, - }); - }); - it("ignores malformed and empty entries instead of throwing", () => { const result = normalizeDesktopUpdateReleaseNotes( [ @@ -193,13 +160,6 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { }); }); - it("returns an empty result for an invalid payload", () => { - expect(normalizeDesktopUpdateReleaseNotes({ note: "- Invalid" }, "1.0.0", "latest")).toEqual({ - releaseNotes: [], - omittedReleaseCount: 0, - }); - }); - it("does not throw on out-of-range numeric entities and keeps the literal", () => { const result = normalizeDesktopUpdateReleaseNotes( "- Broken entity �", diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index ef6d217299d09..69d710ff7b269 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -30,8 +30,6 @@ const HTML_ENTITY_REPLACEMENTS: Readonly> = { }; function decodeCodePoint(codePoint: number, entity: string): string { - // String.fromCodePoint throws RangeError outside the valid Unicode range, and - // Number.isFinite alone lets oversized values (e.g. �) through. if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) { return `&${entity};`; } @@ -124,12 +122,7 @@ interface NormalizedDesktopUpdateReleaseNotes { readonly omittedReleaseCount: number; } -/** - * With `fullChangelog` on (nightly), electron-updater collects every GitHub - * release whose version is semver-greater than the running one, whatever train - * it belongs to; a maintainers' `-preview.` cut sorts above every `-nightly.` - * of the same base version and would lead the list. - */ +/** fullChangelog includes all greater semvers, so preview cuts sort above nightlies of the same base version. */ export function normalizeDesktopUpdateReleaseNotes( releaseNotes: unknown, fallbackVersion: string, diff --git a/apps/desktop/src/updates/remoteUpdateFlow.test.ts b/apps/desktop/src/updates/remoteUpdateFlow.test.ts index d7afeafab879e..5247931221f0b 100644 --- a/apps/desktop/src/updates/remoteUpdateFlow.test.ts +++ b/apps/desktop/src/updates/remoteUpdateFlow.test.ts @@ -2,10 +2,8 @@ import { assert, describe, it } from "@effect/vitest"; import type { DesktopUpdateState } from "@t3tools/contracts"; import { - MAX_REMOTE_UPDATE_CHECKS, MAX_REMOTE_UPDATE_DOWNLOADS, nextRemoteDesktopUpdateStep, - normalizeRemoteUpdateReason, type RemoteDesktopUpdateAttempts, } from "./remoteUpdateFlow.ts"; @@ -117,23 +115,6 @@ describe("nextRemoteDesktopUpdateStep", () => { }); }); - it("rides along while a check or download is already in flight", () => { - assert.deepEqual( - nextRemoteDesktopUpdateStep(makeState({ status: "checking" }), NO_ATTEMPTS, null), - { - action: "wait", - }, - ); - assert.deepEqual( - nextRemoteDesktopUpdateStep( - makeState({ status: "downloading", availableVersion: "1.2.4", downloadPercent: 40 }), - NO_ATTEMPTS, - null, - ), - { action: "wait" }, - ); - }); - it("downloads an available update until the attempt cap, then fails", () => { const available = makeState({ status: "available", availableVersion: "1.2.4" }); assert.deepEqual(nextRemoteDesktopUpdateStep(available, NO_ATTEMPTS, null), { @@ -200,29 +181,4 @@ describe("nextRemoteDesktopUpdateStep", () => { reason: "The desktop app update failed.", }); }); - - it("checks from idle until the attempt cap, then fails", () => { - assert.deepEqual(nextRemoteDesktopUpdateStep(makeState(), NO_ATTEMPTS, null), { - action: "check", - }); - assert.deepEqual( - nextRemoteDesktopUpdateStep( - makeState(), - { checks: MAX_REMOTE_UPDATE_CHECKS, downloads: 0 }, - null, - ), - { - action: "done", - outcome: "failed", - reason: "The desktop app did not report an update result.", - }, - ); - }); - - it("drops blank reasons so the wire report still encodes", () => { - assert.equal(normalizeRemoteUpdateReason(undefined), undefined); - assert.equal(normalizeRemoteUpdateReason(""), undefined); - assert.equal(normalizeRemoteUpdateReason(" "), undefined); - assert.equal(normalizeRemoteUpdateReason(" feed unreachable "), "feed unreachable"); - }); }); diff --git a/apps/desktop/src/updates/remoteUpdateFlow.ts b/apps/desktop/src/updates/remoteUpdateFlow.ts index 91fb45fee3a42..1d9588315559c 100644 --- a/apps/desktop/src/updates/remoteUpdateFlow.ts +++ b/apps/desktop/src/updates/remoteUpdateFlow.ts @@ -11,18 +11,13 @@ export type RemoteDesktopUpdateStep = readonly reason?: string; }; -/** - * The caps are what stop a check -> up-to-date -> check loop and endless - * download retries; they are counts rather than booleans because a state event - * raced by the local 4-minute poller can re-show an already-handled status - * once. - */ +/** Bound retries with counts: background poller races can repeat an already-handled status once. */ export interface RemoteDesktopUpdateAttempts { readonly checks: number; readonly downloads: number; } -export const MAX_REMOTE_UPDATE_CHECKS = 2; +const MAX_REMOTE_UPDATE_CHECKS = 2; export const MAX_REMOTE_UPDATE_DOWNLOADS = 3; function isInstallableDesktopUpdateState(state: DesktopUpdateState): boolean { @@ -46,9 +41,7 @@ export function nextRemoteDesktopUpdateStep( reason: disabledReason ?? "Automatic updates are disabled on this machine.", }; } - // An install of this version already failed to apply here. Installing it - // again from afar would stop the app's threads for nothing, so only the user - // on this machine retries it. + // Reinstalling a failed version disrupts threads without updating; retries require the local user. if ( state.notAppliedVersion !== undefined && (state.downloadedVersion ?? state.availableVersion) === state.notAppliedVersion @@ -59,11 +52,7 @@ export function nextRemoteDesktopUpdateStep( reason: `Update ${state.notAppliedVersion} did not apply on this machine. Retry it from the desktop app there.`, }; } - // Mirror installDownloadedUpdate's own admission rule exactly, so the run - // never reports an install that the updater then refuses. A download - // survives an unrelated background updater error (errorContext null) and - // a previous failed install (errorContext "install"); it does not survive - // a check or download error, which fall through to the error branch. + // Match install admission, including retained downloads after unrelated background or earlier install errors. if (isInstallableDesktopUpdateState(state)) { return { action: "install" }; } @@ -80,9 +69,7 @@ export function nextRemoteDesktopUpdateStep( } return { action: "download" }; } - // "up-to-date" and "error" are retained from earlier/background checks, - // so before this run has issued its own check they are stale, not - // terminal: the whole point of a remote request is to look again. + // Background up-to-date/error states are stale until this request has issued its own check. if (state.status === "up-to-date") { if (attempts.checks === 0) { return { action: "check" }; @@ -109,11 +96,7 @@ export function nextRemoteDesktopUpdateStep( return { action: "check" }; } -/** - * Updater messages are plain strings and may be blank; a blank reason would - * fail encoding and silently drop the terminal report, leaving the server to - * wait for its timeout. - */ +/** Blank reasons fail encoding and drop the terminal report, forcing the server to time out. */ export function normalizeRemoteUpdateReason(reason: string | undefined): string | undefined { const trimmed = reason?.trim(); return trimmed ? trimmed : undefined; diff --git a/apps/desktop/src/updates/updateChannels.test.ts b/apps/desktop/src/updates/updateChannels.test.ts deleted file mode 100644 index acf4155fab8e3..0000000000000 --- a/apps/desktop/src/updates/updateChannels.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; - -import { isNightlyDesktopVersion, resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts"; - -describe("updateChannels", () => { - it("keeps preview builds branded as nightly but on the latest update channel", () => { - expect(isNightlyDesktopVersion("0.0.41-preview.20260911.7")).toBe(true); - expect(resolveDefaultDesktopUpdateChannel("0.0.41-preview.20260911.7")).toBe("latest"); - expect(resolveDefaultDesktopUpdateChannel("0.0.41-nightly.20260911.7")).toBe("nightly"); - }); - - it("only matches the first prerelease identifier", () => { - expect(isNightlyDesktopVersion("1.2.3-foo-preview.20260911.1")).toBe(false); - expect(isNightlyDesktopVersion("1.2.3")).toBe(false); - }); -}); diff --git a/apps/desktop/src/updates/updateChannels.ts b/apps/desktop/src/updates/updateChannels.ts index 1b1a1ec1efa99..d79a374a668a5 100644 --- a/apps/desktop/src/updates/updateChannels.ts +++ b/apps/desktop/src/updates/updateChannels.ts @@ -1,10 +1,7 @@ import type { DesktopUpdateChannel } from "@t3tools/contracts"; const NIGHTLY_VERSION_PATTERN = /^[^-+]+-nightly\.\d{8}\.\d+$/; -// They share nightly's branding but are packaged without an update feed (see -// isDesktopPreviewVersion in scripts/build-desktop-artifact.ts), so the channel -// a preview install reports is cosmetic: it never checks for updates and no -// updater feed ever lists a preview release. +// Preview builds share nightly branding but ship without an update feed. const PRERELEASE_VERSION_PATTERN = /^[^-+]+-(?:nightly|preview)\.\d{8}\.\d+$/; export function isNightlyDesktopVersion(version: string): boolean { diff --git a/apps/desktop/src/updates/updateMachine.test.ts b/apps/desktop/src/updates/updateMachine.test.ts index de57e0a8e2c70..03e864b93d271 100644 --- a/apps/desktop/src/updates/updateMachine.test.ts +++ b/apps/desktop/src/updates/updateMachine.test.ts @@ -6,12 +6,8 @@ import { reduceDesktopUpdateStateOnCheckStart, reduceDesktopUpdateStateOnDownloadComplete, reduceDesktopUpdateStateOnDownloadFailure, - reduceDesktopUpdateStateOnDownloadProgress, - reduceDesktopUpdateStateOnDownloadStart, reduceDesktopUpdateStateOnInstallFailure, reduceDesktopUpdateStateOnNoUpdate, - reduceDesktopUpdateStateOnUpdateAvailable, - resolveNotAppliedInstallVersion, } from "./updateMachine.ts"; const runtimeInfo = { @@ -21,41 +17,6 @@ const runtimeInfo = { } as const; describe("updateMachine", () => { - it("clears transient errors when a check starts", () => { - const state = reduceDesktopUpdateStateOnCheckStart( - { - ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"), - enabled: true, - status: "error", - message: "network", - errorContext: "check", - canRetry: true, - }, - "2026-03-04T00:00:00.000Z", - ); - - expect(state.status).toBe("checking"); - expect(state.message).toBeNull(); - expect(state.errorContext).toBeNull(); - expect(state.canRetry).toBe(false); - }); - - it("records a check failure without exposing an action", () => { - const state = reduceDesktopUpdateStateOnCheckFailure( - { - ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"), - enabled: true, - status: "checking", - }, - "network unavailable", - "2026-03-04T00:00:00.000Z", - ); - - expect(state.status).toBe("error"); - expect(state.errorContext).toBe("check"); - expect(state.canRetry).toBe(true); - }); - it("preserves an already-downloaded update while checking the feed", () => { const downloadedState = { ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"), @@ -88,30 +49,6 @@ describe("updateMachine", () => { expect(failed.message).toBeNull(); }); - it("keeps the installer when the feed still offers its version", () => { - const releaseNotes = [{ version: "1.1.0", items: ["fix: queued update"], totalItems: 1 }]; - const state = reduceDesktopUpdateStateOnUpdateAvailable( - { - ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"), - enabled: true, - status: "downloaded", - availableVersion: "1.1.0", - downloadedVersion: "1.1.0", - releaseNotes, - omittedReleaseCount: 2, - downloadPercent: 100, - }, - "1.1.0", - "2026-03-04T00:00:00.000Z", - ); - - expect(state.status).toBe("downloaded"); - expect(state.downloadedVersion).toBe("1.1.0"); - expect(state.releaseNotes).toEqual(releaseNotes); - expect(state.omittedReleaseCount).toBe(2); - expect(state.downloadPercent).toBe(100); - }); - it("preserves available version on download failure for retry", () => { const state = reduceDesktopUpdateStateOnDownloadFailure( { @@ -152,35 +89,6 @@ describe("updateMachine", () => { expect(failedInstall.canRetry).toBe(true); }); - it("preserves a downloaded update when no update is available", () => { - const releaseNotes = [{ version: "1.1.0", items: ["fix: queued update"], totalItems: 1 }]; - const state = reduceDesktopUpdateStateOnNoUpdate( - { - ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"), - enabled: true, - status: "error", - availableVersion: "1.1.0", - downloadedVersion: "1.1.0", - releaseNotes, - omittedReleaseCount: 2, - message: "old failure", - errorContext: "download", - canRetry: true, - }, - "2026-03-04T00:00:00.000Z", - ); - - expect(state.status).toBe("downloaded"); - expect(state.availableVersion).toBe("1.1.0"); - expect(state.downloadedVersion).toBe("1.1.0"); - expect(state.releaseNotes).toBe(releaseNotes); - expect(state.omittedReleaseCount).toBe(2); - expect(state.downloadPercent).toBe(100); - expect(state.message).toBeNull(); - expect(state.errorContext).toBeNull(); - expect(state.canRetry).toBe(true); - }); - it("clears stale available state when no update is available", () => { const state = reduceDesktopUpdateStateOnNoUpdate( { @@ -205,67 +113,4 @@ describe("updateMachine", () => { expect(state.message).toBeNull(); expect(state.errorContext).toBeNull(); }); - - it("tracks available, download start, and progress cleanly", () => { - const releaseNotes = [ - { - version: "1.1.0", - items: ["feat: add update release notes"], - totalItems: 1, - }, - ]; - const available = reduceDesktopUpdateStateOnUpdateAvailable( - { - ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"), - enabled: true, - status: "checking", - }, - "1.1.0", - "2026-03-04T00:00:00.000Z", - releaseNotes, - 2, - ); - const downloading = reduceDesktopUpdateStateOnDownloadStart(available); - const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5); - - expect(available.status).toBe("available"); - expect(available.channel).toBe("latest"); - expect(available.releaseNotes).toBe(releaseNotes); - expect(available.omittedReleaseCount).toBe(2); - expect(downloading.releaseNotes).toBe(releaseNotes); - expect(downloading.status).toBe("downloading"); - expect(downloading.downloadPercent).toBe(0); - expect(progress.downloadPercent).toBe(55.5); - expect(progress.errorContext).toBeNull(); - }); - - it("clears release notes when checking again", () => { - const state = reduceDesktopUpdateStateOnCheckStart( - { - ...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "nightly"), - enabled: true, - status: "available", - availableVersion: "1.1.0-nightly.1", - releaseNotes: [{ version: "1.1.0-nightly.1", items: ["feat: old note"], totalItems: 1 }], - omittedReleaseCount: 2, - }, - "2026-03-04T00:00:00.000Z", - ); - - expect(state.releaseNotes).toEqual([]); - expect(state.omittedReleaseCount).toBe(0); - }); -}); - -describe("resolveNotAppliedInstallVersion", () => { - const record = { fromVersion: "1.2.3", targetVersion: "1.2.4" }; - - it("flags the target when the app came back on the version it installed from", () => { - expect(resolveNotAppliedInstallVersion(record, "1.2.3")).toBe("1.2.4"); - }); - - it("stays quiet when the install applied or the app runs another version", () => { - expect(resolveNotAppliedInstallVersion(record, "1.2.4")).toBeNull(); - expect(resolveNotAppliedInstallVersion(record, "1.2.5")).toBeNull(); - }); }); diff --git a/apps/desktop/src/window/ContextMenuImage.test.ts b/apps/desktop/src/window/ContextMenuImage.test.ts index c5e3194f5bb84..dbc7a47ee910d 100644 --- a/apps/desktop/src/window/ContextMenuImage.test.ts +++ b/apps/desktop/src/window/ContextMenuImage.test.ts @@ -59,22 +59,6 @@ beforeEach(() => { ); }); -it("preserves the clipboard when the context-menu frame is missing", async () => { - await copyContextMenuImage( - contents as unknown as Electron.WebContents, - { ...params, frame: null } as unknown as Electron.ContextMenuParams, - ); - expect(contents.copyImageAt).not.toHaveBeenCalled(); - expect(native.fetch).not.toHaveBeenCalled(); - expect(native.write).not.toHaveBeenCalled(); -}); - -it("keeps native image copying for the main frame", async () => { - await copyImage({ frame: mainFrame }); - expect(contents.copyImageAt).toHaveBeenCalledWith(12, 34); - expect(native.fetch).not.toHaveBeenCalled(); -}); - it.each(["https://example.com/image.png", `data:image/png;base64,${sourcePng.toString("base64")}`])( "copies an iframe image from %s", async (srcURL) => { diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 2b8bea6be9a27..df7e1fd2e85ac 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -129,95 +129,6 @@ const configureMenu = ( ); describe("DesktopApplicationMenu", () => { - it.effect("keeps display branding in the macOS application menu", () => - Effect.gen(function* () { - const selectedAction = yield* Deferred.make(); - const applicationMenuTemplate = - yield* Deferred.make(); - - yield* configureMenu(selectedAction, applicationMenuTemplate, { - platform: "darwin", - appVersion: "0.0.43-nightly.20260929.2428", - }); - - const template = yield* Deferred.await(applicationMenuTemplate); - const applicationMenu = template[0]; - assert.isDefined(applicationMenu); - assert.equal(applicationMenu.label, "T3 Code (Nightly)"); - if (!Array.isArray(applicationMenu.submenu)) { - throw new Error("Expected application menu submenu to be an array."); - } - assert.equal( - applicationMenu.submenu.find((item) => item.role === "about")?.label, - "About T3 Code (Nightly)", - ); - assert.equal( - applicationMenu.submenu.find((item) => item.role === "hide")?.label, - "Hide T3 Code (Nightly)", - ); - assert.equal( - applicationMenu.submenu.find((item) => item.role === "quit")?.label, - "Quit T3 Code (Nightly)", - ); - }), - ); - - it.effect("installs the native menu and routes Settings through DesktopWindow", () => - Effect.gen(function* () { - const selectedAction = yield* Deferred.make(); - const applicationMenuTemplate = - yield* Deferred.make(); - - yield* configureMenu(selectedAction, applicationMenuTemplate); - - const template = yield* Deferred.await(applicationMenuTemplate); - const fileMenu = template.find((item) => item.label === "File"); - assert.isDefined(fileMenu); - if (!Array.isArray(fileMenu.submenu)) { - throw new Error("Expected File menu submenu to be an array."); - } - const settingsItem = fileMenu.submenu.find((item) => item.label === "Settings..."); - assert.isDefined(settingsItem); - const settingsClick = settingsItem.click; - if (typeof settingsClick !== "function") { - throw new Error("Expected Settings menu item to have a click handler."); - } - - settingsClick({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent); - assert.equal(yield* Deferred.await(selectedAction), "open-settings"); - }), - ); - - it.effect("owns Paste as Text and routes it through the renderer", () => - Effect.gen(function* () { - const selectedAction = yield* Deferred.make(); - const applicationMenuTemplate = - yield* Deferred.make(); - - yield* configureMenu(selectedAction, applicationMenuTemplate); - - const template = yield* Deferred.await(applicationMenuTemplate); - const editMenu = template.find((item) => item.label === "Edit"); - assert.isDefined(editMenu); - if (!Array.isArray(editMenu.submenu)) { - throw new Error("Expected Edit menu submenu to be an array."); - } - const pasteAsTextItem = editMenu.submenu.find((item) => item.label === "Paste as Text"); - assert.isDefined(pasteAsTextItem); - assert.equal(pasteAsTextItem.accelerator, "CmdOrCtrl+Shift+V"); - if (typeof pasteAsTextItem.click !== "function") { - throw new Error("Expected Paste as Text menu item to have a click handler."); - } - - pasteAsTextItem.click( - {} as Electron.MenuItem, - {} as Electron.BrowserWindow, - {} as KeyboardEvent, - ); - assert.equal(yield* Deferred.await(selectedAction), "paste-as-text"); - }), - ); - it.effect("leaves the accelerator to Chromium instead of injecting a paste", () => Effect.gen(function* () { const selectedAction = yield* Deferred.make(); @@ -247,13 +158,13 @@ describe("DesktopApplicationMenu", () => { }), ); - it.effect("routes View menu zoom to the main window instead of zoom roles", () => + it.effect("registers macOS command-plus once and routes it through main-window zoom", () => Effect.gen(function* () { const selectedAction = yield* Deferred.make(); const applicationMenuTemplate = yield* Deferred.make(); - yield* configureMenu(selectedAction, applicationMenuTemplate); + yield* configureMenu(selectedAction, applicationMenuTemplate, { platform: "darwin" }); const template = yield* Deferred.await(applicationMenuTemplate); const viewMenu = template.find((item) => item.label === "View"); @@ -268,9 +179,17 @@ describe("DesktopApplicationMenu", () => { ), ); - const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In"); + const shiftedEqual = viewMenu.submenu.filter( + (item) => item.accelerator === "CmdOrCtrl+Shift+=", + ); + assert.lengthOf(shiftedEqual, 1); + assert.lengthOf( + viewMenu.submenu.filter((item) => item.accelerator === "CmdOrCtrl+numadd"), + 1, + ); + const zoomIn = shiftedEqual[0]; assert.isDefined(zoomIn); - assert.equal(zoomIn.accelerator, "CmdOrCtrl+="); + assert.isFalse(zoomIn.visible); if (typeof zoomIn.click !== "function") { throw new Error("Expected Zoom In menu item to have a click handler."); } diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 09808348a0d66..7c70656c1ac4c 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -106,14 +106,13 @@ const handleCheckForUpdatesMenuClick = Effect.gen(function* () { return; } - // The result dialogs need no main window. Opening one before the backend - // answers strands the renderer on a failed auth bootstrap. + // Opening a window before backend confirmation can strand it on failed auth bootstrap. const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.activate; yield* checkForUpdatesFromMenu; }).pipe(Effect.withSpan("desktop.menu.handleCheckForUpdatesClick")); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const electronMenu = yield* ElectronMenu.ElectronMenu; const environment = yield* DesktopEnvironment.DesktopEnvironment; @@ -143,10 +142,7 @@ export const make = Effect.gen(function* () { const settingsClick = () => { runMenuEffect("open-settings", dispatchMenuAction("open-settings")); }; - // Chromium already pastes as plain text for this chord, so the accelerator - // needs nothing from the menu: the composer and the terminal each arm - // themselves from the same keydown. Routing it through the renderer anyway - // lands a second, injected paste and doubles the text. + // Chromium and the renderer already handle this chord; injecting another paste duplicates text. const pasteAsTextClick = ( _item: Electron.MenuItem, _window: Electron.BaseWindow | undefined, @@ -238,11 +234,7 @@ export const make = Effect.gen(function* () { { label: "View", submenu: [ - /* - Not the reload, DevTools or zoom roles: those act on the focused - webContents, so with a browser page focused they reload or zoom - the guest page and the app UI appears stuck. - */ + /* Native reload/DevTools/zoom roles target focused guests; these commands must target the app. */ { label: "Reload", accelerator: "CmdOrCtrl+R", click: mainContentsClick("reload") }, { label: "Force Reload", @@ -263,7 +255,36 @@ export const make = Effect.gen(function* () { visible: false, click: zoomClick("in"), }, + ...(environment.platform === "darwin" + ? [ + { + label: "Zoom In", + accelerator: "CmdOrCtrl+Shift+=", + visible: false, + click: zoomClick("in"), + }, + ] + : []), { label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") }, + // Keypad codes do not match number-row accelerators. + { + label: "Actual Size", + accelerator: "CmdOrCtrl+num0", + visible: false, + click: zoomClick("reset"), + }, + { + label: "Zoom In", + accelerator: "CmdOrCtrl+numadd", + visible: false, + click: zoomClick("in"), + }, + { + label: "Zoom Out", + accelerator: "CmdOrCtrl+numsub", + visible: false, + click: zoomClick("out"), + }, { type: "separator" }, { role: "togglefullscreen" }, ], diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 8f8b8d4077743..8b6ab7c7d8a5e 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -3,18 +3,16 @@ import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import { DesktopSnapShotId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; -import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as References from "effect/References"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; import * as Electron from "electron"; -import * as NodeEvents from "node:events"; import { vi } from "vite-plus/test"; vi.mock("electron", async (importOriginal) => ({ @@ -47,12 +45,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; -import { - MENU_ACTION_CHANNEL, - SNAP_SHOT_EVENT_CHANNEL, - TRACKPAD_SCROLL_END_CHANNEL, - WINDOW_FULLSCREEN_STATE_CHANNEL, -} from "../ipc/channels.ts"; +import { SNAP_SHOT_EVENT_CHANNEL } from "../ipc/channels.ts"; import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; import * as DesktopWindow from "./DesktopWindow.ts"; import * as PreviewManager from "../preview/Manager.ts"; @@ -227,6 +220,9 @@ function layerTest(input: { readonly beforeMainWindowBoundsUpdate?: ( bounds: DesktopAppSettings.DesktopWindowBounds, ) => Effect.Effect; + readonly setPreviewMainWindow?: (window: Electron.BrowserWindow) => Effect.Effect; + readonly destroyAll?: Effect.Effect; + readonly onWindowCreate?: Effect.Effect; readonly openedExternalUrls?: unknown[]; readonly copiedTexts?: string[]; readonly onPopupTemplate?: (input: ElectronMenu.ElectronMenuTemplateInput) => Effect.Effect; @@ -275,6 +271,7 @@ function layerTest(input: { input.createdWindowOptions?.push(options); }).pipe( Effect.andThen(Ref.update(input.createCount, (count) => count + 1)), + Effect.andThen(input.onWindowCreate ?? Effect.void), Effect.as(input.window), ), main: Ref.get(input.mainWindow), @@ -288,7 +285,7 @@ function layerTest(input: { prepareReveal: () => Effect.succeed(false), reveal: (window) => Effect.sync(() => input.onReveal?.(window)), sendAll: () => Effect.void, - destroyAll: Effect.void, + destroyAll: input.destroyAll ?? Effect.void, syncAllAppearance: (sync) => sync(input.window), } satisfies ElectronWindow.ElectronWindow["Service"]); @@ -333,7 +330,7 @@ function layerTest(input: { }), Layer.mock(PreviewManager.PreviewManager)({ getBrowserSession: () => Effect.succeed({} as Electron.Session), - setMainWindow: () => Effect.void, + setMainWindow: input.setPreviewMainWindow ?? (() => Effect.void), prepareWebview: () => Effect.void, isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"), getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"), @@ -344,6 +341,7 @@ function layerTest(input: { }), ), ), + Layer.merge(DesktopState.layer), ); } @@ -425,6 +423,7 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n DesktopAppSettings.layerTest(), layerDesktopClientSettings, layerDesktopServerExposure, + DesktopState.layer, layerElectronApp, layerElectronMenu, Layer.succeed(ElectronShell.ElectronShell, { @@ -456,143 +455,6 @@ const captureOne = DesktopSnapShotId.make("11111111-1111-4111-8111-111111111111" const captureTwo = DesktopSnapShotId.make("22222222-2222-4222-8222-222222222222"); describe("DesktopWindow", () => { - it.effect("shows native context menus for browser guests and sign-in popups", () => - Effect.gen(function* () { - const host = makeFakeBrowserWindow(); - const popup = makeFakeBrowserWindow(); - let focusedContents: unknown = host.window.webContents; - const makeContents = () => { - const contents = Object.assign(new NodeEvents.EventEmitter(), { - mainFrame: { - routingId: 7, - isDestroyed: vi.fn(() => false), - } as unknown as Electron.WebFrameMain, - isDestroyed: vi.fn(() => false), - focus: vi.fn(() => { - focusedContents = contents; - }), - copyImageAt: vi.fn(), - replaceMisspelling: vi.fn(), - }); - return contents; - }; - const guest = makeContents(); - const popupContents = makeContents(); - const popupWindow = { ...popup.window, webContents: popupContents }; - const menus = yield* Queue.unbounded<{ - input: ElectronMenu.ElectronMenuTemplateInput; - focusedContents: unknown; - }>(); - const copiedTexts: string[] = []; - const layer = layerTest({ - window: host.window, - createCount: yield* Ref.make(0), - mainWindow: yield* Ref.make>(Option.none()), - copiedTexts, - onPopupTemplate: (input) => - Queue.offer(menus, { input, focusedContents }).pipe(Effect.asVoid), - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - const attach = host.webContentsListeners.get("did-attach-webview"); - assert.isDefined(attach); - attach({}, guest); - attach({}, guest); - guest.emit("did-create-window", popupWindow); - guest.emit("did-create-window", popupWindow); - - for (const [contents, owner] of [ - [guest, host.window], - [popupContents, popupWindow], - ] as const) { - const frame = { routingId: 7 } as Electron.WebFrameMain; - const preventDefault = vi.fn(); - const params = { - frame, - x: 12, - y: 34, - misspelledWord: "helo", - dictionarySuggestions: ["hello"], - linkURL: "", - mediaType: "none", - editFlags: { canCut: false, canCopy: true, canPaste: true, canSelectAll: true }, - }; - focusedContents = host.window.webContents; - contents.emit("context-menu", { preventDefault }, params); - const menu = yield* Queue.take(menus); - assert.strictEqual(menu.input.window, owner); - assert.strictEqual(menu.input.frame, frame); - assert.strictEqual(menu.focusedContents, contents); - assert.equal(preventDefault.mock.calls.length, 1); - assert.deepEqual( - menu.input.template.filter((item) => item.role), - [ - { role: "cut", enabled: false }, - { role: "copy", enabled: true }, - { role: "paste", enabled: true }, - { role: "selectAll", enabled: true }, - ], - ); - const correction = menu.input.template.find((item) => item.label === "hello"); - assert.isDefined(correction?.click); - correction.click({} as Electron.MenuItem, undefined, {} as Electron.KeyboardEvent); - assert.deepEqual(contents.replaceMisspelling.mock.calls, [["hello"]]); - - contents.emit( - "context-menu", - { preventDefault }, - { - ...params, - frame: contents.mainFrame, - misspelledWord: "", - dictionarySuggestions: [], - mediaType: "image", - linkURL: "https://example.com/image.png", - }, - ); - const imageMenu = (yield* Queue.take(menus)).input; - assert.strictEqual(imageMenu.frame, contents.mainFrame); - const copyImage = imageMenu.template.find((item) => item.label === "Copy Image"); - const copyLink = imageMenu.template.find((item) => item.label === "Copy Link"); - assert.isDefined(copyImage?.click); - assert.isDefined(copyLink?.click); - copyImage.click({} as Electron.MenuItem, undefined, {} as Electron.KeyboardEvent); - copyLink.click({} as Electron.MenuItem, undefined, {} as Electron.KeyboardEvent); - assert.deepEqual(contents.copyImageAt.mock.calls, [[12, 34]]); - assert.equal(copiedTexts.at(-1), "https://example.com/image.png"); - - contents.isDestroyed.mockReturnValue(true); - correction.click({} as Electron.MenuItem, undefined, {} as Electron.KeyboardEvent); - copyImage.click({} as Electron.MenuItem, undefined, {} as Electron.KeyboardEvent); - assert.equal(contents.replaceMisspelling.mock.calls.length, 1); - assert.equal(contents.copyImageAt.mock.calls.length, 1); - assert.equal(yield* Queue.size(menus), 0); - } - }).pipe(Effect.provide(layer)); - }), - ); - - it("leaves fullscreen before concealing a pending quit", () => { - const fakeWindow = makeFakeBrowserWindow(); - - DesktopWindow.concealPendingQuitWindow(fakeWindow.window); - assert.deepEqual(fakeWindow.setOpacity.mock.calls, [[0]]); - - fakeWindow.setOpacity.mockClear(); - fakeWindow.isFullScreen.mockReturnValue(true); - DesktopWindow.concealPendingQuitWindow(fakeWindow.window); - assert.deepEqual(fakeWindow.setFullScreen.mock.calls, [[false]]); - assert.deepEqual(fakeWindow.setOpacity.mock.calls, [[0]]); - - fakeWindow.setOpacity.mockClear(); - fakeWindow.isFullScreen.mockReturnValue(false); - fakeWindow.isDestroyed.mockReturnValue(true); - DesktopWindow.concealPendingQuitWindow(fakeWindow.window); - assert.equal(fakeWindow.setOpacity.mock.calls.length, 0); - }); - it("restores bounds only when the window fits within a connected display", () => { const persistedBounds = { x: 2040, y: 80, width: 1320, height: 880 }; const displays = [ @@ -610,60 +472,6 @@ describe("DesktopWindow", () => { ); }); - it("recognizes only same-origin renderer navigations", () => { - assert.isTrue( - DesktopWindow.isSameOriginRendererNavigation({ - applicationUrl: "t3code://app/", - navigationUrl: "t3code://app/settings/connections", - }), - ); - assert.isFalse( - DesktopWindow.isSameOriginRendererNavigation({ - applicationUrl: "t3code://app/", - navigationUrl: "https://accounts.microsoft.com/oauth", - }), - ); - assert.isFalse( - DesktopWindow.isSameOriginRendererNavigation({ - applicationUrl: "t3code://app/", - navigationUrl: "not a url", - }), - ); - }); - - it.effect("does not open a development window until the backend is ready", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = []; - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - createdWindowOptions, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.activate; - assert.equal(yield* Ref.get(createCount), 0); - - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - assert.equal(yield* Ref.get(createCount), 1); - assert.equal(createdWindowOptions[0]?.width, 1100); - assert.equal(createdWindowOptions[0]?.height, 780); - assert.isUndefined(createdWindowOptions[0]?.x); - assert.isUndefined(createdWindowOptions[0]?.y); - assert.isTrue(createdWindowOptions[0]?.disableAutoHideCursor); - assert.isFalse(createdWindowOptions[0]?.webPreferences?.backgroundThrottling); - assert.deepEqual(fakeWindow.setAutoHideCursor.mock.calls, [[false]]); - assert.deepEqual(fakeWindow.loadURL.mock.calls[0], ["t3code-dev://app/"]); - assert.equal(fakeWindow.openDevTools.mock.calls.length, 1); - }).pipe(Effect.provide(layer)); - }), - ); - it.effect( "opens and reopens the window without backend readiness when local execution is disabled", () => @@ -740,36 +548,13 @@ describe("DesktopWindow", () => { }), ); - it.effect("forwards native trackpad release to the renderer", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const send = vi.spyOn(fakeWindow.window.webContents, "send"); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - const onInput = fakeWindow.webContentsListeners.get("input-event"); - if (!onInput) return yield* Effect.die("input-event listener was not registered"); - onInput({}, { type: "gestureScrollUpdate" }); - assert.notInclude( - send.mock.calls.map(([channel]) => channel), - TRACKPAD_SCROLL_END_CHANNEL, - ); - onInput({}, { type: "gestureScrollEnd" }); - assert.isTrue(send.mock.calls.some(([channel]) => channel === TRACKPAD_SCROLL_END_CHANNEL)); - }).pipe(Effect.provide(layer)); - }), - ); - // Chromium hands the main window's zoom level down to embedded preview // guests, so every app zoom has to put the preview browser back at its own // zoom or zooming the UI drags the previewed page with it. - it.effect("restores the preview browser's own zoom after zooming the app", () => + it.effect("zooms main with a focused popup and reapplies preview zoom", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); + const popup = makeFakeBrowserWindow(); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); const previewZoomReapplies: number[] = []; @@ -778,6 +563,7 @@ describe("DesktopWindow", () => { createCount, mainWindow, previewZoomReapplies, + focusedWindow: popup.window, }); yield* Effect.gen(function* () { @@ -794,196 +580,206 @@ describe("DesktopWindow", () => { [-0.5, -1, -0.5, 0], ); assert.deepEqual(previewZoomReapplies, [-0.5, -1, -0.5, 0]); + assert.equal(popup.setZoomLevel.mock.calls.length, 0); }).pipe(Effect.provide(layer)); }), ); - it.effect("reloads and inspects the main window even when a popup has focus", () => + it.effect("zooms the app from Ctrl+wheel like the menu does", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); - const popup = makeFakeBrowserWindow(); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); + const previewZoomReapplies: number[] = []; const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow, - focusedWindow: popup.window, + previewZoomReapplies, }); yield* Effect.gen(function* () { const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - yield* desktopWindow.runMainContentsCommand("reload"); - yield* desktopWindow.runMainContentsCommand("forceReload"); - yield* desktopWindow.runMainContentsCommand("toggleDevTools"); - - assert.equal(fakeWindow.reload.mock.calls.length, 1); - assert.equal(fakeWindow.reloadIgnoringCache.mock.calls.length, 1); - assert.equal(fakeWindow.toggleDevTools.mock.calls.length, 1); - assert.equal(popup.reload.mock.calls.length, 0); - assert.equal(popup.reloadIgnoringCache.mock.calls.length, 0); - assert.equal(popup.toggleDevTools.mock.calls.length, 0); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("keeps macOS window buttons centered when zooming and leaving fullscreen", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow }); + const zoomChanged = fakeWindow.webContentsListeners.get("zoom-changed"); + if (!zoomChanged) return yield* Effect.die("zoom-changed listener was not registered"); + zoomChanged({}, "in"); + zoomChanged({}, "out"); + zoomChanged({}, "out"); - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - for (const direction of ["in", "in", "out", "reset", "out"] as const) { - yield* desktopWindow.zoomMain(direction); - const position = fakeWindow.setWindowButtonPosition.mock.lastCall?.[0]; - assert.isDefined(position); - const headerCenter = 26 * fakeWindow.window.webContents.getZoomFactor(); - assert.isAtMost(Math.abs(position.y + 7 - headerCenter), 0.5); - assert.equal(position.x, 16); - } - - fakeWindow.isFullScreen.mockReturnValue(true); - fakeWindow.setWindowButtonPosition.mockClear(); - yield* desktopWindow.zoomMain("reset"); - assert.equal(fakeWindow.setWindowButtonPosition.mock.calls.length, 0); - - fakeWindow.isFullScreen.mockReturnValue(false); - fakeWindow.windowListeners.get("leave-full-screen")?.(); - assert.deepEqual(fakeWindow.setWindowButtonPosition.mock.lastCall, [{ x: 16, y: 19 }]); + assert.deepEqual( + fakeWindow.setZoomLevel.mock.calls.map(([level]) => level), + [0.5, 0, -0.5], + ); + assert.deepEqual(previewZoomReapplies, [0.5, 0, -0.5]); }).pipe(Effect.provide(layer)); }), ); - it.effect("uses the persisted main window bounds when opening the window", () => + it.effect("reloads and inspects the main window even when a popup has focus", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); + const popup = makeFakeBrowserWindow(); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); - const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = []; const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow, - createdWindowOptions, - desktopSettings: { - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 }, - }, + focusedWindow: popup.window, }); yield* Effect.gen(function* () { const desktopWindow = yield* DesktopWindow.DesktopWindow; yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - assert.equal(createdWindowOptions[0]?.width, 1320); - assert.equal(createdWindowOptions[0]?.height, 880); - assert.equal(createdWindowOptions[0]?.x, 120); - assert.equal(createdWindowOptions[0]?.y, 80); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("restores the persisted maximized state", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - desktopSettings: { - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - mainWindowBounds: { x: 120, y: 80, width: 1320, height: 880 }, - mainWindowMaximized: true, - }, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* desktopWindow.runMainContentsCommand("reload"); + yield* desktopWindow.runMainContentsCommand("forceReload"); + yield* desktopWindow.runMainContentsCommand("toggleDevTools"); - assert.equal(fakeWindow.maximize.mock.calls.length, 0); - const readyToShow = fakeWindow.windowListeners.get("ready-to-show"); - if (!readyToShow) { - return yield* Effect.die("window ready-to-show listener was not registered"); - } - readyToShow(); - assert.equal(fakeWindow.maximize.mock.calls.length, 1); + assert.equal(fakeWindow.reload.mock.calls.length, 1); + assert.equal(fakeWindow.reloadIgnoringCache.mock.calls.length, 1); + assert.equal(fakeWindow.toggleDevTools.mock.calls.length, 1); + assert.equal(popup.reload.mock.calls.length, 0); + assert.equal(popup.reloadIgnoringCache.mock.calls.length, 0); + assert.equal(popup.toggleDevTools.mock.calls.length, 0); }).pipe(Effect.provide(layer)); }), ); - it.effect("re-enables background throttling on first reveal", () => + it.effect("does not open main or splash windows once quitting has started", () => Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); + const fake = makeFakeBrowserWindow(); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - }); - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - assert.equal(fakeWindow.setBackgroundThrottling.mock.calls.length, 0); - const readyToShow = fakeWindow.windowListeners.get("ready-to-show"); - if (!readyToShow) { - return yield* Effect.die("window ready-to-show listener was not registered"); + const windows = yield* DesktopWindow.DesktopWindow; + const state = yield* DesktopState.DesktopState; + yield* Ref.set(state.quitting, true); + + yield* windows.showConnectingSplash; + yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773")); + yield* windows.activate; + yield* windows.dispatchMenuAction("open-settings"); + for (const creation of [ + windows.createMain, + windows.ensureMain, + windows.revealOrCreateMain, + ]) { + assert.isTrue(Exit.isFailure(yield* Effect.exit(creation))); } - readyToShow(); - assert.deepEqual(fakeWindow.setBackgroundThrottling.mock.calls, [[true]]); - }).pipe(Effect.provide(layer)); + + assert.equal(yield* Ref.get(createCount), 0); + assert.isTrue(Option.isNone(yield* Ref.get(mainWindow))); + assert.equal(fake.send.mock.calls.length, 0); + }).pipe(Effect.provide(layerTest({ window: fake.window, createCount, mainWindow }))); }), ); - it.effect("debounces move and resize bounds updates", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - mainWindowBoundsUpdates, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - const move = fakeWindow.windowListeners.get("move"); - const resize = fakeWindow.windowListeners.get("resize"); - if (!move || !resize) { - return yield* Effect.die("window bounds listeners were not registered"); - } + it.effect.each(["main", "splash"] as const)( + "destroys a %s window when quit races native creation without loading or revealing it", + (kind) => + Effect.gen(function* () { + const fake = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const creationStarted = yield* Deferred.make(); + const releaseCreation = yield* Deferred.make(); + const reveal = vi.fn(); + const layer = layerTest({ + window: fake.window, + createCount, + mainWindow, + onWindowCreate: Deferred.succeed(creationStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseCreation)), + ), + destroyAll: Effect.sync(() => fake.isDestroyed.mockReturnValue(true)), + onReveal: reveal, + }); - fakeWindow.getBounds.mockReturnValue({ x: 120, y: 80, width: 1280, height: 840 }); - move(); - yield* TestClock.adjust(250); + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + const state = yield* DesktopState.DesktopState; + const fiber = yield* ( + kind === "splash" + ? windows.showConnectingSplash + : windows.handleBackendReady(new URL("http://127.0.0.1:3773")) + ).pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(creationStarted); + yield* Ref.set(state.quitting, true); + yield* Deferred.succeed(releaseCreation, undefined); + assert.isTrue(Exit.isSuccess(yield* Fiber.await(fiber))); + assert.equal(yield* Ref.get(createCount), 1); + assert.isTrue(fake.window.isDestroyed()); + assert.isTrue(Option.isNone(yield* Ref.get(mainWindow))); + assert.equal(fake.loadURL.mock.calls.length, 0); + assert.equal(fake.openDevTools.mock.calls.length, 0); + assert.equal(reveal.mock.calls.length, 0); + }).pipe(Effect.provide(layer)); + }), + ); - fakeWindow.getBounds.mockReturnValue({ x: 160, y: 100, width: 1360, height: 900 }); - resize(); - yield* TestClock.adjust(499); - assert.deepEqual(mainWindowBoundsUpdates, []); + it.effect.each(["backend ready", "activation", "renderer event"] as const)( + "quietly cancels %s when quit races preview cleanup", + (entry) => + Effect.gen(function* () { + const fake = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const previewStarted = yield* Deferred.make(); + const releasePreview = yield* Deferred.make(); + const reveal = vi.fn(); + const warnings: unknown[] = []; + const logger = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn" || logLevel === "Error") warnings.push(message); + }); + const layer = layerTest({ + window: fake.window, + createCount, + mainWindow, + desktopSettings: { + ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, + localEnvironmentEnabled: false, + }, + setPreviewMainWindow: () => + Deferred.succeed(previewStarted, undefined).pipe( + Effect.andThen(Deferred.await(releasePreview)), + ), + destroyAll: Effect.sync(() => fake.isDestroyed.mockReturnValue(true)), + onReveal: reveal, + }); - yield* TestClock.adjust(1); - yield* Effect.promise(() => Promise.resolve()); - assert.deepEqual(mainWindowBoundsUpdates, [{ x: 160, y: 100, width: 1360, height: 900 }]); - }).pipe(Effect.provide(layer)); - }), + yield* Effect.gen(function* () { + const windows = yield* DesktopWindow.DesktopWindow; + const state = yield* DesktopState.DesktopState; + const creation = + entry === "backend ready" + ? windows.handleBackendReady(new URL("http://127.0.0.1:3773")) + : entry === "activation" + ? windows.activate + : windows.dispatchMenuAction("open-settings"); + const fiber = yield* creation.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(previewStarted); + yield* Ref.set(state.quitting, true); + // Cover both an already-destroyed window and one shutdown has yet to destroy. + fake.isDestroyed.mockReturnValue(entry !== "backend ready"); + yield* Deferred.succeed(releasePreview, undefined); + + assert.isTrue(Exit.isSuccess(yield* Fiber.await(fiber))); + assert.isTrue(fake.window.isDestroyed()); + assert.isTrue(Option.isNone(yield* Ref.get(mainWindow))); + assert.equal(fake.loadURL.mock.calls.length, 0); + assert.equal(fake.openDevTools.mock.calls.length, 0); + assert.equal(fake.send.mock.calls.length, 0); + assert.equal(reveal.mock.calls.length, 0); + assert.deepEqual(warnings, []); + }).pipe( + Effect.provide( + Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false })), + ), + ); + }), ); it.effect("persists normal bounds and state for a maximized window", () => @@ -1023,74 +819,6 @@ describe("DesktopWindow", () => { }), ); - it.effect("persists normal bounds and state from the native maximize event", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; - const mainWindowMaximizedUpdates: boolean[] = []; - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - mainWindowBoundsUpdates, - mainWindowMaximizedUpdates, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - const maximize = fakeWindow.windowListeners.get("maximize"); - if (!maximize) { - return yield* Effect.die("window maximize listener was not registered"); - } - - fakeWindow.isMaximized.mockReturnValue(true); - fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 }); - fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 }); - maximize(); - yield* TestClock.adjust(500); - yield* Effect.promise(() => Promise.resolve()); - - assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]); - assert.deepEqual(mainWindowMaximizedUpdates, [true]); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("does not persist bounds that fail the domain schema", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - fakeWindow.getBounds.mockReturnValue({ x: 100.4, y: 80.2, width: 839.4, height: 619.4 }); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - mainWindowBoundsUpdates, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - const resize = fakeWindow.windowListeners.get("resize"); - if (!resize) { - return yield* Effect.die("window resize listener was not registered"); - } - resize(); - yield* TestClock.adjust(500); - yield* Effect.promise(() => Promise.resolve()); - - assert.deepEqual(mainWindowBoundsUpdates, []); - }).pipe(Effect.provide(layer)); - }), - ); - it.effect("preserves unrestorable bounds until the user changes the window", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1131,42 +859,6 @@ describe("DesktopWindow", () => { }), ); - it.effect("flushes normal bounds when fullscreen before the debounce completes", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - fakeWindow.getBounds.mockReturnValue({ x: 0, y: 0, width: 1920, height: 1080 }); - fakeWindow.getNormalBounds.mockReturnValue({ x: 200, y: 130, width: 1400, height: 940 }); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - mainWindowBoundsUpdates, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - const resize = fakeWindow.windowListeners.get("resize"); - if (!resize) { - return yield* Effect.die("window resize listener was not registered"); - } - resize(); - yield* TestClock.adjust(250); - fakeWindow.isFullScreen.mockReturnValue(true); - - yield* desktopWindow.flushMainWindowBounds; - - assert.deepEqual(mainWindowBoundsUpdates, [{ x: 200, y: 130, width: 1400, height: 940 }]); - assert.equal(fakeWindow.getBounds.mock.calls.length, 0); - assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1); - }).pipe(Effect.provide(layer)); - }), - ); - it.effect("flushes normal bounds when minimized before the debounce completes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1203,54 +895,6 @@ describe("DesktopWindow", () => { }), ); - it.effect("logs display lookup failures before falling back to the default size", () => - Effect.gen(function* () { - const displayLookupFailure = new Error("screen API unavailable"); - vi.mocked(Electron.screen.getAllDisplays).mockImplementationOnce(() => { - throw displayLookupFailure; - }); - const logRecords: Array<{ - readonly message: unknown; - readonly annotations: Readonly>; - }> = []; - const logger = Logger.make(({ fiber, message }) => { - logRecords.push({ - message, - annotations: { ...fiber.getRef(References.CurrentLogAnnotations) }, - }); - }); - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const createdWindowOptions: Electron.BrowserWindowConstructorOptions[] = []; - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - createdWindowOptions, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - }).pipe( - Effect.provide(Layer.mergeAll(layer, Logger.layer([logger], { mergeWithExisting: false }))), - ); - - const warning = logRecords.find( - (record) => - Array.isArray(record.message) && - record.message[0] === "failed to read connected displays; using defaults", - ); - assert.isDefined(warning); - assert.strictEqual(warning.annotations.cause, displayLookupFailure); - assert.equal(createdWindowOptions[0]?.width, 1100); - assert.equal(createdWindowOptions[0]?.height, 780); - assert.isUndefined(createdWindowOptions[0]?.x); - assert.isUndefined(createdWindowOptions[0]?.y); - }), - ); - it.effect("persists the current main window bounds before the window closes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1308,145 +952,6 @@ describe("DesktopWindow", () => { }), ); - it.effect("publishes native macOS fullscreen changes to the renderer", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - const enterFullscreen = fakeWindow.windowListeners.get("enter-full-screen"); - const leaveFullscreen = fakeWindow.windowListeners.get("leave-full-screen"); - if (!enterFullscreen || !leaveFullscreen) { - return yield* Effect.die("fullscreen listeners were not registered"); - } - - enterFullscreen(); - leaveFullscreen(); - assert.deepEqual(fakeWindow.send.mock.calls, [ - [WINDOW_FULLSCREEN_STATE_CHANNEL, true], - [WINDOW_FULLSCREEN_STATE_CHANNEL, false], - ]); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect( - "recovers killed renderers without reloading indefinitely or reviving closed windows", - () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow }); - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.createMain; - const onGone = fakeWindow.webContentsListeners.get("render-process-gone"); - const onLoaded = fakeWindow.webContentsListeners.get("did-finish-load"); - if (!onGone || !onLoaded) - return yield* Effect.die("renderer lifecycle listeners missing"); - - onGone({}, { reason: "clean-exit", exitCode: 0 }); - yield* TestClock.adjust(500); - assert.equal(fakeWindow.loadURL.mock.calls.length, 1); - - for (let attempt = 0; attempt < 4; attempt += 1) { - onGone({}, { reason: "killed", exitCode: 9 }); - yield* TestClock.adjust(500); - onLoaded(); - } - assert.equal(fakeWindow.loadURL.mock.calls.length, 4); - - yield* TestClock.adjust(60_000); - onGone({}, { reason: "killed", exitCode: 9 }); - yield* TestClock.adjust(500); - assert.equal(fakeWindow.loadURL.mock.calls.length, 5); - assert.equal(yield* Ref.get(createCount), 1); - - onGone({}, { reason: "killed", exitCode: 9 }); - fakeWindow.isDestroyed.mockReturnValue(true); - yield* TestClock.adjust(500); - assert.equal(fakeWindow.loadURL.mock.calls.length, 5); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("recovers when the development renderer is temporarily unreachable", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - - const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load"); - const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load"); - if (!didFailLoad || !didFinishLoad) { - return yield* Effect.die("renderer load listeners were not registered"); - } - - didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true); - assert.equal(fakeWindow.loadURL.mock.calls.length, 1); - - yield* TestClock.adjust(100); - assert.deepEqual(fakeWindow.loadURL.mock.calls, [ - ["t3code-dev://app/"], - ["t3code-dev://app/"], - ]); - assert.equal(fakeWindow.reload.mock.calls.length, 0); - - didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true); - didFinishLoad(); - yield* TestClock.adjust(250); - assert.equal(fakeWindow.loadURL.mock.calls.length, 2); - assert.equal(fakeWindow.reload.mock.calls.length, 0); - }).pipe(Effect.provide(layer)); - }), - ); - - it("retries only transient failures for the development renderer", () => { - assert.isTrue( - DesktopWindow.isRetryableDevelopmentRendererLoadFailure({ - applicationUrl: "t3code-dev://app/", - errorCode: -102, - isMainFrame: true, - validatedUrl: "t3code-dev://app/", - }), - ); - assert.isFalse( - DesktopWindow.isRetryableDevelopmentRendererLoadFailure({ - applicationUrl: "t3code-dev://app/", - errorCode: -3, - isMainFrame: true, - validatedUrl: "t3code-dev://app/", - }), - ); - assert.isFalse( - DesktopWindow.isRetryableDevelopmentRendererLoadFailure({ - applicationUrl: "t3code-dev://app/", - errorCode: -102, - isMainFrame: true, - validatedUrl: "https://example.com/", - }), - ); - }); - it.effect("opens safe off-origin renderer navigations in the system browser", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1515,68 +1020,6 @@ describe("DesktopWindow", () => { }), ); - it.effect( - "re-reveals the connecting splash on activate while the backend is still cold-booting", - () => - Effect.gen(function* () { - const splash = makeFakeBrowserWindow(); - const scenario = yield* makeSplashScenario([splash.window]); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - - yield* desktopWindow.showConnectingSplash; - assert.equal(yield* Ref.get(scenario.createCalls), 1); - - yield* desktopWindow.activate; - assert.equal(yield* Ref.get(scenario.createCalls), 1); - assert.deepEqual(yield* Ref.get(scenario.revealedWindows), [splash.window]); - }).pipe(Effect.provide(scenario.layer)); - }), - ); - - it.effect("does not dispatch menu actions to the splash before the backend is ready", () => - Effect.gen(function* () { - const splash = makeFakeBrowserWindow(); - const main = makeFakeBrowserWindow(); - const scenario = yield* makeSplashScenario([splash.window, main.window]); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - - yield* desktopWindow.showConnectingSplash; - yield* desktopWindow.dispatchMenuAction("open-settings"); - - assert.equal(yield* Ref.get(scenario.createCalls), 1); - assert.equal(splash.send.mock.calls.length, 0); - assert.equal(main.send.mock.calls.length, 0); - }).pipe(Effect.provide(scenario.layer)); - }), - ); - - it.effect("dispatches menu actions after backend readiness when no main window exists", () => - Effect.gen(function* () { - const splash = makeFakeBrowserWindow(); - const main = makeFakeBrowserWindow(); - const scenario = yield* makeSplashScenario([splash.window, null, main.window]); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - - yield* desktopWindow.showConnectingSplash; - const readyExit = yield* Effect.exit( - desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")), - ); - assert.equal(readyExit._tag, "Failure"); - - yield* desktopWindow.dispatchMenuAction("open-settings"); - - assert.equal(yield* Ref.get(scenario.createCalls), 3); - assert.deepEqual(main.send.mock.calls, [[MENU_ACTION_CHANNEL, "open-settings"]]); - }).pipe(Effect.provide(scenario.layer)); - }), - ); - it.effect("delivers capture completion and late errors without taking focus back", () => Effect.gen(function* () { const operations: Array = []; @@ -1617,51 +1060,6 @@ describe("DesktopWindow", () => { }), ); - it.effect("delivers the renderer event even when the reveal fails", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>(Option.none()); - const layer = layerTest({ - window: fakeWindow.window, - createCount, - mainWindow, - onReveal: () => { - throw new Error("another process kept the foreground"); - }, - }); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); - yield* Effect.exit( - desktopWindow.dispatchSnapShotEvent({ type: "started", id: captureOne }), - ); - - assert.deepEqual(fakeWindow.send.mock.calls, [ - [SNAP_SHOT_EVENT_CHANNEL, { type: "started", id: captureOne }], - ]); - }).pipe(Effect.provide(layer)); - }), - ); - - it.effect("leaves a completed capture pending while only the connecting splash exists", () => - Effect.gen(function* () { - const splash = makeFakeBrowserWindow(); - const scenario = yield* makeSplashScenario([splash.window]); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.showConnectingSplash; - yield* desktopWindow.dispatchSnapShotEvent({ type: "ready", id: captureOne }); - - assert.equal(yield* Ref.get(scenario.createCalls), 1); - assert.equal(splash.send.mock.calls.length, 0); - assert.deepEqual(yield* Ref.get(scenario.revealedWindows), []); - }).pipe(Effect.provide(scenario.layer)); - }), - ); - it.effect("does not reopen a closed main window for a completed capture", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1683,34 +1081,4 @@ describe("DesktopWindow", () => { }).pipe(Effect.provide(layer)); }), ); - - it.effect("waits for a loading renderer without foregrounding it when capture is ready", () => - Effect.gen(function* () { - const fakeWindow = makeFakeBrowserWindow(); - const createCount = yield* Ref.make(0); - const mainWindow = yield* Ref.make>( - Option.some(fakeWindow.window), - ); - const onReveal = vi.fn(); - const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow, onReveal }); - vi.mocked(fakeWindow.window.webContents.isLoadingMainFrame).mockReturnValue(true); - - yield* Effect.gen(function* () { - const desktopWindow = yield* DesktopWindow.DesktopWindow; - yield* desktopWindow.dispatchSnapShotEvent({ type: "ready", id: captureOne }); - assert.equal(fakeWindow.send.mock.calls.length, 0); - const onLoad = fakeWindow.webContentsOnce.mock.calls.find( - ([event]) => event === "did-finish-load", - )?.[1]; - assert.isDefined(onLoad); - onLoad?.(); - - assert.deepEqual(fakeWindow.send.mock.calls, [ - [SNAP_SHOT_EVENT_CHANNEL, { type: "ready", id: captureOne }], - ]); - assert.equal(onReveal.mock.calls.length, 0); - assert.equal(yield* Ref.get(createCount), 0); - }).pipe(Effect.provide(layer)); - }), - ); }); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 2a39c15193e6f..6270f80a4a7e6 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -13,6 +13,7 @@ import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/con import * as DesktopAssets from "../app/DesktopAssets.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; +import * as DesktopState from "../app/DesktopState.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; import { getDesktopUrl } from "../electron/ElectronProtocol.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; @@ -36,8 +37,7 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; const TITLEBAR_HEIGHT = 40; -// Matches --workspace-topbar-height in apps/web/src/index.css. Native macOS -// buttons are 14 points tall and do not scale with the renderer's zoom. +// Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom. const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52; const MACOS_WINDOW_BUTTON_RADIUS = 7; @@ -69,6 +69,7 @@ type WindowTitleBarOptions = Pick< type DesktopWindowRuntimeServices = | DesktopEnvironment.DesktopEnvironment + | DesktopState.DesktopState | DesktopAssets.DesktopAssets | DesktopAppSettings.DesktopAppSettings | DesktopClientSettings.DesktopClientSettings @@ -107,9 +108,7 @@ export class DesktopWindow extends Context.Service< readonly dispatchSnapShotEvent: ( event: DesktopSnapShotEvent, ) => Effect.Effect; - // The Electron `zoomIn`/`zoomOut` menu roles act on whichever webContents - // has keyboard focus, so with an embedded preview WebContentsView (or - // DevTools) focused they zoom the guest page instead of the app UI. + // Electron zoom roles target focused guests; zoomMain must always target the app. readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect; readonly runMainContentsCommand: (command: MainWindowContentsCommand) => Effect.Effect; readonly syncAppearance: Effect.Effect; @@ -183,7 +182,7 @@ function buildConnectingSplashDataUrl(shouldUseDarkColors: boolean): string { return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`; } -export function isSameOriginRendererNavigation(input: { +function isSameOriginRendererNavigation(input: { readonly applicationUrl: string; readonly navigationUrl: string; }): boolean { @@ -194,7 +193,7 @@ export function isSameOriginRendererNavigation(input: { } } -export function isRetryableDevelopmentRendererLoadFailure(input: { +function isRetryableDevelopmentRendererLoadFailure(input: { readonly applicationUrl: string; readonly errorCode: number; readonly isMainFrame: boolean; @@ -210,7 +209,7 @@ export function isRetryableDevelopmentRendererLoadFailure(input: { ); } -export function concealPendingQuitWindow( +function concealPendingQuitWindow( window: Pick< Electron.BrowserWindow, "isDestroyed" | "isFullScreen" | "setFullScreen" | "setOpacity" @@ -220,8 +219,7 @@ export function concealPendingQuitWindow( if (window.isFullScreen()) { window.setFullScreen(false); } - // Electron implements window opacity on macOS and Windows. Linux keeps the - // release-gated quit behavior but cannot make the pending window disappear. + // Linux lacks Electron window opacity; release-gated quits remain visible there. window.setOpacity(0); } @@ -284,9 +282,10 @@ function bindFirstRevealTrigger( } } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; + const desktopState = yield* DesktopState.DesktopState; const assets = yield* DesktopAssets.DesktopAssets; const electronMenu = yield* ElectronMenu.ElectronMenu; const electronShell = yield* ElectronShell.ElectronShell; @@ -312,11 +311,7 @@ export const make = Effect.gen(function* () { } }); - // currentMainOrFirst / focusedMainOrFirst fall back to "any first window", - // which during WSL-only boot is the connecting splash. The splash is never - // registered via setMain, so it must be treated as "no real main window" -- - // otherwise ensureMain/activate/dispatchMenuAction latch onto it and never - // open (or retry) the real main. + // Electron's first-window fallback can select the unregistered connecting splash; exclude it so main creation retries. const withoutSplash = (window: Option.Option) => Ref.get(splashWindowRef).pipe( Effect.map((splash) => @@ -329,10 +324,24 @@ export const make = Effect.gen(function* () { const currentMainWindow = electronWindow.currentMainOrFirst.pipe(Effect.flatMap(withoutSplash)); const focusedMainWindow = electronWindow.focusedMainOrFirst.pipe(Effect.flatMap(withoutSplash)); + const zoomWindow = Effect.fn("desktop.window.zoomWindow")(function* ( + window: Electron.BrowserWindow, + direction: MainWindowZoomDirection, + ) { + const webContents = window.webContents; + webContents.setZoomLevel( + direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5), + ); + if (environment.platform === "darwin") syncMacosWindowButtons(window); + // App zoom propagates to guests; restore each preview's own zoom. + yield* previewManager.reapplyZoom(); + }); + const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return< - Electron.BrowserWindow, + Option.Option, DesktopWindowError > { + if (yield* Ref.get(desktopState.quitting)) return Option.none(); yield* previewManager.getBrowserSession(); const applicationUrl = getDesktopUrl(environment.isDevelopment); const iconPaths = yield* assets.iconPaths; @@ -361,6 +370,7 @@ export const make = Effect.gen(function* () { if (persistedBounds !== null && initialBounds === DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE) { yield* logWindowWarning("saved main window bounds could not be restored; using defaults"); } + if (yield* Ref.get(desktopState.quitting)) return Option.none(); const window = yield* electronWindow.create({ ...initialBounds, minWidth: 840, @@ -374,21 +384,20 @@ export const make = Effect.gen(function* () { ...getWindowTitleBarOptions(shouldUseDarkColors, environment.platform), webPreferences: { preload: environment.preloadPath, - // Chromium throttles hidden renderers: timers coalesce and rAF stops, - // which stalls first paint. Boot unthrottled; the first-reveal trigger - // re-enables throttling so a hidden or minimized window goes back to - // being cheap after it has been shown once. + // Hidden-renderer throttling stalls first paint; re-enable it after the first reveal. backgroundThrottling: false, contextIsolation: true, nodeIntegration: false, sandbox: true, webviewTag: true, - // A preview guest's fullscreen request is mirrored onto this embedder, - // which would otherwise put the whole window into OS fullscreen. With - // both sides opted out the page fills its webview and the window stays. + // Guest fullscreen propagates to the embedder; both must opt out to keep it inside the webview. disableHtmlFullscreenWindowResize: true, }, }); + if (yield* Ref.get(desktopState.quitting)) { + yield* electronWindow.destroyAll; + return Option.none(); + } yield* rendererHistory.register(window.webContents, { surface: "main" }); if (environment.platform === "darwin") { @@ -482,6 +491,10 @@ export const make = Effect.gen(function* () { flushMainWindowBounds = flushBoundsPersist; yield* previewManager.setMainWindow(window); + if (yield* Ref.get(desktopState.quitting)) { + yield* electronWindow.destroyAll; + return Option.none(); + } window.webContents.on("will-attach-webview", (event, webPreferences, params) => { if ( typeof params.partition !== "string" || @@ -513,8 +526,7 @@ export const make = Effect.gen(function* () { contents.on("context-menu", (event, params) => { event.preventDefault(); if (contents.isDestroyed() || ownerWindow.isDestroyed()) return; - // Native editing roles act on the focused contents, which may still be - // the host renderer when the user right-clicks inside a browser guest. + // Right-clicking a guest may leave native editing roles targeting the host renderer. contents.focus(); const menuTemplate: Electron.MenuItemConstructorOptions[] = []; @@ -607,9 +619,7 @@ export const make = Effect.gen(function* () { } }); - // Electron's windowMenu close role owns CmdOrCtrl+W. Holding the - // close-terminal shortcut can outlive the terminal that handled its first - // press, so reject repeats before they reach the native window accelerator. + // Terminal-close repeats can outlive the terminal; reject them before the native close-window accelerator. const quitShortcutHandler = makeQuitShortcutHandler({ platform: environment.platform, getMode: () => @@ -627,8 +637,7 @@ export const make = Effect.gen(function* () { window.webContents.send(QUIT_SHORTCUT_CHANNEL, hint); } }, - // Keep the transparent window focused until the physical shortcut is - // released so its remaining repeats cannot reach the next app. + // Hold focus until shortcut release so remaining repeats cannot reach the next app. concealWindow: () => concealPendingQuitWindow(window), quit: () => { void runPromise(electronApp.quit); @@ -645,6 +654,11 @@ export const make = Effect.gen(function* () { window.webContents.on("input-event", (_event, input) => { if (input.type === "gestureScrollEnd") window.webContents.send(TRACKPAD_SCROLL_END_CHANNEL); }); + // Ctrl+wheel bypasses menus; guest contents emit their own zoom-changed event. + window.webContents.on("zoom-changed", (_event, direction) => { + if (window.isDestroyed()) return; + runFork(zoomWindow(window, direction)); + }); window.on("page-title-updated", (event) => { event.preventDefault(); @@ -758,8 +772,6 @@ export const make = Effect.gen(function* () { details.reason === "oom" || details.reason === "killed" || details.reason === "abnormal-exit"; - // Recovery attempts are bounded so a renderer that dies immediately on - // boot cannot reload-loop forever. runFork( Effect.gen(function* () { @@ -813,26 +825,35 @@ export const make = Effect.gen(function* () { void runPromise(electronWindow.clearMain(Option.some(window))); }); - return window; + return Option.some(window); }); const createMain = Effect.gen(function* () { const window = yield* createWindow(); - yield* electronWindow.setMain(window); - yield* logWindowInfo("main window created"); + if (Option.isSome(window)) { + yield* electronWindow.setMain(window.value); + yield* logWindowInfo("main window created"); + } return window; }).pipe(Effect.withSpan("desktop.window.createMain")); const ensureMain = Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return Option.none(); const existingWindow = yield* currentMainWindow; if (Option.isSome(existingWindow)) { - return existingWindow.value; + return existingWindow; } return yield* createMain; }).pipe(Effect.withSpan("desktop.window.ensureMain")); + const requireWindow = (window: Option.Option) => + Option.match(window, { + onNone: () => Effect.interrupt, + onSome: Effect.succeed, + }); + const revealOrCreateMain = Effect.gen(function* () { - const window = yield* ensureMain; + const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow)); yield* electronWindow.reveal(window); return window; }).pipe(Effect.withSpan("desktop.window.revealOrCreateMain")); @@ -843,6 +864,7 @@ export const make = Effect.gen(function* () { }); const createMainIfBackendReady = Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return; if (yield* waitingForBackend) return; const existingWindow = yield* currentMainWindow; if (Option.isSome(existingWindow)) return; @@ -850,12 +872,14 @@ export const make = Effect.gen(function* () { }).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady")); const showConnectingSplash = Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return; const existingSplash = yield* Ref.get(splashWindowRef); if (Option.isSome(existingSplash)) return; const existingWindow = yield* electronWindow.currentMainOrFirst; if (Option.isSome(existingWindow)) return; const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors; + if (yield* Ref.get(desktopState.quitting)) return; const splash = yield* electronWindow.create({ width: 360, height: 220, @@ -875,6 +899,10 @@ export const make = Effect.gen(function* () { sandbox: true, }, }); + if (yield* Ref.get(desktopState.quitting)) { + yield* electronWindow.destroyAll; + return; + } yield* rendererHistory.register(splash.webContents, { surface: "splash" }); yield* Ref.set(splashWindowRef, Option.some(splash)); splash.once("closed", () => { @@ -899,15 +927,16 @@ export const make = Effect.gen(function* () { payload: unknown, { reveal = true }: { readonly reveal?: boolean } = {}, ) { + if (yield* Ref.get(desktopState.quitting)) return; const existingWindow = yield* reveal ? focusedMainWindow : electronWindow.main; if (Option.isNone(existingWindow) && (!reveal || (yield* waitingForBackend))) return; - const targetWindow = Option.isSome(existingWindow) ? existingWindow.value : yield* ensureMain; - if (targetWindow.isDestroyed()) return; + const window = Option.isSome(existingWindow) ? existingWindow : yield* ensureMain; + if (Option.isNone(window) || window.value.isDestroyed()) return; + const targetWindow = window.value; const send = Effect.sync(() => { if (!targetWindow.isDestroyed()) targetWindow.webContents.send(channel, payload); }); - // The renderer must learn about the event even when another process refuses to - // yield the foreground, so send first and treat the reveal as best effort. + // Send before best-effort reveal; another process may refuse to yield foreground focus. const dispatch = reveal ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause))) : send; @@ -919,8 +948,8 @@ export const make = Effect.gen(function* () { }); return DesktopWindow.of({ - createMain, - ensureMain, + createMain: createMain.pipe(Effect.flatMap(requireWindow)), + ensureMain: ensureMain.pipe(Effect.flatMap(requireWindow)), revealOrCreateMain, prepareCaptureReveal: Effect.gen(function* () { const existingWindow = yield* currentMainWindow; @@ -929,6 +958,7 @@ export const make = Effect.gen(function* () { } }), activate: Effect.gen(function* () { + if (yield* Ref.get(desktopState.quitting)) return; const existingWindow = yield* currentMainWindow; if (Option.isSome(existingWindow)) { yield* electronWindow.reveal(existingWindow.value); @@ -972,24 +1002,15 @@ export const make = Effect.gen(function* () { }), zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) { yield* Effect.annotateCurrentSpan({ direction }); - const window = yield* focusedMainWindow; + const window = yield* electronWindow.main; if (Option.isNone(window) || window.value.isDestroyed()) { return; } - const webContents = window.value.webContents; - webContents.setZoomLevel( - direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5), - ); - if (environment.platform === "darwin") syncMacosWindowButtons(window.value); - // Chromium pushes the new level down to embedded guests, which would zoom - // the previewed page along with the app UI. The preview browser keeps its - // own zoom, so put each guest back where the preview left it. - yield* previewManager.reapplyZoom(); + yield* zoomWindow(window.value, direction); }), runMainContentsCommand: Effect.fn("desktop.window.runMainContentsCommand")(function* (command) { yield* Effect.annotateCurrentSpan({ command }); - // The registered main window, never the focused one: with an OAuth popup - // focused, Reload would otherwise reload the popup mid sign-in. + // A focused OAuth popup must not receive the app's Reload command. const window = yield* electronWindow.main; if (Option.isNone(window) || window.value.isDestroyed()) return; const webContents = window.value.webContents; diff --git a/apps/desktop/src/window/QuitHold.test.ts b/apps/desktop/src/window/QuitHold.test.ts index 591fad185a5da..bebcd66e61c6e 100644 --- a/apps/desktop/src/window/QuitHold.test.ts +++ b/apps/desktop/src/window/QuitHold.test.ts @@ -4,12 +4,10 @@ import { makeQuitShortcutHandler, QUIT_DOUBLE_PRESS_MS, QUIT_HOLD_DURATION_MS, - QUIT_HOLD_RELEASE_GRACE_MS, } from "./QuitHold.ts"; import type { QuitHoldKeyInput } from "./QuitHold.ts"; import type { QuitConfirmationMode, QuitShortcutHintEvent } from "@t3tools/contracts"; -const HOLD_DOWN = { state: "down", mode: "hold" } as const; const DOUBLE_CLICK_DOWN = { state: "down", mode: "double-click" } as const; const UP = { state: "up" } as const; @@ -68,165 +66,6 @@ describe("makeQuitShortcutHandler", () => { vi.useRealTimers(); }); - it("shows the hint on a tap without quitting, even when the release is never seen", async () => { - // macOS suppresses the letter's keyUp while Cmd is held, so a tap may - // produce no keyUp at all. Quit must still not fire. - const harness = makeHarness(); - await harness.send(makeInput({})); - expect(harness.preventDefault).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([HOLD_DOWN]); - - vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS); - expect(harness.quit).not.toHaveBeenCalled(); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - }); - - it("conceals a completed hold, then quits after release", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_HOLD_DURATION_MS + 200); - expect(harness.concealWindow).toHaveBeenCalledTimes(1); - expect(harness.quit).not.toHaveBeenCalled(); - await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false })); - expect(harness.quit).not.toHaveBeenCalled(); - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS); - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - }); - - it("keeps a concealed hold committed when another key is pressed", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_HOLD_DURATION_MS); - - await harness.send(makeInput({ key: "Shift", shift: true })); - expect(harness.concealWindow).toHaveBeenCalledTimes(1); - expect(harness.quit).not.toHaveBeenCalled(); - - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS); - expect(harness.quit).toHaveBeenCalledTimes(1); - }); - - it("keeps a concealed hold committed through a fresh Cmd+Q press", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_HOLD_DURATION_MS); - - await harness.send(makeInput({})); - expect(harness.concealWindow).toHaveBeenCalledTimes(1); - expect(harness.quit).not.toHaveBeenCalled(); - - await harness.send(makeInput({ type: "keyUp" })); - expect(harness.quit).toHaveBeenCalledTimes(1); - }); - - it("quits when a completed hold goes quiet without release events", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS * 2); - - expect(harness.quit).not.toHaveBeenCalled(); - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS); - - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - }); - - it("waits for slow repeats to stop before quitting", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - - vi.advanceTimersByTime(300); - await harness.send(makeInput({ isAutoRepeat: true })); - vi.advanceTimersByTime(900); - await harness.send(makeInput({ isAutoRepeat: true })); - - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS); - expect(harness.quit).not.toHaveBeenCalled(); - - vi.advanceTimersByTime(300); - await harness.send(makeInput({ isAutoRepeat: true })); - vi.advanceTimersByTime(1_799); - expect(harness.quit).not.toHaveBeenCalled(); - vi.advanceTimersByTime(1); - expect(harness.quit).toHaveBeenCalledTimes(1); - }); - - it("uses the initial repeat delay when the first repeat completes the hold", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - - vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + 100); - await harness.send(makeInput({ isAutoRepeat: true })); - - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS); - expect(harness.quit).not.toHaveBeenCalled(); - vi.advanceTimersByTime(1_999); - expect(harness.quit).not.toHaveBeenCalled(); - vi.advanceTimersByTime(1); - expect(harness.quit).toHaveBeenCalledTimes(1); - }); - - it("waits for Q release when Cmd is released first", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_HOLD_DURATION_MS + 200); - await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false })); - harness.preventDefault.mockClear(); - await harness.holdFor(QUIT_HOLD_RELEASE_GRACE_MS * 2, { meta: false }); - expect(harness.preventDefault).toHaveBeenCalled(); - expect(harness.quit).not.toHaveBeenCalled(); - await harness.send(makeInput({ type: "keyUp", meta: false })); - expect(harness.quit).toHaveBeenCalledTimes(1); - }); - - it("commits a concealed hold when the last Q repeat is never released", async () => { - // macOS can drop the final Q keyUp. The quit must land on its own once - // repeats stop, rather than sitting armed until an unrelated key arrives. - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_HOLD_DURATION_MS + 200); - await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false })); - await harness.send(makeInput({ meta: false, isAutoRepeat: true })); - - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS); - expect(harness.quit).toHaveBeenCalledTimes(1); - - harness.quit.mockClear(); - await harness.send(makeInput({ key: "Meta" })); - await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false })); - vi.advanceTimersByTime(QUIT_HOLD_RELEASE_GRACE_MS * 4); - expect(harness.quit).not.toHaveBeenCalled(); - }); - - it("does not quit when the hold stops before the duration", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(500); - await harness.send(makeInput({ type: "keyUp" })); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2); - expect(harness.concealWindow).not.toHaveBeenCalled(); - expect(harness.quit).not.toHaveBeenCalled(); - }); - - it("cancels the hold when the modifier is released first", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false })); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2); - expect(harness.quit).not.toHaveBeenCalled(); - }); - - it("quits without showing a hint in direct mode", async () => { - const harness = makeHarness({ mode: "direct" }); - await harness.send(makeInput({})); - expect(harness.concealWindow).not.toHaveBeenCalled(); - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([]); - }); - it("honors direct mode when the key is released before its mode read settles", async () => { let resolveMode: ((mode: QuitConfirmationMode) => void) | undefined; const harness = makeHarness({ @@ -313,128 +152,6 @@ describe("makeQuitShortcutHandler", () => { expect(harness.quit).toHaveBeenCalledTimes(1); }); - it("quits on a quick double press in double-click mode when the first release is unseen", async () => { - const harness = makeHarness({ mode: "double-click" }); - await harness.send(makeInput({})); - vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100); - await harness.send(makeInput({})); - expect(harness.concealWindow).not.toHaveBeenCalled(); - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]); - }); - - it("keeps the double-press hint visible after key release until the window ends", async () => { - const harness = makeHarness({ mode: "double-click" }); - await harness.send(makeInput({})); - vi.advanceTimersByTime(100); - await harness.send(makeInput({ type: "keyUp" })); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]); - - vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 101); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]); - vi.advanceTimersByTime(1); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]); - }); - - it("accepts a second full shortcut after the modifier is released and pressed again", async () => { - const harness = makeHarness({ mode: "double-click" }); - await harness.send(makeInput({})); - await harness.send(makeInput({ type: "keyUp" })); - await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false })); - vi.advanceTimersByTime(100); - - await harness.send(makeInput({ key: "Meta" })); - await harness.send(makeInput({})); - - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]); - }); - - it("expires a delayed double-press hint from keydown rather than mode resolution", async () => { - let resolveMode: ((mode: QuitConfirmationMode) => void) | undefined; - const harness = makeHarness({ - getMode: () => - new Promise((resolve) => { - resolveMode = resolve; - }), - }); - await harness.send(makeInput({})); - vi.advanceTimersByTime(100); - await harness.send(makeInput({ type: "keyUp" })); - vi.advanceTimersByTime(100); - resolveMode?.("double-click"); - await Promise.resolve(); - await Promise.resolve(); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]); - - vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 201); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN]); - vi.advanceTimersByTime(1); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP]); - }); - - it("treats two slow presses as separate attempts in double-click mode", async () => { - const harness = makeHarness({ mode: "double-click" }); - await harness.send(makeInput({})); - await harness.send(makeInput({ type: "keyUp" })); - vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS + 100); - await harness.send(makeInput({})); - expect(harness.quit).not.toHaveBeenCalled(); - expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP, DOUBLE_CLICK_DOWN]); - }); - - it("quits on a quick second press in hold mode", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.send(makeInput({ type: "keyUp" })); - vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100); - await harness.send(makeInput({})); - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - }); - - it("quits on a quick second press in hold mode when the first release is unseen", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - vi.advanceTimersByTime(QUIT_DOUBLE_PRESS_MS - 100); - await harness.send(makeInput({})); - - expect(harness.concealWindow).not.toHaveBeenCalled(); - expect(harness.quit).toHaveBeenCalledTimes(1); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - }); - - it("does not count auto-repeat as a second press", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(QUIT_DOUBLE_PRESS_MS - 100); - - expect(harness.quit).not.toHaveBeenCalled(); - expect(harness.notifications).toEqual([HOLD_DOWN]); - }); - - it("does not count a released tap after another shortcut interrupts it", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.send(makeInput({ type: "keyUp" })); - await harness.send(makeInput({ key: "c" })); - vi.advanceTimersByTime(100); - await harness.send(makeInput({})); - - expect(harness.quit).not.toHaveBeenCalled(); - expect(harness.notifications).toEqual([HOLD_DOWN, UP, HOLD_DOWN]); - }); - - it("cancels the hold when another key interrupts it", async () => { - const harness = makeHarness(); - await harness.send(makeInput({})); - await harness.holdFor(500); - await harness.send(makeInput({ shift: true })); - expect(harness.notifications).toEqual([HOLD_DOWN, UP]); - await harness.holdFor(QUIT_HOLD_DURATION_MS); - expect(harness.quit).not.toHaveBeenCalled(); - }); - it("does not count an interrupted press toward a double press", async () => { const harness = makeHarness({ mode: "double-click" }); await harness.send(makeInput({})); @@ -443,22 +160,4 @@ describe("makeQuitShortcutHandler", () => { expect(harness.quit).not.toHaveBeenCalled(); expect(harness.notifications).toEqual([DOUBLE_CLICK_DOWN, UP, DOUBLE_CLICK_DOWN]); }); - - it("ignores other shortcuts", async () => { - const harness = makeHarness(); - await harness.send(makeInput({ key: "w" })); - await harness.send(makeInput({ shift: true })); - await harness.send(makeInput({ meta: false })); - expect(harness.preventDefault).not.toHaveBeenCalled(); - expect(harness.notifications).toEqual([]); - }); - - it("uses control on non-mac platforms", async () => { - const harness = makeHarness({ platform: "linux" }); - await harness.send(makeInput({ meta: false, control: true })); - expect(harness.preventDefault).toHaveBeenCalledTimes(1); - await harness.holdFor(QUIT_HOLD_DURATION_MS + 200, { meta: false, control: true }); - await harness.send(makeInput({ type: "keyUp", meta: false, control: true })); - expect(harness.quit).toHaveBeenCalledTimes(1); - }); }); diff --git a/apps/desktop/src/window/QuitHold.ts b/apps/desktop/src/window/QuitHold.ts index eb0b3141c47a8..f7db33f17ed5e 100644 --- a/apps/desktop/src/window/QuitHold.ts +++ b/apps/desktop/src/window/QuitHold.ts @@ -4,12 +4,10 @@ import type { QuitConfirmationMode, QuitShortcutHintEvent } from "@t3tools/contr export const QUIT_HOLD_DURATION_MS = 1200; export const QUIT_DOUBLE_PRESS_MS = 500; -// "Still held" is proven by auto-repeat keydowns, not by the absence of a -// release: macOS suppresses a letter keyUp while the command key is down, so a -// tap release can go completely unseen and a release-based timer would quit -// anyway. Once held, quitting waits for Q keyUp or a quiet grace period after -// repeats stop so they cannot reach the next app. -export const QUIT_HOLD_RELEASE_GRACE_MS = 600; +// Auto-repeat keydowns prove the hold: macOS drops a letter keyUp while Command is down, +// so a release-based timer would quit anyway. Once held, quitting waits for Q keyUp or a +// quiet grace period so trailing repeats cannot reach the next app. +const QUIT_HOLD_RELEASE_GRACE_MS = 600; // A slow repeat rate can exceed the fixed grace. Waiting for two observed // cadences keeps the timer behind the next repeat without slowing normal rates. const QUIT_HOLD_REPEAT_CADENCE_MULTIPLIER = 2; @@ -46,9 +44,7 @@ export function makeQuitShortcutHandler( let lastPressAt = 0; let lastRepeatAt = 0; let repeatCadenceMs = 0; - // Incremented when a press is superseded or explicitly cancelled. A plain - // key release does not invalidate its pending mode read: a direct-mode - // press must still quit after that read settles. + // A key release must not invalidate a pending direct-mode read; only superseding/cancelled presses do. let generation = 0; const clearWatchdog = () => { @@ -125,8 +121,7 @@ export function makeQuitShortcutHandler( if (!modifierDown || input.alt || input.shift || key !== "q") { if (key === modifierKey && !input.alt && !input.shift) return; - // Keep this separate from release(), which also runs when a fresh Q - // keydown follows a keyUp that macOS did not deliver. + // release() also runs on fresh keydown after a missing macOS keyUp. if (!input.isAutoRepeat) { lastPressAt = 0; release(); diff --git a/apps/desktop/src/wsl/DesktopWslBackend.test.ts b/apps/desktop/src/wsl/DesktopWslBackend.test.ts index e6dcb7bd7133e..8468a9538630c 100644 --- a/apps/desktop/src/wsl/DesktopWslBackend.test.ts +++ b/apps/desktop/src/wsl/DesktopWslBackend.test.ts @@ -84,29 +84,6 @@ const layerNet = Layer.succeed(NetService.NetService, { } satisfies NetService.NetService["Service"]); describe("DesktopWslBackend", () => { - it.effect("does not discover or start WSL when local execution is disabled", () => - Effect.gen(function* () { - const backend = yield* DesktopWslBackend.DesktopWslBackend; - yield* backend.reconcile; - }).pipe( - Effect.provide( - DesktopWslBackend.layer.pipe( - Layer.provide(Layer.mock(DesktopBackendPool.DesktopBackendPool, {})), - Layer.provide(layerBackendConfiguration), - Layer.provide(layerServerExposure), - Layer.provide(layerNet), - Layer.provide(Layer.mock(DesktopWslEnvironment.DesktopWslEnvironment, {})), - Layer.provide( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - localEnvironmentEnabled: false, - wslBackendEnabled: true, - }), - ), - ), - ), - ), - ); it.effect("clears the stored preflight error when a registered WSL backend becomes ready", () => { let registeredSpec: DesktopBackendPool.BackendInstanceSpec | undefined; let registeredWsl: DesktopBackendPool.DesktopBackendInstance | undefined; @@ -214,47 +191,4 @@ describe("DesktopWslBackend", () => { ), ); }); - - it.effect("retries an unchanged WSL instance when it is idle after failed preflight", () => { - let startCount = 0; - const primary = makeStubInstance({ - id: DesktopBackendPool.PRIMARY_INSTANCE_ID, - label: "Windows", - snapshot: primarySnapshot, - }); - const wsl = makeStubInstance({ - id: DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"), - label: "WSL (Ubuntu)", - snapshot: idleSnapshot, - start: Effect.sync(() => { - startCount += 1; - }), - }); - - return Effect.gen(function* () { - const backend = yield* DesktopWslBackend.DesktopWslBackend; - - yield* backend.reconcile; - - assert.equal(startCount, 1); - }).pipe( - Effect.provide( - DesktopWslBackend.layer.pipe( - Layer.provideMerge(DesktopBackendPool.layerTest([primary, wsl])), - Layer.provideMerge(layerBackendConfiguration), - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(layerNet), - Layer.provideMerge( - DesktopAppSettings.layerTest({ - ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS, - wslBackendEnabled: true, - wslDistro: "Ubuntu", - wslOnly: false, - }), - ), - Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })), - ), - ), - ); - }); }); diff --git a/apps/desktop/src/wsl/DesktopWslBackend.ts b/apps/desktop/src/wsl/DesktopWslBackend.ts index 95e5e84d91347..e77d896be2469 100644 --- a/apps/desktop/src/wsl/DesktopWslBackend.ts +++ b/apps/desktop/src/wsl/DesktopWslBackend.ts @@ -15,8 +15,6 @@ import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopWslEnvironment from "./DesktopWslEnvironment.ts"; -// Exported so callers that parse pool ids (e.g. the pickFolder IPC handler in -// ipc/methods/window.ts) reference the same prefix this module produces. export const WSL_INSTANCE_ID_PREFIX = "wsl:"; const WSL_DEFAULT_DISTRO_ID = `${WSL_INSTANCE_ID_PREFIX}default`; const MAX_TCP_PORT = 65_535; @@ -43,9 +41,7 @@ const isWslInstanceId = (id: DesktopBackendPool.BackendInstanceId): boolean => const buildLabel = (distro: string | null): string => distro === null ? "WSL (default distro)" : `WSL (${distro})`; -// Loopback-only port scan starting one above the primary's port. The -// WSL backend is reachable via 127.0.0.1 from Windows (wslhost -// auto-forwards), so we only need to verify the IPv4 loopback can bind. +// WSL auto-forwards loopback ports, so only IPv4 loopback availability matters. const scanForWslPort = Effect.fn("desktop.wslBackend.scanForWslPort")(function* ( startPort: number, ): Effect.fn.Return { @@ -69,11 +65,7 @@ export const layer = Layer.effect( const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; const net = yield* NetService.NetService; - // Serialize reconcile so the bootstrap fork and the IPC handlers - // (setWslBackendEnabled, setWslDistro) can't interleave. Without - // this, two reconciles could both observe "no WSL instance - // registered" between their pool reads and both call startNew - // with different distros, leaving the loser stranded. + // Serialize bootstrap and IPC reconciles so concurrent reads cannot register competing WSL instances. const reconcileMutex = yield* Semaphore.make(1); const preflightErrorRef = yield* Ref.make(Option.none()); @@ -136,7 +128,7 @@ export const layer = Layer.effect( Ref.set( preflightErrorRef, Option.some( - "Another T3 Code server is using this distro's T3 home. Stop it, or pair with it instead.", + "Another T3 Code server is using this distro's T3 home, or an older background service is set up for it. Stop that server or pair with it, or try `t3 update` in the distro. If the older launcher cannot update, run `t3 service uninstall` and optionally reinstall with `t3 service install` from a current CLI in the distro. Use `npx t3@latest` if `t3` is missing or outdated, and pass `--base-dir` with the service's T3 home to each command.", ), ), ), @@ -169,11 +161,7 @@ export const layer = Layer.effect( const existing = yield* findExistingWslInstance; const existingId = Option.map(existing, (instance) => instance.id); - // In wsl-only mode the pool's primary IS the WSL backend (see - // DesktopBackendConfiguration.resolvePrimary), so the - // orchestrator skips registering a parallel "wsl:" - // secondary. Without this skip we'd spin up two WSL processes - // on the same distro for users who explicitly asked for one. + // In wsl-only mode WSL is already primary; do not start a second backend on the same distro. const shouldRun = settings.wslBackendEnabled && available && !settings.wslOnly; const targetId = shouldRun ? Option.some(resolveTargetInstanceId(settings.wslDistro)) @@ -210,8 +198,7 @@ export const layer = Layer.effect( } if (Option.isSome(targetId)) { - // Pre-warm the WSL VM before registering so the readiness probe doesn't - // race wsl.exe's first-spawn cold start. + // Pre-warm WSL so readiness cannot race its cold start. yield* wslEnvironment.preWarm(settings.wslDistro); yield* startNew({ distro: settings.wslDistro }); } diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 0224eca440ea6..67549f6b8a54f 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -2,32 +2,16 @@ import { describe, it } from "@effect/vitest"; import { afterAll, expect } from "vite-plus/test"; import * as NodeChildProcess from "node:child_process"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Sink from "effect/Sink"; -import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import { ChildProcessSpawner } from "effect/process"; import { buildWslRuntimeInstallScript, buildWslRuntimeInvalidateScript, buildWslRuntimePruneScript, buildWslRuntimeProbeScript, - DesktopWslDistroListError, - formatMissingToolsReason, - parseNodePath, - parseNodeVersion, parseResolvedPath, - parseToolchainReport, parseWslRuntimeRoot, - probeWslDistros, } from "./DesktopWslEnvironment.ts"; -const encoder = new TextEncoder(); - // The install script only fails the way this file cares about when a real shell // runs it, so find one that has the tools it needs: bash directly on Linux, and // the WSL distro on a Windows dev box, where Git Bash ships no flock. Anywhere @@ -55,8 +39,7 @@ const posixShellRunner = (() => { const runShell = (script: string) => { if (posixShellRunner === null) throw new Error("no POSIX shell runner available"); - // The install script arrives on stdin in production too, which is what lets - // its own /proc scan not match itself. + // Pass the script on stdin, as production does, to avoid matching its own /proc scan. const result = NodeChildProcess.spawnSync( posixShellRunner.file, [...posixShellRunner.args, "-s"], @@ -70,10 +53,7 @@ const sh = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; const awaitHolder = (condition: string) => `i=0; until ${condition}; do i=$((i + 1)); [ "$i" -lt 500 ] || exit 1; sleep 0.01; done`; -// Holds a cache busy the way a running server does: the holder's argv[0] is the -// runtime entry, which the prune and install scripts look for in /proc cmdline. -// It reads a pipe the script keeps open on fd 7, so it exits with the script -// instead of outliving it on a timer. +// Use runtime-entry argv[0] for /proc detection; an open pipe keeps it alive only while this script runs. const holdRuntimeBusy = (entry: string) => [ `exec 7> >(exec -a ${entry} cat >/dev/null 2>&1)`, @@ -94,70 +74,6 @@ const readField = (stdout: string, field: string) => { const SERVER_ENTRY_SOURCE = '#!/bin/sh\necho "t3code wsl runtime test server 0.0.0"\n'; -const makeDistroListSpawner = (result: { readonly stdout?: string; readonly exitCode?: number }) => - ChildProcessSpawner.make(() => - Effect.succeed( - ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(1), - exitCode: - result.exitCode === undefined - ? Effect.never - : Effect.succeed(ChildProcessSpawner.ExitCode(result.exitCode)), - isRunning: Effect.succeed(result.exitCode === undefined), - kill: () => Effect.void, - unref: Effect.succeed(Effect.void), - stdin: Sink.drain, - stdout: Stream.make(encoder.encode(result.stdout ?? "")), - stderr: Stream.empty, - all: Stream.empty, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }), - ), - ); - -describe("probeWslDistros", () => { - it.effect("preserves a successful empty distro list", () => - Effect.gen(function* () { - const distros = yield* probeWslDistros; - expect(distros).toEqual([]); - }).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - makeDistroListSpawner({ stdout: "", exitCode: 0 }), - ), - ), - ); - - it.effect("fails when the distro-list command exits unsuccessfully", () => - Effect.gen(function* () { - const error = yield* probeWslDistros.pipe(Effect.flip); - expect(error).toBeInstanceOf(DesktopWslDistroListError); - expect(error.message).toContain("exited with code 1"); - }).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - makeDistroListSpawner({ exitCode: 1 }), - ), - ), - ); - - it.effect("fails when the distro-list command times out", () => { - const layer = Layer.merge( - TestClock.layer(), - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, makeDistroListSpawner({})), - ); - return Effect.gen(function* () { - const fiber = yield* probeWslDistros.pipe(Effect.flip, Effect.forkScoped); - yield* Effect.yieldNow; - yield* TestClock.adjust(Duration.seconds(8)); - const error = yield* Fiber.join(fiber); - expect(error).toBeInstanceOf(DesktopWslDistroListError); - expect(error.message).toContain("timed out"); - }).pipe(Effect.provide(layer)); - }); -}); - describe("WSL runtime cache", () => { it.each([ [ @@ -172,198 +88,6 @@ describe("WSL runtime cache", () => { expect(script).toContain("/1.2.3_x64__touch__tmp_nope"); expect(script).not.toContain(runtimeId); }); - - it("installs through a temporary directory and only reuses valid completed caches", () => { - const script = buildWslRuntimeInstallScript( - "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz", - "1.2.3-x64", - "b".repeat(64), - ); - - expect(script).toContain('runtime_parent="$HOME/.t3/wsl-runtime"'); - expect(script).toContain(' [ -f "$ready_marker" ] &&'); - expect(script).toContain(' runtime_entry_runs "$runtime_root" &&'); - expect(script).toContain("if runtime_is_ready; then"); - expect(script).not.toContain("bin.mjs"); - expect(script).not.toContain("node-pty"); - expect(script).toContain("trap 'exit 1' HUP INT TERM"); - expect(script).toContain('exec 9> "$runtime_lock"'); - expect(script).toContain("flock -x 9"); - expect(script).not.toContain('rm -rf "$runtime_lock"'); - expect(script).toContain('mv -T "$runtime_root" "$runtime_stale"'); - expect(script).toContain('mktemp -d "$runtime_parent/.1.2.3-x64.tmp.XXXXXX"'); - // The release archive wraps everything in one `t3--linux-x64/` - // directory; stripping it puts the executable at `$runtime_root/t3`. - expect(script).toContain( - "tar -xzf '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' -C \"$runtime_tmp\" --strip-components=1", - ); - expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then'); - expect(script).toContain('mv -T "$runtime_tmp" "$runtime_root"'); - expect(script).not.toContain('rm -rf "$runtime_root"'); - - const lockAcquired = script.indexOf("flock -x 9"); - const readinessAfterLock = script.indexOf("if runtime_is_ready; then", lockAcquired + 1); - const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"'); - expect(lockAcquired).toBeGreaterThan(-1); - expect(readinessAfterLock).toBeGreaterThan(lockAcquired); - expect(existingRuntimeMoved).toBeGreaterThan(readinessAfterLock); - }); - - it("verifies the archive digest before extracting, and only on a cache miss", () => { - const script = buildWslRuntimeInstallScript( - "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz", - "1.2.3-x64", - "b".repeat(64), - ); - - const expected = "b".repeat(64); - expect(script).toContain( - "archive_sha=$(sha256sum '/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz' | cut -d ' ' -f 1)", - ); - expect(script).toContain(`if [ "$archive_sha" != '${expected}' ]; then`); - - const readyShortCircuit = script.indexOf("if runtime_is_ready; then"); - const digestChecked = script.indexOf("archive_sha=$(sha256sum"); - const existingRuntimeMoved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"'); - const extracted = script.indexOf("tar -xzf"); - expect(digestChecked).toBeGreaterThan(readyShortCircuit); - expect(existingRuntimeMoved).toBeGreaterThan(digestChecked); - expect(extracted).toBeGreaterThan(digestChecked); - }); - - it("moves an in-use runtime aside instead of deleting it under a live backend", () => { - const script = buildWslRuntimeInstallScript( - "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz", - "sha256-" + "c".repeat(64), - "b".repeat(64), - ); - - expect(script).toContain('grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null'); - expect(script).toContain(" [ -d /proc/1 ] || return 0"); - expect(script).toContain(' if runtime_in_use "$runtime_root"; then'); - - // A process's cmdline keeps the pre-rename path, so the question is only - // answerable before the move. - const inUseChecked = script.indexOf('if runtime_in_use "$runtime_root"; then'); - const moved = script.indexOf('mv -T "$runtime_root" "$runtime_stale"'); - expect(inUseChecked).toBeGreaterThan(-1); - expect(inUseChecked).toBeLessThan(moved); - - const kept = script.indexOf('touch "$runtime_stale"'); - const deleted = script.indexOf('rm -rf "$runtime_stale"'); - expect(kept).toBeGreaterThan(moved); - expect(deleted).toBeGreaterThan(kept); - }); - - it("treats a runtime whose executable no longer runs as a cache miss", () => { - const script = buildWslRuntimeInstallScript( - "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz", - "1.2.3-x64", - "b".repeat(64), - ); - - expect(script).toContain(' [ -x "$1/t3" ] && "$1/t3" --version >/dev/null 2>&1'); - - const entryCheckDefined = script.indexOf("runtime_entry_runs() {"); - const readinessDefined = script.indexOf("runtime_is_ready() {"); - const readyShortCircuit = script.indexOf("if runtime_is_ready; then"); - expect(entryCheckDefined).toBeGreaterThan(-1); - expect(entryCheckDefined).toBeLessThan(readinessDefined); - expect(readinessDefined).toBeLessThan(readyShortCircuit); - }); - - it("re-hashes the executable against the digest the install recorded", () => { - const script = buildWslRuntimeInstallScript( - "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz", - "1.2.3-x64", - "b".repeat(64), - ); - - expect(script).toContain(` sha256sum "$1/t3" 2>/dev/null | cut -d ' ' -f 1`); - expect(script).toContain( - ' [ "$recorded_entry_digest" = "$(runtime_server_entry_digest "$runtime_root")" ]', - ); - expect(script).toContain(' [ -n "$recorded_entry_digest" ] &&'); - expect(script).toContain( - `printf '%s\\n' "$installed_entry_digest" > "$runtime_tmp/.t3code-wsl-runtime-ready"`, - ); - - const extracted = script.indexOf("tar -xzf"); - const digestRecorded = script.indexOf( - 'installed_entry_digest=$(runtime_server_entry_digest "$runtime_tmp")', - ); - const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"'); - const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"'); - expect(digestRecorded).toBeGreaterThan(extracted); - expect(markerWritten).toBeGreaterThan(digestRecorded); - expect(promoted).toBeGreaterThan(markerWritten); - }); - - it("refuses to mark an archive whose executable does not run as ready", () => { - const script = buildWslRuntimeInstallScript( - "/mnt/c/Program Files/T3 Code/wsl-runtime.tar.gz", - "1.2.3-x64", - "b".repeat(64), - ); - - expect(script).toContain('if ! runtime_entry_runs "$runtime_tmp"; then'); - - const payloadValidated = script.indexOf('runtime_entry_runs "$runtime_tmp"'); - const markerWritten = script.indexOf('> "$runtime_tmp/.t3code-wsl-runtime-ready"'); - const promoted = script.indexOf('mv -T "$runtime_tmp" "$runtime_root"'); - expect(payloadValidated).toBeGreaterThan(-1); - expect(markerWritten).toBeGreaterThan(payloadValidated); - expect(promoted).toBeGreaterThan(payloadValidated); - }); - - it("parses only absolute Linux runtime paths", () => { - expect(parseWslRuntimeRoot("runtimeRoot:/home/josh/.t3/wsl-runtime/1.2.3-x64\n")).toBe( - "/home/josh/.t3/wsl-runtime/1.2.3-x64", - ); - expect(parseWslRuntimeRoot("runtimeRoot:relative/path\n")).toBeNull(); - expect(parseWslRuntimeRoot("noise\n")).toBeNull(); - }); - - it("prunes completed runtimes except the current and newest previous cache", () => { - const script = buildWslRuntimePruneScript("1.2.3/x64"); - - expect(script).toContain('current_runtime="$runtime_parent/1.2.3_x64"'); - expect(script).toContain('[ "$candidate" -nt "$previous_runtime" ]'); - expect(script).toContain('[ "$candidate" != "$current_runtime" ] || continue'); - expect(script).toContain('[ "$candidate" != "$previous_runtime" ] || continue'); - expect(script).toContain('[ -f "$candidate/.t3code-wsl-runtime-ready" ] || continue'); - expect(script).toContain('rm -rf -- "$candidate"'); - }); - - it("never deletes a runtime another backend is running from", () => { - const script = buildWslRuntimePruneScript("1.2.3/x64"); - - expect(script).toContain(' grep -qF -- "$1/" /proc/[0-9]*/cmdline 2>/dev/null'); - expect(script).toContain(' ! runtime_in_use "$candidate" || continue'); - - expect(script).toContain("[ -d /proc/1 ] || exit 0"); - - const inUseChecked = script.indexOf('! runtime_in_use "$candidate"'); - const removed = script.indexOf('rm -rf -- "$candidate"'); - expect(inUseChecked).toBeGreaterThan(-1); - expect(removed).toBeGreaterThan(inUseChecked); - }); - - it("sweeps orphaned install scratch directories the ready-marker loops cannot see", () => { - const script = buildWslRuntimePruneScript("1.2.3/x64"); - - expect(script).toContain( - 'for scratch in "$runtime_parent"/.*.tmp.* "$runtime_parent"/.*.stale.*; do', - ); - expect(script).toContain('find "$scratch" -maxdepth 0 -mmin +120'); - }); - - it("invalidates a cache by dropping its ready marker, not the tree", () => { - const script = buildWslRuntimeInvalidateScript("1.2.3/x64"); - - expect(script).toContain('rm -f "$HOME/.t3/wsl-runtime/1.2.3_x64/.t3code-wsl-runtime-ready"'); - expect(script).not.toContain("rm -rf"); - }); }); describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed)", () => { @@ -374,14 +98,14 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed fixtures.length = 0; }); - const createFixture = () => { + const createFixture = (serverEntry = SERVER_ENTRY_SOURCE) => { const result = runShell( [ "set -eu", "work=$(mktemp -d)", 'stage="$work/stage/t3-0.0.0-linux-x64"', 'mkdir -p "$stage/node_modules/node-pty/build/Release" "$work/home"', - `printf '%s' ${sh(SERVER_ENTRY_SOURCE)} > "$stage/t3"`, + `printf '%s' ${sh(serverEntry)} > "$stage/t3"`, 'chmod +x "$stage/t3"', `printf '%s' 'pty-native-payload' > "$stage/node_modules/node-pty/build/Release/pty.node"`, `tar -czf "$work/wsl-runtime.tar.gz" -C "$work/stage" t3-0.0.0-linux-x64`, @@ -396,8 +120,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed const archivePath = `${work}/wsl-runtime.tar.gz`; const archiveSha = readField(result.stdout, "archiveSha"); const runtimeId = `sha256-${archiveSha}`; - // The script reads $HOME, and WSL does not inherit the parent process's - // environment, so the home override rides in the script itself. + // WSL does not inherit HOME; embed the fixture's override in the script. const installScript = (archive = archivePath, sha = archiveSha) => [ `HOME=${sh(`${work}/home`)}`, @@ -459,16 +182,6 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(provider.stdout).toBe("linux-node-provider\n"); }); - it("keeps standalone runtime readiness independent of Node availability", () => { - const fixture = createFixture(); - expect(fixture.install().status).toBe(0); - - const probe = probeFixture(fixture); - - expect(probe.status, probe.stderr).toBe(0); - expect(parseResolvedPath(probe.stdout)).not.toBeNull(); - }); - it("keeps the inherited PATH when bash is unavailable", () => { const fixture = createFixture(); expect(fixture.install().status).toBe(0); @@ -495,6 +208,18 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(parseWslRuntimeRoot(warm.stdout)).toBe(fixture.runtimeRoot); }); + it("retains the loader error when a bundled executable needs a missing system library", () => { + const fixture = createFixture( + '#!/bin/sh\nprintf "error while loading shared libraries: libatomic.so.1: cannot open shared object file\\n" >&2\nexit 127\n', + ); + + const result = fixture.install(); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("libatomic.so.1"); + expect(parseWslRuntimeRoot(result.stdout)).toBeNull(); + }); + it("reinstalls a cache whose executable was truncated", () => { const fixture = createFixture(); expect(fixture.install().status).toBe(0); @@ -508,6 +233,28 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(restored.stdout).toBe(SERVER_ENTRY_SOURCE); }); + it("reinstalls an executable that fails --version despite a matching recorded digest", () => { + const fixture = createFixture(); + expect(fixture.install().status).toBe(0); + const brokenEntry = "#!/bin/sh\nexit 42\n"; + const corrupt = runShell( + [ + "set -eu", + `printf '%s' ${sh(brokenEntry)} > ${sh(fixture.serverEntry)}`, + `chmod +x ${sh(fixture.serverEntry)}`, + `sha256sum ${sh(fixture.serverEntry)} | cut -d ' ' -f 1 > ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-ready`)}`, + ].join("\n"), + ); + expect(corrupt.status, corrupt.stderr).toBe(0); + expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(42); + + const repaired = fixture.install(); + expect(repaired.status, repaired.stderr).toBe(0); + expect(parseWslRuntimeRoot(repaired.stdout)).toBe(fixture.runtimeRoot); + expect(runShell(`cat ${sh(fixture.serverEntry)}`).stdout).toBe(SERVER_ENTRY_SOURCE); + expect(runShell(`${sh(fixture.serverEntry)} --version`).status).toBe(0); + }); + it("falls back instead of launching a corrupted cache it cannot reinstall", () => { const fixture = createFixture(); expect(fixture.install().status).toBe(0); @@ -536,8 +283,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed `cat > "$work/install.sh" <<'T3CODE_INSTALL_SCRIPT'`, fixture.installScript(), "T3CODE_INSTALL_SCRIPT", - // Both racers run the same file, and neither file path contains the - // runtime root, so the script's own /proc scan cannot see them. + // Keep runtime roots out of both racers' argv so their /proc scans cannot match themselves. 'sh "$work/install.sh" > "$work/first.out" 2>&1 &', "first=$!", 'sh "$work/install.sh" > "$work/second.out" 2>&1 &', @@ -626,53 +372,6 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(selected.status, `${selected.stdout}\n${selected.stderr}`).toBe(0); }); - it("prunes a selected cache after its prepare-to-spawn grace period expires", () => { - const fixture = createFixture(); - expect(fixture.install().status).toBe(0); - const result = runShell( - [ - "set -eu", - `runtime_parent=${sh(fixture.runtimeParent)}`, - 'mkdir -p "$runtime_parent/sha256-current" "$runtime_parent/sha256-previous"', - 'printf ready > "$runtime_parent/sha256-current/.t3code-wsl-runtime-ready"', - 'printf ready > "$runtime_parent/sha256-previous/.t3code-wsl-runtime-ready"', - `touch -d "10 minutes ago" ${sh(fixture.runtimeRoot)}`, - `touch -d "10 minutes ago" ${sh(`${fixture.runtimeRoot}/.t3code-wsl-runtime-selected`)}`, - 'touch -d "1 minute ago" "$runtime_parent/sha256-previous"', - `HOME=${sh(`${fixture.work}/home`)}`, - "export HOME", - buildWslRuntimePruneScript("sha256-current"), - `test ! -e ${sh(fixture.runtimeRoot)}`, - ].join("\n"), - ); - - expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); - }); - - it("removes an aged stale tree after replacing an active unready cache", () => { - const fixture = createFixture(); - expect(fixture.install().status).toBe(0); - const result = runShell( - [ - "set -eu", - `runtime_root=${sh(fixture.runtimeRoot)}`, - `runtime_parent=${sh(fixture.runtimeParent)}`, - 'rm "$runtime_root/.t3code-wsl-runtime-ready"', - holdRuntimeBusy('"$runtime_root/t3"'), - fixture.installScript(), - 'stale=$(find "$runtime_parent" -maxdepth 1 -type d -name ".sha256-*.stale.*" -print -quit)', - 'test -n "$stale"', - 'touch -d "180 minutes ago" "$stale"', - `HOME=${sh(`${fixture.work}/home`)}`, - "export HOME", - buildWslRuntimePruneScript(fixture.runtimeId), - 'test ! -e "$stale"', - ].join("\n"), - ); - - expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); - }); - it("prunes old and markerless caches without touching retained, active, locked, or unrelated roots", () => { const result = runShell( [ @@ -712,78 +411,6 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed }); }); -describe("parseToolchainReport", () => { - it("returns no missing tools and no node version on empty output", () => { - expect(parseToolchainReport("")).toEqual({ missingTools: [], nodeVersion: null }); - }); - - it("collects all missing: lines", () => { - const stdout = ["missing:make", "missing:g++", "nodeVersion:24.10.0"].join("\n"); - expect(parseToolchainReport(stdout)).toEqual({ - missingTools: ["make", "g++"], - nodeVersion: "24.10.0", - }); - }); - - it("ignores blank lines and trims whitespace", () => { - const stdout = [" missing:python3 ", "", " nodeVersion:v22.16.0 "].join("\n"); - expect(parseToolchainReport(stdout)).toEqual({ - missingTools: ["python3"], - nodeVersion: "v22.16.0", - }); - }); - - it("returns null node version when value after prefix is empty", () => { - expect(parseToolchainReport("nodeVersion:")).toEqual({ - missingTools: [], - nodeVersion: null, - }); - }); -}); - -describe("parseNodePath", () => { - it("extracts the absolute node path from a nodePath: line", () => { - const stdout = "nodePath:/home/josh/.nvm/versions/node/v22.16.0/bin/node"; - expect(parseNodePath(stdout)).toBe("/home/josh/.nvm/versions/node/v22.16.0/bin/node"); - }); - - it("returns null when node was not found (empty value after prefix)", () => { - expect(parseNodePath("nodePath:")).toBeNull(); - }); - - it("returns null when there is no nodePath line at all", () => { - expect(parseNodePath("missing:node\nnodeVersion:")).toBeNull(); - }); - - it("ignores surrounding noise and trims whitespace", () => { - const stdout = ["some preamble noise", " nodePath:/usr/bin/node ", "trailing"].join("\n"); - expect(parseNodePath(stdout)).toBe("/usr/bin/node"); - }); -}); - -describe("parseNodeVersion", () => { - it("extracts the node version from a nodeVersion: line", () => { - expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0"); - }); - - it("returns null when the version value is empty", () => { - expect(parseNodeVersion("nodeVersion:")).toBeNull(); - }); - - it("returns null when there is no nodeVersion line at all", () => { - expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull(); - }); - - it("ignores surrounding noise and trims whitespace", () => { - const stdout = [ - "some preamble noise", - " nodeVersion:22.16.0 ", - "nodePath:/usr/bin/node", - ].join("\n"); - expect(parseNodeVersion(stdout)).toBe("22.16.0"); - }); -}); - describe("parseResolvedPath", () => { it("preserves spaces and apostrophes in the resolved login-shell PATH", () => { const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin"; @@ -797,52 +424,4 @@ describe("parseResolvedPath", () => { "/usr/local/bin:/usr/bin", ); }); - - it("returns null when the resolved PATH is absent or empty", () => { - expect(parseResolvedPath("nodePath:/usr/bin/node\n")).toBeNull(); - expect(parseResolvedPath("resolvedPath:\n")).toBeNull(); - }); -}); - -describe("formatMissingToolsReason", () => { - it("returns null when everything is present and node is in range", () => { - expect( - formatMissingToolsReason({ missingTools: [], nodeVersion: "24.10.0" }, "^24.10"), - ).toBeNull(); - }); - - it("returns null when range is not specified and tools are present", () => { - expect(formatMissingToolsReason({ missingTools: [], nodeVersion: "18.0.0" }, null)).toBeNull(); - }); - - it("flags missing node first", () => { - const reason = formatMissingToolsReason( - { missingTools: ["node", "make"], nodeVersion: null }, - "^24.10", - ); - expect(reason).toContain("node"); - expect(reason).toContain("^24.10"); - expect(reason).toContain("make"); - expect(reason).toContain("nvm"); - }); - - it("flags an out-of-range node version with the actual version surfaced", () => { - const reason = formatMissingToolsReason( - { missingTools: [], nodeVersion: "20.0.0" }, - "^24.10 || ^22.16", - ); - expect(reason).toContain("node 20.0.0"); - expect(reason).toContain("requires ^24.10 || ^22.16"); - }); - - it("flags missing build tools without node when node is fine", () => { - const reason = formatMissingToolsReason( - { missingTools: ["g++", "python3"], nodeVersion: "24.10.0" }, - "^24.10", - ); - expect(reason).toContain("g++"); - expect(reason).toContain("python3"); - expect(reason).toContain("build-essential"); - expect(reason).not.toContain("nvm"); - }); }); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 7e00f1b40ad18..5017793d07357 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -17,7 +17,8 @@ import { parseWslDistroList, type WslDistro } from "./wslPathParsing.ts"; const PROCESS_TERMINATE_GRACE = Duration.seconds(1); const LIST_TIMEOUT = Duration.seconds(8); -const PRE_WARM_TIMEOUT = Duration.seconds(10); +// Booting a stopped distro needs more time than converting paths in a running one. +const PRE_WARM_TIMEOUT = Duration.seconds(30); const WSLPATH_TIMEOUT = Duration.seconds(10); const PROBE_TIMEOUT = Duration.seconds(10); const TOOLCHAIN_TIMEOUT = Duration.seconds(10); @@ -88,9 +89,7 @@ export class DesktopWslEnvironment extends Context.Service< DesktopWslEnvironment, { readonly isAvailable: Effect.Effect; - // Best-effort enumeration for renderer UX. Backend health checks must use - // probeDistros so a transient command failure is not mistaken for a - // successful empty installation. + // UX-only best effort; health checks need probeDistros to distinguish failures from an empty installation. readonly listDistros: Effect.Effect; readonly probeDistros: Effect.Effect; readonly preWarm: (distro: string | null) => Effect.Effect; @@ -99,11 +98,7 @@ export class DesktopWslEnvironment extends Context.Service< windowsPath: string, ) => Effect.Effect>; readonly getUserHome: (distro: string | null) => Effect.Effect>; - // The orchestrator uses this for the WSL backend's httpBaseUrl so the - // renderer can reach it without relying on wslhost's localhost→WSL - // automatic forwarding, which is flaky in practice (the backend can be - // listening for 30+ seconds before wslhost starts forwarding 127.0.0.1:port - // to WSL-side localhost). + // Use the distro IP to avoid unreliable wslhost localhost forwarding. readonly getDistroIp: (distro: string | null) => Effect.Effect>; readonly prepareRuntime: ( distro: string | null, @@ -176,8 +171,7 @@ const buildWslNodeEnvPreamble = ( ensure_remote_node_path || true `; -// wsl.exe re-escapes args before forwarding them to the Linux side, which -// mangles quotes inside `bash -lc " ", + ); + yield* htmlRender.prepare(``); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("inlines an SVG behind processing instructions and a doctype subset", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -196,10 +189,22 @@ describe("HtmlRender", () => { const fileSystem = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const htmlRender = yield* HtmlRender.HtmlRender; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const threadId = ThreadId.make("thread-html-render"); + const session = { + environmentId: EnvironmentId.make("html-render-environment"), + threadId, + providerSessionId: "first-credential", + providerInstanceId: ProviderInstanceId.make("claude"), + endpoint: "http://localhost:8311/mcp", + authorizationHeader: "Bearer first-token", + browserToolsAvailable: false, + }; + yield* mcpSessions.set(session); const reference = yield* htmlRender.publish({ - threadId: ThreadId.make("thread-html-render"), - html: "

Quarterly revenue

", + threadId, + html: `

Quarterly revenue

${" ".repeat(8_000)}`, title: " Revenue ", height: 9_000, }); @@ -217,32 +222,62 @@ describe("HtmlRender", () => { const html = yield* fileSystem.readFileString(stored ?? ""); expect(html).toContain('", + "

The moon garden opens at dusk

", + '', ].join(""), - width: 400, - appearance: "dark", }); - - const png = Buffer.from(preview.png, "base64"); - expect(png.readUInt32BE(0)).toBe(0x89504e47); - expect([png.readUInt32BE(16), png.readUInt32BE(20)]).toEqual([400, 300]); - expect(preview).toMatchObject({ - width: 400, - contentHeight: 300, - capturedHeight: 300, - missingImages: ["/nonexistent/t3-missing.png"], + expect(preview.consoleMessages).toContainEqual({ + level: "log", + text: appearance === "light" ? "false rgb(24, 24, 27)" : "true rgb(250, 250, 250)", }); - // Headless Chrome prefers light, so a dark background proves the theme fragment applied. - expect(preview.consoleMessages).toEqual( - expect.arrayContaining([ - { level: "log", text: "ready 3" }, - { level: "log", text: "focus 2px -2px 400 400" }, - { level: "info", text: HTML_RENDER_MEASURE_FONTS.sans }, - { - level: "warning", - text: htmlRenderTheme(T3_CODE_DARK_THEME_COLORS, "dark").variables["--background"], - }, - { level: "error", text: "boom" }, - { - level: "error", - text: expect.stringMatching(/^Error: broken chart\n\s+at page\.html:1:\d+$/), - }, - ]), - ); - }).pipe(Effect.provide(layerHtmlRender(executable))); - }), - 30_000, + } + }).pipe(Effect.provide(layerHtmlRender(executable))); + }), ); - it.live( - "keeps every local file but the page itself out of the browser", - (ctx) => - Effect.gen(function* () { - const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; - if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`); - yield* Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const htmlRender = yield* HtmlRender.HtmlRender; - const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" }); - const secret = path.join(directory, "secret.js"); - yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";'); - const secretUrl = NodeURL.pathToFileURL(secret).href; - - const preview = yield* htmlRender.preview({ - html: [ - ``, - ``, - '', - ].join(""), - }); - - const texts = preview.consoleMessages.map((message) => message.text); - expect(texts).toContain("secret: none"); - expect(texts.join(" ")).not.toContain("abc123"); - }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable))); - }), - 30_000, + it.live("keeps every local file but the page itself out of the browser", (ctx) => + Effect.gen(function* () { + const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; + if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`); + yield* Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const htmlRender = yield* HtmlRender.HtmlRender; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-html-files-" }); + const secret = path.join(directory, "secret.js"); + yield* fileSystem.writeFileString(secret, 'window.secret = "abc123";'); + const secretUrl = NodeURL.pathToFileURL(secret).href; + + const preview = yield* htmlRender.preview({ + html: [ + ``, + ``, + '', + ].join(""), + }); + + const texts = preview.consoleMessages.map((message) => message.text); + expect(texts).toContain("secret: none"); + expect(texts.join(" ")).not.toContain("abc123"); + }).pipe(Effect.scoped, Effect.provide(layerHtmlRender(executable))); + }), ); - it.live( - "keeps the page off this machine's local network", - (ctx) => - Effect.gen(function* () { - const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; - if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`); - const requests: Array = []; - const server = yield* Effect.acquireRelease( - Effect.callback((resume) => { - const listening = NodeHttp.createServer((request, response) => { - requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`); - response.end("

LOCAL

"); - }); - listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening))); + it.live("keeps the page off this machine's local network", (ctx) => + Effect.gen(function* () { + const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; + if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`); + const requests: Array = []; + const server = yield* Effect.acquireRelease( + Effect.callback((resume) => { + const listening = NodeHttp.createServer((request, response) => { + requests.push(`${request.url} ${request.headers["sec-purpose"] ?? ""}`); + response.end("

LOCAL

"); + }); + listening.listen(0, "127.0.0.1", () => resume(Effect.succeed(listening))); + }), + (listening) => + Effect.callback((resume) => { + listening.close(() => resume(Effect.void)); }), - (listening) => - Effect.callback((resume) => { - listening.close(() => resume(Effect.void)); - }), - ); - const datagrams: Array = []; - const udp = yield* Effect.acquireRelease( - Effect.callback((resume) => { - const socket = NodeDgram.createSocket("udp4"); - socket.on("message", (message) => datagrams.push(message.toString("hex"))); - socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket))); + ); + const datagrams: Array = []; + const udp = yield* Effect.acquireRelease( + Effect.callback((resume) => { + const socket = NodeDgram.createSocket("udp4"); + socket.on("message", (message) => datagrams.push(message.toString("hex"))); + socket.bind(0, "127.0.0.1", () => resume(Effect.succeed(socket))); + }), + (socket) => + Effect.callback((resume) => { + socket.close(() => resume(Effect.void)); }), - (socket) => - Effect.callback((resume) => { - socket.close(() => resume(Effect.void)); - }), - ); - const address = server.address(); - const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`; - const stun = `stun:127.0.0.1:${udp.address().port}`; - yield* Effect.gen(function* () { - const htmlRender = yield* HtmlRender.HtmlRender; - yield* htmlRender.preview({ - html: [ - ``, - ``, - ``, - ].join(""), - }); - }).pipe(Effect.provide(layerHtmlRender(executable))); - expect(requests).toEqual([]); - expect(datagrams).toEqual([]); - }).pipe(Effect.scoped), - 30_000, - ); - - it.live( - "measures a published page at every client width with a fresh load each", - (ctx) => - Effect.gen(function* () { - const executable = (yield* HostProcess.Environment)[TEST_BROWSER_ENV]; - if (!executable) return ctx.skip(`Set ${TEST_BROWSER_ENV} to run this test.`); - yield* Effect.gen(function* () { - const htmlRender = yield* HtmlRender.HtmlRender; - const reference = yield* htmlRender.publish({ - threadId: ThreadId.make("thread-html-measure"), - html: '
', - title: "Chart", - height: 600, - }); - - expect(reference.heights).toEqual( - HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]), - ); - expect(reference.outline).toBe("m0,0,182,91,1"); - }).pipe(Effect.provide(layerHtmlRender(executable))); - }), - 30_000, + ); + const address = server.address(); + const origin = `http://127.0.0.1:${typeof address === "object" && address ? address.port : 0}`; + const stun = `stun:127.0.0.1:${udp.address().port}`; + yield* Effect.gen(function* () { + const htmlRender = yield* HtmlRender.HtmlRender; + yield* htmlRender.preview({ + html: [ + ``, + ``, + ``, + ].join(""), + }); + }).pipe(Effect.provide(layerHtmlRender(executable))); + expect(requests).toEqual([]); + expect(datagrams).toEqual([]); + }).pipe(Effect.scoped), ); }); diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.ts index e927bd56a1977..44ea627ceab72 100644 --- a/apps/server/src/htmlRender/HtmlRender.ts +++ b/apps/server/src/htmlRender/HtmlRender.ts @@ -1,4 +1,5 @@ import type { ThreadId } from "@t3tools/contracts"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { clampHtmlRenderHeight, @@ -67,6 +68,31 @@ export class HtmlRenderPageTooLargeError extends Schema.TaggedError()( + "HtmlRenderViewportHeightError", + { found: Schema.String }, +) { + override get message(): string { + return `The page uses a viewport height unit (${this.found}). The frame grows to fit the page, so a size that follows the viewport makes it grow again and again. Let content set the height, or use fixed pixel heights.`; + } +} + +// Check only stylesheets and style attributes, even inside scripts; skip comments whole. +// Consume unclosed comments, tags, or quotes through EOF to keep both patterns linear. +const CSS_SOURCE = + /|$)|]*(?:>|$)([\s\S]*?)(?:<\/style\s*>|$)|\sstyle\s*=\s*(?:"([^"]*)(?:"|$)|'([^']*)(?:'|$)|([^\s>]+))/gi; +// The lookbehind skips base64 runs, such as an inlined image that happens to contain "1vh". +const VIEWPORT_HEIGHT_UNIT = /(? { + for (const [, sheet, doubleQuoted, singleQuoted, unquoted] of html.matchAll(CSS_SOURCE)) { + const css = sheet ?? doubleQuoted ?? singleQuoted ?? unquoted ?? ""; + const found = VIEWPORT_HEIGHT_UNIT.exec(css)?.[0]; + if (found !== undefined) return Effect.fail(new HtmlRenderViewportHeightError({ found })); + } + return Effect.void; +}; + export class HtmlRenderStoreError extends Schema.TaggedError()( "HtmlRenderStoreError", { cause: Schema.Defect() }, @@ -79,7 +105,8 @@ export class HtmlRenderStoreError extends Schema.TaggedError const latin1 = (bytes: Uint8Array, start: number, end: number) => String.fromCharCode(...bytes.subarray(start, end)); -/** - * Whether file bytes are an image, whatever the file is named, so a symlink or - * renamed file cannot carry other data, such as a secret, into a page. - */ +// Validate bytes, not filenames, so renamed files or symlinks cannot inline secrets. const isImageBytes = (bytes: Uint8Array) => { const head = latin1(bytes, 0, 12); if ( @@ -242,8 +266,7 @@ const inlineLocalImages = Effect.fn("HtmlRender.inlineLocalImages")(function* (h if (pageBytes > MAX_PAGE_BYTES) { return yield* new HtmlRenderPageTooLargeError({ sizeBytes: pageBytes }); } - // Files can grow after `stat`. Each read stops one byte past the image - // limit, and reading stops once the images read so far cannot fit the page. + // Files can grow after stat; bound each read and stop when accumulated images cannot fit. let readBytes = 0; const images = yield* Effect.forEach( files.filter((file) => file.size !== undefined), @@ -310,12 +333,12 @@ const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const previewBrowser = yield* PreviewBrowser.PreviewBrowser; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const services = yield* Effect.context< FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner >(); const browsers = yield* Semaphore.make(MAX_CONCURRENT_BROWSERS); - // Chrome's sandbox stays on unless the operator explicitly turns it off. - // Chrome also refuses it as root, where that opt-out is the only way to run. + // Keep Chrome sandboxed unless explicitly disabled; root must opt out to run. const noSandbox = PreviewBrowserHost.sandboxDisabled(yield* HostProcess.Environment); const setupCommand = yield* resolveRootCliCommand(PreviewBrowserHost.SETUP_SUBCOMMAND); @@ -341,11 +364,11 @@ const make = Effect.gen(function* () { ), ); - const measure = (html: string) => - Effect.gen(function* () { + const measure = Effect.fn("HtmlRender.measure")( + function* (html: string) { const executable = yield* previewBrowser.installed; if (Option.isNone(executable)) return undefined; - const { heights, outline } = yield* launching(executable.value, (noSandbox) => + const heights = yield* launching(executable.value, (noSandbox) => HeadlessChrome.measureHtmlHeights({ executable: executable.value, noSandbox, @@ -364,21 +387,21 @@ const make = Effect.gen(function* () { ), }), ); - return { heights: heights.toSorted(([left], [right]) => left - right), outline }; - }).pipe( - Effect.catch((cause) => - Effect.logWarning("Could not measure an HTML render; publishing it without heights.", { - cause, - }).pipe(Effect.as(undefined)), - ), - Effect.withSpan("HtmlRender.measure"), - ); + return heights.toSorted(([left], [right]) => left - right); + }, + Effect.catch((cause) => + Effect.logWarning("Could not measure an HTML render; publishing it without heights.", { + cause, + }).pipe(Effect.as(undefined)), + ), + ); // The bootstrap goes in first so its head scan never runs over inlined image data. const inline = (html: string) => inlineLocalImages(injectHtmlRenderBootstrap(html)).pipe(Effect.provideContext(services)); const prepare = Effect.fn("HtmlRender.prepare")(function* (html: string) { + yield* rejectViewportHeight(html); const inlined = yield* inline(html); if (inlined.missing.length > 0) { return yield* new HtmlRenderImagesNotFoundError({ paths: inlined.missing }); @@ -405,20 +428,35 @@ const make = Effect.gen(function* () { if (attachmentId === null || filePath === null) { return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") }); } - const measured = yield* fileSystem.writeFileString(filePath, html).pipe( - Effect.mapError((cause) => new HtmlRenderStoreError({ cause })), - Effect.andThen(measure(html)), - // Only the returned reference lets thread deletion find the page, so a - // publish that fails or is interrupted before returning removes it. - Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore)), - ); - return { + const baseReference: HtmlRenderReference = { attachmentId, title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML", height: clampHtmlRenderHeight(input.height), - ...(measured === undefined ? {} : { heights: measured.heights }), - ...(measured?.outline === undefined ? {} : { outline: measured.outline }), - } satisfies HtmlRenderReference; + }; + return yield* fileSystem.writeFileString(filePath, html).pipe( + Effect.mapError((cause) => new HtmlRenderStoreError({ cause })), + Effect.uninterruptible, + Effect.andThen(measure(html)), + Effect.andThen((heights) => { + const reference: HtmlRenderReference = { + ...baseReference, + ...(heights === undefined ? {} : { heights }), + }; + return mcpSessions + .recordHtmlRender(input.threadId, input, reference) + .pipe(Effect.as(reference)); + }), + // An interrupted publish must leave neither an attachment nor a recoverable reference. + Effect.onError(() => + Effect.all( + [ + fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore), + mcpSessions.takeHtmlRender(input.threadId, input, baseReference).pipe(Effect.ignore), + ], + { discard: true }, + ), + ), + ); }); const preview = Effect.fn("HtmlRender.preview")(function* (input: { @@ -431,6 +469,7 @@ const make = Effect.gen(function* () { Math.max(MIN_PREVIEW_WIDTH, Math.round(input.width ?? HTML_RENDER_COLUMN_WIDTH)), ); const appearance = input.appearance ?? "dark"; + yield* rejectViewportHeight(input.html); const inlined = yield* inline(input.html); const executable = yield* previewBrowser.executable; const theme = htmlRenderTheme( @@ -445,6 +484,7 @@ const make = Effect.gen(function* () { html: inlined.html, width, urlFragment: htmlRenderThemeFragment(theme), + appearance, }).pipe(Effect.provideContext(services)), ); return { diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.ts index 5c36cbb1d4d64..5562d43826c76 100644 --- a/apps/server/src/htmlRender/headlessChrome.ts +++ b/apps/server/src/htmlRender/headlessChrome.ts @@ -1,3 +1,4 @@ +import type { ThemeAppearance } from "@t3tools/shared/themePalettes"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -9,11 +10,6 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; -import { - encodeHtmlRenderOutline, - HTML_RENDER_COLUMN_WIDTH, - HTML_RENDER_OUTLINE_MAX_BOXES, -} from "@t3tools/shared/htmlRender"; import { publicProxy } from "./publicProxy.ts"; @@ -50,14 +46,8 @@ const MAX_CONSOLE_TEXT_CHARS = 500; const VIEWPORT_HEIGHT = 800; const MAX_CAPTURE_HEIGHT = 4_000; const CAPTURE_TIMEOUT = "20 seconds"; -// Chrome refuses local files to every web page, frame, worker, and popup, so a -// page cannot read files the agent's provider withholds; local images reach it -// already inlined as data URIs. `.localhost` keeps it a secure context that may -// still load plain-http resources, and the request never leaves the browser. -// All of the browser's traffic goes through `publicProxy`, which only reaches -// public addresses, so a page cannot reach this machine's local network. The -// main frame also stays on the page and the browser opens no popups, so a -// capture always shows the page itself. +// Chrome blocks file access; images arrive inlined. Browser-only .localhost permits secure contexts and HTTP resources. +// publicProxy blocks local networks; pinning the main frame and forbidding popups keeps captures on the page. const PAGE_ORIGIN = "http://t3-page.localhost"; const PAGE_URL = `${PAGE_ORIGIN}/page.html`; const PAGE_NAME = "page.html"; @@ -65,9 +55,7 @@ const MEASURE_CONCURRENCY = 3; const textEncoder = new TextEncoder(); -/** - * Node's encoder, since pages run to 25 MiB. - */ +// Pages reach 25 MiB; use Node's encoder. const pageBody = (html: string) => Buffer.from(Buffer.from(html, "utf8").toString("base64"), "latin1"); @@ -156,92 +144,13 @@ const consoleMessageFromEvent = (method: string, params: unknown): ConsoleMessag return undefined; }; -// Resolves after web fonts load and two frames paint, so late layout lands in the capture. +// Wait for fonts and two paint frames to capture late layout. const SETTLE_EXPRESSION = "document.fonts.ready.then(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)))))"; -// The root's scroll height never drops below the viewport, so a short page -// reports its own box height instead. +// scrollHeight is at least viewport height; use the root box for shorter pages. const MEASURE_EXPRESSION = "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()"; -const OUTLINE_MAX_VISITS = 2_000; -const OUTLINE_EXPRESSION = `(() => { - const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES}; - const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button"; - const pageBackground = getComputedStyle(document.documentElement).backgroundColor; - const filled = (s) => (s.backgroundColor !== "rgba(0, 0, 0, 0)" && s.backgroundColor !== pageBackground) || s.backgroundImage !== "none" || parseFloat(s.borderTopWidth) + parseFloat(s.borderBottomWidth) + parseFloat(s.borderLeftWidth) > 0; - const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]); - const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20))); - // Text's own extent, so a short heading in a wide block stays short. - const addText = (el, s, r) => { - const range = document.createRange(); - range.selectNodeContents(el); - const t = range.getBoundingClientRect(); - const box = t.width >= 2 && t.height >= 2 ? t : r; - add("text", box, lineCount(s, box)); - }; - // Visits are capped too, so a huge generated DOM costs no more than a page. - let full = false, visits = 0; - // Whether an element holds text of its own, looking at its first few children only. - const hasOwnText = (el) => { - let n = el.firstChild; - for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true; - return false; - }; - const walk = (parent, ps) => { - for (const el of parent.childNodes) { - // The last slot is kept for whatever the outline has no room left for. - if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; } - // Bare text only reaches here under body or a display: contents element. - if (el.nodeType === 3) { - if (el.data.trim() === "") continue; - const range = document.createRange(); - range.selectNodeContents(el); - const t = range.getBoundingClientRect(); - if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t)); - continue; - } - if (el.nodeType !== 1) continue; - const s = getComputedStyle(el); - if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue; - if (s.display === "contents") { walk(el, s); continue; } - const r = el.getBoundingClientRect(); - // A zero-size box can still show positioned children, unless it clips them. - if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; } - const tag = el.localName; - if (el.matches(media)) { add("media", r, 1); continue; } - if (tag === "table") { add("table", r, el.rows.length); continue; } - const text = hasOwnText(el); - if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; } - if (text) { addText(el, s, r); continue; } - if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; } - walk(el, s); - } - }; - walk(document.body, getComputedStyle(document.body)); - if (full) { - const top = Math.max(0, ...boxes.map((b) => b[2] + b[4])); - const root = document.documentElement; - const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top; - if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]); - } - return boxes; -})()`; -const Outlined = Schema.Struct({ - result: Schema.Struct({ - value: Schema.Array( - Schema.Tuple([ - Schema.Literals(["text", "media", "table"]), - Schema.Finite, - Schema.Finite, - Schema.Finite, - Schema.Finite, - Schema.Finite, - ]), - ), - }), -}); - const Ignored = Schema.Unknown; const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) }); const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) }); @@ -257,10 +166,7 @@ interface PageEvents { omittedConsoleMessages: number; } -/** - * Starts the headless shell for the life of the scope, speaking CDP over - * `--remote-debugging-pipe` (fd 3 in, fd 4 out, NUL-delimited JSON). - */ +// CDP pipe uses fd 3 in, fd 4 out and NUL-delimited JSON. const launchBrowser = Effect.fnUntraced(function* (input: { readonly executable: string; readonly noSandbox: boolean; @@ -312,6 +218,13 @@ const launchBrowser = Effect.fnUntraced(function* (input: { (cause) => new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }), ), + // Node throws some spawn errors synchronously, such as `spawn UNKNOWN` + // when policy blocks the executable; `mapError` cannot catch those. + Effect.catchDefect((cause) => + Effect.fail( + new HtmlRenderBrowserError({ reason: "the browser could not be started", cause }), + ), + ), ); let stderrTail = ""; @@ -342,9 +255,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { ), ).pipe(Effect.asVoid); - // Serves the page. Its body is shared bytes between two small JSON halves, - // queued together, so loading a page of up to 25 MiB at several widths never - // copies it on this side. + // Queue shared body bytes between JSON halves to avoid copies across capture widths. const fulfillPage = (sessionId: string, requestId: string, body: Uint8Array) => Queue.offerAll(outgoing, [ textEncoder.encode( @@ -384,8 +295,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { if (url === PAGE_URL && body !== undefined) { return fulfillPage(sessionId, paused.requestId, body); } - // A frame inside the page may show another site; Local Network Access - // still covers it. The main frame and T3's own origin serve nothing else. + // Subframes may show other sites covered by Local Network Access; the main frame stays on T3's page. const otherSiteFrame = paused.resourceType === "Document" && paused.frameId !== page.mainFrameId && @@ -413,8 +323,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { return Effect.void; }; - // The pipe closes when the browser exits. A startup abort, such as a missing - // sandbox, says why on stderr, which may still be draining, so give it a moment. + // Startup aborts close the pipe; let stderr drain to recover the reason. const disconnect = Effect.gen(function* () { yield* Fiber.await(stderrReader).pipe(Effect.timeout("1 second"), Effect.ignore); const exit = yield* child.exitCode.pipe( @@ -443,7 +352,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { ); }); - // Decoded text chunks may split a message anywhere, and a screenshot reply spans many. + // Chunks may split messages; screenshot replies span many chunks. let partial: Array = []; yield* child.getOutputFd(4).pipe( Stream.decodeText(), @@ -464,33 +373,32 @@ const launchBrowser = Effect.fnUntraced(function* (input: { Effect.forkScoped, ); - const send = ( + const send = Effect.fn("headlessChrome.send")(function* ( method: string, params: Record, result: Schema.Decoder, sessionId?: string, - ) => - Effect.gen(function* () { - if (disconnected) return yield* disconnected; - const id = ++nextId; - const reply = yield* Deferred.make(); - pending.set(id, { method, reply }); - const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) }); - yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`)); - return yield* Deferred.await(reply).pipe( - Effect.flatMap(Schema.decodeUnknownEffect(result)), - Effect.mapError((error) => - error._tag === "HtmlRenderBrowserError" - ? error - : new HtmlRenderBrowserError({ - reason: `${method} returned an unexpected result`, - cause: error, - }), - ), - ); - }); + ) { + if (disconnected) return yield* disconnected; + const id = ++nextId; + const reply = yield* Deferred.make(); + pending.set(id, { method, reply }); + const message = encodeCdpCommand({ id, method, params, ...(sessionId ? { sessionId } : {}) }); + yield* Queue.offer(outgoing, new TextEncoder().encode(`${message}\0`)); + return yield* Deferred.await(reply).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(result)), + Effect.mapError((error) => + error._tag === "HtmlRenderBrowserError" + ? error + : new HtmlRenderBrowserError({ + reason: `${method} returned an unexpected result`, + cause: error, + }), + ), + ); + }); - const openPage = Effect.fnUntraced(function* (width: number) { + const openPage = Effect.fnUntraced(function* (width: number, appearance: ThemeAppearance) { const { targetId } = yield* send( "Target.createTarget", { url: "about:blank" }, @@ -513,6 +421,12 @@ const launchBrowser = Effect.fnUntraced(function* (input: { yield* send("Page.enable", {}, Ignored, sessionId); yield* send("Runtime.enable", {}, Ignored, sessionId); yield* send("Log.enable", {}, Ignored, sessionId); + yield* send( + "Emulation.setEmulatedMedia", + { features: [{ name: "prefers-color-scheme", value: appearance }] }, + Ignored, + sessionId, + ); // Previews have no use for WebRTC, whose ICE servers can make the browser // resolve names outside the proxy. Runs before page scripts in every frame. yield* send( @@ -524,8 +438,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { Ignored, sessionId, ); - // Pauses T3's own origin, to serve the page, and every document, to keep - // the main frame on it. + // Intercept T3's page and all document navigations to keep the main frame on it. yield* send( "Fetch.enable", { @@ -601,27 +514,7 @@ const launchBrowser = Effect.fnUntraced(function* (input: { Effect.ignore, ); - const outline = send( - "Runtime.evaluate", - { expression: OUTLINE_EXPRESSION, returnByValue: true }, - Outlined, - sessionId, - ).pipe( - Effect.map(({ result }) => - encodeHtmlRenderOutline( - result.value.map(([kind, x, y, boxWidth, height, lines]) => ({ - kind, - x, - y, - width: boxWidth, - height, - lines, - })), - ), - ), - ); - - return { load, outline, screenshot, consoleMessages, close }; + return { load, screenshot, consoleMessages, close }; }); return { openPage }; @@ -647,6 +540,7 @@ export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreen readonly html: string; readonly width: number; readonly urlFragment: string; + readonly appearance: ThemeAppearance; }) { const path = yield* Path.Path; const directory = yield* scratchDirectory; @@ -655,7 +549,7 @@ export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreen noSandbox: input.noSandbox, profileDirectory: path.join(directory, "profile"), }); - const page = yield* browser.openPage(input.width); + const page = yield* browser.openPage(input.width, input.appearance); const contentHeight = yield* page.load(pageBody(input.html), input.urlFragment); const capturedHeight = Math.max(1, Math.min(contentHeight, MAX_CAPTURE_HEIGHT)); const png = yield* page.screenshot(capturedHeight); @@ -673,10 +567,7 @@ export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreen }), ); -/** - * Content heights of the page at each width, each from a fresh load, since - * pages often lay themselves out from the width once at load. - */ +/** Fresh load per width, since pages may lay out only at load. */ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: { readonly executable: string; readonly noSandbox: boolean; @@ -692,27 +583,15 @@ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights") profileDirectory: path.join(directory, "profile"), }); const body = pageBody(input.html); - let outline: string | undefined; - const heights = yield* Effect.forEach( + return yield* Effect.forEach( input.widths, (width) => - browser.openPage(width).pipe( + browser.openPage(width, "dark").pipe( Effect.flatMap((page) => - page.load(body, input.urlFragment).pipe( - Effect.tap(() => - width === HTML_RENDER_COLUMN_WIDTH - ? page.outline.pipe( - Effect.tap((value) => Effect.sync(() => (outline = value))), - Effect.ignore, - ) - : Effect.void, - ), - Effect.ensuring(page.close), - ), + page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)), ), Effect.map((height) => [width, height] as const), ), { concurrency: MEASURE_CONCURRENCY }, ); - return { heights, outline }; }, Effect.scoped); diff --git a/apps/server/src/htmlRender/publicProxy.test.ts b/apps/server/src/htmlRender/publicProxy.test.ts index 15c1e7f369ad3..12d0dd65ad342 100644 --- a/apps/server/src/htmlRender/publicProxy.test.ts +++ b/apps/server/src/htmlRender/publicProxy.test.ts @@ -128,30 +128,6 @@ describe("publicProxy", () => { }).pipe(Effect.scoped), ); - it.effect("refuses a request with a wrong version byte", () => - Effect.gen(function* () { - const port = yield* publicProxy; - const { code, socket } = yield* connectThrough(port, ipv4Target("1.1.1.1", 443), 4); - socket.destroy(); - expect(code).toBe(7); - }).pipe(Effect.scoped), - ); - - it.effect("fails instead of crashing when it cannot listen", () => - Effect.gen(function* () { - const exhausted = Object.assign(new Error("too many open files"), { code: "EMFILE" }); - const listen = vi.spyOn(NodeNet.Server.prototype, "listen").mockImplementationOnce(function ( - this: NodeNet.Server, - ) { - process.nextTick(() => this.emit("error", exhausted)); - return this; - }); - const error = yield* publicProxy.pipe(Effect.flip, Effect.scoped); - listen.mockRestore(); - expect(error).toBe(exhausted); - }), - ); - it.effect("closes every connection when its scope closes", () => Effect.gen(function* () { const socket = yield* Effect.scoped( diff --git a/apps/server/src/htmlRender/publicProxy.ts b/apps/server/src/htmlRender/publicProxy.ts index ce6b7796fe138..e73135e5a8f10 100644 --- a/apps/server/src/htmlRender/publicProxy.ts +++ b/apps/server/src/htmlRender/publicProxy.ts @@ -19,8 +19,7 @@ for (const [network, prefix] of [ ] as const) { LOCAL_ADDRESSES.addSubnet(network, prefix, "ipv4"); } -// Also the IPv6 ranges that carry an IPv4 address a translator may route to -// without checking it: IPv4-compatible, local-use NAT64, and Teredo. +// Block IPv4-carrying IPv6 ranges that translators may route without checking. for (const [network, prefix] of [ ["::", 96], ["64:ff9b:1::", 48], @@ -52,11 +51,7 @@ const ipv6Groups = (address: string) => { ); }; -/** - * The IPv4 address a NAT64 or 6to4 address stands for, which a translator - * will route to, so it is checked as well. Public NAT64 targets stay - * reachable, as on IPv6-only networks. - */ +// Check the translated IPv4 too, while allowing public NAT64 targets on IPv6-only networks. const embeddedIPv4 = (address: string) => { const at = NAT64.check(address, "ipv6") ? 6 : SIX_TO_FOUR.check(address, "ipv6") ? 1 : -1; if (at === -1) return undefined; @@ -81,10 +76,7 @@ const isLocal = (address: string, family: number): boolean => { return embedded !== undefined && isLocal(embedded, 4); }; -/** - * The caller connects only to addresses checked here, so a name that later resolves elsewhere - * (DNS rebinding) changes nothing. - */ +// Connect only to checked addresses to prevent DNS rebinding. const publicAddresses = async (host: string) => { const addresses = NodeNet.isIP(host) ? [{ address: host, family: NodeNet.isIP(host) }] @@ -121,10 +113,7 @@ const readRequest = (data: Buffer) => { return { command: data[1], host, port: data.readUInt16BE(end - 2), rest: data.subarray(end) }; }; -/** - * Chrome's Local Network Access misses some requests, such as speculation-rules prefetches; - * nothing misses this. - */ +/** Covers requests Chrome's Local Network Access misses, including speculation prefetches. */ export const publicProxy = Effect.acquireRelease( Effect.callback< { readonly server: NodeNet.Server; readonly sockets: Set }, @@ -171,8 +160,7 @@ export const publicProxy = Effect.acquireRelease( client.off("data", holdEarly); if (addresses === undefined) return refuse(client, 2); client.pause(); - // Tries every checked address, IPv6 and IPv4 alike, so a host is - // still reached on a network whose IPv6 route is broken. + // Try all checked addresses so broken IPv6 routes do not block IPv4 access. const upstream = track( NodeNet.connect({ host: request.host, diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 058d423d8e33f..d37b94477a1a9 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -10,7 +10,10 @@ 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 Logger from "effect/Logger"; +import * as References from "effect/References"; import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import * as Queue from "effect/Queue"; import * as Tracer from "effect/Tracer"; import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/http"; @@ -26,15 +29,9 @@ import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts"; import * as ServerConfig from "./config.ts"; -import { - assetResponseHeaders, - assetFileResponse, - downloadContentDisposition, - isLoopbackHostname, - resolveDevRedirectUrl, - withUntracedRequests, -} from "./http.ts"; +import { assetResponseHeaders, assetFileResponse, downloadContentDisposition } from "./http.ts"; import * as ServerHttp from "./http.ts"; +import { withUntracedRequests } from "./http.ts"; describe("MCP app asset responses", () => { it.effect( @@ -108,6 +105,11 @@ describe("untraced requests", () => { Effect.gen(function* () { const router = yield* HttpRouter.HttpRouter; yield* router.add("POST", "/api/observability/v1/traces", HttpServerResponse.empty()); + yield* router.add( + "POST", + "/api/speech-to-text/transcriptions/*", + HttpServerResponse.empty(), + ); yield* router.add("GET", "/api/environment", HttpServerResponse.empty()); }), ); @@ -120,6 +122,8 @@ describe("untraced requests", () => { yield* client.post("/api/observability/v1/traces"); yield* client.post("/api/observability/v1/traces?x=1"); + // The signed upload token is the path's last segment. + yield* client.post("/api/speech-to-text/transcriptions/payload.signature"); expect(spanNames).toEqual([]); yield* client.get("/api/environment"); @@ -139,6 +143,64 @@ describe("untraced requests", () => { }); }); +describe("unlogged credential requests", () => { + it.effect("keeps dictation upload tokens out of the access log, preflights included", () => { + const logged: Array = []; + const token = "payload.signature-secret"; + return Effect.gen(function* () { + const layerRoutes = Layer.mergeAll( + Layer.effectDiscard( + Effect.gen(function* () { + const router = yield* HttpRouter.HttpRouter; + yield* router.add( + "POST", + "/api/speech-to-text/transcriptions/*", + HttpServerResponse.empty(), + ); + yield* router.add("GET", "/api/environment", HttpServerResponse.empty()); + }), + ), + HttpRouter.cors({ allowedOrigins: ["https://app.example"] }), + ); + const services = yield* Layer.build( + HttpRouter.serve(layerRoutes, { + disableListenLog: true, + middleware: ServerHttp.withUnloggedCredentialRequests, + }).pipe(Layer.provideMerge(NodeHttpServer.layerTest)), + ); + const client = Context.get(services, HttpClient.HttpClient); + const path = `/api/speech-to-text/transcriptions/${token}`; + + yield* client.execute( + HttpClientRequest.make("OPTIONS")(path).pipe( + HttpClientRequest.setHeaders({ + origin: "https://app.example", + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }), + ), + ); + yield* client.post(path); + yield* client.get("/api/environment"); + + expect(logged.some((line) => line.includes("/api/environment"))).toBe(true); + expect(logged.filter((line) => line.includes(token))).toEqual([]); + }).pipe( + Effect.scoped, + Effect.provide( + Logger.layer( + [ + Logger.make(({ fiber }) => { + logged.push(JSON.stringify(fiber.getRef(References.CurrentLogAnnotations))); + }), + ], + { mergeWithExisting: false }, + ), + ), + ); + }); +}); + describe("browser API CORS", () => { it("accepts protocol negotiation with authenticated browser headers", async () => { const layerRoute = Layer.effectDiscard( @@ -194,9 +256,7 @@ const makeStaticRequest = Effect.fn("HttpTest.makeStaticRequest")(function* (sta ServerHttp.layerStaticAndDevRoute, ServerHttp.layerHttpCompression, ).pipe(Layer.provideMerge(NodeHttpPlatform.layer)); - // HttpRouter.serve reuses services from the layers around it before the - // app's own, and NodeHttpServer.layerTest brings a real FileSystem, so the - // caller's FileSystem and static directory go between the two. + // HttpRouter.serve prefers outer services; inject the test FileSystem between it and NodeHttpServer.layerTest. const services = yield* Layer.build( HttpRouter.serve(layerApp, { disableListenLog: true }).pipe( Layer.provideMerge(ServerConfig.layer({ ...config, staticDir })), @@ -257,6 +317,107 @@ it.layer( }), ); + it.effect("serves static files without handles and skips fallback reads for HEAD and 304", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-no-open-" }); + const filePath = path.join(staticDir, "app.txt"); + const body = "packaged asset"; + yield* fs.writeFileString(filePath, body); + let reads = 0; + // Electron asar files can be statted and read even when opening a handle fails. + const fileSystem = FileSystem.FileSystem.of({ + ...fs, + open: (candidate, options) => + candidate === filePath + ? Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "open", + pathOrDescriptor: candidate, + }), + ) + : fs.open(candidate, options), + readFile: (candidate) => + Effect.gen(function* () { + if (candidate === filePath) reads += 1; + return yield* fs.readFile(candidate); + }), + }); + const request = yield* makeStaticRequest(staticDir).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + ); + + const get = yield* request("/app.txt"); + expect(get.status).toBe(200); + expect(yield* get.text).toBe(body); + expect(reads).toBeGreaterThan(0); + const readsAfterGet = reads; + const head = yield* request("/app.txt", { method: "HEAD" }); + expect(head.status).toBe(200); + expect(yield* head.text).toBe(""); + expect(reads).toBe(readsAfterGet); + const unchanged = yield* request("/app.txt", { + headers: { "if-none-match": get.headers["etag"]! }, + }); + expect(unchanged.status).toBe(304); + expect(yield* unchanged.text).toBe(""); + expect(reads).toBe(readsAfterGet); + }), + ); + + it.effect("serves replacement bytes with matching static fallback length and validators", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-replaced-" }); + const filePath = path.join(staticDir, "app.txt"); + const before = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z")); + const after = DateTime.toDateUtc(DateTime.makeUnsafe("2015-10-21T16:29:00.000Z")); + const replacement = "the replacement asset"; + const replacementPath = path.join(staticDir, "replacement.txt"); + yield* fs.writeFileString(filePath, "old"); + yield* fs.utimes(filePath, before, before); + yield* fs.writeFileString(replacementPath, replacement); + yield* fs.utimes(replacementPath, after, after); + let replaceOnOpen = false; + const fileSystem = FileSystem.FileSystem.of({ + ...fs, + open: (candidate, options) => + Effect.gen(function* () { + if (candidate !== filePath) return yield* fs.open(candidate, options); + if (replaceOnOpen) { + yield* fs.rename(replacementPath, filePath); + replaceOnOpen = false; + } + return yield* PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "open", + pathOrDescriptor: candidate, + }); + }), + }); + const request = yield* makeStaticRequest(staticDir).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + ); + const initial = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } }); + expect(yield* initial.text).toBe("old"); + + replaceOnOpen = true; + const response = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } }); + expect(response.status).toBe(200); + expect(response.headers).toMatchObject({ + "content-length": String(Buffer.byteLength(replacement)), + "last-modified": after.toUTCString(), + }); + expect(response.headers["etag"]).not.toBe(initial.headers["etag"]); + expect(yield* response.text).toBe(replacement); + }), + ); + it.effect("serves changed HTML when deployments preserve its size and timestamp", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -467,46 +628,6 @@ describe("video asset byte ranges", () => { }).pipe(Effect.provide(layerFileResponse)), ); - it.effect("streams guarded file ranges, including suffixes and conditional requests", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-guarded-range-" }); - const filePath = path.join(directory, "clip.mp4"); - yield* fs.writeFileString(filePath, "0123456789"); - const canonicalPath = yield* fs.realPath(filePath); - for (const [range, ifRange, expected, status, contentRange] of [ - [undefined, undefined, "0123456789", 200, null], - ["bytes=0-1", undefined, "01", 206, "bytes 0-1/10"], - ["bytes=4-", undefined, "456789", 206, "bytes 4-9/10"], - ["bytes=-3", undefined, "789", 206, "bytes 7-9/10"], - ["bytes=-999999999999999999999999", undefined, "0123456789", 206, "bytes 0-9/10"], - ["bytes=10-", undefined, "", 416, "bytes */10"], - ["bytes=0-1", '"old-etag"', "0123456789", 200, null], - ["bytes=0-1", "", "0123456789", 200, null], - ] as const) { - const file = yield* openMediaFile(canonicalPath); - if (!file) throw new Error("Expected an opened media file"); - const response = HttpServerResponse.toWeb( - yield* assetFileResponse( - { path: canonicalPath, file, mimeType: "video/mp4" }, - range, - ifRange, - ), - ); - expect(response.status).toBe(status); - expect(response.headers.get("accept-ranges")).toBe("bytes"); - expect(response.headers.get("content-range")).toBe(contentRange); - expect(response.headers.get("cache-control")).toBe("private, no-store"); - expect(response.headers.get("etag")).toBeNull(); - expect(response.headers.get("last-modified")).toBeNull(); - if (status !== 416) - expect(response.headers.get("content-length")).toBe(String(expected.length)); - expect(yield* Effect.promise(() => response.text())).toBe(expected); - } - }).pipe(Effect.provide(layerFileResponse)), - ); - it.effect("keeps attachment media out of the cache once its signed URL expires", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -678,30 +799,6 @@ describe("video asset byte ranges", () => { ); }); -describe("http dev routing", () => { - it("treats localhost and loopback addresses as local", () => { - expect(isLoopbackHostname("127.0.0.1")).toBe(true); - expect(isLoopbackHostname("localhost")).toBe(true); - expect(isLoopbackHostname("::1")).toBe(true); - expect(isLoopbackHostname("[::1]")).toBe(true); - }); - - it("does not treat LAN addresses as local", () => { - expect(isLoopbackHostname("192.168.86.35")).toBe(false); - expect(isLoopbackHostname("10.0.0.24")).toBe(false); - expect(isLoopbackHostname("example.local")).toBe(false); - }); - - it("preserves path and query when redirecting to the dev server", () => { - const devUrl = new URL("http://127.0.0.1:5173/"); - const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token"); - - expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe( - "http://127.0.0.1:5173/pair?token=test-token", - ); - }); -}); - describe("assetResponseHeaders", () => { it("sandboxes SVG assets", () => { expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({ @@ -712,25 +809,6 @@ describe("assetResponseHeaders", () => { "Content-Security-Policy", ); }); - - it("does not apply document policy to raster images", () => { - expect(assetResponseHeaders("/attachments/user-image.png")).toEqual({ - "Cache-Control": "private, max-age=3600", - "X-Content-Type-Options": "nosniff", - }); - }); - - it("serves inline videos with their declared mime type", () => { - expect( - assetResponseHeaders("/attachments/demo.bin", { - mimeType: 'video/mp4; codecs="avc1.42E01E"', - }), - ).toEqual({ - "Cache-Control": "private, max-age=3600", - "Content-Type": "video/mp4", - "X-Content-Type-Options": "nosniff", - }); - }); it("serves inline attachment documents with their declared mime type", () => { expect( assetResponseHeaders("/attachments/upload.bin", { mimeType: "application/pdf" }), @@ -744,14 +822,6 @@ describe("assetResponseHeaders", () => { "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads", }); }); - it("serves HTML assets as utf-8 inside a sandboxed origin", () => { - for (const path of ["/workspace/page.html", "/workspace/PAGE.HTM", "/tmp/report.html"]) { - expect(assetResponseHeaders(path)).toMatchObject({ - "Content-Type": "text/html; charset=utf-8", - "Content-Security-Policy": "sandbox allow-scripts allow-forms allow-popups allow-downloads", - }); - } - }); it("downloads uploaded documents without executing their content", () => { expect(assetResponseHeaders("/attachments/upload.html", { download: true })).toMatchObject({ @@ -793,18 +863,6 @@ describe("assetResponseHeaders", () => { ).toHaveProperty("Content-Type", "application/octet-stream"); } }); - - it("preserves official Office Open XML mime types", () => { - for (const mimeType of [ - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "application/vnd.openxmlformats-officedocument.presentationml.presentation", - ]) { - expect( - assetResponseHeaders("/attachments/upload.bin", { download: true, mimeType }), - ).toHaveProperty("Content-Type", mimeType); - } - }); }); describe("downloadContentDisposition", () => { diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 9f3f1e87ab4df..9a5e64fef487b 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -7,6 +7,7 @@ import { import { isDevProxiedPath } from "@t3tools/shared/devProxy"; import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; +import * as ByteSize from "effect/ByteSize"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -30,7 +31,7 @@ import { OtlpTracer, OtlpSerialization } from "effect/observability"; import * as ServerConfig from "./config.ts"; import { ASSET_ROUTE_PREFIX, readMcpAppHtml, resolveAsset } from "./assets/AssetAccess.ts"; -import { githubMediaResponse } from "./assets/GitHubMediaFetch.ts"; +import { sourceControlMediaResponse } from "./assets/sourceControlMediaResponse.ts"; import { statMediaFile, streamMediaFile, type OpenMediaFile } from "./assets/MediaFile.ts"; import { ATTACHMENT_UPLOAD_ROUTE_PREFIX, @@ -48,6 +49,7 @@ import { } from "./auth/http.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import { WEBHOOK_ROUTE_PREFIX } from "./scheduledTasks/ScheduledTaskService.ts"; +import { SPEECH_TO_TEXT_ROUTE_PREFIX } from "./speechToText/SpeechToTextRoute.ts"; import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods, @@ -57,15 +59,12 @@ import { const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces"; const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]); const SVG_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'; sandbox"; -// The sandbox gives the document an opaque origin: scripts run, but same-origin -// cookies, storage, and API calls are out of reach. No modals: agent HTML can -// open without a click (inline renders, and mobile loads it as the top document), -// and must not raise blocking dialogs. +// Opaque origin blocks cookies, storage and API access while allowing scripts. +// Agent HTML can open without a click, so disallow blocking modals. const HTML_CONTENT_SECURITY_POLICY = "sandbox allow-scripts allow-forms allow-popups allow-downloads"; -// Types a browser may render as a document if a proxy strips the disposition -// header. Downloads of these fall back to octet-stream. +// Proxies may strip disposition; force document-capable downloads to octet-stream. const DOWNLOAD_MIME_TYPE_PATTERN = /^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/; const isSafeDownloadMimeType = (mimeType: string): boolean => DOWNLOAD_MIME_TYPE_PATTERN.test(mimeType) && @@ -195,9 +194,7 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( const mediaInfo = mediaFile ? yield* statMediaFile(asset.path, mediaFile) : undefined; const isMedia = /^(?:audio|video)\//i.test(headers["Content-Type"] ?? ""); if (isMedia) { - // Do not invite conditional range requests with validators that cannot establish - // byte-for-byte identity. Attachment media carries no `file`, and must not - // outlive the signed URL that granted it either. + // Without file identity, validators cannot guarantee byte equality; attachments must also expire with their URL. headers["Cache-Control"] = "private, no-store"; } let status = 200; @@ -258,8 +255,7 @@ export const layerBrowserApiCors = Layer.unwrap( Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const devOrigin = config.devUrl?.origin; - // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be - // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin. + // Credentialed dev requests need explicit Vite/Electron origins; packaged desktop uses the default wildcard. return HttpRouter.cors({ ...(devOrigin ? { @@ -274,7 +270,7 @@ export const layerBrowserApiCors = Layer.unwrap( }), ); -export function isLoopbackHostname(hostname: string): boolean { +function isLoopbackHostname(hostname: string): boolean { const normalizedHostname = hostname .trim() .toLowerCase() @@ -282,7 +278,7 @@ export function isLoopbackHostname(hostname: string): boolean { return LOOPBACK_HOSTNAMES.has(normalizedHostname); } -export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string { +function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string { const redirectUrl = new URL(devUrl.toString()); redirectUrl.pathname = requestUrl.pathname; redirectUrl.search = requestUrl.search; @@ -290,10 +286,11 @@ export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string { return redirectUrl.toString(); } -const authenticateRawRouteWithScope = ( - scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope, -) => - Effect.gen(function* () { +const authenticateRawRouteWithScope = + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* ( + scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope, + ) { const request = yield* HttpServerRequest.HttpServerRequest; const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; const session = yield* serverAuth.authenticateHttpRequest(request).pipe( @@ -331,8 +328,7 @@ class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecor readonly cause: unknown; }> {} -// Renderers export up to once a second while they have spans buffered, so -// tracing this proxy would add more server spans than it forwards. +// Tracing once-per-second renderer exports would create more spans than it forwards. export const layerOtlpTracesProxyRoute = HttpRouter.add( "POST", OTLP_TRACES_PROXY_PATH, @@ -389,18 +385,34 @@ export const layerOtlpTracesProxyRoute = HttpRouter.add( const UNTRACED_REQUEST_PATHS: ReadonlySet = new Set([OTLP_TRACES_PROXY_PATH]); -// TracerDisabledWhen is one predicate for the whole server, and -// HttpRouter.serve builds its routes privately, so it is provided to the served -// layer, never merged into the routes. +// HttpRouter.serve builds routes privately; provide the server-wide TracerDisabledWhen to the served layer. const layerUntracedRequests = Layer.succeed(HttpMiddleware.TracerDisabledWhen)((request) => { const queryIndex = request.url.indexOf("?"); const path = queryIndex === -1 ? request.url : request.url.slice(0, queryIndex); - // Webhook URLs carry their secret token in the path, so they never reach a trace. - return UNTRACED_REQUEST_PATHS.has(path) || path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`); + // Webhook and dictation upload URLs carry their secret token in the path, so they never + // reach a trace. + return ( + UNTRACED_REQUEST_PATHS.has(path) || + path.startsWith(`${WEBHOOK_ROUTE_PREFIX}/`) || + path.startsWith(`${SPEECH_TO_TEXT_ROUTE_PREFIX}/`) + ); }); export const withUntracedRequests = Layer.provide(layerUntracedRequests); +/** + * Passed as HttpRouter.serve's middleware, which runs inside the access logger and before CORS, + * so preflights for token-bearing dictation upload URLs are kept out of the log as well. + */ +export const withUnloggedCredentialRequests = + /* Wraps every request inside the server's request span; a span per request would be noise. */ + Effect.fnUntraced(function* (effect: Effect.Effect) { + const request = yield* HttpServerRequest.HttpServerRequest; + return yield* request.url.startsWith(`${SPEECH_TO_TEXT_ROUTE_PREFIX}/`) + ? HttpMiddleware.withLoggerDisabled(effect) + : effect; + }); + export const layerAssetRoute = HttpRouter.add( "GET", `${ASSET_ROUTE_PREFIX}/*`, @@ -430,10 +442,15 @@ export const layerAssetRoute = HttpRouter.add( headers: { "cache-control": "private, max-age=3600", "x-content-type-options": "nosniff" }, }); } - if (asset.kind === "github-media") { - return yield* githubMediaResponse(asset, request.headers).pipe( + if (asset.kind === "source-control-media") { + return yield* sourceControlMediaResponse(asset, request.headers).pipe( Effect.tapError((cause) => - Effect.logWarning("Failed to fetch GitHub media.", { url: asset.url, cause }), + // The URL can carry a token in its query string, and the error keeps the request it + // failed on; the host and the failure kind are enough to diagnose. + Effect.logWarning("Failed to fetch source control media.", { + host: URL.canParse(asset.url) ? new URL(asset.url).host : undefined, + reason: cause.reason._tag, + }), ), Effect.orElseSucceed(() => HttpServerResponse.empty({ @@ -533,8 +550,15 @@ const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string) const fileSystem = yield* FileSystem.FileSystem; const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null)); if (pathInfo?.type !== "File") return null; - const file = yield* fileSystem.open(filePath, { flag: "r" }); - const info = yield* file.stat; + const file = yield* fileSystem.open(filePath, { flag: "r" }).pipe( + Effect.catchTags({ + PlatformError: (error) => + error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error), + }), + ); + // Electron asar can stat and read files even when opening a handle returns NotFound. + // Refresh path metadata because the file may have been replaced since the first stat. + const info = yield* file === null ? fileSystem.stat(filePath) : file.stat; return info.type === "File" ? { file, info } : null; }); @@ -572,6 +596,14 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( const staticDir = config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined); + if (!staticDir && config.devUrl) { + // `vp run dev --share --built` prints the pairing URL before its first + // web build lands in apps/web/dist. Reload until it does. + return HttpServerResponse.text( + '

Waiting for the first web build. This page reloads by itself.

', + { status: 503, contentType: "text/html", headers: { "Retry-After": "2" } }, + ); + } if (!staticDir) { return HttpServerResponse.text("No static directory configured and no dev URL set.", { status: 503, @@ -629,21 +661,25 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( !isHtml && /^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) && immutableBuildAssets.has(relativePath); + const cacheControl = immutable ? "public, max-age=31536000, immutable" : "no-cache"; + const validators = (info: FileSystem.File.Info) => { + // Deployments can preserve HTML size and mtime while changing its bundle URLs. + const modifiedAt = isHtml ? undefined : Option.getOrUndefined(info.mtime); + return modifiedAt + ? { + ETag: `W/"${info.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`, + "Last-Modified": modifiedAt.toUTCString(), + } + : {}; + }; const headers: Record = { - "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache", + "Cache-Control": cacheControl, + ...validators(fileInfo), }; - // Deployments can preserve HTML size and mtime while changing its bundle URLs. - const modifiedAt = isHtml ? undefined : Option.getOrUndefined(fileInfo.mtime); - const etag = modifiedAt - ? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"` - : undefined; - if (etag !== undefined && modifiedAt !== undefined) { - headers.ETag = etag; - headers["Last-Modified"] = modifiedAt.toUTCString(); - } + const etag = headers.ETag; + const lastModified = headers["Last-Modified"]; - // If-None-Match takes precedence over dates and uses weak comparison for - // GET/HEAD, including when compression changes the transferred bytes. + // If-None-Match precedes dates and uses weak GET/HEAD comparison even across compression. const ifNoneMatch = request.headers["if-none-match"]; const ifModifiedSince = request.headers["if-modified-since"]; const unchanged = @@ -656,8 +692,8 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( ); }) : ifModifiedSince !== undefined && - modifiedAt !== undefined && - Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince); + lastModified !== undefined && + Date.parse(lastModified) <= Date.parse(ifModifiedSince); if (!isHtml && unchanged) { return HttpServerResponse.empty({ status: 304, @@ -666,11 +702,29 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( } const contentType = isHtml ? "text/html; charset=utf-8" : mimeType; - return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), { - headers, - contentType, - contentLength: Number(fileInfo.size), - }); + if (opened.file === null && request.method !== "HEAD") { + const fileSystem = yield* FileSystem.FileSystem; + // Complete fallback reads before success headers; stream errors arrive too late for a 500. + const bytes = yield* fileSystem.readFile(filePath); + const info = yield* fileSystem.stat(filePath); + return HttpServerResponse.uint8Array(bytes, { + headers: { + "Cache-Control": cacheControl, + ...validators({ ...info, size: ByteSize.bytes(bytes.byteLength) }), + }, + contentType, + }); + } + // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation. + // HEAD still passes through compression, which selects headers without reading the stream. + return HttpServerResponse.stream( + opened.file === null ? Stream.empty : streamStaticFile(opened.file, fileInfo.size), + { + headers, + contentType, + contentLength: Number(fileInfo.size), + }, + ); }, Effect.catchTags({ PlatformError: () => diff --git a/apps/server/src/httpResponseErrorGuard.test.ts b/apps/server/src/httpResponseErrorGuard.test.ts index de5e759a8425d..ed3c7e65c7974 100644 --- a/apps/server/src/httpResponseErrorGuard.test.ts +++ b/apps/server/src/httpResponseErrorGuard.test.ts @@ -1,36 +1,80 @@ +// Exercise the raw Node HTTP boundary before Effect attaches serving handlers. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; import * as NodeNet from "node:net"; import { afterEach, describe, expect, it } from "vite-plus/test"; -import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts"; +import * as HttpResponseErrorGuard from "./httpResponseErrorGuard.ts"; + +const { guardHttpResponseWriteErrors } = HttpResponseErrorGuard; const servers: NodeHttp.Server[] = []; +const requests: NodeHttp.ClientRequest[] = []; +const sockets: NodeNet.Socket[] = []; function listen(server: NodeHttp.Server): Promise { servers.push(server); - return new Promise((resolve) => { + server.on("connection", (socket) => sockets.push(socket)); + return new Promise((resolve, reject) => { + server.once("error", reject); server.listen(0, "127.0.0.1", () => { resolve((server.address() as NodeNet.AddressInfo).port); }); }); } -function fetchStatus(port: number, path: string): Promise { +function fetchResponse( + port: number, + path: string, + upgrade = false, +): Promise { return new Promise((resolve, reject) => { - const request = NodeHttp.get({ host: "127.0.0.1", port, path }, (response) => { - response.resume(); - resolve(response.statusCode ?? 0); - }); + const request = NodeHttp.get( + { + host: "127.0.0.1", + port, + path, + agent: false, + headers: upgrade + ? { + connection: "Upgrade", + upgrade: "websocket", + "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==", + "sec-websocket-version": "13", + } + : {}, + }, + (response) => { + response.on("error", reject); + response.on("end", () => resolve(response)); + response.resume(); + }, + ); + requests.push(request); request.on("error", reject); - request.setTimeout(5_000, () => reject(new Error("request timed out"))); + request.on("upgrade", (response, socket) => { + socket.destroy(); + resolve(response); + }); }); } -afterEach(() => { - for (const server of servers.splice(0)) { - server.close(); +function fetchStatus(port: number, path: string): Promise { + return fetchResponse(port, path).then((response) => response.statusCode ?? 0); +} + +afterEach(async () => { + for (const request of requests.splice(0)) { + request.destroy(); + } + for (const socket of sockets.splice(0)) { + socket.destroy(); } + await Promise.all( + servers + .splice(0) + .map((server) => new Promise((resolve) => server.close(() => resolve()))), + ); }); describe("guardHttpResponseWriteErrors", () => { @@ -43,9 +87,7 @@ describe("guardHttpResponseWriteErrors", () => { }); server.on("upgrade", (_request, socket) => { - // Simulate the client vanishing while the auth rejection response is - // written to the upgrade socket: the write failure surfaces as an - // "error" event on a socket Node's http server no longer listens to. + // Node's HTTP server no longer listens for errors on an upgraded socket. socket.destroy(Object.assign(new Error("write EPIPE"), { code: "EPIPE" })); }); @@ -65,6 +107,7 @@ describe("guardHttpResponseWriteErrors", () => { ].join("\r\n"), ); }); + sockets.push(client); client.on("error", () => {}); await failureObserved.promise; @@ -80,24 +123,43 @@ describe("guardHttpResponseWriteErrors", () => { }); await expect(fetchStatus(port, "/")).resolves.toBe(200); }); +}); - it("arms every response with an error listener without disturbing normal traffic", async () => { +describe("rejectRequestsUntilServing", () => { + it("rejects early HTTP and upgrades, then hands each off to its serving handler", async () => { const writeErrors: unknown[] = []; - let responseErrorListeners = -1; - const server = guardHttpResponseWriteErrors(NodeHttp.createServer(), (error) => { - writeErrors.push(error); - }); + const server = HttpResponseErrorGuard.rejectRequestsUntilServing( + guardHttpResponseWriteErrors(NodeHttp.createServer(), (error) => writeErrors.push(error)), + ); + const port = await listen(server); - server.on("request", (_request, response) => { - responseErrorListeners = response.listenerCount("error"); - response.writeHead(200, { "content-type": "text/plain" }); - response.end("ok"); - }); + const earlyHttp = await fetchResponse(port, "/"); + expect(earlyHttp.statusCode).toBe(503); + expect(earlyHttp.headers["retry-after"]).toBe("1"); - const port = await listen(server); + const earlyUpgrade = await fetchResponse(port, "/rpc", true); + expect(earlyUpgrade.statusCode).toBe(503); + expect(earlyUpgrade.headers["retry-after"]).toBe("1"); - await expect(fetchStatus(port, "/")).resolves.toBe(200); - expect(responseErrorListeners).toBeGreaterThan(0); + server.on("request", (_request, response) => response.writeHead(204).end()); + + const servingHttp = await fetchResponse(port, "/"); + expect(servingHttp.statusCode).toBe(204); + expect(servingHttp.headers["retry-after"]).toBeUndefined(); + + const pendingUpgrade = await fetchResponse(port, "/rpc", true); + expect(pendingUpgrade.statusCode).toBe(503); + expect(pendingUpgrade.headers["retry-after"]).toBe("1"); + + server.on("upgrade", (_request, socket) => { + socket.end( + "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n", + ); + }); + + const servingUpgrade = await fetchResponse(port, "/rpc", true); + expect(servingUpgrade.statusCode).toBe(101); + expect(servingUpgrade.headers["retry-after"]).toBeUndefined(); expect(writeErrors).toEqual([]); }); }); diff --git a/apps/server/src/httpResponseErrorGuard.ts b/apps/server/src/httpResponseErrorGuard.ts index 1461e6a5ead90..0f215ba797f87 100644 --- a/apps/server/src/httpResponseErrorGuard.ts +++ b/apps/server/src/httpResponseErrorGuard.ts @@ -1,11 +1,8 @@ +// These guards run on the raw Node HTTP server before Effect handles requests. // @effect-diagnostics nodeBuiltinImport:off import type * as NodeHttp from "node:http"; +import type * as NodeStream from "node:stream"; -/** - * An "error" event without a listener escalates into an uncaught exception and - * terminates the whole server process, taking every other client and all - * in-flight provider work with it. - */ export function guardHttpResponseWriteErrors( server: T, onError?: (error: unknown) => void, @@ -22,3 +19,33 @@ export function guardHttpResponseWriteErrors( }); return server; } + +/** + * NodeHttpServer listens before serve() attaches its handlers, so requests in + * between would hang. Install this after the write-error guards so only the + * serving handlers trigger the handoff. + */ +export function rejectRequestsUntilServing(server: T): T { + const rejectRequest = (_request: NodeHttp.IncomingMessage, response: NodeHttp.ServerResponse) => { + response.writeHead(503, { "retry-after": "1", connection: "close" }).end(); + }; + const rejectUpgrade = (_request: NodeHttp.IncomingMessage, socket: NodeStream.Duplex) => { + socket.end( + "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", + ); + }; + server.on("request", rejectRequest); + server.on("upgrade", rejectUpgrade); + // Node emits newListener before adding the handler, making the handoff synchronous. + server.on("newListener", function onNewListener(event) { + if (event === "request") server.off("request", rejectRequest); + if (event === "upgrade") server.off("upgrade", rejectUpgrade); + if ( + !server.listeners("request").includes(rejectRequest) && + !server.listeners("upgrade").includes(rejectUpgrade) + ) { + server.off("newListener", onNewListener); + } + }); + return server; +} diff --git a/apps/server/src/imageMime.test.ts b/apps/server/src/imageMime.test.ts index f9c83400edbcb..5d427b957265a 100644 --- a/apps/server/src/imageMime.test.ts +++ b/apps/server/src/imageMime.test.ts @@ -3,13 +3,6 @@ import { describe, expect, it } from "vite-plus/test"; import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts"; describe("imageMime", () => { - it("parses base64 data URL with mime type", () => { - expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=")).toEqual({ - mimeType: "image/png", - base64: "SGVsbG8=", - }); - }); - it("parses base64 data URL with mime parameters", () => { expect(parseBase64DataUrl("data:image/png;charset=utf-8;base64,SGVsbG8=")).toEqual({ mimeType: "image/png", @@ -17,14 +10,6 @@ describe("imageMime", () => { }); }); - it("rejects non-base64 data URL", () => { - expect(parseBase64DataUrl("data:image/png;charset=utf-8,hello")).toBeNull(); - }); - - it("rejects missing mime type", () => { - expect(parseBase64DataUrl("data:;base64,SGVsbG8=")).toBeNull(); - }); - it("parses base64 data URL with spaces in payload", () => { expect(parseBase64DataUrl("data:image/png;base64,SGVs bG8=\n")).toEqual({ mimeType: "image/png", @@ -37,6 +22,7 @@ describe("imageMime", () => { expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull(); }); + // regression: #3952 image upload crashed dispatchCommand with a stack overflow it("rejects structurally malformed base64", () => { expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull(); expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull(); @@ -67,22 +53,6 @@ describe("imageMime", () => { }); }); - it("parses a multi-megabyte payload from a deep call stack", () => { - const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`; - const atDepth = (depth: number): ReturnType => - depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1); - const findMaxDepth = (depth: number): number => { - try { - return findMaxDepth(depth + 1); - } catch { - return depth; - } - }; - const result = atDepth(Math.floor(findMaxDepth(0) * 0.85)); - expect(result?.mimeType).toBe("image/png"); - expect(result?.base64.length).toBe(14_000_000); - }); - it("does not read inherited keys from mime extension map", () => { expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin"); }); diff --git a/apps/server/src/imageMime.ts b/apps/server/src/imageMime.ts index b180dda51a095..338bbd62ce592 100644 --- a/apps/server/src/imageMime.ts +++ b/apps/server/src/imageMime.ts @@ -45,10 +45,7 @@ function isBase64Whitespace(code: number): boolean { return code === 0x0d || code === 0x0a || code === 0x20; } -// Data URLs carry the full image payload, so this parser must never run a -// regex across the payload: V8's regex engine borrows the JS call stack, and -// matching a multi-megabyte string from a deep call stack (e.g. inside fiber -// execution) throws "Maximum call stack size exceeded". +// V8 regexes use the JS stack; scanning image payloads can overflow a deep fiber stack. export function parseBase64DataUrl( dataUrl: string, ): { readonly mimeType: string; readonly base64: string } | null { @@ -100,8 +97,7 @@ export function parseBase64DataUrl( if (base64.length === 0 || base64.length % 4 !== 0) return null; const firstPad = base64.indexOf("="); if (firstPad !== -1) { - // '=' is only valid as one or two trailing padding characters; Node's - // decoder would otherwise silently truncate at the first '='. + // Node silently truncates at the first =; allow only one or two trailing padding characters. if (base64.length - firstPad > 2) return null; for (let index = firstPad; index < base64.length; index += 1) { if (base64.charCodeAt(index) !== 0x3d) return null; diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index bef260bf92547..80d4a52625ed7 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -2,7 +2,6 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { assertFailure } from "@effect/vitest/utils"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -12,17 +11,10 @@ import * as Schema from "effect/Schema"; import * as ServerConfig from "./config.ts"; import * as Keybindings from "./keybindings.ts"; import { KeybindingsConfigError, MAX_KEYBINDINGS_COUNT } from "@t3tools/contracts"; -import * as HostProcess from "@t3tools/shared/HostProcess"; const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson); const decodeKeybindingsConfigJson = Schema.decodeUnknownEffect(KeybindingsConfigJson); -const encodeResolvedKeybindingFromConfig = Schema.encodeEffect( - Keybindings.ResolvedKeybindingFromConfig, -); -const decodeResolvedKeybindingFromConfigExit = Schema.decodeUnknownExit( - Keybindings.ResolvedKeybindingFromConfig, -); const layerKeybindings = () => { return Keybindings.layer.pipe( Layer.provideMerge( @@ -109,25 +101,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }), ); - it.effect("encodes resolved plus-key shortcuts", () => - Effect.gen(function* () { - const encoded = yield* encodeResolvedKeybindingFromConfig({ - command: "terminal.toggle", - shortcut: { - key: "+", - metaKey: false, - ctrlKey: false, - shiftKey: false, - altKey: false, - modKey: true, - }, - }); - - assert.equal(encoded.key, "mod++"); - assert.equal(encoded.command, "terminal.toggle"); - }), - ); - it.effect("rejects invalid rules", () => Effect.sync(() => { assert.isNull( @@ -155,23 +128,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }), ); - it.effect("formats invalid resolved keybinding rules with the custom message", () => - Effect.sync(() => { - const result = decodeResolvedKeybindingFromConfigExit({ - key: "mod+shift+d+o", - command: "terminal.new", - }); - - if (result._tag !== "Failure") { - assert.fail("Expected invalid keybinding decode to fail"); - } - - const detail = Cause.pretty(result.cause); - assert.isTrue(detail.includes("Invalid keybinding rule")); - assert.isFalse(detail.includes("Invalid data")); - }), - ); - it.effect("bootstraps default keybindings when config file is missing", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -396,32 +352,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => { ); }); - it.effect("upserts custom keybindings to configured path", () => - Effect.gen(function* () { - const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; - yield* writeKeybindingsConfig(keybindingsConfigPath, [ - { key: "mod+j", command: "terminal.toggle" }, - ]); - - const resolved = yield* Effect.gen(function* () { - const keybindings = yield* Keybindings.Keybindings; - return yield* keybindings.upsertKeybindingRule({ - key: "mod+shift+r", - command: "script.run-tests.run", - }); - }); - - const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); - const persistedView = persisted.map(({ key, command }) => ({ key, command })); - - assert.deepEqual(persistedView, [ - { key: "mod+j", command: "terminal.toggle" }, - { key: "mod+shift+r", command: "script.run-tests.run" }, - ]); - assert.isTrue(resolved.some((entry) => entry.command === "script.run-tests.run")); - }).pipe(Effect.provide(layerKeybindings())), - ); - it.effect("appends additional custom keybindings for the same command", () => Effect.gen(function* () { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; @@ -533,84 +463,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(layerKeybindings())), ); - it.effect("reports non-array config parse errors without duplicate prefix", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; - yield* fs.writeFileString( - keybindingsConfigPath, - '{"key":"mod+j","command":"terminal.toggle"}', - ); - - const firstResult = yield* Effect.gen(function* () { - const keybindings = yield* Keybindings.Keybindings; - return yield* keybindings.upsertKeybindingRule({ - key: "mod+shift+r", - command: "script.run-tests.run", - }); - }).pipe(toDetailResult); - assertFailure(firstResult, "expected JSON array"); - - const secondResult = yield* Effect.gen(function* () { - const keybindings = yield* Keybindings.Keybindings; - return yield* keybindings.upsertKeybindingRule({ - key: "mod+shift+r", - command: "script.run-tests.run", - }); - }).pipe(toDetailResult); - assertFailure(secondResult, "expected JSON array"); - }).pipe(Effect.provide(layerKeybindings())), - ); - - // chmod cannot make a directory unwritable on Windows, so the write succeeds. - it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( - "fails when config directory is not writable", - () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; - const { dirname } = yield* Path.Path; - yield* writeKeybindingsConfig(keybindingsConfigPath, [ - { key: "mod+j", command: "terminal.toggle" }, - ]); - yield* fs.chmod(dirname(keybindingsConfigPath), 0o500); - - const result = yield* Effect.gen(function* () { - const keybindings = yield* Keybindings.Keybindings; - return yield* keybindings.upsertKeybindingRule({ - key: "mod+shift+r", - command: "script.run-tests.run", - }); - }).pipe(toDetailResult); - assertFailure(result, "failed to write keybindings config"); - - yield* fs.chmod(dirname(keybindingsConfigPath), 0o700); - - const persisted = yield* readKeybindingsConfig(keybindingsConfigPath); - const persistedView = persisted.map(({ key, command }) => ({ key, command })); - assert.deepEqual(persistedView, [{ key: "mod+j", command: "terminal.toggle" }]); - }).pipe(Effect.provide(layerKeybindings())), - ); - - it.effect("caches loaded resolved config across repeated reads", () => - Effect.gen(function* () { - const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; - yield* writeKeybindingsConfig(keybindingsConfigPath, [ - { key: "mod+j", command: "terminal.toggle" }, - ]); - - const [first, second] = yield* Effect.gen(function* () { - const keybindings = yield* Keybindings.Keybindings; - const firstLoad = (yield* keybindings.loadConfigState).keybindings; - const secondLoad = (yield* keybindings.loadConfigState).keybindings; - return [firstLoad, secondLoad] as const; - }); - - assert.deepEqual(first, second); - assert.isTrue(second.some((entry) => entry.command === "terminal.toggle")); - }).pipe(Effect.provide(layerKeybindings())), - ); - it.effect("retries a failed config read instead of keeping the failure", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -632,28 +484,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(layerKeybindings())), ); - it.effect("updates cached resolved config after upsert", () => - Effect.gen(function* () { - const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; - yield* writeKeybindingsConfig(keybindingsConfigPath, [ - { key: "mod+j", command: "terminal.toggle" }, - ]); - - const loadedAfterUpsert = yield* Effect.gen(function* () { - const keybindings = yield* Keybindings.Keybindings; - yield* keybindings.loadConfigState; - yield* keybindings.upsertKeybindingRule({ - key: "mod+shift+r", - command: "script.run-tests.run", - }); - return (yield* keybindings.loadConfigState).keybindings; - }); - - assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "script.run-tests.run")); - assert.isTrue(loadedAfterUpsert.some((entry) => entry.command === "terminal.toggle")); - }).pipe(Effect.provide(layerKeybindings())), - ); - it.effect("serializes concurrent upserts to avoid lost updates", () => Effect.gen(function* () { const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 177da66522343..bf87ee2eabc01 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -66,24 +66,23 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( Effect.map((resolved) => resolved), ), - encode: (resolved) => - Effect.gen(function* () { - const key = encodeShortcut(resolved.shortcut); - if (!key) { - return yield* Effect.fail( - new SchemaIssue.InvalidValue({ - message: "Resolved shortcut cannot be encoded to key string", - }), - ); - } + encode: Effect.fn("keybindings.encode")(function* (resolved) { + const key = encodeShortcut(resolved.shortcut); + if (!key) { + return yield* Effect.fail( + new SchemaIssue.InvalidValue({ + message: "Resolved shortcut cannot be encoded to key string", + }), + ); + } - const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined; - return { - key, - command: resolved.command, - when, - }; - }), + const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined; + return { + key, + command: resolved.command, + when, + }; + }), }), ), ); @@ -228,6 +227,13 @@ export class Keybindings extends Context.Service< readonly streamChanges: Stream.Stream; + /** Acquire before reading a snapshot to buffer changes until the stream starts. */ + readonly subscribeChanges: Effect.Effect< + Stream.Stream, + never, + Scope.Scope + >; + /** * Writes config atomically and enforces the max rule count by truncating * oldest entries when needed. @@ -542,8 +548,7 @@ const make = Effect.gen(function* () { } } - // Keep only defaults that fit, before persisted rules so existing - // custom shortcuts retain priority when their conditions overlap. + // Put defaults before persisted rules so custom shortcuts win overlapping conditions. const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length); const defaultsToAppend = missingDefaults.slice(0, availableSlots); const skippedDefaults = missingDefaults.slice(availableSlots); @@ -588,8 +593,7 @@ const make = Effect.gen(function* () { const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); - // Editors emit multiple events per save (truncate, write, rename) and - // `fs.watch` can fire before the content has been flushed to disk. + // Saves emit multiple events; fs.watch may fire before content is flushed. const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe( Stream.filter((event) => { return ( @@ -640,6 +644,9 @@ const make = Effect.gen(function* () { get streamChanges() { return Stream.fromPubSub(changesPubSub); }, + get subscribeChanges() { + return PubSub.subscribe(changesPubSub).pipe(Effect.map(Stream.fromSubscription)); + }, upsertKeybindingRule: (input) => upsertSemaphore.withPermits(1)( Effect.gen(function* () { diff --git a/apps/server/src/launcherWatch.test.ts b/apps/server/src/launcherWatch.test.ts index 43c3e381f6fb4..1482804c61e0e 100644 --- a/apps/server/src/launcherWatch.test.ts +++ b/apps/server/src/launcherWatch.test.ts @@ -1,7 +1,6 @@ -import { assert, it } from "@effect/vitest"; +import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import * as TestClock from "effect/testing/TestClock"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { awaitLauncherLoss } from "./launcherWatch.ts"; @@ -15,21 +14,6 @@ const watch = (getParentPid: () => number, platform: NodeJS.Platform, startPid = Effect.provideService(HostProcess.Platform, platform), ); -it.effect("completes when the parent changes, including to a subreaper", () => - Effect.gen(function* () { - let parentPid = launcherPid; - const fiber = yield* Effect.forkChild(watch(() => parentPid, "linux")); - yield* Effect.yieldNow; - - yield* TestClock.adjust("10 seconds"); - assert.isUndefined(fiber.pollUnsafe(), "still watching while the launcher is alive"); - - parentPid = subreaperPid; - yield* TestClock.adjust("2 seconds"); - yield* Fiber.join(fiber); - }), -); - it.effect("notices a launcher that was already gone when the watch began", () => Effect.gen(function* () { const fiber = yield* Effect.forkChild(watch(() => subreaperPid, "linux")); @@ -37,29 +21,3 @@ it.effect("notices a launcher that was already gone when the watch began", () => yield* Fiber.join(fiber); }), ); - -it.effect("does not watch a backend that already starts under init", () => - Effect.gen(function* () { - let parentPid = 1; - const fiber = yield* Effect.forkChild(watch(() => parentPid, "linux", 1)); - yield* Effect.yieldNow; - - parentPid = subreaperPid; - yield* TestClock.adjust("1 minute"); - assert.isUndefined(fiber.pollUnsafe()); - yield* Fiber.interrupt(fiber); - }), -); - -it.effect("does not watch on Windows, where the original parent id outlives the parent", () => - Effect.gen(function* () { - let parentPid = launcherPid; - const fiber = yield* Effect.forkChild(watch(() => parentPid, "win32")); - yield* Effect.yieldNow; - - parentPid = subreaperPid; - yield* TestClock.adjust("1 minute"); - assert.isUndefined(fiber.pollUnsafe()); - yield* Fiber.interrupt(fiber); - }), -); diff --git a/apps/server/src/launcherWatch.ts b/apps/server/src/launcherWatch.ts index 4e1c5a8321214..ca109422c95a8 100644 --- a/apps/server/src/launcherWatch.ts +++ b/apps/server/src/launcherWatch.ts @@ -4,42 +4,32 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; const DEFAULT_POLL_INTERVAL = Duration.seconds(2); -// Sampled when this module loads, before config resolution and the bootstrap -// read, so a launcher that dies during startup is still noticed. +// Capture before config and bootstrap reads to detect launcher loss during startup. const startupParentPid = process.ppid; /** - * Completes when the process that launched this backend is gone. - * - * A desktop-launched backend reads its bootstrap envelope once and never looks - * at its launcher again. When the launcher dies without a graceful stop (a WSL - * relay killed during an app update, for instance), the backend would keep - * serving and holding its ownership lock while no desktop can reach it, and - * every replacement launch is refused. An orphan is adopted by init or, on - * Linux, by a subreaper, so any change of parent counts rather than only a - * move to pid 1. A backend that already starts under init has no launcher to - * lose, and Windows keeps the original parent id after the parent exits, so - * neither is watched. + * Any parent change signals launcher loss, including adoption by a Linux subreaper; + * otherwise an orphan backend keeps its ownership lock and blocks replacement launches. + * Skip init-launched backends and Windows, which retains the exited parent's id. */ -export const awaitLauncherLoss = (options?: { +export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (options?: { readonly launcherPid?: number; readonly getParentPid?: () => number; readonly interval?: Duration.Input; -}): Effect.Effect => - Effect.gen(function* () { - const platform = yield* HostProcess.Platform; - const launcherPid = options?.launcherPid ?? startupParentPid; - const getParentPid = options?.getParentPid ?? (() => process.ppid); - const interval = options?.interval ?? DEFAULT_POLL_INTERVAL; - if (platform === "win32" || launcherPid <= 1) return yield* Effect.never; - const poll: Effect.Effect = Effect.suspend(() => { - const parentPid = getParentPid(); - return parentPid === launcherPid - ? Effect.flatMap(Effect.sleep(interval), () => poll) - : Effect.logWarning("desktop launcher is gone; shutting down the backend", { - launcherPid, - parentPid, - }); - }); - return yield* poll; +}): Effect.fn.Return { + const platform = yield* HostProcess.Platform; + const launcherPid = options?.launcherPid ?? startupParentPid; + const getParentPid = options?.getParentPid ?? (() => process.ppid); + const interval = options?.interval ?? DEFAULT_POLL_INTERVAL; + if (platform === "win32" || launcherPid <= 1) return yield* Effect.never; + const poll: Effect.Effect = Effect.suspend(() => { + const parentPid = getParentPid(); + return parentPid === launcherPid + ? Effect.flatMap(Effect.sleep(interval), () => poll) + : Effect.logWarning("desktop launcher is gone; shutting down the backend", { + launcherPid, + parentPid, + }); }); + return yield* poll; +}); diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.test.ts b/apps/server/src/mcp/AcpMcpStdioBridge.test.ts index 5734d613bf524..0f1bedc17c631 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.test.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.test.ts @@ -2,10 +2,11 @@ import * as NodeStream from "node:stream"; import { describe, expect, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import { AcpMcpBridgeError, callAcpMcpTool, runAcpMcpStdioBridge } from "./AcpMcpStdioBridge.ts"; +import { mcpToolSession, runAcpMcpStdioBridge } from "./AcpMcpStdioBridge.ts"; function makeHarness(responder: (request: Request) => Promise | Response) { const input = new NodeStream.PassThrough(); @@ -29,67 +30,14 @@ function makeHarness(responder: (request: Request) => Promise | Respon return { input, written, requests, bridge }; } -describe("AcpMcpStdioBridge", () => { - it.effect("preserves the original transport failure as the typed error cause", () => - Effect.gen(function* () { - const source = new Error("fetch failed"); - const failure = yield* callAcpMcpTool({ - endpoint: "http://127.0.0.1:1/mcp", - authorization: "Bearer bridge-test", - tool: "orchestrator_capabilities", - arguments: {}, - fetchImplementation: () => Promise.reject(source), - }).pipe(Effect.asVoid, Effect.flip); - - expect(failure).toBeInstanceOf(AcpMcpBridgeError); - expect(failure.cause).toBe(source); - }), - ); - - it.effect("calls one tool through a fresh authenticated MCP session", () => - Effect.gen(function* () { - const requests: Array<{ readonly body: unknown; readonly headers: Headers }> = []; - const result = yield* callAcpMcpTool({ - endpoint: "http://127.0.0.1:1/mcp", - authorization: "Bearer bridge-test", - tool: "orchestrator_capabilities", - arguments: {}, - fetchImplementation: async (_url, init) => { - const headers = new Headers(init?.headers); - const body: unknown = JSON.parse(String(init?.body ?? "{}")); - requests.push({ body, headers }); - const request = body as { readonly id?: unknown; readonly method?: unknown }; - if (request.method === "notifications/initialized") { - return new Response(null, { status: 202 }); - } - return new Response( - JSON.stringify({ - jsonrpc: "2.0", - id: request.id, - result: - request.method === "initialize" - ? { protocolVersion: "2025-06-18", capabilities: {}, serverInfo: {} } - : { structuredContent: { providers: ["codex"] } }, - }), - { - headers: { "content-type": "application/json", "mcp-session-id": "session-42" }, - }, - ); - }, - }); - - expect(result).toEqual({ structuredContent: { providers: ["codex"] } }); - expect(requests).toHaveLength(3); - expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test"); - expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42"); - expect(requests[2]?.headers.get("mcp-protocol-version")).toBe("2025-06-18"); - expect(requests[2]?.body).toMatchObject({ - method: "tools/call", - params: { name: "orchestrator_capabilities", arguments: {} }, - }); - }), - ); +function pendingFetch(started: Deferred.Deferred) { + return (_url: string, init?: RequestInit): Promise => { + Deferred.doneUnsafe(started, Effect.succeed(init?.signal ?? undefined)); + return new Promise(() => {}); + }; +} +describe("AcpMcpStdioBridge", () => { it.effect("forwards requests and replays the session id and protocol version", () => Effect.gen(function* () { const { input, written, requests, bridge } = makeHarness((request) => { @@ -342,4 +290,43 @@ describe("AcpMcpStdioBridge", () => { expect(JSON.parse(written[0]!)).toMatchObject({ id: 7, result: {} }); }), ); + + it.effect("aborts the pending fetch when a tool call is interrupted", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const fiber = yield* mcpToolSession({ + endpoint: "http://127.0.0.1:1/mcp", + authorization: "Bearer bridge-test", + clientName: "t3-code-acp-cli", + fetchImplementation: pendingFetch(started), + }).pipe( + Effect.flatMap((session) => session.call("orchestrator_capabilities", {})), + Effect.scoped, + Effect.forkChild, + ); + + const signal = yield* Deferred.await(started); + yield* Fiber.interrupt(fiber); + expect(signal?.aborted).toBe(true); + }), + ); + + it.effect("aborts the pending fetch when the stdio bridge is interrupted", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const input = new NodeStream.PassThrough(); + const fiber = yield* runAcpMcpStdioBridge({ + endpoint: "http://127.0.0.1:1/mcp", + authorization: "Bearer bridge-test", + input, + output: { write: () => undefined }, + fetchImplementation: pendingFetch(started), + }).pipe(Effect.forkChild); + + input.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })}\n`); + const signal = yield* Deferred.await(started); + yield* Fiber.interrupt(fiber); + expect(signal?.aborted).toBe(true); + }), + ); }); diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index 82a3aaa16eb32..2e7c22ce00405 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -1,18 +1,15 @@ -// The bridge relays opaque JSON-RPC lines verbatim; schema-decoding foreign -// payloads here would reject traffic it must pass through untouched. +// Relay JSON-RPC verbatim; schema decoding would reject foreign payloads. // @effect-diagnostics nodeBuiltinImport:off preferSchemaOverJson:off import * as NodeReadline from "node:readline"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; -/** - * ACP agents must support stdio MCP servers, while optional http/sse support is - * unevenly implemented. - */ +/** ACP mandates stdio MCP support; HTTP/SSE support varies. */ export class AcpMcpBridgeError extends Error { readonly _tag = "AcpMcpBridgeError"; @@ -53,95 +50,126 @@ function protocolVersionOf(entry: unknown): string | null { return typeof version === "string" && version.length > 0 ? version : null; } -export interface AcpMcpToolCallOptions { +export interface McpToolSessionOptions { readonly endpoint: string; readonly authorization: string; - readonly tool: string; - readonly arguments: Readonly>; + readonly clientName: string; readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise; } +export interface McpToolSession { + /** Resolves to the JSON-RPC `result` of `tools/call`, a `CallToolResult`. */ + readonly call: ( + tool: string, + args: Readonly>, + ) => Effect.Effect; +} + /** - * This is the terminal fallback for ACP agents that accept `mcpServers` in - * `session/new` but fail to expose those tools to their model. Compliant ACP - * agents continue to use the stdio bridge above. + * One initialized MCP session over T3 Code's HTTP endpoint, terminated when + * the scope closes. Used by the ACP terminal fallback and `t3 thread`. */ -export function callAcpMcpTool( - options: AcpMcpToolCallOptions, -): Effect.Effect { +export const mcpToolSession = ( + options: McpToolSessionOptions, +): Effect.Effect => { const fetchImplementation = options.fetchImplementation ?? fetch; - return Effect.gen(function* () { - let sessionId: string | null = null; - let protocolVersion: string | null = null; + let sessionId: string | null = null; + let protocolVersion: string | null = null; + let nextId = 0; - const send = (message: unknown): Effect.Effect, AcpMcpBridgeError> => - Effect.gen(function* () { - const response = yield* Effect.tryPromise({ - try: () => - fetchImplementation(options.endpoint, { - method: "POST", - headers: { - "content-type": "application/json", - accept: "application/json, text/event-stream", - authorization: options.authorization, - ...(sessionId === null ? {} : { "mcp-session-id": sessionId }), - ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }), - }, - body: JSON.stringify(message), - }), - catch: bridgeError, - }); - sessionId = response.headers.get("mcp-session-id") ?? sessionId; - if (!response.ok) { - yield* discardResponseBody(response); - return yield* Effect.fail( - new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`), - ); - } - const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError)); - for (const payload of payloads) { - protocolVersion = protocolVersionOf(payload) ?? protocolVersion; - } - return payloads; - }); + const headers = () => ({ + accept: "application/json, text/event-stream", + authorization: options.authorization, + ...(sessionId === null ? {} : { "mcp-session-id": sessionId }), + ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }), + }); - const initializeId = "t3-acp-cli-initialize"; - const initialized = yield* send({ - jsonrpc: "2.0", - id: initializeId, - method: "initialize", - params: { - protocolVersion: MCP_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: "t3-code-acp-cli", version: "0.0.0" }, - }, + const send = Effect.fn("AcpMcpStdioBridge.send")(function* ( + message: unknown, + ): Effect.fn.Return, AcpMcpBridgeError> { + const response = yield* Effect.tryPromise({ + try: (signal) => + fetchImplementation(options.endpoint, { + method: "POST", + headers: { "content-type": "application/json", ...headers() }, + body: JSON.stringify(message), + signal, + }), + catch: bridgeError, }); - const initializeResponse = initialized.find((entry) => asEnvelope(entry)?.id === initializeId); - if (initializeResponse === undefined || asEnvelope(initializeResponse)?.error !== undefined) { + sessionId = response.headers.get("mcp-session-id") ?? sessionId; + if (!response.ok) { + yield* discardResponseBody(response); return yield* Effect.fail( - new AcpMcpBridgeError("T3 Code MCP endpoint rejected initialization."), + new AcpMcpBridgeError(`T3 Code MCP endpoint responded with HTTP ${response.status}.`), ); } - yield* send({ jsonrpc: "2.0", method: "notifications/initialized" }); + const payloads = yield* Stream.runCollect(responsePayloads(response, bridgeError)); + for (const payload of payloads) { + protocolVersion = protocolVersionOf(payload) ?? protocolVersion; + } + return payloads; + }); - const callId = "t3-acp-cli-tool-call"; - const responses = yield* send({ - jsonrpc: "2.0", - id: callId, - method: "tools/call", - params: { name: options.tool, arguments: options.arguments }, - }); - const response = responses.find((entry) => asEnvelope(entry)?.id === callId); - const envelope = asEnvelope(response); + const request = Effect.fn("AcpMcpStdioBridge.request")(function* ( + method: string, + params: unknown, + ): Effect.fn.Return { + const id = `t3-cli-${nextId++}`; + const responses = yield* send({ jsonrpc: "2.0", id, method, params }); + const envelope = asEnvelope(responses.find((entry) => asEnvelope(entry)?.id === id)); if (envelope === null || envelope.error !== undefined) { return yield* Effect.fail( new AcpMcpBridgeError( - `T3 Code MCP tool call failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`, + `T3 Code MCP ${method} failed${envelope?.error === undefined ? "." : `: ${JSON.stringify(envelope.error)}`}`, ), ); } - return envelope.result; + return envelope; + }); + + const terminate = Effect.suspend(() => + sessionId === null + ? Effect.void + : Effect.tryPromise(() => + fetchImplementation(options.endpoint, { method: "DELETE", headers: headers() }), + ).pipe(Effect.flatMap(discardResponseBody), Effect.ignore), + ); + + // Registered before the handshake so a session the server opened is ended + // even when the handshake fails, and the handshake stays interruptible. + return Effect.gen(function* () { + yield* Effect.addFinalizer(() => terminate); + yield* request("initialize", { + protocolVersion: MCP_PROTOCOL_VERSION, + capabilities: {}, + clientInfo: { name: options.clientName, version: "0.0.0" }, + }); + yield* send({ jsonrpc: "2.0", method: "notifications/initialized" }); + return { + call: (tool, args) => + request("tools/call", { name: tool, arguments: args }).pipe( + Effect.map((envelope) => envelope.result), + ), + } satisfies McpToolSession; }); +}; + +/** + * This is the terminal fallback for ACP agents that accept `mcpServers` in + * `session/new` but fail to expose those tools to their model. Compliant ACP + * agents continue to use the stdio bridge above. + */ +function callAcpMcpTool(options: { + readonly endpoint: string; + readonly authorization: string; + readonly tool: string; + readonly arguments: Readonly>; +}): Effect.Effect { + return mcpToolSession({ ...options, clientName: "t3-code-acp-cli" }).pipe( + Effect.flatMap((session) => session.call(options.tool, options.arguments)), + Effect.scoped, + ); } export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.Effect { @@ -156,13 +184,14 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. options.output.write(`${JSON.stringify(message)}\n`); }); - const handleServerPayload = (payload: unknown): Effect.Effect => - Effect.gen(function* () { - for (const entry of Array.isArray(payload) ? payload : [payload]) { - protocolVersion = protocolVersionOf(entry) ?? protocolVersion; - yield* writeMessage(entry); - } - }); + const handleServerPayload = Effect.fn("AcpMcpStdioBridge.handleServerPayload")(function* ( + payload: unknown, + ): Effect.fn.Return { + for (const entry of Array.isArray(payload) ? payload : [payload]) { + protocolVersion = protocolVersionOf(entry) ?? protocolVersion; + yield* writeMessage(entry); + } + }); const respondWithError = ( requestId: unknown, @@ -175,10 +204,12 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. error: { code, message }, }); - const forward = (line: string, envelope: JsonRpcEnvelope): Effect.Effect => - Effect.gen(function* () { + const forward: (line: string, envelope: JsonRpcEnvelope) => Effect.Effect = Effect.fn( + "AcpMcpStdioBridge.forward", + )( + function* (line: string, envelope: JsonRpcEnvelope) { const response = yield* Effect.tryPromise({ - try: () => + try: (signal) => fetchImplementation(options.endpoint, { method: "POST", headers: { @@ -189,6 +220,7 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }), }, body: line, + signal, }), catch: bridgeError, }); @@ -203,83 +235,82 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. return yield* discardResponseBody(response); } yield* Stream.runForEach(responsePayloads(response, bridgeError), handleServerPayload); - }).pipe( - Effect.catchCause((cause) => { - if (envelope.id === undefined) return Effect.void; - const error = Cause.squash(cause); - return respondWithError( - envelope.id, - `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`, - ); - }), - ); + }, + (effect, _line, envelope) => + effect.pipe( + Effect.catchCause((cause) => { + if (envelope.id === undefined) return Effect.void; + const error = Cause.squash(cause); + return respondWithError( + envelope.id, + `T3 Code MCP bridge request failed: ${error instanceof Error ? error.message : String(error)}`, + ); + }), + ), + ); - // Only session establishment is ordered; client responses to - // server-initiated SSE requests must bypass the barrier or they would - // deadlock the still-open HTTP exchange, and normal MCP calls stay - // concurrent after initialization. + // Order only session establishment; SSE responses must bypass it to avoid deadlock. Calls remain concurrent after initialization. let sessionBarrier: Effect.Effect = Effect.void; let sessionBarrierPending = false; - const launch = (task: Effect.Effect): Effect.Effect => - Effect.gen(function* () { - const fiber = yield* Effect.forkChild(task); + const launch = Effect.fn("AcpMcpStdioBridge.launch")(function* ( + task: Effect.Effect, + ): Effect.fn.Return { + const fiber = yield* Effect.forkChild(task); + running.add(fiber); + yield* Effect.forkChild( + Fiber.await(fiber).pipe( + Effect.andThen( + Effect.sync(() => { + running.delete(fiber); + }), + ), + ), + ); + }); + + const dispatch = Effect.fn("AcpMcpStdioBridge.dispatch")(function* ( + line: string, + ): Effect.fn.Return { + if (line.trim().length === 0) return; + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + return yield* respondWithError(null, "Parse error", -32700); + } + const envelope = asEnvelope(parsed); + if (envelope === null) return; + const isResponse = envelope.id !== undefined && ("result" in envelope || "error" in envelope); + const isSessionHandshake = + envelope.method === "initialize" || envelope.method === "notifications/initialized"; + if (isResponse) { + return yield* launch(forward(line, envelope)); + } + if (isSessionHandshake) { + const prior = sessionBarrier; + const fiber = yield* Effect.forkChild(prior.pipe(Effect.andThen(forward(line, envelope)))); running.add(fiber); + const barrier = Fiber.await(fiber).pipe(Effect.asVoid); + sessionBarrier = barrier; + sessionBarrierPending = true; yield* Effect.forkChild( Fiber.await(fiber).pipe( Effect.andThen( Effect.sync(() => { running.delete(fiber); + if (sessionBarrier === barrier) sessionBarrierPending = false; }), ), ), ); - }); - - const dispatch = (line: string): Effect.Effect => - Effect.gen(function* () { - if (line.trim().length === 0) return; - let parsed: unknown; - try { - parsed = JSON.parse(line); - } catch { - return yield* respondWithError(null, "Parse error", -32700); - } - const envelope = asEnvelope(parsed); - if (envelope === null) return; - const isResponse = - envelope.id !== undefined && ("result" in envelope || "error" in envelope); - const isSessionHandshake = - envelope.method === "initialize" || envelope.method === "notifications/initialized"; - if (isResponse) { - return yield* launch(forward(line, envelope)); - } - if (isSessionHandshake) { - const prior = sessionBarrier; - const fiber = yield* Effect.forkChild( - prior.pipe(Effect.andThen(forward(line, envelope))), - ); - running.add(fiber); - const barrier = Fiber.await(fiber).pipe(Effect.asVoid); - sessionBarrier = barrier; - sessionBarrierPending = true; - yield* Effect.forkChild( - Fiber.await(fiber).pipe( - Effect.andThen( - Effect.sync(() => { - running.delete(fiber); - if (sessionBarrier === barrier) sessionBarrierPending = false; - }), - ), - ), - ); - return; - } - const task = sessionBarrierPending - ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope))) - : forward(line, envelope); - return yield* launch(task); - }); + return; + } + const task = sessionBarrierPending + ? sessionBarrier.pipe(Effect.andThen(forward(line, envelope))) + : forward(line, envelope); + return yield* launch(task); + }); const reader = NodeReadline.createInterface({ input: options.input }); yield* Stream.runForEach(Stream.fromAsyncIterable(reader, bridgeError), dispatch).pipe( @@ -289,10 +320,7 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. }); } -/** - * Kept free of heavy imports: these commands run on the ACP first-message - * critical path. - */ +/** Avoid heavy imports on the ACP first-message path. */ export async function runAcpMcpCliFastPath( command: "acp-mcp-bridge" | "acp-mcp-call", args: ReadonlyArray, diff --git a/apps/server/src/mcp/McpDeviceToolkit.test.ts b/apps/server/src/mcp/McpDeviceToolkit.test.ts index 8e80b30a7f10f..967f9e138c1b2 100644 --- a/apps/server/src/mcp/McpDeviceToolkit.test.ts +++ b/apps/server/src/mcp/McpDeviceToolkit.test.ts @@ -9,10 +9,12 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import { McpSchema, McpServer } from "effect/ai"; import * as ServerConfig from "../config.ts"; import * as DeviceService from "../device/DeviceService.ts"; +import * as ProjectService from "../project/ProjectService.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts"; @@ -83,9 +85,30 @@ new DataView(png.buffer).setUint32(12, 0x49484452); new DataView(png.buffer).setUint32(16, 1206); new DataView(png.buffer).setUint32(20, 2622); +const unused = Effect.die("not used"); +const readiness = { + hostId: "local", + nodePath: process.execPath, + hub: { origin: "http://hub.test" }, + devices: { + list: unused, + boot: () => unused, + attach: () => unused, + shutdown: () => unused, + screenshot: () => unused, + }, + run: () => unused, + helpers: { serveSimAxSettings: null, serveSimCli: null }, + agentDevice: null, +}; +const layerProjectsMock = Layer.mock(ProjectService.ProjectService)({ + getById: () => Effect.succeed(Option.none()), +}); + const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({ state: Effect.succeed(state), list: Effect.succeed(state), + agentReadinessIfSupported: () => Effect.succeed(readiness), open: (input) => Effect.succeed({ threadId: input.threadId, @@ -113,13 +136,19 @@ const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({ close: () => Effect.void, agentCli: Effect.succeed("/cli"), testHost: () => Effect.die("not used"), - agentTarget: () => Effect.succeed(["--config", "/host.json", "--session", "thread-device"]), + // As for an EAS device, agent-device knows the device by a different id than T3. + agentTarget: () => + Effect.succeed({ + agentDeviceId: "SIM-UDID", + args: ["--config", "/host.json", "--session", "thread-device"], + }), }); const layerTest = McpHttpServer.layerDeviceToolkit.pipe( Layer.provideMerge(McpServer.McpServer.layer), Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer), Layer.provideMerge(layerDeviceServiceMock), + Layer.provide(layerProjectsMock), Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" })), Layer.provide(NodeServices.layer), ); @@ -139,7 +168,7 @@ it.effect("registers the device tools and returns the screenshot as image conten .pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client)); expect(opened.isError).toBe(false); const openedContent = opened.structuredContent as { quickStart: string }; - expect(openedContent.quickStart).toContain("--udid UDID-1"); + expect(openedContent.quickStart).toContain("--udid SIM-UDID"); const shot = yield* server .callTool({ name: "device_screenshot", arguments: { deviceId: "UDID-1" } }) @@ -167,7 +196,7 @@ it.effect("registers the device tools and returns the screenshot as image conten it.effect("rejects unavailable agent access before booting or opening a device", () => { const layerUnavailable = Layer.mock(DeviceService.DeviceService)({ list: Effect.succeed(state), - agentTarget: () => + agentReadinessIfSupported: () => Effect.fail( new DeviceHostUnavailableError({ hostId: "local", reason: "Agent access is disabled." }), ), @@ -197,6 +226,7 @@ it.effect("rejects unavailable agent access before booting or opening a device", Layer.provideMerge(McpServer.McpServer.layer), Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer), Layer.provide(layerUnavailable), + Layer.provide(layerProjectsMock), Layer.provide( ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }), ), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 9d28aeb4dfc1b..27e93f2ecefdb 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -12,19 +12,11 @@ import { } from "@t3tools/contracts"; 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 Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; -import { - HttpBody, - HttpClient, - HttpClientRequest, - HttpRouter, - HttpServerResponse, -} from "effect/http"; +import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http"; import * as ProjectService from "../project/ProjectService.ts"; import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts"; @@ -34,11 +26,13 @@ import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; +import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; +import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts"; +import { ProjectToolkit } from "./toolkits/project/tools.ts"; const environmentId = EnvironmentId.make("environment-mcp-test"); const threadId = ThreadId.make("thread-mcp-test"); -const tabId = PreviewTabId.make("tab-mcp-test"); const alternateTabId = PreviewTabId.make("tab-mcp-alternate"); const decodeJsonText = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); const invocation = { @@ -125,28 +119,53 @@ const serveSnapshots = (clientId: string, result: unknown) => return inputs; }); -const callSnapshot = (args: Record) => +const callTool = (name: string, args: Record) => Effect.gen(function* () { const server = yield* McpServer.McpServer; return yield* server - .callTool({ name: "preview_snapshot", arguments: args }) + .callTool({ name, arguments: args }) .pipe( Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), Effect.provideService(McpSchema.McpServerClient, client), ); }); -it("normalizes empty successful notification responses to accepted", () => { - const notificationResponse = McpHttpServer.normalizeMcpHttpResponse( - HttpServerResponse.text("", { status: 200, contentType: "application/json" }), - ); - expect(notificationResponse.status).toBe(202); +const callSnapshot = (args: Record) => callTool("preview_snapshot", args); - const resultResponse = McpHttpServer.normalizeMcpHttpResponse( - HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }), +const layerRecordingTools = (calls: Array) => { + const RecordingToolkit = Toolkit.make( + OrchestratorToolkit.tools.delegate_task, + OrchestratorToolkit.tools.t3_thread_read, + OrchestratorToolkit.tools.t3_thread_wait, + ProjectToolkit.tools.t3_project_update, ); - expect(resultResponse.status).toBe(200); -}); + const record = McpToolAccess.reads((params: unknown) => + Effect.sync(() => calls.push(params)).pipe( + Effect.andThen( + Effect.fail(new OrchestratorMcpFailure({ code: "thread_not_found", message: "Recorded." })), + ), + ), + ); + return McpHttpServer.toolkitRegistration( + RecordingToolkit, + McpToolAccess.toLayer(RecordingToolkit, { + delegate_task: record, + t3_thread_read: record, + t3_thread_wait: record, + t3_project_update: record, + }), + ).pipe( + Layer.provideMerge(McpServer.McpServer.layer), + Layer.provide( + Layer.mergeAll( + McpToolAccessTestkit.liveThreadsLayer, + Layer.mock(OrchestratorMcpService.OrchestratorMcpService)({}), + Layer.mock(ProjectService.ProjectService)({}), + NodeServices.layer, + ), + ), + ); +}; it.effect.each([{}, { includeImage: false }])( "returns bounded structural preview snapshot failures %#", @@ -200,56 +219,6 @@ it.effect.each([{}, { includeImage: false }])( ).pipe(Effect.provide(layerTest)), ); -it.effect.each([ - { args: {}, advice: "No active preview tab was found for snapshot. Call preview_open first." }, - { - args: { tabId: alternateTabId }, - advice: `Preview tab ${alternateTabId} was not found for snapshot. Omit tabId to use the current tab, or call preview_open.`, - }, -])("tells the agent to open a tab when the snapshot has none $args", ({ args, advice }) => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker; - const connected = yield* Deferred.make(); - const events = yield* broker.connect({ clientId: "mcp-no-tab-client", environmentId }); - yield* Stream.runForEach(events, (event) => - event.type === "connected" - ? Deferred.succeed(connected, undefined) - : broker.respond({ - clientId: "mcp-no-tab-client", - connectionId: event.connectionId, - requestId: event.request.requestId, - ok: false, - error: { _tag: "PreviewAutomationTabNotFoundError", message: "no tab" }, - }), - ).pipe(Effect.forkScoped); - yield* Deferred.await(connected); - - const snapshot = yield* callSnapshot(args); - - expect(snapshot.isError).toBe(true); - expect(snapshot.content).toEqual([ - { type: "text", text: `Preview snapshot failed: ${advice}` }, - ]); - }), - ).pipe(Effect.provide(layerTest)), -); - -it.effect("tells the agent how to recover when no preview host can run the snapshot", () => - Effect.gen(function* () { - const snapshot = yield* callSnapshot({}); - - expect(snapshot.isError).toBe(true); - const [text] = snapshot.content; - expect(text?.type === "text" ? text.text : "").toContain( - "Retry preview_status, then call preview_open", - ); - expect(snapshot.structuredContent).toMatchObject({ - error: { _tag: "PreviewAutomationNoAvailableHostError" }, - }); - }).pipe(Effect.provide(layerTest)), -); - it.effect.each([ { mode: "default", input: {}, images: false }, { mode: "explicit image", input: { includeImage: true }, images: true }, @@ -387,87 +356,81 @@ it.effect("refuses preview tools to a client outside a thread before they run", }).pipe(Effect.provide(layerTest)), ); -it.effect("rejects non-boolean snapshot image options before selecting a browser host", () => - Effect.gen(function* () { - const server = yield* McpServer.McpServer; - for (const includeImage of ["false", 0, null]) { - const result = yield* server - .callTool({ - name: "preview_snapshot", - arguments: { includeImage }, - }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.provideService(McpSchema.McpServerClient, client), - ); - expect(result.isError).toBe(true); - expect(result.content).toEqual([{ type: "text", text: "Preview snapshot failed: AiError." }]); - expect(result.structuredContent).toEqual({ - error: { _tag: "AiError", operation: "snapshot", failureCount: 1 }, - }); - } - }).pipe(Effect.provide(layerTest)), -); - -it.effect("saves the snapshot PNG on request and reports its path", () => - Effect.scoped( - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const inputs = yield* serveSnapshots("mcp-save-client", snapshotResult); - - const snapshot = yield* callSnapshot({ save: true, includeImage: true }); - - expect(snapshot.isError).toBe(false); - expect(inputs).toEqual([{}]); - expect(snapshot.content.map((content) => content.type)).toContain("image"); - const structured = snapshot.structuredContent as { readonly screenshotPath?: string }; - const screenshotPath = structured.screenshotPath; - expect(typeof screenshotPath).toBe("string"); - expect(path.dirname(screenshotPath!)).toBe(config.browserArtifactsDir); - expect(path.basename(screenshotPath!)).toMatch( - /^browser-screenshot-example-test-[0-9a-z]+-[0-9a-f]{8}\.png$/, - ); - expect(Buffer.from(yield* fileSystem.readFile(screenshotPath!)).toString()).toBe("png"); - const [, text] = snapshot.content; - expect(text?.type === "text" ? text.text : "").toContain(screenshotPath); +it.effect("decodes null optional arguments the way it decodes omitted ones", () => { + const calls: Array = []; + return Effect.gen(function* () { + const thread = { threadId: "thread-null-arguments" }; + yield* callTool("t3_thread_read", thread); + yield* callTool("t3_thread_read", { ...thread, afterPosition: null, view: null }); + yield* callTool("delegate_task", { task: "Inspect", target: {} }); + yield* callTool("delegate_task", { task: "Inspect", title: null, target: { model: null } }); + yield* callTool("t3_project_update", { projectId: "project-1", projectIcon: null }); + + expect(calls).toHaveLength(5); + expect(calls[1]).toEqual(calls[0]); + expect(calls[3]).toEqual(calls[2]); + expect(calls[4]).toStrictEqual({ projectId: "project-1", projectIcon: null }); + }).pipe(Effect.provide(layerRecordingTools(calls))); +}); - const unsaved = yield* callSnapshot({}); - expect(unsaved.structuredContent).not.toHaveProperty("screenshotPath"); +it.effect( + "clamps t3_thread_read page sizes above their maximum instead of rejecting the call", + () => { + const calls: Array = []; + return Effect.gen(function* () { + const thread = { threadId: "thread-clamped-arguments" }; + // Codex never shows the model these bounds, so an over-large page must still read. + yield* callTool("t3_thread_read", { + ...thread, + limit: 150, + runLimit: 80, + maxCharsPerItem: 60_000, + }); + yield* callTool("t3_thread_read", { + ...thread, + limit: 100, + runLimit: 50, + maxCharsPerItem: 50_000, + }); + yield* callTool("t3_thread_read", { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 }); - const pathOnly = yield* callSnapshot({ save: true }); - const saved = pathOnly.structuredContent as { readonly screenshotPath: string }; - expect(saved).toEqual({ url: snapshotResult.url, screenshotPath: expect.any(String) }); - expect(Buffer.from(yield* fileSystem.readFile(saved.screenshotPath)).toString()).toBe("png"); - const [only, ...others] = pathOnly.content; - expect(others).toEqual([]); - expect(only?.type === "text" ? decodeJsonText(only.text) : null).toEqual(saved); - }), - ).pipe(Effect.provide(layerTest)), + expect(calls).toEqual([ + { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 }, + { ...thread, limit: 100, runLimit: 50, maxCharsPerItem: 50_000 }, + { ...thread, limit: 7, runLimit: 1, maxCharsPerItem: 1 }, + ]); + }).pipe(Effect.provide(layerRecordingTools(calls))); + }, ); -it.effect("reports a tagged error when the screenshot cannot be saved", () => - Effect.scoped( - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - yield* fileSystem.writeFileString(config.browserArtifactsDir, ""); - yield* serveSnapshots("mcp-save-failure-client", snapshotResult); - - const snapshot = yield* callSnapshot({ save: true }); - - expect(snapshot.isError).toBe(true); - expect(snapshot.content).toEqual([ - { type: "text", text: "Preview snapshot failed: PreviewScreenshotSaveError." }, - ]); - expect(snapshot.structuredContent).toEqual({ - error: { _tag: "PreviewScreenshotSaveError", operation: "snapshot", failureCount: 1 }, - }); - }), - ).pipe(Effect.provide(layerTest)), +it.effect.each(["limit", "runLimit", "maxCharsPerItem"])( + "still rejects a t3_thread_read %s below its minimum", + (field) => { + const calls: Array = []; + return Effect.gen(function* () { + // Zero is a different request than one item, so it fails rather than answering another question. + const rejected = yield* callTool("t3_thread_read", { + threadId: "thread-below-minimum", + [field]: 0, + }).pipe(Effect.flip); + + expect(String(rejected)).toContain("greater than or equal to 1"); + expect(calls).toEqual([]); + }).pipe(Effect.provide(layerRecordingTools(calls))); + }, ); +it("routes same-child follow-ups to t3_thread_send and independent reviews to delegate_task", () => { + const description = OrchestratorToolkit.tools.delegate_task.description ?? ""; + expect(description).toContain( + "For independent T3 delegated review rounds, call delegate_task again", + ); + expect(description).toContain( + "For a follow-up that needs the same child's conversation, use t3_thread_send on its childThreadId.", + ); + expect(description).not.toContain("not the target for starting another"); +}); + it.effect( "registers the pull request toolkit and surfaces a missing capability as a tool error", () => @@ -499,24 +462,6 @@ it.effect( }).pipe(Effect.provide(layerPullRequestsTest)), ); -it.effect("returns server ARIA refs to agents in text and structured results", () => - Effect.scoped( - Effect.gen(function* () { - const accessibilityTree = - '- button "delete" [ref=t3-snapshot-e1]\n- iframe [ref=t3-snapshot-e2]:\n - textbox "child" [ref=t3-snapshot-f1e1]'; - yield* serveSnapshots("mcp-server-refs", { ...snapshotResult, accessibilityTree }); - const result = yield* callSnapshot({ includeImage: false }); - expect(result.isError).toBe(false); - expect(result.structuredContent).toMatchObject({ accessibilityTree }); - expect( - result.content.some( - (entry) => entry.type === "text" && entry.text.includes("t3-snapshot-f1e1"), - ), - ).toBe(true); - }), - ).pipe(Effect.provide(layerTest)), -); - it.effect("bounds large ARIA trees without dropping every server locator", () => Effect.scoped( Effect.gen(function* () { @@ -597,7 +542,6 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => expect(parsed.consoleEntries[0]?.text).toBe("entry 60"); expect(notice?.type === "text" ? notice.text : "").toContain("accessibilityTree"); expect(notice?.type === "text" ? notice.text : "").toContain("60 older console entries"); - // Claude Code shows the model structuredContent instead of the text, so it is bounded too. expect(snapshot.structuredContent).toEqual({ ...parsed, omitted: expect.arrayContaining(["60 older console entries"]), @@ -606,6 +550,7 @@ it.effect("keeps the snapshot text under the agent's output ceiling", () => ).pipe(Effect.provide(layerTest)), ); +// regression: #10501 keep preview snapshots usable by the agent it.effect("bounds the snapshot text even when nothing but logs and the title are large", () => Effect.scoped( Effect.gen(function* () { @@ -638,6 +583,7 @@ it.effect("bounds the snapshot text even when nothing but logs and the title are ).pipe(Effect.provide(layerTest)), ); +// regression: #13558 preview snapshots overflowed the agent's tool output it.effect("bounds page text made of wide characters before dropping locators", () => Effect.scoped( Effect.gen(function* () { @@ -676,71 +622,6 @@ it.effect("bounds page text made of wide characters before dropping locators", ( ).pipe(Effect.provide(layerTest)), ); -it.effect("sheds log entries before locators when every list is full", () => - Effect.scoped( - Effect.gen(function* () { - const long = "x".repeat(2_000); - const oversized = { - ...snapshotResult, - interactiveElements: Array.from({ length: 20 }, (_, i) => ({ - tag: "button", - role: "button", - name: `Button ${i}`, - selector: `#button-${i}`, - x: 0, - y: 0, - width: 10, - height: 10, - })), - consoleEntries: Array.from({ length: 200 }, () => ({ - level: long, - text: long, - timestamp: long, - source: long, - })), - networkEntries: Array.from({ length: 200 }, () => ({ - url: long, - method: long, - status: 200, - failed: false, - errorText: long, - timestamp: long, - })), - actionTimeline: Array.from({ length: 200 }, () => ({ - id: long, - action: long, - status: "succeeded", - startedAt: long, - completedAt: long, - error: long, - })), - }; - yield* serveSnapshots("mcp-full-logs-client", oversized); - - const snapshot = yield* callSnapshot({ includeImage: false }); - - const [, text, notice] = snapshot.content; - const body = text?.type === "text" ? text.text : ""; - expect(Buffer.byteLength(body, "utf8")).toBeLessThanOrEqual( - McpHttpServer.MAX_SNAPSHOT_TEXT_BYTES, - ); - const parsed = decodeJsonText(body) as { - readonly interactiveElements: ReadonlyArray; - readonly consoleEntries: ReadonlyArray; - readonly networkEntries: ReadonlyArray; - readonly actionTimeline: ReadonlyArray; - }; - expect(parsed.interactiveElements).toHaveLength(20); - expect( - parsed.consoleEntries.length + parsed.networkEntries.length + parsed.actionTimeline.length, - ).toBeLessThan(120); - const noticeText = notice?.type === "text" ? notice.text : ""; - expect(noticeText).toContain("40 of 40 actionTimeline"); - expect(noticeText).not.toMatch(/\d+ of \d+ interactiveElements/); - }), - ).pipe(Effect.provide(layerTest)), -); - it.effect("terminates HTTP MCP sessions with DELETE", () => Effect.scoped( Effect.gen(function* () { @@ -816,155 +697,6 @@ it.effect("terminates HTTP MCP sessions with DELETE", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); -it.effect("registers annotated tools and preserves authenticated request context", () => - Effect.scoped( - Effect.gen(function* () { - const server = yield* McpServer.McpServer; - const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker; - const toolIcon = { - _tag: "website" as const, - pageUrl: "http://example.test/", - }; - const routedRequests: Array<{ - readonly operation: string; - readonly tabId?: string | undefined; - }> = []; - const events = yield* broker.connect({ - clientId: "mcp-test-client", - environmentId, - }); - yield* Stream.runForEach(events, (event) => { - if (event.type === "connected") return Effect.void; - routedRequests.push(event.request); - return broker.respond({ - clientId: "mcp-test-client", - connectionId: event.connectionId, - requestId: event.request.requestId, - ok: true, - result: - event.request.operation === "snapshot" - ? snapshotResult - : event.request.operation === "evaluate" - ? ["Connect", "Continue"] - : event.request.operation === "press" - ? undefined - : { - available: true, - visible: true, - tabId, - url: "http://example.test/", - title: "Example", - loading: false, - }, - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status"); - expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true); - expect(statusTool?.tool.annotations?.idempotentHint).toBe(true); - expect(statusTool?.tool.annotations?.destructiveHint).toBe(false); - - const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot"); - expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(false); - expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(false); - expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true); - - const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click"); - expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false); - expect(clickTool?.tool.annotations?.destructiveHint).toBe(true); - expect(clickTool?.tool.annotations?.openWorldHint).toBe(true); - expect(clickTool?.tool.outputSchema).toMatchObject({ - type: "object", - additionalProperties: true, - description: "The preview action completed successfully.", - }); - - const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate"); - expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false); - expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true); - - const status = yield* server - .callTool({ name: "preview_status", arguments: {} }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.provideService(McpSchema.McpServerClient, client), - ); - expect(status.isError).toBe(false); - expect(status.structuredContent).toMatchObject({ - available: true, - tabId, - }); - - const malformed = yield* server - .callTool({ name: "preview_click", arguments: { selector: "" } }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.provideService(McpSchema.McpServerClient, client), - Effect.flip, - ); - expect(malformed._tag).toBe("InvalidParams"); - - const snapshot = yield* server - .callTool({ - name: "preview_snapshot", - arguments: { tabId: alternateTabId, includeImage: true }, - }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.provideService(McpSchema.McpServerClient, client), - ); - expect(snapshot.isError).toBe(false); - expect(snapshot.content.some((content) => content.type === "image")).toBe(true); - expect(snapshot.structuredContent).toMatchObject({ - screenshot: { mimeType: "image/png", width: 10, height: 5 }, - }); - expect(routedRequests.find(({ operation }) => operation === "snapshot")?.tabId).toBe( - alternateTabId, - ); - - // Arrays and primitives are wrapped so structuredContent stays a JSON object. - // Claude Code rejects the whole result otherwise. - const evaluateTool = server.tools.find(({ tool }) => tool.name === "preview_evaluate"); - expect(evaluateTool?.tool.outputSchema).toMatchObject({ type: "object" }); - const evaluated = yield* server - .callTool({ name: "preview_evaluate", arguments: { expression: "buttons()" } }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.provideService(McpSchema.McpServerClient, client), - ); - expect(evaluated.isError).toBe(false); - expect(evaluated.structuredContent).toEqual({ value: ["Connect", "Continue"], toolIcon }); - const evaluatedText = evaluated.content[0]; - expect(evaluatedText?.type === "text" ? decodeJsonText(evaluatedText.text) : null).toEqual({ - toolIcon, - value: ["Connect", "Continue"], - }); - - const actionRequests = [ - { name: "preview_click", arguments: { x: 10, y: 10 } }, - { name: "preview_type", arguments: { text: "Hello" } }, - { name: "preview_press", arguments: { key: "Enter" } }, - { name: "preview_scroll", arguments: { deltaY: 100 } }, - { name: "preview_wait_for", arguments: { text: "Example" } }, - ]; - for (const request of actionRequests) { - const result = yield* server - .callTool(request) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.provideService(McpSchema.McpServerClient, client), - ); - expect(result.isError).toBe(false); - expect(result.structuredContent).toEqual({ toolIcon }); - expect(routedRequests.at(-1)?.operation).toBe("status"); - const text = result.content[0]; - expect(text?.type === "text" ? decodeJsonText(text.text) : null).toEqual({ toolIcon }); - } - }), - ).pipe(Effect.provide(layerTest)), -); - it.effect("admits provider and OAuth client credentials and points only clients at OAuth", () => Effect.scoped( Effect.gen(function* () { @@ -1085,3 +817,90 @@ it.effect("admits provider and OAuth client credentials and points only clients }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + +it.effect("lists pull request watch tools only to threads that are not delegated children", () => + Effect.scoped( + Effect.gen(function* () { + const scopeFor = ( + token: string, + subagent: boolean, + ): McpInvocationContext.McpThreadInvocationScope => ({ + environmentId, + requestNamespace: token, + thread: { + threadId: ThreadId.make(`thread-${token}`), + providerSessionId: token, + providerInstanceId: ProviderInstanceId.make("codex"), + subagent, + }, + client: undefined, + capabilities: new Set(["pull-requests"]), + issuedAt: 1, + }); + const scopes = new Map([ + ["parentToken", scopeFor("parentToken", false)], + ["childToken", scopeFor("childToken", true)], + ]); + const serverLayer = McpHttpServer.layerPullRequestsToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerMcpTransport), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: (token) => Effect.succeed(scopes.get(token)), + }), + ), + Layer.provide( + Layer.mergeAll( + McpToolAccessTestkit.liveThreadsLayer, + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), + Layer.mock(Orchestrator.OrchestratorV2)({}), + Layer.mock(ProjectionStore.ProjectionStoreV2)({}), + NodeServices.layer, + ), + ), + ); + yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe( + Layer.build, + ); + const httpClient = yield* HttpClient.HttpClient; + const listedTools = (token: string) => + Effect.gen(function* () { + const headers = { + accept: "application/json, text/event-stream", + authorization: `Bearer ${token}`, + }; + const initialize = yield* httpClient.post("/mcp", { + headers, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`, + "application/json", + ), + }); + const listed = yield* httpClient.post("/mcp", { + headers: { + ...headers, + "mcp-session-id": initialize.headers["mcp-session-id"]!, + "mcp-protocol-version": "2025-06-18", + }, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`, + "application/json", + ), + }); + const body = (yield* listed.json) as { + readonly result: { readonly tools: ReadonlyArray<{ readonly name: string }> }; + }; + return body.result.tools.map((tool) => tool.name); + }); + + const parentTools = yield* listedTools("parentToken"); + const childTools = yield* listedTools("childToken"); + expect(parentTools).toEqual( + expect.arrayContaining(["link_pull_request", "watch_pull_request", "unwatch_pull_request"]), + ); + expect(childTools).toContain("link_pull_request"); + expect(childTools).not.toContain("watch_pull_request"); + expect(childTools).not.toContain("unwatch_pull_request"); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index cd2ccf1416389..5a4e62e3b2417 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -11,9 +11,14 @@ import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import type * as Types from "effect/Types"; -import { AiError, McpProtocol, McpSchema, McpServer, Tool, type Toolkit } from "effect/ai"; +import { AiError, McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai"; import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; -import { OrchestratorMcpFailure, PreviewAutomationError } from "@t3tools/contracts"; +import { + OrchestratorMcpFailure, + PreviewAutomationError, + type RunId, + ThreadId, +} from "@t3tools/contracts"; import packageJson from "../../package.json" with { type: "json" }; import * as ServerConfig from "../config.ts"; @@ -21,6 +26,15 @@ import * as DeviceService from "../device/DeviceService.ts"; import * as HtmlRender from "../htmlRender/HtmlRender.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; +import { + type AgentThread, + agentToolProperties, + handoffSettings, + MAX_REPORTED_DEPTH, + toolOutcome, +} from "../telemetry/ProviderDimensions.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; @@ -64,11 +78,7 @@ const mcpResourceMetadataUrl = (request: HttpServerRequest.HttpServerRequest) => Option.map((url) => `${url.origin}/.well-known/oauth-protected-resource/mcp`), ); -/** - * Agents T3 Code launched carry a registry token and must never be sent into an - * OAuth flow when it dies: they cannot open a browser, and a sign-in would mint - * a credential that outlives their session. - */ +/** Launched agents cannot open OAuth browsers; OAuth would mint credentials outliving their session. */ const unauthorized = (input: { readonly request: HttpServerRequest.HttpServerRequest; readonly presentedToken: boolean; @@ -124,7 +134,7 @@ type McpAuthMiddleware = ( HttpServerRequest.HttpServerRequest >; -export const normalizeMcpHttpResponse = ( +const normalizeMcpHttpResponse = ( response: HttpServerResponse.HttpServerResponse, ): HttpServerResponse.HttpServerResponse => { const bodyIsEmpty = @@ -175,13 +185,7 @@ const layerMcpAuthMiddleware = HttpRouter.middleware<{ provides: McpInvocationContext.McpInvocationContext; }>()(makeMcpAuthMiddleware).layer; -/** - * Claude Code moves an MCP result above its output limit to a file and hands - * the agent a notice instead, so a snapshot that carries the full accessibility - * tree and page text loses its locators too. Claude Code also shows the model - * `structuredContent` in place of the text blocks when a result has both, so - * both carry the same bounded snapshot. - */ +/** Claude Code spills oversized results to files, losing locators; bound both text and its preferred structuredContent. */ export const MAX_SNAPSHOT_TEXT_BYTES = 20_000; const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000; const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200; @@ -266,8 +270,7 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { actionTimeline: tail(metadata.actionTimeline, "action timeline entries"), }; - // Per-field caps do not sum below the ceiling: three log arrays of 40 capped - // entries alone can pass 60 KB, and the caps count characters, not bytes. + // Per-field character caps can still exceed the total byte ceiling. const shedOrder = [ "actionTimeline", "networkEntries", @@ -316,7 +319,6 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { } else { const keep = Math.floor(lists[key].length / 2); dropped[key] += lists[key].length - keep; - // slice(-0) keeps everything, so spell out the empty case. lists[key] = keep === 0 ? [] @@ -386,6 +388,16 @@ const saveScreenshot = Effect.fn("McpHttpServer.saveScreenshot")(function* ( return screenshotPath; }); +/** Decode with the advertised JSON codec, which permits null for optional fields that the raw schema rejects. */ +const decodeAsAdvertised = >( + toolkit: Toolkit.Toolkit, +): Toolkit.Toolkit => + Toolkit.make( + ...Object.values(toolkit.tools).map((tool) => + tool.setParameters(Schema.toCodecJson(tool.parametersSchema)), + ), + ) as unknown as Toolkit.Toolkit; + const isPreviewAutomationError = Schema.is(PreviewAutomationError); const previewSnapshotFailure = (cause: Cause.Cause) => { @@ -401,8 +413,7 @@ const previewSnapshotFailure = (cause: Cause.Cause) => { typeof firstFailure._tag === "string" ? firstFailure._tag : "PreviewSnapshotError"; - // Preview errors build their message on the server, never from page output, - // and it tells the agent what to do next, such as falling back to a shell browser. + // Preview errors contain server-authored recovery guidance, never page output. const message = isPreviewAutomationError(firstFailure) ? firstFailure.message : undefined; const result = new McpSchema.CallToolResult({ isError: true, @@ -431,7 +442,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot const saveServices = yield* Effect.context< ServerConfig.ServerConfig | FileSystem.FileSystem | Path.Path | Crypto.Crypto >(); - const built = yield* PreviewSnapshotToolkit; + const built = yield* decodeAsAdvertised(PreviewSnapshotToolkit); const tool = PreviewSnapshotTool; yield* server.addTool({ tool: new McpSchema.Tool({ @@ -478,8 +489,7 @@ const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot const png = new Uint8Array(Buffer.from(screenshot.data, "base64")); const screenshotPath = payload?.save === true ? yield* saveScreenshot(snapshot.url, png) : undefined; - // Images stay out of tool history unless asked for: providers replay them on every - // later request, and some reject inline images outright. + // Providers replay images on later requests, and some reject them; include images only when requested. const includeImage = payload?.includeImage === true; if (screenshotPath !== undefined && !includeImage) { const saved = { @@ -551,11 +561,7 @@ interface ImageToolResult { readonly [key: string]: unknown; } -/** - * Failures surface only their tag unless the tool describes them: the remote - * message may carry renderer or device output the agent should not see, and the - * tag is what it can act on. - */ +/** Expose only undescribed failures' tags; remote messages may contain renderer or device output. */ const imageToolFailure = (toolName: string, operation: string, failureText: string | ((error: E) => string)) => (cause: Cause.Cause) => { @@ -604,7 +610,11 @@ const imageToolFailure = * `McpServer.toolkit` serializes every result as JSON text, which is the wrong * shape for a screenshot: the model needs image content. */ -const registerImageTool = ( +const registerImageTool = Effect.fn("McpHttpServer.registerImageTool")(function* < + T extends Tool.Any, + E, + R, +>( tool: T, handle: (payload: Tool.Parameters) => Effect.Effect<{ readonly encodedResult: unknown }, E, R>, provide: ( @@ -616,78 +626,77 @@ const registerImageTool = ( >, operation: string, failureText: string | ((error: E) => string), -) => - Effect.gen(function* () { - const server = yield* McpServer.McpServer; - yield* server.addTool({ - tool: new McpSchema.Tool({ - name: tool.name, - description: Tool.getDescription(tool), - inputSchema: Tool.getJsonSchema(tool), - annotations: { - ...Context.getOption(tool.annotations, Tool.Title).pipe( - Option.map((title) => ({ title })), - Option.getOrUndefined, - ), - readOnlyHint: Context.get(tool.annotations, Tool.Readonly), - destructiveHint: Context.get(tool.annotations, Tool.Destructive), - idempotentHint: Context.get(tool.annotations, Tool.Idempotent), - openWorldHint: Context.get(tool.annotations, Tool.OpenWorld), - }, +) { + const server = yield* McpServer.McpServer; + yield* server.addTool({ + tool: new McpSchema.Tool({ + name: tool.name, + description: Tool.getDescription(tool), + inputSchema: Tool.getJsonSchema(tool), + annotations: { + ...Context.getOption(tool.annotations, Tool.Title).pipe( + Option.map((title) => ({ title })), + Option.getOrUndefined, + ), + readOnlyHint: Context.get(tool.annotations, Tool.Readonly), + destructiveHint: Context.get(tool.annotations, Tool.Destructive), + idempotentHint: Context.get(tool.annotations, Tool.Idempotent), + openWorldHint: Context.get(tool.annotations, Tool.OpenWorld), + }, + }), + annotations: tool.annotations, + handle: (payload) => + Effect.withFiber((fiber) => { + const invocation = Context.getUnsafe( + fiber.context, + McpInvocationContext.McpInvocationContext, + ); + return provide(handle(payload as Tool.Parameters)).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.matchCauseEffect({ + onFailure: imageToolFailure(tool.name, operation, failureText), + onSuccess: ({ encodedResult }) => { + const { screenshot, ...rest } = encodedResult as ImageToolResult; + const includeImage = + (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !== + false; + const metadata = { + ...rest, + screenshot: { + mimeType: screenshot.mimeType, + width: screenshot.width, + height: screenshot.height, + }, + }; + return Effect.succeed( + new McpSchema.CallToolResult({ + isError: false, + structuredContent: metadata, + content: [ + { type: "text", text: JSON.stringify(metadata) }, + ...(includeImage + ? [ + { + type: "image" as const, + data: new Uint8Array(Buffer.from(screenshot.data, "base64")), + mimeType: screenshot.mimeType, + }, + ] + : []), + ], + }), + ); + }, + }), + ); }), - annotations: tool.annotations, - handle: (payload) => - Effect.withFiber((fiber) => { - const invocation = Context.getUnsafe( - fiber.context, - McpInvocationContext.McpInvocationContext, - ); - return provide(handle(payload as Tool.Parameters)).pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.matchCauseEffect({ - onFailure: imageToolFailure(tool.name, operation, failureText), - onSuccess: ({ encodedResult }) => { - const { screenshot, ...rest } = encodedResult as ImageToolResult; - const includeImage = - (payload as { readonly includeImage?: boolean } | undefined)?.includeImage !== - false; - const metadata = { - ...rest, - screenshot: { - mimeType: screenshot.mimeType, - width: screenshot.width, - height: screenshot.height, - }, - }; - return Effect.succeed( - new McpSchema.CallToolResult({ - isError: false, - structuredContent: metadata, - content: [ - { type: "text", text: JSON.stringify(metadata) }, - ...(includeImage - ? [ - { - type: "image" as const, - data: new Uint8Array(Buffer.from(screenshot.data, "base64")), - mimeType: screenshot.mimeType, - }, - ] - : []), - ], - }), - ); - }, - }), - ); - }), - }); }); +}); const registerDeviceScreenshot = Effect.fn("McpHttpServer.registerDeviceScreenshot")(function* () { const devices = yield* DeviceService.DeviceService; const threads = yield* ThreadManagementService.ThreadManagementService; - const built = yield* DeviceScreenshotToolkit; + const built = yield* decodeAsAdvertised(DeviceScreenshotToolkit); yield* registerImageTool( DeviceScreenshotTool, (payload) => @@ -709,7 +718,7 @@ const isOrchestratorMcpFailure = Schema.is(OrchestratorMcpFailure); const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(function* () { const htmlRender = yield* HtmlRender.HtmlRender; const threads = yield* ThreadManagementService.ThreadManagementService; - const built = yield* HtmlPreviewToolkit; + const built = yield* decodeAsAdvertised(HtmlPreviewToolkit); yield* registerImageTool( HtmlPreviewTool, (payload) => @@ -730,6 +739,198 @@ const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(funct ); }); +/** + * Tools that hand work to another thread's agent: they create it, message it, + * steer it, or move context into it. Their events name the receiving agent too. + */ +const HANDOFF_TOOLS: ReadonlySet = new Set([ + "delegate_task", + "create_threads", + "t3_thread_launch", + "t3_thread_send", + "t3_thread_send_attachments", + "t3_thread_fork", + "t3_thread_merge_back", + "t3_queue_edit", + "t3_queue_promote_to_steer", + "t3_pending_request_respond", + "schedule_task", + "run_scheduled_task_now", +]); + +/** Handoff tools whose result is only `{ sequence }`; their input names the receiving thread. */ +const INPUT_TARGET_TOOLS: ReadonlySet = new Set([ + "t3_queue_edit", + "t3_queue_promote_to_steer", + "t3_pending_request_respond", +]); + +const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const; + +/** Thread ids a handoff tool result names: the thread that received the work. */ +const resultThreadIds = (content: unknown): ReadonlyArray => { + if (typeof content !== "object" || content === null) return []; + const record = content as Readonly>; + if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds); + const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string"); + return key === undefined ? [] : [record[key] as string]; +}; + +/** + * Thread ids that received a handoff. The input's `threadId` is used only after + * the call succeeded, so it is one the handler already resolved and authorized. + */ +const handoffTargetIds = ( + tool: string, + args: unknown, + result: McpSchema.CallToolResult | undefined, +): ReadonlyArray => { + if (!INPUT_TARGET_TOOLS.has(tool)) return resultThreadIds(result?.structuredContent); + if (result === undefined || toolOutcome(result).outcome !== "ok") return []; + const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId; + return typeof threadId === "string" ? [threadId] : []; +}; + +/** Tool analytics must never include IDs, prompts or free text. */ +const withToolAnalytics = + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (registration: Effect.Effect) { + const server = yield* McpServer.McpServer; + const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService); + if (Option.isNone(analytics)) return yield* registration; + const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry); + const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService); + const shellOf = (threadId: string) => + Option.isNone(threads) + ? Effect.succeed(null) + : threads.value + .getThreadShell(ThreadId.make(threadId)) + .pipe(Effect.orElseSucceed(() => null)); + // Delegation depth: parents walked from the caller, capped. + const depthOf = + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (thread: AgentThread) { + let depth = 0; + let parentId = + thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null; + while (parentId !== null && depth < MAX_REPORTED_DEPTH) { + depth += 1; + const parent = yield* shellOf(parentId); + parentId = + parent?.lineage.relationshipToParent === "subagent" + ? parent.lineage.parentThreadId + : null; + } + return depth; + }); + // Whether the caller's active run was started by a scheduled task. + const scheduledRunOf = (threadId: string, runId: RunId | null) => + Option.isNone(threads) || runId === null + ? Effect.succeed(false) + : threads.value + .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], { + 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 record = + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced( + function* ( + tool: string, + args: unknown, + result: McpSchema.CallToolResult | undefined, + durationMs: number, + ) { + const handoff = HANDOFF_TOOLS.has(tool); + const outcome = toolOutcome(result); + // Agents call status, read, and preview tools in tight loops, so an + // event per successful call floods analytics. Only failures count there. + if (!handoff && outcome.outcome === "ok") return; + // Client credentials (no calling thread) report an unknown caller. + const invocation = Option.getOrUndefined( + yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext), + )?.thread; + const providers = Option.isSome(registry) ? yield* registry.value.getProviders : []; + // Only handoff tools pay for thread lookups; the rest report the + // caller's provider from the credential. + const caller = + handoff && invocation !== undefined + ? ((yield* shellOf(invocation.threadId)) ?? undefined) + : undefined; + const targetIds = handoff + ? [...new Set(handoffTargetIds(tool, args, result))].filter( + (threadId) => threadId !== invocation?.threadId, + ) + : []; + const targets = yield* Effect.forEach(targetIds, shellOf); + for (const properties of agentToolProperties({ + tool, + providers, + caller, + ...(invocation === undefined + ? {} + : { callerProviderInstanceId: invocation.providerInstanceId }), + ...(caller === undefined || invocation === undefined + ? {} + : { + callerDepth: yield* depthOf(caller), + callerScheduledRun: yield* scheduledRunOf( + invocation.threadId, + caller.activeRunId, + ), + }), + targets: targets.filter((thread) => thread !== null), + outcome, + ...(handoff + ? { settings: handoffSettings(tool, args, result?.structuredContent) } + : {}), + durationMs, + })) { + yield* analytics.value.record("mcp.tool.invoked", properties); + } + }, + (effect, _tool, _args, _result, _durationMs) => effect.pipe(Effect.ignoreCause), + ); + const recordingServer = McpServer.McpServer.of({ + ...server, + addTool: (options) => + server.addTool({ + ...options, + handle: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (payload) { + const startedAt = yield* Clock.currentTimeMillis; + return yield* options.handle(payload).pipe( + Effect.onExit((exit) => { + const result = exit._tag === "Success" ? exit.value : undefined; + // A call that asks for input is retried with it, and that call is the one counted. + if (result instanceof McpSchema.InputRequired) return Effect.void; + // Handoff tools look up threads to record; the response must not wait on them. + return Clock.currentTimeMillis.pipe( + Effect.flatMap((endedAt) => + record(options.tool.name, payload, result, endedAt - startedAt), + ), + Effect.forkDetach, + Effect.asVoid, + ); + }), + ); + }), + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); + }); + /** * `McpServer.toolkit` asks for every service its tools declare when it * registers them, but the auth middleware provides `McpInvocationContext` to @@ -740,7 +941,9 @@ export const toolkitRegistration = , EX, toolkit: Toolkit.Toolkit, handlers: McpToolAccess.HandlersLayer, ) => { - const registration = McpServer.toolkit(toolkit); + const registration = Layer.effectDiscard( + withToolAnalytics(McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ).pipe(Layer.provide(McpServer.McpServer.layer)); // @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request. const registered = registration as Layer.Layer< never, @@ -753,7 +956,10 @@ export const toolkitRegistration = , EX, const imageToolRegistration = , A, E, R, EX, RX>( register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, -) => Layer.effectDiscard(register).pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers))); +) => + Layer.effectDiscard(withToolAnalytics(register)).pipe( + Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), + ); export const layerHtmlToolkit = Layer.mergeAll( toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender), @@ -792,7 +998,7 @@ const layerPreviewControlsRegistration = toolkitRegistration( PreviewControlsHandlers.layer, ); -export const layerEnvironmentToolkit = toolkitRegistration( +const layerEnvironmentToolkit = toolkitRegistration( EnvironmentToolkit, EnvironmentHandlers.layer, ).pipe(Layer.provide(ThreadCommandExecutor.layer)); diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts index e3bc3face4110..94059d4fd8c53 100644 --- a/apps/server/src/mcp/McpInvocationContext.test.ts +++ b/apps/server/src/mcp/McpInvocationContext.test.ts @@ -10,39 +10,6 @@ import * as Effect from "effect/Effect"; import * as McpInvocationContext from "./McpInvocationContext.ts"; -it.effect("reports the scoped credential context when preview capability is unavailable", () => { - const invocation: McpInvocationContext.McpInvocationScope = { - 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(), - issuedAt: 1, - }; - - return Effect.gen(function* () { - const error = yield* McpInvocationContext.requireMcpCapability("preview").pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), - Effect.flip, - ); - - expect(error).toBeInstanceOf(PreviewAutomationUnavailableError); - expect(error).toMatchObject({ - capability: "preview", - environmentId: invocation.environmentId, - threadId: invocation.thread?.threadId, - providerSessionId: invocation.thread?.providerSessionId, - providerInstanceId: invocation.thread?.providerInstanceId, - }); - expect(error.message).toContain("MCP credential does not grant the preview capability"); - expect(error.message).toContain("use a headless browser from the shell"); - }); -}); - it.effect("reports other missing capabilities with the neutral error", () => { const invocation: McpInvocationContext.McpInvocationScope = { environmentId: EnvironmentId.make("environment-1"), diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index f830da3d4a03c..cc45af6bae4df 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -10,6 +10,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; const ALL_MCP_CAPABILITIES = [ "preview", @@ -24,6 +25,8 @@ export interface McpThreadCaller { readonly threadId: ThreadId; readonly providerSessionId: string; readonly providerInstanceId: ProviderInstanceId; + /** A delegated child task; its parent owns the work it hands back. */ + readonly subagent?: boolean; } export interface McpClientCaller { @@ -32,18 +35,11 @@ export interface McpClientCaller { readonly access: AuthMcpClientAccess; } -/** - * A read-only client never reaches a write (`McpToolAccess` refuses it first), - * so it maps to the lowest mode rather than to nothing. - */ +/** Read-only clients map to the lowest mode because McpToolAccess blocks writes first. */ export const clientRuntimeModeCeiling = (client: McpClientCaller | undefined): RuntimeMode => client === undefined || client.access === "read-only" ? "approval-required" : client.access; -/** - * A thread caller's omitted target falls back to its own thread; a client - * caller has no own thread, so tools that act as the caller (delegate_task, - * preview, worktree handoff) need `thread`. - */ +/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */ export interface McpInvocationScope { readonly environmentId: EnvironmentId; readonly capabilities: ReadonlySet; @@ -58,6 +54,16 @@ export class McpInvocationContext extends Context.Service< McpInvocationScope >()("t3/mcp/McpInvocationContext") {} +/** + * `McpSchema.EnabledWhen` for tools a delegated child must not see or call. + * EnabledWhen only receives the MCP client profile, so read the T3 caller from the request fiber. + */ +export const hiddenFromSubagents = (): boolean => { + const fiber = Fiber.getCurrent(); + const scope = fiber && Context.getOrUndefined(fiber.context, McpInvocationContext); + return scope?.thread?.subagent !== true; +}; + export type McpCapabilityError = C extends "preview" ? PreviewAutomationUnavailableError : McpCapabilityUnavailableError; diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index a3f74c3e28c24..282c3dffd6d64 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -102,6 +102,7 @@ it.effect("always grants pull-requests and gates browser and device access indep }), ); +// regression: #3114 use bound host for MCP endpoint it.effect("builds MCP endpoints from the bound server host", () => Effect.gen(function* () { const cases = [ @@ -139,42 +140,83 @@ it.effect("expires credentials once their session stops showing signs of life", }), ); -it.effect("keeps a credential alive across turns that never touch an MCP tool", () => +it.effect("does not keep credentials of other threads alive", () => Effect.gen(function* () { let timestamp = 1_000; const registry = yield* makeRegistry(() => timestamp); - const threadId = ThreadId.make("thread-3"); const issued = yield* registry.issue({ - threadId, - providerInstanceId: ProviderInstanceId.make("claude"), + threadId: ThreadId.make("thread-4"), + providerInstanceId: ProviderInstanceId.make("codex"), capabilities: new Set(["preview"]), }); const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, ""); - for (let turn = 0; turn < 10; turn += 1) { - timestamp += 99; - yield* registry.touch(threadId); - } + timestamp += 99; + yield* registry.touch(ThreadId.make("thread-unrelated")); + timestamp += 2; - expect((yield* registry.resolve(token))?.thread.threadId).toBe(threadId); + expect(yield* registry.resolve(token)).toBeUndefined(); }), ); -it.effect("does not keep credentials of other threads alive", () => +it.effect("only a trusted touch restores an expired token with its original scope", () => Effect.gen(function* () { let timestamp = 1_000; const registry = yield* makeRegistry(() => timestamp); + const threadId = ThreadId.make("thread-idle"); const issued = yield* registry.issue({ - threadId: ThreadId.make("thread-4"), - providerInstanceId: ProviderInstanceId.make("codex"), + threadId, + providerInstanceId: ProviderInstanceId.make("claude"), capabilities: new Set(["preview"]), }); const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, ""); + const scope = yield* registry.resolve(token); + expect(scope).toBeDefined(); - timestamp += 99; - yield* registry.touch(ThreadId.make("thread-unrelated")); - timestamp += 2; + timestamp += 101; + expect(yield* registry.resolve(token)).toBeUndefined(); + const otherThreadId = ThreadId.make("thread-active"); + const other = yield* registry.issue({ + threadId: otherThreadId, + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(["device"]), + }); + yield* registry.touch(otherThreadId); + expect( + (yield* registry.resolve(other.config.authorizationHeader.replace(/^Bearer\s+/, "")))?.thread + .threadId, + ).toBe(otherThreadId); + expect(yield* registry.resolve("unknown-token")).toBeUndefined(); + expect(yield* registry.resolve(token)).toBeUndefined(); + yield* registry.touch(threadId); + expect(yield* registry.resolve(token)).toEqual(scope); + timestamp += 101; expect(yield* registry.resolve(token)).toBeUndefined(); }), ); + +it.effect.each(["provider-session", "thread", "all"] as const)( + "never restores an expired token after %s revocation", + (revocation) => + Effect.gen(function* () { + let timestamp = 1_000; + const registry = yield* makeRegistry(() => timestamp); + const threadId = ThreadId.make("thread-revoked"); + const issued = yield* registry.issue({ + threadId, + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(["preview"]), + }); + const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, ""); + + timestamp += 101; + yield* { + "provider-session": registry.revokeProviderSession(issued.config.providerSessionId), + thread: registry.revokeThread(threadId), + all: registry.revokeAll, + }[revocation]; + yield* registry.touch(threadId); + expect(yield* registry.resolve(token)).toBeUndefined(); + }), +); diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index b16529924a430..ce424d7b662cd 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -15,13 +15,10 @@ import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; export interface McpCredentialRequest { readonly threadId: ThreadId; readonly providerInstanceId: ProviderInstanceId; - /** - * When false, the credential is minted without the "preview" capability so - * the user's choice to withhold agent browser access holds everywhere the - * token is honored (#7083). Defaults to full access. - */ + /** False omits the preview capability wherever the token is honored. Defaults to full access. */ readonly browserToolsAvailable?: boolean; readonly capabilities?: ReadonlySet; + readonly subagent?: boolean; } export interface McpIssuedCredential { @@ -60,9 +57,9 @@ export interface McpSessionRegistryOptions { } /** - * The bound matters because `/mcp` is mounted outside the environment auth - * stack and is reachable on whatever host the server binds to, so this token is - * the only thing guarding the `t3-code` toolkits on a remote-reachable server. + * `/mcp` is outside environment auth, so idle tokens stop authenticating. + * Keep expired records until explicit revocation: a trusted provider turn can + * refresh the token its subprocess still holds; MCP requests cannot. */ const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000; @@ -95,15 +92,6 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( .digest("SHA-256", new TextEncoder().encode(token)) .pipe(Effect.map(bytesToHex), Effect.orDie); - const pruneDead = (records: ReadonlyMap, timestamp: number) => { - const next = new Map( - Array.from(records).filter( - ([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs, - ), - ); - return next.size === records.size ? records : next; - }; - const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")( function* (request) { const issuedAt = yield* currentTimeMillis; @@ -118,6 +106,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( threadId: ThreadId.make(request.threadId), providerSessionId, providerInstanceId: ProviderInstanceId.make(request.providerInstanceId), + subagent: request.subagent === true, }, client: undefined, capabilities: new Set([ @@ -129,7 +118,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( issuedAt, }; yield* SynchronizedRef.update(state, ({ records }) => { - const next = new Map(pruneDead(records, issuedAt)); + const next = new Map(records); next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt }); return { records: next }; }); @@ -154,10 +143,11 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( const tokenHash = yield* hashToken(rawToken); const timestamp = yield* currentTimeMillis; return yield* SynchronizedRef.modify(state, ({ records }) => { - const current = pruneDead(records, timestamp); - const record = current.get(tokenHash); - if (!record) return [undefined, { records: current }] as const; - const next = new Map(current); + const record = records.get(tokenHash); + if (!record || timestamp - record.lastAliveAt > livenessWindowMs) { + return [undefined, { records }] as const; + } + const next = new Map(records); next.set(tokenHash, { ...record, lastAliveAt: timestamp }); return [record.scope, { records: next }] as const; }); @@ -168,9 +158,8 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( function* (threadId) { const timestamp = yield* currentTimeMillis; yield* SynchronizedRef.update(state, ({ records }) => { - const current = pruneDead(records, timestamp); - const next = new Map(current); - for (const [tokenHash, record] of current) { + const next = new Map(records); + for (const [tokenHash, record] of records) { if (record.scope.thread.threadId === threadId) { next.set(tokenHash, { ...record, lastAliveAt: timestamp }); } @@ -221,15 +210,6 @@ const make = Effect.acquireRelease( export const layer = Layer.effect(McpSessionRegistry, make); -export const issueActiveMcpCredential = ( - request: McpCredentialRequest, -): Effect.Effect => - activeMcpSessionRegistry - ? activeMcpSessionRegistry - .revokeThread(request.threadId) - .pipe(Effect.andThen(activeMcpSessionRegistry.issue(request))) - : Effect.undefined; - export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect => activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void; diff --git a/apps/server/src/mcp/McpToolAccess.race.test.ts b/apps/server/src/mcp/McpToolAccess.race.test.ts index 52b8523ad56d9..b02ef26374848 100644 --- a/apps/server/src/mcp/McpToolAccess.race.test.ts +++ b/apps/server/src/mcp/McpToolAccess.race.test.ts @@ -188,22 +188,4 @@ it.layer(layerOrchestrator)("writesThreads against a mode raise", (it) => { ), ), ); - - it.effect("lets the write through when the thread stays within the caller's modes", () => - Effect.gen(function* () { - const projections = yield* ProjectionStore.ProjectionStoreV2; - const threadId = ThreadId.make("thread:race-steady"); - yield* createSupervisedThread(threadId); - const outcome = yield* renameRacingTheUser(threadId, false); - assert.deepEqual(outcome, { renamed: true }); - assert.equal((yield* projections.getThreadShell(threadId))?.title, "Renamed by the agent"); - }).pipe( - Effect.provide( - ThreadManagement.layer.pipe( - Layer.provide(ServerSettings.layerTest()), - Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), - ), - ), - ), - ); }); diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts index 46371724119a8..ecfb8a9993b30 100644 --- a/apps/server/src/mcp/McpToolAccess.test.ts +++ b/apps/server/src/mcp/McpToolAccess.test.ts @@ -216,7 +216,6 @@ const supervised = threadCaller(supervisedThreadId); const plan = threadCaller(planThreadId); const fullAccess = threadCaller(fullAccessThreadId); const ended = threadCaller(endedThreadId); -// Its turn ended, but a background subagent it started still runs. const background = threadCaller(backgroundThreadId); const oldProviderBackground = threadCaller(oldProviderThreadId); const archivedBackground = threadCaller(archivedThreadId); @@ -311,11 +310,6 @@ it.effect.each([ ), ); -it("refuses a declaration or handlers layer built outside McpToolAccess", () => { - expect(() => Reflect.construct(McpToolAccess.Declaration, [unchecked])).toThrow(TypeError); - expect(() => Reflect.construct(McpToolAccess.HandlersLayer, [Layer.empty])).toThrow(TypeError); -}); - it("refuses a declaration or handlers layer that only wears another's fields", () => { const copiedDeclaration = Object.assign( unchecked, diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index 5cc8dc0c38b8f..9d99fb7da89e3 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -27,10 +27,7 @@ import { unavailable, } from "./threadAccess.ts"; -/** - * Their private constructors only stop the type checker; this also stops - * `Reflect.construct` and friends at runtime. - */ +/** Private constructors only enforce types; the token also blocks runtime construction. */ const builtHere: unique symbol = Symbol("t3/mcp/McpToolAccess/builtHere"); const refuseOutsideConstruction = (token: symbol) => { @@ -55,11 +52,7 @@ let handlersLayer: , EX, RX>( layer: Layer.Layer, EX, RX>, ) => HandlersLayer; -/** - * Effect's own registration functions accept any handler, so the - * `t3code/no-raw-mcp-registration` lint rule keeps Effect's `McpServer` inside - * McpHttpServer. - */ +/** t3code/no-raw-mcp-registration confines Effect's unchecked registration API to McpHttpServer. */ export class Declaration { readonly #handle: Handler; private constructor(token: typeof builtHere, handle: Handler) { @@ -117,10 +110,7 @@ export const actsAsCaller = (handle: (params: P) => Effect.Effect(handle: (params: P) => Effect.Effect) => declare((params: P) => orchestratingCaller.pipe(Effect.flatMap(() => handle(params)))); -/** - * Unlike `writes` it does not need thread control; the handler checks its - * capability, as the capability toolkits do. - */ +/** Requires handler capability checks, not thread control. */ export const writesWithCapability = (handle: (params: P) => Effect.Effect) => declare((params: P) => writingCaller.pipe(Effect.flatMap(() => handle(params)))); @@ -140,9 +130,7 @@ export const writesThreads = ( yield* assertTargetWithinLimits(caller.limits, target); } } - // The target's user can raise its modes after the check above; the - // orchestrator checks again under the thread's lock and records its - // refusal here, since handlers wrap dispatch errors their own way. + // Modes can rise after this check; the orchestrator rechecks under lock and records refusal before handlers wrap errors. const refused = yield* Ref.make(undefined); return yield* handle(params).pipe( Effect.provideService(DispatchModeLimit, { ...caller.limits, refused }), @@ -196,10 +184,7 @@ export const startsThreads = ( const fullAccessRequired = "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client."; -/** - * `check` re-checks the caller wherever the handler waits before writing, such - * as for a lock, since the caller's modes can change meanwhile. - */ +/** Recheck after waits before writing; caller modes may have changed. */ export const writesEnvironment = ( handle: ( params: P, diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 12e7f7fd0d47e..d7f9746f76ea5 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -181,71 +181,6 @@ it("readThread prefers activity-run status over a newer cancelled queued run", a }).pipe(Effect.provide(layer), Effect.runPromise); }); -it("readThread prefers waiting activity status over a newer cancelled queued run", async () => { - const projection = { - thread: baseThread({ - threadId: parentThreadId, - title: "Parent waiting", - instanceId: parentInstanceId, - model: "gpt-5.4", - }), - runs: [ - makeRun({ id: activeRunId, ordinal: 1, status: "waiting" }), - makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }), - ], - visibleTurnItems: [], - runtimeRequests: [], - messages: [], - contextTransfers: [], - subagents: [], - updatedAt: now, - } as unknown as OrchestrationV2ThreadProjection; - - const layer = layerOrchestratorService.pipe( - Layer.provide( - Layer.mergeAll( - Layer.mock(ThreadManagementService.ThreadManagementService)({ - getTimelinePage: () => Effect.succeed({ items: [], totalItems: 0, hasMore: false }), - getThreadRecords: (threadId) => - threadId === parentThreadId - ? Effect.succeed(projection) - : Effect.die(`unexpected thread ${threadId}`), - getThreadShell: (threadId) => - Effect.succeed( - threadId === parentThreadId - ? (projection.thread as unknown as OrchestrationV2ThreadShell) - : null, - ), - getProjectThreadRecords: (input) => - input.threadId === parentThreadId - ? Effect.succeed(projection) - : Effect.die(`unexpected thread ${input.threadId}`), - } satisfies Partial), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([]), - } satisfies Partial), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - 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 result = yield* service.readThread(makeScope(), { threadId: parentThreadId }); - expect(result.thread.status).toBe("waiting"); - expect(result.thread.activeRunId).toBe(activeRunId); - }).pipe(Effect.provide(layer), Effect.runPromise); -}); - it("taskStatus returns task.providerInstanceId rather than the driver kind", async () => { const parentProjection = { thread: baseThread({ @@ -533,7 +468,6 @@ it("readThread and sendToThread reach threads in other projects", async () => { .pipe(Effect.flip); expect(staleDelete.code).toBe("parent_not_active"); - // A background item keeps only its owning instance live, even after a switch. const backgroundTasks = [ { taskId: "background-subagent", @@ -577,7 +511,6 @@ it("readThread and sendToThread reach threads in other projects", async () => { .pipe(Effect.flip); expect(mismatched.code).toBe("parent_not_active"); - // A fresh active run wins over the earlier inactive projection and empty roster. parentShell = liveThreadShell(parentThreadId); const restarted = yield* service.sendToThread(makeScope(), { threadId: foreignThreadId, diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f0ada42011ea1..6ce02cbb32e2a 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3,7 +3,11 @@ import { assert, describe, it } from "@effect/vitest"; import { CommandId, EnvironmentId, + MessageId, NodeId, + ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, + type OrchestratorMcpCapabilitiesResult, + OrchestratorMcpTarget, type OrchestrationV2ThreadShell, type ScheduledTask, ScheduledTaskId, @@ -12,14 +16,23 @@ import { ProviderInstanceId, RunId, ThreadId, + type OrchestrationV2ServerCommand, type OrchestrationV2ThreadProjection, type ServerProvider, } from "@t3tools/contracts"; +import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; - +import * as Schema from "effect/Schema"; + +import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; +import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts"; +import * as LegacyV1ThreadImporter from "../orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { DispatchModeLimit, type DispatchModeRefusal, @@ -43,6 +56,8 @@ import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.t import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +const decodeTarget = Schema.decodeUnknownEffect(OrchestratorMcpTarget); + const layerOrchestratorService = OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), @@ -75,7 +90,7 @@ describe("OrchestratorMcpService", () => { ], } as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [ { id: childRunId, @@ -209,7 +224,7 @@ describe("OrchestratorMcpService", () => { ], } as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [ { id: RunId.make("run:mcp-restart-child"), @@ -278,6 +293,114 @@ describe("OrchestratorMcpService", () => { }), ); + it.effect("tells the parent to end its turn only while its task still runs", () => + Effect.gen(function* () { + const parentThreadId = ThreadId.make("thread:mcp-next-parent"); + const childThreadId = ThreadId.make("thread:mcp-next-child"); + const taskId = NodeId.make("node:mcp-next-task"); + let finished = false; + let pendingRequest = false; + const parentProjection = () => + ({ + thread: { id: parentThreadId }, + runs: [], + contextTransfers: [], + subagents: [ + { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + driver: "codex", + model: "gpt-5.6-terra", + status: finished ? "completed" : "running", + result: finished ? "done" : null, + completionDelivery: { state: "pending" }, + }, + ], + }) as unknown as OrchestrationV2ThreadProjection; + const childRun = () => ({ + id: RunId.make("run:mcp-next-child"), + ordinal: 1, + status: finished ? ("completed" as const) : ("running" as const), + delegatedTaskId: taskId, + }); + const childProjection = () => + ({ + thread: { id: childThreadId, title: "Child task" }, + runs: [childRun()], + contextTransfers: [], + messages: [], + subagents: [], + providerThreads: [], + runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], + nodes: [], + turnItems: [], + }) as unknown as OrchestrationV2ThreadProjection; + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (threadId) => + Effect.succeed(threadId === parentThreadId ? parentProjection() : childProjection()), + getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + getProjectThreadRecords: () => Effect.succeed(childProjection()), + waitForThread: () => + Effect.succeed({ + threadId: childThreadId, + run: childRun() as unknown as OrchestrationV2ThreadProjection["runs"][number], + timedOut: !finished, + }), + dispatch: () => Effect.succeed({} as never), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const scope: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:mcp-next"), + requestNamespace: "provider-session:mcp-next", + thread: { + threadId: parentThreadId, + providerSessionId: "provider-session:mcp-next", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const running = yield* service.taskStatus(scope, taskId); + assert.equal(running.status, "running"); + assert.equal(running.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + const waiting = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.isTrue(waiting.timedOut); + assert.equal(waiting.next, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT); + + // A child waiting on a question or approval needs an answer, not a wake. + pendingRequest = true; + const asking = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.isTrue(asking.timedOut); + assert.notProperty(asking, "next"); + pendingRequest = false; + + finished = true; + const completed = yield* service.taskStatus(scope, taskId); + assert.equal(completed.status, "completed"); + assert.notProperty(completed, "next"); + const waited = yield* service.waitForThread(scope, { threadId: childThreadId }); + assert.equal(waited.status, "completed"); + assert.notProperty(waited, "next"); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + }), + ); + it.effect("does not dispose delivery when a nonterminal task has no active child run", () => Effect.gen(function* () { const parentThreadId = ThreadId.make("thread:mcp-cancel-parent"); @@ -302,7 +425,7 @@ describe("OrchestratorMcpService", () => { ], } as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [], contextTransfers: [], messages: [], @@ -354,6 +477,116 @@ describe("OrchestratorMcpService", () => { }), ); + it.effect.each(["no runs", "a finished run"] as const)( + "cancels an orphaned follow-up through its parent when the child has %s", + (childState) => + Effect.gen(function* () { + const parentThreadId = ThreadId.make("thread:mcp-orphan-parent"); + const childThreadId = ThreadId.make("thread:mcp-orphan-child"); + const taskId = NodeId.make("node:mcp-orphan-task"); + const parentRunId = RunId.make("run:mcp-orphan-parent"); + const dispatched = yield* Ref.make>([]); + const status = yield* Ref.make("running"); + const parentProjection = (taskStatus: string) => + ({ + thread: { id: parentThreadId }, + runs: [], + contextTransfers: [], + subagents: [ + { + id: taskId, + threadId: parentThreadId, + runId: parentRunId, + origin: "app_owned", + childThreadId, + driver: "codex", + model: "gpt-5.6-terra", + status: taskStatus, + result: null, + completionDelivery: { state: "pending" }, + }, + ], + }) as unknown as OrchestrationV2ThreadProjection; + // A finished run whose binding to the follow-up was lost. + const childProjection = { + thread: { id: childThreadId, title: "Child" }, + runs: + childState === "no runs" + ? [] + : [{ id: RunId.make("run:mcp-orphan-child"), ordinal: 1, status: "completed" }], + contextTransfers: [], + messages: [], + subagents: [], + providerThreads: [], + runtimeRequests: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection; + const layerDependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (threadId) => + threadId === parentThreadId + ? Effect.map(Ref.get(status), parentProjection) + : Effect.succeed(childProjection), + getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)), + delegatedTaskResultPending: () => Effect.succeed(false), + stopDelegatedTasks: () => Effect.void, + // The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts. + dispatch: (command) => + Ref.update(dispatched, (commands) => [...commands, command]).pipe( + Effect.andThen( + command.type === "subagent.stop" ? Ref.set(status, "cancelled") : Effect.void, + ), + Effect.as({} as never), + ), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + const scope: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:mcp-orphan"), + requestNamespace: "provider-session:mcp-orphan", + thread: { + threadId: parentThreadId, + providerSessionId: "provider-session:mcp-orphan", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const result = yield* service.cancelTask(scope, { + taskId, + clientRequestId: "cancel-orphan-task", + }); + assert.deepEqual(result, { taskId, status: "cancelled" }); + const commands = yield* Ref.get(dispatched); + // A child whose run finished can still run another turn's work, so it is stopped too. + assert.deepEqual( + commands.flatMap((command) => + command.type === "thread.stop" ? [command.threadId] : [], + ), + childState === "a finished run" ? [childThreadId] : [], + ); + const stop = commands.find((command) => command.type === "subagent.stop"); + if (stop?.type !== "subagent.stop") return; + assert.deepEqual( + { threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId }, + { threadId: parentThreadId, runId: parentRunId, subagentId: taskId }, + ); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + }), + ); + it.effect("does not dispose delivery when the child stop fails", () => Effect.gen(function* () { const parentThreadId = ThreadId.make("thread:mcp-cancel-failed-parent"); @@ -379,7 +612,7 @@ describe("OrchestratorMcpService", () => { ], } as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [{ id: childRunId, status: "running" }], contextTransfers: [], messages: [], @@ -459,7 +692,7 @@ describe("OrchestratorMcpService", () => { ], } as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [{ id: childRunId, status: "running" }], contextTransfers: [], messages: [], @@ -545,7 +778,7 @@ describe("OrchestratorMcpService", () => { ], } as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [{ id: childRunId, status: "running" }], contextTransfers: [], messages: [], @@ -640,7 +873,7 @@ describe("OrchestratorMcpService", () => { [ childThreadId, { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [{ id: RunId.make("run:mcp-cancel-grandchild-child"), status: "running" }], contextTransfers: [], messages: [], @@ -798,10 +1031,11 @@ describe("OrchestratorMcpService provider resolution", () => { instanceId: input.instanceId, driver: input.driver, enabled: input.enabled ?? true, - installed: true, - version: "test", - status: "ready", - auth: { status: "authenticated" }, + installed: input.enabled !== false, + version: input.enabled === false ? null : "test", + status: input.enabled === false ? "disabled" : "ready", + auth: { status: input.enabled === false ? "unknown" : "authenticated" }, + ...(input.enabled === false ? { message: "Provider is disabled in T3 Code settings." } : {}), checkedAt: "2026-09-13T00:00:00.000Z", models: input.model === undefined @@ -867,7 +1101,7 @@ describe("OrchestratorMcpService provider resolution", () => { }) as unknown as OrchestrationV2ThreadProjection; const childProjection = { - thread: { id: childThreadId }, + thread: { id: childThreadId, title: "Child" }, runs: [], contextTransfers: [], messages: [], @@ -882,6 +1116,7 @@ describe("OrchestratorMcpService provider resolution", () => { () => Effect.gen(function* () { const disabledAntigravityInstanceId = ProviderInstanceId.make("antigravity-alt"); + const disabledWithoutAdapterInstanceId = ProviderInstanceId.make("codex-without-adapter"); const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); const forkShadow = yield* buildUnavailableProviderSnapshot({ driverKind: "forkOnly", @@ -921,6 +1156,12 @@ describe("OrchestratorMcpService provider resolution", () => { model: "ant-model", enabled: false, }), + providerSnapshot({ + instanceId: disabledWithoutAdapterInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + enabled: false, + }), forkShadow, ]; const layerDependencies = Layer.mergeAll( @@ -1000,48 +1241,224 @@ describe("OrchestratorMcpService provider resolution", () => { const disabled = byId.get(disabledAntigravityInstanceId); assert.isDefined(disabled); assert.isFalse(disabled!.canRunChildTask); + assert.isFalse(disabled!.canRunCrossProviderChildTask); assert.deepEqual(disabled!.constraints, ["Provider instance is disabled."]); + const disabledWithoutAdapter = byId.get(disabledWithoutAdapterInstanceId); + assert.isDefined(disabledWithoutAdapter); + assert.isFalse(disabledWithoutAdapter!.canRunChildTask); + assert.isFalse(disabledWithoutAdapter!.canRunCrossProviderChildTask); + assert.deepEqual(disabledWithoutAdapter!.constraints, [ + "No V2 provider adapter is registered.", + "Provider instance is disabled.", + ]); + const fork = byId.get(forkOnlyInstanceId); assert.isDefined(fork); assert.isFalse(fork!.canRunChildTask); - assert.isTrue( - fork!.constraints.includes("No V2 provider adapter is registered."), - `expected missing-adapter constraint, got ${fork!.constraints.join(" | ")}`, - ); - assert.isTrue( - fork!.constraints.includes("Driver 'forkOnly' is not registered in this build."), - ); + assert.isFalse(fork!.canRunCrossProviderChildTask); + assert.deepEqual(fork!.constraints, [ + "No V2 provider adapter is registered.", + "Driver 'forkOnly' is not registered in this build.", + "Provider instance is disabled.", + ]); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); - it.effect("leaves models the user hid out of the capability catalog", () => + describe("listed models", () => { + const opencodeInstanceId = ProviderInstanceId.make("opencode"); + const model = (slug: string, extra: Partial = {}) => ({ + slug, + name: slug, + isCustom: false, + capabilities: null, + ...extra, + }); + const opencodeSlugs = Array.from( + { length: 12 }, + (_, index) => `oc/m${String(index + 1).padStart(2, "0")}`, + ); + const catalog: ReadonlyArray = [ + { + ...providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + }), + models: [ + model("gpt-6", { + name: "Sol", + capabilities: { + optionDescriptors: [ + { + id: "effort", + label: "Reasoning", + description: "How hard the model thinks.", + type: "select", + options: [ + { id: "low", label: "Low", description: "Fast." }, + { id: "high", label: "High", isDefault: true }, + ], + promptInjectedValues: ["high"], + }, + { id: "fastMode", label: "Fast", type: "boolean" }, + { + id: "agent", + label: "Agent", + type: "select", + options: [{ id: "build", label: "Build" }], + currentValue: "build", + }, + ], + }, + }), + model("gpt-5", { isLegacy: true }), + model("gpt-4", { isLegacy: true }), + model("gpt-3", { name: "GPT-3", isLegacy: true }), + model("my-alpha", { isCustom: true }), + ], + }, + { + ...providerSnapshot({ + instanceId: opencodeInstanceId, + driver: ProviderDriverKind.make("opencode"), + }), + models: [ + ...opencodeSlugs.map((slug) => model(slug, { isLegacy: slug === "oc/m03" })), + model("oc-custom", { isCustom: true }), + ], + }, + ]; + + const capabilitiesWith = (search?: string) => + Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* service.capabilities(scope, search === undefined ? {} : { search }); + }).pipe( + Effect.provide( + layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => + Effect.succeed( + parentProjection([], { instanceId: codexInstanceId, model: "gpt-3" }), + ), + }), + ServerSettings.layerTest({ + favorites: [ + { provider: codexInstanceId, model: "gpt-4" }, + { provider: opencodeInstanceId, model: "oc/m10" }, + ], + providerModelPreferences: { + [opencodeInstanceId]: { hiddenModels: ["oc/m02"], modelOrder: ["oc/m12"] }, + }, + }), + providerRegistryLayer(catalog), + adapterRegistryLayer([codexInstanceId, opencodeInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ), + ), + ), + ), + ); + + const listing = (capabilities: OrchestratorMcpCapabilitiesResult) => + capabilities.providers.map((provider) => ({ + id: provider.providerInstanceId, + models: provider.models.map((entry) => entry.id), + omitted: provider.omittedModels ?? 0, + })); + + it.effect( + "skips legacy models, lists the first 8 of large catalogs, and keeps pinned models", + () => + Effect.gen(function* () { + assert.deepEqual(listing(yield* capabilitiesWith()), [ + // gpt-4 is a favorite and gpt-3 is the caller's model; legacy gpt-5 is left out. + { id: codexInstanceId, models: ["gpt-6", "gpt-4", "gpt-3", "my-alpha"], omitted: 1 }, + { + id: opencodeInstanceId, + models: [ + "oc/m12", + "oc/m01", + "oc/m04", + "oc/m05", + "oc/m06", + "oc/m07", + "oc/m08", + "oc/m09", + "oc/m10", + "oc-custom", + ], + omitted: 2, + }, + ]); + }), + ); + + it.effect("search matches every word and caps each provider's matches", () => + Effect.gen(function* () { + assert.deepEqual(listing(yield* capabilitiesWith("GPT 5")), [ + { id: codexInstanceId, models: ["gpt-5"], omitted: 0 }, + { id: opencodeInstanceId, models: [], omitted: 0 }, + ]); + const opencode = listing(yield* capabilitiesWith("oc/m"))[1]; + assert.deepEqual(opencode, { + id: opencodeInstanceId, + models: ["oc/m12", "oc/m01", "oc/m03", "oc/m04", "oc/m05", "oc/m06", "oc/m07", "oc/m08"], + omitted: 3, + }); + }), + ); + + it.effect("describes models by id, distinct label, and option values", () => + Effect.gen(function* () { + const codex = (yield* capabilitiesWith()).providers[0]; + assert.deepEqual(codex?.models.slice(0, 4), [ + { + id: "gpt-6", + label: "Sol", + options: [ + { id: "effort", values: ["low", "high"], default: "high" }, + { id: "fastMode", values: [false, true] }, + { id: "agent", values: ["build"], default: "build" }, + ], + }, + { id: "gpt-4" }, + { id: "gpt-3" }, + { id: "my-alpha" }, + ]); + }), + ); + }); + + it.effect("rejects delegation to a provider without a registered adapter", () => Effect.gen(function* () { - const codex = providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", + const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); + const forkShadow = yield* buildUnavailableProviderSnapshot({ + driverKind: "forkOnly", + instanceId: forkOnlyInstanceId, + reason: "Driver 'forkOnly' is not registered in this build.", + checkedAt: "2026-09-13T00:00:00.000Z", }); const layerDependencies = Layer.mergeAll( NodeServices.layer, Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), getThreadRecords: () => Effect.succeed(parentProjection([])), }), - ServerSettings.layerTest({ - providerModelPreferences: { - [codexInstanceId]: { hiddenModels: ["gpt-5.4-mini", "my-model"], modelOrder: [] }, - }, - }), + ServerSettings.layerTest(), providerRegistryLayer([ - { - ...codex, - models: [ - ...codex.models, - { slug: "gpt-5.4-mini", name: "Mini", isCustom: false, capabilities: null }, - { slug: "my-model", name: "Mine", isCustom: true, capabilities: null }, - ], - }, + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + forkShadow, ]), adapterRegistryLayer([codexInstanceId]), Layer.mock(ProjectService.ProjectService)({}), @@ -1051,117 +1468,36 @@ describe("OrchestratorMcpService provider resolution", () => { yield* Effect.gen(function* () { const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const capabilities = yield* service.capabilities(scope); - assert.deepEqual( - capabilities.providers[0]?.models.map((model) => model.id), - ["gpt-5.4", "my-model"], - ); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); - }), - ); - - it.effect( - "delegates to an Antigravity instance whose adapter resolves through the registry", - () => - Effect.gen(function* () { - let delegated = false; - const task = { - id: taskId, - threadId: parentThreadId, - runId: parentRunId, - parentNodeId, - origin: "app_owned", - createdBy: "agent", - driver: ProviderDriverKind.make("antigravity"), - providerInstanceId: antigravityInstanceId, - providerThreadId: null, - childThreadId, - nativeTaskRef: null, - prompt: "Summarize the diff.", - title: null, - model: "ant-model", - status: "running", - result: null, - startedAt: null, - completedAt: null, - }; - const dispatched = yield* Ref.make>([]); - const layerDependencies = Layer.mergeAll( - NodeServices.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - assertProviderInstanceEnabled: () => Effect.void, - getThreadRecords: (threadId) => - Effect.succeed( - threadId === parentThreadId - ? parentProjection(delegated ? [task] : []) - : childProjection, - ), - dispatch: (command) => - Ref.update(dispatched, (commands) => [...commands, command]).pipe( - Effect.andThen( - Effect.sync(() => { - delegated = true; - }), - ), - Effect.as({ - sequence: 1, - storedEvents: [ - { - sequence: 1, - commandId: null, - event: { type: "subagent.updated", payload: task }, - }, - ], - } as never), - ), - }), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - providerSnapshot({ - instanceId: antigravityInstanceId, - driver: ProviderDriverKind.make("antigravity"), - model: "ant-model", - }), - ]), - }), - adapterRegistryLayer([codexInstanceId, antigravityInstanceId]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ); + const byInstance = yield* service + .delegateTask(scope, { + task: "Summarize the diff.", + target: { providerInstanceId: forkOnlyInstanceId }, + mode: "async", + clientRequestId: "delegate-fork-1", + }) + .pipe(Effect.flip); + assert.equal(byInstance.code, "provider_unavailable"); + assert.isTrue(byInstance.message.includes("No V2 provider adapter is registered.")); - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const result = yield* service.delegateTask(scope, { + const byDriver = yield* service + .delegateTask(scope, { task: "Summarize the diff.", - target: { providerInstanceId: antigravityInstanceId, model: "ant-model" }, + target: { driverKind: ProviderDriverKind.make("forkOnly") }, mode: "async", - clientRequestId: "delegate-antigravity-1", - }); - assert.equal(result.status, "running"); - assert.equal(result.providerInstanceId, antigravityInstanceId); - const commands = yield* Ref.get(dispatched); - assert.equal(commands.length, 1); - const request = commands[0] as { - type: string; - modelSelection: { instanceId: string; model: string }; - }; - assert.equal(request.type, "delegated_task.request"); - assert.equal(request.modelSelection.instanceId, antigravityInstanceId); - assert.equal(request.modelSelection.model, "ant-model"); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); - }), + clientRequestId: "delegate-fork-2", + }) + .pipe(Effect.flip); + assert.equal(byDriver.code, "provider_unavailable"); + assert.isTrue( + byDriver.message.includes("No V2 provider adapter is registered for driver forkOnly."), + ); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); + }), ); - it.effect("resolves a driverKind target to a capable Antigravity instance", () => + it.effect("driver-only delegation skips an instance the project turned off", () => Effect.gen(function* () { + const altInstanceId = ProviderInstanceId.make("codex-alt"); const dispatched = yield* Ref.make>([]); const task = { id: taskId, @@ -1170,214 +1506,14 @@ describe("OrchestratorMcpService provider resolution", () => { parentNodeId, origin: "app_owned", createdBy: "agent", - driver: ProviderDriverKind.make("antigravity"), - providerInstanceId: antigravityInstanceId, + driver: ProviderDriverKind.make("codex"), + providerInstanceId: altInstanceId, providerThreadId: null, childThreadId, nativeTaskRef: null, prompt: "Summarize the diff.", title: null, - model: "ant-model", - status: "running", - result: null, - startedAt: null, - completedAt: null, - }; - let delegated = false; - const layerDependencies = Layer.mergeAll( - NodeServices.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - assertProviderInstanceEnabled: () => Effect.void, - isProviderInstanceEnabledForProject: () => Effect.succeed(true), - getThreadRecords: (threadId) => - Effect.succeed( - threadId === parentThreadId - ? parentProjection(delegated ? [task] : []) - : childProjection, - ), - dispatch: (command) => - Ref.update(dispatched, (commands) => [...commands, command]).pipe( - Effect.andThen( - Effect.sync(() => { - delegated = true; - }), - ), - Effect.as({ - sequence: 1, - storedEvents: [ - { - sequence: 1, - commandId: null, - event: { type: "subagent.updated", payload: task }, - }, - ], - } as never), - ), - }), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - providerSnapshot({ - instanceId: antigravityInstanceId, - driver: ProviderDriverKind.make("antigravity"), - model: "ant-model", - }), - ]), - }), - adapterRegistryLayer([codexInstanceId, antigravityInstanceId]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ); - - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const result = yield* service.delegateTask(scope, { - task: "Summarize the diff.", - target: { driverKind: ProviderDriverKind.make("antigravity") }, - mode: "async", - clientRequestId: "delegate-antigravity-driver-1", - }); - assert.equal(result.status, "running"); - const commands = yield* Ref.get(dispatched); - assert.equal(commands.length, 1); - const request = commands[0] as { - modelSelection: { instanceId: string; model: string }; - }; - assert.equal(request.modelSelection.instanceId, antigravityInstanceId); - assert.equal(request.modelSelection.model, "ant-model"); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); - }), - ); - - it.effect("rejects delegation to a provider without a registered adapter", () => - Effect.gen(function* () { - const forkOnlyInstanceId = ProviderInstanceId.make("forkOnly"); - const forkShadow = yield* buildUnavailableProviderSnapshot({ - driverKind: "forkOnly", - instanceId: forkOnlyInstanceId, - reason: "Driver 'forkOnly' is not registered in this build.", - checkedAt: "2026-09-13T00:00:00.000Z", - }); - const layerDependencies = Layer.mergeAll( - NodeServices.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - getThreadRecords: () => Effect.succeed(parentProjection([])), - }), - ServerSettings.layerTest(), - providerRegistryLayer([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - forkShadow, - ]), - adapterRegistryLayer([codexInstanceId]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ); - - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const byInstance = yield* service - .delegateTask(scope, { - task: "Summarize the diff.", - target: { providerInstanceId: forkOnlyInstanceId }, - mode: "async", - clientRequestId: "delegate-fork-1", - }) - .pipe(Effect.flip); - assert.equal(byInstance.code, "provider_unavailable"); - assert.isTrue(byInstance.message.includes("No V2 provider adapter is registered.")); - - const byDriver = yield* service - .delegateTask(scope, { - task: "Summarize the diff.", - target: { driverKind: ProviderDriverKind.make("forkOnly") }, - mode: "async", - clientRequestId: "delegate-fork-2", - }) - .pipe(Effect.flip); - assert.equal(byDriver.code, "provider_unavailable"); - assert.isTrue( - byDriver.message.includes("No V2 provider adapter is registered for driver forkOnly."), - ); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); - }), - ); - - it.effect("refuses delegation to a provider the project turned off", () => - Effect.gen(function* () { - const layerDependencies = Layer.mergeAll( - NodeServices.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - getThreadRecords: () => Effect.succeed(parentProjection([])), - dispatch: () => - Effect.fail( - new ThreadManagementService.ThreadManagementProviderInstanceDisabledError({ - projectId, - instanceId: codexInstanceId, - }), - ), - }), - providerRegistryLayer([ - providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }), - ]), - adapterRegistryLayer([codexInstanceId]), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - ServerSettings.layerTest(), - ); - - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const error = yield* service - .delegateTask(scope, { - task: "Summarize the diff.", - target: { providerInstanceId: codexInstanceId }, - mode: "async", - clientRequestId: "delegate-disabled-1", - }) - .pipe(Effect.flip); - assert.equal(error.code, "invalid_request"); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); - }), - ); - - it.effect("driver-only delegation skips an instance the project turned off", () => - Effect.gen(function* () { - const altInstanceId = ProviderInstanceId.make("codex-alt"); - const dispatched = yield* Ref.make>([]); - const task = { - id: taskId, - threadId: parentThreadId, - runId: parentRunId, - parentNodeId, - origin: "app_owned", - createdBy: "agent", - driver: ProviderDriverKind.make("codex"), - providerInstanceId: altInstanceId, - providerThreadId: null, - childThreadId, - nativeTaskRef: null, - prompt: "Summarize the diff.", - title: null, - model: "gpt-5.4", + model: "gpt-5.4", status: "running", result: null, startedAt: null, @@ -1581,108 +1717,166 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); - it.effect("re-probes an unavailable target once before refusing it", () => - Effect.gen(function* () { - const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); - const claudeDriver = ProviderDriverKind.make("claudeAgent"); - const task = { - id: taskId, - threadId: parentThreadId, - runId: parentRunId, - parentNodeId, - origin: "app_owned", - createdBy: "agent", - driver: claudeDriver, - providerInstanceId: claudeInstanceId, - providerThreadId: null, - childThreadId, - nativeTaskRef: null, - prompt: "Review the diff.", - title: null, - model: "claude-opus-5-5", - status: "running", - result: null, - startedAt: null, - completedAt: null, - }; - const healthy = providerSnapshot({ - instanceId: claudeInstanceId, - driver: claudeDriver, - model: "claude-opus-5-5", - }); - const missingCli: ServerProvider = { - ...healthy, - installed: false, - status: "error", - message: "Claude Agent CLI (`claude`) was not found on PATH.", - }; - const codex = providerSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: "gpt-5.4", - }); - let cliInstalled = false; - const probes = yield* Ref.make(0); - const dispatched = yield* Ref.make(0); - const layerDependencies = Layer.mergeAll( - NodeServices.layer, - Layer.mock(ThreadManagementService.ThreadManagementService)({ - hasReceipt: () => Effect.succeed(false), - assertProviderInstanceEnabled: () => Effect.void, - getThreadRecords: (threadId) => - Effect.succeed( - threadId === parentThreadId ? parentProjection([task]) : childProjection, - ), - dispatch: () => - Ref.update(dispatched, (count) => count + 1).pipe( - Effect.as({ - sequence: 1, - storedEvents: [ - { - sequence: 1, - commandId: null, - event: { type: "subagent.updated", payload: task }, - }, - ], - } as never), + it.live.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), + ), ), - }), - ServerSettings.layerTest(), - Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([codex, missingCli]), - refreshInstance: () => - Ref.update(probes, (count) => count + 1).pipe( - Effect.as([codex, cliInstalled ? healthy : missingCli]), + Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), + Layer.provideMerge(layerSettings), + ); + const layerTest = layerOrchestratorService.pipe( + Layer.provideMerge(layerThreads), + Layer.provide( + Layer.mergeAll( + NodeServices.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(ScheduledTaskService.ScheduledTaskService)({}), + ), ), - }), - adapterRegistryLayer([codexInstanceId, claudeInstanceId]), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - ); - - yield* Effect.gen(function* () { - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const delegate = (clientRequestId: string) => - service.delegateTask(scope, { - task: "Review the diff.", - target: { providerInstanceId: claudeInstanceId, model: "claude-opus-5-5" }, - mode: "async", - clientRequestId, - }); - - const error = yield* delegate("delegate-recheck-1").pipe(Effect.flip); - assert.equal(error.code, "provider_unavailable"); - assert.equal(yield* Ref.get(probes), 1); - assert.equal(yield* Ref.get(dispatched), 0); + ); + 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", + }); - cliInstalled = true; - const result = yield* delegate("delegate-recheck-2"); - assert.equal(result.providerInstanceId, claudeInstanceId); - assert.equal(yield* Ref.get(probes), 2); - assert.equal(yield* Ref.get(dispatched), 1); - }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); - }), + 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); + + 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(NodeServices.layer)), + ), ); it.effect( @@ -1758,6 +1952,22 @@ describe("OrchestratorMcpService provider resolution", () => { selectedInstanceId: null, candidateDriver: driver, }, + { + name: "inherited-unavailable", + inheritedEnabled: false, + peerEnabled: true, + explicit: false, + selectedInstanceId: null, + candidateDriver: driver, + }, + { + name: "explicit-disabled-without-adapter", + inheritedEnabled: false, + peerEnabled: true, + explicit: true, + selectedInstanceId: null, + candidateDriver: driver, + }, { name: "explicit-healthy", inheritedEnabled: true, @@ -1817,7 +2027,11 @@ describe("OrchestratorMcpService provider resolution", () => { enabled: testCase.peerEnabled, }), ]), - adapterRegistryLayer([codexInstanceId, codexAltInstanceId]), + adapterRegistryLayer( + testCase.name === "explicit-disabled-without-adapter" + ? [codexAltInstanceId] + : [codexInstanceId, codexAltInstanceId], + ), Layer.mock(ProjectService.ProjectService)({}), Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), @@ -1825,14 +2039,17 @@ describe("OrchestratorMcpService provider resolution", () => { yield* Effect.gen(function* () { const service = yield* OrchestratorMcpService.OrchestratorMcpService; - const target = testCase.explicit - ? ({ - providerInstanceId: - testCase.selectedInstanceId === null - ? codexInstanceId - : testCase.selectedInstanceId, - } as const) - : ({ driverKind: testCase.candidateDriver } as const); + const target = + testCase.name === "inherited-unavailable" + ? undefined + : testCase.explicit + ? ({ + providerInstanceId: + testCase.selectedInstanceId === null + ? codexInstanceId + : testCase.selectedInstanceId, + } as const) + : ({ driverKind: testCase.candidateDriver } as const); if (testCase.selectedInstanceId === null) { const error = yield* service .delegateTask(scope, { @@ -1843,6 +2060,27 @@ describe("OrchestratorMcpService provider resolution", () => { }) .pipe(Effect.flip); assert.equal(error.code, "provider_unavailable", testCase.name); + if ( + testCase.name === "explicit-unavailable" || + testCase.name === "inherited-unavailable" || + testCase.name === "explicit-disabled-without-adapter" + ) { + const expectedMessage = + `Provider ${codexInstanceId} cannot run a child task: ` + + (testCase.name === "explicit-disabled-without-adapter" + ? "No V2 provider adapter is registered. " + : "") + + "Provider instance is disabled."; + assert.equal(error.message, expectedMessage); + const threadError = yield* service + .createThreads(scope, { + threads: [{ prompt: "Summarize the diff.", target }], + clientRequestId: `disabled-threads-${testCase.name}`, + }) + .pipe(Effect.flip); + assert.equal(threadError.code, "provider_unavailable"); + assert.equal(threadError.message, expectedMessage); + } if (testCase.name === "cross-driver-no-available-candidate") { assert.isTrue(error.message.includes("driver claudeAgent"), testCase.name); const threadError = yield* service @@ -2138,6 +2376,192 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); }); + it.effect( + "reports the child run's selection after a restart and the thread selection before launch", + () => + Effect.gen(function* () { + const runSelection = { + instanceId: ProviderInstanceId.make("claudeAgent-personal"), + model: "claude-opus-4-6", + options: [ + { id: "effort", value: "max" }, + { id: "fastMode", value: true }, + ], + } as const; + const threadSelection = { + instanceId: codexInstanceId, + model: "gpt-5.4", + options: [{ id: "reasoningEffort", value: "high" }], + } as const; + let hasRun = true; + const task = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + providerInstanceId: ProviderInstanceId.make("claudeAgent-work"), + model: "claude-sonnet-4-6", + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? parentProjection([task]) + : ({ + ...childProjection, + thread: { ...childProjection.thread, modelSelection: threadSelection }, + runs: hasRun + ? [ + { + id: RunId.make("run:mcp-restarted-child"), + ordinal: 1, + status: "running", + modelSelection: runSelection, + }, + ] + : [], + } as unknown as OrchestrationV2ThreadProjection), + ), + }), + ServerSettings.layerTest(), + providerRegistryLayer([]), + adapterRegistryLayer([]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + for (const selection of [runSelection, threadSelection]) { + const result = yield* service.taskStatus(scope, taskId); + assert.equal(result.providerInstanceId, selection.instanceId); + assert.equal(result.model, selection.model); + assert.deepEqual(result.options, selection.options); + hasRun = false; + } + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + + it.effect( + "inherits delegated options, merges overrides, and resets on explicit clearing or a new target", + () => + Effect.gen(function* () { + const peerId = ProviderInstanceId.make("codex-subscription-2"); + const driver = ProviderDriverKind.make("codex"); + const inherited = { + instanceId: codexInstanceId, + model: "gpt-5.4", + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "serviceTier", value: "priority" }, + ], + } as const; + const override = [{ id: "reasoningEffort", value: "max" }] as const; + const cases = [ + { + name: "partial override", + target: { options: override }, + expected: { ...inherited, options: [...override, inherited.options[1]] }, + }, + { + name: "clear with array", + target: { options: [] }, + expected: { ...inherited, options: [] }, + }, + { + name: "clear with object", + target: { options: {} }, + expected: { ...inherited, options: [] }, + }, + { + name: "change model", + target: { model: "other-model" }, + expected: { instanceId: codexInstanceId, model: "other-model" }, + }, + { + name: "change provider with override", + target: { providerInstanceId: peerId, options: { reasoningEffort: "max" } }, + expected: { instanceId: peerId, model: inherited.model, options: override }, + }, + ] as const; + for (const testCase of cases) { + const commands: Array = []; + const task = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + providerInstanceId: testCase.expected.instanceId, + model: testCase.expected.model, + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + assertProviderInstanceEnabled: () => Effect.void, + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? parentProjection(commands.length > 0 ? [task] : [], inherited) + : childProjection, + ), + dispatch: (command) => + Effect.sync(() => { + commands.push(command); + return { + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task } }], + } as never; + }), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + { + ...providerSnapshot({ + instanceId: codexInstanceId, + driver, + model: inherited.model, + }), + models: [inherited.model, "other-model"].map((model) => ({ + slug: model, + name: model, + isCustom: false, + capabilities: null, + })), + }, + providerSnapshot({ instanceId: peerId, driver, model: inherited.model }), + ]), + adapterRegistryLayer([codexInstanceId, peerId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const capabilities = yield* service.capabilities(scope); + assert.deepEqual(capabilities.inheritedOptions, inherited.options); + yield* service.delegateTask(scope, { + task: "Review the change.", + target: yield* decodeTarget(testCase.target), + mode: "async", + clientRequestId: testCase.name, + }); + assert.deepEqual( + (commands[0] as { modelSelection: unknown }).modelSelection, + testCase.expected, + testCase.name, + ); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + } + }), + ); describe("resolveRuntimeMode", () => { const muse = { @@ -2171,3 +2595,79 @@ describe("OrchestratorMcpService provider resolution", () => { ); }); }); + +describe("OrchestratorMcpService thread lookup", () => { + const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04"); + const launched = liveThreadShell(ThreadId.make(`mcp:${bareId}`)); + const deletedLaunched = { ...launched, deletedAt: DateTime.makeUnsafe("2026-10-05T00:00:00Z") }; + const client: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:thread-lookup"), + requestNamespace: "client:thread-lookup", + thread: undefined, + client: { sessionId: "thread-lookup", label: "Claude Code", access: "full-access" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const service = (shells: ReadonlyArray, sent: Ref.Ref) => + layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadShell: (threadId) => + Effect.succeed(shells.find((shell) => shell.id === threadId) ?? null), + sendToThread: () => Ref.update(sent, (count) => count + 1).pipe(Effect.as({} as never)), + }), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ), + ), + ); + const failuresFor = (shells: ReadonlyArray) => + Effect.gen(function* () { + const sent = yield* Ref.make(0); + return yield* Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + const read = yield* mcp.readThread(client, { threadId: bareId }).pipe(Effect.flip); + const send = yield* mcp + .sendToThread(client, { threadId: bareId, message: "hello" }) + .pipe(Effect.flip); + return { read, send, sends: yield* Ref.get(sent) }; + }).pipe(Effect.provide(service(shells, sent))); + }); + + it.effect("points a bare uuid at the mcp: thread it belongs to", () => + Effect.gen(function* () { + const { read, send, sends } = yield* failuresFor([launched]); + for (const error of [read, send]) { + assert.equal(error.code, "thread_not_found"); + assert.include(error.message, `mcp:${bareId}`); + } + assert.equal(sends, 0); + }), + ); + + it.effect("keeps the plain message for an id that matches nothing", () => + Effect.gen(function* () { + const { read, send } = yield* failuresFor([]); + assert.equal(read.code, "thread_not_found"); + assert.equal(read.message, `Thread ${bareId} is no longer available.`); + assert.equal(send.code, "thread_not_found"); + assert.equal(send.message, `Thread ${bareId} was not found.`); + }), + ); + + it.effect("does not name an mcp: thread that was deleted", () => + Effect.gen(function* () { + const { read, send } = yield* failuresFor([deletedLaunched]); + assert.equal(read.message, `Thread ${bareId} is no longer available.`); + assert.equal(send.message, `Thread ${bareId} was not found.`); + }), + ); +}); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 94189a7587090..d69a8649d13cf 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -5,6 +5,7 @@ import { MessageId, type ModelSelection, NodeId, + ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, TurnItemId, type OrchestrationV2Run, type OrchestrationV2Subagent, @@ -13,7 +14,9 @@ import { type OrchestrationV2ThreadLaunchWorkspaceStrategy, type OrchestrationV2TurnItem, OrchestratorMcpFailure, + type OrchestratorMcpCapabilitiesInput, type OrchestratorMcpCapabilitiesResult, + type OrchestratorMcpModelOption, type OrchestratorMcpCreateThreadsInput, type OrchestratorMcpCreateThreadsResult, type OrchestratorMcpCreatedThread, @@ -36,6 +39,7 @@ import { type OrchestratorMcpListScheduledTasksInput, type ProjectId, type OrchestratorMcpThreadDetail, + type OrchestratorMcpThreadPullRequest, type OrchestratorMcpThreadInterruptInput, type OrchestratorMcpThreadInterruptResult, type OrchestratorMcpThreadListInput, @@ -53,13 +57,22 @@ import { type ProviderInstanceId, type ProviderOptionDescriptor, type ProviderOptionSelection, + ProviderRequestKind, type RuntimeMode, type ScheduledTask, type ScheduledTaskUpsertInput, type ServerProvider, + type ServerProviderModel, ThreadId, + isOrchestrationV2WorkActive, } from "@t3tools/contracts"; +import { getProviderOptionCurrentValue } from "@t3tools/shared/model"; import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; +import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import { + normalizeThreadPullRequestKey, + visibleThreadPullRequests, +} from "../sourceControl/threadPullRequests.ts"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -87,6 +100,7 @@ import * as ThreadManagementService from "../orchestration-v2/ThreadManagementSe import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { isSnoozed } from "../orchestration-v2/ThreadSettlementService.ts"; +import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts"; @@ -128,6 +142,7 @@ type TerminalTaskStatus = Extract< export interface OrchestratorMcpServiceShape { readonly capabilities: ( scope: McpInvocationScope, + input?: OrchestratorMcpCapabilitiesInput, ) => Effect.Effect; readonly delegateTask: ( scope: McpInvocationScope, @@ -161,9 +176,7 @@ export interface OrchestratorMcpServiceShape { scope: McpInvocationScope, input: OrchestratorMcpDeleteScheduledTaskInput, ) => Effect.Effect; - /** - * The value never reaches the agent: the result is a status. - */ + /** Only status reaches the agent, never this value. */ readonly requestSecret: ( scope: McpInvocationScope, input: OrchestratorMcpRequestSecretInput, @@ -201,13 +214,7 @@ function failure(code: OrchestratorMcpFailure["code"], message: string): Orchest return new OrchestratorMcpFailure({ code, message }); } -/** - * A caller's thread is live while it is not archived, runs on the caller's - * provider instance, and has an active run or a background subagent that - * instance started. A background subagent outlives its run and calls tools - * with its thread's credential, which is revoked when the provider process - * goes away. - */ +/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */ export const isLiveCallerShell = ( shell: Pick< OrchestrationV2ThreadShell, @@ -224,6 +231,26 @@ export const isLiveCallerShell = ( ) ?? false)); +/** + * Threads an agent starts over MCP are `mcp:`, and agents often paste the + * bare uuid. The id is never rewritten, so permission checks keyed on it still + * hold; the miss only names a live thread the caller could read by its full id. + */ +export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* ( + threads: Pick, + threadId: ThreadId, + message: string, +) { + const prefixed = ThreadId.make(`mcp:${threadId}`); + const shell = yield* threads.getThreadShell(prefixed).pipe(Effect.orElseSucceed(() => null)); + return yield* failure( + "thread_not_found", + shell === null || shell.deletedAt !== null + ? message + : `${message} Did you mean \`${prefixed}\`?`, + ); +}); + function threadManagementFailure(error: unknown): OrchestratorMcpFailure { if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error)); switch (error._tag) { @@ -245,6 +272,11 @@ function threadManagementFailure(error: unknown): OrchestratorMcpFailure { } } +// Without a reason, a Stop reads as the user's (see RunExecutionService.USER_STOP_REASON). +function agentStopReason(reason: string | undefined): string { + return reason === undefined ? "Stopped by an agent" : `Stopped by an agent: ${reason}`; +} + function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } @@ -275,6 +307,61 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato }; } +/** + * Large catalogs (OpenCode, Cursor, Pi) can list hundreds of models, so agents + * get a short list by default and search for the rest. These providers have + * small official catalogs, so all their current models are listed. + */ +const FULL_CATALOG_DRIVERS: ReadonlySet = new Set(["codex", "claudeAgent", "muse", "grok"]); +const LISTED_MODEL_LIMIT = 8; + +/** + * Picks the models orchestrator_capabilities shows for one provider. Hidden + * models never appear. With search terms, lists matches; otherwise lists pinned + * models (custom, favorite, the caller's own) plus the provider's non-legacy + * models, or only the first few in the user's model order for large catalogs. + */ +function listCapabilityModels(input: { + readonly provider: ServerProvider; + readonly preferences: + | { readonly hiddenModels: ReadonlyArray; readonly modelOrder: ReadonlyArray } + | undefined; + readonly isPinned: (model: ServerProviderModel) => boolean; + readonly searchTerms: ReadonlyArray; +}) { + const rank = new Map(input.preferences?.modelOrder.map((slug, index) => [slug, index])); + const visible = input.provider.models + .filter((model) => model.isCustom || !input.preferences?.hiddenModels.includes(model.slug)) + .toSorted((a, b) => (rank.get(a.slug) ?? rank.size) - (rank.get(b.slug) ?? rank.size)); + if (input.searchTerms.length > 0) { + const matches = visible.filter((model) => { + const text = `${model.slug} ${model.name} ${model.subProvider ?? ""}`.toLowerCase(); + return input.searchTerms.every((term) => text.includes(term)); + }); + const listed = matches.slice(0, LISTED_MODEL_LIMIT); + return { listed, omitted: matches.length - listed.length }; + } + const current = visible.filter((model) => !model.isLegacy); + const shown = new Set( + FULL_CATALOG_DRIVERS.has(input.provider.driver) + ? current + : current.slice(0, LISTED_MODEL_LIMIT), + ); + const listed = visible.filter((model) => input.isPinned(model) || shown.has(model)); + return { listed, omitted: visible.length - listed.length }; +} + +/** Option ids and allowed values are all a delegating agent needs; labels are UI copy. */ +function capabilityModelOption(descriptor: ProviderOptionDescriptor): OrchestratorMcpModelOption { + const defaultValue = getProviderOptionCurrentValue(descriptor); + return { + id: descriptor.id, + values: + descriptor.type === "boolean" ? [false, true] : descriptor.options.map((choice) => choice.id), + ...(defaultValue === undefined ? {} : { default: defaultValue }), + }; +} + function providerConstraints( provider: ServerProvider | undefined, supportsOrchestrationV2: boolean, @@ -284,11 +371,15 @@ function providerConstraints( constraints.push("No V2 provider adapter is registered."); } if (provider === undefined) return constraints; - if (!provider.enabled) constraints.push("Provider instance is disabled."); - if (!provider.installed) constraints.push("Provider executable is not installed."); if (!isProviderAvailable(provider)) { constraints.push(provider.unavailableReason ?? "Provider driver is unavailable."); } + if (!provider.enabled) { + constraints.push("Provider instance is disabled."); + // Disabled snapshots contain placeholders for installation, health, and auth. + return constraints; + } + if (!provider.installed) constraints.push("Provider executable is not installed."); if (provider.status === "error" || provider.status === "disabled") { constraints.push(provider.message ?? `Provider status is ${provider.status}.`); } @@ -298,11 +389,7 @@ function providerConstraints( return constraints; } -/** - * Models without descriptors skip the descriptor checks (mirroring how model slugs are only - * validated when the provider advertises models), but duplicate ids always fail: downstream - * consumers disagree on whether the first or last value of a duplicated id wins. - */ +/** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */ function invalidOptionSelections( selections: ReadonlyArray, descriptors: ReadonlyArray | undefined, @@ -362,7 +449,7 @@ function taskStatusForRun( } } -export function delegatedTaskRun( +function delegatedTaskRun( childProjection: Pick, task: OrchestrationV2Subagent, ): OrchestrationV2Run | undefined { @@ -382,7 +469,7 @@ export function delegatedTaskRun( : childProjection.runs.find((run) => run.id === spawnTransfer.targetRunId); } -export function hasPendingChildRuns( +function hasPendingChildRuns( childProjection: Pick, delegatedRun: OrchestrationV2Run | undefined, ): boolean { @@ -405,6 +492,53 @@ function isTerminalTaskStatus( ); } +function endsTaskWait(result: OrchestratorMcpDelegateTaskResult): boolean { + return ( + result.hasPendingQuestion || + result.pendingApproval !== null || + isTerminalTaskStatus(result.status) + ); +} + +const isApprovalRequestKind = Schema.is(ProviderRequestKind); + +function pendingTaskApproval( + child: Pick, + taskId: NodeId, + originalRun: OrchestrationV2Run | undefined, +) { + const taskRunIds = new Set( + child.runs + .filter( + (run) => + !ThreadManagementService.isTerminalRunStatus(run.status) && + (run.delegatedTaskId === taskId || + // Legacy tasks own only their original run, not later turns in the child thread. + (run.delegatedTaskId === undefined && run.id === originalRun?.id)), + ) + .map((run) => run.id), + ); + let approval: OrchestratorMcpDelegateTaskResult["pendingApproval"] = null; + let oldestCreatedAt = Infinity; + for (const request of child.runtimeRequests) { + if ( + request.status !== "pending" || + request.responseCapability.type !== "live" || + !isApprovalRequestKind(request.kind) + ) { + continue; + } + const runId = child.nodes.find((node) => node.id === request.nodeId)?.runId; + if (runId === undefined || runId === null || !taskRunIds.has(runId)) continue; + const createdAt = DateTime.toEpochMillis(request.createdAt); + if (createdAt < oldestCreatedAt) { + oldestCreatedAt = createdAt; + approval = { requestId: request.id, kind: request.kind, runId }; + } + } + return approval; +} + function directAppOwnedChildTasks( parent: Pick, target: Pick, @@ -703,6 +837,19 @@ function threadSnooze( }; } +function threadPullRequests( + links: OrchestrationV2ThreadShell["pullRequests"], +): OrchestratorMcpThreadPullRequest[] { + return visibleThreadPullRequests(links ?? []).map((link) => ({ + host: normalizeThreadPullRequestKey(link).host, + repository: link.repository, + number: link.number, + url: link.url, + source: link.source, + state: link.snapshot?.state ?? null, + })); +} + function listItemFromShell( shell: OrchestrationV2ThreadShell, nowMs: number, @@ -710,6 +857,7 @@ function listItemFromShell( return { threadId: shell.id, title: shell.title, + link: formatThreadLink(shell.id, shell.title), createdBy: shell.createdBy, creationSource: shell.creationSource, status: shell.activityRunStatus ?? shell.status, @@ -719,6 +867,7 @@ function listItemFromShell( runtimeMode: shell.runtimeMode, interactionMode: shell.interactionMode, linkedPullRequest: shell.linkedPullRequest ?? null, + pullRequests: threadPullRequests(shell.pullRequests), ...threadSettlement(shell), ...threadSnooze(shell, nowMs), parentThreadId: shell.lineage.parentThreadId, @@ -741,6 +890,7 @@ function threadDetail( threadId: projection.thread.id, projectId: projection.thread.projectId, title: projection.thread.title, + link: formatThreadLink(projection.thread.id, projection.thread.title), createdBy: projection.thread.createdBy, creationSource: projection.thread.creationSource, status: active?.status ?? latest?.status ?? "idle", @@ -751,6 +901,7 @@ function threadDetail( runtimeMode: projection.thread.runtimeMode, interactionMode: projection.thread.interactionMode, linkedPullRequest: projection.thread.linkedPullRequest ?? null, + pullRequests: threadPullRequests(projection.thread.pullRequests), titleRegeneration: projection.thread.titleRegeneration === undefined || projection.thread.titleRegeneration === null @@ -832,7 +983,9 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { case "web_search": return jsonText({ patterns: item.patterns, results: item.results }); case "approval_request": - return item.prompt ?? item.requestKind; + return [item.prompt ?? item.requestKind, item.reason] + .filter((line): line is string => line !== undefined) + .join("\n"); case "checkpoint": return jsonText(item.files); case "run_interrupt_request": @@ -888,6 +1041,7 @@ function timelineItem(input: { messageId, createdBy: message?.createdBy ?? null, creationSource: message?.creationSource ?? null, + ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), type: input.row.item.type, status: input.row.item.status, title: input.row.item.title, @@ -992,35 +1146,38 @@ const make = Effect.gen(function* () { ) .pipe(Effect.mapError(threadManagementFailure)); - const loadCaller = (scope: McpInvocationScope) => - Effect.gen(function* () { - yield* requireCapability(scope); - if (scope.thread === undefined) { - return { - parent: undefined, - limits: { - runtimeMode: clientRuntimeModeCeiling(scope.client), - interactionMode: "default", - } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode }, - } as const; - } - const parent = yield* loadProjection(scope.thread.threadId); + const loadCaller = Effect.fn("OrchestratorMcpService.loadCaller")(function* ( + scope: McpInvocationScope, + ) { + yield* requireCapability(scope); + if (scope.thread === undefined) { return { - parent, + parent: undefined, limits: { - runtimeMode: parent.thread.runtimeMode, - interactionMode: parent.thread.interactionMode, - }, + runtimeMode: clientRuntimeModeCeiling(scope.client), + interactionMode: "default", + } satisfies { runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode }, } as const; - }); + } + const parent = yield* loadProjection(scope.thread.threadId); + return { + parent, + limits: { + runtimeMode: parent.thread.runtimeMode, + interactionMode: parent.thread.interactionMode, + }, + } as const; + }); - const loadThreadCaller = (scope: McpInvocationScope, operation: string) => - Effect.gen(function* () { - yield* requireCapability(scope); - const threadScope = yield* requireThreadScope(scope, operation); - const parent = yield* loadProjection(threadScope.thread.threadId); - return { scope: threadScope, parent } as const; - }); + const loadThreadCaller = Effect.fn("OrchestratorMcpService.loadThreadCaller")(function* ( + scope: McpInvocationScope, + operation: string, + ) { + yield* requireCapability(scope); + const threadScope = yield* requireThreadScope(scope, operation); + const parent = yield* loadProjection(threadScope.thread.threadId); + return { scope: threadScope, parent } as const; + }); const resolveProjectTarget = ( parent: Pick | undefined, @@ -1037,31 +1194,31 @@ const make = Effect.gen(function* () { ), ); - const loadTargetThread = (threadId: ThreadId) => - Effect.gen(function* () { - const shell = yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.mapError(threadManagementFailure)); - if (shell === null || shell.deletedAt !== null) { - return yield* failure("thread_not_found", `Thread ${threadId} was not found.`); - } - return yield* loadProjectThread(shell.projectId, threadId); - }); + const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* ( + threadId: ThreadId, + ) { + const shell = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(threadManagementFailure)); + if (shell === null || shell.deletedAt !== null) { + return yield* threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`); + } + return yield* loadProjectThread(shell.projectId, threadId); + }); - const loadScopedThread = (scope: McpInvocationScope, threadId: ThreadId) => - Effect.gen(function* () { - const caller = yield* loadCaller(scope); - const target = - caller.parent !== undefined && threadId === caller.parent.thread.id - ? caller.parent - : yield* loadTargetThread(threadId); - return { ...caller, target } as const; - }); + const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* ( + scope: McpInvocationScope, + threadId: ThreadId, + ) { + const caller = yield* loadCaller(scope); + const target = + caller.parent !== undefined && threadId === caller.parent.thread.id + ? caller.parent + : yield* loadTargetThread(threadId); + return { ...caller, target } as const; + }); - /** - * A thread caller writes to another thread only while its own run is live, - * so a credential that outlived its session cannot reach across threads. - */ + /** Cross-thread writes require a live caller run; stale session credentials cannot authorize them. */ const assertLiveCallerForOtherThread = ( scope: McpInvocationScope, parent: Pick | undefined, @@ -1107,35 +1264,37 @@ const make = Effect.gen(function* () { : Effect.void; }; - const loadReadableThread = (scope: McpInvocationScope, threadId: ThreadId) => - Effect.gen(function* () { - const { parent } = yield* loadCaller(scope); - const shell = yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.mapError(threadManagementFailure)); - if (shell === null || shell.deletedAt !== null) { - return yield* failure("thread_not_found", `Thread ${threadId} is no longer available.`); - } - const target = yield* threadManagement - .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [ - "runs", - "runtimeRequests", - "contextTransfers", - ]) - .pipe(Effect.mapError(threadManagementFailure)); - return { parent, target, shell } as const; - }); + const loadReadableThread = Effect.fn("OrchestratorMcpService.loadReadableThread")(function* ( + scope: McpInvocationScope, + threadId: ThreadId, + ) { + const { parent } = yield* loadCaller(scope); + const shell = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(threadManagementFailure)); + if (shell === null || shell.deletedAt !== null) { + return yield* threadNotFound( + threadManagement, + threadId, + `Thread ${threadId} is no longer available.`, + ); + } + const target = yield* threadManagement + .getProjectThreadRecords({ projectId: shell.projectId, threadId }, [ + "runs", + "runtimeRequests", + "contextTransfers", + ]) + .pipe(Effect.mapError(threadManagementFailure)); + return { parent, target, shell } as const; + }); const loadProviders = providerRegistry.getProviders; const loadOrchestrationCapableInstanceIds = () => providerAdapters.list().pipe(Effect.map((instanceIds) => new Set(instanceIds))); - /** - * Provider snapshots only re-probe while a client is in the foreground, so an - * unattended agent can see a provider as unavailable after it was fixed. - * Re-probe the requested instance once before refusing it. - */ + /** Background agents miss foreground-only health probes; re-probe once before refusing. */ const assertTargetEnabledForProject = ( parent: Pick, commandId: CommandId, @@ -1168,344 +1327,365 @@ const make = Effect.gen(function* () { ); }; - const resolveTarget = (input: { + const resolveTarget = Effect.fn("OrchestratorMcpService.resolveTarget")(function* (input: { readonly parent: Pick; readonly target: OrchestratorMcpTarget | undefined; readonly providers: ReadonlyArray; - /** - * Set only when the command that will dispatch this target already has a receipt: that - * dispatch can only replay the recorded result, never start anything new, so filtering - * candidates by the project's current settings would just refuse a retry that does no new - * work. Never set this for a resolution whose dispatch uses a different command id than the - * one checked for a receipt. - */ + /** Receipt replays bypass current settings because they start no work. Dispatch must reuse the checked command ID. */ readonly skipProjectEnablementFilter?: boolean; - }): Effect.Effect => - Effect.gen(function* () { - const requestedInstanceId = input.target?.providerInstanceId; - const requestedDriver = input.target?.driverKind; - const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds(); - let instanceId = requestedInstanceId; - - if (instanceId === undefined && requestedDriver !== undefined) { - const candidates = input.providers.filter( - (provider) => - provider.driver === requestedDriver && - orchestrationCapableInstanceIds.has(provider.instanceId), - ); - if (candidates.length === 0) { - return yield* failure( - "provider_unavailable", - `No V2 provider adapter is registered for driver ${requestedDriver}.`, - ); - } - const healthyCandidates = candidates.filter( - (candidate) => providerConstraints(candidate, true).length === 0, - ); - const inheritedCandidate = healthyCandidates.find( - (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId, - ); - const orderedCandidates = [ - ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]), - ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate), - ]; - for (const candidate of orderedCandidates) { - const enabledForProject = - input.skipProjectEnablementFilter === true || - (yield* threadManagement.isProviderInstanceEnabledForProject({ - projectId: input.parent.thread.projectId, - instanceId: candidate.instanceId, - })); - if (enabledForProject) { - instanceId = candidate.instanceId; - break; - } - } - if (instanceId === undefined) { - return yield* failure( - "provider_unavailable", - healthyCandidates.length === 0 - ? `No available V2 provider instance for driver ${requestedDriver}.` - : `No instance of driver ${requestedDriver} is enabled for this project.`, - ); - } - } - instanceId ??= input.parent.thread.modelSelection.instanceId; - - const provider = input.providers.find((candidate) => candidate.instanceId === instanceId); - if (provider === undefined) { + }): Effect.fn.Return { + const requestedInstanceId = input.target?.providerInstanceId; + const requestedDriver = input.target?.driverKind; + const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds(); + let instanceId = requestedInstanceId; + + if (instanceId === undefined && requestedDriver !== undefined) { + const candidates = input.providers.filter( + (provider) => + provider.driver === requestedDriver && + orchestrationCapableInstanceIds.has(provider.instanceId), + ); + if (candidates.length === 0) { return yield* failure( "provider_unavailable", - `Provider instance ${instanceId} is not registered.`, + `No V2 provider adapter is registered for driver ${requestedDriver}.`, ); } - if (requestedDriver !== undefined && provider.driver !== requestedDriver) { - return yield* failure( - "invalid_request", - `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`, - ); - } - const constraints = providerConstraints( - provider, - orchestrationCapableInstanceIds.has(provider.instanceId), + const healthyCandidates = candidates.filter( + (candidate) => providerConstraints(candidate, true).length === 0, ); - if (constraints.length > 0) { + const inheritedCandidate = healthyCandidates.find( + (candidate) => candidate.instanceId === input.parent.thread.modelSelection.instanceId, + ); + const orderedCandidates = [ + ...(inheritedCandidate === undefined ? [] : [inheritedCandidate]), + ...healthyCandidates.filter((candidate) => candidate !== inheritedCandidate), + ]; + for (const candidate of orderedCandidates) { + const enabledForProject = + input.skipProjectEnablementFilter === true || + (yield* threadManagement.isProviderInstanceEnabledForProject({ + projectId: input.parent.thread.projectId, + instanceId: candidate.instanceId, + })); + if (enabledForProject) { + instanceId = candidate.instanceId; + break; + } + } + if (instanceId === undefined) { return yield* failure( "provider_unavailable", - `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`, + healthyCandidates.length === 0 + ? `No available V2 provider instance for driver ${requestedDriver}.` + : `No instance of driver ${requestedDriver} is enabled for this project.`, ); } + } + instanceId ??= input.parent.thread.modelSelection.instanceId; - const inheritedSelection = input.parent.thread.modelSelection; - const requestedModel = input.target?.model; - const model = - requestedModel ?? - (instanceId === inheritedSelection.instanceId - ? inheritedSelection.model - : provider?.models[0]?.slug); - if (model === undefined) { - return yield* failure( - "model_unavailable", - `Provider ${instanceId} has no model available for inheritance.`, - ); - } - if ( - requestedModel !== undefined && - provider !== undefined && - provider.models.length > 0 && - !provider.models.some((candidate) => candidate.slug === requestedModel) - ) { + const provider = input.providers.find((candidate) => candidate.instanceId === instanceId); + if (provider === undefined) { + return yield* failure( + "provider_unavailable", + `Provider instance ${instanceId} is not registered.`, + ); + } + if (requestedDriver !== undefined && provider.driver !== requestedDriver) { + return yield* failure( + "invalid_request", + `Provider instance ${instanceId} uses driver ${provider.driver}, not ${requestedDriver}.`, + ); + } + const constraints = providerConstraints( + provider, + orchestrationCapableInstanceIds.has(provider.instanceId), + ); + if (constraints.length > 0) { + return yield* failure( + "provider_unavailable", + `Provider ${instanceId} cannot run a child task: ${constraints.join(" ")}`, + ); + } + + const inheritedSelection = input.parent.thread.modelSelection; + const requestedModel = input.target?.model; + const model = + requestedModel ?? + (instanceId === inheritedSelection.instanceId + ? inheritedSelection.model + : provider?.models[0]?.slug); + if (model === undefined) { + return yield* failure( + "model_unavailable", + `Provider ${instanceId} has no model available for inheritance.`, + ); + } + if ( + requestedModel !== undefined && + provider !== undefined && + provider.models.length > 0 && + !provider.models.some((candidate) => candidate.slug === requestedModel) + ) { + return yield* failure( + "model_unavailable", + `Model ${requestedModel} is not advertised by provider ${instanceId}.`, + ); + } + + const requestedOptions = input.target?.options; + if (requestedOptions !== undefined) { + const descriptors = provider.models.find((candidate) => candidate.slug === model) + ?.capabilities?.optionDescriptors; + const invalid = invalidOptionSelections(requestedOptions, descriptors); + if (invalid.length > 0) { return yield* failure( - "model_unavailable", - `Model ${requestedModel} is not advertised by provider ${instanceId}.`, + "invalid_request", + `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`, ); } + } - const requestedOptions = input.target?.options; - if (requestedOptions !== undefined) { - const descriptors = provider.models.find((candidate) => candidate.slug === model) - ?.capabilities?.optionDescriptors; - const invalid = invalidOptionSelections(requestedOptions, descriptors); - if (invalid.length > 0) { - return yield* failure( - "invalid_request", - `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`, - ); - } + const inheritsOptions = + instanceId === inheritedSelection.instanceId && model === inheritedSelection.model; + let options = inheritsOptions ? inheritedSelection.options : undefined; + if (requestedOptions !== undefined) { + const selections = new Map( + (requestedOptions.length === 0 ? [] : (options ?? [])).map((selection) => [ + selection.id, + selection, + ]), + ); + for (const selection of requestedOptions) { + selections.set(selection.id, selection); } - - return { - modelSelection: - instanceId === inheritedSelection.instanceId && - model === inheritedSelection.model && - requestedOptions === undefined - ? inheritedSelection - : requestedOptions === undefined - ? { instanceId, model } - : { instanceId, model, options: requestedOptions }, - supportedRuntimeModes: provider.supportedRuntimeModes, - }; - }); + options = [...selections.values()]; + } + return { + modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) }, + supportedRuntimeModes: provider.supportedRuntimeModes, + }; + }); const requestKey = (clientRequestId: string | undefined): Effect.Effect => clientRequestId === undefined ? crypto.randomUUIDv4().pipe(Effect.orDie) : Effect.succeed(clientRequestId); - const readTask = ( + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, waitTimedOut = false, acknowledgeTerminal = false, acknowledgementOperation = "task-status-acknowledge", - ): Effect.Effect => - Effect.gen(function* () { - yield* requireCapability(scope); - const parentProjection = yield* loadProjection(scope.thread.threadId); - const task = parentProjection.subagents.find( - (candidate) => - candidate.id === taskId && - candidate.origin === "app_owned" && - candidate.threadId === scope.thread.threadId, + ): Effect.fn.Return { + yield* requireCapability(scope); + const parentProjection = yield* loadProjection(scope.thread.threadId); + const task = parentProjection.subagents.find( + (candidate) => + candidate.id === taskId && + candidate.origin === "app_owned" && + candidate.threadId === scope.thread.threadId, + ); + if (task === undefined || task.childThreadId === null) { + return yield* failure( + "task_not_found", + `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, ); - if (task === undefined || task.childThreadId === null) { - return yield* failure( - "task_not_found", - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, - ); - } - const childControls = yield* threadManagement - .getThreadRecords( - task.childThreadId, - [ - "runs", - "messages", - "contextTransfers", - "subagents", - "providerThreads", - "runtimeRequests", - ], - { messageRoles: ["user"] }, - ) - .pipe(Effect.mapError(threadManagementFailure)); - const childRun = delegatedTaskRun(childControls, task); - const terminalRun = latestTerminalResultRun(childControls, childRun); - const progress = delegatedTaskProgress(childControls); - const taskResultRun = - childRun?.delegatedTaskId === task.id - ? childControls.runs - .filter((run) => run.delegatedTaskId === task.id) - .toSorted((a, b) => b.ordinal - a.ordinal)[0] - : progress.resultRun; - const taskWorkState = - childRun?.delegatedTaskId === task.id - ? isTerminalTaskStatus(taskStatusForRun(taskResultRun)) - ? "result_available" - : "working" - : progress.state; - const resultRunIds = [ - ...new Set( - [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined), - ), - ]; - const resultRecords = yield* threadManagement - .getThreadRecords(task.childThreadId, ["messages", "turnItems"], { - messageRoles: ["assistant"], - messageRunIds: resultRunIds, - turnItemRunIds: resultRunIds, - turnItemTypes: ["assistant_message", "error"], - }) - .pipe(Effect.mapError(threadManagementFailure)); - const childProjection = { - ...childControls, - messages: [...childControls.messages, ...resultRecords.messages], - turnItems: resultRecords.turnItems, + } + const childControls = yield* threadManagement + .getThreadRecords( + task.childThreadId, + [ + "runs", + "messages", + "contextTransfers", + "subagents", + "providerThreads", + "runtimeRequests", + "nodes", + ], + { messageRoles: ["user"], omitSettledLeafNodes: true }, + ) + .pipe(Effect.mapError(threadManagementFailure)); + const childRun = delegatedTaskRun(childControls, task); + const terminalRun = latestTerminalResultRun(childControls, childRun); + const progress = delegatedTaskProgress(childControls); + const taskResultRun = + childRun?.delegatedTaskId === task.id + ? childControls.runs + .filter((run) => run.delegatedTaskId === task.id) + .toSorted((a, b) => b.ordinal - a.ordinal)[0] + : progress.resultRun; + const taskWorkState = + childRun?.delegatedTaskId === task.id + ? isTerminalTaskStatus(taskStatusForRun(taskResultRun)) + ? "result_available" + : "working" + : progress.state; + const resultRunIds = [ + ...new Set( + [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined), + ), + ]; + const resultRecords = yield* threadManagement + .getThreadRecords(task.childThreadId, ["messages", "turnItems"], { + messageRoles: ["assistant"], + messageRunIds: resultRunIds, + turnItemRunIds: resultRunIds, + turnItemTypes: ["assistant_message", "error"], + }) + .pipe(Effect.mapError(threadManagementFailure)); + const childProjection = { + ...childControls, + messages: [...childControls.messages, ...resultRecords.messages], + turnItems: resultRecords.turnItems, + }; + const heldForRestart = + task.result === null && + taskWorkState === "result_available" && + (yield* threadManagement + .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId) + .pipe(Effect.mapError(threadManagementFailure))); + const workState = + task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState; + const status = + task.result !== null + ? taskStatusForRun( + task.status === "completed" || + task.status === "failed" || + task.status === "cancelled" || + task.status === "interrupted" + ? { status: task.status } + : childRun, + ) + : workState === "result_available" + ? taskStatusForRun(taskResultRun ?? childRun) + : taskStatusForRun(taskResultRun ?? childRun) === "queued" + ? "queued" + : "running"; + const derivedResult = + task.result !== null + ? task.result + : taskResultRun !== undefined && isTerminalTaskStatus(status) + ? subagentResultForRun(childProjection, taskResultRun).text + : null; + const resultTransfers = parentProjection.contextTransfers.filter( + (transfer) => + transfer.type === "subagent_result" && + transfer.sourceThreadId === task.childThreadId && + transfer.targetThreadId === scope.thread.threadId, + ); + const resultTransferForRun = (run: OrchestrationV2Run | undefined) => + !canExposeTaskRunResult(run) + ? null + : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ?? + (run.id === childRun?.id + ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined) + : undefined) ?? + null); + const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null; + const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun); + const latestTerminalSummary = canExposeTaskRunResult(terminalRun) + ? terminalRun.id === childRun?.id + ? derivedResult + : subagentResultForRun(childProjection, terminalRun).text + : null; + const resultContextTransferId = resultTransfer?.id ?? null; + const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null; + const modelSelection = childRun?.modelSelection ?? + childControls.thread.modelSelection ?? { + instanceId: task.providerInstanceId, + model: task.model, }; - const heldForRestart = - task.result === null && - taskWorkState === "result_available" && - (yield* threadManagement - .delegatedTaskResultPending(task.childThreadId, childRun?.delegatedTaskId) - .pipe(Effect.mapError(threadManagementFailure))); - const workState = - task.result !== null ? "result_available" : heldForRestart ? "working" : taskWorkState; - const status = - task.result !== null - ? taskStatusForRun( - task.status === "completed" || - task.status === "failed" || - task.status === "cancelled" || - task.status === "interrupted" - ? { status: task.status } - : childRun, - ) - : workState === "result_available" - ? taskStatusForRun(taskResultRun ?? childRun) - : taskStatusForRun(taskResultRun ?? childRun) === "queued" - ? "queued" - : "running"; - const derivedResult = - task.result !== null - ? task.result - : taskResultRun !== undefined && isTerminalTaskStatus(status) - ? subagentResultForRun(childProjection, taskResultRun).text - : null; - const resultTransfers = parentProjection.contextTransfers.filter( - (transfer) => - transfer.type === "subagent_result" && - transfer.sourceThreadId === task.childThreadId && - transfer.targetThreadId === scope.thread.threadId, - ); - const resultTransferForRun = (run: OrchestrationV2Run | undefined) => - !canExposeTaskRunResult(run) + const result = { + taskId: task.id, + childThreadId: task.childThreadId, + link: formatThreadLink(task.childThreadId, childControls.thread.title), + childRunId: childRun?.id ?? null, + childNodeId: task.id, + status, + workState, + hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun), + providerInstanceId: modelSelection.instanceId, + model: modelSelection.model, + options: modelSelection.options ?? [], + summary: derivedResult, + resultContextTransferId, + latestTerminalRunId: terminalRun?.id ?? null, + latestTerminalStatus: + terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null, + latestTerminalSummary: latestTerminalSummary === derivedResult ? null : latestTerminalSummary, + latestTerminalResultContextTransferId: + latestTerminalResultContextTransferId === resultContextTransferId ? null - : (resultTransfers.find((transfer) => transfer.sourcePoint.runId === run.id) ?? - (run.id === childRun?.id - ? resultTransfers.find((transfer) => transfer.sourcePoint.runId === undefined) - : undefined) ?? - null); - const resultTransfer = taskResultTransfer(parentProjection, childProjection, task) ?? null; - const terminalStatus = terminalRun === undefined ? null : taskStatusForRun(terminalRun); - const response = { - taskId: task.id, - childThreadId: task.childThreadId, - childRunId: childRun?.id ?? null, - childNodeId: task.id, - status, - workState, - hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun), - providerInstanceId: task.providerInstanceId, - model: task.model, - summary: derivedResult, - resultContextTransferId: resultTransfer?.id ?? null, - latestTerminalRunId: terminalRun?.id ?? null, - latestTerminalStatus: - terminalStatus !== null && isTerminalTaskStatus(terminalStatus) ? terminalStatus : null, - latestTerminalSummary: canExposeTaskRunResult(terminalRun) - ? terminalRun.id === childRun?.id - ? derivedResult - : subagentResultForRun(childProjection, terminalRun).text - : null, - latestTerminalResultContextTransferId: resultTransferForRun(terminalRun)?.id ?? null, - hasPendingQuestion: - !isTerminalTaskStatus(status) && - childControls.runtimeRequests.some( - (request) => - request.kind === "user_input" && - request.status === "pending" && - request.responseCapability.type === "live", - ), - waitTimedOut, - } satisfies OrchestratorMcpDelegateTaskResult; - if ( - acknowledgeTerminal && - isTerminalTaskStatus(status) && - task.completionDelivery?.state !== "acknowledged" && - task.completionDelivery?.state !== "disposed" - ) { - const observingRun = ThreadManagementService.latestActiveRun(parentProjection); - const acknowledgementRequestKey = yield* requestKey(undefined); - yield* threadManagement - .dispatch({ - type: "delegated_task.completion-delivery.acknowledge", - commandId: stableCommandId({ - scope, - requestKey: acknowledgementRequestKey, - operation: acknowledgementOperation, - }), - parentThreadId: scope.thread.threadId, - taskId, - observedByRunId: - observingRun?.providerInstanceId === scope.thread.providerInstanceId - ? observingRun.id - : null, - }) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`, - ), + : latestTerminalResultContextTransferId, + hasPendingQuestion: + !isTerminalTaskStatus(status) && + childControls.runtimeRequests.some( + (request) => + request.kind === "user_input" && + request.status === "pending" && + request.responseCapability.type === "live", + ), + pendingApproval: + isTerminalTaskStatus(status) || task.completionDelivery?.state === "disposed" + ? null + : pendingTaskApproval(childControls, task.id, childRun), + waitTimedOut, + } satisfies OrchestratorMcpDelegateTaskResult; + const response: OrchestratorMcpDelegateTaskResult = + endsTaskWait(result) || task.completionDelivery?.state === "disposed" + ? result + : { ...result, next: ORCHESTRATOR_MCP_RUNNING_TASK_NEXT }; + if ( + acknowledgeTerminal && + isTerminalTaskStatus(status) && + task.completionDelivery?.state !== "acknowledged" && + task.completionDelivery?.state !== "disposed" + ) { + const observingRun = ThreadManagementService.latestActiveRun(parentProjection); + const acknowledgementRequestKey = yield* requestKey(undefined); + yield* threadManagement + .dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: stableCommandId({ + scope, + requestKey: acknowledgementRequestKey, + operation: acknowledgementOperation, + }), + parentThreadId: scope.thread.threadId, + taskId, + observedByRunId: + observingRun?.providerInstanceId === scope.thread.providerInstanceId + ? observingRun.id + : null, + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to acknowledge delegated task ${taskId}: ${errorMessage(error)}`, ), - ); - } - return response; - }); + ), + ); + } + return response; + }); - const waitForTask = (scope: McpThreadInvocationScope, taskId: NodeId, timeoutMs: number) => - Effect.gen(function* () { + const waitForTask = Effect.fn("OrchestratorMcpService.waitForTask")( + function* (scope: McpThreadInvocationScope, taskId: NodeId, _timeoutMs: number) { const streamError = (error: unknown) => failure( "orchestration_error", `Unable to watch delegated task ${taskId}: ${errorMessage(error)}`, ); - // Sequences are global, so one cursor taken before the first read - // replays anything either thread records after it. + // One global cursor before both reads captures later events from either thread. const afterSequence = yield* threadManagement .getThreadEventSequence(scope.thread.threadId) .pipe(Effect.mapError(streamError)); const initial = yield* readTask(scope, taskId, false, true); - if (initial.hasPendingQuestion || isTerminalTaskStatus(initial.status)) { + if (endsTaskWait(initial)) { return Option.some(initial); } // One stream per event type, so transcript events never fill a buffer. @@ -1521,20 +1701,24 @@ const make = Effect.gen(function* () { ).pipe( Stream.mapError(streamError), Stream.mapEffect(() => readTask(scope, taskId, false, true)), - Stream.filter((result) => result.hasPendingQuestion || isTerminalTaskStatus(result.status)), + Stream.filter(endsTaskWait), Stream.runHead, ); - }).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)); + }, + (effect, _scope, _taskId, timeoutMs) => + effect.pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)), + ); - const scheduledTaskRunModes = (task: ScheduledTask) => - Effect.gen(function* () { + const scheduledTaskRunModes = Effect.fn("OrchestratorMcpService.scheduledTaskRunModes")( + function* (task: ScheduledTask) { const modes = [{ runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }]; if (task.threadId === null) return modes; const bound = yield* threadManagement .getThreadShell(task.threadId) .pipe(Effect.mapError(threadManagementFailure)); return bound === null || bound.deletedAt !== null ? modes : [...modes, bound]; - }); + }, + ); const withinLimits = ( limits: { @@ -1551,18 +1735,18 @@ const make = Effect.gen(function* () { * approved for read-only access, and a thread caller only with a live turn, at modes covering * every mode the task runs at. */ - const summarizeScheduledTask = ( - scope: McpInvocationScope, - caller: { - readonly parent: Pick | undefined; - readonly limits: { - readonly runtimeMode: RuntimeMode; - readonly interactionMode: ProviderInteractionMode; - }; - }, - task: ScheduledTask, - ) => - Effect.gen(function* () { + const summarizeScheduledTask = Effect.fn("OrchestratorMcpService.summarizeScheduledTask")( + function* ( + scope: McpInvocationScope, + caller: { + readonly parent: Pick | undefined; + readonly limits: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }; + }, + task: ScheduledTask, + ) { const live = caller.parent === undefined ? scope.client?.access !== "read-only" @@ -1574,101 +1758,97 @@ const make = Effect.gen(function* () { Option.isSome(modes) && modes.value.every((mode) => withinLimits(caller.limits, mode)), ); - }); + }, + ); /** * A scheduled task the caller may change: one whose runs execute at modes no * broader than the caller's own, so editing its prompt cannot run work above * the caller's limits. */ - const loadScheduledTask = ( + const loadScheduledTask = Effect.fn("OrchestratorMcpService.loadScheduledTask")(function* ( scheduledTaskId: ScheduledTask["id"], limits: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode; }, - ): Effect.Effect => - Effect.gen(function* () { - const { tasks } = yield* scheduledTasks - .list() - .pipe( - Effect.mapError((error) => - failure("orchestration_error", `Could not load scheduled task: ${error.message}`), - ), - ); - const task = tasks.find((candidate) => candidate.id === scheduledTaskId); - if (task === undefined) { - return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); - } - for (const modes of yield* scheduledTaskRunModes(task)) { - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); - } - return task; - }); + ): Effect.fn.Return { + const { tasks } = yield* scheduledTasks + .list() + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not load scheduled task: ${error.message}`), + ), + ); + const task = tasks.find((candidate) => candidate.id === scheduledTaskId); + if (task === undefined) { + return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); + } + for (const modes of yield* scheduledTaskRunModes(task)) { + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); + } + return task; + }); return OrchestratorMcpService.of({ - scheduleTask: (scope, input) => - Effect.gen(function* () { - const { parent, limits } = yield* loadCaller(scope); - const projectId = yield* resolveProjectTarget(parent, input.projectId); - yield* assertLiveCallerForOtherProject(scope, parent, projectId); - const project = yield* requireProject(projectId); - const bindToCurrentThread = - input.bindToCurrentThread ?? - (parent !== undefined && parent.thread.projectId === projectId); - if ( - bindToCurrentThread && - (parent === undefined || parent.thread.projectId !== projectId) - ) { - return yield* failure( - "invalid_request", - parent === undefined - ? "bindToCurrentThread needs an agent running inside a T3 thread." - : "bindToCurrentThread binds to this thread, which belongs to a different project.", - ); - } - const modelSelection = - parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project)); - const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? ""; - const title = - input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task"); - const upsertInput: ScheduledTaskUpsertInput = { - title, - prompt: input.prompt, - enabled: input.enabled ?? true, - schedule: input.schedule, - projectId, - threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null, - workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread), - modelSelection, - runtimeMode: limits.runtimeMode, - interactionMode: limits.interactionMode, - createdBy: "agent", - creationSource: "mcp", - // Scope the idempotency key by provider session so two callers - // reusing the same clientRequestId cannot collide on one task row. - ...(input.clientRequestId === undefined - ? {} - : { - commandId: stableCommandId({ - scope, - requestKey: input.clientRequestId, - operation: "schedule-task", - }), + scheduleTask: Effect.fn("OrchestratorMcpService.scheduleTask")(function* (scope, input) { + const { parent, limits } = yield* loadCaller(scope); + const projectId = yield* resolveProjectTarget(parent, input.projectId); + yield* assertLiveCallerForOtherProject(scope, parent, projectId); + const project = yield* requireProject(projectId); + const bindToCurrentThread = + input.bindToCurrentThread ?? + (parent !== undefined && parent.thread.projectId === projectId); + if (bindToCurrentThread && (parent === undefined || parent.thread.projectId !== projectId)) { + return yield* failure( + "invalid_request", + parent === undefined + ? "bindToCurrentThread needs an agent running inside a T3 thread." + : "bindToCurrentThread binds to this thread, which belongs to a different project.", + ); + } + const modelSelection = + parent?.thread.modelSelection ?? (yield* projectDefaultModelSelection(project)); + const derivedTitle = input.prompt.split("\n")[0]?.trim() ?? ""; + const title = + input.title ?? (derivedTitle.length > 0 ? derivedTitle.slice(0, 80) : "Scheduled task"); + const upsertInput: ScheduledTaskUpsertInput = { + title, + prompt: input.prompt, + enabled: input.enabled ?? true, + schedule: input.schedule, + projectId, + threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null, + workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread), + modelSelection, + runtimeMode: limits.runtimeMode, + interactionMode: limits.interactionMode, + createdBy: "agent", + creationSource: "mcp", + // Scope the idempotency key by provider session so two callers + // reusing the same clientRequestId cannot collide on one task row. + ...(input.clientRequestId === undefined + ? {} + : { + commandId: stableCommandId({ + scope, + requestKey: input.clientRequestId, + operation: "schedule-task", }), - }; - const { task } = yield* scheduledTasks - .upsert(upsertInput) - .pipe( - Effect.mapError((error) => - failure("orchestration_error", `Could not schedule task: ${error.message}`), - ), - ); - return yield* summarizeScheduledTask(scope, { parent, limits }, task); - }), - listScheduledTasks: (scope, input) => - Effect.gen(function* () { + }), + }; + const { task } = yield* scheduledTasks + .upsert(upsertInput) + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not schedule task: ${error.message}`), + ), + ); + return yield* summarizeScheduledTask(scope, { parent, limits }, task); + }), + listScheduledTasks: Effect.fn("OrchestratorMcpService.listScheduledTasks")( + function* (scope, input) { const { parent, limits } = yield* loadCaller(scope); const projectId = input.projectId ?? parent?.thread.projectId; const { tasks } = yield* scheduledTasks @@ -1684,9 +1864,10 @@ const make = Effect.gen(function* () { (task) => summarizeScheduledTask(scope, { parent, limits }, task), ), }; - }), - updateScheduledTask: (scope, input) => - Effect.gen(function* () { + }, + ), + updateScheduledTask: Effect.fn("OrchestratorMcpService.updateScheduledTask")( + function* (scope, input) { const { parent, limits } = yield* loadCaller(scope); const existing = yield* loadScheduledTask(input.scheduledTaskId, limits); yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId); @@ -1707,9 +1888,7 @@ const make = Effect.gen(function* () { : input.bindToCurrentThread && parent !== undefined ? parent.thread.id : null; - // Rebinding changes where runs execute, so the workspace strategy must - // follow: unbinding a root-strategy task would otherwise run loose - // prompts in the shared project checkout. + // Update workspace strategy on rebinding so unbound root tasks cannot run in the shared checkout. const workspaceStrategy = input.bindToCurrentThread === undefined ? existing.workspaceStrategy @@ -1737,9 +1916,10 @@ const make = Effect.gen(function* () { ), ); return yield* summarizeScheduledTask(scope, { parent, limits }, task); - }), - deleteScheduledTask: (scope, input) => - Effect.gen(function* () { + }, + ), + deleteScheduledTask: Effect.fn("OrchestratorMcpService.deleteScheduledTask")( + function* (scope, input) { const { parent, limits } = yield* loadCaller(scope); const existing = yield* loadScheduledTask(input.scheduledTaskId, limits); yield* assertLiveCallerForOtherProject(scope, parent, existing.projectId); @@ -1751,516 +1931,586 @@ const make = Effect.gen(function* () { ), ); return { scheduledTaskId: existing.id, deleted: true }; - }), - requestSecret: (scope, input) => - Effect.gen(function* () { - const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret"); - const threadId = threadScope.thread.threadId; - const run = ThreadManagementService.latestActiveRun(parent); - if ( - run === undefined || - run.rootNodeId === null || - run.providerInstanceId !== threadScope.thread.providerInstanceId - ) { - return yield* failure( - "parent_not_active", - "Asking for a secret requires an active run owned by this MCP provider session.", - ); - } - const runId = run.id; - const nodeId = run.rootNodeId; - const key = yield* requestKey(input.clientRequestId); - const turnItemId = TurnItemId.make( - `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`, + }, + ), + requestSecret: Effect.fn("OrchestratorMcpService.requestSecret")(function* (scope, input) { + const { scope: threadScope, parent } = yield* loadThreadCaller(scope, "request_secret"); + const threadId = threadScope.thread.threadId; + const run = ThreadManagementService.latestActiveRun(parent); + if ( + run === undefined || + run.rootNodeId === null || + run.providerInstanceId !== threadScope.thread.providerInstanceId + ) { + return yield* failure( + "parent_not_active", + "Asking for a secret requires an active run owned by this MCP provider session.", ); - const record = (secretStatus: "pending" | "cancelled") => - threadManagement - .dispatch({ - type: "secret_request.record", - commandId: stableCommandId({ - scope, - requestKey: key, - operation: `secret-${secretStatus}`, - }), - threadId: threadId, - runId, - nodeId, - turnItemId, - label: input.label, - reason: input.reason, - ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }), - secretStatus, + } + const runId = run.id; + const nodeId = run.rootNodeId; + const key = yield* requestKey(input.clientRequestId); + const turnItemId = TurnItemId.make( + `turn-item:secret-request:${stablePart(threadId)}:${stablePart(key)}`, + ); + const record = (secretStatus: "pending" | "cancelled") => + threadManagement + .dispatch({ + type: "secret_request.record", + commandId: stableCommandId({ + scope, + requestKey: key, + operation: `secret-${secretStatus}`, + }), + threadId: threadId, + runId, + nodeId, + turnItemId, + label: input.label, + reason: input.reason, + ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }), + ...(input.delivery === "file" ? { delivery: "file" as const } : {}), + secretStatus, + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Could not record the secret request: ${errorMessage(error)}`, + ), + ), + ); + yield* record("pending"); + // Only this call can hand the agent its ref, so the card must not + // outlive it: a timeout, a failed wait or an aborted call closes it as + // cancelled. + const closeCard = record("cancelled").pipe( + Effect.catch((error) => + Effect.logWarning("Could not close a secret request card", { error: error.message }), + ), + ); + + const answered = yield* Effect.gen(function* () { + while (true) { + const projection = yield* threadManagement + .getThreadRecords(threadId, ["runs", "turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], }) .pipe( Effect.mapError((error) => failure( "orchestration_error", - `Could not record the secret request: ${errorMessage(error)}`, + `Unable to read the secret request: ${errorMessage(error)}`, ), ), ); - yield* record("pending"); - // Only this call can hand the agent its ref, so the card must not - // outlive it: a timeout, a failed wait or an aborted call closes it as - // cancelled. - const closeCard = record("cancelled").pipe( - Effect.catch((error) => - Effect.logWarning("Could not close a secret request card", { error: error.message }), - ), - ); - - const answered = yield* Effect.gen(function* () { - while (true) { - const projection = yield* threadManagement - .getThreadRecords(threadId, ["runs", "turnItems"], { - turnItemTypes: ["secret_request"], - messageRoles: [], - }) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to read the secret request: ${errorMessage(error)}`, - ), - ), - ); - const item = projection.turnItems.find((candidate) => candidate.id === turnItemId); - if (item?.type === "secret_request" && item.secretStatus !== "pending") { - return item.secretStatus; - } - const current = projection.runs.find((candidate) => candidate.id === runId); - if ( - current === undefined || - ThreadManagementService.isTerminalRunStatus(current.status) - ) { - yield* record("cancelled"); - return "cancelled" as const; - } - yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); + const item = projection.turnItems.find((candidate) => candidate.id === turnItemId); + if (item?.type === "secret_request" && item.secretStatus !== "pending") { + return item.secretStatus; } - }).pipe( - Effect.timeoutOption( - Duration.millis( - Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS), - ), + const current = projection.runs.find((candidate) => candidate.id === runId); + if ( + current === undefined || + ThreadManagementService.isTerminalRunStatus(current.status) + ) { + yield* record("cancelled"); + return "cancelled" as const; + } + yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); + } + }).pipe( + Effect.timeoutOption( + Duration.millis( + Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS), ), - Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)), + ), + Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)), + ); + if (Option.isNone(answered)) yield* closeCard; + const status = Option.isSome(answered) + ? answered.value + : yield* threadManagement + .getThreadRecords(threadId, ["turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], + }) + .pipe( + Effect.map((records) => { + const item = records.turnItems.find((candidate) => candidate.id === turnItemId); + return item?.type === "secret_request" && + (item.secretStatus === "saved" || item.secretStatus === "declined") + ? item.secretStatus + : ("timed_out" as const); + }), + Effect.orElseSucceed(() => "timed_out" as const), + ); + yield* Effect.annotateCurrentSpan({ "secret_request.status": status }); + yield* Metrics.increment(Metrics.secretRequestsTotal, { status }); + if (status !== "saved") return { status }; + if (input.delivery === "file") { + const file = yield* secretRequests + .saveToFile({ threadId, turnItemId }) + .pipe(Effect.mapError((error) => failure("orchestration_error", error.message))); + return { status, file }; + } + const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId }); + if (Option.isNone(secretRef)) { + return yield* failure( + "orchestration_error", + "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.", ); - if (Option.isNone(answered)) yield* closeCard; - const status = Option.isSome(answered) - ? answered.value - : yield* threadManagement - .getThreadRecords(threadId, ["turnItems"], { - turnItemTypes: ["secret_request"], - messageRoles: [], - }) - .pipe( - Effect.map((records) => { - const item = records.turnItems.find((candidate) => candidate.id === turnItemId); - return item?.type === "secret_request" && - (item.secretStatus === "saved" || item.secretStatus === "declined") - ? item.secretStatus - : ("timed_out" as const); - }), - Effect.orElseSucceed(() => "timed_out" as const), - ); - yield* Effect.annotateCurrentSpan({ "secret_request.status": status }); - yield* Metrics.increment(Metrics.secretRequestsTotal, { status }); - if (status !== "saved") return { status }; - const secretRef = yield* secretRequests.savedRef({ threadId: threadId, turnItemId }); - if (Option.isNone(secretRef)) { - return yield* failure( - "orchestration_error", - "The user saved the secret, but it could not be read. Ask again with a new clientRequestId.", - ); - } - return { status, secretRef: secretRef.value }; - }).pipe(Effect.withSpan("OrchestratorMcpService.requestSecret")), + } + return { status, secretRef: secretRef.value }; + }), - capabilities: (scope) => - Effect.gen(function* () { - const { parent, limits } = yield* loadCaller(scope); - const providers = yield* loadProviders; - const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds(); - const modelPreferences = yield* serverSettings.getSettings.pipe( - Effect.map((settings) => settings.providerModelPreferences ?? {}), - Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")), - ); - return { - parentThreadId: parent?.thread.id ?? null, - inheritedProviderInstanceId: parent?.thread.modelSelection.instanceId ?? null, - inheritedModel: parent?.thread.modelSelection.model ?? null, - runtimeMode: limits.runtimeMode, - interactionMode: limits.interactionMode, - providers: providers.map((provider) => { - const constraints = providerConstraints( - provider, - orchestrationCapableInstanceIds.has(provider.instanceId), - ); - return { - providerInstanceId: provider.instanceId, - driverKind: provider.driver, - displayName: provider?.displayName ?? null, - models: - provider?.models - .filter( - (model) => - model.isCustom || - !modelPreferences[provider.instanceId]?.hiddenModels.includes(model.slug), - ) - .map((model) => ({ - id: model.slug, - label: model.name ?? null, - ...(model.capabilities?.optionDescriptors === undefined - ? {} - : { options: model.capabilities.optionDescriptors }), - })) ?? [], - ...(provider.supportedRuntimeModes === undefined || - provider.supportedRuntimeModes.length === 0 - ? {} - : { runtimeModes: [...provider.supportedRuntimeModes] }), - canRunChildTask: constraints.length === 0, - canRunCrossProviderChildTask: constraints.length === 0, - constraints: [...constraints], - }; - }), - features: { - appOwnedSubagents: true, - asyncPolling: true, - cancellation: true, - batchThreadCreation: true, - threadManagement: true, - incrementalThreadRead: true, - scheduledTasks: true, - maxBatchThreads: 20, - }, - }; - }), - delegateTask: (callerScope, input) => - Effect.gen(function* () { - const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); - const parentRun = parent.runs - .filter(ThreadManagementService.isActiveRun) - .toSorted((left, right) => right.ordinal - left.ordinal)[0]; - if ( - parentRun === undefined || - parentRun.rootNodeId === null || - parentRun.providerInstanceId !== scope.thread.providerInstanceId - ) { - return yield* failure( - "parent_not_active", - "Delegated tasks require an active run owned by this MCP provider session.", + capabilities: Effect.fn("OrchestratorMcpService.capabilities")(function* (scope, input = {}) { + const { parent, limits } = yield* loadCaller(scope); + const providers = yield* loadProviders; + const orchestrationCapableInstanceIds = yield* loadOrchestrationCapableInstanceIds(); + const settings = yield* serverSettings.getSettings.pipe( + Effect.mapError(() => failure("orchestration_error", "Unable to read server settings.")), + ); + const inherited = parent?.thread.modelSelection; + const searchTerms = input.search?.toLowerCase().split(/\s+/) ?? []; + return { + parentThreadId: parent?.thread.id ?? null, + inheritedProviderInstanceId: inherited?.instanceId ?? null, + inheritedModel: inherited?.model ?? null, + inheritedOptions: inherited?.options ?? [], + runtimeMode: limits.runtimeMode, + interactionMode: limits.interactionMode, + providers: providers.map((provider) => { + const constraints = providerConstraints( + provider, + orchestrationCapableInstanceIds.has(provider.instanceId), ); - } - const providers = yield* loadProviders; - const key = yield* requestKey(input.clientRequestId); - const commandId = stableCommandId({ - scope, - requestKey: key, - operation: "delegate-task", - }); - const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId); - const target = yield* resolveTargetRechecking({ - parent, - target: input.target, - providers, - skipProjectEnablementFilter: isRetryOfAcceptedDelegation, - }); - const runtimeMode = yield* resolveRuntimeMode( - parent.thread.runtimeMode, - input.runtimeMode, - target, - ); - const interactionMode = yield* resolveInteractionMode( - parent.thread.interactionMode, - input.interactionMode, + const { listed, omitted } = listCapabilityModels({ + provider, + preferences: settings.providerModelPreferences?.[provider.instanceId], + searchTerms, + isPinned: (model) => + model.isCustom || + (inherited?.instanceId === provider.instanceId && inherited.model === model.slug) || + (settings.favorites ?? []).some( + (favorite) => + favorite.provider === provider.instanceId && favorite.model === model.slug, + ), + }); + return { + providerInstanceId: provider.instanceId, + driverKind: provider.driver, + displayName: provider.displayName ?? null, + models: listed.map((model) => { + const options = model.capabilities?.optionDescriptors ?? []; + return { + id: model.slug, + ...(model.name.toLowerCase() === model.slug.toLowerCase() + ? {} + : { label: model.name }), + ...(options.length === 0 ? {} : { options: options.map(capabilityModelOption) }), + }; + }), + ...(omitted === 0 ? {} : { omittedModels: omitted }), + ...(provider.supportedRuntimeModes === undefined || + provider.supportedRuntimeModes.length === 0 + ? {} + : { runtimeModes: [...provider.supportedRuntimeModes] }), + canRunChildTask: constraints.length === 0, + canRunCrossProviderChildTask: constraints.length === 0, + constraints: [...constraints], + }; + }), + features: { + appOwnedSubagents: true, + asyncPolling: true, + cancellation: true, + batchThreadCreation: true, + threadManagement: true, + incrementalThreadRead: true, + scheduledTasks: true, + maxBatchThreads: 20, + }, + }; + }), + delegateTask: Effect.fn("OrchestratorMcpService.delegateTask")(function* (callerScope, input) { + const { scope, parent } = yield* loadThreadCaller(callerScope, "delegate_task"); + const parentRun = parent.runs + .filter(ThreadManagementService.isActiveRun) + .toSorted((left, right) => right.ordinal - left.ordinal)[0]; + if ( + parentRun === undefined || + parentRun.rootNodeId === null || + parentRun.providerInstanceId !== scope.thread.providerInstanceId + ) { + return yield* failure( + "parent_not_active", + "Delegated tasks require an active run owned by this MCP provider session.", ); - let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; - if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) { - const project = yield* requireProject(parent.thread.projectId); - const base = yield* gitDriver - .resolveCommit({ - cwd: parent.thread.worktreePath ?? project.workspaceRoot, - revision: "HEAD", - }) + } + const providers = yield* loadProviders; + const key = yield* requestKey(input.clientRequestId); + const commandId = stableCommandId({ + scope, + requestKey: key, + operation: "delegate-task", + }); + const isRetryOfAcceptedDelegation = yield* threadManagement.hasReceipt(commandId); + const target = yield* resolveTargetRechecking({ + parent, + target: input.target, + providers, + skipProjectEnablementFilter: isRetryOfAcceptedDelegation, + }); + const runtimeMode = yield* resolveRuntimeMode( + parent.thread.runtimeMode, + input.runtimeMode, + target, + ); + const interactionMode = yield* resolveInteractionMode( + parent.thread.interactionMode, + input.interactionMode, + ); + let workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy | undefined; + if (input.isolation === "worktree" && !isRetryOfAcceptedDelegation) { + const project = yield* requireProject(parent.thread.projectId); + const base = yield* gitDriver + .resolveCommit({ + cwd: parent.thread.worktreePath ?? project.workspaceRoot, + revision: "HEAD", + }) + .pipe( + Effect.mapError(() => + failure("invalid_request", "Unable to resolve the parent checkout commit."), + ), + ); + // Launch preparation creates the worktree from the project root, so a + // parent checkout in another repository (such as a Git folder inside + // Scratch) would hand it a commit it cannot find. + if (parent.thread.worktreePath !== null) { + yield* gitDriver + .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha }) .pipe( Effect.mapError(() => - failure("invalid_request", "Unable to resolve the parent checkout commit."), + failure( + "invalid_request", + `Isolation "worktree" creates the child checkout in project "${project.title}" (${project.workspaceRoot}), which does not contain the parent checkout's commit. Use isolation "shared" to work in the parent's checkout.`, + ), ), ); - // Launch preparation creates the worktree from the project root, so a - // parent checkout in another repository (such as a Git folder inside - // Scratch) would hand it a commit it cannot find. - if (parent.thread.worktreePath !== null) { - yield* gitDriver - .resolveCommit({ cwd: project.workspaceRoot, revision: base.commitSha }) + } + workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false }; + } + // ThreadManagementService.dispatch is the chokepoint for this command + // type's own enablement check, using the same command id and its + // receipt-replay exemption, so no separate assert runs here. + const result = yield* threadManagement + .dispatch({ + type: "delegated_task.request", + createdBy: "agent", + creationSource: "mcp", + commandId, + parentThreadId: scope.thread.threadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId, + task: taskPrompt(input), + ...(input.title === undefined ? {} : { title: input.title }), + modelSelection: target.modelSelection, + runtimeMode, + interactionMode, + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), + // Async delegations wake the parent on every child terminal; wait + // delegations deliver through the blocking tool call, so a wake is + // only needed if the parent settled first (timeout, disconnect). + completionWake: input.mode === "wait" ? "settled_only" : "always", + }) + .pipe( + Effect.mapError((error) => + error._tag === "ThreadManagementProviderInstanceDisabledError" + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to create delegated task: ${errorMessage(error)}`, + ), + ), + ); + const taskEvent = result.storedEvents.find( + (stored) => + stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned", + ); + if (taskEvent?.event.type !== "subagent.updated") { + return yield* failure( + "orchestration_error", + "Delegated task command did not produce a task projection.", + ); + } + const taskId = taskEvent.event.payload.id; + const childThreadId = taskEvent.event.payload.childThreadId; + const childRunEvent = result.storedEvents.find( + (stored) => stored.event.type === "run.created" && stored.event.threadId === childThreadId, + ); + if ( + childThreadId !== null && + childRunEvent?.event.type === "run.created" && + childRunEvent.event.payload.workspacePreparation !== undefined + ) { + yield* threadLaunch.prepareRun({ + commandId, + threadId: childThreadId, + runId: childRunEvent.event.payload.id, + }); + } + + if (input.mode !== "wait") { + return yield* readTask(scope, taskId, false, true); + } + const timeoutMs = Math.min( + MAX_WAIT_TIMEOUT_MS, + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + ); + const waited = yield* waitForTask(scope, taskId, timeoutMs); + if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) { + return waited.value; + } + // An incomplete wait gives up delivery: upgrade so a later terminal + // wakes the parent even mid-turn. + yield* threadManagement + .dispatch({ + type: "delegated_task.wake-policy", + commandId: stableCommandId({ + scope, + requestKey: key, + operation: "delegate-task-wake-policy", + }), + parentThreadId: scope.thread.threadId, + taskId, + completionWake: "always", + }) + .pipe( + Effect.catch((error) => + Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", { + taskId, + outcome: + error._tag === "OrchestratorCommandPreviouslyRejectedError" + ? "previously_rejected" + : "dispatch_failed", + error, + }), + ), + Effect.catchCause((cause) => + Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", { + taskId, + outcome: "defect", + cause, + }), + ), + ); + return yield* readTask(scope, taskId, Option.isNone(waited), true); + }), + taskStatus: Effect.fn("OrchestratorMcpService.taskStatus")(function* (callerScope, taskId) { + const scope = yield* requireThreadScope(callerScope, "task_status"); + return yield* readTask(scope, taskId, false, true); + }), + cancelTask: Effect.fn("OrchestratorMcpService.cancelTask")(function* (callerScope, input) { + const scope = yield* requireThreadScope(callerScope, "task_cancel"); + const current = yield* readTask(scope, input.taskId); + const key = yield* requestKey(input.clientRequestId); + const parentProjection = yield* loadProjection(scope.thread.threadId); + // Cancelling stops the child and every task under it, each a write to a + // thread its user may have raised above the parent's modes since it was + // delegated. All of them are checked before anything is stopped. + const assertStoppable = Effect.fn("OrchestratorMcpService.assertStoppable")(function* ( + threadId: ThreadId, + ): Effect.fn.Return { + const shell = yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(threadManagementFailure)); + if (shell !== null && shell.deletedAt === null) { + yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode); + yield* resolveInteractionMode( + parentProjection.thread.interactionMode, + shell.interactionMode, + ); + } + const { subagents } = yield* threadManagement + .getThreadRecords(threadId, ["subagents"]) + .pipe(Effect.mapError(threadManagementFailure)); + for (const task of subagents) { + if (task.origin === "app_owned" && task.childThreadId !== null) { + yield* assertStoppable(task.childThreadId); + } + } + }); + yield* assertStoppable(current.childThreadId); + const parentTask = parentProjection.subagents.find( + (task) => task.id === input.taskId && task.origin === "app_owned", + ); + const disposeCompletionDelivery = + parentTask?.completionDelivery?.state === "disposed" + ? Effect.void + : threadManagement + .dispatch({ + type: "delegated_task.completion-delivery.dispose", + commandId: stableCommandId({ + scope, + requestKey: key, + operation: "cancel-task-completion-delivery", + }), + parentThreadId: scope.thread.threadId, + taskId: input.taskId, + }) .pipe( - Effect.mapError(() => + Effect.asVoid, + Effect.mapError((error) => failure( - "invalid_request", - `Isolation "worktree" creates the child checkout in project "${project.title}" (${project.workspaceRoot}), which does not contain the parent checkout's commit. Use isolation "shared" to work in the parent's checkout.`, + "orchestration_error", + `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`, ), ), ); - } - workspaceStrategy = { type: "worktree", baseRef: base.commitSha, startFromOrigin: false }; - } - // ThreadManagementService.dispatch is the chokepoint for this command - // type's own enablement check, using the same command id and its - // receipt-replay exemption, so no separate assert runs here. - const result = yield* threadManagement + const stopChild = Effect.gen(function* () { + const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" }); + const reason = agentStopReason(input.reason); + yield* threadManagement .dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", + type: "thread.stop", commandId, - parentThreadId: scope.thread.threadId, - parentRunId: parentRun.id, - parentNodeId: parentRun.rootNodeId, - task: taskPrompt(input), - ...(input.title === undefined ? {} : { title: input.title }), - modelSelection: target.modelSelection, - runtimeMode, - interactionMode, - ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), - // Async delegations wake the parent on every child terminal; wait - // delegations deliver through the blocking tool call, so a wake is - // only needed if the parent settled first (timeout, disconnect). - completionWake: input.mode === "wait" ? "settled_only" : "always", + threadId: current.childThreadId, + stopDelegatedTasks: false, + reason, }) .pipe( Effect.mapError((error) => - error._tag === "ThreadManagementProviderInstanceDisabledError" - ? threadManagementFailure(error) - : failure( - "orchestration_error", - `Unable to create delegated task: ${errorMessage(error)}`, - ), + failure( + "task_not_cancellable", + `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`, + ), ), ); - const taskEvent = result.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && stored.event.payload.origin === "app_owned", - ); - if (taskEvent?.event.type !== "subagent.updated") { - return yield* failure( - "orchestration_error", - "Delegated task command did not produce a task projection.", - ); - } - const taskId = taskEvent.event.payload.id; - const childThreadId = taskEvent.event.payload.childThreadId; - const childRunEvent = result.storedEvents.find( - (stored) => - stored.event.type === "run.created" && stored.event.threadId === childThreadId, - ); - if ( - childThreadId !== null && - childRunEvent?.event.type === "run.created" && - childRunEvent.event.payload.workspacePreparation !== undefined - ) { - yield* threadLaunch.prepareRun({ - commandId, - threadId: childThreadId, - runId: childRunEvent.event.payload.id, - }); - } - - if (input.mode !== "wait") { - return yield* readTask(scope, taskId, false, true); - } - const timeoutMs = Math.min( - MAX_WAIT_TIMEOUT_MS, - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), - ); - const waited = yield* waitForTask(scope, taskId, timeoutMs); - if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) { - return waited.value; - } - // An incomplete wait gives up delivery: upgrade so a later terminal - // wakes the parent even mid-turn. yield* threadManagement - .dispatch({ - type: "delegated_task.wake-policy", - commandId: stableCommandId({ - scope, - requestKey: key, - operation: "delegate-task-wake-policy", - }), - parentThreadId: scope.thread.threadId, - taskId, - completionWake: "always", - }) + .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason }) .pipe( - Effect.catch((error) => - Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", { - taskId, - outcome: - error._tag === "OrchestratorCommandPreviouslyRejectedError" - ? "previously_rejected" - : "dispatch_failed", - error, - }), - ), - Effect.catchCause((cause) => - Effect.logWarning("orchestrator-mcp.delegate-task.wake-policy-failed", { - taskId, - outcome: "defect", - cause, - }), + Effect.mapError((error) => + failure( + "task_not_cancellable", + `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`, + ), ), ); - return yield* readTask(scope, taskId, Option.isNone(waited), true); - }), - taskStatus: (callerScope, taskId) => - Effect.gen(function* () { - const scope = yield* requireThreadScope(callerScope, "task_status"); - return yield* readTask(scope, taskId, false, true); - }), - cancelTask: (callerScope, input) => - Effect.gen(function* () { - const scope = yield* requireThreadScope(callerScope, "task_cancel"); - const current = yield* readTask(scope, input.taskId); - const key = yield* requestKey(input.clientRequestId); - const parentProjection = yield* loadProjection(scope.thread.threadId); - // Cancelling stops the child and every task under it, each a write to a - // thread its user may have raised above the parent's modes since it was - // delegated. All of them are checked before anything is stopped. - const assertStoppable = (threadId: ThreadId): Effect.Effect => - Effect.gen(function* () { - const shell = yield* threadManagement - .getThreadShell(threadId) - .pipe(Effect.mapError(threadManagementFailure)); - if (shell !== null && shell.deletedAt === null) { - yield* resolveRuntimeMode(parentProjection.thread.runtimeMode, shell.runtimeMode); - yield* resolveInteractionMode( - parentProjection.thread.interactionMode, - shell.interactionMode, - ); - } - const { subagents } = yield* threadManagement - .getThreadRecords(threadId, ["subagents"]) - .pipe(Effect.mapError(threadManagementFailure)); - for (const task of subagents) { - if (task.origin === "app_owned" && task.childThreadId !== null) { - yield* assertStoppable(task.childThreadId); - } - } - }); - yield* assertStoppable(current.childThreadId); - const parentTask = parentProjection.subagents.find( - (task) => task.id === input.taskId && task.origin === "app_owned", - ); - const disposeCompletionDelivery = - parentTask?.completionDelivery?.state === "disposed" - ? Effect.void - : threadManagement - .dispatch({ - type: "delegated_task.completion-delivery.dispose", - commandId: stableCommandId({ - scope, - requestKey: key, - operation: "cancel-task-completion-delivery", - }), - parentThreadId: scope.thread.threadId, - taskId: input.taskId, - }) - .pipe( - Effect.asVoid, - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to dispose delegated task ${input.taskId} completion delivery: ${errorMessage(error)}`, - ), - ), - ); - const stopChild = Effect.gen(function* () { - const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" }); - const reason = input.reason; + const stopped = yield* threadManagement + .getThreadRecords(current.childThreadId, ["runs"]) + .pipe(Effect.mapError(threadManagementFailure)); + for (const run of stopped.runs) { + if ( + run.status !== "queued" || + (run.delegatedTaskId !== input.taskId && run.id !== current.childRunId) + ) + continue; + // Stop preserves the queue for Resume. Cancelling a task must also + // remove that task's queued turn, including a previously held one. yield* threadManagement .dispatch({ - type: "thread.stop", - commandId, + type: "queued-run.cancel", + commandId: stableCommandId({ + scope, + requestKey: key, + operation: `cancel-task-queued-run:${run.id}`, + }), threadId: current.childThreadId, - ...(reason === undefined ? {} : { reason }), + runId: run.id, }) - .pipe( - Effect.mapError((error) => - failure( - "task_not_cancellable", - `Unable to stop delegated task ${input.taskId}: ${errorMessage(error)}`, - ), - ), - ); - yield* threadManagement - .stopDelegatedTasks({ threadId: current.childThreadId, commandId, reason }) - .pipe( - Effect.mapError((error) => - failure( - "task_not_cancellable", - `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`, - ), - ), - ); - }); - // Checked above; a user raising one of these threads meanwhile is - // caught again under that thread's lock, which leaves it running. - const refused = yield* Ref.make(undefined); - const stopWithinLimit = stopChild.pipe( - Effect.provideService(DispatchModeLimit, { - runtimeMode: parentProjection.thread.runtimeMode, - interactionMode: parentProjection.thread.interactionMode, - refused, - }), - Effect.catch((error) => - Effect.flatMap(Ref.get(refused), (refusal) => - Effect.fail( - refusal === undefined - ? error - : failure( - refusal.mode === "runtime" - ? "runtime_mode_escalation_denied" - : "interaction_mode_escalation_denied", - `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this thread's; its user changed it while the task was being cancelled.`, - ), - ), + .pipe(Effect.mapError(threadManagementFailure)); + } + }); + // Checked above; a user raising one of these threads meanwhile is + // caught again under that thread's lock, which leaves it running. + const refused = yield* Ref.make(undefined); + const stopWithinLimit = stopChild.pipe( + Effect.provideService(DispatchModeLimit, { + runtimeMode: parentProjection.thread.runtimeMode, + interactionMode: parentProjection.thread.interactionMode, + refused, + }), + Effect.catch((error) => + Effect.flatMap(Ref.get(refused), (refusal) => + Effect.fail( + refusal === undefined + ? error + : failure( + refusal.mode === "runtime" + ? "runtime_mode_escalation_denied" + : "interaction_mode_escalation_denied", + `Thread ${refusal.threadId} now runs in ${refusal.runtimeMode}/${refusal.interactionMode} mode, above this thread's; its user changed it while the task was being cancelled.`, + ), ), ), - ); - if (isTerminalTaskStatus(current.status)) { - yield* stopWithinLimit; - yield* disposeCompletionDelivery; - return { - taskId: input.taskId, - status: current.status, - } satisfies OrchestratorMcpTaskCancelResult; - } - const child = yield* loadProjection(current.childThreadId); - if ( - current.workState !== "waiting_for_children" && - ThreadManagementService.latestActiveRun(child) === undefined - ) { - return yield* failure( - "task_not_cancellable", - `Delegated task ${input.taskId} has no interruptible child run.`, - ); - } - yield* stopWithinLimit; - yield* disposeCompletionDelivery.pipe( - Effect.catchCause((cause) => - Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", { - taskId: input.taskId, - cause, + ), + ); + // A follow-up that lost its child run stays running on the parent, while its + // status here comes from the child's last run. Stop on the parent cancels that task. + const cancelOrphan = Effect.gen(function* () { + if (parentTask?.runId == null || !isOrchestrationV2WorkActive(parentTask.status)) + return false; + yield* threadManagement + .dispatch({ + type: "subagent.stop", + commandId: stableCommandId({ + scope, + requestKey: key, + operation: "cancel-task-orphan", }), - ), - ); + threadId: scope.thread.threadId, + runId: parentTask.runId, + subagentId: parentTask.id, + }) + .pipe(Effect.mapError(threadManagementFailure)); + const { subagents } = yield* threadManagement + .getThreadRecords(scope.thread.threadId, ["subagents"]) + .pipe(Effect.mapError(threadManagementFailure)); + return subagents.some((task) => task.id === input.taskId && task.status === "cancelled"); + }); + if (isTerminalTaskStatus(current.status)) { + // The child can still run work for another turn, so it is stopped either way. + yield* stopWithinLimit; + const cancelled = yield* cancelOrphan; + yield* disposeCompletionDelivery; return { taskId: input.taskId, - status: "cancel_requested", - }; - }), - createThreads: (callerScope, input) => - Effect.gen(function* () { + status: cancelled ? "cancelled" : current.status, + } satisfies OrchestratorMcpTaskCancelResult; + } + const child = yield* loadProjection(current.childThreadId); + if ( + current.workState !== "waiting_for_children" && + ThreadManagementService.latestActiveRun(child) === undefined && + !child.runs.some( + (run) => + run.status === "queued" && + (run.delegatedTaskId === input.taskId || run.id === current.childRunId), + ) + ) { + if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" }; + return yield* failure( + "task_not_cancellable", + `Delegated task ${input.taskId} has no interruptible child run.`, + ); + } + yield* stopWithinLimit; + yield* disposeCompletionDelivery.pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestrator-mcp.cancel-task.delivery-dispose-failed", { + taskId: input.taskId, + cause, + }), + ), + ); + return { + taskId: input.taskId, + status: "cancel_requested", + }; + }), + createThreads: Effect.fn("OrchestratorMcpService.createThreads")( + function* (callerScope, input) { const { scope, parent } = yield* loadThreadCaller(callerScope, "create_threads"); const parentRun = ThreadManagementService.latestActiveRun(parent); if ( @@ -2280,10 +2530,34 @@ const make = Effect.gen(function* () { input.threads, (request, index) => Effect.gen(function* () { + const commandId = stableCommandId({ + scope, + requestKey: key, + operation: "create-thread", + index, + }); + const threadId = stableThreadId({ + scope, + requestKey: key, + index, + }); + const isRetryOfAcceptedCreation = yield* threadManagement.hasReceipt(commandId); + const committedThread = isRetryOfAcceptedCreation + ? yield* threadManagement + .getThreadShell(threadId) + .pipe(Effect.mapError(threadManagementFailure)) + : null; const target = yield* resolveTargetRechecking({ parent, - target: request.target, + target: + committedThread === null + ? request.target + : { + ...request.target, + providerInstanceId: committedThread.modelSelection.instanceId, + }, providers, + skipProjectEnablementFilter: isRetryOfAcceptedCreation, }); const runtimeMode = yield* resolveRuntimeMode( parent.thread.runtimeMode, @@ -2294,16 +2568,7 @@ const make = Effect.gen(function* () { parent.thread.interactionMode, request.interactionMode, ); - const threadId = stableThreadId({ - scope, - requestKey: key, - index, - }); - yield* assertTargetEnabledForProject( - parent, - stableCommandId({ scope, requestKey: key, operation: "create-thread", index }), - target, - ); + yield* assertTargetEnabledForProject(parent, commandId, target); const title = threadTitle({ parentTitle: parent.thread.title, prompt: request.prompt, @@ -2315,12 +2580,7 @@ const make = Effect.gen(function* () { type: "thread.create", createdBy: "agent", creationSource: "mcp", - commandId: stableCommandId({ - scope, - requestKey: key, - operation: "create-thread", - index, - }), + commandId, threadId, projectId: parent.thread.projectId, title, @@ -2338,6 +2598,10 @@ const make = Effect.gen(function* () { ), ), ); + // A receipt can appear after target resolution; use the committed thread's selection. + const resolvedModelSelection = (yield* threadManagement + .getThreadRecords(threadId, []) + .pipe(Effect.mapError(threadManagementFailure))).thread.modelSelection; if (request.prompt !== undefined) { yield* threadManagement .dispatch({ @@ -2359,15 +2623,17 @@ const make = Effect.gen(function* () { }), text: request.prompt, attachments: [], - modelSelection: target.modelSelection, + modelSelection: resolvedModelSelection, dispatchMode: { type: "start_immediately" }, }) .pipe( Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to start thread ${index + 1}: ${errorMessage(error)}`, - ), + error._tag === "ThreadManagementProviderInstanceDisabledError" + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to start thread ${index + 1}: ${errorMessage(error)}`, + ), ), ); } @@ -2398,275 +2664,289 @@ const make = Effect.gen(function* () { ); return { threadId, + link: formatThreadLink(threadId, projection.thread.title), runId: run?.id ?? null, status: run?.status ?? "idle", title: projection.thread.title, createdBy: projection.thread.createdBy, creationSource: projection.thread.creationSource, - providerInstanceId: target.modelSelection.instanceId, - model: target.modelSelection.model, + providerInstanceId: resolvedModelSelection.instanceId, + model: resolvedModelSelection.model, } satisfies OrchestratorMcpCreatedThread; }), { concurrency: 1 }, ); return { threads: created }; - }), - listThreads: (scope, input) => - Effect.gen(function* () { - const { parent } = yield* loadCaller(scope); - const projectId = yield* resolveProjectTarget(parent, input.projectId); - const projectThreads = yield* threadManagement - .listProjectThreads({ - projectId, - includeSubagents: input.includeSubagents !== false, - }) - .pipe( - Effect.mapError((error) => - failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`), - ), - ); - const nowMs = yield* Clock.currentTimeMillis; - const statuses = input.statuses === undefined ? null : new Set(input.statuses); - const titleContains = input.titleContains?.toLocaleLowerCase(); - const filtered = projectThreads - .filter( - (thread) => - statuses === null || statuses.has(thread.activityRunStatus ?? thread.status), - ) - .filter( - (thread) => - input.settled === undefined || threadSettlement(thread).settled === input.settled, - ) - .filter( - (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed, - ) - .filter( - (thread) => - titleContains === undefined || - thread.title.toLocaleLowerCase().includes(titleContains), - ); - const cursor = input.cursor ?? 0; - const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT; - const page = filtered.slice(cursor, cursor + limit); - const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null; - return { + }, + ), + listThreads: Effect.fn("OrchestratorMcpService.listThreads")(function* (scope, input) { + const { parent } = yield* loadCaller(scope); + const projectId = yield* resolveProjectTarget(parent, input.projectId); + const projectThreads = yield* threadManagement + .listProjectThreads({ projectId, - currentThreadId: parent?.thread.id ?? null, - threads: page.map((shell) => listItemFromShell(shell, nowMs)), - nextCursor, - total: filtered.length, - } satisfies OrchestratorMcpThreadListResult; - }), - readThread: (scope, input) => - Effect.gen(function* () { - const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId); - const view = input.view ?? "messages"; - const afterPosition = input.afterPosition ?? -1; - const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT; - const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS; - const timeline = yield* threadManagement - .getTimelinePage(input.threadId, { - afterPosition, - limit, - view, - ...(input.itemId === undefined ? {} : { itemId: input.itemId }), - }) - .pipe(Effect.mapError(threadManagementFailure)); - const page = timeline.items; - const messageIdsByThread = new Map>(); - for (const row of page) { - if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue; - const ids = messageIdsByThread.get(row.sourceThreadId) ?? []; - ids.push(row.item.messageId); - messageIdsByThread.set(row.sourceThreadId, ids); - } - const sourceMessages = yield* Effect.forEach( - [...messageIdsByThread], - ([threadId, messageIds]) => - threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe( - Effect.map((records) => [threadId, records.messages] as const), - Effect.mapError(threadManagementFailure), - ), - { concurrency: 1 }, + includeSubagents: input.includeSubagents !== false, + }) + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Unable to list threads: ${errorMessage(error)}`), + ), ); - const messagesByThreadId = new Map(sourceMessages); - const returnedRunIds = new Set( - page - .filter((row) => row.sourceThreadId === target.thread.id) - .map((row) => row.item.runId), + const nowMs = yield* Clock.currentTimeMillis; + const statuses = input.statuses === undefined ? null : new Set(input.statuses); + const titleContains = input.titleContains?.toLocaleLowerCase(); + const filtered = projectThreads + .filter( + (thread) => statuses === null || statuses.has(thread.activityRunStatus ?? thread.status), + ) + .filter( + (thread) => + input.settled === undefined || threadSettlement(thread).settled === input.settled, + ) + .filter( + (thread) => input.snoozed === undefined || isSnoozed(thread, nowMs) === input.snoozed, + ) + .filter( + (thread) => + titleContains === undefined || thread.title.toLocaleLowerCase().includes(titleContains), ); - const tasks = - parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds); - if ( - parent !== undefined && - scope.thread !== undefined && - tasks.length > 0 && - (input.textOffset ?? 0) === 0 - ) { - for (const task of tasks) { - const transfer = taskResultTransfer(parent, target, task); - const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id; - const resultRunIds = resultRunId === undefined ? [] : [resultRunId]; - const resultRecords = yield* threadManagement - .getThreadRecords(target.thread.id, ["messages", "turnItems"], { - messageRoles: ["assistant"], - messageRunIds: resultRunIds, - turnItemRunIds: resultRunIds, - turnItemTypes: ["assistant_message", "error"], - }) - .pipe(Effect.mapError(threadManagementFailure)); - if ( - pageIncludesTerminalTaskResult({ - parent, - page, - task, - target: { ...target, ...resultRecords }, - maxChars, - }) - ) { - yield* readTask( - scope as McpThreadInvocationScope, - task.id, - false, - true, - "thread-read-acknowledge", - ); - } + const cursor = input.cursor ?? 0; + const limit = input.limit ?? DEFAULT_THREAD_LIST_LIMIT; + const page = filtered.slice(cursor, cursor + limit); + const nextCursor = cursor + page.length < filtered.length ? cursor + page.length : null; + return { + projectId, + currentThreadId: parent?.thread.id ?? null, + threads: page.map((shell) => listItemFromShell(shell, nowMs)), + nextCursor, + total: filtered.length, + } satisfies OrchestratorMcpThreadListResult; + }), + readThread: Effect.fn("OrchestratorMcpService.readThread")(function* (scope, input) { + const { parent, target, shell } = yield* loadReadableThread(scope, input.threadId); + const view = input.view ?? "messages"; + const afterPosition = input.afterPosition ?? -1; + const limit = input.limit ?? DEFAULT_THREAD_READ_LIMIT; + const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS; + const timeline = yield* threadManagement + .getTimelinePage(input.threadId, { + afterPosition, + limit, + view, + ...(input.itemId === undefined ? {} : { itemId: input.itemId }), + }) + .pipe(Effect.mapError(threadManagementFailure)); + const page = timeline.items; + const messageIdsByThread = new Map>(); + for (const row of page) { + if (row.item.type !== "user_message" && row.item.type !== "assistant_message") continue; + const ids = messageIdsByThread.get(row.sourceThreadId) ?? []; + ids.push(row.item.messageId); + messageIdsByThread.set(row.sourceThreadId, ids); + } + const sourceMessages = yield* Effect.forEach( + [...messageIdsByThread], + ([threadId, messageIds]) => + threadManagement.getThreadRecords(threadId, ["messages"], { messageIds }).pipe( + Effect.map((records) => [threadId, records.messages] as const), + Effect.mapError(threadManagementFailure), + ), + { concurrency: 1 }, + ); + const messagesByThreadId = new Map(sourceMessages); + const returnedRunIds = new Set( + page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId), + ); + const tasks = + parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds); + if ( + parent !== undefined && + scope.thread !== undefined && + tasks.length > 0 && + (input.textOffset ?? 0) === 0 + ) { + for (const task of tasks) { + const transfer = taskResultTransfer(parent, target, task); + const resultRunId = transfer?.sourcePoint.runId ?? delegatedTaskRun(target, task)?.id; + const resultRunIds = resultRunId === undefined ? [] : [resultRunId]; + const resultRecords = yield* threadManagement + .getThreadRecords(target.thread.id, ["messages", "turnItems"], { + messageRoles: ["assistant"], + messageRunIds: resultRunIds, + turnItemRunIds: resultRunIds, + turnItemTypes: ["assistant_message", "error"], + }) + .pipe(Effect.mapError(threadManagementFailure)); + if ( + pageIncludesTerminalTaskResult({ + parent, + page, + task, + target: { ...target, ...resultRecords }, + maxChars, + }) + ) { + yield* readTask( + scope as McpThreadInvocationScope, + task.id, + false, + true, + "thread-read-acknowledge", + ); } } - return { - thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis), - recentRuns: target.runs - .toSorted((left, right) => right.ordinal - left.ordinal) - .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT) - .map(threadRun), - items: page.map((row) => - timelineItem({ - row, - maxChars, - messagesByThreadId, - ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }), - }), - ), - nextPosition: page.at(-1)?.position ?? null, - hasMore: timeline.hasMore, - } satisfies OrchestratorMcpThreadReadResult; - }), - sendToThread: (scope, input) => - Effect.gen(function* () { - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId); - yield* assertLiveCallerForOtherThread(scope, parent, target); - yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); - - const mode = input.mode ?? "auto"; - const key = yield* requestKey(input.clientRequestId); - const messageId = stableOperationMessageId({ - scope, - requestKey: key, - operation: "thread-send", - }); - const result = yield* threadManagement - .sendToThread({ - projectId: target.thread.projectId, - commandId: stableCommandId({ - scope, - requestKey: key, - operation: "thread-send", - }), - threadId: input.threadId, - ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }), - messageId, - text: input.message, - attachments: [], - mode, - createdBy: "agent", - creationSource: "mcp", - }) - .pipe( - Effect.mapError((error) => - isThreadManagementError(error) - ? threadManagementFailure(error) - : failure( - "orchestration_error", - `Unable to send to thread ${input.threadId}: ${errorMessage(error)}`, - ), - ), - ); - return { + } + return { + thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis), + recentRuns: target.runs + .toSorted((left, right) => right.ordinal - left.ordinal) + .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT) + .map(threadRun), + items: page.map((row) => + timelineItem({ + row, + maxChars, + messagesByThreadId, + ...(input.itemId === undefined ? {} : { textOffset: input.textOffset ?? 0 }), + }), + ), + nextPosition: page.at(-1)?.position ?? null, + hasMore: timeline.hasMore, + } satisfies OrchestratorMcpThreadReadResult; + }), + sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) { + const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId); + yield* assertLiveCallerForOtherThread(scope, parent, target); + yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); + + const mode = input.mode ?? "auto"; + const key = yield* requestKey(input.clientRequestId); + const messageId = stableOperationMessageId({ + scope, + requestKey: key, + operation: "thread-send", + }); + const result = yield* threadManagement + .sendToThread({ + projectId: target.thread.projectId, + commandId: stableCommandId({ + scope, + requestKey: key, + operation: "thread-send", + }), threadId: input.threadId, + ...(parent === undefined ? {} : { senderThreadId: parent.thread.id }), messageId, - runId: result.run.id, - ...(result.run.delegatedTaskId === undefined - ? {} - : { taskId: result.run.delegatedTaskId }), - status: result.run.status, - delivery: result.delivery, - } satisfies OrchestratorMcpThreadSendResult; - }), - waitForThread: (scope, input) => - Effect.gen(function* () { - const { target } = yield* loadScopedThread(scope, input.threadId); - const result = yield* threadManagement - .waitForThread({ - projectId: target.thread.projectId, - threadId: input.threadId, - ...(input.runId === undefined ? {} : { runId: input.runId }), - timeoutMs: Math.min( - MAX_WAIT_TIMEOUT_MS, - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), - ), - }) - .pipe(Effect.mapError(threadManagementFailure)); - return { + text: input.message, + attachments: [], + mode, + createdBy: "agent", + creationSource: "mcp", + }) + .pipe( + Effect.mapError((error) => + isThreadManagementError(error) + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to send to thread ${input.threadId}: ${userFacingDispatchErrorMessage(error) ?? errorMessage(error)}`, + ), + ), + ); + return { + threadId: input.threadId, + link: formatThreadLink(input.threadId, target.thread.title), + messageId, + runId: result.run.id, + ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }), + status: result.run.status, + delivery: result.delivery, + } satisfies OrchestratorMcpThreadSendResult; + }), + waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) { + const { parent, target } = yield* loadScopedThread(scope, input.threadId); + const result = yield* threadManagement + .waitForThread({ + projectId: target.thread.projectId, threadId: input.threadId, - runId: result.run?.id ?? null, - status: result.run === null ? "idle" : runOutcome(result.run), - timedOut: result.timedOut, - } satisfies OrchestratorMcpThreadWaitResult; - }), - interruptThread: (scope, input) => - Effect.gen(function* () { - const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId); - yield* assertLiveCallerForOtherThread(scope, parent, target); - yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); - const key = yield* requestKey(input.clientRequestId); - const result = yield* threadManagement - .interruptThread({ - projectId: target.thread.projectId, - commandId: stableCommandId({ - scope, - requestKey: key, - operation: "thread-interrupt", - }), - threadId: input.threadId, - ...(input.runId === undefined ? {} : { runId: input.runId }), - ...(input.reason === undefined ? {} : { reason: input.reason }), - }) - .pipe( - Effect.mapError((error) => - isThreadManagementError(error) - ? threadManagementFailure(error) - : failure( - "orchestration_error", - `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`, - ), - ), - ); - if (result.type === "no_active_run") { - return { - threadId: input.threadId, - runId: null, - status: "no_active_run", - } satisfies OrchestratorMcpThreadInterruptResult; - } + ...(input.runId === undefined ? {} : { runId: input.runId }), + timeoutMs: Math.min( + MAX_WAIT_TIMEOUT_MS, + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + ), + }) + .pipe(Effect.mapError(threadManagementFailure)); + const status = result.run === null ? "idle" : runOutcome(result.run); + const taskId = result.run?.delegatedTaskId; + const ownedTask = + result.timedOut && + status !== "waiting" && + parent?.subagents.some( + (task) => + task.id === taskId && + task.origin === "app_owned" && + task.threadId === parent.thread.id && + task.childThreadId === input.threadId && + task.completionDelivery?.state !== "disposed", + ) === true; + // A child waiting on a question or approval needs an answer, not a wake. + const childRequests = ownedTask + ? (yield* threadManagement + .getThreadRecords(input.threadId, ["runtimeRequests"]) + .pipe(Effect.mapError(threadManagementFailure))).runtimeRequests + : []; + const wakesCaller = + ownedTask && !childRequests.some((request) => request.status === "pending"); + return { + threadId: input.threadId, + runId: result.run?.id ?? null, + status, + timedOut: result.timedOut, + ...(wakesCaller ? { next: ORCHESTRATOR_MCP_RUNNING_TASK_NEXT } : {}), + } satisfies OrchestratorMcpThreadWaitResult; + }), + interruptThread: Effect.fn("OrchestratorMcpService.interruptThread")(function* (scope, input) { + const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId); + yield* assertLiveCallerForOtherThread(scope, parent, target); + yield* resolveRuntimeMode(limits.runtimeMode, target.thread.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, target.thread.interactionMode); + const key = yield* requestKey(input.clientRequestId); + const result = yield* threadManagement + .interruptThread({ + projectId: target.thread.projectId, + commandId: stableCommandId({ + scope, + requestKey: key, + operation: "thread-interrupt", + }), + threadId: input.threadId, + ...(input.runId === undefined ? {} : { runId: input.runId }), + reason: agentStopReason(input.reason), + }) + .pipe( + Effect.mapError((error) => + isThreadManagementError(error) + ? threadManagementFailure(error) + : failure( + "orchestration_error", + `Unable to interrupt thread ${input.threadId}: ${errorMessage(error)}`, + ), + ), + ); + if (result.type === "no_active_run") { return { threadId: input.threadId, - runId: result.run.id, - status: result.type === "already_terminal" ? result.run.status : "interrupt_requested", + runId: null, + status: "no_active_run", } satisfies OrchestratorMcpThreadInterruptResult; - }), + } + return { + threadId: input.threadId, + runId: result.run.id, + status: result.type === "already_terminal" ? result.run.status : "interrupt_requested", + } satisfies OrchestratorMcpThreadInterruptResult; + }), }); }); diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 44d53fdbc0126..d47fb11fe6a2b 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -1,71 +1,37 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; -import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv"; -import type { JsonSchemaType } from "@modelcontextprotocol/sdk/validation"; import { CommandId, EnvironmentId, - EventId, - IsoDateTime, isProviderNativeSubagentThread, MessageId, type ModelSelection, - type OrchestrationV2DelegatedCompletionDelivery, - type OrchestrationV2ProviderCapabilities, - type OrchestrationV2ProviderSession, - type OrchestrationV2ProviderThread, - type OrchestrationV2ThreadProjection, - OrchestratorMcpCreateThreadsResult, OrchestratorMcpDelegateTaskResult, - OrchestratorMcpTaskCancelResult, OrchestratorMcpThreadInterruptResult, - OrchestratorMcpThreadListResult, - OrchestratorMcpThreadReadResult, OrchestratorMcpThreadSendResult, - OrchestratorMcpThreadWaitResult, ProjectId, ProviderDriverKind, ProviderInstanceId, type ProviderOptionDescriptor, - ProviderThreadId, - ProviderTurnId, - type ScheduledTask, - RuntimeRequestId, - ScheduledTaskId, - type ScheduledTaskUpsertInput, type ServerProvider, ThreadId, - ThreadMetadataMcpUpdateResult, - TurnItemId, } from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -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 Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import * as Fiber from "effect/Fiber"; import * as Stream from "effect/Stream"; import { McpSchema, McpServer } from "effect/ai"; -import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; -import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts"; import { CodexOrchestratorReplayHarness } from "../orchestration-v2/Adapters/CodexAdapterV2.testkit.ts"; -import { threadShellFromProjection } from "../orchestration-v2/ProjectionStore.ts"; import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts"; -import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; -import * as ThreadSearch from "../orchestration-v2/ThreadSearch.ts"; -import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; -import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts"; @@ -80,8 +46,6 @@ import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as McpHttpServer from "./McpHttpServer.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; -import { delegatedTaskRun, hasPendingChildRuns } from "./OrchestratorMcpService.ts"; -import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), @@ -90,72 +54,43 @@ const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe( // Effect returns a declared tool failure as `isError` with its encoded payload // as JSON text, never as `structuredContent`. -const declaredFailure = (result: McpSchema.CallToolResult) => { - const text = result.content[0]; - return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined; -}; const parentThreadId = ThreadId.make("thread:mcp-orchestrator-parent"); const projectId = ProjectId.make("project:mcp-orchestrator"); const codexInstanceId = ProviderInstanceId.make("codex"); -const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); const codexModel = "gpt-5.4"; -const claudeModel = "claude-sonnet-4-6"; const parentPrompt = "Keep this parent turn active while orchestration tools are tested."; const delegatedPrompt = "Inspect the delegated API boundary and return the result."; const delegatedResult = "Delegated API boundary inspected."; const cancellationPrompt = "Remain active until the parent cancels this delegated task."; -const createdThreadPrompt = "Complete the newly created ordinary thread."; const queuedFollowupPrompt = "Complete the queued follow-up and return the final result."; const queuedFollowupResult = "Queued delegated follow-up completed."; -const decodeCreateThreadsResult = Schema.decodeUnknownEffect(OrchestratorMcpCreateThreadsResult); const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult); -const decodeTaskCancelResult = Schema.decodeUnknownEffect(OrchestratorMcpTaskCancelResult); const decodeThreadInterruptResult = Schema.decodeUnknownEffect( OrchestratorMcpThreadInterruptResult, ); -const decodeThreadListResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadListResult); -const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult); const decodeThreadSendResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadSendResult); -const decodeThreadWaitResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadWaitResult); -const decodeThreadUpdateResult = Schema.decodeUnknownEffect(ThreadMetadataMcpUpdateResult); const codexSelection = { instanceId: codexInstanceId, model: codexModel, } satisfies ModelSelection; -const claudeSelection = { - instanceId: claudeInstanceId, - model: claudeModel, -} satisfies ModelSelection; - const delegatedTaskStatusTranscriptFile = new URL( "../orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson", import.meta.url, ); -const readDelegatedTaskStatusTranscript = Effect.fn("readDelegatedTaskStatusTranscript")( - function* () { - const fs = yield* FileSystem.FileSystem; - const text = yield* fs.readFileString( - decodeURIComponent(delegatedTaskStatusTranscriptFile.pathname), - ); - return yield* decodeProviderReplayNdjson(text); - }, - Effect.provide(NodeServices.layer), -); - -interface CapturedTurn { - readonly instanceId: ProviderInstanceId; - readonly threadId: ThreadId; - readonly text: string; -} - -function unsupported(driver: ProviderDriverKind, detail: string) { - return Effect.fail(new ProviderAdapter.ProviderAdapterProtocolError({ driver, detail })); -} +const readDelegatedTaskStatusTranscript = Effect.fn("readDelegatedTaskStatusTranscript")(function* ( + followupResult: string, +) { + const fs = yield* FileSystem.FileSystem; + const text = yield* fs.readFileString( + decodeURIComponent(delegatedTaskStatusTranscriptFile.pathname), + ); + return yield* decodeProviderReplayNdjson(text.replaceAll(queuedFollowupResult, followupResult)); +}, Effect.provide(NodeServices.layer)); function makeProviderSnapshot(input: { readonly instanceId: ProviderInstanceId; @@ -188,261 +123,6 @@ function makeProviderSnapshot(input: { }; } -function makeDeterministicAdapter(input: { - readonly instanceId: ProviderInstanceId; - readonly driver: ProviderDriverKind; - readonly capabilities: OrchestrationV2ProviderCapabilities; - readonly capturedTurns: Ref.Ref>; - readonly shouldComplete: (turn: ProviderAdapter.ProviderAdapterV2TurnInput) => boolean; - readonly terminalGate?: ( - turn: ProviderAdapter.ProviderAdapterV2TurnInput, - ) => Deferred.Deferred | undefined; - readonly response: (turn: ProviderAdapter.ProviderAdapterV2TurnInput) => string; - readonly steerReceived?: ( - steer: ProviderAdapter.ProviderAdapterV2SteerInput, - ) => Deferred.Deferred | undefined; -}): ProviderAdapter.ProviderAdapterV2["Service"] { - return { - instanceId: input.instanceId, - driver: input.driver, - getCapabilities: () => Effect.succeed(input.capabilities), - planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), - openSession: (sessionInput) => - Effect.gen(function* () { - const events = yield* PubSub.unbounded(); - const now = yield* DateTime.now; - const providerSession: OrchestrationV2ProviderSession = { - id: sessionInput.providerSessionId, - driver: input.driver, - providerInstanceId: input.instanceId, - status: "ready", - cwd: sessionInput.runtimePolicy.cwd ?? process.cwd(), - model: sessionInput.modelSelection.model, - capabilities: input.capabilities, - createdAt: now, - updatedAt: now, - lastError: null, - }; - - const publish = (providerEvents: ReadonlyArray) => - Effect.forEach(providerEvents, (event) => PubSub.publish(events, event), { - discard: true, - }); - const runOrdinals = new Map(); - const turnInputs = new Map(); - - return { - instanceId: input.instanceId, - driver: input.driver, - providerSessionId: sessionInput.providerSessionId, - providerSession, - events: Stream.fromPubSub(events), - ensureThread: (threadInput) => - Effect.gen(function* () { - const createdAt = yield* DateTime.now; - const nativeThreadId = `${input.driver}:${threadInput.threadId}`; - return { - id: ProviderThreadId.make(`provider-thread:${nativeThreadId}`), - driver: input.driver, - providerInstanceId: input.instanceId, - providerSessionId: sessionInput.providerSessionId, - appThreadId: threadInput.threadId, - ownerNodeId: null, - nativeThreadRef: { - driver: input.driver, - nativeId: nativeThreadId, - strength: "strong", - }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: null, - createdAt, - updatedAt: createdAt, - } satisfies OrchestrationV2ProviderThread; - }), - resumeThread: ({ providerThread }) => Effect.succeed(providerThread), - startTurn: (turnInput) => - Effect.gen(function* () { - yield* Ref.update(input.capturedTurns, (turns) => [ - ...turns, - { - instanceId: input.instanceId, - threadId: turnInput.threadId, - text: turnInput.message.text, - }, - ]); - const eventTime = yield* DateTime.now; - const providerTurnId = ProviderTurnId.make( - `provider-turn:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}`, - ); - runOrdinals.set(providerTurnId, turnInput.runOrdinal); - turnInputs.set(providerTurnId, turnInput); - yield* publish([ - { - type: "provider_turn.updated", - driver: input.driver, - providerTurn: { - id: providerTurnId, - providerThreadId: turnInput.providerThread.id, - nodeId: turnInput.rootNodeId, - runAttemptId: turnInput.attemptId, - nativeTurnRef: { - driver: input.driver, - nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`, - strength: "strong", - }, - ordinal: turnInput.providerTurnOrdinal, - status: "running", - startedAt: eventTime, - completedAt: null, - }, - }, - ]); - const terminalGate = input.terminalGate?.(turnInput); - if (terminalGate !== undefined) { - yield* Deferred.await(terminalGate); - } else if (!input.shouldComplete(turnInput)) { - return; - } - const response = input.response(turnInput); - yield* publish([ - { - type: "provider_turn.updated", - driver: input.driver, - providerTurn: { - id: providerTurnId, - providerThreadId: turnInput.providerThread.id, - nodeId: turnInput.rootNodeId, - runAttemptId: turnInput.attemptId, - nativeTurnRef: { - driver: input.driver, - nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`, - strength: "strong", - }, - ordinal: turnInput.providerTurnOrdinal, - status: "completed", - startedAt: eventTime, - completedAt: eventTime, - }, - }, - { - type: "turn_item.updated", - driver: input.driver, - turnItem: { - id: TurnItemId.make( - `turn-item:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, - ), - threadId: turnInput.threadId, - runId: turnInput.runId, - nodeId: turnInput.rootNodeId, - providerThreadId: turnInput.providerThread.id, - providerTurnId, - nativeItemRef: null, - parentItemId: null, - ordinal: turnInput.runOrdinal * 100 + 1, - status: "completed", - title: null, - startedAt: eventTime, - completedAt: eventTime, - updatedAt: eventTime, - type: "assistant_message", - messageId: MessageId.make( - `message:${input.instanceId}:${turnInput.threadId}:${turnInput.runOrdinal}:assistant`, - ), - text: response, - streaming: false, - }, - }, - { - type: "turn.terminal", - driver: input.driver, - providerThreadId: turnInput.providerThread.id, - providerTurnId, - runOrdinal: turnInput.runOrdinal, - status: "completed", - failure: null, - threadDisposition: "reusable", - }, - ]); - }), - steerTurn: (steer) => { - const received = input.steerReceived?.(steer); - return received === undefined - ? Effect.void - : Deferred.succeed(received, undefined).pipe(Effect.asVoid); - }, - interruptTurn: ({ providerThread, providerTurnId }) => - Effect.gen(function* () { - const turnInput = turnInputs.get(providerTurnId); - const completedAt = yield* DateTime.now; - if (turnInput !== undefined) { - yield* publish([ - { - type: "provider_turn.updated", - driver: input.driver, - providerTurn: { - id: providerTurnId, - providerThreadId: providerThread.id, - nodeId: turnInput.rootNodeId, - runAttemptId: turnInput.attemptId, - nativeTurnRef: { - driver: input.driver, - nativeId: `native-turn:${turnInput.threadId}:${turnInput.runOrdinal}`, - strength: "strong", - }, - ordinal: turnInput.providerTurnOrdinal, - status: "interrupted", - startedAt: completedAt, - completedAt, - }, - }, - ]); - } - yield* publish([ - { - type: "turn.terminal", - driver: input.driver, - providerThreadId: providerThread.id, - providerTurnId, - runOrdinal: runOrdinals.get(providerTurnId) ?? 1, - status: "interrupted", - failure: null, - threadDisposition: "reusable", - }, - ]); - }), - respondToRuntimeRequest: () => Effect.void, - readThreadSnapshot: () => - unsupported(input.driver, "readThreadSnapshot is unused in this test"), - rollbackThread: () => unsupported(input.driver, "rollbackThread is unused in this test"), - forkThread: () => unsupported(input.driver, "forkThread is unused in this test"), - }; - }), - }; -} - -function waitForProjection( - orchestrator: Orchestrator.OrchestratorV2Shape, - threadId: ThreadId, - predicate: (projection: OrchestrationV2ThreadProjection) => boolean, -) { - return Effect.gen(function* () { - for (let attempt = 0; attempt < 1_000; attempt += 1) { - const projection = yield* orchestrator.getThreadProjection(threadId); - if (predicate(projection)) { - return projection; - } - yield* Effect.sleep("5 millis"); - } - return yield* Effect.die( - new Error(`Timed out waiting for orchestration projection ${threadId}.`), - ); - }); -} - const client = McpSchema.McpServerClient.of({ clientId: 1, protocolVersion: "2025-06-18", @@ -456,45 +136,6 @@ const client = McpSchema.McpServerClient.of({ getClient: Effect.die("unused"), }); -function scheduledTaskFromUpsert(input: ScheduledTaskUpsertInput): ScheduledTask { - const timestamp = IsoDateTime.make("2026-07-01T09:00:00.000Z"); - return { - id: input.id ?? ScheduledTaskId.make(`scheduled-task:${input.commandId ?? "stub"}`), - title: input.title, - prompt: input.prompt, - enabled: input.enabled, - schedule: - input.schedule.type === "webhook" - ? { - type: "webhook", - signature: - input.schedule.signature == null - ? null - : { - header: input.schedule.signature.header, - encoding: input.schedule.signature.encoding, - prefix: input.schedule.signature.prefix, - }, - } - : input.schedule, - projectId: input.projectId, - threadId: input.threadId ?? null, - workspaceStrategy: input.workspaceStrategy, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - createdBy: input.createdBy ?? "user", - creationSource: input.creationSource ?? "web", - createdAt: timestamp, - updatedAt: timestamp, - nextRunAt: null, - lastRunAt: null, - lastRunStatus: "never", - lastRunError: null, - runCount: 0, - }; -} - const layerMemorySecretStore = Layer.sync(ServerSecretStore.ServerSecretStore, () => { const stored = new Map(); return ServerSecretStore.ServerSecretStore.of({ @@ -521,6 +162,7 @@ const layerUnusedScheduledTaskStub = Layer.succeed( upsert: () => Effect.die("ScheduledTaskService.upsert is unused in this test"), setEnabled: () => Effect.die("ScheduledTaskService.setEnabled is unused in this test"), delete: () => Effect.die("ScheduledTaskService.delete is unused in this test"), + deleteForThread: () => Effect.die("unused in this test"), runNow: () => Effect.die("ScheduledTaskService.runNow is unused in this test"), rotateWebhookToken: () => Effect.die("unused in this test"), listWebhookDeliveries: () => Effect.die("unused in this test"), @@ -530,3380 +172,14 @@ const layerUnusedScheduledTaskStub = Layer.succeed( ); describe("orchestrator MCP toolkit", () => { - it.live( - "delegates cross-provider tasks, polls and cancels children, and creates ordinary threads", - () => - Effect.scoped( - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("orchestrator-mcp-toolkit"); - const capturedTurns = yield* Ref.make>([]); - const steerReceivedGates = new Map>(); - const parentTerminalGates = new Map>(); - const deliveryTerminalGates = new Map>(); - const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([ - makeDeterministicAdapter({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - capabilities: { - ...CodexProviderCapabilitiesV2, - turns: { ...CodexProviderCapabilitiesV2.turns, supportsActiveSteering: false }, - }, - capturedTurns, - shouldComplete: (turn) => - turn.threadId !== parentThreadId && turn.message.text !== cancellationPrompt, - terminalGate: (turn) => - turn.message.text.startsWith("Delegated task") || - turn.message.text.startsWith("Delegated tasks") - ? deliveryTerminalGates.get(turn.threadId) - : parentTerminalGates.get(turn.threadId), - response: (turn) => `Codex completed: ${turn.message.text}`, - }), - makeDeterministicAdapter({ - instanceId: claudeInstanceId, - driver: ProviderDriverKind.make("claudeAgent"), - capabilities: ClaudeProviderCapabilitiesV2, - capturedTurns, - shouldComplete: (turn) => turn.message.text !== cancellationPrompt, - terminalGate: (turn) => - turn.message.text.startsWith("Delegated task") || - turn.message.text.startsWith("Delegated tasks") - ? deliveryTerminalGates.get(turn.threadId) - : parentTerminalGates.get(turn.threadId), - response: (turn) => - turn.message.text === delegatedPrompt - ? delegatedResult - : `Claude completed: ${turn.message.text}`, - steerReceived: (steer) => steerReceivedGates.get(steer.message.text), - }), - ]); - const continuationOffers = yield* Ref.make< - ReadonlyArray - >([]); - const layerContinuationProbe = Layer.succeed( - ProviderContinuationRequests.ProviderContinuationRequests, - { - offer: (request) => - Ref.update(continuationOffers, (existing) => [...existing, request]), - take: Effect.never, - }, - ); - const waitForContinuationOffers = (count: number) => - Effect.gen(function* () { - for (let attempt = 0; attempt < 1_000; attempt += 1) { - const current = yield* Ref.get(continuationOffers); - if (current.length >= count) { - return current; - } - yield* Effect.sleep("5 millis"); - } - return yield* Ref.get(continuationOffers); - }); - const expectOffersToStay = (count: number) => - Effect.gen(function* () { - for (let sample = 0; sample < 4; sample += 1) { - yield* Effect.sleep("50 millis"); - expect(yield* Ref.get(continuationOffers)).toHaveLength(count); - } - }); - const layerOrchestrator = ProviderReplayHarness.layerWithRegistry( - { - name: "orchestrator-mcp-toolkit", - runtimePolicyOverride: { - cwd, - approvalPolicy: "never", - sandboxPolicy: { - type: "readOnly", - access: { type: "fullAccess" }, - networkAccess: false, - }, - }, - }, - layerRegistry, - ).pipe(Layer.provide(layerContinuationProbe)); - 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 layerProviderRegistry = ProviderRegistryMock.layer([ - makeProviderSnapshot({ - instanceId: codexInstanceId, - driver: ProviderDriverKind.make("codex"), - model: codexModel, - optionDescriptors: [ - { - id: "reasoning", - label: "Reasoning effort", - type: "select", - options: [ - { id: "low", label: "Low" }, - { id: "medium", label: "Medium" }, - { id: "high", label: "High" }, - ], - }, - ], - }), - makeProviderSnapshot({ - instanceId: claudeInstanceId, - driver: ProviderDriverKind.make("claudeAgent"), - model: claudeModel, - }), - makeProviderSnapshot({ - instanceId: ProviderInstanceId.make("opencode"), - driver: ProviderDriverKind.make("opencode"), - model: "opencode/test", - }), - ]); - const scheduledStore = yield* Ref.make>([]); - const layerScheduledTaskStub = Layer.succeed( - ScheduledTaskService.ScheduledTaskService, - ScheduledTaskService.ScheduledTaskService.of({ - list: () => Ref.get(scheduledStore).pipe(Effect.map((tasks) => ({ tasks }))), - subscribeList: () => Stream.empty, - upsert: (input) => - Effect.gen(function* () { - const task = scheduledTaskFromUpsert(input); - yield* Ref.update(scheduledStore, (all) => [ - ...all.filter((candidate) => candidate.id !== task.id), - task, - ]); - return { task }; - }), - setEnabled: () => - Effect.die("ScheduledTaskService.setEnabled is unused in this test"), - delete: (input) => - Ref.update(scheduledStore, (all) => - all.filter((candidate) => candidate.id !== input.id), - ).pipe(Effect.as({ id: input.id })), - runNow: () => Effect.die("ScheduledTaskService.runNow is unused in this test"), - rotateWebhookToken: () => Effect.die("unused in this test"), - listWebhookDeliveries: () => Effect.die("unused in this test"), - getWebhookDelivery: () => Effect.die("unused in this test"), - triggerWebhook: () => Effect.die("unused in this test"), - }), - ); - const layerTest = Layer.merge( - layerOrchestratorToolkit, - McpHttpServer.layerThreadToolkit, - ).pipe( - Layer.provideMerge(McpServer.McpServer.layer), - Layer.provideMerge(layerOrchestration), - Layer.provide(layerRegistry), - Layer.provide(layerProviderRegistry), - Layer.provide(ServerSettings.layerTest()), - Layer.provide(layerScheduledTaskStub), - Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), - Layer.provide( - Layer.mock(ProjectService.ProjectService)({ - getById: (id) => - Effect.succeed( - id === projectId - ? Option.some({ id, defaultModelSelection: null } as never) - : Option.none(), - ), - }), - ), - Layer.provideMerge( - SecretRequests.layer.pipe( - Layer.provide(layerMemorySecretStore), - Layer.provide(layerOrchestration), - ), - ), - Layer.provide(NodeServices.layer), - ); - - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const server = yield* McpServer.McpServer; - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-parent:create"), - threadId: parentThreadId, - projectId, - title: "MCP 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-parent:start"), - threadId: parentThreadId, - messageId: MessageId.make("message:mcp-parent:start"), - text: parentPrompt, - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "start_immediately" }, - }); - const parent = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.some((run) => - ["starting", "running", "waiting"].includes(run.status), - ) && projection.providerTurns.some((turn) => turn.status === "running"), - ); - const parentRun = parent.runs[0]; - expect(parentRun?.status).toBe("running"); - - const invocation: McpInvocationContext.McpInvocationScope = { - environmentId: EnvironmentId.make("environment:mcp-orchestrator"), - requestNamespace: "mcp-provider-session-parent", - thread: { - threadId: parentThreadId, - providerSessionId: "mcp-provider-session-parent", - providerInstanceId: codexInstanceId, - }, - client: undefined, - capabilities: new Set(["orchestration"]), - issuedAt: 1, - }; - const invokeAs = ( - callScope: McpInvocationContext.McpInvocationScope, - name: string, - args: Record, - ) => - server - .callTool({ name, arguments: args }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, callScope), - Effect.provideService(McpSchema.McpServerClient, client), - ); - const invoke = (name: string, args: Record) => - invokeAs(invocation, name, args); - - const deferredSettle = yield* invoke("t3_thread_organize", { action: "settle" }); - expect(deferredSettle.isError).toBe(false); - expect(deferredSettle.structuredContent).toEqual({ settlesWhenTurnEnds: true }); - const afterDeferredSettle = yield* orchestrator.getThreadProjection(parentThreadId); - expect(afterDeferredSettle.thread.settledOverride).not.toBe("settled"); - expect(afterDeferredSettle.runs.find((run) => run.id === parentRun?.id)?.status).toBe( - "running", - ); - - const pinned = yield* invoke("t3_thread_organize", { action: "pin" }); - expect(pinned.isError).toBe(false); - expect(pinned.structuredContent).toHaveProperty("sequence"); - expect((yield* orchestrator.getThreadShell(parentThreadId))?.pinnedAt).not.toBeNull(); - yield* invoke("t3_thread_organize", { action: "unpin" }); - expect((yield* orchestrator.getThreadShell(parentThreadId))?.pinnedAt).toBeNull(); - - if (parentRun === undefined || parentRun.rootNodeId === null) { - return yield* Effect.die(new Error("Parent run missing.")); - } - for (const name of ["t3_queue_edit", "t3_queue_cancel"]) { - const refusedQueueMutation = yield* invoke(name, { - queuedRunId: parentRun.id, - ...(name === "t3_queue_edit" ? { text: "Keep the active turn." } : {}), - }); - expect(refusedQueueMutation.isError).toBe(true); - expect(refusedQueueMutation.structuredContent).toBeUndefined(); - expect(declaredFailure(refusedQueueMutation)).toEqual({ - _tag: "OrchestratorMcpFailure", - code: "orchestration_error", - message: `Run ${parentRun.id} is not queued.`, - }); - } - - let parentRootNodeId = parentRun.rootNodeId; - const queueAutomaticCompletion = (suffix: string, taskText: string) => - Effect.gen(function* () { - const delegated = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make(`command:mcp-parent:${suffix}:delegate`), - parentThreadId, - parentRunId: parentRun.id, - parentNodeId: parentRootNodeId, - task: taskText, - modelSelection: claudeSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const taskEvent = delegated.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.origin === "app_owned", - ); - if (taskEvent?.event.type !== "subagent.updated") { - return yield* Effect.die( - new Error(`Automatic completion task ${suffix} was not created.`), - ); - } - const task = taskEvent.event.payload; - const reserved = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => { - const delivery = projection.runs.find((run) => run.id === parentRun.id) - ?.delegatedCompletion?.delivery; - return ( - projection.subagents.find((candidate) => candidate.id === task.id)?.status === - "completed" && - delivery !== undefined && - delivery !== null && - delivery.taskIds.includes(task.id) - ); - }, - ); - const delivery = reserved.runs.find((run) => run.id === parentRun.id) - ?.delegatedCompletion?.delivery; - if (delivery === undefined || delivery === null) { - return yield* Effect.die( - new Error(`Automatic completion delivery ${suffix} was not reserved.`), - ); - } - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make(`command:mcp-parent:${suffix}:dispatch`), - threadId: parentThreadId, - messageId: delivery.messageId, - text: "Delegated task reached a terminal state.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: parentRun.id, - generation: delivery.generation, - taskIds: delivery.taskIds, - }, - }); - const queued = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.some( - (run) => run.userMessageId === delivery.messageId && run.status === "queued", - ), - ); - const queuedRun = queued.runs.find( - (run) => run.userMessageId === delivery.messageId, - ); - if (queuedRun === undefined) { - return yield* Effect.die( - new Error(`Automatic completion delivery ${suffix} was not queued.`), - ); - } - return { task, delivery, queuedRun }; - }); - - const coalescedTask = (suffix: string) => - orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make(`command:mcp-parent:coalesced-${suffix}`), - parentThreadId, - parentRunId: parentRun.id, - parentNodeId: parentRootNodeId, - task: `Complete coalesced task ${suffix}.`, - modelSelection: claudeSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const firstCoalesced = yield* coalescedTask("one"); - const secondCoalesced = yield* coalescedTask("two"); - const coalescedTaskIds = [firstCoalesced, secondCoalesced].map((result) => { - const taskEvent = result.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.origin === "app_owned", - ); - if (taskEvent?.event.type !== "subagent.updated") { - throw new Error("Coalesced delegated task projection missing."); - } - return taskEvent.event.payload.id; - }); - const coalescedProjection = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - coalescedTaskIds.every( - (taskId) => - projection.subagents.find((task) => task.id === taskId)?.status === "completed", - ) && - projection.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion !== - undefined, - ); - const coalescedCohort = coalescedProjection.runs.find( - (run) => run.id === parentRun.id, - )?.delegatedCompletion; - expect(coalescedCohort?.delivery?.taskIds).toEqual( - expect.arrayContaining(coalescedTaskIds), - ); - expect(coalescedCohort?.delivery?.taskIds).toHaveLength(2); - const coalescedOffers = yield* waitForContinuationOffers(1); - expect(coalescedOffers).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - delegatedCompletion: expect.objectContaining({ - parentRunId: parentRun.id, - messageId: coalescedCohort?.delivery?.messageId, - }), - }), - ]), - ); - if (coalescedCohort?.delivery === undefined || coalescedCohort.delivery === null) { - return yield* Effect.die(new Error("Coalesced delivery reservation missing.")); - } - const coalescedDelivery = coalescedCohort.delivery; - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make("command:mcp-parent:dispatch-coalesced-delivery"), - threadId: parentThreadId, - messageId: coalescedDelivery.messageId, - text: "Delegated tasks reached terminal states.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: parentRun.id, - generation: coalescedDelivery.generation, - taskIds: coalescedDelivery.taskIds, - }, - }); - const queuedCoalesced = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.some( - (run) => - run.userMessageId === coalescedDelivery.messageId && run.status === "queued", - ), - ); - const queuedCoalescedRun = queuedCoalesced.runs.find( - (run) => run.userMessageId === coalescedDelivery.messageId, - ); - expect(queuedCoalescedRun?.status).toBe("queued"); - if (queuedCoalescedRun === undefined) { - return yield* Effect.die(new Error("Queued coalesced delivery missing.")); - } - - const completionEditError = yield* orchestrator - .dispatch({ - type: "queued-run.edit", - commandId: CommandId.make("command:mcp-parent:edit-coalesced-delivery"), - threadId: parentThreadId, - runId: queuedCoalescedRun.id, - text: "Rewrite the automatic delivery.", - }) - .pipe(Effect.flip); - expect(completionEditError._tag).toBe("OrchestratorCommandRejectedError"); - const completionReorderError = yield* orchestrator - .dispatch({ - type: "queued-run.reorder", - commandId: CommandId.make("command:mcp-parent:reorder-coalesced-delivery"), - threadId: parentThreadId, - runId: queuedCoalescedRun.id, - beforeRunId: null, - }) - .pipe(Effect.flip); - expect(completionReorderError._tag).toBe("OrchestratorDispatchError"); - const completionSteerError = yield* orchestrator - .dispatch({ - type: "queued-message.promote-to-steer", - commandId: CommandId.make("command:mcp-parent:steer-coalesced-delivery"), - threadId: parentThreadId, - queuedRunId: queuedCoalescedRun.id, - targetRunId: parentRun.id, - }) - .pipe(Effect.flip); - expect(completionSteerError._tag).toBe("OrchestratorDispatchError"); - - for (const taskId of coalescedTaskIds) { - const statusCall = yield* invoke("task_status", { taskId }); - expect(statusCall.isError).toBe(false); - } - const acknowledgedCoalesced = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.find((run) => run.id === queuedCoalescedRun.id)?.status === - "cancelled" && - coalescedTaskIds.every( - (taskId) => - projection.subagents.find((task) => task.id === taskId)?.completionDelivery - ?.state === "acknowledged", - ), - ); - expect( - acknowledgedCoalesced.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion - ?.delivery, - ).toBeNull(); - yield* Ref.set(continuationOffers, []); - - const directRead = yield* queueAutomaticCompletion( - "direct-child-read", - "Complete before a parent reads this child result directly.", - ); - if (directRead.task.childThreadId === null) { - return yield* Effect.die(new Error("Direct-read child thread missing.")); - } - const directChildThreadId = directRead.task.childThreadId; - const directChildWaitCall = yield* invoke("t3_thread_wait", { - threadId: directChildThreadId, - timeoutMs: 10_000, - }); - const directChildWait = yield* decodeThreadWaitResult( - directChildWaitCall.structuredContent, - ).pipe(Effect.orDie); - expect(directChildWait).toMatchObject({ - threadId: directChildThreadId, - status: "completed", - timedOut: false, - }); - const pendingAfterWait = yield* orchestrator.getThreadProjection(parentThreadId); - expect( - pendingAfterWait.subagents.find((task) => task.id === directRead.task.id) - ?.completionDelivery?.state, - ).toBe("claimed"); - expect( - pendingAfterWait.runs.find((run) => run.id === directRead.queuedRun.id)?.status, - ).toBe("queued"); - - const childPromptReadCall = yield* invoke("t3_thread_read", { - threadId: directChildThreadId, - limit: 1, - }); - const childPromptRead = yield* decodeThreadReadResult( - childPromptReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(childPromptRead.items.map((item) => item.type)).toEqual(["user_message"]); - if (childPromptRead.nextPosition === null) { - return yield* Effect.die(new Error("Direct-read child prompt position missing.")); - } - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === directRead.task.id, - )?.completionDelivery?.state, - ).toBe("claimed"); - - const truncatedResultReadCall = yield* invoke("t3_thread_read", { - threadId: directChildThreadId, - afterPosition: childPromptRead.nextPosition, - limit: 1, - maxCharsPerItem: 1, - }); - const truncatedResultRead = yield* decodeThreadReadResult( - truncatedResultReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(truncatedResultRead.items).toMatchObject([ - { type: "assistant_message", textTruncated: true }, - ]); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === directRead.task.id, - )?.completionDelivery?.state, - ).toBe("claimed"); - - const firstChunk = truncatedResultRead.items[0]!; - expect(firstChunk.nextTextOffset).toBe(1); - const remainderCall = yield* invoke("t3_thread_read", { - threadId: directChildThreadId, - itemId: firstChunk.itemId, - textOffset: firstChunk.nextTextOffset, - maxCharsPerItem: 50_000, - }); - const remainder = yield* decodeThreadReadResult(remainderCall.structuredContent).pipe( - Effect.orDie, - ); - expect(remainder.items[0]?.nextTextOffset).toBeNull(); - expect(firstChunk.text + (remainder.items[0]?.text ?? "")).toBe( - "Claude completed: Complete before a parent reads this child result directly.", - ); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === directRead.task.id, - )?.completionDelivery?.state, - ).toBe("claimed"); - - const terminalResultReadCall = yield* invoke("t3_thread_read", { - threadId: directChildThreadId, - afterPosition: childPromptRead.nextPosition, - limit: 1, - }); - const terminalResultRead = yield* decodeThreadReadResult( - terminalResultReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(terminalResultRead.items).toMatchObject([ - { - type: "assistant_message", - text: "Claude completed: Complete before a parent reads this child result directly.", - textTruncated: false, - }, - ]); - const longText = "界🧪\n".repeat(20_000) + "FINAL_CONSTRAINT"; - const childProjection = yield* orchestrator.getThreadProjection(directChildThreadId); - const sourceItem = childProjection.turnItems.find( - (item) => item.type === "user_message", - )!; - const oversizedItem = { - ...sourceItem, - id: TurnItemId.make("item:oversized-retrieval"), - type: "assistant_message" as const, - text: longText, - streaming: false, - ordinal: 999, - }; - yield* (yield* EventSink.EventSinkV2).write({ - events: [ - { - id: EventId.make("event:oversized-retrieval"), - type: "turn-item.updated", - threadId: directChildThreadId, - occurredAt: yield* DateTime.now, - payload: oversizedItem, - }, - ], - }); - let recovered = ""; - let textOffset: number | null = 0; - while (textOffset !== null) { - const pageCall = yield* invoke("t3_thread_read", { - threadId: directChildThreadId, - itemId: oversizedItem.id, - textOffset, - maxCharsPerItem: 50_000, - }); - const page: OrchestratorMcpThreadReadResult = yield* decodeThreadReadResult( - pageCall.structuredContent, - ).pipe(Effect.orDie); - expect(page.items).toHaveLength(1); - recovered += page.items[0]!.text; - textOffset = page.items[0]!.nextTextOffset ?? null; - } - expect(recovered).toBe(longText); - - const acknowledgedByDirectRead = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.find((run) => run.id === directRead.queuedRun.id)?.status === - "cancelled" && - projection.subagents.find((task) => task.id === directRead.task.id) - ?.completionDelivery?.state === "acknowledged", - ); - expect( - acknowledgedByDirectRead.subagents.find((task) => task.id === directRead.task.id) - ?.completionDelivery, - ).toMatchObject({ state: "acknowledged", observedByRunId: parentRun.id }); - yield* Ref.set(continuationOffers, []); - - const queueRace = yield* queueAutomaticCompletion( - "queue-race", - "Complete before a user queues follow-up work.", - ); - const queuedUserMessageId = MessageId.make("message:mcp-parent:queue-race:user"); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-parent:queue-race:user"), - threadId: parentThreadId, - messageId: queuedUserMessageId, - text: "🙂".repeat(16001), - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - }); - const queueRaceQueued = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.some((run) => run.id === queueRace.queuedRun.id) && - projection.runs.some( - (run) => run.userMessageId === queuedUserMessageId && run.status === "queued", - ), - ); - const queuedUserRun = queueRaceQueued.runs.find( - (run) => run.userMessageId === queuedUserMessageId, - ); - if (queuedUserRun === undefined) { - return yield* Effect.die(new Error("Queued user follow-up missing.")); - } - const queueFirstPage = yield* invoke("t3_queue_list", { limit: 1 }); - expect(queueFirstPage.isError).toBe(false); - expect(queueFirstPage.structuredContent).toMatchObject({ - items: [{ queuedRunId: queueRace.queuedRun.id }], - nextCursor: 1, - }); - const queueDefinition = server.tools.find(({ tool }) => tool.name === "t3_queue_list"); - const validateQueue = new AjvJsonSchemaValidator().getValidator( - queueDefinition!.tool.outputSchema! as JsonSchemaType, - ); - expect(validateQueue(queueFirstPage.structuredContent).valid).toBe(true); - const missingThreadId = ThreadId.make("00000000-0000-4000-8000-000000000000"); - const missingThreadQueue = yield* invoke("t3_queue_list", { - threadId: missingThreadId, - limit: 1, - }); - expect(missingThreadQueue.isError).toBe(true); - expect(declaredFailure(missingThreadQueue)).toMatchObject({ - _tag: "OrchestratorMcpFailure", - code: "thread_not_found", - message: "The thread was not found.", - }); - expect(missingThreadQueue.structuredContent).toBeUndefined(); - expect(validateQueue({ items: "invalid", nextCursor: null }).valid).toBe(false); - const missingThreadRead = yield* invoke("t3_thread_read", { - threadId: missingThreadId, - }); - expect(missingThreadRead.isError).toBe(true); - expect(declaredFailure(missingThreadRead)).toMatchObject({ - _tag: "OrchestratorMcpFailure", - }); - const queueSecondPage = yield* invoke("t3_queue_list", { cursor: 1, limit: 1 }); - expect(queueSecondPage.structuredContent).toEqual({ - items: [{ queuedRunId: queuedUserRun.id, text: "🙂".repeat(1000), truncated: true }], - nextCursor: null, - }); - const queueRead = yield* invoke("t3_queue_read", { queuedRunId: queuedUserRun.id }); - expect(queueRead.structuredContent).toEqual({ - queuedRunId: queuedUserRun.id, - text: "🙂".repeat(16000), - truncated: true, - }); - const missingQueueRead = yield* invoke("t3_queue_read", { queuedRunId: parentRun.id }); - expect(declaredFailure(missingQueueRead)).toMatchObject({ code: "invalid_request" }); - const queueRaceStatus = yield* invoke("task_status", { taskId: queueRace.task.id }); - expect(queueRaceStatus.isError).toBe(false); - yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.find((run) => run.id === queueRace.queuedRun.id)?.status === - "cancelled" && - projection.runs.find((run) => run.id === queuedUserRun.id)?.status === "queued" && - projection.subagents.find((task) => task.id === queueRace.task.id) - ?.completionDelivery?.state === "acknowledged", - ); - yield* orchestrator.dispatch({ - type: "queued-run.cancel", - commandId: CommandId.make("command:mcp-parent:queue-race:cleanup"), - threadId: parentThreadId, - runId: queuedUserRun.id, - }); - - const steerRace = yield* queueAutomaticCompletion( - "steer-race", - "Complete before a user steers the parent.", - ); - const steerMessageId = MessageId.make("message:mcp-parent:steer-race:user"); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-parent:steer-race:user"), - threadId: parentThreadId, - messageId: steerMessageId, - text: "Steer the active parent after receiving the result.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "steer_active", targetRunId: parentRun.id }, - }); - const steerRaceStatus = yield* invoke("task_status", { taskId: steerRace.task.id }); - expect(steerRaceStatus.isError).toBe(false); - const acknowledgedSteerRace = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.messages.some((message) => message.id === steerMessageId) && - projection.runs.find((run) => run.id === parentRun.id)?.status === "running" && - projection.runs.find((run) => run.id === steerRace.queuedRun.id)?.status === - "cancelled" && - projection.subagents.find((task) => task.id === steerRace.task.id) - ?.completionDelivery?.state === "acknowledged", - ); - expect( - acknowledgedSteerRace.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion - ?.delivery, - ).toBeNull(); - - const restartRace = yield* queueAutomaticCompletion( - "restart-race", - "Complete before a user restarts the parent.", - ); - const attemptBeforeRestart = (yield* orchestrator.getThreadProjection( - parentThreadId, - )).runs.find((run) => run.id === parentRun.id)?.activeAttemptId; - const restartMessageId = MessageId.make("message:mcp-parent:restart-race:user"); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-parent:restart-race:user"), - threadId: parentThreadId, - messageId: restartMessageId, - text: "Restart the active parent after receiving the result.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "restart_active", targetRunId: parentRun.id }, - }); - const restartedParent = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => { - const run = projection.runs.find((candidate) => candidate.id === parentRun.id); - return ( - run?.status === "running" && - run.activeAttemptId !== attemptBeforeRestart && - run.rootNodeId !== null - ); - }, - ); - const currentParentRun = restartedParent.runs.find((run) => run.id === parentRun.id); - if (currentParentRun?.rootNodeId === null || currentParentRun === undefined) { - return yield* Effect.die(new Error("Restarted parent run missing.")); - } - parentRootNodeId = currentParentRun.rootNodeId; - expect(currentParentRun.delegatedCompletion?.disposition).toBe("open"); - const restartRaceStatus = yield* invoke("task_status", { - taskId: restartRace.task.id, - }); - expect(restartRaceStatus.isError).toBe(false); - yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.messages.some((message) => message.id === restartMessageId) && - projection.runs.find((run) => run.id === restartRace.queuedRun.id)?.status === - "cancelled" && - projection.subagents.find((task) => task.id === restartRace.task.id) - ?.completionDelivery?.state === "acknowledged" && - projection.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion - ?.disposition === "open", - ); - yield* Ref.set(continuationOffers, []); - - const capabilitiesTool = server.tools.find( - ({ tool }) => tool.name === "orchestrator_capabilities", - ); - expect(capabilitiesTool?.tool.annotations?.readOnlyHint).toBe(true); - expect(capabilitiesTool?.tool.annotations?.idempotentHint).toBe(true); - const delegateTool = server.tools.find(({ tool }) => tool.name === "delegate_task"); - expect(delegateTool?.tool.annotations?.destructiveHint).toBe(true); - expect(delegateTool?.tool.annotations?.openWorldHint).toBe(true); - const taskStatusTool = server.tools.find(({ tool }) => tool.name === "task_status"); - expect(taskStatusTool?.tool.annotations?.readOnlyHint).toBe(false); - expect(taskStatusTool?.tool.annotations?.idempotentHint).toBe(true); - const createThreadsTool = server.tools.find( - ({ tool }) => tool.name === "create_threads", - ); - expect(createThreadsTool?.tool.annotations?.destructiveHint).toBe(true); - const threadListTool = server.tools.find(({ tool }) => tool.name === "t3_thread_list"); - expect(threadListTool?.tool.annotations?.readOnlyHint).toBe(true); - expect(threadListTool?.tool.annotations?.idempotentHint).toBe(true); - const threadReadTool = server.tools.find(({ tool }) => tool.name === "t3_thread_read"); - expect(threadReadTool?.tool.annotations?.readOnlyHint).toBe(false); - expect(threadReadTool?.tool.inputSchema).toMatchObject({ additionalProperties: false }); - const unknownPagingParamError = yield* invoke("t3_thread_read", { - threadId: parentThreadId, - cursor: 90, - }).pipe(Effect.flip); - expect(unknownPagingParamError.message).toContain("Expected no excess property"); - const threadUpdateTool = server.tools.find( - ({ tool }) => tool.name === "t3_thread_update", - ); - expect(threadUpdateTool?.tool.annotations?.destructiveHint).toBe(true); - expect(threadUpdateTool?.tool.annotations?.idempotentHint).toBe(false); - expect(threadUpdateTool?.tool.inputSchema).toMatchObject({ - type: "object", - properties: { - action: expect.any(Object), - title: expect.any(Object), - pullRequest: expect.any(Object), - }, - }); - const deniedThreadUpdate = yield* invokeAs( - { ...invocation, capabilities: new Set() }, - "t3_thread_update", - { action: "rename", title: "Denied title" }, - ); - expect(declaredFailure(deniedThreadUpdate)).toMatchObject({ - _tag: "OrchestratorMcpFailure", - code: "capability_denied", - }); - const threadSendTool = server.tools.find(({ tool }) => tool.name === "t3_thread_send"); - expect(threadSendTool?.tool.annotations?.destructiveHint).toBe(true); - const threadWaitTool = server.tools.find(({ tool }) => tool.name === "t3_thread_wait"); - expect(threadWaitTool?.tool.annotations?.readOnlyHint).toBe(true); - const threadInterruptTool = server.tools.find( - ({ tool }) => tool.name === "t3_thread_interrupt", - ); - expect(threadInterruptTool?.tool.annotations?.destructiveHint).toBe(true); - - const capabilities = yield* invoke("orchestrator_capabilities", {}); - expect(capabilities.isError).toBe(false); - expect(capabilities.structuredContent).toMatchObject({ - inheritedProviderInstanceId: codexInstanceId, - inheritedModel: codexModel, - features: { - appOwnedSubagents: true, - asyncPolling: true, - cancellation: true, - batchThreadCreation: true, - threadManagement: true, - incrementalThreadRead: true, - }, - providers: expect.arrayContaining([ - expect.objectContaining({ - providerInstanceId: claudeInstanceId, - canRunCrossProviderChildTask: true, - }), - expect.objectContaining({ - providerInstanceId: "opencode", - canRunChildTask: false, - }), - expect.objectContaining({ - providerInstanceId: codexInstanceId, - models: [ - expect.objectContaining({ - id: codexModel, - options: [expect.objectContaining({ id: "reasoning", type: "select" })], - }), - ], - }), - ]), - }); - - const scheduleTool = server.tools.find(({ tool }) => tool.name === "schedule_task"); - expect(scheduleTool?.tool.annotations?.destructiveHint).toBe(true); - const scheduleCall = yield* invoke("schedule_task", { - prompt: "wake up in this thread and say hello", - schedule: { type: "interval", everyMs: 60_000 }, - clientRequestId: "schedule-hello-1", - }); - expect(scheduleCall.isError).toBe(false); - expect(scheduleCall.structuredContent).toMatchObject({ - boundThreadId: parentThreadId, - projectId, - enabled: true, - schedule: { type: "interval", everyMs: 60_000 }, - title: "wake up in this thread and say hello", - }); - const scheduledTaskId = (scheduleCall.structuredContent as { scheduledTaskId: string }) - .scheduledTaskId; - const storedAfterCreate = yield* Ref.get(scheduledStore); - expect(storedAfterCreate).toHaveLength(1); - expect(storedAfterCreate[0]).toMatchObject({ - threadId: parentThreadId, - projectId, - createdBy: "agent", - creationSource: "mcp", - modelSelection: codexSelection, - }); - - const scheduledListCall = yield* invoke("list_scheduled_tasks", {}); - expect(scheduledListCall.isError).toBe(false); - expect(scheduledListCall.structuredContent).toMatchObject({ - tasks: [{ scheduledTaskId, boundThreadId: parentThreadId }], - }); - - const scheduledUpdateCall = yield* invoke("update_scheduled_task", { - scheduledTaskId, - enabled: false, - }); - expect(scheduledUpdateCall.isError).toBe(false); - expect(scheduledUpdateCall.structuredContent).toMatchObject({ - scheduledTaskId, - enabled: false, - }); - - const scheduledDeleteCall = yield* invoke("delete_scheduled_task", { scheduledTaskId }); - expect(scheduledDeleteCall.isError).toBe(false); - expect(scheduledDeleteCall.structuredContent).toMatchObject({ - scheduledTaskId, - deleted: true, - }); - expect(yield* Ref.get(scheduledStore)).toHaveLength(0); - - // OpenCode 1.15 has emitted this exact nested-object-as-JSON-string - // shape. Decode it at the MCP boundary rather than failing a task - // the model otherwise specified correctly. - const serializedScheduleCall = yield* invoke("schedule_task", { - prompt: "check for new pull requests", - schedule: '{"type":"interval","everyMs":3600000}', - clientRequestId: "schedule-opencode-compat-1", - }); - expect(serializedScheduleCall.isError).toBe(false); - expect(serializedScheduleCall.structuredContent).toMatchObject({ - schedule: { type: "interval", everyMs: 3_600_000 }, - boundThreadId: parentThreadId, - }); - const serializedScheduledTaskId = ( - serializedScheduleCall.structuredContent as { scheduledTaskId: string } - ).scheduledTaskId; - yield* invoke("delete_scheduled_task", { - scheduledTaskId: serializedScheduledTaskId, - }); - expect(yield* Ref.get(scheduledStore)).toHaveLength(0); - - const secretRequests = yield* SecretRequests.SecretRequests; - const secretFiber = yield* invoke("request_secret", { - label: "GitHub webhook secret", - reason: "Signs release webhooks. Enter the same value in GitHub's webhook settings.", - placeholder: "Paste the webhook secret", - clientRequestId: "release-webhook-secret", - }).pipe(Effect.forkChild); - const asked = yield* Effect.gen(function* () { - while (true) { - const projection = yield* orchestrator.getThreadProjection(parentThreadId); - if ( - projection.turnItems.some( - (item) => item.type === "secret_request" && item.secretStatus === "pending", - ) - ) { - return projection; - } - yield* Effect.sleep("5 millis"); - } - }); - const card = asked.turnItems.find((item) => item.type === "secret_request"); - if (card?.type !== "secret_request") { - return yield* Effect.die(new Error("Secret request card missing.")); - } - expect(card).toMatchObject({ - label: "GitHub webhook secret", - placeholder: "Paste the webhook secret", - }); - yield* orchestrator.dispatch({ - type: "secret_request.record", - commandId: CommandId.make("command:test:secret-request-replay"), - threadId: parentThreadId, - runId: card.runId!, - nodeId: card.nodeId!, - turnItemId: card.id, - label: "Something else", - reason: "A different reason.", - secretStatus: "pending", - }); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).turnItems.find( - (item) => item.id === card.id, - ), - ).toMatchObject({ label: "GitHub webhook secret", runId: card.runId }); - expect( - (yield* orchestrator.getThreadShell(parentThreadId))?.pendingRuntimeRequest, - ).toMatchObject({ kind: "user_input" }); - expect(threadShellFromProjection(asked).pendingRuntimeRequest).toMatchObject({ - kind: "user_input", - }); - yield* secretRequests.answer({ - threadId: parentThreadId, - turnItemId: card.id, - answer: { type: "save", secret: "github-webhook-secret" }, - }); - const secretCall = yield* Fiber.join(secretFiber); - expect(secretCall.isError).toBe(false); - const secretResult = secretCall.structuredContent as { - status: string; - secretRef?: string; - }; - expect(secretResult.status).toBe("saved"); - expect( - (yield* orchestrator.getThreadShell(parentThreadId))?.pendingRuntimeRequest ?? null, - ).toBeNull(); - expect(secretResult.secretRef).toMatch(/^secret-ref:[0-9a-f]{32}$/); - const received = [ - ...secretCall.content.map((part) => ("text" in part ? part.text : "")), - ...Object.values(secretResult), - ]; - expect(received.some((value) => value.includes("github-webhook-secret"))).toBe(false); - - const retried = yield* invoke("request_secret", { - label: "GitHub webhook secret", - reason: "Signs release webhooks. Enter the same value in GitHub's webhook settings.", - clientRequestId: "release-webhook-secret", - }); - expect(retried.structuredContent).toEqual(secretResult); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).turnItems.filter( - (item) => item.type === "secret_request", - ), - ).toHaveLength(1); - - expect( - yield* secretRequests.consume({ - ref: secretResult.secretRef as never, - projectId, - }), - ).toBe("github-webhook-secret"); - const reused = yield* secretRequests - .consume({ ref: secretResult.secretRef as never, projectId }) - .pipe(Effect.flip); - expect(reused.message).toContain("already used"); - - const delegatedCall = yield* invoke("delegate_task", { - task: delegatedPrompt, - target: { - providerInstanceId: claudeInstanceId, - model: claudeModel, - }, - mode: "wait", - timeoutMs: 10_000, - clientRequestId: "delegate-claude-1", - }); - expect(delegatedCall.isError).toBe(false); - const delegated = yield* decodeDelegateTaskResult(delegatedCall.structuredContent).pipe( - Effect.orDie, - ); - const delegatedSource = yield* orchestrator.getThreadProjection( - delegated.childThreadId, - ); - expect(delegatedSource.messages[0]).toMatchObject({ - senderThreadId: parentThreadId, - }); - expect( - delegatedSource.turnItems.find((item) => item.type === "user_message"), - ).toMatchObject({ - senderThreadId: parentThreadId, - }); - expect(delegated.status).toBe("completed"); - expect(delegated.summary).toBe(delegatedResult); - expect(delegated.providerInstanceId).toBe(claudeInstanceId); - - const completedParent = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.subagents.some( - (task) => - task.id === delegated.taskId && - task.status === "completed" && - task.result === delegatedResult, - ) && - projection.contextTransfers.some( - (transfer) => - transfer.type === "subagent_result" && - transfer.sourceThreadId === delegated.childThreadId, - ), - ); - const completedTask = completedParent.subagents.find( - (task) => task.id === delegated.taskId, - ); - expect(completedTask).toMatchObject({ - origin: "app_owned", - createdBy: "agent", - childThreadId: delegated.childThreadId, - status: "completed", - result: delegatedResult, - }); - const child = yield* orchestrator.getThreadProjection(delegated.childThreadId); - expect(child.thread.lineage).toEqual({ - parentThreadId, - relationshipToParent: "subagent", - rootThreadId: parentThreadId, - }); - expect(child.thread).toMatchObject({ - createdBy: "agent", - creationSource: "mcp", - }); - expect(child.thread.modelSelection).toEqual(claudeSelection); - expect( - child.messages - .filter((message) => message.role === "user") - .map((message) => message.text), - ).toEqual([delegatedPrompt]); - expect( - child.contextTransfers.some( - (transfer) => - transfer.type === "subagent_spawn" && transfer.sourceThreadId === parentThreadId, - ), - ).toBe(true); - const capturedAfterDelegate = yield* Ref.get(capturedTurns); - expect( - capturedAfterDelegate.filter((turn) => turn.threadId === delegated.childThreadId), - ).toEqual([ - { - instanceId: claudeInstanceId, - threadId: delegated.childThreadId, - text: delegatedPrompt, - }, - ]); - expect( - capturedAfterDelegate.some( - (turn) => - turn.threadId === delegated.childThreadId && turn.text.includes(parentPrompt), - ), - ).toBe(false); - - const delegatedStatusCall = yield* invoke("task_status", { - taskId: delegated.taskId, - }); - const delegatedStatus = yield* decodeDelegateTaskResult( - delegatedStatusCall.structuredContent, - ).pipe(Effect.orDie); - expect(delegatedStatus).toMatchObject({ - childRunId: delegated.childRunId, - status: "completed", - hasPendingChildRuns: false, - latestTerminalRunId: delegated.childRunId, - latestTerminalStatus: "completed", - latestTerminalSummary: delegatedResult, - }); - expect(delegatedStatus.resultContextTransferId).not.toBeNull(); - expect(delegatedStatus.latestTerminalResultContextTransferId).not.toBeNull(); - - yield* expectOffersToStay(0); - - const childFollowupCall = yield* invoke("t3_thread_send", { - threadId: delegated.childThreadId, - message: "Confirm the delegated API boundary remains inspected.", - clientRequestId: "delegated-child-followup-1", - }); - const childFollowup = yield* decodeThreadSendResult( - childFollowupCall.structuredContent, - ).pipe(Effect.orDie); - const childFollowupWaitCall = yield* invoke("t3_thread_wait", { - threadId: delegated.childThreadId, - runId: childFollowup.runId, - timeoutMs: 10_000, - }); - const childFollowupWait = yield* decodeThreadWaitResult( - childFollowupWaitCall.structuredContent, - ).pipe(Effect.orDie); - expect(childFollowupWait).toMatchObject({ - runId: childFollowup.runId, - status: "completed", - timedOut: false, - }); - const delegatedStatusAfterFollowupCall = yield* invoke("task_status", { - taskId: delegated.taskId, - }); - const delegatedStatusAfterFollowup = yield* decodeDelegateTaskResult( - delegatedStatusAfterFollowupCall.structuredContent, - ).pipe(Effect.orDie); - expect(delegatedStatusAfterFollowup).toMatchObject({ - childRunId: delegated.childRunId, - status: "completed", - summary: delegatedResult, - hasPendingChildRuns: false, - latestTerminalRunId: childFollowup.runId, - latestTerminalStatus: "completed", - }); - expect(delegatedStatusAfterFollowup.latestTerminalSummary).not.toBeNull(); - - const activeChildFollowupCall = yield* invoke("t3_thread_send", { - threadId: delegated.childThreadId, - message: cancellationPrompt, - clientRequestId: "delegated-child-active-followup-1", - }); - const activeChildFollowup = yield* decodeThreadSendResult( - activeChildFollowupCall.structuredContent, - ).pipe(Effect.orDie); - yield* waitForProjection(orchestrator, delegated.childThreadId, (projection) => - projection.runs.some( - (run) => run.id === activeChildFollowup.runId && run.status === "running", - ), - ); - const delegatedStatusDuringFollowupCall = yield* invoke("task_status", { - taskId: delegated.taskId, - }); - const delegatedStatusDuringFollowup = yield* decodeDelegateTaskResult( - delegatedStatusDuringFollowupCall.structuredContent, - ).pipe(Effect.orDie); - expect(delegatedStatusDuringFollowup).toMatchObject({ - childRunId: delegated.childRunId, - status: "completed", - summary: delegatedResult, - hasPendingChildRuns: true, - latestTerminalRunId: childFollowup.runId, - latestTerminalStatus: "completed", - }); - const activeChildProjection = yield* orchestrator.getThreadProjection( - delegated.childThreadId, - ); - const legacyChildProjection = { - ...activeChildProjection, - contextTransfers: activeChildProjection.contextTransfers.filter( - (transfer) => transfer.type !== "subagent_spawn", - ), - }; - const legacyDelegatedRun = delegatedTaskRun(legacyChildProjection, completedTask!); - expect(legacyDelegatedRun?.id).toBe(delegated.childRunId); - expect(hasPendingChildRuns(legacyChildProjection, legacyDelegatedRun)).toBe(true); - expect( - hasPendingChildRuns( - { - ...legacyChildProjection, - runs: legacyChildProjection.runs.map((run) => - run.id === activeChildFollowup.runId ? { ...run, status: "queued" } : run, - ), - }, - legacyDelegatedRun, - ), - ).toBe(true); - expect( - hasPendingChildRuns( - { - ...legacyChildProjection, - runs: legacyChildProjection.runs.map((run) => - run.id === activeChildFollowup.runId - ? { ...run, status: "queued", queueHeld: true } - : run, - ), - }, - legacyDelegatedRun, - ), - ).toBe(false); - const completedTaskCancelCall = yield* invoke("task_cancel", { - taskId: delegated.taskId, - reason: "Stop the child's later work too.", - clientRequestId: "cancel-completed-delegated-task-1", - }); - const completedTaskCancel = yield* decodeTaskCancelResult( - completedTaskCancelCall.structuredContent, - ).pipe(Effect.orDie); - expect(completedTaskCancel).toEqual({ - taskId: delegated.taskId, - status: "completed", - }); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === delegated.taskId, - ), - ).toMatchObject({ - result: delegatedResult, - completionDelivery: { state: "disposed" }, - }); - yield* waitForProjection(orchestrator, delegated.childThreadId, (projection) => - projection.runs.some( - (run) => run.id === activeChildFollowup.runId && run.status === "interrupted", - ), - ); - const delegatedStatusAfterCancelCall = yield* invoke("task_status", { - taskId: delegated.taskId, - }); - const delegatedStatusAfterCancel = yield* decodeDelegateTaskResult( - delegatedStatusAfterCancelCall.structuredContent, - ).pipe(Effect.orDie); - expect(delegatedStatusAfterCancel).toMatchObject({ - childRunId: delegated.childRunId, - status: "completed", - summary: delegatedResult, - hasPendingChildRuns: false, - latestTerminalRunId: activeChildFollowup.runId, - latestTerminalStatus: "interrupted", - }); - - expect(childFollowup.taskId).toBeDefined(); - expect(activeChildFollowup.taskId).toBeDefined(); - yield* waitForContinuationOffers(2); - yield* expectOffersToStay(2); - yield* invoke("task_status", { taskId: childFollowup.taskId }); - yield* invoke("task_status", { taskId: activeChildFollowup.taskId }); - yield* Ref.set(continuationOffers, []); - - // A send into a child run the server started has no task to join. - // It gets its own task only when it starts a new attempt; a steer - // into the running attempt leaves no run that could settle one. - const childSteerText = "Include the parent's latest guidance before finishing."; - const steerIntoUntaskedChildRun = ( - target: { readonly providerInstanceId: ProviderInstanceId; readonly model: string }, - name: string, - ) => - Effect.gen(function* () { - const delegateCall = yield* invoke("delegate_task", { - task: "Inspect the steering boundary and return the result.", - target, - mode: "wait", - timeoutMs: 10_000, - clientRequestId: `${name}-delegate`, - }); - const child = yield* decodeDelegateTaskResult(delegateCall.structuredContent).pipe( - Effect.orDie, - ); - expect(child.status).toBe("completed"); - const messageId = MessageId.make(`message:mcp-child:${name}`); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make(`command:mcp-child:${name}`), - threadId: child.childThreadId, - messageId, - text: cancellationPrompt, - attachments: [], - modelSelection: { instanceId: target.providerInstanceId, model: target.model }, - dispatchMode: { type: "start_immediately" }, - }); - const running = yield* waitForProjection( - orchestrator, - child.childThreadId, - (projection) => { - const run = projection.runs.find((row) => row.userMessageId === messageId); - return ( - run?.status === "running" && - projection.providerTurns.some( - (turn) => turn.nodeId === run.rootNodeId && turn.status === "running", - ) - ); - }, - ); - const run = running.runs.find((row) => row.userMessageId === messageId)!; - expect(run.delegatedTaskId).toBeUndefined(); - const sendCall = yield* invoke("t3_thread_send", { - threadId: child.childThreadId, - message: childSteerText, - mode: "steer", - clientRequestId: `${name}-steer`, - }); - const sent = yield* decodeThreadSendResult(sendCall.structuredContent).pipe( - Effect.orDie, - ); - expect(sent).toMatchObject({ runId: run.id, delivery: "steered" }); - return { child, sent }; - }); - const waitForChildRun = ( - childThreadId: ThreadId, - runId: string, - status: "completed" | "interrupted", - ) => - waitForProjection(orchestrator, childThreadId, (projection) => - projection.runs.some((run) => run.id === runId && run.status === status), - ); - - // Claude steers into the running turn, which then ends. - const steerReceived = yield* Deferred.make(); - steerReceivedGates.set(childSteerText, steerReceived); - const steeredSend = yield* steerIntoUntaskedChildRun( - { providerInstanceId: claudeInstanceId, model: claudeModel }, - "steer-untasked-run", - ); - // A steer that misses the turn is sent again as its own run, so - // end the turn only once the steer reached it. - yield* Deferred.await(steerReceived); - steerReceivedGates.delete(childSteerText); - yield* invoke("t3_thread_interrupt", { - threadId: steeredSend.child.childThreadId, - runId: steeredSend.sent.runId, - clientRequestId: "steer-untasked-run-interrupt", - }); - yield* waitForChildRun( - steeredSend.child.childThreadId, - steeredSend.sent.runId, - "interrupted", - ); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.filter( - (task) => - task.origin === "app_owned" && - task.childThreadId === steeredSend.child.childThreadId && - task.status === "running", - ), - ).toEqual([]); - expect(steeredSend.sent.taskId).toBeUndefined(); - - // This Codex session has active steering off, so the send restarts the - // turn as a new attempt that owns the follow-up task and settles it. - const restarted = yield* steerIntoUntaskedChildRun( - { providerInstanceId: codexInstanceId, model: codexModel }, - "restart-untasked-run", - ); - const restartedTaskId = restarted.sent.taskId; - expect(restartedTaskId).toBeDefined(); - yield* waitForChildRun( - restarted.child.childThreadId, - restarted.sent.runId, - "completed", - ); - yield* waitForProjection(orchestrator, parentThreadId, (projection) => - projection.subagents.some( - (task) => task.id === restartedTaskId && task.status === "completed", - ), - ); - expect( - (yield* orchestrator.getThreadProjection(restarted.child.childThreadId)).runs.find( - (run) => run.id === restarted.sent.runId, - )?.delegatedTaskId, - ).toBe(restartedTaskId); - yield* invoke("task_status", { taskId: steeredSend.child.taskId }); - yield* invoke("task_status", { taskId: restarted.child.taskId }); - yield* invoke("task_status", { taskId: restartedTaskId }); - yield* Ref.set(continuationOffers, []); - - const repeatedDelegatedCall = yield* invoke("delegate_task", { - task: delegatedPrompt, - target: { - providerInstanceId: claudeInstanceId, - model: claudeModel, - }, - mode: "async", - clientRequestId: "delegate-claude-1", - }); - const repeatedDelegated = yield* decodeDelegateTaskResult( - repeatedDelegatedCall.structuredContent, - ).pipe(Effect.orDie); - expect(repeatedDelegated.taskId).toBe(delegated.taskId); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.filter( - (task) => task.id === delegated.taskId, - ), - ).toHaveLength(1); - - const rejectedOptionsCall = yield* invoke("delegate_task", { - task: cancellationPrompt, - target: { - providerInstanceId: codexInstanceId, - model: codexModel, - options: { reasoning: "extreme" }, - }, - mode: "async", - clientRequestId: "delegate-rejected-options-1", - }); - expect(declaredFailure(rejectedOptionsCall)).toMatchObject({ - _tag: "OrchestratorMcpFailure", - code: "invalid_request", - message: expect.stringContaining("rejected options"), - }); - - const duplicateOptionsCall = yield* invoke("delegate_task", { - task: cancellationPrompt, - target: { - providerInstanceId: codexInstanceId, - model: codexModel, - options: [ - { id: "reasoning", value: "low" }, - { id: "reasoning", value: "high" }, - ], - }, - mode: "async", - clientRequestId: "delegate-duplicate-options-1", - }); - expect(declaredFailure(duplicateOptionsCall)).toMatchObject({ - _tag: "OrchestratorMcpFailure", - code: "invalid_request", - message: expect.stringContaining("more than once"), - }); - - const cancellableCall = yield* invoke("delegate_task", { - task: cancellationPrompt, - target: { - providerInstanceId: codexInstanceId, - model: codexModel, - options: { reasoning: "low" }, - }, - mode: "async", - clientRequestId: "delegate-cancel-1", - }); - const cancellable = yield* decodeDelegateTaskResult( - cancellableCall.structuredContent, - ).pipe(Effect.orDie); - expect(cancellable.status).toBe("running"); - expect(cancellable.hasPendingChildRuns).toBe(false); - yield* waitForProjection(orchestrator, cancellable.childThreadId, (projection) => - projection.providerTurns.some((turn) => turn.status === "running"), - ); - const statusWhileOriginalRunningCall = yield* invoke("task_status", { - taskId: cancellable.taskId, - }); - const statusWhileOriginalRunning = yield* decodeDelegateTaskResult( - statusWhileOriginalRunningCall.structuredContent, - ).pipe(Effect.orDie); - expect(statusWhileOriginalRunning).toMatchObject({ - childRunId: cancellable.childRunId, - status: "running", - hasPendingChildRuns: false, - latestTerminalRunId: null, - latestTerminalStatus: null, - }); - const optionedChild = yield* orchestrator.getThreadProjection( - cancellable.childThreadId, - ); - expect(optionedChild.thread.modelSelection).toEqual({ - instanceId: codexInstanceId, - model: codexModel, - options: [{ id: "reasoning", value: "low" }], - }); - const cancelCall = yield* invoke("task_cancel", { - taskId: cancellable.taskId, - reason: "Parent no longer needs this work.", - clientRequestId: "cancel-1", - }); - const cancelResult = yield* decodeTaskCancelResult(cancelCall.structuredContent).pipe( - Effect.orDie, - ); - expect(cancelResult.status).toBe("cancel_requested"); - yield* waitForProjection(orchestrator, cancellable.childThreadId, (projection) => - projection.runs.some((run) => run.status === "interrupted"), - ); - const cancelledStatusCall = yield* invoke("task_status", { - taskId: cancellable.taskId, - }); - const cancelledStatus = yield* decodeDelegateTaskResult( - cancelledStatusCall.structuredContent, - ).pipe(Effect.orDie); - expect(cancelledStatus.status).toBe("interrupted"); - - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === cancellable.taskId, - )?.completionDelivery, - ).toMatchObject({ state: "disposed" }); - yield* expectOffersToStay(0); - - const createInput = { - clientRequestId: "create-thread-batch-1", - threads: [ - { - title: "Inherited empty thread", - }, - { - title: "Claude ordinary thread", - prompt: createdThreadPrompt, - target: { - driverKind: "claudeAgent", - }, - }, - ], - }; - const createCall = yield* invoke("create_threads", createInput); - expect(createCall.isError).toBe(false); - const created = yield* decodeCreateThreadsResult(createCall.structuredContent).pipe( - Effect.orDie, - ); - expect(created.threads).toHaveLength(2); - const emptyThread = created.threads[0]!; - const promptedThread = created.threads[1]!; - expect(emptyThread).toMatchObject({ - status: "idle", - createdBy: "agent", - creationSource: "mcp", - providerInstanceId: codexInstanceId, - model: codexModel, - }); - expect(promptedThread).toMatchObject({ - createdBy: "agent", - creationSource: "mcp", - providerInstanceId: claudeInstanceId, - model: claudeModel, - }); - const createdSource = yield* orchestrator.getThreadProjection(promptedThread.threadId); - expect(createdSource.messages[0]).toMatchObject({ - senderThreadId: parentThreadId, - }); - expect( - createdSource.turnItems.find((item) => item.type === "user_message"), - ).toMatchObject({ - senderThreadId: parentThreadId, - }); - const emptyProjection = yield* orchestrator.getThreadProjection(emptyThread.threadId); - expect(emptyProjection.thread.lineage).toEqual({ - parentThreadId: null, - relationshipToParent: null, - rootThreadId: emptyThread.threadId, - }); - expect(emptyProjection.thread).toMatchObject({ - createdBy: "agent", - creationSource: "mcp", - }); - expect(emptyProjection.thread.forkedFrom).toBeNull(); - expect(emptyProjection.runs).toEqual([]); - - const defaultRenameCall = yield* invoke("t3_thread_update", { - action: "rename", - title: "MCP parent metadata", - clientRequestId: "metadata-default-thread-1", - }); - const defaultRenamed = yield* decodeThreadUpdateResult( - defaultRenameCall.structuredContent, - ).pipe(Effect.orDie); - expect(defaultRenamed).toMatchObject({ - threadId: parentThreadId, - action: "rename", - title: "MCP parent metadata", - }); - - const renameCall = yield* invoke("t3_thread_update", { - threadId: emptyThread.threadId, - action: "rename", - title: "Metadata-managed thread", - clientRequestId: "metadata-rename-1", - }); - const renamed = yield* decodeThreadUpdateResult(renameCall.structuredContent).pipe( - Effect.orDie, - ); - expect(renamed).toMatchObject({ - threadId: emptyThread.threadId, - action: "rename", - title: "Metadata-managed thread", - linkedPullRequest: null, - }); - const repeatedRenameCall = yield* invoke("t3_thread_update", { - threadId: emptyThread.threadId, - action: "rename", - title: "Metadata-managed thread", - clientRequestId: "metadata-rename-1", - }); - const repeatedRename = yield* decodeThreadUpdateResult( - repeatedRenameCall.structuredContent, - ).pipe(Effect.orDie); - expect(repeatedRename.commandId).toBe(renamed.commandId); - expect(repeatedRename.sequence).toBe(renamed.sequence); - - const linkedCall = yield* invoke("t3_thread_update", { - threadId: emptyThread.threadId, - action: "link_pull_request", - pullRequest: { - repository: "pingdotgg/t3code", - number: 8689, - url: "https://github.com/pingdotgg/t3code/pull/8689", - }, - clientRequestId: "metadata-link-1", - }); - const linked = yield* decodeThreadUpdateResult(linkedCall.structuredContent).pipe( - Effect.orDie, - ); - expect(linked.linkedPullRequest).toEqual({ - projectId, - repository: "pingdotgg/t3code", - number: 8689, - url: "https://github.com/pingdotgg/t3code/pull/8689", - }); - const metadataReadCall = yield* invoke("t3_thread_read", { - threadId: emptyThread.threadId, - }); - const metadataRead = yield* decodeThreadReadResult( - metadataReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(metadataRead.thread).toMatchObject({ - title: "Metadata-managed thread", - linkedPullRequest: linked.linkedPullRequest, - }); - const metadataListCall = yield* invoke("t3_thread_list", { limit: 100 }); - const metadataList = yield* decodeThreadListResult( - metadataListCall.structuredContent, - ).pipe(Effect.orDie); - expect( - metadataList.threads.find((thread) => thread.threadId === emptyThread.threadId), - ).toMatchObject({ - title: "Metadata-managed thread", - linkedPullRequest: linked.linkedPullRequest, - settled: false, - settledAt: null, - }); - expect(metadataRead.thread).toMatchObject({ settled: false, settledAt: null }); - - yield* orchestrator.dispatch({ - type: "thread.settle", - commandId: CommandId.make("command:mcp-empty:settle"), - threadId: emptyThread.threadId, - settledAt: DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"), - }); - const settledReadCall = yield* invoke("t3_thread_read", { - threadId: emptyThread.threadId, - }); - const settledRead = yield* decodeThreadReadResult( - settledReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(settledRead.thread).toMatchObject({ - settled: true, - settledAt: "2026-01-01T00:00:00.000Z", - }); - const settledListCall = yield* invoke("t3_thread_list", { settled: true, limit: 100 }); - const settledList = yield* decodeThreadListResult( - settledListCall.structuredContent, - ).pipe(Effect.orDie); - expect(settledList.threads.map((thread) => thread.threadId)).toEqual([ - emptyThread.threadId, - ]); - expect(settledList.threads[0]).toMatchObject({ - settled: true, - settledAt: "2026-01-01T00:00:00.000Z", - }); - const activeListCall = yield* invoke("t3_thread_list", { settled: false, limit: 100 }); - const activeList = yield* decodeThreadListResult(activeListCall.structuredContent).pipe( - Effect.orDie, - ); - expect( - activeList.threads.some((thread) => thread.threadId === emptyThread.threadId), - ).toBe(false); - yield* orchestrator.dispatch({ - type: "thread.unsettle", - commandId: CommandId.make("command:mcp-empty:unsettle"), - threadId: emptyThread.threadId, - reason: "user", - }); - - expect(metadataRead.thread).toMatchObject({ snoozed: false, snoozedUntil: null }); - yield* orchestrator.dispatch({ - type: "thread.snooze", - commandId: CommandId.make("command:mcp-empty:snooze"), - threadId: emptyThread.threadId, - snoozedUntil: "2099-01-01T00:00:00.000Z", - }); - const snoozedListCall = yield* invoke("t3_thread_list", { snoozed: true, limit: 100 }); - const snoozedList = yield* decodeThreadListResult( - snoozedListCall.structuredContent, - ).pipe(Effect.orDie); - expect(snoozedList.threads.map((thread) => thread.threadId)).toEqual([ - emptyThread.threadId, - ]); - expect(snoozedList.threads[0]).toMatchObject({ - snoozed: true, - snoozedUntil: "2099-01-01T00:00:00.000Z", - }); - const snoozedReadCall = yield* invoke("t3_thread_read", { - threadId: emptyThread.threadId, - }); - const snoozedRead = yield* decodeThreadReadResult( - snoozedReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(snoozedRead.thread).toMatchObject({ - snoozed: true, - snoozedUntil: "2099-01-01T00:00:00.000Z", - }); - yield* orchestrator.dispatch({ - type: "thread.unsnooze", - commandId: CommandId.make("command:mcp-empty:unsnooze"), - threadId: emptyThread.threadId, - reason: "user", - }); - - const unlinkedCall = yield* invoke("t3_thread_update", { - threadId: emptyThread.threadId, - action: "unlink_pull_request", - clientRequestId: "metadata-unlink-1", - }); - const unlinked = yield* decodeThreadUpdateResult(unlinkedCall.structuredContent).pipe( - Effect.orDie, - ); - expect(unlinked.linkedPullRequest).toBeNull(); - - const regenerateCall = yield* invoke("t3_thread_update", { - threadId: emptyThread.threadId, - action: "regenerate_title", - clientRequestId: "metadata-regenerate-title-1", - }); - const regenerating = yield* decodeThreadUpdateResult( - regenerateCall.structuredContent, - ).pipe(Effect.orDie); - expect(regenerating).toMatchObject({ - threadId: emptyThread.threadId, - action: "regenerate_title", - titleRegeneration: { requestId: regenerating.commandId }, - }); - const promptedProjection = yield* waitForProjection( - orchestrator, - promptedThread.threadId, - (projection) => projection.runs.some((run) => run.status === "completed"), - ); - expect(promptedProjection.thread.lineage.parentThreadId).toBeNull(); - expect( - promptedProjection.messages - .filter((message) => message.role === "user") - .map((message) => message.text), - ).toEqual([createdThreadPrompt]); - const createdThreadItems = (yield* orchestrator.getThreadProjection( - parentThreadId, - )).visibleTurnItems - .map((row) => row.item) - .filter((item) => item.type === "thread_created"); - expect( - createdThreadItems.map((item) => ({ - targetThreadId: item.targetThreadId, - targetRunId: item.targetRunId, - title: item.title, - providerInstanceId: item.targetProviderInstanceId, - model: item.targetModel, - })), - ).toEqual([ - { - targetThreadId: emptyThread.threadId, - targetRunId: null, - title: emptyThread.title, - providerInstanceId: codexInstanceId, - model: codexModel, - }, - { - targetThreadId: promptedThread.threadId, - targetRunId: promptedThread.runId, - title: promptedThread.title, - providerInstanceId: claudeInstanceId, - model: claudeModel, - }, - ]); - - const repeatedCreateCall = yield* invoke("create_threads", createInput); - const repeatedCreated = yield* decodeCreateThreadsResult( - repeatedCreateCall.structuredContent, - ).pipe(Effect.orDie); - expect(repeatedCreated.threads.map((thread) => thread.threadId)).toEqual( - created.threads.map((thread) => thread.threadId), - ); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).visibleTurnItems.filter( - (row) => { - if (row.item.type !== "thread_created") return false; - const targetThreadId = row.item.targetThreadId; - return created.threads.some((thread) => thread.threadId === targetThreadId); - }, - ), - ).toHaveLength(2); - - const promptedReadCall = yield* invoke("t3_thread_read", { - threadId: promptedThread.threadId, - limit: 1, - }); - const promptedRead = yield* decodeThreadReadResult( - promptedReadCall.structuredContent, - ).pipe(Effect.orDie); - expect(promptedRead.thread.status).toBe("completed"); - expect(promptedRead.thread).toMatchObject({ - createdBy: "agent", - creationSource: "mcp", - }); - expect(promptedRead.items.map((item) => item.type)).toEqual(["user_message"]); - expect(promptedRead.items[0]).toMatchObject({ - createdBy: "agent", - creationSource: "mcp", - }); - expect(promptedRead.hasMore).toBe(true); - const promptedReadNextCall = yield* invoke("t3_thread_read", { - threadId: promptedThread.threadId, - afterPosition: promptedRead.nextPosition, - limit: 1, - }); - const promptedReadNext = yield* decodeThreadReadResult( - promptedReadNextCall.structuredContent, - ).pipe(Effect.orDie); - expect(promptedReadNext.items.map((item) => item.type)).toEqual(["assistant_message"]); - expect(promptedReadNext.items[0]?.text).toBe( - `Claude completed: ${createdThreadPrompt}`, - ); - - const forkedThreadId = ThreadId.make("thread:mcp-orchestrator-inherited-read"); - yield* orchestrator.dispatch({ - type: "thread.fork", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-orchestrator-inherited-read"), - sourceThreadId: promptedThread.threadId, - targetThreadId: forkedThreadId, - sourcePoint: { type: "latest_stable" }, - title: "Inherited read thread", - }); - const forkedProjection = yield* orchestrator.getThreadProjection(forkedThreadId); - expect(forkedProjection.messages).toEqual([]); - expect( - forkedProjection.visibleTurnItems.some( - (row) => - row.sourceThreadId === promptedThread.threadId && - row.item.type === "user_message", - ), - ).toBe(true); - - const forkedReadCall = yield* invoke("t3_thread_read", { - threadId: forkedThreadId, - }); - const forkedRead = yield* decodeThreadReadResult(forkedReadCall.structuredContent).pipe( - Effect.orDie, - ); - expect( - forkedRead.items.find((item) => item.text === createdThreadPrompt), - ).toMatchObject({ - sourceThreadId: promptedThread.threadId, - createdBy: "agent", - creationSource: "mcp", - }); - - const ordinaryLoopPrompt = "Run an ordinary thread loop iteration."; - const sendCall = yield* invoke("t3_thread_send", { - threadId: emptyThread.threadId, - message: ordinaryLoopPrompt, - clientRequestId: "ordinary-loop-send-1", - }); - const sent = yield* decodeThreadSendResult(sendCall.structuredContent).pipe( - Effect.orDie, - ); - const sentSource = yield* orchestrator.getThreadProjection(emptyThread.threadId); - expect( - sentSource.messages.find((message) => message.id === sent.messageId), - ).toMatchObject({ - senderThreadId: parentThreadId, - }); - expect( - sentSource.turnItems.find( - (item) => item.type === "user_message" && item.messageId === sent.messageId, - ), - ).toMatchObject({ - senderThreadId: parentThreadId, - }); - expect(sent.delivery).toBe("started"); - const waitCall = yield* invoke("t3_thread_wait", { - threadId: emptyThread.threadId, - runId: sent.runId, - timeoutMs: 10_000, - }); - const waited = yield* decodeThreadWaitResult(waitCall.structuredContent).pipe( - Effect.orDie, - ); - expect(waited).toMatchObject({ - runId: sent.runId, - status: "completed", - timedOut: false, - }); - const repeatedSendCall = yield* invoke("t3_thread_send", { - threadId: emptyThread.threadId, - message: ordinaryLoopPrompt, - clientRequestId: "ordinary-loop-send-1", - }); - const repeatedSend = yield* decodeThreadSendResult( - repeatedSendCall.structuredContent, - ).pipe(Effect.orDie); - expect(repeatedSend.runId).toBe(sent.runId); - expect( - (yield* orchestrator.getThreadProjection(emptyThread.threadId)).runs, - ).toHaveLength(1); - - const activeThreadCall = yield* invoke("create_threads", { - threads: [{ prompt: cancellationPrompt, title: "Managed active thread" }], - clientRequestId: "managed-active-thread-1", - }); - const activeThread = (yield* decodeCreateThreadsResult( - activeThreadCall.structuredContent, - ).pipe(Effect.orDie)).threads[0]!; - const activeThreadItem = (yield* orchestrator.getThreadProjection( - parentThreadId, - )).visibleTurnItems - .map((row) => row.item) - .find( - (item) => - item.type === "thread_created" && item.targetThreadId === activeThread.threadId, - ); - expect(activeThreadItem).toMatchObject({ - type: "thread_created", - title: "Managed active thread", - targetThreadId: activeThread.threadId, - targetRunId: activeThread.runId, - targetProviderInstanceId: codexInstanceId, - targetModel: codexModel, - }); - const activeProjection = yield* waitForProjection( - orchestrator, - activeThread.threadId, - (projection) => - projection.runs.some((run) => run.status === "running") && - projection.providerTurns.some((turn) => turn.status === "running"), - ); - const activeRun = activeProjection.runs[0]!; - const activeTimeoutCall = yield* invoke("t3_thread_wait", { - threadId: activeThread.threadId, - runId: activeRun.id, - timeoutMs: 1, - }); - const activeTimeout = yield* decodeThreadWaitResult( - activeTimeoutCall.structuredContent, - ).pipe(Effect.orDie); - expect(activeTimeout).toMatchObject({ - runId: activeRun.id, - status: "running", - timedOut: true, - }); - const steerCall = yield* invoke("t3_thread_send", { - threadId: activeThread.threadId, - message: "Include the latest parent guidance before finishing.", - mode: "steer", - clientRequestId: "managed-active-steer-1", - }); - const steered = yield* decodeThreadSendResult(steerCall.structuredContent).pipe( - Effect.orDie, - ); - expect(steered).toMatchObject({ - runId: activeRun.id, - delivery: "steered", - }); - const steeredSource = yield* orchestrator.getThreadProjection(activeThread.threadId); - expect( - steeredSource.messages.find((message) => message.id === steered.messageId), - ).toMatchObject({ - senderThreadId: parentThreadId, - }); - expect( - steeredSource.turnItems.find( - (item) => item.type === "user_message" && item.messageId === steered.messageId, - ), - ).toMatchObject({ - senderThreadId: parentThreadId, - }); - const interruptCall = yield* invoke("t3_thread_interrupt", { - threadId: activeThread.threadId, - reason: "The orchestration loop has enough evidence.", - clientRequestId: "managed-active-interrupt-1", - }); - const interrupted = yield* decodeThreadInterruptResult( - interruptCall.structuredContent, - ).pipe(Effect.orDie); - expect(interrupted).toMatchObject({ - runId: activeRun.id, - status: "interrupt_requested", - }); - const interruptedWaitCall = yield* invoke("t3_thread_wait", { - threadId: activeThread.threadId, - runId: activeRun.id, - timeoutMs: 10_000, - }); - const interruptedWait = yield* decodeThreadWaitResult( - interruptedWaitCall.structuredContent, - ).pipe(Effect.orDie); - expect(interruptedWait.status).toBe("interrupted"); - const repeatedInterruptCall = yield* invoke("t3_thread_interrupt", { - threadId: activeThread.threadId, - runId: activeRun.id, - }); - const repeatedInterrupt = yield* decodeThreadInterruptResult( - repeatedInterruptCall.structuredContent, - ).pipe(Effect.orDie); - expect(repeatedInterrupt.status).toBe("interrupted"); - - const foreignThreadId = ThreadId.make("thread:mcp-foreign-project"); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-foreign-project:create"), - threadId: foreignThreadId, - projectId: ProjectId.make("project:mcp-foreign"), - title: "Foreign project thread", - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - }); - const foreignOrganizeCall = yield* invoke("t3_thread_organize", { - threadId: foreignThreadId, - action: "pin", - }); - expect(foreignOrganizeCall.isError).toBe(false); - expect((yield* orchestrator.getThreadShell(foreignThreadId))?.pinnedAt).not.toBeNull(); - - const foreignReadCall = yield* invoke("t3_thread_read", { - threadId: foreignThreadId, - }); - expect(foreignReadCall.structuredContent).toMatchObject({ - thread: { threadId: foreignThreadId, projectId: "project:mcp-foreign" }, - }); - const foreignUpdateCall = yield* invoke("t3_thread_update", { - threadId: foreignThreadId, - action: "rename", - title: "Renamed from another project", - }); - expect(foreignUpdateCall.structuredContent).toMatchObject({ - threadId: foreignThreadId, - title: "Renamed from another project", - }); - const foreignListCall = yield* invoke("t3_thread_list", { - projectId: "project:mcp-foreign", - }); - const foreignListed = yield* decodeThreadListResult( - foreignListCall.structuredContent, - ).pipe(Effect.orDie); - expect(foreignListed.threads.map((thread) => thread.threadId)).toEqual([ - foreignThreadId, - ]); - const listCall = yield* invoke("t3_thread_list", { - includeSubagents: false, - limit: 100, - }); - const listed = yield* decodeThreadListResult(listCall.structuredContent).pipe( - Effect.orDie, - ); - expect(listed.projectId).toBe(projectId); - expect(listed.threads.map((thread) => thread.threadId)).toEqual( - expect.arrayContaining([ - parentThreadId, - emptyThread.threadId, - promptedThread.threadId, - activeThread.threadId, - ]), - ); - expect( - listed.threads.find((thread) => thread.threadId === emptyThread.threadId), - ).toMatchObject({ - createdBy: "agent", - creationSource: "mcp", - }); - expect(listed.threads.some((thread) => thread.threadId === foreignThreadId)).toBe( - false, - ); - expect( - listed.threads.some((thread) => thread.relationshipToParent === "subagent"), - ).toBe(false); - - const upgradedCall = yield* invoke("delegate_task", { - task: cancellationPrompt, - target: { - providerInstanceId: codexInstanceId, - model: codexModel, - }, - mode: "wait", - timeoutMs: 1, - clientRequestId: "delegate-wait-upgrade-1", - }); - const upgradedDelegated = yield* decodeDelegateTaskResult( - upgradedCall.structuredContent, - ).pipe(Effect.orDie); - expect(upgradedDelegated.status).toBe("running"); - yield* waitForProjection(orchestrator, upgradedDelegated.childThreadId, (projection) => - projection.providerTurns.some((turn) => turn.status === "running"), - ); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === upgradedDelegated.taskId, - )?.completionWake, - ).toBe("always"); - const upgradeCancelCall = yield* invoke("task_cancel", { - taskId: upgradedDelegated.taskId, - reason: "Terminalize while the parent run is live.", - clientRequestId: "cancel-wait-upgrade-1", - }); - expect(upgradeCancelCall.isError).toBe(false); - yield* waitForProjection(orchestrator, parentThreadId, (projection) => - projection.subagents.some( - (task) => task.id === upgradedDelegated.taskId && task.status === "interrupted", - ), - ); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === upgradedDelegated.taskId, - )?.completionDelivery, - ).toMatchObject({ state: "disposed" }); - yield* expectOffersToStay(0); - - const questionWait = yield* invoke("delegate_task", { - task: cancellationPrompt, - title: "Wait question", - target: { providerInstanceId: codexInstanceId, model: codexModel }, - mode: "wait", - timeoutMs: 30_000, - clientRequestId: "delegate-wait-question-1", - }).pipe(Effect.forkChild); - const question = (yield* waitForProjection(orchestrator, parentThreadId, (p) => - p.subagents.some( - (task) => task.title === "Wait question" && task.childThreadId !== null, - ), - )).subagents.find((task) => task.title === "Wait question")!; - const asking = yield* waitForProjection(orchestrator, question.childThreadId!, (p) => - p.providerTurns.some((turn) => turn.status === "running"), - ); - const askedAt = yield* DateTime.now; - yield* (yield* EventSink.EventSinkV2).write({ - events: [ - { - id: EventId.make("event:wait-question:live"), - type: "runtime-request.updated", - threadId: question.childThreadId!, - occurredAt: askedAt, - payload: { - id: RuntimeRequestId.make("request:wait-question"), - nodeId: question.id, - providerTurnId: null, - nativeRequestRef: null, - kind: "user_input", - status: "pending", - responseCapability: { - type: "live", - providerSessionId: asking.providerSessions[0]!.id, - }, - createdAt: askedAt, - resolvedAt: null, - }, - }, - ], - }); - expect((yield* Fiber.join(questionWait)).structuredContent).toMatchObject({ - status: "running", - hasPendingQuestion: true, - waitTimedOut: false, - }); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === question.id, - )?.completionWake, - ).toBe("always"); - yield* invoke("task_cancel", { - taskId: question.id, - clientRequestId: "cancel-wait-question-1", - }); - yield* waitForProjection(orchestrator, parentThreadId, (p) => - p.subagents.some((task) => task.id === question.id && task.status === "interrupted"), - ); - - const terminalUpgrade = yield* orchestrator.dispatch({ - type: "delegated_task.wake-policy", - commandId: CommandId.make("command:mcp-parent:wake-policy-terminal"), - parentThreadId, - taskId: delegated.taskId, - completionWake: "always", - }); - expect( - terminalUpgrade.storedEvents.some( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.id === delegated.taskId && - stored.event.payload.completionWake === "always", - ), - ).toBe(true); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === delegated.taskId, - )?.completionWake, - ).toBe("always"); - yield* expectOffersToStay(0); - - const legacyDispatch = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-parent:delegate-legacy"), - parentThreadId, - parentRunId: parentRun.id, - parentNodeId: parentRootNodeId, - task: cancellationPrompt, - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - }); - const legacyTaskEvent = legacyDispatch.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.origin === "app_owned", - ); - if (legacyTaskEvent?.event.type !== "subagent.updated") { - return yield* Effect.die(new Error("Legacy delegated task projection missing.")); - } - const legacyTask = legacyTaskEvent.event.payload; - expect(legacyTask.completionWake).toBeUndefined(); - if (legacyTask.childThreadId === null) { - return yield* Effect.die(new Error("Legacy delegated task child thread missing.")); - } - const legacyChildThreadId = legacyTask.childThreadId; - yield* waitForProjection(orchestrator, legacyChildThreadId, (projection) => - projection.providerTurns.some((turn) => turn.status === "running"), - ); - yield* expectOffersToStay(0); - - const stopQueuedDispatch = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-parent:stop-queued-delivery"), - parentThreadId, - parentRunId: parentRun.id, - parentNodeId: parentRootNodeId, - task: "Complete the stop barrier delivery task.", - modelSelection: claudeSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const stopQueuedTaskEvent = stopQueuedDispatch.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.origin === "app_owned", - ); - if (stopQueuedTaskEvent?.event.type !== "subagent.updated") { - return yield* Effect.die( - new Error("Stop barrier delegated task projection missing."), - ); - } - const stopQueuedTaskId = stopQueuedTaskEvent.event.payload.id; - const stopQueuedProjection = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.subagents.find((task) => task.id === stopQueuedTaskId)?.status === - "completed" && - projection.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion - ?.delivery !== null && - projection.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion - ?.delivery !== undefined, - ); - const stopQueuedDelivery = stopQueuedProjection.runs.find( - (run) => run.id === parentRun.id, - )?.delegatedCompletion?.delivery; - if (stopQueuedDelivery === undefined || stopQueuedDelivery === null) { - return yield* Effect.die(new Error("Stop barrier delivery reservation missing.")); - } - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make("command:mcp-parent:dispatch-stop-queued-delivery"), - threadId: parentThreadId, - messageId: stopQueuedDelivery.messageId, - text: "Delegated task reached a terminal state.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: parentRun.id, - generation: stopQueuedDelivery.generation, - taskIds: stopQueuedDelivery.taskIds, - }, - }); - const queuedStopDelivery = yield* waitForProjection( - orchestrator, - parentThreadId, - (projection) => - projection.runs.some( - (run) => - run.userMessageId === stopQueuedDelivery.messageId && run.status === "queued", - ), - ); - const queuedStopDeliveryRun = queuedStopDelivery.runs.find( - (run) => run.userMessageId === stopQueuedDelivery.messageId, - ); - if (queuedStopDeliveryRun === undefined) { - return yield* Effect.die(new Error("Queued stop barrier delivery missing.")); - } - yield* Ref.set(continuationOffers, []); - - const parentStop = yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("command:mcp-parent:interrupt-wake"), - threadId: parentThreadId, - runId: parentRun.id, - reason: "Settle the parent before the legacy child terminalizes.", - }); - yield* waitForProjection(orchestrator, parentThreadId, (projection) => - projection.runs.every( - (run) => - run.status !== "preparing" && - run.status !== "starting" && - run.status !== "running", - ), - ); - const stoppedParent = yield* orchestrator.getThreadProjection(parentThreadId); - expect(stoppedParent.runs.some((run) => run.id === parentRun.id)).toBe(true); - expect( - parentStop.storedEvents.some( - (stored) => - stored.event.type === "run.updated" && - stored.event.payload.id === parentRun.id && - stored.event.payload.delegatedCompletion?.disposition === "stopped", - ), - ).toBe(true); - expect( - stoppedParent.runs.find((run) => run.id === parentRun.id)?.delegatedCompletion, - ).toMatchObject({ disposition: "stopped", delivery: null }); - expect( - stoppedParent.runs.find((run) => run.id === queuedStopDeliveryRun.id)?.status, - ).toBe("cancelled"); - expect( - stoppedParent.subagents.find((task) => task.id === legacyTask.id)?.completionDelivery, - ).toMatchObject({ state: "disposed" }); - const legacyChildRun = (yield* orchestrator.getThreadProjection( - legacyChildThreadId, - )).runs.find((run) => run.status === "running"); - if (legacyChildRun === undefined) { - return yield* Effect.die( - new Error("Still-running child was missing after parent Stop."), - ); - } - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("command:mcp-parent:interrupt-legacy-after-parent-stop"), - threadId: legacyChildThreadId, - runId: legacyChildRun.id, - reason: "Terminalize after the parent Stop barrier.", - }); - yield* waitForProjection(orchestrator, legacyChildThreadId, (projection) => - projection.runs.some((run) => run.status === "interrupted"), - ); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === legacyTask.id, - )?.completionDelivery, - ).toMatchObject({ state: "disposed" }); - yield* expectOffersToStay(0); - - const settledUpgrade = yield* orchestrator.dispatch({ - type: "delegated_task.wake-policy", - commandId: CommandId.make("command:mcp-parent:wake-policy-settled"), - parentThreadId, - taskId: legacyTask.id, - completionWake: "always", - }); - expect( - settledUpgrade.storedEvents.some( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.id === legacyTask.id && - stored.event.payload.completionWake === "always", - ), - ).toBe(true); - expect( - (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( - (task) => task.id === legacyTask.id, - )?.completionWake, - ).toBe("always"); - yield* expectOffersToStay(0); - - const lateParentThreadId = ThreadId.make("thread:mcp-late-completion-parent"); - const lateParentGate = yield* Deferred.make(); - const lateDeliveryGate = yield* Deferred.make(); - parentTerminalGates.set(lateParentThreadId, lateParentGate); - deliveryTerminalGates.set(lateParentThreadId, lateDeliveryGate); - yield* Ref.set(continuationOffers, []); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-late-parent:create"), - threadId: lateParentThreadId, - projectId, - title: "Late completion 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-late-parent:start"), - threadId: lateParentThreadId, - messageId: MessageId.make("message:mcp-late-parent:start"), - text: "Hold this parent until its completion delivery is queued.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "start_immediately" }, - }); - const lateParentProjection = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.some((run) => run.status === "running") && - projection.providerTurns.some((turn) => turn.status === "running"), - ); - const lateParentRun = lateParentProjection.runs.find((run) => run.status === "running"); - if (lateParentRun?.rootNodeId === null || lateParentRun === undefined) { - return yield* Effect.die(new Error("Late completion parent run missing.")); - } - const earlyLateDelivery = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-late-parent:early-task"), - parentThreadId: lateParentThreadId, - parentRunId: lateParentRun.id, - parentNodeId: lateParentRun.rootNodeId, - task: "Complete before the first delivery starts.", - modelSelection: claudeSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const lateChild = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-late-parent:late-task"), - parentThreadId: lateParentThreadId, - parentRunId: lateParentRun.id, - parentNodeId: lateParentRun.rootNodeId, - task: cancellationPrompt, - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const taskFromDispatch = (result: typeof earlyLateDelivery) => { - const taskEvent = result.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.origin === "app_owned", - ); - if (taskEvent?.event.type !== "subagent.updated") { - throw new Error("Late completion delegated task projection missing."); - } - return taskEvent.event.payload; - }; - const earlyLateTask = taskFromDispatch(earlyLateDelivery); - const lateTask = taskFromDispatch(lateChild); - const thirdLateChild = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-late-parent:third-late-task"), - parentThreadId: lateParentThreadId, - parentRunId: lateParentRun.id, - parentNodeId: lateParentRun.rootNodeId, - task: cancellationPrompt, - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const thirdLateTask = taskFromDispatch(thirdLateChild); - const fourthLateTask = taskFromDispatch( - yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-late-parent:fourth-late-task"), - parentThreadId: lateParentThreadId, - parentRunId: lateParentRun.id, - parentNodeId: lateParentRun.rootNodeId, - task: cancellationPrompt, - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }), - ); - if ( - lateTask.childThreadId === null || - thirdLateTask.childThreadId === null || - fourthLateTask.childThreadId === null - ) { - return yield* Effect.die(new Error("Late completion child thread missing.")); - } - const beforeFirstDelivery = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.subagents.find((task) => task.id === earlyLateTask.id)?.status === - "completed" && - projection.subagents.find((task) => task.id === lateTask.id)?.status === - "running" && - projection.runs.find((run) => run.id === lateParentRun.id)?.delegatedCompletion - ?.delivery !== null && - projection.runs.find((run) => run.id === lateParentRun.id)?.delegatedCompletion - ?.delivery !== undefined, - ); - const firstLateDelivery = beforeFirstDelivery.runs.find( - (run) => run.id === lateParentRun.id, - )?.delegatedCompletion?.delivery; - if (firstLateDelivery === undefined || firstLateDelivery === null) { - return yield* Effect.die(new Error("First late completion delivery missing.")); - } - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make("command:mcp-late-parent:dispatch-first-delivery"), - threadId: lateParentThreadId, - messageId: firstLateDelivery.messageId, - text: "Delegated task reached a terminal state.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: lateParentRun.id, - generation: firstLateDelivery.generation, - taskIds: firstLateDelivery.taskIds, - }, - }); - yield* Deferred.succeed(lateParentGate, undefined); - const activeFirstDelivery = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.some( - (run) => - run.userMessageId === firstLateDelivery.messageId && run.status === "running", - ), - ); - const activeFirstDeliveryRun = activeFirstDelivery.runs.find( - (run) => run.userMessageId === firstLateDelivery.messageId, - ); - if (activeFirstDeliveryRun === undefined) { - return yield* Effect.die(new Error("First late completion delivery did not start.")); - } - const lateChildProjection = yield* orchestrator.getThreadProjection( - lateTask.childThreadId, - ); - const lateChildRun = lateChildProjection.runs[0]; - if (lateChildRun === undefined) { - return yield* Effect.die(new Error("Late completion child run missing.")); - } - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("command:mcp-late-parent:interrupt-late-child"), - threadId: lateTask.childThreadId, - runId: lateChildRun.id, - reason: "Terminalize after the first completion delivery started.", - }); - yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.subagents.find((task) => task.id === lateTask.id)?.completionDelivery - ?.state === "pending", - ); - yield* Deferred.succeed(lateDeliveryGate, undefined); - const successorReserved = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => { - const delivery = projection.runs.find((run) => run.id === lateParentRun.id) - ?.delegatedCompletion?.delivery; - return ( - delivery !== undefined && - delivery !== null && - delivery.generation === firstLateDelivery.generation + 1 && - delivery.taskIds.length === 1 && - delivery.taskIds[0] === lateTask.id - ); - }, - ); - const successorDelivery = successorReserved.runs.find( - (run) => run.id === lateParentRun.id, - )?.delegatedCompletion?.delivery; - expect(successorDelivery).toMatchObject({ - generation: firstLateDelivery.generation + 1, - taskIds: [lateTask.id], - }); - const lateOffers = yield* waitForContinuationOffers(2); - expect(lateOffers).toHaveLength(2); - expect( - successorReserved.runs.filter((run) => { - const message = successorReserved.messages.find( - (candidate) => candidate.id === run.userMessageId, - ); - return message?.delegatedCompletion?.parentRunId === lateParentRun.id; - }), - ).toHaveLength(1); - if (successorDelivery === undefined || successorDelivery === null) { - return yield* Effect.die(new Error("Late completion successor delivery missing.")); - } - - const successorGate = yield* Deferred.make(); - deliveryTerminalGates.set(lateParentThreadId, successorGate); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make("command:mcp-late-parent:dispatch-successor-delivery"), - threadId: lateParentThreadId, - messageId: successorDelivery.messageId, - text: "Delegated task reached a terminal state.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: lateParentRun.id, - generation: successorDelivery.generation, - taskIds: successorDelivery.taskIds, - }, - }); - const activeSuccessor = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.some( - (run) => - run.userMessageId === successorDelivery.messageId && run.status === "running", - ), - ); - const activeSuccessorRun = activeSuccessor.runs.find( - (run) => run.userMessageId === successorDelivery.messageId, - ); - if (activeSuccessorRun === undefined) { - return yield* Effect.die(new Error("Late completion successor did not start.")); - } - expect(activeSuccessor.turnItems).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "notification", - runId: activeSuccessorRun.id, - source: { - kind: "delegated_task", - taskIds: successorDelivery.taskIds, - childThreadId: lateTask.childThreadId, - }, - outcome: "cancelled", - summary: `Delegated task "${cancellationPrompt}" stopped`, - }), - ]), - ); - expect( - activeSuccessor.turnItems.some( - (item) => - item.type === "user_message" && item.messageId === successorDelivery.messageId, - ), - ).toBe(false); - for (const [label, childThreadId] of [ - ["third", thirdLateTask.childThreadId], - ["fourth", fourthLateTask.childThreadId], - ] as const) { - const childProjection = yield* waitForProjection( - orchestrator, - childThreadId, - (projection) => - projection.runs.some((run) => run.status === "running") && - projection.providerTurns.some((turn) => turn.status === "running"), - ); - const childRun = childProjection.runs.find((run) => run.status === "running"); - if (childRun === undefined) { - return yield* Effect.die(new Error(`${label} late completion child run missing.`)); - } - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make(`command:mcp-late-parent:interrupt-${label}-late-child`), - threadId: childThreadId, - runId: childRun.id, - reason: "Terminalize while the successor delivery is running.", - }); - } - const pendingDuringSuccessor = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - [thirdLateTask.id, fourthLateTask.id].every( - (taskId) => - projection.subagents.find((task) => task.id === taskId)?.completionDelivery - ?.state === "pending", - ), - ); - expect( - pendingDuringSuccessor.runs.find((run) => run.id === lateParentRun.id) - ?.delegatedCompletion?.delivery, - ).toMatchObject({ - generation: successorDelivery.generation, - taskIds: successorDelivery.taskIds, - }); - yield* expectOffersToStay(2); - yield* Deferred.succeed(successorGate, undefined); - const batchedReserved = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => { - const delivery = projection.runs.find((run) => run.id === lateParentRun.id) - ?.delegatedCompletion?.delivery; - return ( - delivery !== undefined && - delivery !== null && - delivery.generation === successorDelivery.generation + 1 && - projection.runs.find((run) => run.id === activeSuccessorRun.id)?.status === - "completed" - ); - }, - ); - const batchedDelivery = batchedReserved.runs.find((run) => run.id === lateParentRun.id) - ?.delegatedCompletion?.delivery; - if (batchedDelivery === undefined || batchedDelivery === null) { - return yield* Effect.die(new Error("Batched late completion delivery missing.")); - } - expect([...batchedDelivery.taskIds].toSorted()).toEqual( - [thirdLateTask.id, fourthLateTask.id].toSorted(), - ); - expect( - [lateTask.id, thirdLateTask.id, fourthLateTask.id].map( - (taskId) => - batchedReserved.subagents.find((task) => task.id === taskId)?.completionDelivery - ?.state, - ), - ).toEqual(["delivered", "claimed", "claimed"]); - yield* waitForContinuationOffers(3); - yield* expectOffersToStay(3); - expect( - batchedReserved.runs.filter((run) => { - const message = batchedReserved.messages.find( - (candidate) => candidate.id === run.userMessageId, - ); - return ( - message?.delegatedCompletion?.parentRunId === lateParentRun.id && - run.status !== "completed" - ); - }), - ).toHaveLength(0); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make("command:mcp-late-parent:dispatch-batched-delivery"), - threadId: lateParentThreadId, - messageId: batchedDelivery.messageId, - text: "Delegated tasks reached terminal states.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: lateParentRun.id, - generation: batchedDelivery.generation, - taskIds: batchedDelivery.taskIds, - }, - }); - const drainedCohort = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.find((run) => run.id === lateParentRun.id)?.delegatedCompletion - ?.delivery === null && - projection.runs.some( - (run) => - run.userMessageId === batchedDelivery.messageId && run.status === "completed", - ), - ); - expect( - [earlyLateTask.id, lateTask.id, thirdLateTask.id, fourthLateTask.id].map( - (taskId) => - drainedCohort.subagents.find((task) => task.id === taskId)?.completionDelivery - ?.state, - ), - ).toEqual(["delivered", "delivered", "delivered", "delivered"]); - yield* expectOffersToStay(3); - - const removeParentGate = yield* Deferred.make(); - parentTerminalGates.set(lateParentThreadId, removeParentGate); - const removeParentMessageId = MessageId.make("message:mcp-late-parent:remove-start"); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-late-parent:remove-start"), - threadId: lateParentThreadId, - messageId: removeParentMessageId, - text: "Keep the parent active while removing automatic delivery.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "start_immediately" }, - }); - const removeParentProjection = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.some( - (run) => run.userMessageId === removeParentMessageId && run.status === "running", - ), - ); - const removeParentRun = removeParentProjection.runs.find( - (run) => run.userMessageId === removeParentMessageId, - ); - if (removeParentRun?.rootNodeId === null || removeParentRun === undefined) { - return yield* Effect.die(new Error("Queue Remove parent run missing.")); - } - const removeDelegation = yield* orchestrator.dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make("command:mcp-late-parent:remove-delegate"), - parentThreadId: lateParentThreadId, - parentRunId: removeParentRun.id, - parentNodeId: removeParentRun.rootNodeId, - task: "Complete before Queue Remove disposes this automatic delivery.", - modelSelection: claudeSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }); - const removeTaskEvent = removeDelegation.storedEvents.find( - (stored) => - stored.event.type === "subagent.updated" && - stored.event.payload.origin === "app_owned", - ); - if (removeTaskEvent?.event.type !== "subagent.updated") { - return yield* Effect.die( - new Error("Queue Remove delegated task projection missing."), - ); - } - const removeTask = removeTaskEvent.event.payload; - const removeReserved = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.subagents.find((task) => task.id === removeTask.id)?.status === - "completed" && - projection.runs.find((run) => run.id === removeParentRun.id)?.delegatedCompletion - ?.delivery !== null && - projection.runs.find((run) => run.id === removeParentRun.id)?.delegatedCompletion - ?.delivery !== undefined, - ); - const removeDelivery = removeReserved.runs.find((run) => run.id === removeParentRun.id) - ?.delegatedCompletion?.delivery; - if (removeDelivery === undefined || removeDelivery === null) { - return yield* Effect.die(new Error("Queue Remove delivery reservation missing.")); - } - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make("command:mcp-late-parent:remove-dispatch"), - threadId: lateParentThreadId, - messageId: removeDelivery.messageId, - text: "Delegated task reached a terminal state.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: removeParentRun.id, - generation: removeDelivery.generation, - taskIds: removeDelivery.taskIds, - }, - }); - const removeQueued = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.some( - (run) => - run.userMessageId === removeDelivery.messageId && run.status === "queued", - ), - ); - const removeQueuedRun = removeQueued.runs.find( - (run) => run.userMessageId === removeDelivery.messageId, - ); - if (removeQueuedRun === undefined) { - return yield* Effect.die(new Error("Queue Remove delivery did not queue.")); - } - yield* Ref.set(continuationOffers, []); - yield* orchestrator.dispatch({ - type: "queued-run.cancel", - commandId: CommandId.make("command:mcp-late-parent:remove-queued-delivery"), - threadId: lateParentThreadId, - runId: removeQueuedRun.id, - }); - const removedDelivery = yield* waitForProjection( - orchestrator, - lateParentThreadId, - (projection) => - projection.runs.find((run) => run.id === removeParentRun.id)?.delegatedCompletion - ?.disposition === "disposed" && - projection.runs.find((run) => run.id === removeQueuedRun.id)?.status === - "cancelled" && - projection.subagents.find((task) => task.id === removeTask.id)?.completionDelivery - ?.state === "disposed", - ); - expect( - removedDelivery.runs.find((run) => run.id === removeParentRun.id) - ?.delegatedCompletion, - ).toMatchObject({ disposition: "disposed", delivery: null }); - expect( - removedDelivery.subagents.find((task) => task.id === removeTask.id), - ).toMatchObject({ result: expect.any(String), status: "completed" }); - yield* expectOffersToStay(0); - - const fanoutParentThreadId = ThreadId.make("thread:mcp-fanout-parent"); - const fanoutParentGate = yield* Deferred.make(); - const firstFanoutDeliveryGate = yield* Deferred.make(); - const secondFanoutDeliveryGate = yield* Deferred.make(); - parentTerminalGates.set(fanoutParentThreadId, fanoutParentGate); - deliveryTerminalGates.set(fanoutParentThreadId, firstFanoutDeliveryGate); - yield* Ref.set(continuationOffers, []); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:mcp-fanout-parent:create"), - threadId: fanoutParentThreadId, - projectId, - title: "Fan-out 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-fanout-parent:start"), - threadId: fanoutParentThreadId, - messageId: MessageId.make("message:mcp-fanout-parent:start"), - text: "Fan out twelve review agents.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "start_immediately" }, - }); - const fanoutStarted = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - projection.runs.some((run) => run.status === "running") && - projection.providerTurns.some((turn) => turn.status === "running"), - ); - const fanoutRun = fanoutStarted.runs.find((run) => run.status === "running"); - if (fanoutRun === undefined || fanoutRun.rootNodeId === null) { - return yield* Effect.die(new Error("Fan-out parent run missing.")); - } - const fanoutRootNodeId = fanoutRun.rootNodeId; - const fanoutTasks = yield* Effect.forEach( - Array.from({ length: 12 }, (_, index) => index), - (index) => - orchestrator - .dispatch({ - type: "delegated_task.request", - createdBy: "agent", - creationSource: "mcp", - commandId: CommandId.make(`command:mcp-fanout-parent:task-${index}`), - parentThreadId: fanoutParentThreadId, - parentRunId: fanoutRun.id, - parentNodeId: fanoutRootNodeId, - task: cancellationPrompt, - modelSelection: codexSelection, - runtimeMode: "full-access", - interactionMode: "default", - completionWake: "always", - }) - .pipe(Effect.map(taskFromDispatch)), - ); - type FanoutTask = (typeof fanoutTasks)[number]; - const finishFanoutChildren = (tasks: ReadonlyArray) => - Effect.forEach( - tasks, - (task) => - Effect.gen(function* () { - const childThreadId = task.childThreadId; - if (childThreadId === null) { - return yield* Effect.die(new Error("Fan-out child thread missing.")); - } - const child = yield* waitForProjection( - orchestrator, - childThreadId, - (projection) => - projection.runs.some((run) => run.status === "running") && - projection.providerTurns.some((turn) => turn.status === "running"), - ); - const childRun = child.runs.find((run) => run.status === "running"); - if (childRun === undefined) { - return yield* Effect.die(new Error("Fan-out child run missing.")); - } - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make(`command:mcp-fanout-parent:finish-${task.id}`), - threadId: childThreadId, - runId: childRun.id, - reason: "Finish this fan-out child.", - }); - }), - { discard: true }, - ); - const fanoutDelivery = (projection: OrchestrationV2ThreadProjection) => - projection.runs.find((run) => run.id === fanoutRun.id)?.delegatedCompletion - ?.delivery ?? null; - const fanoutDeliveryRuns = (projection: OrchestrationV2ThreadProjection) => - projection.runs.filter( - (run) => - projection.messages.find((message) => message.id === run.userMessageId) - ?.delegatedCompletion?.parentRunId === fanoutRun.id, - ); - const expectAtMostOneOutstandingDelivery = ( - projection: OrchestrationV2ThreadProjection, - ) => - expect( - fanoutDeliveryRuns(projection).filter( - (run) => - run.status !== "completed" && - run.status !== "failed" && - run.status !== "cancelled" && - run.status !== "interrupted", - ).length, - ).toBeLessThanOrEqual(1); - const deliveryStates = ( - projection: OrchestrationV2ThreadProjection, - tasks: ReadonlyArray, - ) => - tasks.map( - (task) => - projection.subagents.find((candidate) => candidate.id === task.id) - ?.completionDelivery?.state, - ); - const sortedIds = (ids: ReadonlyArray) => [...ids].toSorted(); - const idsOf = (tasks: ReadonlyArray) => - sortedIds(tasks.map((task) => task.id)); - const dispatchFanoutDelivery = ( - label: string, - delivery: OrchestrationV2DelegatedCompletionDelivery, - ) => - orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "agent", - creationSource: "server", - commandId: CommandId.make(`command:mcp-fanout-parent:dispatch-${label}`), - threadId: fanoutParentThreadId, - messageId: delivery.messageId, - text: "Delegated tasks reached terminal states.", - attachments: [], - modelSelection: codexSelection, - dispatchMode: { type: "queue_after_active" }, - delegatedCompletion: { - parentRunId: fanoutRun.id, - generation: delivery.generation, - taskIds: delivery.taskIds, - }, - }); - const deliveryRunStatus = ( - projection: OrchestrationV2ThreadProjection, - delivery: OrchestrationV2DelegatedCompletionDelivery, - ) => projection.runs.find((run) => run.userMessageId === delivery.messageId)?.status; - - const beforeFirstStarts = fanoutTasks.slice(0, 2); - const duringFirst = fanoutTasks.slice(2, 7); - const beforeSecondStarts = fanoutTasks.slice(7, 10); - const duringSecond = fanoutTasks.slice(10, 12); - - yield* finishFanoutChildren(beforeFirstStarts); - const firstReserved = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryStates(projection, beforeFirstStarts).every( - (state) => state === "claimed", - ) && fanoutDelivery(projection)?.taskIds.length === 2, - ); - const firstFanoutDelivery = fanoutDelivery(firstReserved); - if (firstFanoutDelivery === null) { - return yield* Effect.die(new Error("First fan-out delivery missing.")); - } - expect(sortedIds(firstFanoutDelivery.taskIds)).toEqual(idsOf(beforeFirstStarts)); - yield* dispatchFanoutDelivery("first", firstFanoutDelivery); - yield* Deferred.succeed(fanoutParentGate, undefined); - yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => deliveryRunStatus(projection, firstFanoutDelivery) === "running", - ); - - yield* finishFanoutChildren(duringFirst); - const pendingDuringFirst = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryStates(projection, duringFirst).every((state) => state === "pending"), - ); - expect(fanoutDelivery(pendingDuringFirst)).toEqual(firstFanoutDelivery); - expectAtMostOneOutstandingDelivery(pendingDuringFirst); - - deliveryTerminalGates.set(fanoutParentThreadId, secondFanoutDeliveryGate); - yield* Deferred.succeed(firstFanoutDeliveryGate, undefined); - const secondReserved = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryRunStatus(projection, firstFanoutDelivery) === "completed" && - fanoutDelivery(projection)?.generation === firstFanoutDelivery.generation + 1, - ); - expect(sortedIds(fanoutDelivery(secondReserved)?.taskIds ?? [])).toEqual( - idsOf(duringFirst), - ); - expect(deliveryStates(secondReserved, beforeFirstStarts)).toEqual([ - "delivered", - "delivered", - ]); - - yield* finishFanoutChildren(beforeSecondStarts); - const secondJoined = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryStates(projection, beforeSecondStarts).every( - (state) => state === "claimed", - ) && fanoutDelivery(projection)?.taskIds.length === 8, - ); - const secondFanoutDelivery = fanoutDelivery(secondJoined); - if (secondFanoutDelivery === null) { - return yield* Effect.die(new Error("Second fan-out delivery missing.")); - } - expect(sortedIds(secondFanoutDelivery.taskIds)).toEqual( - idsOf([...duringFirst, ...beforeSecondStarts]), - ); - expectAtMostOneOutstandingDelivery(secondJoined); - yield* dispatchFanoutDelivery("second", secondFanoutDelivery); - yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => deliveryRunStatus(projection, secondFanoutDelivery) === "running", - ); - - yield* finishFanoutChildren(duringSecond); - const pendingDuringSecond = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryStates(projection, duringSecond).every((state) => state === "pending"), - ); - expectAtMostOneOutstandingDelivery(pendingDuringSecond); - - deliveryTerminalGates.delete(fanoutParentThreadId); - yield* Deferred.succeed(secondFanoutDeliveryGate, undefined); - const thirdReserved = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryRunStatus(projection, secondFanoutDelivery) === "completed" && - fanoutDelivery(projection)?.generation === secondFanoutDelivery.generation + 1, - ); - const thirdFanoutDelivery = fanoutDelivery(thirdReserved); - if (thirdFanoutDelivery === null) { - return yield* Effect.die(new Error("Third fan-out delivery missing.")); - } - expect(sortedIds(thirdFanoutDelivery.taskIds)).toEqual(idsOf(duringSecond)); - yield* dispatchFanoutDelivery("third", thirdFanoutDelivery); - const fanoutDrained = yield* waitForProjection( - orchestrator, - fanoutParentThreadId, - (projection) => - deliveryRunStatus(projection, thirdFanoutDelivery) === "completed" && - fanoutDelivery(projection) === null, - ); - expect(deliveryStates(fanoutDrained, fanoutTasks)).toEqual( - fanoutTasks.map(() => "delivered"), - ); - expect( - fanoutTasks.map( - (task) => - fanoutDrained.subagents.find((candidate) => candidate.id === task.id)?.status, - ), - ).toEqual(fanoutTasks.map(() => "interrupted")); - const drainedDeliveryRuns = fanoutDeliveryRuns(fanoutDrained); - expect(drainedDeliveryRuns.map((run) => run.status)).toEqual([ - "completed", - "completed", - "completed", - ]); - const deliveredTaskIds = drainedDeliveryRuns.flatMap( - (run) => - fanoutDrained.messages.find((message) => message.id === run.userMessageId) - ?.delegatedCompletion?.taskIds ?? [], - ); - expect(sortedIds(deliveredTaskIds)).toEqual(idsOf(fanoutTasks)); - const offeredDeliveries = new Set( - (yield* Ref.get(continuationOffers)).map( - (offer) => offer.delegatedCompletion?.messageId, - ), - ); - expect(offeredDeliveries).toEqual( - new Set([ - firstFanoutDelivery.messageId, - secondFanoutDelivery.messageId, - thirdFanoutDelivery.messageId, - ]), - ); - }).pipe(Effect.provide(layerTest)); - }), - ), - ); - - it.live("reports running and queued child follow-ups from a Codex replay transcript", () => + it.live.each([ + { label: "distinct", result: queuedFollowupResult, latestSummary: queuedFollowupResult }, + { label: "identical", result: delegatedResult, latestSummary: null }, + ])("reports $label child results", ({ result, latestSummary }) => Effect.scoped( Effect.gen(function* () { const cwd = yield* checkpointWorkspace("delegated-task-status"); - const rawTranscript = yield* readDelegatedTaskStatusTranscript(); + const rawTranscript = yield* readDelegatedTaskStatusTranscript(result); const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( materializeReplayTranscriptWorkspace(rawTranscript, cwd), ); @@ -4072,12 +348,10 @@ describe("orchestrator MCP toolkit", () => { hasPendingChildRuns: false, latestTerminalRunId: delegated.childRunId, latestTerminalStatus: "completed", - latestTerminalSummary: delegatedResult, + latestTerminalSummary: null, + latestTerminalResultContextTransferId: null, }); expect(delegated.resultContextTransferId).not.toBeNull(); - expect(delegated.latestTerminalResultContextTransferId).toBe( - delegated.resultContextTransferId, - ); const delegatedChild = yield* orchestrator.getThreadProjection(delegated.childThreadId); expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent"); @@ -4171,8 +445,8 @@ describe("orchestrator MCP toolkit", () => { hasPendingChildRuns: true, latestTerminalRunId: delegated.childRunId, latestTerminalStatus: "completed", - latestTerminalSummary: delegatedResult, - latestTerminalResultContextTransferId: delegated.resultContextTransferId, + latestTerminalSummary: null, + latestTerminalResultContextTransferId: null, }); const finalSequence = yield* orchestrator.getThreadEventSequence(delegated.childThreadId); @@ -4217,6 +491,14 @@ describe("orchestrator MCP toolkit", () => { 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, @@ -4245,7 +527,7 @@ describe("orchestrator MCP toolkit", () => { finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id), ).toMatchObject({ status: "completed", - result: queuedFollowupResult, + result, }); expect( finishedParent.contextTransfers.filter( @@ -4272,9 +554,18 @@ describe("orchestrator MCP toolkit", () => { hasPendingChildRuns: false, latestTerminalRunId: queuedFollowup.runId, latestTerminalStatus: "completed", - latestTerminalSummary: queuedFollowupResult, + latestTerminalSummary: latestSummary, }); - expect(finalStatus.latestTerminalResultContextTransferId).not.toBeNull(); + 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 read = yield* invoke("t3_thread_read", { threadId: delegated.childThreadId, limit: 100, diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index aab23b3c49ea1..f9d618f0520e3 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -3,10 +3,8 @@ import { expect, it } from "@effect/vitest"; import { EnvironmentId, PreviewAutomationClientDisconnectedError, - PreviewAutomationInvalidSelectorError, PreviewAutomationMalformedResponseError, PreviewAutomationNoAvailableHostError, - PreviewAutomationTargetNotEditableError, PreviewTabId, ProviderInstanceId, ThreadId, @@ -16,13 +14,10 @@ import { SERVER_BROWSER_AUTOMATION_CLIENT_ID, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as Result from "effect/Result"; -import * as Scheduler from "effect/Scheduler"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; @@ -201,40 +196,6 @@ it.effect.each([true, false])( ), ); -it.effect("tracks the tab returned by a targeted recording stop", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const browsingTabId = PreviewTabId.make("tab-session-b"); - const recordingTabId = PreviewTabId.make("tab-session-a-recording"); - 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: browsingTabId } - : request.operation === "recordingStop" - ? { id: "recording-1", tabId: recordingTabId } - : { url: "http://localhost:3200" }, - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.invoke({ scope, operation: "open", input: {} }); - yield* broker.invoke({ scope, operation: "recordingStop", input: {} }); - yield* broker.invoke({ scope, operation: "snapshot", input: {} }); - - expect(routedRequests.at(-1)?.tabId).toBe(recordingTabId); - }), - ), -); - it.effect("does not let a no-tab response suppress an earlier tab decision", () => Effect.scoped( Effect.gen(function* () { @@ -326,192 +287,6 @@ it.effect("announces a live replacement stream before delivering requests", () = ), ); -it.effect( - "keeps a server-host open alive for installation without extending other operations", - () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const received = yield* Deferred.make(); - const requests = requestsFrom(yield* broker.connect(makeHost(), { preferred: true })); - yield* Stream.runForEach(requests, (request) => - request.operation === "open" - ? Deferred.succeed(received, request) - : broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: request.timeoutMs, - }), - ).pipe(Effect.forkScoped); - const opening = yield* broker - .invoke({ scope, operation: "open", input: {} }) - .pipe(Effect.forkScoped); - const request = yield* Deferred.await(received); - yield* TestClock.adjust(16_000); - yield* broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: "opened", - }); - expect(yield* Fiber.join(opening)).toBe("opened"); - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe(15_000); - expect(yield* broker.invoke({ scope, operation: "navigate", input: {} })).toBe(15_000); - }), - ), -); - -it.effect("preserves bounded request and remote selector diagnostics", () => { - const locator = "role=button[name='request-secret']"; - const remoteMessage = "Unexpected token near remote-secret."; - const remoteError = { - _tag: "PreviewAutomationInvalidSelectorError", - message: remoteMessage, - detail: { selector: "role=button[name='remote-secret']" }, - } as const; - - return 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, - error: remoteError, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - const error = yield* broker - .invoke({ - scope, - operation: "click", - input: { locator }, - tabId: PreviewTabId.make("tab-1"), - timeoutMs: 1_234, - }) - .pipe(Effect.flip); - - expect(error).toBeInstanceOf(PreviewAutomationInvalidSelectorError); - expect(error).toMatchObject({ - operation: "click", - environmentId: scope.environmentId, - threadId: scope.thread.threadId, - providerSessionId: scope.thread.providerSessionId, - providerInstanceId: scope.thread.providerInstanceId, - clientId: "client-1", - requestId: "preview-0", - tabId: "tab-1", - timeoutMs: 1_234, - selectorKind: "locator", - selectorLength: locator.length, - remoteTag: "PreviewAutomationInvalidSelectorError", - remoteMessageLength: remoteMessage.length, - remoteDetailKind: "object", - }); - expect(error.message).toBe( - `Preview automation click received an invalid locator (${locator.length} characters).`, - ); - expect(error.message).not.toContain("secret"); - expect(error.cause).toBe(remoteError); - expect("selector" in error).toBe(false); - expect("remoteMessage" in error).toBe(false); - expect("remoteDetail" in error).toBe(false); - }), - ); -}); - -it.effect("classifies a remote non-editable target without collapsing it to execution", () => { - const remoteError = { - _tag: "PreviewAutomationTargetNotEditableError", - message: "remote target details", - detail: { selectorKind: "focused-element" }, - } as const; - - return 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, - error: remoteError, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - const error = yield* broker - .invoke({ - scope, - operation: "type", - input: { text: "hello" }, - tabId: PreviewTabId.make("tab-1"), - }) - .pipe(Effect.flip); - - expect(error).toBeInstanceOf(PreviewAutomationTargetNotEditableError); - expect(error).toMatchObject({ - operation: "type", - tabId: "tab-1", - selectorKind: "focused-element", - remoteTag: "PreviewAutomationTargetNotEditableError", - }); - expect(error.message).toBe("Preview automation type requires an editable focused element."); - }), - ); -}); - -it.effect.each([ - "PreviewAutomationRecordingTransferError", - "PreviewAutomationRecordingDesktopUpdateRequiredError", - "PreviewAutomationRecordingTooLargeError", - "PreviewAutomationRecordingDeadlineExpiredError", -] as const)("preserves recording failure %s", (tag) => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const remoteError = { - _tag: tag, - message: "remote recording details", - detail: { reason: "untrusted-reason", threadId: "untrusted-thread" }, - }; - 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, - error: remoteError, - }), - ).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - const error = yield* broker - .invoke({ - scope, - operation: "recordingStop", - input: {}, - }) - .pipe(Effect.flip); - expect(error).toMatchObject({ - _tag: tag, - threadId: scope.thread.threadId, - }); - expect(error.cause).toBe(remoteError); - expect(error.message).not.toContain("remote recording details"); - }), - ), -); - it.effect.each([ { clientId: SERVER_BROWSER_AUTOMATION_CLIENT_ID, shown: true }, { clientId: "client-1", shown: false }, @@ -576,24 +351,6 @@ it.effect("distinguishes malformed remote failures", () => ), ); -it.effect("rejects calls when no connected host exists", () => - Effect.gen(function* () { - const broker = yield* makeBroker; - const error = yield* broker - .invoke({ scope, operation: "status", input: {} }) - .pipe(Effect.flip); - - expect(error).toBeInstanceOf(PreviewAutomationNoAvailableHostError); - expect(error).toMatchObject({ - operation: "status", - environmentId: scope.environmentId, - threadId: scope.thread.threadId, - providerSessionId: scope.thread.providerSessionId, - providerInstanceId: scope.thread.providerInstanceId, - }); - }), -); - it.effect("does not create host state from focus updates without a live stream", () => Effect.gen(function* () { const broker = yield* makeBroker; @@ -889,63 +646,6 @@ it.effect("prefers the live tab owner for new sessions without moving existing l ), ); -it.effect("prefers a focused host over unrelated extra capabilities for a new session", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - let focusedConnectionId = ""; - for (const [clientId, supportedOperations] of [ - ["focused", ["status"]], - ["background", ["status", "resize"]], - ] as const) { - const requests = requestsFrom( - yield* broker.connect(makeHost({ clientId, supportedOperations })), - (connectionId) => { - if (clientId === "focused") focusedConnectionId = 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: "focused", - environmentId: scope.environmentId, - connectionId: focusedConnectionId, - focused: true, - }); - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe( - "focused", - ); - }), - ), -); - -it.effect("does not route new operations to legacy hosts that did not advertise support", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const legacyEvents = yield* broker.connect(makeHost()); - yield* Stream.runDrain(legacyEvents).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(error).toMatchObject({ operation: "resize", environmentId: scope.environmentId }); - }), - ), -); - it.effect("routes resize to a capable host instead of a newer legacy connection", () => Effect.scoped( Effect.gen(function* () { @@ -1142,30 +842,6 @@ it.effect("fails over a pinned provider session only after its host disconnects" ), ); -it.effect("lets the browser host resolve an active tab locally", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - let routedTabId: string | undefined; - yield* Stream.runForEach(requests, (request) => { - routedTabId = request.tabId; - return broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - }); - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - - yield* broker.invoke({ scope, operation: "click", input: { x: 10, y: 10 } }); - - expect(routedTabId).toBeUndefined(); - }), - ), -); - it.effect("keeps a replacement stream authoritative when the old stream finalizes", () => Effect.scoped( Effect.gen(function* () { @@ -1317,186 +993,41 @@ it.effect("accepts responses only from the host that received the request", () = ), ); -it.effect("discards buffered actions before completing an evicted host stream", () => +it.effect("keeps each thread's current tab when threads share a provider session", () => Effect.scoped( Effect.gen(function* () { const broker = yield* makeBroker; - const connected = yield* Deferred.make(); - const received = yield* Deferred.make(); - const actionRouted = yield* Deferred.make(); - const releaseConsumer = yield* Deferred.make(); - const operations: string[] = []; - const consumer = yield* Stream.runForEach(yield* broker.connect(makeHost()), (event) => { - if (event.type === "connected") return Deferred.succeed(connected, undefined); - operations.push(event.request.operation); - return Deferred.succeed(received, undefined).pipe( - Effect.andThen(Deferred.await(releaseConsumer)), - ); - }).pipe(Effect.forkScoped); - yield* Deferred.await(connected); - const timedOut = yield* broker - .invoke({ scope, operation: "snapshot", input: {}, timeoutMs: 1_000 }) - .pipe(Effect.flip, Effect.forkScoped); - yield* Deferred.await(received); - const buffered = yield* broker - .invoke({ - scope, - operation: "click", - input: {}, - timeoutMs: 10_000, - onTargetTab: () => { - Deferred.doneUnsafe(actionRouted, Effect.void); - }, - }) - .pipe(Effect.flip, Effect.forkScoped); - yield* Deferred.await(actionRouted); - yield* TestClock.adjust(2_000); - expect(yield* Fiber.join(timedOut)).toMatchObject({ _tag: "PreviewAutomationTimeoutError" }); - expect(yield* Fiber.join(buffered)).toMatchObject({ - _tag: "PreviewAutomationClientDisconnectedError", - }); - yield* Deferred.succeed(releaseConsumer, undefined); - expect(Exit.isSuccess(yield* Fiber.await(consumer))).toBe(true); - expect(operations).toEqual(["snapshot"]); - }), - ), -); - -it.effect("rejects a routed action when its generation is evicted before delivery", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const connected = yield* Deferred.make(); - const received = yield* Deferred.make(); - const actionRouted = yield* Deferred.make(); - const operations: string[] = []; - const consumer = yield* Stream.runForEach(yield* broker.connect(makeHost()), (event) => { - if (event.type === "connected") return Deferred.succeed(connected, undefined); - operations.push(event.request.operation); - return Deferred.succeed(received, undefined); + 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* Deferred.await(connected); - const timedOut = yield* broker - .invoke({ scope, operation: "snapshot", input: {}, timeoutMs: 1_000 }) - .pipe(Effect.flip, Effect.forkScoped); - yield* Deferred.await(received); - - const tasks: Array<() => void> = []; - let paused = false; - const dispatcher: Scheduler.SchedulerDispatcher = { - scheduleTask: (task) => tasks.push(task), - flush: () => { - let task: (() => void) | undefined; - while ((task = tasks.shift()) !== undefined) task(); - }, - }; - const scheduler: Scheduler.Scheduler = { - executionMode: "async", - makeDispatcher: () => dispatcher, - shouldYield: () => paused, - }; - const action = yield* broker - .invoke({ - scope, - operation: "click", - input: {}, - onTargetTab: () => { - paused = true; - Deferred.doneUnsafe(actionRouted, Effect.void); - }, - }) - .pipe( - Effect.flip, - Effect.provideService(Scheduler.Scheduler, scheduler), - Effect.forkScoped, - ); - yield* Deferred.await(actionRouted); - yield* TestClock.adjust(2_000); - expect(yield* Fiber.join(timedOut)).toMatchObject({ _tag: "PreviewAutomationTimeoutError" }); - expect(Exit.isSuccess(yield* Fiber.await(consumer))).toBe(true); - - paused = false; - dispatcher.flush(); - expect(yield* Fiber.join(action)).toMatchObject({ - _tag: "PreviewAutomationClientDisconnectedError", - }); - expect(operations).toEqual(["snapshot"]); - }), - ), -); - -it.effect("keeps a host whose operation timeout arrives just after the budget", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const received = yield* Deferred.make(); - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => - Effect.gen(function* () { - if (request.operation === "waitFor") { - yield* Deferred.succeed(received, undefined); - yield* Effect.sleep(request.timeoutMs + 50); - } - yield* broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ...(request.operation === "waitFor" - ? { - ok: false, - error: { _tag: "PreviewAutomationTimeoutError", message: "Selector timed out" }, - } - : { ok: true, result: "responsive" }), - }); - }), - ).pipe(Effect.forkScoped); - const timedOut = yield* broker - .invoke({ scope, operation: "waitFor", input: {}, timeoutMs: 1_000 }) - .pipe(Effect.flip, Effect.forkScoped); - yield* Deferred.await(received); - yield* TestClock.adjust(1_050); - expect(yield* Fiber.join(timedOut)).toMatchObject({ - _tag: "PreviewAutomationTimeoutError", - remoteTag: "PreviewAutomationTimeoutError", - }); - expect(yield* broker.invoke({ scope, operation: "status", input: {} })).toBe("responsive"); - }), - ), -); - -it.effect("keeps the host connected when a background status read times out", () => - Effect.scoped( - Effect.gen(function* () { - const broker = yield* makeBroker; - const requests = requestsFrom(yield* broker.connect(makeHost())); - yield* Stream.runForEach(requests, (request) => - request.operation === "status" - ? Effect.void - : broker.respond({ - clientId: "client-1", - connectionId: request.connectionId, - requestId: request.requestId, - ok: true, - result: { operation: request.operation }, - }), - ).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") }, + }; - const status = yield* broker - .invoke({ - scope, - operation: "status", - input: {}, - timeoutMs: 500, - updateCurrentTab: false, - }) - .pipe(Effect.flip, Effect.forkScoped); - yield* TestClock.adjust(500); - expect(yield* Fiber.join(status)).toMatchObject({ _tag: "PreviewAutomationTimeoutError" }); - - expect(yield* broker.invoke({ scope, operation: "snapshot", input: {} })).toEqual({ - operation: "snapshot", - }); + 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 1a68cf6f0544b..2aced7dc3684b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -93,11 +93,7 @@ interface PendingRequest { readonly context: PreviewAutomationRequestErrorContext; } -/** - * It lives exactly as long as the connection it names: `connectionId`/`queue` - * identity is what makes a lease valid, so a disconnected or replaced host is - * dropped on the next lookup. - */ +/** A lease belongs to this exact connectionId/queue; replacing the host invalidates it. */ interface HostAssignment { readonly clientId: ClientConnection["clientId"]; readonly connectionId: ClientConnection["connectionId"]; @@ -166,8 +162,9 @@ const selectorDiagnosticsFromInput = ( return {}; }; +/** Codex/OpenCode share sessions across threads; include thread id to isolate tabs and ownership. */ const hostAssignmentKey = (scope: McpInvocationContext.McpThreadInvocationScope): string => - `${scope.environmentId}\u0000${scope.thread.providerSessionId}`; + `${scope.environmentId}\u0000${scope.thread.providerSessionId}\u0000${scope.thread.threadId}`; const isPreviewTabId = Schema.is(PreviewTabId); const decodeControlReason = Schema.decodeUnknownOption(PreviewAutomationControlReason); @@ -200,6 +197,14 @@ function remoteDetailKind(detail: unknown): RemoteDetailKind { } } +const readRemoteTimeoutMs = (detail: unknown): number | undefined => { + if (typeof detail !== "object" || detail === null || !("timeoutMs" in detail)) return undefined; + const timeoutMs = detail.timeoutMs; + return typeof timeoutMs === "number" && Number.isInteger(timeoutMs) && timeoutMs > 0 + ? timeoutMs + : undefined; +}; + const MAX_REASON_CHARS = 500; const classifyResponseError = ( @@ -248,11 +253,16 @@ const classifyResponseError = ( ...context, ...remoteDiagnostics, }); - case "PreviewAutomationTimeoutError": + case "PreviewAutomationTimeoutError": { + const remoteTimeoutMs = readRemoteTimeoutMs(error.detail); return new PreviewAutomationTimeoutError({ ...context, ...remoteDiagnostics, + ...(remoteTimeoutMs === undefined + ? {} + : { timeoutMs: Math.min(context.timeoutMs, remoteTimeoutMs) }), }); + } case "PreviewAutomationControlInterruptedError": { const reason = decodeControlReason(error.detail); return new PreviewAutomationControlInterruptedError({ @@ -352,8 +362,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { completeStream = false, ) { if (completeStream) { - // Discard this generation's commands and complete the RPC stream so a - // responsive desktop can re-register after a timeout eviction. + // Close the evicted generation's RPC stream so a responsive desktop can re-register. yield* Queue.clear(queue); yield* Queue.end(queue); } else { @@ -510,9 +519,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { const assigned = assignments.get(assignmentKey); const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined; const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId; - // Keep one provider session on one physical desktop runtime so a - // multi-step browser interaction cannot jump between independent Electron - // cookie/DOM state. + // Pin interactions to one desktop runtime so cookie/DOM state cannot jump between hosts. const ownsTargetTab = (host: ClientConnection, visibleOnly = false) => host.liveTabs.some( (tab) => @@ -545,8 +552,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { if (!hasLiveAssignment) assignments.delete(assignmentKey); return [undefined, { ...current, assignments }] as const; } - // The environment host may install Chromium on its first open (up to - // ten minutes). Keep that request alive without replaying its effects. + // First open may install Chromium for ten minutes; keep it alive without replaying effects. const timeoutMs = input.timeoutMs ?? (input.operation === "open" && connection.preferred ? 660_000 : 15_000); const canReuseAssignedTab = @@ -607,8 +613,7 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { }); const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () { const offered = yield* SynchronizedRef.modifyEffect(state, (current) => { - // A route can outlive its generation while another request evicts it. - // Serialize the live-generation check and offer with queue closure. + // Serialize generation checks and offers with queue closure; routes can outlive eviction. if ( current.clients.get(connection.clientId)?.queue !== connection.queue || !current.pending.has(requestId) @@ -637,18 +642,14 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { } return yield* new PreviewAutomationRequestQueueClosedError(requestContext); } - // The browser starts its operation timer after delivery. Allow its timeout - // response to arrive before treating the entire host as unresponsive. + // The browser timer starts on delivery; allow its timeout response before evicting the host. const responseTimeoutMs = input.updateCurrentTab === false ? timeoutMs : timeoutMs + HOST_RESPONSE_GRACE_MS; const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(responseTimeoutMs)); return yield* Option.match(result, { onNone: () => Effect.gen(function* () { - // Do not replay actions: the client may have applied them before - // becoming unreachable. A background metadata read has a short budget - // and changes nothing, so a slow one must not cut the host off from the - // agent's next call. + // Never replay possibly applied actions; slow metadata reads must not evict the host. if (input.updateCurrentTab !== false) { yield* disconnect(connection.clientId, connection.queue, true); } diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index 9c36a26045dc5..504ae749a78ac 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -50,9 +50,6 @@ const driver = ProviderDriverKind.make("claudeAgent"); const instanceId = ProviderInstanceId.make("claudeAgent"); const modelSelection = { instanceId, model: "claude-test" }; -// A delegated Claude child ends its turn while a background native subagent it -// started keeps running (#17154). - it.effect("task_cancel ends a delegated child's background native subagent", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.test.ts b/apps/server/src/mcp/ThreadMetadataMcpService.test.ts deleted file mode 100644 index 411568f75745c..0000000000000 --- a/apps/server/src/mcp/ThreadMetadataMcpService.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { expect, it } from "@effect/vitest"; -import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts"; -import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; -import type * as McpInvocationContext from "./McpInvocationContext.ts"; -import * as ThreadMetadataMcp from "./ThreadMetadataMcpService.ts"; - -const threadId = ThreadId.make("thread:metadata-caller"); -const scope: McpInvocationContext.McpInvocationScope = { - environmentId: EnvironmentId.make("environment:metadata-test"), - requestNamespace: "provider-session:metadata-test", - thread: { - threadId, - providerSessionId: "provider-session:metadata-test", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(["orchestration"]), - issuedAt: 1, -}; - -function layerService( - getThreadShell: ThreadManagement.ThreadManagementService["Service"]["getThreadShell"], -) { - return ThreadMetadataMcp.layer.pipe( - Layer.provide( - Layer.merge( - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell, - getThreadRecords: () => Effect.die("projection must not load after shell failure"), - } satisfies Partial), - NodeCrypto.layer, - ), - ), - ); -} - -const updateCallingThread = Effect.gen(function* () { - const service = yield* ThreadMetadataMcp.ThreadMetadataMcpService; - return yield* service.update(scope, { - action: "rename", - title: "Renamed thread", - clientRequestId: "metadata-caller-classification", - }); -}); - -it.effect("reports an absent calling thread as thread_not_found", () => - Effect.gen(function* () { - const error = yield* updateCallingThread.pipe( - Effect.provide(layerService(() => Effect.succeed(null))), - Effect.flip, - ); - - expect(error.code).toBe("thread_not_found"); - }), -); - -it.effect("keeps calling-thread storage failures as orchestration errors", () => - Effect.gen(function* () { - const error = yield* updateCallingThread.pipe( - Effect.provide( - layerService(() => - Effect.fail( - new OrchestratorProjectionError({ - threadId, - cause: new Error("storage unavailable"), - }), - ), - ), - ), - Effect.flip, - ); - - expect(error.code).toBe("orchestration_error"); - }), -); diff --git a/apps/server/src/mcp/ThreadMetadataMcpService.ts b/apps/server/src/mcp/ThreadMetadataMcpService.ts index 74176ec90c7b9..421d728461eb1 100644 --- a/apps/server/src/mcp/ThreadMetadataMcpService.ts +++ b/apps/server/src/mcp/ThreadMetadataMcpService.ts @@ -16,6 +16,7 @@ import * as Layer from "effect/Layer"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import type { McpInvocationScope } from "./McpInvocationContext.ts"; +import { threadNotFound } from "./OrchestratorMcpService.ts"; export class ThreadMetadataMcpService extends Context.Service< ThreadMetadataMcpService, @@ -167,7 +168,7 @@ const make = Effect.gen(function* () { ), ); if (shell === null || shell.deletedAt !== null) { - return yield* failure("thread_not_found", `Thread ${threadId} was not found.`); + return yield* threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`); } const target = yield* threadManagement .getProjectThreadRecords({ projectId: shell.projectId, threadId }, []) @@ -202,8 +203,7 @@ const make = Effect.gen(function* () { const metadataEvent = dispatched.storedEvents.find( (stored) => stored.event.type === "thread.metadata-updated", ); - // A retried commandId replays the stored events of the first dispatch; - // compaction may have deleted them by then, so answer from the projection. + // Retries may find stored events compacted away; answer from the projection. const thread = metadataEvent?.event.type === "thread.metadata-updated" ? metadataEvent.event.payload diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index eea8d4bbd8a76..c6a00aabcb0cc 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -15,11 +15,14 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as ServerConfig from "../config.ts"; import { OrchestratorDispatchError, OrchestratorProjectionError, @@ -85,6 +88,7 @@ const project: Project = { } as Project; interface HarnessOptions { + readonly git?: Partial; readonly thread?: ThreadFixture | null; readonly threadReadError?: "projection" | "dispatch"; readonly capabilities?: ReadonlySet; @@ -104,8 +108,8 @@ interface HarnessOptions { readonly projectReadFails?: boolean; readonly existingBranchWorktreePath?: string | null; readonly createWorktreeFails?: boolean; - readonly fetchRemoteFails?: boolean; - readonly resolveRemoteFails?: boolean; + readonly fetchWorktreeBaseFails?: boolean; + readonly worktreeBaseMissing?: boolean; readonly removeWorktreeFails?: boolean; readonly deleteLocalBranchFails?: boolean; readonly createWorktreeGate?: Effect.Effect; @@ -206,13 +210,12 @@ const makeHarness = (options: HarnessOptions = {}) => { ? (Effect.fail("simulated local branch deletion failure") as never) : Effect.void, ); - const fetchRemote = vi.fn((_: unknown) => - options.fetchRemoteFails ? (Effect.fail("simulated fetch failure") as never) : Effect.void, - ); - const resolveRemoteTrackingCommit = vi.fn((_: unknown) => - options.resolveRemoteFails - ? (Effect.fail("simulated remote resolve failure") as never) - : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }), + const fetchWorktreeBaseCommit = vi.fn((_: unknown) => + options.fetchWorktreeBaseFails + ? (Effect.fail("simulated fetch failure") as never) + : options.worktreeBaseMissing + ? Effect.succeed(null) + : Effect.succeed({ commitSha: "abc123", remoteRefName: "origin/dev" }), ); const createWorktree = vi.fn( (input: { readonly newRefName?: string | undefined; readonly path: string | null }) => @@ -303,11 +306,11 @@ const makeHarness = (options: HarnessOptions = {}) => { listRefs, listLocalBranchNames, localStatus, - fetchRemote, - resolveRemoteTrackingCommit, + fetchWorktreeBaseCommit, createWorktree, removeWorktree, deleteLocalBranch, + ...options.git, } satisfies Partial), Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({ runForThread, @@ -325,8 +328,7 @@ const makeHarness = (options: HarnessOptions = {}) => { scope, dispatch, sendToThread, - fetchRemote, - resolveRemoteTrackingCommit, + fetchWorktreeBaseCommit, createWorktree, removeWorktree, deleteLocalBranch, @@ -346,9 +348,7 @@ const expectTypedFailure = (exit: Exit.Exit, expected: object) expect(reason.error).toMatchObject(expected); }; -// Resolves the service once from the harness layer; used by tests that must -// make several calls against the SAME instance (the in-flight guard lives in -// the layer's closure, so a fresh layer per call would never see it). +// Resolve once so calls share the in-flight guard. const resolveService = (harness: ReturnType) => Effect.gen(function* () { return yield* WorktreeMcpService.WorktreeMcpService; @@ -369,85 +369,9 @@ const runStatus = (harness: ReturnType) => return yield* service.status(harness.scope); }).pipe(Effect.provide(harness.layer)); -// Decodes tool arguments the way the MCP tool does before calling the service. const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput); describe("t3_worktree_handoff", () => { - it.effect("creates a worktree from the current branch and re-points the thread", () => { - const harness = makeHarness(); - return Effect.gen(function* () { - const result = yield* runHandoff(harness, { branch: "feature/handoff" }); - - expect(result.branch).toBe("feature/handoff"); - expect(result.baseRef).toBe("dev"); - expect(result.startedFromOrigin).toBe(false); - expect(result.worktreePath).toBe("/worktrees/project/feature/handoff"); - expect(result.setupScript).toMatchObject({ - status: "started", - scriptName: "Setup", - }); - - expect(harness.fetchRemote).not.toHaveBeenCalled(); - expect(harness.createWorktree).toHaveBeenCalledWith({ - cwd: workspaceRoot, - refName: "dev", - newRefName: "feature/handoff", - baseRefName: "dev", - path: null, - }); - expect(harness.dispatch).toHaveBeenCalledWith( - expect.objectContaining({ - type: "thread.metadata.update", - threadId, - branch: "feature/handoff", - worktreePath: "/worktrees/project/feature/handoff", - expectedWorktreePath: null, - }), - ); - expect(harness.runForThread).toHaveBeenCalledWith({ - threadId, - projectId, - projectCwd: workspaceRoot, - worktreePath: "/worktrees/project/feature/handoff", - project: { id: projectId, workspaceRoot, scripts: [] }, - }); - }); - }); - - it.effect("skips the continuation when no continuationPrompt is given", () => { - const harness = makeHarness(); - return Effect.gen(function* () { - const result = yield* runHandoff(harness, { branch: "feature/no-continuation" }); - expect(result.continuation).toEqual({ status: "skipped" }); - expect(harness.sendToThread).not.toHaveBeenCalled(); - }); - }); - - it.effect("queues the continuation prompt as the thread's next message", () => { - const harness = makeHarness(); - return Effect.gen(function* () { - const result = yield* runHandoff(harness, { - branch: "feature/continue", - continuationPrompt: "Keep fixing the login bug in the new worktree.", - }); - - expect(result.continuation).toEqual({ status: "scheduled", delivery: "queued" }); - expect(harness.sendToThread).toHaveBeenCalledWith( - expect.objectContaining({ - projectId, - threadId, - text: "Keep fixing the login bug in the new worktree.", - mode: "queue", - createdBy: "agent", - creationSource: "mcp", - }), - ); - expect(harness.sendToThread.mock.invocationCallOrder[0]).toBeLessThan( - harness.runForThread.mock.invocationCallOrder[0]!, - ); - }); - }); - it.effect("reports a continuation failure without failing the handoff", () => { const harness = makeHarness({ continuation: "fails" }); return Effect.gen(function* () { @@ -461,18 +385,6 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("reports a continuation defect without failing the handoff", () => { - const harness = makeHarness({ continuation: "dies" }); - return Effect.gen(function* () { - const result = yield* runHandoff(harness, { - branch: "feature/continue-dies", - continuationPrompt: "Keep going.", - }); - expect(result.continuation).toEqual({ status: "failed", detail: "send defect" }); - expect(result.setupScript).toMatchObject({ status: "started" }); - }); - }); - it.effect("does not queue a continuation when the thread update fails", () => { const harness = makeHarness({ dispatchFails: true }); return Effect.gen(function* () { @@ -487,48 +399,59 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("starts from origin and honors an explicit baseRef", () => { - const harness = makeHarness(); - return Effect.gen(function* () { + it.effect("uses the fetched commit and remote PR base for an explicit local alias", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const git = yield* GitVcsDriver.GitVcsDriver; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "handoff-remote-base-" }); + const cwd = `${directory}/repo`; + const remote = `${directory}/remote.git`; + const worktreePath = `${directory}/worktree`; + yield* fs.makeDirectory(cwd); + const command = (at: string, args: string[]) => + git.execute({ operation: "handoff-test", cwd: at, args }); + yield* command(cwd, ["init", "-b", "stable"]); + yield* command(cwd, ["config", "user.name", "Test"]); + yield* command(cwd, ["config", "user.email", "test@example.test"]); + yield* command(cwd, ["commit", "--allow-empty", "-m", "remote base"]); + const remoteHead = (yield* command(cwd, ["rev-parse", "HEAD"])).stdout.trim(); + yield* command(cwd, ["init", "--bare", remote]); + yield* command(cwd, ["remote", "add", "upstream", remote]); + yield* command(cwd, ["push", "-u", "upstream", "stable:release"]); + yield* command(cwd, ["commit", "--allow-empty", "-m", "local only"]); + const harness = makeHarness({ + git: { + fetchWorktreeBaseCommit: (input) => git.fetchWorktreeBaseCommit({ ...input, cwd }), + createWorktree: (input) => git.createWorktree({ ...input, cwd, path: worktreePath }), + }, + }); const result = yield* runHandoff(harness, { - branch: "feature/from-origin", - baseRef: "dev", + branch: "feature/from-remote", + baseRef: "stable", startFromOrigin: true, runSetupScript: false, }); - expect(harness.fetchRemote).toHaveBeenCalledWith({ - cwd: workspaceRoot, - remoteName: "origin", - }); - expect(harness.resolveRemoteTrackingCommit).toHaveBeenCalledWith({ - cwd: workspaceRoot, - refName: "dev", - fallbackRemoteName: "origin", - }); - expect(harness.createWorktree).toHaveBeenCalledWith({ - cwd: workspaceRoot, - refName: "abc123", - newRefName: "feature/from-origin", - baseRefName: "dev", - path: null, - }); - expect(harness.localStatus).toHaveBeenCalled(); - expect(harness.runForThread).not.toHaveBeenCalled(); - expect(result.worktreePath).toBe("/worktrees/project/feature/from-origin"); + expect(result.worktreePath).toBe(worktreePath); expect(result.startedFromOrigin).toBe(true); expect(result.setupScript).toEqual({ status: "skipped" }); - }); - }); - - it.effect("uses the server setting for startFromOrigin when unspecified", () => { - const harness = makeHarness({ newWorktreesStartFromOrigin: true }); - return Effect.gen(function* () { - const result = yield* runHandoff(harness, { branch: "feature/settings-origin" }); - expect(result.startedFromOrigin).toBe(true); - expect(harness.fetchRemote).toHaveBeenCalled(); - }); - }); + expect((yield* command(worktreePath, ["rev-parse", "HEAD"])).stdout.trim()).toBe(remoteHead); + const preview = yield* git.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; + expect( + (yield* command(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`])).stdout.trim(), + ).toBe(remoteHead); + }).pipe( + Effect.provide( + GitVcsDriver.layer.pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "handoff-remote-git-" })), + Layer.provideMerge(NodeServices.layer), + ), + ), + ), + ); it.effect("fails when the thread is already attached to a worktree", () => { const harness = makeHarness({ @@ -544,60 +467,6 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("fails when the thread does not exist", () => { - const harness = makeHarness({ thread: null }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/missing" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("treats a soft-deleted thread as not found", () => { - const harness = makeHarness({ thread: { deletedAt: "2026-01-02T00:00:00.000Z" } }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/deleted" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("maps a non-projection orchestrator error to operation_failed", () => { - const harness = makeHarness({ threadReadError: "dispatch" }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/read-error" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("fails when the project does not exist", () => { - const harness = makeHarness({ projectMissing: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-project" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("maps a project read error to operation_failed", () => { - const harness = makeHarness({ projectReadFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/project-error" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("fails when the project workspace is not a git repository", () => { - const harness = makeHarness({ notARepo: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-repo" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - it.effect("rejects an existing branch with an actionable error naming its checkout", () => { const harness = makeHarness({ existingBranchWorktreePath: "/elsewhere/checkout" }); return Effect.gen(function* () { @@ -613,16 +482,7 @@ describe("t3_worktree_handoff", () => { expect(error.message).toContain("already exists"); expect(error.message).toContain("/elsewhere/checkout"); expect(harness.createWorktree).not.toHaveBeenCalled(); - expect(harness.fetchRemote).not.toHaveBeenCalled(); - }); - }); - - it.effect("rejects an existing branch that is not checked out anywhere", () => { - const harness = makeHarness({ existingBranchWorktreePath: null }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/taken-idle" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); + expect(harness.fetchWorktreeBaseCommit).not.toHaveBeenCalled(); }); }); @@ -635,17 +495,6 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("rejects a non-repository workspace even when baseRef is explicit", () => { - const harness = makeHarness({ notARepo: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit( - runHandoff(harness, { branch: "feature/no-repo-baseref", baseRef: "dev" }), - ); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - it.effect("propagates an interrupted dispatch without rolling back the worktree", () => { const harness = makeHarness({ dispatchInterrupts: true }); return Effect.gen(function* () { @@ -658,35 +507,18 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("maps a worktree creation failure to operation_failed", () => { - const harness = makeHarness({ createWorktreeFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/create-fails" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.dispatch).not.toHaveBeenCalled(); - expect(harness.removeWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("maps an origin fetch failure to operation_failed", () => { - const harness = makeHarness({ fetchRemoteFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit( - runHandoff(harness, { branch: "feature/fetch-fails", startFromOrigin: true }), - ); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - - it.effect("maps a remote-tracking resolve failure to operation_failed", () => { - const harness = makeHarness({ resolveRemoteFails: true }); + it.effect("falls back to the local base when no remote holds it", () => { + const harness = makeHarness({ worktreeBaseMissing: true }); return Effect.gen(function* () { - const exit = yield* Effect.exit( - runHandoff(harness, { branch: "feature/resolve-fails", startFromOrigin: true }), + const result = yield* runHandoff(harness, { + branch: "feature/local-fallback", + baseRef: "dev", + startFromOrigin: true, + }); + expect(harness.createWorktree).toHaveBeenCalledWith( + expect.objectContaining({ refName: "dev", baseRefName: "dev" }), ); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); + expect(result.startedFromOrigin).toBe(false); }); }); @@ -751,15 +583,6 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("rejects a handoff for an archived thread", () => { - const harness = makeHarness({ thread: { archivedAt: "2026-01-02T00:00:00.000Z" } }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/archived" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" }); - expect(harness.createWorktree).not.toHaveBeenCalled(); - }); - }); - it.effect("queues the continuation even when interrupted during the binding dispatch", () => Effect.gen(function* () { const gate = yield* Deferred.make(); @@ -784,32 +607,6 @@ describe("t3_worktree_handoff", () => { }), ); - it.effect("still fails with a typed error when the rollback removal also fails", () => { - const harness = makeHarness({ dispatchFails: true, removeWorktreeFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/rollback-fails" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.removeWorktree).toHaveBeenCalledTimes(1); - expect(harness.deleteLocalBranch).not.toHaveBeenCalled(); - }); - }); - - it.effect("preserves the typed failure when rollback branch deletion also fails", () => { - const harness = makeHarness({ dispatchFails: true, deleteLocalBranchFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit( - runHandoff(harness, { branch: "feature/rollback-branch-fails" }), - ); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.removeWorktree).toHaveBeenCalledTimes(1); - expect(harness.deleteLocalBranch).toHaveBeenCalledWith({ - cwd: workspaceRoot, - refName: "feature/rollback-branch-fails", - force: true, - }); - }); - }); - it.effect("creates the worktree in the managed directory even when a call names a path", () => { const harness = makeHarness(); return Effect.gen(function* () { @@ -841,14 +638,6 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("fails when the worktree capability is missing", () => { - const harness = makeHarness({ capabilities: new Set(["preview"]) }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/no-capability" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" }); - }); - }); - it.effect("serializes concurrent handoffs for the same thread", () => Effect.gen(function* () { const gate = yield* Deferred.make(); @@ -873,37 +662,6 @@ describe("t3_worktree_handoff", () => { }), ); - it.effect("removes the created worktree when the thread update fails", () => { - const harness = makeHarness({ dispatchFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/dispatch-fails" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.createWorktree).toHaveBeenCalledTimes(1); - expect(harness.removeWorktree).toHaveBeenCalledWith({ - cwd: workspaceRoot, - path: "/worktrees/project/feature/dispatch-fails", - force: true, - }); - }); - }); - - it.effect("fails when baseRef is omitted and HEAD is detached", () => { - const harness = makeHarness({ currentBranch: null }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runHandoff(harness, { branch: "feature/detached" })); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "invalid_request" }); - }); - }); - - it.effect("reports setup script failure without failing the handoff", () => { - const harness = makeHarness({ setupScript: "fails" }); - return Effect.gen(function* () { - const result = yield* runHandoff(harness, { branch: "feature/setup-fails" }); - expect(result.setupScript.status).toBe("failed"); - expect(harness.dispatch).toHaveBeenCalled(); - }); - }); - it.effect("reports a setup script defect without failing the handoff", () => { const harness = makeHarness({ setupScript: "dies" }); return Effect.gen(function* () { @@ -915,20 +673,6 @@ describe("t3_worktree_handoff", () => { }); describe("t3_worktree_status", () => { - it.effect("reports an unattached thread", () => { - const harness = makeHarness({ newWorktreesStartFromOrigin: true }); - return Effect.gen(function* () { - const result = yield* runStatus(harness); - expect(result).toEqual({ - attached: false, - worktreePath: null, - branch: null, - projectWorkspaceRoot: workspaceRoot, - defaultStartFromOrigin: true, - }); - }); - }); - it.effect("reports an attached thread's worktree and branch", () => { const harness = makeHarness({ thread: { @@ -946,46 +690,4 @@ describe("t3_worktree_status", () => { }); }); }); - - it.effect("fails when the worktree capability is missing", () => { - const harness = makeHarness({ capabilities: new Set(["preview"]) }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runStatus(harness)); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "capability_denied" }); - }); - }); - - it.effect("fails when the thread does not exist", () => { - const harness = makeHarness({ thread: null }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runStatus(harness)); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "thread_not_found" }); - }); - }); - - it.effect("fails when the project does not exist", () => { - const harness = makeHarness({ projectMissing: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit(runStatus(harness)); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "project_not_found" }); - }); - }); -}); - -describe("WorktreeMcpHandoffInput schema", () => { - const decode = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput); - - it.effect("rejects a missing or blank branch", () => - Effect.gen(function* () { - expect(Exit.isFailure(yield* Effect.exit(decode({})))).toBe(true); - expect(Exit.isFailure(yield* Effect.exit(decode({ branch: " " })))).toBe(true); - }), - ); - - it.effect("rejects a blank continuationPrompt", () => - Effect.gen(function* () { - const exit = yield* Effect.exit(decode({ branch: "feature/x", continuationPrompt: " " })); - expect(Exit.isFailure(exit)).toBe(true); - }), - ); }); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index b738aaac12fd7..8f02ee1546424 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -63,9 +63,7 @@ const make = Effect.gen(function* () { const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - // Serializes handoffs per thread: two concurrent calls could otherwise both - // pass the worktreePath === null check and each create a worktree, leaving - // one untracked on disk. + // Serialize handoffs per thread to avoid creating two worktrees and orphaning one. const handoffThreadsInFlight = new Set(); const requireThreadScope = (scope: McpInvocationScope) => @@ -210,30 +208,22 @@ const make = Effect.gen(function* () { const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin); let worktreeBaseRef = baseRef; + let baseRefName = baseRef; + let startedFromOrigin = false; if (startFromOrigin) { - yield* gitWorkflow - .fetchRemote({ cwd: projectCwd, remoteName: "origin" }) - .pipe(asOperationFailed("Unable to fetch origin")); const resolvedRemoteBase = yield* gitWorkflow - .resolveRemoteTrackingCommit({ - cwd: projectCwd, - refName: baseRef, - fallbackRemoteName: "origin", - }) - .pipe(asOperationFailed(`Unable to resolve the remote-tracking commit of '${baseRef}'`)); - worktreeBaseRef = resolvedRemoteBase.commitSha; + .fetchWorktreeBaseCommit({ cwd: projectCwd, refName: baseRef }) + .pipe(asOperationFailed(`Unable to fetch the remote base of '${baseRef}'`)); + if (resolvedRemoteBase !== null) { + worktreeBaseRef = resolvedRemoteBase.commitSha; + baseRefName = `refs/remotes/${resolvedRemoteBase.remoteRefName}`; + startedFromOrigin = true; + } } const ids = yield* handoffIds(scope); - // uninterruptibleMask: only the potentially slow worktree creation itself - // stays interruptible (restore). From the moment it succeeds, through the - // binding, continuation queue, setup script launch, and result - // construction, there is no interruptible gap: a client cancel can - // therefore neither orphan the created worktree before the rollback is - // armed, nor skip setting up a worktree the thread was just bound to - // (once the binding commits, the scheduled session detach can sever this - // request's connection and interrupt the fiber). + // Mask interruption after worktree creation through setup; binding can detach and interrupt the caller. return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { const worktree = yield* restore( @@ -242,7 +232,7 @@ const make = Effect.gen(function* () { cwd: projectCwd, refName: worktreeBaseRef, newRefName: input.branch, - baseRefName: baseRef, + baseRefName, path: null, }) .pipe(asOperationFailed("Unable to create the worktree")), @@ -274,10 +264,7 @@ const make = Effect.gen(function* () { ).pipe(Effect.ignoreCause({ log: true })); const recheckAndBind = Effect.gen(function* () { - // The projection was read before the potentially slow git work - // above; a concurrent binding (for example from the UI) could have - // attached the thread in the meantime. Re-check before committing so - // the race cannot leave a second, untracked worktree. + // A concurrent UI binding may have landed during git work; do not orphan a second worktree. const recheck = yield* loadThread(scope); if (recheck.thread.worktreePath !== null) { return yield* alreadyInWorktree(recheck.thread.worktreePath); @@ -310,18 +297,13 @@ const make = Effect.gen(function* () { ), ); }).pipe( - // Interrupt-only causes skip the removal: the binding may have - // committed, and force-deleting a worktree the thread now points at - // would be worse than leaking one. + // Do not remove on interruption alone; the thread binding may already have committed. Effect.onError((cause) => Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree, ), ); - // Queue the continuation right after the binding commits: the detach - // that the metadata update schedules will terminate the calling - // session, and a durably queued message is what guarantees the thread - // re-launches inside the worktree. + // Queue continuation immediately after binding; detachment terminates the caller, so relaunch needs a durable message. const queueContinuation: Effect.Effect = Effect.suspend(() => input.continuationPrompt === undefined @@ -385,7 +367,7 @@ const make = Effect.gen(function* () { worktreePath, branch: worktree.worktree.refName, baseRef, - startedFromOrigin: startFromOrigin, + startedFromOrigin, setupScript, continuation, note: @@ -402,11 +384,7 @@ const make = Effect.gen(function* () { function* (callerScope, input) { yield* requireCapability(callerScope); const scope = yield* requireThreadScope(callerScope); - // uninterruptibleMask: the guard acquisition and the registration of the - // releasing finalizer happen with no interruptible gap in between. An - // interrupt landing between a bare add() and the start of an ensured - // effect would otherwise leak the guard entry and block every future - // handoff for this thread until restart. + // Acquire and register cleanup atomically so cancellation cannot strand the guard until restart. return yield* Effect.uninterruptibleMask((restore) => Effect.suspend(() => { if (handoffThreadsInFlight.has(scope.thread.threadId)) { diff --git a/apps/server/src/mcp/threadAccess.test.ts b/apps/server/src/mcp/threadAccess.test.ts new file mode 100644 index 0000000000000..aa107711f334e --- /dev/null +++ b/apps/server/src/mcp/threadAccess.test.ts @@ -0,0 +1,40 @@ +import { expect, it } from "@effect/vitest"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as McpInvocationContext from "./McpInvocationContext.ts"; +import { liveThreadShell } from "./McpToolAccess.testkit.ts"; +import { readThread } from "./threadAccess.ts"; + +const bareId = ThreadId.make("5d0b4a3e-8c1f-4a52-9d37-2f6c7e1b9a04"); +const client: McpInvocationContext.McpInvocationScope = { + environmentId: EnvironmentId.make("environment:thread-access"), + requestNamespace: "client:thread-access", + thread: undefined, + client: { sessionId: "thread-access", label: "Claude Code", access: "full-access" }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, +}; + +const readBare = (existing: ReadonlyArray) => + readThread(bareId).pipe( + Effect.flip, + Effect.provideService(McpInvocationContext.McpInvocationContext, client), + Effect.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (threadId) => + Effect.succeed(existing.includes(threadId) ? liveThreadShell(threadId) : null), + }), + ), + ); + +it.effect("points a bare uuid at the mcp: thread it belongs to", () => + Effect.gen(function* () { + const error = yield* readBare([ThreadId.make(`mcp:${bareId}`)]); + + expect(error.code).toBe("thread_not_found"); + expect(error.message).toBe(`The thread was not found. Did you mean \`mcp:${bareId}\`?`); + }), +); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index be70ecf1807fb..9f3a8a57c05b2 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -102,12 +102,7 @@ export const assertTargetWithinLimits = ( Effect.asVoid, ); -/** - * A thread caller acts only while it owns a live run, or a background - * subagent that run started, of a thread that is not archived, so a provider - * token that outlived its session cannot act. An OAuth client has no run; its - * session and ceiling are its authority. - */ +/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */ export function assertLiveCaller({ caller, scope }: Caller) { if (caller === undefined) return Effect.void; return OrchestrationMcp.isLiveCallerShell(caller, scope.thread?.providerInstanceId) @@ -156,10 +151,11 @@ export const readThread = Effect.fn("mcp.readThread")(function* < const targetId = yield* resolveThreadId(context, threadId); const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable)); if (shell === null || shell.deletedAt !== null) { - return yield* new OrchestratorMcpFailure({ - code: "thread_not_found", - message: "The thread was not found.", - }); + return yield* OrchestrationMcp.threadNotFound( + context.threads, + targetId, + "The thread was not found.", + ); } const projection = yield* context.threads .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, { diff --git a/apps/server/src/mcp/toolkits/attachment/handlers.ts b/apps/server/src/mcp/toolkits/attachment/handlers.ts index e1a6428eba8d3..4c7f168f60128 100644 --- a/apps/server/src/mcp/toolkits/attachment/handlers.ts +++ b/apps/server/src/mcp/toolkits/attachment/handlers.ts @@ -34,10 +34,7 @@ export function resolveAttachmentReferences( }); } -/** - * The sweep counts its 24 hours from when the upload finishes, which can be up - * to the upload URL's lifetime after issue. - */ +/** The 24-hour sweep starts at upload completion, possibly one upload-URL lifetime after issue. */ const UPLOAD_OWNER_TTL_MS = 24 * 60 * 60 * 1000 + ATTACHMENT_UPLOAD_URL_TTL_MS; const uploadOwner = McpInvocationContext.McpInvocationContext.pipe( diff --git a/apps/server/src/mcp/toolkits/attachment/input.ts b/apps/server/src/mcp/toolkits/attachment/input.ts index f29d00d1f9f9d..1f37edbbf6d4d 100644 --- a/apps/server/src/mcp/toolkits/attachment/input.ts +++ b/apps/server/src/mcp/toolkits/attachment/input.ts @@ -2,8 +2,7 @@ import { ChatFileAttachment, ChatImageAttachment } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; -// Screenshot provenance is app-owned. Existing attachments recover it from stored -// metadata; exposing its recursive accessibility tree breaks model tool schemas. +// Keep screenshot provenance in app metadata; its recursive tree breaks model tool schemas. export const McpAttachmentInput = Schema.Union([ ChatImageAttachment.mapFields(Struct.omit(["source"])), ChatFileAttachment, diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 45ea89082f42e..76d8131e27bb9 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1,8 +1,6 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; -import { AjvJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/ajv"; -import type { JsonSchemaType } from "@modelcontextprotocol/sdk/validation"; import { DEFAULT_SERVER_SETTINGS, ChatImageAttachment, @@ -13,17 +11,20 @@ import { ProviderDriverKind, ProviderInstanceId, RunId, + RuntimeRequestId, ThreadId, TurnItemId, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as TestClock from "effect/testing/TestClock"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import { McpAttachmentInput } from "./attachment/input.ts"; -import { McpSchema, McpServer, Tool } from "effect/ai"; +import { McpSchema, McpServer } from "effect/ai"; import { FetchHttpClient } from "effect/http"; import { @@ -48,37 +49,20 @@ import * as ServerSettings from "../../serverSettings.ts"; import * as McpHttpServer from "../McpHttpServer.ts"; import * as McpInvocationContext from "../McpInvocationContext.ts"; import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts"; +import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; import { dispatchFailure } from "../threadAccess.ts"; -import { OrchestratorToolkit } from "./orchestrator/tools.ts"; -import { PreviewToolkit } from "./preview/tools.ts"; -import { PreviewControlsToolkit } from "./previewControls/tools.ts"; -import { EnvironmentToolkit } from "./environment/tools.ts"; import * as EnvironmentHandlers from "./environment/handlers.ts"; -import { ProjectToolkit } from "./project/tools.ts"; -import { AttachmentToolkit } from "./attachment/tools.ts"; import * as AttachmentHandlers from "./attachment/handlers.ts"; -import { ThreadToolkit } from "./thread/tools.ts"; -import { WorktreeToolkit } from "./worktree/tools.ts"; -import { DeviceToolkit } from "./device/tools.ts"; const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})), ); -// Effect returns a declared tool failure as `isError` with its encoded payload -// as JSON text, never as `structuredContent`. const declaredFailure = (result: McpSchema.CallToolResult) => { const text = result.content[0]; return result.isError === true && text?.type === "text" ? JSON.parse(text.text) : undefined; }; -import { PullRequestsToolkit } from "./pullRequests/tools.ts"; -import { HtmlToolkit } from "./html/tools.ts"; -import { - resolveT3McpToolDefinition, - resolveT3McpToolPresentation, - resolveT3McpToolSummaryAction, -} from "@t3tools/shared/t3McpToolPresentation"; import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput); @@ -89,43 +73,6 @@ const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe( Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), ); -it("publishes unique tool names with reference-free object-root inputs", () => { - const names = new Set(); - for (const toolkit of [ - OrchestratorToolkit, - PreviewToolkit, - WorktreeToolkit, - ThreadToolkit, - AttachmentToolkit, - ProjectToolkit, - EnvironmentToolkit, - PreviewControlsToolkit, - DeviceToolkit, - PullRequestsToolkit, - HtmlToolkit, - ]) { - for (const tool of Object.values(toolkit.tools)) { - expect(names.has(tool.name)).toBe(false); - names.add(tool.name); - const schema = Tool.getJsonSchema(tool); - expect(schema).toMatchObject({ type: "object" }); - expect(JSON.stringify(schema), tool.name).not.toContain('"$ref"'); - const definition = resolveT3McpToolDefinition(tool.name); - expect(definition, tool.name).not.toBeNull(); - expect( - definition?.labels.every((label) => label.trim().length > 0), - tool.name, - ).toBe(true); - for (const name of [tool.name, `mcp__t3-code__${tool.name}`, `T3-code.${tool.name}`]) { - expect(resolveT3McpToolPresentation(name)?.logo, name).toBe("t3-code"); - expect(resolveT3McpToolSummaryAction(name), name).not.toBeNull(); - } - } - } - expect(names.has("t3_thread_launch")).toBe(true); - expect(names.has("t3_thread_start")).toBe(false); -}); - const threadId = ThreadId.make("mcp-core-thread"); const scope: McpInvocationContext.McpInvocationScope = { environmentId: EnvironmentId.make("mcp-core-environment"), @@ -179,36 +126,30 @@ it.effect("checks capability through the production registration", () => ), ); -it.effect("returns a bounded public failure without serializing storage causes", () => - Effect.gen(function* () { +it.effect("an answered question reports already answered instead of not found", () => { + const shell = McpToolAccessTestkit.liveThreadShell(threadId); + const requestId = RuntimeRequestId.make("answered-question"); + const projection = McpToolAccessTestkit.idleThreadProjection(shell); + return Effect.gen(function* () { const server = yield* McpServer.McpServer; - const result = yield* server - .callTool({ name: "t3_thread_organize", arguments: { action: "pin" } }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, scope), - Effect.provideService(McpSchema.McpServerClient, client), - ); - expect(declaredFailure(result)).toEqual({ - _tag: "OrchestratorMcpFailure", - code: "orchestration_error", - message: "The operation could not be completed.", + const respond = (id: string) => + server + .callTool({ + name: "t3_pending_request_respond", + arguments: { requestId: id, answers: { size: "large" } }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(declaredFailure(yield* respond(requestId))).toMatchObject({ + code: "invalid_request", + message: "The user-input request was already answered.", + }); + expect(declaredFailure(yield* respond("missing-question"))).toMatchObject({ + code: "invalid_request", + message: "The pending user-input request was not found.", }); - expect(result.isError).toBe(true); - expect(result.content).toEqual([ - { - type: "text", - text: '{"_tag":"OrchestratorMcpFailure","code":"orchestration_error","message":"The operation could not be completed."}', - }, - ]); - const definition = server.tools.find(({ tool }) => tool.name === "t3_thread_organize"); - expect(definition?.tool.outputSchema).toBeDefined(); - const validate = new AjvJsonSchemaValidator().getValidator( - definition!.tool.outputSchema! as JsonSchemaType, - ); - expect(result.structuredContent).toBeUndefined(); - expect(validate({ sequence: 1 }).valid).toBe(true); - expect(validate({ code: "orchestration_error" }).valid).toBe(false); - expect(validate({ sequence: "invalid" }).valid).toBe(false); }).pipe( Effect.provide( layerThreadToolkit.pipe( @@ -216,19 +157,53 @@ it.effect("returns a bounded public failure without serializing storage causes", Layer.provide(NodeCrypto.layer), Layer.provide( Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => - Effect.fail( - new OrchestratorProjectionError({ - threadId, - cause: new Error("private-storage-path"), - }), - ), + getThreadShell: () => Effect.succeed(shell), + getProjectThreadRecords: () => + Effect.succeed({ + ...projection, + runtimeRequests: [ + { + id: requestId, + nodeId: NodeId.make("root"), + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "resolved", + responseCapability: { type: "message" }, + createdAt: shell.createdAt, + resolvedAt: shell.updatedAt, + answers: { size: "large" }, + }, + ], + turnItems: [ + { + id: TurnItemId.make("answered-question-item"), + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: shell.createdAt, + completedAt: shell.updatedAt, + updatedAt: shell.updatedAt, + type: "user_input_request", + requestId, + questions: [], + }, + ], + }), + dispatch: () => Effect.die("an answered question must not dispatch again"), }), ), ), ), - ), -); + ); +}); it("bounds public command rejections and redacts internal dispatch causes", () => { const command = { commandId: CommandId.make("mcp-core-command"), commandType: "thread.settle" }; @@ -290,6 +265,7 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both Effect.provide( McpHttpServer.layerHtmlToolkit.pipe( Layer.provideMerge(McpServer.McpServer.layer), + Layer.provide(McpProviderSessions.layer), Layer.provide(PreviewBrowser.layer), Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-html-render-" })), Layer.provide(NodeServices.layer), @@ -311,27 +287,60 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both ), ); -it.effect("returns invalid parameter errors through the production registration", () => - Effect.gen(function* () { +it.effect("records only failed calls of tools that hand off no work", () => { + // Recording runs detached from the tool response, so the first event is awaited. + const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>(); + return Effect.gen(function* () { const server = yield* McpServer.McpServer; - const error = yield* server - .callTool({ name: "t3_thread_organize", arguments: { action: "invalid" } }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + const organize = (capabilities: McpInvocationContext.McpInvocationScope["capabilities"]) => + server.callTool({ name: "t3_thread_organize", arguments: { action: "pin" } }).pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, { + ...scope, + capabilities, + }), Effect.provideService(McpSchema.McpServerClient, client), - Effect.flip, ); - expect(error._tag).toBe("InvalidParams"); + expect((yield* organize(scope.capabilities)).isError).not.toBe(true); + expect(declaredFailure(yield* organize(new Set()))).toMatchObject({ + code: "capability_denied", + }); + // The successful call ran first, so it would be the first event if it were recorded. + expect(yield* Deferred.await(recorded)).toMatchObject({ + event: "mcp.tool.invoked", + properties: { tool: "t3_thread_organize", outcome: "error" }, + }); }).pipe( Effect.provide( layerThreadToolkit.pipe( Layer.provideMerge(McpServer.McpServer.layer), Layer.provide(NodeCrypto.layer), - Layer.provide(Layer.mock(ThreadManagement.ThreadManagementService)({})), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: ({ threadId: id }) => + Effect.succeed( + McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)), + ), + dispatch: () => Effect.succeed({ sequence: 1 } as never), + }), + ), + Layer.provide( + Layer.succeed( + AnalyticsService.AnalyticsService, + AnalyticsService.AnalyticsService.of({ + record: (event, properties) => + Deferred.succeed(recorded, { event, properties: properties ?? {} }).pipe( + Effect.asVoid, + ), + flush: Effect.void, + recordOwners: () => Effect.void, + }), + ), + ), ), ), - ), -); + ); +}); it.effect("keeps unexpected handler defects private through the production registration", () => Effect.gen(function* () { diff --git a/apps/server/src/mcp/toolkits/device/handlers.test.ts b/apps/server/src/mcp/toolkits/device/handlers.test.ts index 110d4cbba72a6..0ad4b95581b2d 100644 --- a/apps/server/src/mcp/toolkits/device/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/device/handlers.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { agentDeviceQuickStart, agentDeviceTargetArgs, pngDimensions } from "./handlers.ts"; +import { agentDeviceQuickStart, pngDimensions } from "./handlers.ts"; const device = { hostId: "local", @@ -13,23 +13,6 @@ const device = { }; describe("device tool helpers", () => { - it("pins agent-device commands to the device by platform-specific flag", () => { - expect(agentDeviceTargetArgs(device)).toEqual(["--platform", "ios", "--udid", "ABCD-1234"]); - expect(agentDeviceTargetArgs({ ...device, platform: "android", id: "emulator-5554" })).toEqual([ - "--platform", - "android", - "--serial", - "emulator-5554", - ]); - }); - - it("writes the quick start around the pinned target", () => { - const text = agentDeviceQuickStart(device); - expect(text).toContain("agent-device snapshot -i --platform ios --udid ABCD-1234"); - expect(text).toContain("iPhone 17 Pro (iOS 27.0)"); - expect(text).toContain("XCTest runner"); - }); - it("uses the absolute launcher in every quick-start command", () => { const text = agentDeviceQuickStart( device, diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.ts index d42efd9168c45..8fdbd264b8726 100644 --- a/apps/server/src/mcp/toolkits/device/handlers.ts +++ b/apps/server/src/mcp/toolkits/device/handlers.ts @@ -15,11 +15,12 @@ import { ensureAgentDeviceShim } from "../../../device/AgentDeviceShim.ts"; import { nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime"; import * as DeviceService from "../../../device/DeviceService.ts"; +import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { DeviceScreenshotToolkit, DeviceStandardToolkit, DeviceToolkit } from "./tools.ts"; -export function agentDeviceTargetArgs(device: DeviceSummary): ReadonlyArray { +function agentDeviceTargetArgs(device: DeviceSummary): ReadonlyArray { return device.platform === "ios" ? ["--platform", "ios", "--udid", device.id] : ["--platform", "android", "--serial", device.id]; @@ -29,6 +30,7 @@ export function agentDeviceQuickStart( device: DeviceSummary, targetArgs = agentDeviceTargetArgs(device), command = "agent-device", + cloud = false, ): string { const executable = /^[a-zA-Z0-9_./:-]+$/.test(command) ? command @@ -38,8 +40,9 @@ export function agentDeviceQuickStart( /^[a-zA-Z0-9_./:-]+$/.test(arg) ? arg : "'" + arg.replaceAll("'", "'\"'\"'") + "'", ) .join(" "); - const platformNotes = - device.platform === "ios" + const platformNotes = cloud + ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine." + : device.platform === "ios" ? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast." : "The Android snapshot helper installs itself on first use."; return [ @@ -69,46 +72,45 @@ const requireDeviceAccess = McpInvocationContext.requireThreadMcpCapability("dev ), ); -const pickDevice = ( +const pickDevice = Effect.fn("handlers.pickDevice")(function* ( devices: ReadonlyArray, input: { readonly deviceId?: DeviceId | undefined; readonly platform?: DevicePlatform | undefined; readonly hostId?: DeviceHostId | undefined; }, -): Effect.Effect => - Effect.gen(function* () { - const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID; - if (input.deviceId !== undefined) { - const match = devices.find( - (device) => device.hostId === hostId && device.id === input.deviceId, - ); - if (match) return match; - return yield* new DeviceToolUnavailableError({ - reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`, - }); - } - const candidates = devices.filter( - (device) => - device.hostId === hostId && - (input.platform === undefined || device.platform === input.platform), +): Effect.fn.Return { + const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID; + if (input.deviceId !== undefined) { + const match = devices.find( + (device) => device.hostId === hostId && device.id === input.deviceId, ); - if (candidates.length === 0) { - return yield* new DeviceToolUnavailableError({ - reason: - input.platform === undefined - ? "No simulators or emulators were found. Call device_list to see why." - : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`, - }); - } - const platforms = new Set(candidates.map((device) => device.platform)); - if (input.platform === undefined && platforms.size > 1) { - return yield* new DeviceToolUnavailableError({ - reason: "Both iOS and Android devices are available; pass platform or deviceId.", - }); - } - return candidates.find((device) => device.booted) ?? candidates[0]!; - }); + if (match) return match; + return yield* new DeviceToolUnavailableError({ + reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`, + }); + } + const candidates = devices.filter( + (device) => + device.hostId === hostId && + (input.platform === undefined || device.platform === input.platform), + ); + if (candidates.length === 0) { + return yield* new DeviceToolUnavailableError({ + reason: + input.platform === undefined + ? "No simulators or emulators were found. Call device_list to see why." + : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`, + }); + } + const platforms = new Set(candidates.map((device) => device.platform)); + if (input.platform === undefined && platforms.size > 1) { + return yield* new DeviceToolUnavailableError({ + reason: "Both iOS and Android devices are available; pass platform or deviceId.", + }); + } + return candidates.find((device) => device.booted) ?? candidates[0]!; +}); const toolError = (error: DeviceError | DeviceToolUnavailableError) => error; @@ -153,23 +155,38 @@ const handlers = { } const target = yield* pickDevice(state.devices, input); // Resolve consent and agent connectivity before booting or registering a session. - const agentArgs = yield* devices.agentTarget({ - threadId: scope.thread.threadId, - hostId: target.hostId, - deviceId: target.id, - }); - const session = yield* devices.open({ - threadId: scope.thread.threadId, - hostId: target.hostId, - deviceId: target.id, - platform: target.platform, - }); + if (!(yield* devices.agentReadinessIfSupported(target.hostId))) { + return yield* new DeviceToolUnavailableError({ + reason: + "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.", + }); + } + const session = yield* devices.open( + { + threadId: scope.thread.threadId, + hostId: target.hostId, + deviceId: target.id, + platform: target.platform, + }, + { workspaceRoot: yield* threadWorkspaceRoot(scope.thread.threadId) }, + ); const after = yield* devices.state; const device = after.devices.find( (candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId, ) ?? target; - const targetArgs = [...agentDeviceTargetArgs(device), ...agentArgs]; + // Target the opened device: an EAS device and its agent-device daemon + // exist only once its session runs, and Android ids change on boot. + const agent = yield* devices.agentTarget({ + threadId: scope.thread.threadId, + hostId: device.hostId, + deviceId: device.id, + }); + const cloud = after.hosts.some((host) => host.id === device.hostId && host.kind === "eas"); + const targetArgs = [ + ...agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId }), + ...agent.args, + ]; const config = yield* ServerConfig.ServerConfig; const path = yield* Path.Path; const platform = yield* HostProcess.Platform; @@ -195,7 +212,7 @@ const handlers = { return { device, agentDevice: { command, targetArgs }, - quickStart: agentDeviceQuickStart(device, targetArgs, command), + quickStart: agentDeviceQuickStart(device, targetArgs, command, cloud), }; }).pipe(Effect.mapError(toolError)), ), diff --git a/apps/server/src/mcp/toolkits/device/tools.ts b/apps/server/src/mcp/toolkits/device/tools.ts index 5771e8233cd7a..36a91b844ade5 100644 --- a/apps/server/src/mcp/toolkits/device/tools.ts +++ b/apps/server/src/mcp/toolkits/device/tools.ts @@ -17,6 +17,7 @@ import { Tool, Toolkit } from "effect/ai"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as DeviceService from "../../../device/DeviceService.ts"; import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "../../../project/ProjectService.ts"; const dependencies = [ McpInvocationContext.McpInvocationContext, @@ -29,8 +30,7 @@ const DeviceToolFailure = Schema.Union([DeviceToolError, OrchestratorMcpFailure] const DeviceListTool = Tool.make("device_list", { description: "List iOS Simulators and Android Emulators on this environment's device hosts, which platforms each host can run, and which devices are already open in this thread's Device panel. Call this before device_open when you do not know a device id.", - // An empty struct serializes as `anyOf [object, array]`, which some - // providers reject and then drop every tool on the server with it. + // Empty Struct emits object|array, which can make providers reject every server tool. parameters: Schema.Struct({ hostId: Schema.optional( Schema.String.annotate({ description: "Limit to one device host. Defaults to all hosts." }), @@ -52,7 +52,14 @@ const DeviceOpenTool = Tool.make("device_open", { parameters: DeviceToolOpenInput, success: DeviceToolOpenResult, failure: DeviceToolFailure, - dependencies: [...dependencies, FileSystem.FileSystem, Path.Path, ServerConfig.ServerConfig], + dependencies: [ + ...dependencies, + FileSystem.FileSystem, + Path.Path, + ServerConfig.ServerConfig, + // The thread's project can name the EAS project a cloud device runs under. + ProjectService.ProjectService, + ], }) .annotate(Tool.Title, "Open device") .annotate(Tool.Readonly, false) diff --git a/apps/server/src/mcp/toolkits/environment/handlers.test.ts b/apps/server/src/mcp/toolkits/environment/handlers.test.ts index c870a7354bcd2..b4d39bd41c17f 100644 --- a/apps/server/src/mcp/toolkits/environment/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/environment/handlers.test.ts @@ -12,13 +12,11 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; -import { McpSchema, McpServer } from "effect/ai"; import * as Environment from "../../../environment/ServerEnvironment.ts"; import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts"; import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts"; import * as Settings from "../../../serverSettings.ts"; -import * as McpHttpServer from "../../McpHttpServer.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { liveThreadShell } from "../../McpToolAccess.testkit.ts"; @@ -27,71 +25,6 @@ import { EnvironmentToolkit } from "./tools.ts"; const environmentId = EnvironmentId.make("environment:preferences"); const threadId = ThreadId.make("thread:preferences"); -const caller: McpInvocationContext.McpInvocationScope = { - environmentId, - requestNamespace: "provider:preferences", - thread: { - threadId, - providerSessionId: "provider:preferences", - providerInstanceId: ProviderInstanceId.make("codex"), - }, - client: undefined, - capabilities: new Set(["orchestration" as const]), - issuedAt: 0, -}; -const layerEnvironment = Layer.mock(Environment.ServerEnvironment)({ - getDescriptor: Effect.succeed({ - environmentId, - label: "Test", - platform: { os: "linux", arch: "x64" }, - serverVersion: "0.0.0", - capabilities: { repositoryIdentity: false }, - }), -}); - -it.effect("updates preferences for a thread caller through the /mcp registration", () => - Effect.gen(function* () { - const server = yield* McpServer.McpServer; - const result = yield* server - .callTool({ - name: "t3_environment_preferences_update", - arguments: { newWorktreesStartFromOrigin: true }, - }) - .pipe( - Effect.provideService(McpInvocationContext.McpInvocationContext, caller), - Effect.provideService( - McpSchema.McpServerClient, - McpSchema.McpServerClient.of({ - clientId: 1, - protocolVersion: "2025-06-18", - clientCapabilities: {}, - clientInfo: { name: "preferences", version: "1" }, - initializePayload: { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "preferences", version: "1" }, - }, - getClient: Effect.die("unused"), - }), - ), - ); - expect(result.isError).toBe(false); - expect(result.structuredContent).toMatchObject({ newWorktreesStartFromOrigin: true }); - }).pipe( - Effect.provide( - McpHttpServer.layerEnvironmentToolkit.pipe( - Layer.provideMerge(McpServer.McpServer.layer), - Layer.provide( - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: (id) => Effect.succeed(liveThreadShell(id)), - }), - ), - Layer.provide(layerEnvironment), - Layer.provide(Settings.layerTest()), - ), - ), - ), -); it.effect("refuses a preferences update when the caller's turn ends while it waits", () => Effect.gen(function* () { diff --git a/apps/server/src/mcp/toolkits/html/handlers.ts b/apps/server/src/mcp/toolkits/html/handlers.ts index 9ef61c1fcfab1..1a402ca0bb4e1 100644 --- a/apps/server/src/mcp/toolkits/html/handlers.ts +++ b/apps/server/src/mcp/toolkits/html/handlers.ts @@ -10,6 +10,7 @@ const INVALID_PAGE_ERRORS = new Set([ "HtmlRenderImagesNotFoundError", "HtmlRenderImageTooLargeError", "HtmlRenderPageTooLargeError", + "HtmlRenderViewportHeightError", ]); const toFailure = (error: { readonly _tag: string; readonly message: string }) => @@ -19,8 +20,7 @@ const toFailure = (error: { readonly _tag: string; readonly message: string }) = }); const handlers = { - // The headless browser runs on the host and can open local files, so only - // agents T3 launched, which already work on this machine, get it. + // Local-file access limits this host browser to T3-launched agents. html_preview: McpToolAccess.readsAsCaller((input) => Effect.gen(function* () { const htmlRender = yield* HtmlRender.HtmlRender; diff --git a/apps/server/src/mcp/toolkits/html/tools.ts b/apps/server/src/mcp/toolkits/html/tools.ts index 993acd9453ee5..f061923993b84 100644 --- a/apps/server/src/mcp/toolkits/html/tools.ts +++ b/apps/server/src/mcp/toolkits/html/tools.ts @@ -2,6 +2,7 @@ import { OrchestratorMcpFailure } from "@t3tools/contracts"; import { HTML_RENDER_COLUMN_WIDTH, HTML_RENDER_LAYOUT_GUIDE, + HTML_RENDER_MAX_FIT_HEIGHT, HTML_RENDER_MAX_HEIGHT, HTML_RENDER_MAX_TITLE_LENGTH, HTML_RENDER_MIN_HEIGHT, @@ -68,10 +69,9 @@ export const HtmlPreviewTool = Tool.make("html_preview", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, true); -// Read-only in the MCP sense: it shows a page in the caller's own thread and -// touches no workspace, so plan mode and read-only sandboxes can use it. +// This affects only the caller's thread, not its workspace, so read-only sandboxes and plan mode may use it. const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, { - description: `Show a finished HTML page (chart, table, diagram, collage, mockup) inline in this thread, above your final text reply; call it before writing that reply. The reader already sees the page, so the reply should not announce it, say where it is, or restate it: add only what the page doesn't say. Preview with html_preview first. T3 fits the frame to the page's height at each reader's width. A height below the page's contentHeight caps the frame there, and the rest scrolls inside it. ${PAGE_RULES} ${HTML_RENDER_LAYOUT_GUIDE} ${HTML_RENDER_THEME_GUIDE}`, + description: `Show a finished HTML page (chart, table, diagram, collage, mockup) inline in this thread, above your final text reply; call it before writing that reply. The reader already sees the page, so the reply should not announce it, say where it is, or restate it: add only what the page doesn't say. Preview with html_preview first. T3 fits the frame to the page's height at each reader's width. On mobile, a height below the page's contentHeight caps the frame there, and the rest scrolls inside it; web and desktop fit the whole page, up to ${HTML_RENDER_MAX_FIT_HEIGHT}px. ${PAGE_RULES} ${HTML_RENDER_LAYOUT_GUIDE} ${HTML_RENDER_THEME_GUIDE}`, parameters: Schema.Struct({ html: Html, title: Schema.String.check( @@ -79,7 +79,7 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, { Schema.isMaxLength(HTML_RENDER_MAX_TITLE_LENGTH), ).annotate({ description: "Short name for the page." }), height: Schema.Int.annotate({ - description: `The frame height in CSS pixels, ${HTML_RENDER_MIN_HEIGHT}-${HTML_RENDER_MAX_HEIGHT}. Use html_preview's contentHeight, or less to make long content scroll inside the frame.`, + description: `The frame height in CSS pixels, ${HTML_RENDER_MIN_HEIGHT}-${HTML_RENDER_MAX_HEIGHT}. Use html_preview's contentHeight. A lower height makes long content scroll inside the frame on mobile only.`, }), }), success: Schema.Struct({ @@ -88,7 +88,6 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, { title: Schema.String, height: Schema.Number, heights: Schema.optional(Schema.Array(Schema.Tuple([Schema.Int, Schema.Int]))), - outline: Schema.optional(Schema.String), }), message: Schema.String, }), diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 7c05b330047cf..a6f9a1302c670 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -9,11 +9,11 @@ import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts"; import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; const handlers = { - orchestrator_capabilities: McpToolAccess.reads(() => + orchestrator_capabilities: McpToolAccess.reads((input) => Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; const service = yield* OrchestratorMcpService.OrchestratorMcpService; - return yield* service.capabilities(scope); + return yield* service.capabilities(scope, input); }), ), delegate_task: McpToolAccess.actsAsCaller((input) => @@ -57,6 +57,27 @@ const handlers = { ); }), ), + t3_background_wait: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const { scope, threads } = yield* readCaller(); + const caller = yield* McpInvocationContext.requireThreadScope(scope, "t3_background_wait"); + return yield* threads + .awaitBackgroundTasks({ + threadId: caller.thread.threadId, + taskIds: input.taskIds, + awaited: input.waiting ?? true, + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorMcpFailure({ + code: cause.reason === "unsupported" ? "invalid_request" : "orchestration_error", + message: cause.message, + }), + ), + ); + }), + ), schedule_task: McpToolAccess.startsThreads( () => ({}), (input) => diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts deleted file mode 100644 index b8f735069d31c..0000000000000 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import { Tool } from "effect/ai"; - -import { - CreateThreadsTool, - DelegateTaskTool, - OrchestratorToolkit, - ScheduleTaskTool, - ThreadUpdateTool, -} from "./tools.ts"; - -describe("orchestrator MCP tool guidance", () => { - it("directs subagent requests to delegation instead of ordinary threads", () => { - assert.include(DelegateTaskTool.description ?? "", "child agent/subagent"); - assert.include(DelegateTaskTool.description ?? "", "cross-provider"); - assert.include(CreateThreadsTool.description ?? "", "not delegation"); - assert.include(CreateThreadsTool.description ?? "", "call delegate_task"); - assert.include(DelegateTaskTool.description ?? "", "waitTimedOut"); - assert.include(DelegateTaskTool.description ?? "", "does not cancel the child"); - assert.include(DelegateTaskTool.description ?? "", "keep that taskId"); - assert.include(DelegateTaskTool.description ?? "", "call delegate_task again"); - assert.include(DelegateTaskTool.description ?? "", "childThreadId is backing storage"); - assert.include( - OrchestratorToolkit.tools.t3_thread_send.description ?? "", - "a requested follow-up creates a fresh task", - ); - assert.include( - OrchestratorToolkit.tools.task_cancel.description ?? "", - "This includes later child-thread runs, even after the task is terminal", - ); - }); - - it("documents wait timeout as a parent budget, not a child failure", () => { - const schema = Tool.getJsonSchema(DelegateTaskTool) as { - readonly properties?: Readonly< - Record< - string, - { - readonly description?: unknown; - readonly anyOf?: ReadonlyArray<{ readonly description?: unknown }>; - } - > - >; - }; - const mode = schema.properties?.mode; - const timeoutMs = schema.properties?.timeoutMs; - const modeText = [mode?.description, ...(mode?.anyOf ?? []).map((entry) => entry.description)] - .filter((value) => typeof value === "string") - .join(" "); - const timeoutText = [ - timeoutMs?.description, - ...(timeoutMs?.anyOf ?? []).map((entry) => entry.description), - ] - .filter((value) => typeof value === "string") - .join(" "); - assert.include(modeText, "Defaults to async"); - assert.include(timeoutText, "does not cancel the child"); - }); - - it("publishes an actionable schedule schema and compatibility string branch", () => { - const schema = Tool.getJsonSchema(ScheduleTaskTool) as { - readonly type?: unknown; - readonly properties?: Readonly< - Record }> - >; - }; - - assert.equal(schema.type, "object"); - assert.isString(schema.properties?.schedule?.description); - assert.isAtLeast(schema.properties?.schedule?.anyOf?.length ?? 0, 2); - assert.include(ScheduleTaskTool.description ?? "", "STRUCTURED OBJECT"); - assert.include(ScheduleTaskTool.description ?? "", "nextRunAt"); - }); - - it("publishes thread metadata actions from an object-root schema", () => { - const schema = Tool.getJsonSchema(ThreadUpdateTool) as { - readonly type?: unknown; - readonly properties?: Readonly>; - }; - - assert.equal(schema.type, "object"); - assert.hasAllKeys(schema.properties ?? {}, [ - "threadId", - "action", - "title", - "pullRequest", - "clientRequestId", - ]); - assert.include(ThreadUpdateTool.description ?? "", "Workspace and branch changes"); - }); -}); diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 05299626c6748..2b56e12b025a8 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -1,4 +1,5 @@ import { + OrchestratorMcpCapabilitiesInput, OrchestratorMcpCapabilitiesResult, OrchestrationV2StopWorkflowInput, OrchestratorMcpCreateThreadsInput, @@ -30,6 +31,7 @@ import { OrchestratorMcpThreadWaitResult, ThreadMetadataMcpUpdateInput, ThreadMetadataMcpUpdateResult, + TrimmedNonEmptyString, } from "@t3tools/contracts"; import { Tool, Toolkit } from "effect/ai"; import * as Schema from "effect/Schema"; @@ -52,7 +54,8 @@ const threadMetadataDependencies = [ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", { description: - "List the V2 provider instances and their current models from the same live catalog as the composer, including configured custom models, inherited runtime settings, and app-owned orchestration features available to this caller. For a separate top-level thread in a new or existing worktree, use t3_thread_launch with workspaceStrategy.", + "List the V2 provider instances, a short list of their models from the same live catalog as the composer, inherited runtime settings, and app-owned orchestration features available to this caller. The list has the user's favorite and custom models, your own model, every current Codex, Claude, Muse and Grok model, and the first 8 current models of other providers. Other legacy models are left out. omittedModels counts models left out; pass search, such as 'sonnet 4.6', to find them. delegate_task accepts any catalog model, listed or not. For a separate top-level thread in a new or existing worktree, use t3_thread_launch with workspaceStrategy.", + parameters: OrchestratorMcpCapabilitiesInput, success: OrchestratorMcpCapabilitiesResult, failure: OrchestratorMcpFailure, failureMode: "return", @@ -63,9 +66,9 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", { .annotate(Tool.Destructive, false) .annotate(Tool.Idempotent, true); -export const DelegateTaskTool = Tool.make("delegate_task", { +const DelegateTaskTool = Tool.make("delegate_task", { description: - "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.", + "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For independent T3 delegated review rounds, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. For a follow-up that needs the same child's conversation, use t3_thread_send on its childThreadId. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority; decisions remain with the child's existing approval holder, and pending request tools answer questions only. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.", parameters: OrchestratorMcpDelegateTaskInput, success: OrchestratorMcpDelegateTaskResult, failure: OrchestratorMcpFailure, @@ -78,7 +81,7 @@ export const DelegateTaskTool = Tool.make("delegate_task", { const TaskStatusTool = Tool.make("task_status", { description: - "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results. Reading a terminal result acknowledges its automatic parent delivery.", + "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Decisions remain with the child's existing approval holder. Reading a terminal result acknowledges its automatic parent delivery.", parameters: OrchestratorMcpTaskStatusInput, success: OrchestratorMcpDelegateTaskResult, failure: OrchestratorMcpFailure, @@ -92,7 +95,7 @@ const TaskStatusTool = Tool.make("task_status", { const TaskCancelTool = Tool.make("task_cancel", { description: - "Needs an agent running inside a T3 thread. Stop a T3-owned delegated task and dispose its automatic parent delivery. Its child thread stops like a user Stop: the running turn is interrupted, queued turns are held, pull request watches end, and the tasks it delegated stop too. This includes later child-thread runs, even after the task is terminal. A terminal task returns its existing status, and published task results remain available.", + "Needs an agent running inside a T3 thread. Stop a T3-owned delegated task and dispose its automatic parent delivery. Its child thread stops like a user Stop: the running turn is interrupted, other queued turns are held, pull request watches end, and the tasks it delegated stop too. The task's own queued turn is cancelled, including when held in a stopped queue. This includes later child-thread runs, even after the task is terminal. A terminal task returns its existing status, and published task results remain available.", parameters: OrchestratorMcpTaskCancelInput, success: OrchestratorMcpTaskCancelResult, failure: OrchestratorMcpFailure, @@ -114,9 +117,28 @@ const WorkflowStopTool = Tool.make("t3_workflow_stop", { .annotate(Tool.Title, "Stop a workflow") .annotate(Tool.Destructive, true); -export const ScheduleTaskTool = Tool.make("schedule_task", { +const BackgroundWaitTool = Tool.make("t3_background_wait", { description: - "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.", + "Keep this thread in the user's Working list and out of their inbox while you wait for background work. Start a background command or Monitor first. Call this before you end your turn if you will act on its result when it wakes you. In taskIds, give the ID shown when the task started. The thread stays in Working until the task ends. The user is not told the work is done. Do not mark work you leave running, such as a dev server or watcher. Unmarked commands and monitors never keep the thread in Working. Pass waiting=false to remove the mark. This does not stop the task. IDs that are not running return in unmatched and change nothing. Only Claude threads support this tool. Other providers return an error.", + parameters: Schema.Struct({ + taskIds: Schema.Array(TrimmedNonEmptyString).check( + Schema.isMinLength(1), + Schema.isMaxLength(20), + ), + waiting: Schema.optional(Schema.Boolean), + }), + success: Schema.Struct({ + matched: Schema.Array(Schema.String), + unmatched: Schema.Array(Schema.String), + }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies, +}).annotate(Tool.Title, "Wait on background work"); + +const ScheduleTaskTool = Tool.make("schedule_task", { + description: + "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhook dedupe accepts replayKey and coalesceKey templates with coalesceWindowSeconds (10–3600, default 120); replay keys expire after 7 days and coalescing keeps the latest payload in a window measured from its first delivery. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. To run only for some requests, add filters, all of which must match, e.g. filters:[{path:'headers.x-github-event', op:'equals', value:'pull_request'}, {path:'body.action', op:'in', value:['opened','reopened']}]; ops are equals, notEquals, in, startsWith and exists. A path segment ending in [] fans out over an array: {path:'body.issue.labels[].name', op:'equals', value:'needs more info'} matches when any label has that name, and notEquals only when none does. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.", parameters: OrchestratorMcpScheduleTaskInput, success: OrchestratorMcpScheduleTaskResult, failure: OrchestratorMcpFailure, @@ -143,7 +165,7 @@ const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", { const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", { description: - "Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run.", + "Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Webhook schedule dedupe accepts replayKey, coalesceKey, and coalesceWindowSeconds (10–3600, default 120) to suppress replays for 7 days and retain the latest payload in each fixed window. Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run. A webhook schedule without filters keeps the stored filters; pass filters to replace them, or filters:[] to clear them.", parameters: OrchestratorMcpUpdateScheduledTaskInput, success: OrchestratorMcpScheduleTaskResult, failure: OrchestratorMcpFailure, @@ -167,7 +189,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", { const RequestSecretTool = Tool.make("request_secret", { description: - "Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is kept by the app and NEVER returned to you or shown in the transcript. When saved, the result carries a secretRef: pass it to a tool that accepts one (e.g. schedule_task's signature.secretRef). It works once. Never ask for secrets in chat, and never invent one.", + "Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is NEVER returned to you or shown in the transcript. By default the result carries a one-use secretRef for a tool that accepts one (e.g. schedule_task's signature.secretRef). For a shell CLI token, set delivery to file. Never ask for secrets in chat, and never invent one.", parameters: OrchestratorMcpRequestSecretInput, success: OrchestratorMcpRequestSecretResult, failure: OrchestratorMcpFailure, @@ -177,9 +199,9 @@ const RequestSecretTool = Tool.make("request_secret", { .annotate(Tool.Title, "Request a secret from the user") .annotate(Tool.Destructive, false); -export const CreateThreadsTool = Tool.make("create_threads", { +const CreateThreadsTool = Tool.make("create_threads", { description: - "Needs an agent running inside a T3 thread. Create one or more ORDINARY TOP-LEVEL T3 conversations. This is not delegation and does not create child agents/subagents. For delegated work, choose models from orchestrator_capabilities. Prefer native subagents only when they support the chosen model; otherwise call delegate_task, including for same-provider work. Use create_threads for a batch of separate top-level threads sharing this checkout. Prefer t3_thread_launch for a single thread. Both require the user to request separate/new/top-level threads or conversations. Each entry may override provider, model, options, runtime mode, and interaction mode; omitted settings inherit. Project, branch, and worktree always inherit and cannot be overridden here. For independent implementation or a PR stack in its own worktree, use t3_thread_launch with workspaceStrategy instead of asking the agent to create a worktree in its prompt.", + "Needs an agent running inside a T3 thread. Create one or more ORDINARY TOP-LEVEL T3 conversations. This is not delegation and does not create child agents/subagents. For delegated work, choose models from orchestrator_capabilities. Prefer native subagents only when they support the chosen model and no model options are requested or inherited; otherwise call delegate_task, including for same-provider work. This includes keeping the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities. Use create_threads for a batch of separate top-level threads sharing this checkout. Prefer t3_thread_launch for a single thread. Both require the user to request separate/new/top-level threads or conversations. Each entry may override provider, model, options, runtime mode, and interaction mode; omitted settings inherit. Project, branch, and worktree always inherit and cannot be overridden here. For independent implementation or a PR stack in its own worktree, use t3_thread_launch with workspaceStrategy instead of asking the agent to create a worktree in its prompt.", parameters: OrchestratorMcpCreateThreadsInput, success: OrchestratorMcpCreateThreadsResult, failure: OrchestratorMcpFailure, @@ -192,7 +214,7 @@ export const CreateThreadsTool = Tool.make("create_threads", { const ThreadListTool = Tool.make("t3_thread_list", { description: - "List T3 threads in a project, newest first. Omit projectId for the calling thread's project. Filter by durable run status, title, or settled state (settled=true lists threads the user or auto-settlement moved out of the active list), or snoozed state, and paginate with the returned cursor. A snoozed thread wakes early when it asks for something, fails, or completes. To link a thread for the user, write `[title](t3-thread://v1/)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread's current title.", + "List T3 threads in a project, newest first. Omit projectId for the calling thread's project. Filter by durable run status, title, or settled state (settled=true lists threads the user or auto-settlement moved out of the active list), or snoozed state, and paginate with the returned cursor. A snoozed thread wakes early only when it asks for something or fails after snoozing; completed runs and background wakes keep it snoozed. pullRequests lists every pull request linked to each thread; linkedPullRequest is a legacy single link and can be null while pullRequests still has entries. Mention a thread with its `link`.", parameters: OrchestratorMcpThreadListInput, success: OrchestratorMcpThreadListResult, failure: OrchestratorMcpFailure, @@ -206,7 +228,7 @@ const ThreadListTool = Tool.make("t3_thread_list", { const ThreadReadTool = Tool.make("t3_thread_read", { description: - "Read durable state and a paginated timeline from any T3 thread in this environment. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Reading an untruncated terminal assistant result from this parent thread's direct app-owned child acknowledges that child's automatic completion delivery. Continue with afterPosition=nextPosition. Recover long item text with itemId and textOffset=nextTextOffset until nextTextOffset is null; offsets count UTF-16 code units. The thread also reports its snooze state. To link a thread for the user, write `[title](t3-thread://v1/)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread's current title.", + "Read durable state and a paginated timeline from any T3 thread in this environment. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Reading an untruncated terminal assistant result from this parent thread's direct app-owned child acknowledges that child's automatic completion delivery. Continue with afterPosition=nextPosition. Recover long item text with itemId and textOffset=nextTextOffset until nextTextOffset is null; offsets count UTF-16 code units. The thread also reports its snooze state and, in pullRequests, every linked pull request; linkedPullRequest is a legacy single link and can be null while pullRequests still has entries. Mention a thread with its `link`.", parameters: OrchestratorMcpThreadReadInput, success: OrchestratorMcpThreadReadResult, failure: OrchestratorMcpFailure, @@ -219,7 +241,7 @@ const ThreadReadTool = Tool.make("t3_thread_read", { .annotate(Tool.Destructive, false) .annotate(Tool.Idempotent, true); -export const ThreadUpdateTool = Tool.make("t3_thread_update", { +const ThreadUpdateTool = Tool.make("t3_thread_update", { description: "Update metadata for a thread. Omit threadId to update this thread. Use action='rename' with title, action='regenerate_title' with no extra field, action='link_pull_request' with pullRequest, or action='unlink_pull_request'. Workspace and branch changes are intentionally not supported. clientRequestId makes retries idempotent.", parameters: ThreadMetadataMcpUpdateInput, @@ -277,6 +299,7 @@ export const OrchestratorToolkit = Toolkit.make( TaskStatusTool, TaskCancelTool, WorkflowStopTool, + BackgroundWaitTool, ScheduleTaskTool, ListScheduledTasksTool, UpdateScheduledTaskTool, diff --git a/apps/server/src/mcp/toolkits/preview/handlers.test.ts b/apps/server/src/mcp/toolkits/preview/handlers.test.ts index a2a88e14fcefa..c46e358518084 100644 --- a/apps/server/src/mcp/toolkits/preview/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/preview/handlers.test.ts @@ -11,36 +11,7 @@ import { parseThreadSegmentFromAttachmentId, } from "../../../attachmentStore.ts"; import * as ServerConfig from "../../../config.ts"; -import { claimPreviewRecording, normalizePreviewOpenInput } from "./handlers.ts"; - -describe("normalizePreviewOpenInput", () => { - it("leaves an unstated visibility for the client preference to decide", () => { - // Filling `open` in here would outrank `browserAutoShowFloatingPreview`, - // which is desktop-local and cannot be read from the server. - expect(normalizePreviewOpenInput({})).toEqual({ reuseExistingTab: true }); - }); - - it("preserves an explicit background-only opt-out", () => { - expect(normalizePreviewOpenInput({ open: false })).toEqual({ - open: false, - reuseExistingTab: true, - show: false, - }); - }); - - it("supports show as a legacy alias while preferring open", () => { - expect(normalizePreviewOpenInput({ show: false })).toEqual({ - open: false, - reuseExistingTab: true, - show: false, - }); - expect(normalizePreviewOpenInput({ open: true, show: false })).toEqual({ - open: true, - reuseExistingTab: true, - show: true, - }); - }); -}); +import { claimPreviewRecording } from "./handlers.ts"; describe("claimPreviewRecording", () => { it.effect("overlapping and repeated claims return the same retained recording", () => @@ -129,27 +100,4 @@ describe("claimPreviewRecording", () => { ), ), ); - - it.effect("reports an older desktop without returning its inaccessible path", () => - Effect.gen(function* () { - const result = yield* claimPreviewRecording(ThreadId.make("thread-1"), { - id: "desktop-recording", - tabId: "tab-1", - path: "/desktop/recording.webm", - mimeType: "video/webm", - sizeBytes: 6, - createdAt: "2026-09-07T00:00:00.000Z", - }).pipe(Effect.result); - expect(result._tag).toBe("Failure"); - if (result._tag !== "Failure") return; - expect(result.failure._tag).toBe("PreviewAutomationRecordingDesktopUpdateRequiredError"); - expect(result.failure.message).toContain("Update the desktop app"); - }).pipe( - Effect.provide( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-preview-recording-" }).pipe( - Layer.provideMerge(NodeServices.layer), - ), - ), - ), - ); }); diff --git a/apps/server/src/mcp/toolkits/preview/handlers.ts b/apps/server/src/mcp/toolkits/preview/handlers.ts index cf9423ed5a78e..37b4e0470783b 100644 --- a/apps/server/src/mcp/toolkits/preview/handlers.ts +++ b/apps/server/src/mcp/toolkits/preview/handlers.ts @@ -38,9 +38,7 @@ import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from " * preference, which is desktop-local and unreadable from here — filling in * `true` would silently override it for every `preview_open`. */ -export function normalizePreviewOpenInput( - input: PreviewAutomationOpenInput, -): PreviewAutomationOpenInput { +function normalizePreviewOpenInput(input: PreviewAutomationOpenInput): PreviewAutomationOpenInput { const open = input.open ?? input.show; return { ...input, diff --git a/apps/server/src/mcp/toolkits/preview/tools.test.ts b/apps/server/src/mcp/toolkits/preview/tools.test.ts index 4212c711c3f2e..cefe68c1b0e80 100644 --- a/apps/server/src/mcp/toolkits/preview/tools.test.ts +++ b/apps/server/src/mcp/toolkits/preview/tools.test.ts @@ -3,15 +3,6 @@ import { Tool } from "effect/ai"; import { PreviewToolkit } from "./tools.ts"; -const schemaHasDescription = (schema: unknown): boolean => { - if (!schema || typeof schema !== "object") return false; - const record = schema as Record; - if (typeof record.description === "string" && record.description.length > 0) return true; - return [record.anyOf, record.oneOf, record.allOf] - .filter(Array.isArray) - .some((members) => members.some(schemaHasDescription)); -}; - const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => { if (!schema || typeof schema !== "object") return false; const record = schema as Record; @@ -25,7 +16,7 @@ const schemaHasMultipleAllOfDescriptions = (schema: unknown): boolean => { return descriptionCount > 1 || Object.values(record).some(schemaHasMultipleAllOfDescriptions); }; -it("exports provider-compatible object schemas with described parameters", () => { +it("exports provider-compatible object schemas", () => { for (const tool of Object.values(PreviewToolkit.tools)) { const schema = Tool.getJsonSchema(tool) as { readonly type?: unknown; @@ -33,10 +24,6 @@ it("exports provider-compatible object schemas with described parameters", () => readonly anyOf?: unknown; readonly oneOf?: unknown; }; - expect( - tool.description?.length ?? 0, - `${tool.name} should have a useful description`, - ).toBeGreaterThan(40); expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object"); expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined(); expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined(); @@ -47,34 +34,5 @@ it("exports provider-compatible object schemas with described parameters", () => schema.properties?.tabId, `${tool.name} must allow an explicit collaborative browser tab target`, ).toBeDefined(); - for (const [field, fieldSchema] of Object.entries(schema.properties ?? {})) { - expect( - schemaHasDescription(fieldSchema), - `${tool.name}.${field} should explain what data the agent must pass`, - ).toBe(true); - } - } -}); - -it("exports exact object result schemas for preview actions", () => { - const actionNames = [ - "preview_click", - "preview_type", - "preview_hover", - "preview_drag", - "preview_upload", - "preview_press", - "preview_scroll", - "preview_wait_for", - ] as const; - for (const name of actionNames) { - // Effect's tool schemas follow the decoder default since rc.113 and leave - // unmodeled result keys open. - expect(Tool.getJsonSchemaFromSchema(PreviewToolkit.tools[name].successSchema)).toEqual({ - type: "object", - properties: { toolIcon: expect.any(Object) }, - additionalProperties: true, - description: "The preview action completed successfully.", - }); } }); diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.ts index 88a260ed6d3cc..8d675c8397563 100644 --- a/apps/server/src/mcp/toolkits/preview/tools.ts +++ b/apps/server/src/mcp/toolkits/preview/tools.ts @@ -252,11 +252,7 @@ const PreviewScrollTool = safeBrowserTool( }).annotate(Tool.Title, "Scroll preview page"), ); -/** - * MCP `structuredContent` must be a JSON object, and Claude Code rejects the - * whole result when it is not. Wrapping keeps arrays, strings, numbers, and - * null valid instead of failing only for non-object expressions. - */ +/** Wrap non-objects: MCP requires object structuredContent, and Claude Code rejects invalid results entirely. */ export const PreviewEvaluateResult = Schema.Struct({ ...presentationFields, value: Schema.Unknown.annotate({ diff --git a/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts b/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts index 62840dd21e6ec..4cd06bc4233b7 100644 --- a/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/previewControls/handlers.test.ts @@ -4,10 +4,8 @@ import { expect, it } from "@effect/vitest"; import { DEFAULT_SERVER_SETTINGS, EnvironmentId, - PreviewAutomationControlInterruptedError, ProjectId, ProviderInstanceId, - SERVER_BROWSER_AUTOMATION_CLIENT_ID, ThreadId, } from "@t3tools/contracts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -103,86 +101,3 @@ it.effect.each([ }), ), ); - -it.effect("close reports why the server browser refused to close a tab", () => - Effect.scoped( - Effect.gen(function* () { - const threadId = ThreadId.make("preview-controls-thread"); - 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(["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", - runtime: "server", - }); - const layerDependencies = Layer.mergeAll( - Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({ - invoke: () => - Effect.fail( - new PreviewAutomationControlInterruptedError({ - operation: "close", - environmentId: scope.environmentId, - threadId, - providerSessionId: "preview-controls-provider-session", - providerInstanceId: ProviderInstanceId.make("codex"), - clientId: SERVER_BROWSER_AUTOMATION_CLIENT_ID, - connectionId: "server-browser-connection", - requestId: "close-request", - tabId: tab.tabId, - timeoutMs: 1_000, - remoteTag: "PreviewAutomationControlInterruptedError", - remoteMessageLength: 0, - cause: null, - reason: "agentMismatch", - }), - ), - }), - Layer.succeed(Preview.PreviewManager, manager), - Layer.succeed(McpInvocationContext.McpInvocationContext, scope), - McpToolAccessTestkit.liveThreadsLayer, - Layer.mock(ServerSettings.ServerSettingsService)({ - getSettings: Effect.succeed({ - ...DEFAULT_SERVER_SETTINGS, - enableAgentBrowserAccess: true, - }), - }), - ); - const toolkit = yield* PreviewControlsToolkit.pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(PreviewControlsHandlers.layer).pipe( - Layer.provide(layerDependencies), - ), - ), - ); - - const closed = yield* toolkit - .handle("t3_preview_close", { tabId: tab.tabId }) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); - - expect(closed.at(-1)?.result).toMatchObject({ - _tag: "PreviewAutomationControlInterruptedError", - reason: "agentMismatch", - }); - }), - ), -); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 29a8305358011..ccc4443d0b7ce 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -3,9 +3,9 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, - ThreadId, - type OrchestrationV2ThreadShell, type Project as ProjectRecord, + type ModelSelection, + type RuntimeMode, } from "@t3tools/contracts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -29,278 +29,11 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import * as ProjectHandlers from "./handlers.ts"; import { ProjectToolkit } from "./tools.ts"; -it.effect("attributes a launched thread's first message to the calling thread", () => - Effect.gen(function* () { - const sourceThreadId = ThreadId.make("source-thread"); - const projectId = ProjectId.make("project"); - const providerInstanceId = ProviderInstanceId.make("codex"); - const modelSelection = { instanceId: providerInstanceId, model: "gpt-5" }; - const caller = { - id: sourceThreadId, - projectId, - providerInstanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - activeRunId: "active-run", - archivedAt: null, - deletedAt: null, - } as OrchestrationV2ThreadShell; - let launchedSender: ThreadId | undefined; - const layerDependencies = Layer.mergeAll( - ServerSettings.layerTest(), - NodeCrypto.layer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment"), - requestNamespace: "session", - thread: { - threadId: sourceThreadId, - providerSessionId: "session", - providerInstanceId, - }, - client: undefined, - issuedAt: 0, - capabilities: new Set(["orchestration" as const]), - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => Effect.succeed(caller), - }), - Layer.mock(ThreadLaunch.ThreadLaunchService)({ - launch: (input) => { - launchedSender = input.initialMessage?.senderThreadId; - return Effect.succeed({ - threadId: input.threadId, - projection: { - thread: { id: input.threadId, projectId, modelSelection }, - runs: [], - }, - resumed: false, - } as unknown as ThreadLaunch.ThreadLaunchResult); - }, - }), - Layer.mock(Project.ProjectService)({}), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/projects" }), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - NodeServices.layer, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-link-" }).pipe( - Layer.provide(NodeServices.layer), - ), - ); - const toolkit = yield* ProjectToolkit.pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( - Layer.provide(layerDependencies), - ), - ), - ); - const result = yield* toolkit - .handle("t3_thread_launch", { title: "Audit", message: "Review the change" }) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); - expect(result.at(-1)?.result).toMatchObject({ projectId, modelSelection }); - expect(launchedSender).toBe(sourceThreadId); - }), -); - -it.effect("launches a scratch thread into the Scratch project", () => - Effect.gen(function* () { - const sourceThreadId = ThreadId.make("source-thread"); - const scratchProjectId = ProjectId.make("project:scratch"); - const providerInstanceId = ProviderInstanceId.make("codex"); - const modelSelection = { instanceId: providerInstanceId, model: "gpt-5" }; - const caller = { - id: sourceThreadId, - projectId: ProjectId.make("project:caller"), - providerInstanceId, - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - activeRunId: "active-run", - archivedAt: null, - deletedAt: null, - } as OrchestrationV2ThreadShell; - const launched: Array = []; - const layerDependencies = Layer.mergeAll( - ServerSettings.layerTest(), - NodeCrypto.layer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment"), - requestNamespace: "session", - thread: { - threadId: sourceThreadId, - providerSessionId: "session", - providerInstanceId, - }, - client: undefined, - issuedAt: 0, - capabilities: new Set(["orchestration" as const]), - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => Effect.succeed(caller), - }), - Layer.mock(ThreadLaunch.ThreadLaunchService)({ - launch: (input) => { - launched.push(input); - return Effect.succeed({ - threadId: input.threadId, - projection: { - thread: { id: input.threadId, projectId: input.projectId, modelSelection }, - runs: [], - }, - resumed: false, - } as unknown as ThreadLaunch.ThreadLaunchResult); - }, - }), - Layer.mock(Project.ProjectService)({}), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ - namedProjectsRoot: "/projects", - ensureScratchProject: Effect.succeed({ projectId: scratchProjectId }), - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - NodeServices.layer, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-scratch-launch-" }).pipe( - Layer.provide(NodeServices.layer), - ), - ); - const toolkit = yield* ProjectToolkit.pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( - Layer.provide(layerDependencies), - ), - ), - ); - const handle = (params: Parameters>[1]) => - toolkit - .handle("t3_thread_launch", params) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); - - const result = yield* handle({ title: "Notes", scratch: true, message: "Draft a list" }); - expect(result.at(-1)?.result).toMatchObject({ projectId: scratchProjectId }); - expect(launched.map((input) => [input.projectId, input.workspaceStrategy])).toEqual([ - [scratchProjectId, { type: "root" }], - ]); - - const rejected = yield* handle({ - title: "Notes", - scratch: true, - projectId: caller.projectId, - }); - expect(rejected.at(-1)?.result).toMatchObject({ code: "invalid_request" }); - expect(launched).toHaveLength(1); - }), -); - -it.effect("starts a project from just a title when workspaceRoot is omitted", () => - Effect.gen(function* () { - const sourceThreadId = ThreadId.make("source-thread"); - const createdProjectId = ProjectId.make("project:named"); - const providerInstanceId = ProviderInstanceId.make("codex"); - const caller = { - id: sourceThreadId, - projectId: ProjectId.make("project:caller"), - providerInstanceId, - modelSelection: { instanceId: providerInstanceId, model: "gpt-5" }, - runtimeMode: "full-access", - interactionMode: "default", - activeRunId: "active-run", - archivedAt: null, - deletedAt: null, - } as OrchestrationV2ThreadShell; - const named: Array = []; - const registered: Array = []; - const createdProject = { - id: createdProjectId, - title: "Pinball Stats", - workspaceRoot: "/projects/pinball-stats", - defaultModelSelection: null, - scripts: [], - createdAt: "2026-10-01T00:00:00.000Z", - updatedAt: "2026-10-01T00:00:00.000Z", - deletedAt: null, - }; - const layerDependencies = Layer.mergeAll( - ServerSettings.layerTest(), - NodeCrypto.layer, - Layer.succeed(McpInvocationContext.McpInvocationContext, { - environmentId: EnvironmentId.make("environment"), - requestNamespace: "session", - thread: { - threadId: sourceThreadId, - providerSessionId: "session", - providerInstanceId, - }, - client: undefined, - issuedAt: 0, - capabilities: new Set(["orchestration" as const]), - }), - Layer.mock(ThreadManagement.ThreadManagementService)({ - getThreadShell: () => Effect.succeed(caller), - }), - Layer.mock(ThreadLaunch.ThreadLaunchService)({}), - Layer.mock(Project.ProjectService)({ - create: (input) => - Effect.sync(() => { - registered.push(input.workspaceRoot); - return { ...createdProject, id: input.projectId, workspaceRoot: input.workspaceRoot }; - }), - getById: (projectId) => - Effect.succeed( - projectId === createdProjectId ? Option.some(createdProject) : Option.none(), - ), - }), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ - namedProjectsRoot: "/projects", - createNamedProject: (input) => - Effect.sync(() => { - named.push(input.name); - return { - projectId: createdProjectId, - workspaceRoot: createdProject.workspaceRoot, - commitError: "Git has no name or email on this machine.", - }; - }), - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - NodeServices.layer, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-named-project-" }).pipe( - Layer.provide(NodeServices.layer), - ), - ); - const toolkit = yield* ProjectToolkit.pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( - Layer.provide(layerDependencies), - ), - ), - ); - const handle = (params: Parameters>[1]) => - toolkit - .handle("t3_project_create", params) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(layerDependencies)); - - const result = yield* handle({ title: "Pinball Stats" }); - expect(result.at(-1)?.result).toMatchObject({ - id: createdProjectId, - workspaceRoot: "/projects/pinball-stats", - commitError: "Git has no name or email on this machine.", - }); - expect(named).toEqual(["Pinball Stats"]); - - yield* handle({ title: "Existing", workspaceRoot: "/work/existing" }); - expect(registered).toEqual(["/work/existing"]); - - for (const extra of [ - { scripts: [] }, - { defaultModelSelection: { instanceId: providerInstanceId, model: "gpt-5" } }, - ]) { - const rejected = yield* handle({ title: "Configured", ...extra }); - expect(rejected.at(-1)?.result).toMatchObject({ code: "invalid_request" }); - } - expect(named).toEqual(["Pinball Stats"]); - }), -); - const clientLaunchHarness = (input: { - readonly runtimeModeCeiling: "approval-required" | "auto-accept-edits" | "auto" | "full-access"; + readonly runtimeModeCeiling: RuntimeMode; + readonly defaultRuntimeMode?: RuntimeMode; + /** Where Settings saves a project's model; the legacy project field stays null. */ + readonly overrideModel?: ModelSelection; readonly launched: Array; readonly workspaceRoot?: string; readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"]; @@ -311,7 +44,19 @@ const clientLaunchHarness = (input: { model: "claude-opus", }; const layerDependencies = Layer.mergeAll( - ServerSettings.layerTest(), + ServerSettings.layerTest({ + ...(input.defaultRuntimeMode === undefined + ? {} + : { defaultRuntimeMode: input.defaultRuntimeMode }), + ...(input.overrideModel === undefined + ? {} + : { + projectSettingsFolded: true, + projectSettingsOverrides: { + [projectId]: { defaultModelSelection: input.overrideModel }, + }, + }), + }), NodeCrypto.layer, Layer.succeed(McpInvocationContext.McpInvocationContext, { environmentId: EnvironmentId.make("environment"), @@ -336,6 +81,7 @@ const clientLaunchHarness = (input: { thread: { id: launch.threadId, projectId: launch.projectId, + title: launch.title, modelSelection: launch.modelSelection, }, runs: [], @@ -351,7 +97,7 @@ const clientLaunchHarness = (input: { ? Option.some({ id, workspaceRoot: input.workspaceRoot ?? "/projects/client-target", - defaultModelSelection: modelSelection, + defaultModelSelection: input.overrideModel === undefined ? modelSelection : null, } as unknown as ProjectRecord) : Option.none(), ), @@ -371,35 +117,86 @@ const clientLaunchHarness = (input: { return { projectId, modelSelection, dependencies: layerDependencies }; }; -it.effect("a client launches at its ceiling with the project's default model", () => - Effect.gen(function* () { - const launched: Array = []; - const { projectId, modelSelection, dependencies } = clientLaunchHarness({ - runtimeModeCeiling: "auto-accept-edits", - launched, - }); - const toolkit = yield* ProjectToolkit.pipe( - Effect.provide( - McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)), - ), - ); - const handle = (params: Parameters>[1]) => - toolkit - .handle("t3_thread_launch", params) - .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); +it.effect( + "a client launches with the project's default model and mode, capped at its ceiling", + () => + Effect.gen(function* () { + const launchWith = Effect.fn("test.launchWith")(function* ( + runtimeModeCeiling: RuntimeMode, + defaultRuntimeMode: RuntimeMode, + params: { + readonly title: string; + readonly message?: string; + readonly runtimeMode?: RuntimeMode; + readonly targeted?: false; + readonly overrideModel?: ModelSelection; + }, + ) { + const { targeted, overrideModel, ...input } = params; + const launched: Array = []; + const { projectId, modelSelection, dependencies } = clientLaunchHarness({ + runtimeModeCeiling, + defaultRuntimeMode, + launched, + ...(overrideModel === undefined ? {} : { overrideModel }), + }); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( + Layer.provide(dependencies), + ), + ), + ); + const result = yield* toolkit + .handle("t3_thread_launch", targeted === false ? input : { ...input, projectId }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); + return { result: result.at(-1)?.result, launched, projectId, modelSelection }; + }); + + const belowCeiling = yield* launchWith("full-access", "approval-required", { + title: "Fix", + message: "Fix the bug", + }); + expect(belowCeiling.result).toMatchObject({ + projectId: belowCeiling.projectId, + modelSelection: belowCeiling.modelSelection, + link: `[Fix](t3-thread://v1/${belowCeiling.launched[0]?.threadId})`, + }); + expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); + expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); - const result = yield* handle({ title: "Fix", projectId, message: "Fix the bug" }); - expect(result.at(-1)?.result).toMatchObject({ projectId, modelSelection }); - expect(launched[0]?.runtimeMode).toBe("auto-accept-edits"); - expect(launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); + const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", { title: "Fix" }); + expect(aboveCeiling.launched[0]?.runtimeMode).toBe("auto-accept-edits"); - const escalated = yield* handle({ title: "Fix", projectId, runtimeMode: "full-access" }); - expect(escalated.at(-1)?.result).toMatchObject({ code: "runtime_mode_escalation_denied" }); + const requested = yield* launchWith("full-access", "approval-required", { + title: "Fix", + runtimeMode: "auto", + }); + expect(requested.launched[0]?.runtimeMode).toBe("auto"); - const untargeted = yield* handle({ title: "Fix" }); - expect(untargeted.at(-1)?.result).toMatchObject({ code: "target_required" }); - expect(launched).toHaveLength(1); - }), + const escalated = yield* launchWith("auto-accept-edits", "auto-accept-edits", { + title: "Fix", + runtimeMode: "full-access", + }); + expect(escalated.result).toMatchObject({ code: "runtime_mode_escalation_denied" }); + expect(escalated.launched).toHaveLength(0); + + const untargeted = yield* launchWith("full-access", "full-access", { + title: "Fix", + targeted: false, + }); + expect(untargeted.result).toMatchObject({ code: "target_required" }); + + const overrideModel = { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-settings", + }; + const fromSettings = yield* launchWith("full-access", "full-access", { + title: "Fix", + overrideModel, + }); + expect(fromSettings.launched[0]?.modelSelection).toEqual(overrideModel); + }), ); it.effect("a launch binds only an existing checkout that is one of the project's worktrees", () => diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index ca47192c98e4b..aaf37468f8cde 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -9,6 +9,10 @@ import * as Project from "../../../project/ProjectService.ts"; import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts"; import * as Repositories from "../../../sourceControl/SourceControlRepositoryService.ts"; import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; +import * as ServerSettings from "../../../serverSettings.ts"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import { resolveRuntimeMode } from "../../OrchestratorMcpService.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { newCommandId, readCaller, resolveProjectId, unavailable } from "../../threadAccess.ts"; import { ProjectToolkit } from "./tools.ts"; @@ -24,9 +28,7 @@ function projectFailure(error: Project.ProjectServiceError) { return new OrchestratorMcpFailure({ code: "invalid_request", message }); } -/** - * Without this check a launch could point an agent at any directory on the machine. - */ +/** Require project worktrees so launches cannot target arbitrary host directories. */ const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( workspaceRoot: string, worktreePath: string, @@ -102,8 +104,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }); yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); } - // A launch is accepted before its worktree is provisioned, so a base - // ref that cannot resolve is refused while the agent can still act on it. + // Reject unresolved base refs before accepting a launch; worktree provisioning happens later. const strategy = input.workspaceStrategy; if (strategy?.type === "worktree") yield* ThreadLaunch.ThreadLaunchService.pipe( @@ -116,16 +117,32 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { code: "invalid_request", message: `${error.message} No thread was created. Pass a branch, tag, or commit that exists there${ strategy.startFromOrigin === true - ? "; the project has no origin remote to fetch it from." - : ", or set startFromOrigin:true if it exists only on origin." + ? "; the project has no usable remote to fetch it from." + : ", or set startFromOrigin:true if it exists only on a remote." }`, }), ), ); + // A caller outside a thread has nothing to inherit, so it starts with the + // project's effective defaults, as the composer does. Its mode stays + // within the ceiling it was approved with. + const projectDefaults = + caller === undefined + ? yield* ServerSettings.ServerSettingsService.pipe( + Effect.flatMap((settings) => settings.getSettings), + Effect.mapError(unavailable), + Effect.flatMap((settings) => + Effect.map( + readProject, + (project) => resolveProjectSettings(settings, projectId, project).settings, + ), + ), + ) + : undefined; const modelSelection = input.modelSelection ?? caller?.modelSelection ?? - (yield* readProject)?.defaultModelSelection ?? + projectDefaults?.defaultModelSelection ?? undefined; if (modelSelection === undefined) return yield* new OrchestratorMcpFailure({ @@ -133,13 +150,19 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { message: "Pass modelSelection: the project has no default model. orchestrator_capabilities lists providers and models.", }); + const startedRuntimeMode = + projectDefaults !== undefined && input.runtimeMode === undefined + ? yield* resolveRuntimeMode(runtimeMode, projectDefaults.defaultRuntimeMode).pipe( + Effect.orElseSucceed(() => runtimeMode), + ) + : runtimeMode; const result = yield* ThreadMessageIntake.launchThread({ commandId, threadId, projectId, title: input.title, modelSelection, - runtimeMode, + runtimeMode: startedRuntimeMode, interactionMode, workspaceStrategy: input.workspaceStrategy ?? { type: "root" }, ...(input.message === undefined && attachments.length === 0 @@ -175,6 +198,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { const run = result.projection.runs.find((run) => run.userMessageId === messageId); return { threadId: thread.id, + link: formatThreadLink(thread.id, thread.title), projectId: thread.projectId, modelSelection: thread.modelSelection, runId: run?.id ?? null, @@ -208,8 +232,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { Effect.gen(function* () { const projects = yield* Project.ProjectService; if (workspaceRoot === undefined) { - // Project creation records no model default (only an update does), so - // reject what this mode would otherwise drop silently. + // Only updates record model defaults; reject defaults that creation would silently drop. if ( input.scripts !== undefined || input.createWorkspaceRootIfMissing !== undefined || diff --git a/apps/server/src/mcp/toolkits/project/tools.ts b/apps/server/src/mcp/toolkits/project/tools.ts index e455c041c4c31..fbe73215113cb 100644 --- a/apps/server/src/mcp/toolkits/project/tools.ts +++ b/apps/server/src/mcp/toolkits/project/tools.ts @@ -104,7 +104,7 @@ const ProjectCloneTool = Tool.make("t3_project_clone", { const ThreadLaunchTool = Tool.make("t3_thread_launch", { ...shared, description: - 'Create an ordinary TOP-LEVEL thread with an explicit workspace binding before its agent starts. Use this when the user requests independent work, a new thread, or a PR stack in its own worktree; use delegate_task for child subagents. Set workspaceStrategy to {type:"worktree",baseRef:"parent-branch",branch:"new-branch",startFromOrigin:false} for a new worktree based on local commits, or {type:"existing_worktree",worktreePath:"/absolute/path",branch:"existing-branch"} to use an existing checkout. For upstream commits, set startFromOrigin:true. Omitted workspaceStrategy means the project root, NOT the caller\'s worktree. Omit projectId/modelSelection/modes to inherit those settings from the calling thread; a caller outside a T3 thread must pass projectId and gets the project\'s default model. Set scratch:true instead of projectId for a thread without a project: it runs in a fresh folder of its own, outside any repository. Put the task in message. Do not ask the agent to create its own worktree via shell: that does not update the thread binding. Each call creates a new launch with no retry key; retain threadId and use t3_thread_read/t3_thread_wait to follow preparation. To link a thread for the user, write `[title](t3-thread://v1/)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread\'s current title. After errors or lost responses, inspect t3_thread_list before retrying. Attachments must be pending uploads. The new thread may not run with broader runtime or interaction modes than the caller: the calling T3 thread\'s own modes, or the permission mode an outside agent was approved with.', + 'Create an ordinary TOP-LEVEL thread with an explicit workspace binding before its agent starts. Use this when the user requests independent work, a new thread, or a PR stack in its own worktree; use delegate_task for child subagents. Set workspaceStrategy to {type:"worktree",baseRef:"parent-branch",branch:"new-branch",startFromOrigin:false} for a new worktree based on local commits, or {type:"existing_worktree",worktreePath:"/absolute/path",branch:"existing-branch"} to use an existing checkout. To fetch and start from the base branch\'s remote, set startFromOrigin:true. Omitted workspaceStrategy means the project root, NOT the caller\'s worktree. Omit projectId/modelSelection/modes to inherit those settings from the calling thread; a caller outside a T3 thread must pass projectId and gets the project\'s default model. Set scratch:true instead of projectId for a thread without a project: it runs in a fresh folder of its own, outside any repository. Put the task in message. Do not ask the agent to create its own worktree via shell: that does not update the thread binding. Each call creates a new launch with no retry key; retain threadId and use t3_thread_read/t3_thread_wait to follow preparation. Mention a thread with its `link`. After errors or lost responses, inspect t3_thread_list before retrying. Attachments must be pending uploads. The new thread may not run with broader runtime or interaction modes than the caller: the calling T3 thread\'s own modes, or the permission mode an outside agent was approved with.', parameters: Schema.Struct({ projectId: Schema.optional(ProjectId), scratch: Schema.optional( @@ -133,6 +133,7 @@ const ThreadLaunchTool = Tool.make("t3_thread_launch", { }), success: Schema.Struct({ threadId: ThreadId, + link: Schema.optional(Schema.String), projectId: ProjectId, modelSelection: ModelSelection, runId: Schema.NullOr(RunId), diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index e0c36d7b17338..507381531ac49 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -9,6 +9,7 @@ import { type PullRequestRef, type PullRequestReviewGuideResult, type ThreadPullRequestLink, + SourceControlProviderKind, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Crypto from "effect/Crypto"; @@ -31,7 +32,7 @@ import * as McpToolAccess from "../../McpToolAccess.ts"; import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import { listThreadPullRequests } from "./handlers.ts"; import * as PullRequestsHandlers from "./handlers.ts"; -import { PullRequestLinkFailedError, PullRequestsToolkit } from "./tools.ts"; +import { PullRequestsToolkit } from "./tools.ts"; const PROJECT_ID = ProjectId.make("project-1"); const THREAD_ID = ThreadId.make("thread-1"); @@ -64,7 +65,7 @@ function makeProject( remoteName: "origin", remoteUrl: "git@github.com:T3Tools/T3Code.git", }, - provider: "github", + provider: SourceControlProviderKind.make("github"), displayName: "T3Tools/T3Code", owner: "T3Tools", name: "T3Code", @@ -352,20 +353,36 @@ describe("pull request toolkit handlers", () => { }), ); - it.effect("links by repository and number, defaulting the host to the project's", () => + it.effect("canonicalizes GitCafe links independently of the thread's project host", () => Effect.gen(function* () { - const harness = yield* makeHarness(); - const result = yield* harness.call("link_pull_request", { - repository: "T3Tools/Other", - number: 7, - }); - expect(result).toEqual({ - host: "github.com", - repository: "t3tools/other", - number: 7, - url: "https://github.com/t3tools/other/pull/7", - alreadyLinked: false, - }); + for (const host of ["git.cafe", "staging.git.cafe"]) { + for (const project of [makeProject(), makeProject(null)]) { + for (const target of [ + { host, repository: "PingDotGG/T3Code", number: 21353 }, + { url: `https://${host}/PingDotGG/T3Code/pull/21353` }, + { url: `https://${host}/PingDotGG/T3Code/pulls/21353` }, + ]) { + const harness = yield* makeHarness({ project }); + const result = yield* harness.call("link_pull_request", target); + const url = `https://${host}/pingdotgg/t3code/pulls/21353`; + expect(result).toMatchObject({ + host, + repository: "pingdotgg/t3code", + number: 21353, + url, + }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { + type: "thread.pull-request.link", + host, + repository: "pingdotgg/t3code", + number: 21353, + url, + }, + ]); + } + } + } }), ); @@ -379,7 +396,7 @@ describe("pull request toolkit handlers", () => { remoteName: "origin", remoteUrl: "git@gitlab.com:group/sub/project.git", }, - provider: "gitlab", + provider: SourceControlProviderKind.make("gitlab"), displayName: "group/sub/project", }), }); @@ -389,58 +406,52 @@ describe("pull request toolkit handlers", () => { }); expect(result.url).toBe("https://gitlab.com/group/sub/project/-/merge_requests/42"); expect(result.host).toBe("gitlab.com"); + const other = yield* harness.call("link_pull_request", { + host: "gitlab.example.test", + repository: "team/repo", + number: 7, + }); + expect(other.url).toBe("https://gitlab.example.test/team/repo/-/merge_requests/7"); + const onGitHub = yield* harness.call("link_pull_request", { + host: "github.com", + repository: "acme/web", + number: 9, + }); + expect(onGitHub.url).toBe("https://github.com/acme/web/pull/9"); }), ); - it.effect("links a numeric Forgejo reference with its remote's web origin and mount path", () => + it.effect("links a URL but not a bare number when the project's host is unknown", () => Effect.gen(function* () { const harness = yield* makeHarness({ project: makeProject({ - canonicalKey: "forge.example/git/owner/repo", + canonicalKey: "scm.example.test/tfs/collection/project/_git/repo", locator: { source: "git-remote", remoteName: "origin", - remoteUrl: "http://forge.example:3000/git/owner/repo.git", + remoteUrl: "http://dummy:secret@scm.example.test:8080/tfs/Collection/Project/_git/Repo", }, - provider: "forgejo", - displayName: "git/owner/repo", + provider: SourceControlProviderKind.make("unknown"), + displayName: "tfs/collection/project/_git/repo", }), }); - const result = yield* harness.call("link_pull_request", { - repository: "git/owner/repo", - number: 42, - }); - expect(result).toEqual({ - host: "forge.example:3000", - repository: "git/owner/repo", - number: 42, - url: "http://forge.example:3000/git/owner/repo/pulls/42", - alreadyLinked: false, - }); - const other = yield* harness.call("link_pull_request", { - host: "other.example", - repository: "owner/repo", - number: 42, - }); - expect(other.url).toBe("https://other.example/owner/repo/pull/42"); - }), - ); - - it.effect("rejects a target that names neither a URL nor repository and number", () => - Effect.gen(function* () { - const harness = yield* makeHarness(); const error = yield* harness - .call("link_pull_request", { repository: "x/y" }) - .pipe(Effect.flip); - expect(error).toMatchObject({ _tag: "PullRequestTargetIncompleteError" }); - const unknown = yield* harness - .call("link_pull_request", { - url: "https://github.com/t3tools/t3code/issues/1?token=private-value", - }) + .call("link_pull_request", { repository: "tfs/Collection/Project/_git/Repo", number: 124 }) .pipe(Effect.flip); - expect(unknown).toMatchObject({ _tag: "PullRequestUrlInvalidError" }); - expect(unknown.message).not.toContain("private-value"); - expect(yield* Ref.get(harness.commands)).toEqual([]); + expect(error).toMatchObject({ _tag: "PullRequestUrlUnavailableError" }); + + const supplied = "https://scm.example.test/tfs/Collection/Project/_git/Repo/pullrequest/123"; + const fromUrl = yield* harness.call("link_pull_request", { url: supplied }); + expect(fromUrl).toEqual({ + host: "scm.example.test", + repository: "tfs/collection/project/_git/repo", + number: 123, + url: supplied, + alreadyLinked: false, + }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.link", number: 123, url: supplied }, + ]); }), ); @@ -499,14 +510,6 @@ describe("pull request toolkit handlers", () => { expect(result.pullRequests[0]?.host).toBe("forge.example:3000"); }); - it.effect("fails cleanly when the token's thread no longer exists", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ thread: null }); - const error = yield* harness.call("list_thread_pull_requests", {}).pipe(Effect.flip); - expect(error).toMatchObject({ _tag: "PullRequestThreadNotFoundError", threadId: THREAD_ID }); - }), - ); - it.effect("lists visible links with host state and derived chain order", () => Effect.gen(function* () { const harness = yield* makeHarness({ @@ -605,7 +608,7 @@ describe("pull request guide tools", () => { remoteName: "origin", remoteUrl: "git@github.com:acme/web.git", }, - provider: "github", + provider: SourceControlProviderKind.make("github"), displayName: "acme/web", owner: "acme", name: "web", @@ -637,40 +640,6 @@ describe("pull request guide tools", () => { }), ); - it.effect("reports a refused run on its own pull request without failing the rest", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ - generate: (input) => - input.number === 1 - ? Effect.fail( - new PullRequestOperationError({ - operation: "generateReviewGuide", - detail: "Review guides are off. Turn them on in Settings → Source Control.", - }), - ) - : Effect.succeed({ - ...NO_GUIDE, - run: { - _tag: "Running" as const, - headSha: "head-1", - startedAt: "2026-10-11T00:00:00.000Z", - }, - started: true, - }), - }); - const result = yield* harness.call("write_pull_request_guides", { - pullRequests: [ - { repository: "t3tools/t3code", number: 1 }, - { repository: "t3tools/t3code", number: 2 }, - ], - }); - expect(result.guides.map((guide) => [guide.number, guide.outcome, guide.detail])).toEqual([ - [1, "failed", "Review guides are off. Turn them on in Settings → Source Control."], - [2, "started", null], - ]); - }), - ); - it.effect("reports an unreadable entry on its own and still writes the rest of the batch", () => Effect.gen(function* () { const harness = yield* makeHarness(); @@ -688,23 +657,6 @@ describe("pull request guide tools", () => { }), ); - it.effect("reports a run the service joined as running, not as a new one", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ - generate: () => - Effect.succeed({ - ...NO_GUIDE, - run: { _tag: "Running", headSha: "head-1", startedAt: "2026-10-11T00:00:00.000Z" }, - started: false, - }), - }); - const result = yield* harness.call("write_pull_request_guides", { - pullRequests: [{ repository: "t3tools/t3code", number: 4 }], - }); - expect(result.guides.map((guide) => guide.outcome)).toEqual(["running"]); - }), - ); - it.effect("finds an Azure DevOps checkout for a pull request named by its full path", () => Effect.gen(function* () { const azure = { @@ -715,7 +667,7 @@ describe("pull request guide tools", () => { remoteName: "origin", remoteUrl: "https://dev.azure.com/org/project/_git/web", }, - provider: "azure-devops", + provider: SourceControlProviderKind.make("azure-devops"), displayName: "org/project/_git/web", owner: "org", name: "web", @@ -732,22 +684,4 @@ describe("pull request guide tools", () => { ]); }), ); - - it.effect("reads a stored guide and says when a push left it behind", () => - Effect.gen(function* () { - const harness = yield* makeHarness(); - const result = yield* harness.call("read_pull_request_guide", { - repository: "t3tools/t3code", - number: 3, - }); - expect(result).toMatchObject({ number: 3, guide: null, run: null, stale: false }); - }), - ); -}); - -it("keeps failure diagnostics as the cause rather than exposing them in the tool message", () => { - const cause = new Error("database internals"); - const failure = new PullRequestLinkFailedError({ cause }); - expect(failure.message).toBe("Could not link the pull request."); - expect(failure.cause).toBe(cause); }); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 570d9020715fa..fcd9f8bfef5cd 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -1,24 +1,12 @@ -import { - threadPullRequestsOf, - threadPullRequestKeysEqual, -} from "@t3tools/shared/threadPullRequests"; import { CommandId, - pullRequestHostOf, type OrchestrationProjectShell, type OrchestrationV2ThreadShell, type SourceControlProviderKind, type ThreadId, type ThreadPullRequestLink, } from "@t3tools/contracts"; -import { changeRequestUrlFor, parseChangeRequestUrl } from "@t3tools/shared/changeRequestUrl"; -import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl"; -import { - normalizeThreadPullRequestKey, - resolveThreadPullRequestChains, - threadPullRequestKeyOf, - visibleThreadPullRequests, -} from "@t3tools/shared/threadPullRequests"; +import { canonicalizeGitCafePullRequestUrl } from "@t3tools/source-control-definitions/registry"; import * as Cause from "effect/Cause"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; @@ -28,6 +16,15 @@ import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; import * as ProjectService from "../../../project/ProjectService.ts"; import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; import { pullRequestSyncKey } from "../../../pullRequest/pullRequestSyncKey.ts"; +import { sourceControlDefinitions } from "../../../sourceControl/sourceControlDefinitions.ts"; +import { + normalizeThreadPullRequestKey, + resolveThreadPullRequestChains, + threadPullRequestKeyOf, + threadPullRequestKeysEqual, + threadPullRequestsOf, + visibleThreadPullRequests, +} from "../../../sourceControl/threadPullRequests.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { @@ -36,6 +33,7 @@ import { PullRequestUrlInvalidError, PullRequestTargetIncompleteError, PullRequestHostRequiredError, + PullRequestUrlUnavailableError, PullRequestUnlinkFailedError, PullRequestListFailedError, PullRequestNotOpenError, @@ -62,10 +60,10 @@ function projectHostAndProvider(project: OrchestrationProjectShell | undefined): readonly kind: SourceControlProviderKind | null; } { const identity = project?.repositoryIdentity; - const kind = (identity?.provider as SourceControlProviderKind | undefined) ?? null; + const kind = identity?.provider ?? null; if (!identity || kind === null) return { host: null, kind: null }; return { - host: pullRequestHostOf(identity, kind), + host: sourceControlDefinitions.changeRequestHost(identity, kind), kind, }; } @@ -75,11 +73,14 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* ( project: OrchestrationProjectShell | undefined, ) { if (input.url !== undefined) { - const parsed = parseChangeRequestUrl(input.url); - if (parsed === null) { + const parsed = sourceControlDefinitions.parseChangeRequestUrl(input.url)?.link; + if (parsed === undefined) { return yield* new PullRequestUrlInvalidError({}); } - return { ...normalizeThreadPullRequestKey(parsed), url: input.url } satisfies ResolvedTarget; + return { + ...normalizeThreadPullRequestKey(parsed), + url: canonicalizeGitCafePullRequestUrl(input.url), + } satisfies ResolvedTarget; } if (input.repository === undefined || input.number === undefined) { return yield* new PullRequestTargetIncompleteError({}); @@ -90,17 +91,27 @@ const resolveTarget = Effect.fn("PullRequestsToolkit.resolveTarget")(function* ( return yield* new PullRequestHostRequiredError({}); } const repository = input.repository.toLowerCase(); + // Without a URL, a public forge host says what shape its change request URLs take; + // any other host is taken to run the project's own forge. + const recognizedKind = sourceControlDefinitions.recognizeRemote(`https://${host}`)?.kind; + const kind = + sourceControlDefinitions.findByPublicHost(host)?.kind ?? + (recognizedKind === "gitcafe" ? recognizedKind : projectHost.kind); const url = - changeRequestUrlFor( - host === projectHost.host ? projectHost.kind : null, - host, - repository, - input.number, - project?.repositoryIdentity?.locator.remoteUrl, - ) ?? `https://${host}/${repository}/pull/${input.number}`; + kind === null + ? null + : sourceControlDefinitions.get(kind).changeRequestUrl({ + host, + repository, + number: input.number, + remoteUrl: project?.repositoryIdentity?.locator.remoteUrl, + }); + if (url === null) { + return yield* new PullRequestUrlUnavailableError({}); + } return { ...normalizeThreadPullRequestKey({ host, repository, number: input.number, url }), - url, + url: canonicalizeGitCafePullRequestUrl(url), } satisfies ResolvedTarget; }); @@ -154,8 +165,7 @@ function projectForPullRequest( target: { readonly host: string; readonly repository: string }, preferred: OrchestrationProjectShell | undefined, ): OrchestrationProjectShell | undefined { - // The same rule the guide service uses: a pull request reads through a project whose checkout - // names it with the same host-level key, which also maps Azure DevOps' org/project/_git/repo. + // Match the guide service's host-level repository key, including Azure DevOps org/project/_git/repo. const matches = (project: OrchestrationProjectShell) => { const own = pullRequestSyncKey( { projectId: project.id, host: target.host, repository: target.repository, number: 1 }, @@ -167,7 +177,8 @@ function projectForPullRequest( : pullRequestSyncKey( { projectId: project.id, - repository: sourceControlRepositorySelector(project.repositoryIdentity) ?? "", + repository: + sourceControlDefinitions.repositorySelector(project.repositoryIdentity) ?? "", number: 1, }, project.repositoryIdentity, @@ -304,8 +315,18 @@ const make = Effect.gen(function* () { .listShells() .pipe(Effect.mapError((cause) => new PullRequestListFailedError({ cause }))); const callerProject = known.find((project) => project.id === callerThread?.projectId); + // A pull request named by host and repository builds its URL through the project that holds + // it, which need not be the caller's. + const urlProject = (input: PullRequestTargetInput) => + input.url === undefined && input.host !== undefined && input.repository !== undefined + ? (projectForPullRequest( + known, + { host: input.host, repository: input.repository }, + callerProject, + ) ?? callerProject) + : callerProject; return yield* Effect.forEach(targets, (input) => - resolveTarget(input, callerProject).pipe( + resolveTarget(input, urlProject(input)).pipe( Effect.map((target) => ({ input, target, diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index a3a75eabaa385..cbc369deab053 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -10,6 +10,7 @@ import { ThreadId, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; +import * as McpSchema from "effect/ai/McpSchema"; import * as Tool from "effect/ai/Tool"; import * as Toolkit from "effect/ai/Toolkit"; @@ -43,7 +44,7 @@ export const PullRequestTargetInput = Schema.Struct({ url: Schema.optional( TrimmedNonEmptyString.annotate({ description: - "The pull request's web URL, for example https://github.com/owner/repo/pull/123. Preferred when you have it; host, repository and number are read from it.", + "The pull request's web URL as its host shows it, for example https://git.example.com/owner/repo/pull/123 or https://git.example.com/group/project/-/merge_requests/123. Preferred when you have it; host, repository and number are read from it.", }), ), repository: Schema.optional( @@ -60,7 +61,7 @@ export const PullRequestTargetInput = Schema.Struct({ host: Schema.optional( TrimmedNonEmptyString.annotate({ description: - "Host the repository lives on, for example github.com. Defaults to the host of this thread's project.", + "Host the repository lives on, for example git.example.com. Defaults to the host of this thread's project.", }), ), }); @@ -93,6 +94,15 @@ export class PullRequestHostRequiredError extends Schema.TaggedError()( + "PullRequestUrlUnavailableError", + {}, +) { + override get message(): string { + return "This thread's project is on a host with no known pull request URL shape. Pass url."; + } +} + export class PullRequestThreadRequiredError extends Schema.TaggedError()( "PullRequestThreadRequiredError", {}, @@ -189,6 +199,7 @@ export const PullRequestToolError = Schema.Union([ PullRequestUrlInvalidError, PullRequestTargetIncompleteError, PullRequestHostRequiredError, + PullRequestUrlUnavailableError, PullRequestThreadRequiredError, PullRequestThreadNotFoundError, PullRequestLinkFailedError, @@ -250,7 +261,7 @@ export const ThreadPullRequestEntry = Schema.Struct({ stack: Schema.NullOr( Schema.Struct({ kind: Schema.Literals(["native", "derived"]), - /** 1-based layer, bottom of the stack first. Pull requests built on the same one share it. */ + /** 1-based layer from the bottom; siblings share a layer. */ position: Schema.Int, size: Schema.Int, }), @@ -316,7 +327,7 @@ const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { const WatchPullRequestTool = Tool.make("watch_pull_request", { description: - "Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every two minutes and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles or is archived, when T3 Code fails to read it 8 times in a row (a host rate limit only delays it), when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch. A subagent cannot watch: its parent thread owns the pull request.", + "Have T3 Code watch an open pull request for this thread, linking it first if needed. T3 Code checks it every two minutes and wakes you with a message when a check fails, the required checks pass, someone else comments or reviews, or the branch starts to conflict with its base. Use this to monitor or babysit a pull request instead of polling, sleeping, or running a watcher. Only comments posted after this call wake you, so handle the existing ones first, then end your turn. A wake is news, not a merge decision: check readiness yourself before merging. While T3 Code watches, the thread stays in the user's Working list, not their inbox. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox. Watching ends when the pull request merges or closes, when its thread settles or is archived, when T3 Code fails to read it 8 times in a row (a host rate limit only delays it), when the user stops this thread, or when you call unwatch_pull_request. Unsettle the thread before starting a new watch.", parameters: PullRequestTargetInput, success: WatchPullRequestResult, failure: PullRequestToolError, @@ -326,7 +337,8 @@ const WatchPullRequestTool = Tool.make("watch_pull_request", { .annotate(Tool.Readonly, false) .annotate(Tool.Destructive, false) .annotate(Tool.Idempotent, true) - .annotate(Tool.OpenWorld, false); + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents); const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", { description: @@ -340,7 +352,8 @@ const UnwatchPullRequestTool = Tool.make("unwatch_pull_request", { .annotate(Tool.Readonly, false) .annotate(Tool.Destructive, false) .annotate(Tool.Idempotent, true) - .annotate(Tool.OpenWorld, false); + .annotate(Tool.OpenWorld, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromSubagents); const GuideTarget = Schema.Struct({ url: PullRequestTargetInput.fields.url, diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index e1bf858ca8fb6..8a15d1f156561 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import { modelSelectionCommandType } from "@t3tools/shared/model"; +import { formatThreadLink } from "@t3tools/shared/threadLinks"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { @@ -55,10 +56,7 @@ const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: { }) { const context = yield* readThread(input.threadId, ["runtimeRequests", "turnItems"]); const request = context.projection.runtimeRequests.find( - (request) => - request.id === input.requestId && - request.kind === "user_input" && - request.status === "pending", + (request) => request.id === input.requestId && request.kind === "user_input", ); const item = context.projection.turnItems.find( (item) => item.type === "user_input_request" && item.requestId === input.requestId, @@ -68,6 +66,14 @@ const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: { code: "invalid_request", message: "The pending user-input request was not found.", }); + if (request.status !== "pending") + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + request.status === "resolved" + ? "The user-input request was already answered." + : `The user-input request is no longer pending (${request.status}).`, + }); return { ...context, request, item }; }); const writesThread =

( @@ -84,12 +90,12 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { code: "invalid_request", message: "The scheduled task was not found.", }); - const { task } = yield* scheduler + const { task, threadId } = yield* scheduler .runNow({ id: input.taskId }) .pipe(Effect.mapError(unavailable)); return { taskId: task.id, - threadId: task.threadId, + threadId, lastRunStatus: task.lastRunStatus, runCount: task.runCount, nextRunAt: task.nextRunAt, @@ -99,15 +105,15 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { t3_thread_search: McpToolAccess.reads((input) => Effect.gen(function* () { const { caller } = yield* readCaller(); - const { projectId: requested, ...query } = input; - const projectId = requested ?? caller?.projectId; const threadSearch = yield* ThreadSearch.ThreadSearch; - const result = yield* threadSearch.search(query).pipe(Effect.mapError(unavailable)); + const { matches } = yield* threadSearch + .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId }) + .pipe(Effect.mapError(unavailable)); return { - matches: - projectId === undefined - ? result.matches - : result.matches.filter((match) => match.projectId === projectId), + matches: matches.map((match) => ({ + ...match, + link: formatThreadLink(match.threadId, match.title), + })), }; }), ), diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index b5fb7d6be3a68..5e015368fd28c 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -2,7 +2,7 @@ import { ScheduledTaskId, ScheduledTask, OrchestrationSearchThreadsInput, - OrchestrationSearchThreadsResult, + OrchestrationThreadSearchMatch, OrchestrationV2ThreadForkSourcePoint, OrchestrationV2ContextTransfer, TrimmedNonEmptyString, @@ -243,12 +243,24 @@ const ThreadTransfersTool = Tool.make("t3_thread_transfers", { const ThreadSearchTool = Tool.make("t3_thread_search", { ...commandTool, description: - "Search active thread titles and content with the app's existing bounded search. Matches are limited to one project (projectId, else the calling thread's project) out of the global top matches, so this may return fewer than limit. A caller outside a T3 thread that omits projectId searches every project. No pagination or exhaustive-result guarantee.", + 'Search active threads the way the command palette does: title, branch, pull request, and project matches first (source "title", ranked by match quality and recent use, with one-typo tolerance), then threads whose messages contain every query word of three or more characters (source "user" or "assistant", with a snippet; up to a fifth of the limit is kept for these). Subagent threads are skipped. Limited to one project (projectId, else the calling thread\'s project); a caller outside a T3 thread that omits projectId searches every project. No pagination or exhaustive-result guarantee.', parameters: Schema.Struct({ ...OrchestrationSearchThreadsInput.fields, projectId: Schema.optional(ProjectId), }), - success: OrchestrationSearchThreadsResult, + success: Schema.Struct({ + matches: Schema.Array( + Schema.Struct({ + threadId: OrchestrationThreadSearchMatch.fields.threadId, + projectId: OrchestrationThreadSearchMatch.fields.projectId, + title: Schema.String, + link: Schema.optional(Schema.String), + source: Schema.Literals(["title", "user", "assistant"]), + snippet: Schema.optional(OrchestrationThreadSearchMatch.fields.snippet), + messageCreatedAt: Schema.optional(OrchestrationThreadSearchMatch.fields.messageCreatedAt), + }), + ), + }), dependencies: [...commandTool.dependencies, ThreadSearch.ThreadSearch], }) .annotate(Tool.Readonly, true) @@ -257,7 +269,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", { const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", { ...commandTool, description: - "Run a scheduled task now through the existing scheduler. Requires a full-access/default caller. Each call is a new manual run; completion means dispatch/bookkeeping completed, not that the provider turn finished.", + "Run a scheduled task now through the existing scheduler. Requires a full-access/default caller. Returns the thread this run dispatched to, or null if dispatch failed. Each call is a new manual run; completion means dispatch/bookkeeping completed, not that the provider turn finished.", parameters: Schema.Struct({ taskId: ScheduledTaskId }), success: Schema.Struct({ taskId: ScheduledTaskId, diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts deleted file mode 100644 index 1598031d50c75..0000000000000 --- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts +++ /dev/null @@ -1,171 +0,0 @@ -import * as Orchestrator from "../../../orchestration-v2/Orchestrator.ts"; -import * as ProjectionStore from "../../../orchestration-v2/ProjectionStore.ts"; -import * as DeviceService from "../../../device/DeviceService.ts"; -import * as ServerConfig from "../../../config.ts"; -import { expect, it } from "@effect/vitest"; -import { NodeHttpServer } from "@effect/platform-node"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { ProviderInstanceId, ThreadId } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Schema from "effect/Schema"; -import { HttpBody, HttpClient, HttpRouter } from "effect/http"; - -import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts"; -import * as GitWorkflowService from "../../../git/GitWorkflowService.ts"; -import * as ProviderAdapterRegistry from "../../../orchestration-v2/ProviderAdapterRegistry.ts"; -import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; -import * as ProjectService from "../../../project/ProjectService.ts"; -import * as PullRequestReviewGuideService from "../../../pullRequest/PullRequestReviewGuideService.ts"; -import * as ProjectSetupScriptRunner from "../../../project/ProjectSetupScriptRunner.ts"; -import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; -import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts"; -import * as SecretRequests from "../../../secrets/SecretRequests.ts"; -import * as ServerSettings from "../../../serverSettings.ts"; -import * as VcsStatusBroadcaster from "../../../vcs/VcsStatusBroadcaster.ts"; -import * as ServerSecretStore from "../../../auth/ServerSecretStore.ts"; -import * as ManagedProjectFolders from "../../../project/ManagedProjectFolders.ts"; -import * as ThreadLaunchService from "../../../orchestration-v2/ThreadLaunchService.ts"; -import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; -import * as PreviewManager from "../../../preview/Manager.ts"; -import * as SourceControlRepositoryService from "../../../sourceControl/SourceControlRepositoryService.ts"; -import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; -import * as McpHttpServer from "../../McpHttpServer.ts"; -import * as McpSessionRegistry from "../../McpSessionRegistry.ts"; -import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts"; -import * as PreviewBrowser from "../../../preview/PreviewBrowser.ts"; - -const layerStubServices = Layer.mergeAll( - Layer.mock(Orchestrator.OrchestratorV2)({}), - Layer.mock(ProjectionStore.ProjectionStoreV2)({}), - Layer.mock(DeviceService.DeviceService)({}), - Layer.mock(ThreadManagementService.ThreadManagementService)({}), - Layer.mock(ProviderRegistry.ProviderRegistry)({}), - Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), - Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), - Layer.mock(SecretRequests.SecretRequests)({}), - Layer.mock(ProjectService.ProjectService)({}), - Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), - ServerSettings.layerTest({}), - Layer.mock(GitWorkflowService.GitWorkflowService)({}), - Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}), - Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), - Layer.mock(PreviewManager.PreviewManager)({}), - Layer.mock(ServerSecretStore.ServerSecretStore)({}), - Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}), - Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), - Layer.mock(ThreadSearch.ThreadSearch)({}), -); - -const ToolsListPayload = Schema.fromJsonString( - Schema.Struct({ - result: Schema.Struct({ - tools: Schema.Array( - Schema.Struct({ - name: Schema.String, - inputSchema: Schema.Struct({ type: Schema.optional(Schema.String) }), - annotations: Schema.optional( - Schema.Struct({ - readOnlyHint: Schema.optional(Schema.Boolean), - destructiveHint: Schema.optional(Schema.Boolean), - openWorldHint: Schema.optional(Schema.Boolean), - }), - ), - }), - ), - }), - }), -); -const decodeToolsListPayload = Schema.decodeUnknownEffect(ToolsListPayload); - -it.effect("production mcp layer lists worktree tools over http", () => - Effect.scoped( - Effect.gen(function* () { - const layerRoutes = McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)); - yield* HttpRouter.serve(layerRoutes, { - disableListenLog: true, - disableLogger: true, - }).pipe( - Layer.provide( - Layer.mock(ServerEnvironment.ServerEnvironment)({ - getEnvironmentId: Effect.succeed("environment-scratch" as never), - }), - ), - Layer.provide(PreviewAutomationBroker.layer), - Layer.provide(PreviewBrowser.layer), - Layer.provide(layerStubServices), - Layer.build, - ); - - const registry = McpSessionRegistry.issueActiveMcpCredential({ - threadId: ThreadId.make("thread-scratch"), - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - }); - const credential = yield* registry; - expect(credential).toBeDefined(); - - const httpClient = yield* HttpClient.HttpClient; - const auth = credential!.config.authorizationHeader; - const initResponse = yield* httpClient.post("/mcp", { - headers: { - accept: "application/json, text/event-stream", - authorization: auth, - }, - body: HttpBody.text( - `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"scratch","version":"1.0.0"}}}`, - "application/json", - ), - }); - expect(initResponse.status).toBe(200); - const sessionId = initResponse.headers["mcp-session-id"]; - - const listResponse = yield* httpClient.post("/mcp", { - headers: { - accept: "application/json, text/event-stream", - authorization: auth, - "mcp-protocol-version": "2025-06-18", - ...(sessionId ? { "mcp-session-id": sessionId } : {}), - }, - body: HttpBody.text( - `{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`, - "application/json", - ), - }); - const bodyText = yield* listResponse.text; - const payload = yield* decodeToolsListPayload(bodyText.match(/\{.*\}/s)![0]); - const tools = payload.result.tools; - const toolNames = tools.map((tool) => tool.name); - expect(toolNames).toContain("t3_worktree_handoff"); - expect(toolNames).toContain("t3_worktree_status"); - expect(toolNames).toContain("preview_status"); - expect(toolNames).toContain("delegate_task"); - - const handoff = tools.find((tool) => tool.name === "t3_worktree_handoff"); - expect(handoff?.annotations?.readOnlyHint).toBe(false); - expect(handoff?.annotations?.destructiveHint).toBe(true); - expect(handoff?.annotations?.openWorldHint).toBe(true); - const status = tools.find((tool) => tool.name === "t3_worktree_status"); - expect(status?.annotations?.readOnlyHint).toBe(true); - expect(status?.annotations?.destructiveHint).toBe(false); - - // MCP requires every tool input schema to be a top-level object schema. - // A non-object schema (e.g. the anyOf produced by an empty - // Schema.Struct({})) makes clients reject the entire server. - for (const tool of tools) { - expect(tool.inputSchema.type, `inputSchema.type of ${tool.name}`).toBe("object"); - } - }), - ).pipe( - Effect.provide( - Layer.mergeAll( - NodeHttpServer.layerTest, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-worktree-mcp-" }).pipe( - Layer.provide(NodeServices.layer), - ), - NodeServices.layer, - ), - ), - ), -); diff --git a/apps/server/src/mcp/toolkits/worktree/tools.ts b/apps/server/src/mcp/toolkits/worktree/tools.ts index 85bbfde03ce68..18c261602b03f 100644 --- a/apps/server/src/mcp/toolkits/worktree/tools.ts +++ b/apps/server/src/mcp/toolkits/worktree/tools.ts @@ -27,7 +27,7 @@ const WorktreeToolFailure = Schema.Union([WorktreeMcpFailure, OrchestratorMcpFai const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", { description: - "Needs an agent running inside a T3 thread. Move this agent thread into a new git worktree. To launch a separate agent already bound to a new or existing worktree, use t3_thread_launch with workspaceStrategy instead. Creates the worktree branch (optionally from origin), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.", + "Needs an agent running inside a T3 thread. Move this agent thread into a new git worktree. To launch a separate agent already bound to a new or existing worktree, use t3_thread_launch with workspaceStrategy instead. Creates the worktree branch (optionally from the base branch's remote), re-points the thread at the worktree, and by default runs the project's setup script there. Changing the workspace detaches the live provider session, so the current turn ends shortly after the handoff is recorded; call this as the last action of the turn. To keep working after the handoff, pass continuationPrompt with the remaining work: it is queued as the thread's next message and starts a new turn inside the worktree with the conversation preserved. Without it the thread stays idle until the next message. The worktree is not removed automatically when the thread is deleted. Fails if the thread is already attached to a worktree.", parameters: WorktreeMcpHandoffInput, success: WorktreeMcpHandoffResult, failure: WorktreeToolFailure, @@ -43,10 +43,7 @@ const WorktreeHandoffTool = Tool.make("t3_worktree_handoff", { const WorktreeStatusTool = Tool.make("t3_worktree_status", { description: "Needs an agent running inside a T3 thread. Report this agent thread's worktree binding: whether it is attached to a git worktree, the worktree path and branch, the project's main workspace root, and the server default for t3_worktree_handoff's startFromOrigin. Call this before t3_worktree_handoff to check whether a handoff is possible or has already happened.", - // No `parameters`: Tool.make defaults to Tool.EmptyParams, which serializes - // to a top-level `type: "object"` JSON Schema. An explicit empty - // Schema.Struct({}) serializes to `anyOf: [object, array]`, which is not a - // valid MCP tool input schema and makes clients reject the whole server. + // Empty Struct emits object|array, making MCP clients reject the server; use EmptyParams for an object schema. success: WorktreeMcpStatusResult, failure: WorktreeToolFailure, failureMode: "return", diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.ts index d6894b38f8a33..6e563e10b56ff 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.ts @@ -1,5 +1,6 @@ import type { ThreadId, TurnItemId } from "@t3tools/contracts"; import * as Context from "effect/Context"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -23,7 +24,7 @@ export interface McpAppModelContextEntry { export class McpAppModelContext extends Context.Service< McpAppModelContext, { - /** Replaces the app's context; empty text removes it. */ + /** Empty text removes the app's context. */ readonly set: (input: { readonly threadId: ThreadId; readonly itemId: TurnItemId; @@ -66,9 +67,7 @@ export const layer = Layer.effect( }); const forThread = Effect.fn("McpAppModelContext.forThread")(function* (threadId: ThreadId) { - // The item can live in a thread this one was forked from, so it is - // matched by id alone; that thread rolling the run back later leaves the - // fork's copy in place. + // Match by id across fork lineage; later source rollbacks leave the fork's copy intact. return yield* sql` SELECT context.item_id AS "itemId", context.server, context.tool, context.text FROM mcp_app_model_context AS context @@ -83,7 +82,7 @@ export const layer = Layer.effect( OR run.thread_id <> context.thread_id ) ORDER BY context.updated_at, context.item_id - `.pipe(Effect.mapError(fail)); + `.pipe(NodeSqliteClient.readOnly, Effect.mapError(fail)); }); return McpAppModelContext.of({ set, forThread }); diff --git a/apps/server/src/mcpApps/McpAppRequests.test.ts b/apps/server/src/mcpApps/McpAppRequests.test.ts index e98f824d60889..1fde091c06423 100644 --- a/apps/server/src/mcpApps/McpAppRequests.test.ts +++ b/apps/server/src/mcpApps/McpAppRequests.test.ts @@ -251,26 +251,4 @@ describe("McpAppRequests", () => { assert.isTrue(storedContext.has(`${deepForkId(70)}/${itemId}`)); }).pipe(Effect.provide(makeLayer({ item: appItem({ t3McpApp: app }), live: false }))), ); - - it.effect("reports why a request cannot run", () => - Effect.gen(function* () { - const run = (layer: ReturnType) => - Effect.gen(function* () { - const requests = yield* McpAppRequests.McpAppRequests; - return yield* reason(requests.readResource({ threadId, itemId, uri: "ui://weather/x" })); - }).pipe(Effect.provide(layer)); - assert.equal( - yield* run(makeLayer({ item: appItem({ result: "plain" }), mcpApps })), - "not-an-app", - ); - assert.equal( - yield* run(makeLayer({ item: appItem({ t3McpApp: app }), mcpApps, live: false })), - "session-stopped", - ); - assert.equal( - yield* run(makeLayer({ item: appItem({ t3McpApp: app }) })), - "provider-unsupported", - ); - }), - ); }); diff --git a/apps/server/src/mcpApps/McpAppRequests.ts b/apps/server/src/mcpApps/McpAppRequests.ts index 6e97a726a021b..1387cc6b20c7a 100644 --- a/apps/server/src/mcpApps/McpAppRequests.ts +++ b/apps/server/src/mcpApps/McpAppRequests.ts @@ -26,10 +26,7 @@ import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionMana import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as McpAppModelContext from "./McpAppModelContext.ts"; -/** - * A stopped session is reported, never started: an app view must not spend a - * provider turn. - */ +/** Reports stopped sessions without starting them; app views must not spend provider turns. */ export class McpAppRequests extends Context.Service< McpAppRequests, { @@ -133,8 +130,7 @@ const make = Effect.gen(function* () { const callTool = Effect.fn("McpAppRequests.callTool")(function* (input: McpAppCallToolInput) { const resolved = yield* resolve(input); - // The spec forbids apps calling tools hidden from them; checked here too, - // since a client's own check is only a courtesy to its user. + // Enforce hidden-tool restrictions server-side; client checks cannot enforce the spec. const tool = yield* findTool(input.threadId, resolved, input.name); if (tool === undefined || !mcpAppToolCallableByApp(tool._meta)) { return yield* fail(input.threadId, "tool-not-callable"); @@ -184,8 +180,7 @@ const make = Effect.gen(function* () { input: McpAppUpdateModelContextInput, ) { const { app } = yield* resolveApp(input); - // Context belongs to the conversation on screen, which only shows this app - // when it is the app's own thread or one forked from it. + // Context belongs only to the app's thread or its descendants. if (!(yield* descendsFrom(input.conversationThreadId, input.threadId))) { return yield* fail(input.threadId, "not-an-app"); } diff --git a/apps/server/src/mcpApps/McpAppSnapshot.ts b/apps/server/src/mcpApps/McpAppSnapshot.ts index f47237f5c82c3..a43c01a404178 100644 --- a/apps/server/src/mcpApps/McpAppSnapshot.ts +++ b/apps/server/src/mcpApps/McpAppSnapshot.ts @@ -26,9 +26,7 @@ function readMcpAppDocument( if (content.uri !== undefined && content.uri !== uri) continue; const mimeType = typeof content.mimeType === "string" ? content.mimeType : ""; if (mimeType.replace(/\s+/g, "").toLowerCase() !== MCP_APP_MIME_TYPE) continue; - // Sizes are checked before decoding, so an oversized resource is - // refused without first being copied: a string's UTF-8 form is at least - // its length, and base64 decodes to three quarters of its own. + // Bound before decoding to avoid oversized copies; UTF-8 is at least string length, base64 decodes to 3/4. const html = typeof content.text === "string" ? content.text.length > MCP_APP_MAX_HTML_BYTES @@ -79,8 +77,7 @@ export const snapshotMcpApp = Effect.fn("McpAppSnapshot.snapshot")(function* (in const ui = Predicate.isObject(document.meta) ? document.meta : {}; const csp = readMcpAppCsp(ui.csp); const fileSystem = yield* FileSystem.FileSystem; - // Only the returned reference lets thread deletion find the document, so a - // write that fails or is interrupted removes it. + // Failed or interrupted writes remove documents that thread deletion cannot yet find. yield* fileSystem .writeFileString(filePath, injectMcpAppCsp(html, csp)) .pipe(Effect.onError(() => fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore))); diff --git a/apps/server/src/observability/BrowserTraceCollector.ts b/apps/server/src/observability/BrowserTraceCollector.ts index ee197dd0d7d34..1802a4a665917 100644 --- a/apps/server/src/observability/BrowserTraceCollector.ts +++ b/apps/server/src/observability/BrowserTraceCollector.ts @@ -10,7 +10,7 @@ export class BrowserTraceCollector extends Context.Service< } >()("t3/observability/BrowserTraceCollector") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = (sink: TraceSink): BrowserTraceCollector["Service"] => BrowserTraceCollector.of({ record: (records) => diff --git a/apps/server/src/observability/DefectReporter.test.ts b/apps/server/src/observability/DefectReporter.test.ts index d70f5af1d096d..c749c1a845798 100644 --- a/apps/server/src/observability/DefectReporter.test.ts +++ b/apps/server/src/observability/DefectReporter.test.ts @@ -1,7 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as ErrorReporter from "effect/ErrorReporter"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -81,16 +80,4 @@ describe("DefectReporter", () => { }), ).pipe(Effect.scoped), ); - - it.effect("logs defects, not typed failures or interrupts", () => - withErrorLogs((logs) => - Effect.gen(function* () { - yield* ErrorReporter.report(Cause.fail(new Error("expected"))); - yield* ErrorReporter.report(Cause.interrupt()); - yield* ErrorReporter.report(Cause.die(new Error("bug"))); - - assert.deepEqual((yield* Queue.clear(logs)).map(errorMessage), ["bug"]); - }).pipe(Effect.provide(DefectReporter.layer)), - ), - ); }); diff --git a/apps/server/src/observability/DefectReporter.ts b/apps/server/src/observability/DefectReporter.ts index 4e8911c1493de..39e93ba5fb44a 100644 --- a/apps/server/src/observability/DefectReporter.ts +++ b/apps/server/src/observability/DefectReporter.ts @@ -2,10 +2,7 @@ import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as ErrorReporter from "effect/ErrorReporter"; -/** - * RpcServer reports every failed handler exit; typed failures are expected responses, so only - * dies are logged. - */ +// RpcServer reports typed failures too; log only defects. const reporter: ErrorReporter.ErrorReporter = { [ErrorReporter.TypeId]: ErrorReporter.TypeId, report: ({ cause, fiber }) => { diff --git a/apps/server/src/observability/EventLoopMonitor.test.ts b/apps/server/src/observability/EventLoopMonitor.test.ts index 963279d138247..a3a58e60e4e26 100644 --- a/apps/server/src/observability/EventLoopMonitor.test.ts +++ b/apps/server/src/observability/EventLoopMonitor.test.ts @@ -1,11 +1,4 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; 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 Logger from "effect/Logger"; -import * as Tracer from "effect/Tracer"; -import * as TestClock from "effect/testing/TestClock"; import * as EventLoopMonitor from "./EventLoopMonitor.ts"; @@ -24,117 +17,14 @@ const stalled: EventLoopMonitor.EventLoopReadings = { involuntaryContextSwitches: 57, }, rssBytes: 1536 * 1024 * 1024, + heapUsedBytes: 512 * 1024 * 1024, + elapsedMs: 30_000, + loadAverage: 219.43, + cpuCount: 18, }; -const quiet: EventLoopMonitor.EventLoopReadings = { ...stalled, delayMaxNs: ms(2_950) }; - -const monitor = ( - samples: Array, - stallLog: EventLoopMonitor.StallLogOptions = { filePath: "\0", maxBytes: 1 }, -) => - Layer.build( - EventLoopMonitor.layerWith( - Effect.succeed(Effect.sync(() => samples.shift() ?? quiet)), - stallLog, - ), - ); describe("EventLoopMonitor", () => { - it.effect("records a warning span only for samples that saw a stall", () => - Effect.gen(function* () { - const spans: Array = []; - const tracer = Tracer.make({ - span: (options) => { - const span = new Tracer.NativeSpan(options); - spans.push(span); - return span; - }, - }); - yield* Effect.gen(function* () { - yield* monitor([stalled, quiet, stalled]); - yield* TestClock.adjust("60 seconds"); - assert.lengthOf(spans, 0); - yield* TestClock.adjust("30 seconds"); - }).pipe(Effect.scoped, Effect.withTracer(tracer)); - - assert.deepStrictEqual( - spans.map((span) => span.name), - ["server.eventLoop.stall"], - ); - const [span] = spans; - assert.deepStrictEqual(Object.fromEntries(span!.attributes), { - delayMaxMs: 4_950, - utilization: 0.18, - cpuUserMs: 310, - cpuSystemMs: 96, - majorPageFaults: 8_412, - minorPageFaults: 20_031, - involuntaryContextSwitches: 57, - rssMb: 1536, - }); - assert.deepStrictEqual( - span!.events.map(([name, , attributes]) => [name, attributes["effect.logLevel"]]), - [["event loop stalled for 4950 ms", "WARN"]], - ); - }), - ); - - it.effect("keeps each stall as one line in a capped stall log", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-event-loop-" }); - const filePath = `${directory}/event-loop-stalls.ndjson`; - yield* monitor([stalled, stalled, stalled, { ...stalled, delayMaxNs: ms(7_000) }], { - filePath, - maxBytes: 300, - }); - yield* TestClock.adjust("120 seconds"); - - const lines = (yield* fs.readFileString(filePath)).trim().split("\n"); - assert.deepStrictEqual( - lines.map((line) => JSON.parse(line)), - [ - { - time: "1970-01-01T00:02:00.000Z", - delayMaxMs: 6_000, - utilization: 0.18, - cpuUserMs: 310, - cpuSystemMs: 96, - majorPageFaults: 8_412, - minorPageFaults: 20_031, - involuntaryContextSwitches: 57, - rssMb: 1536, - }, - ], - ); - assert.lengthOf((yield* fs.readFileString(`${filePath}.1`)).trim().split("\n"), 1); - assert.isFalse(yield* fs.exists(`${filePath}.2`)); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("warns when a stall cannot be written to the stall log", () => { - const warnings: Array = []; - const logger = Logger.make(({ message }) => { - warnings.push(Array.isArray(message) ? message[0] : message); - }); - return Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const filePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-event-loop-" }); - yield* monitor([stalled, stalled], { filePath, maxBytes: 1024 * 1024 }); - yield* TestClock.adjust("60 seconds"); - assert.deepStrictEqual(warnings, [ - "event loop stalled for 4950 ms", - "event loop stall log write failed", - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })), - ), - ); - }); - it("ignores delay the loop spent idle, such as a system sleep", () => { - // Waking from sleep reads as a long gap, but the loop was idle in poll for it. const asleep: EventLoopMonitor.EventLoopReadings = { ...stalled, delayMaxNs: ms(600_000), diff --git a/apps/server/src/observability/EventLoopMonitor.ts b/apps/server/src/observability/EventLoopMonitor.ts index d713e71940dec..ed3befd0bb678 100644 --- a/apps/server/src/observability/EventLoopMonitor.ts +++ b/apps/server/src/observability/EventLoopMonitor.ts @@ -1,24 +1,42 @@ -// @effect-diagnostics nodeBuiltinImport:off - only node:perf_hooks exposes the event loop delay histogram. +// @effect-diagnostics nodeBuiltinImport:off - only node:perf_hooks exposes the event loop delay histogram, and node:os the load average. +import * as NodeOS from "node:os"; import * as NodePerfHooks from "node:perf_hooks"; +import type { ServerEventLoopStall } from "@t3tools/contracts"; import { RotatingFileSink } from "@t3tools/shared/logging"; +import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Metric from "effect/Metric"; import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import type * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import * as ServerConfig from "../config.ts"; +import * as Metrics from "./Metrics.ts"; -// Node's delay histogram wakes a native timer every RESOLUTION_MS and records the -// gap between wakeups, so an idle loop reads about RESOLUTION_MS and a stall of S -// reads between S and S + RESOLUTION_MS. We subtract the resolution, so a delay can -// undercount a stall by up to RESOLUTION_MS. +// Subtract the histogram's timer resolution; this can undercount stalls by up to RESOLUTION_MS. const RESOLUTION_MS = 1000; const STALL_THRESHOLD_MS = 2000; const SAMPLE_INTERVAL = "30 seconds"; const STALL_LOG_MAX_BYTES = 256 * 1024; +// Long enough that users felt it. Shorter stalls stay in the log only. +const NOTICEABLE_STALL_MS = 5000; +// Clients show what they get, so an old stall must not explain a new drop. +const NOTICEABLE_STALL_MAX_AGE_MS = 5 * 60_000; + +export class EventLoopMonitor extends Context.Reference<{ + /** + * The latest stall of 5 s or more, if seen in the last 5 minutes. It samples + * first, so a stall that ended just before a client reconnected is included. + */ + readonly latestNoticeableStall: Effect.Effect; +}>("t3/observability/EventLoopMonitor", { + defaultValue: () => ({ latestNoticeableStall: Effect.succeed(undefined) }), +}) {} /** Delay in ns, active time in ms, CPU in µs. */ export interface EventLoopReadings { @@ -34,6 +52,12 @@ export interface EventLoopReadings { | "involuntaryContextSwitches" >; readonly rssBytes: number; + readonly heapUsedBytes: number; + /** Wall time the readings cover. */ + readonly elapsedMs: number; + /** One-minute load average, undefined on Windows. */ + readonly loadAverage: number | undefined; + readonly cpuCount: number; } // Node skips the first gap after a reset, so a stall right at a sample boundary can be missed. @@ -48,11 +72,14 @@ const makeNodeSampler = Effect.gen(function* () { ); let elu = NodePerfHooks.performance.eventLoopUtilization(); let usage = process.resourceUsage(); + let sampledAt = NodePerfHooks.performance.now(); // @effect-diagnostics-next-line returnEffectInGen:off - the read effect is the result. return Effect.sync(() => { const nextElu = NodePerfHooks.performance.eventLoopUtilization(); const nextUsage = process.resourceUsage(); + const nextSampledAt = NodePerfHooks.performance.now(); + const memory = process.memoryUsage(); const loop = NodePerfHooks.performance.eventLoopUtilization(nextElu, elu); const readings: EventLoopReadings = { delayMaxNs: histogram.max, @@ -66,23 +93,43 @@ const makeNodeSampler = Effect.gen(function* () { involuntaryContextSwitches: nextUsage.involuntaryContextSwitches - usage.involuntaryContextSwitches, }, - rssBytes: process.memoryUsage.rss(), + rssBytes: memory.rss, + heapUsedBytes: memory.heapUsed, + elapsedMs: nextSampledAt - sampledAt, + // Windows has no load average and reports 0, which a running process never sees elsewhere. + loadAverage: NodeOS.loadavg()[0] || undefined, + cpuCount: NodeOS.availableParallelism(), }; histogram.reset(); elu = nextElu; usage = nextUsage; + sampledAt = nextSampledAt; return readings; }); }); export const stallMs = ({ delayMaxNs, activeMs }: EventLoopReadings) => { const delayMs = Math.round(delayMaxNs / 1e6) - RESOLUTION_MS; - // libuv's clock keeps running while the system sleeps on macOS and Windows, so a - // sleep also reads as delay, but the loop spent it idle in poll. + // libuv clocks run during macOS/Windows sleep; idle poll time distinguishes it from stalls. if (delayMs <= STALL_THRESHOLD_MS || activeMs < delayMs) return undefined; return delayMs; }; +// Untraced: it runs inside every 30-second tick, which already has the monitor's own span. +const recordGauges = Effect.fnUntraced(function* (readings: EventLoopReadings) { + const cpuMs = (readings.usage.userCPUTime + readings.usage.systemCPUTime) / 1000; + yield* Metric.update(Metrics.serverResidentBytes, readings.rssBytes); + yield* Metric.update(Metrics.serverHeapUsedBytes, readings.heapUsedBytes); + yield* Metric.update(Metrics.serverEventLoopUtilization, readings.utilization); + yield* Metric.update( + Metrics.serverEventLoopDelayMax, + Math.max(0, Math.round(readings.delayMaxNs / 1e6) - RESOLUTION_MS), + ); + if (readings.elapsedMs > 0) { + yield* Metric.update(Metrics.serverCpuUtilization, cpuMs / readings.elapsedMs); + } +}); + const encodeStallLine = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); export interface StallLogOptions { @@ -90,13 +137,20 @@ export interface StallLogOptions { readonly maxBytes: number; } -export const layerWith = ( +const layerWith = ( makeSampler: Effect.Effect, never, Scope.Scope>, stallLog: StallLogOptions, ) => - Layer.effectDiscard( + Layer.effect( + EventLoopMonitor, Effect.gen(function* () { const sample = yield* makeSampler; + // Clients sample on connect as well as the timer, and the sampler resets shared state. + const sampling = yield* Semaphore.make(1); + const warmedUp = yield* Ref.make(false); + const latestNoticeableStall = yield* Ref.make< + { readonly stall: ServerEventLoopStall; readonly detectedAtMs: number } | undefined + >(undefined); const stallSink = yield* Effect.try( () => new RotatingFileSink({ @@ -114,9 +168,25 @@ export const layerWith = ( ); const tick = Effect.gen(function* () { const readings = yield* sample; + yield* recordGauges(readings); const delayMaxMs = stallMs(readings); if (delayMaxMs === undefined) return; - const { utilization, usage, rssBytes } = readings; + const { utilization, usage, rssBytes, loadAverage, cpuCount } = readings; + const now = yield* DateTime.now; + const detectedAt = DateTime.formatIso(now); + if (delayMaxMs >= NOTICEABLE_STALL_MS) { + yield* Ref.set(latestNoticeableStall, { + detectedAtMs: DateTime.toEpochMillis(now), + stall: { + detectedAt, + durationMs: delayMaxMs, + ...(loadAverage === undefined + ? {} + : { loadAverage: Math.round(loadAverage * 10) / 10 }), + cpuCount, + }, + }); + } const attributes = { delayMaxMs, utilization: Math.round(utilization * 100) / 100, @@ -131,8 +201,7 @@ export const layerWith = ( Effect.withSpan("server.eventLoop.stall", { root: true, level: "Warn", attributes }), ); if (stallSink !== undefined) { - const time = DateTime.formatIso(yield* DateTime.now); - yield* encodeStallLine({ time, ...attributes }).pipe( + yield* encodeStallLine({ time: detectedAt, ...attributes }).pipe( Effect.flatMap((line) => Effect.try(() => stallSink.write(`${line}\n`))), Effect.catch(() => Effect.logWarning("event loop stall log write failed", { @@ -141,17 +210,25 @@ export const layerWith = ( ), ); } - }); + }).pipe(sampling.withPermits(1)); const wait = Effect.sleep(SAMPLE_INTERVAL); - // The layer builds before the rest of the server, so the first sample covers - // startup work such as migrations and projection bootstrap. That can block the - // loop for seconds on a large database, so skip it rather than warn at every - // launch. + // The first sample includes migrations and bootstrap; skip expected startup stalls. yield* wait.pipe( - Effect.andThen(sample), + Effect.andThen(sampling.withPermits(1)(sample)), + Effect.andThen(Ref.set(warmedUp, true)), Effect.andThen(wait.pipe(Effect.andThen(tick), Effect.forever)), Effect.forkScoped, ); + + return EventLoopMonitor.of({ + latestNoticeableStall: Effect.gen(function* () { + if (yield* Ref.get(warmedUp)) yield* tick; + const latest = yield* Ref.get(latestNoticeableStall); + if (latest === undefined) return undefined; + const ageMs = DateTime.toEpochMillis(yield* DateTime.now) - latest.detectedAtMs; + return ageMs <= NOTICEABLE_STALL_MAX_AGE_MS ? latest.stall : undefined; + }), + }); }), ); diff --git a/apps/server/src/observability/HeapSnapshot.test.ts b/apps/server/src/observability/HeapSnapshot.test.ts deleted file mode 100644 index 0beb466e50194..0000000000000 --- a/apps/server/src/observability/HeapSnapshot.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - tests fake a failed write at the native v8 boundary. -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeFS from "node:fs"; -import * as NodePath from "node:path"; -import * as NodeV8 from "node:v8"; -import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import { vi } from "vite-plus/test"; - -import { writeHeapSnapshot } from "./HeapSnapshot.ts"; - -vi.mock("node:v8", async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, writeHeapSnapshot: vi.fn(actual.writeHeapSnapshot) }; -}); - -it.layer(NodeServices.layer)("writeHeapSnapshot", (it) => { - it.effect("removes the partial file when the write fails", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const logsDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-heap-snapshot-test-" }); - let partialPath: string | undefined; - vi.mocked(NodeV8.writeHeapSnapshot).mockImplementationOnce((path) => { - partialPath = path; - if (path) NodeFS.writeFileSync(path, "partial"); - throw new Error("ENOSPC: no space left on device"); - }); - - yield* writeHeapSnapshot(logsDir); - - assert.strictEqual(NodePath.dirname(partialPath ?? ""), logsDir); - assert.deepEqual(yield* fs.readDirectory(logsDir), []); - }), - ); -}); diff --git a/apps/server/src/observability/HeapSnapshot.ts b/apps/server/src/observability/HeapSnapshot.ts index d015dce3c2a55..e452f4f5ce341 100644 --- a/apps/server/src/observability/HeapSnapshot.ts +++ b/apps/server/src/observability/HeapSnapshot.ts @@ -10,7 +10,7 @@ import * as Layer from "effect/Layer"; import * as ServerConfig from "../config.ts"; -export const writeHeapSnapshot = Effect.fn("server.heapSnapshot", { root: true })( +const writeHeapSnapshot = Effect.fn("server.heapSnapshot", { root: true })( function* (logsDir: string) { const fs = yield* FileSystem.FileSystem; const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-"); diff --git a/apps/server/src/observability/Metrics.test.ts b/apps/server/src/observability/Metrics.test.ts deleted file mode 100644 index ea1e60012d415..0000000000000 --- a/apps/server/src/observability/Metrics.test.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import { ProviderDriverKind } from "@t3tools/contracts"; -import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; -import * as Metric from "effect/Metric"; -import * as TestClock from "effect/testing/TestClock"; - -import { withMetrics } from "./Metrics.ts"; - -const hasMetricSnapshot = ( - snapshots: ReadonlyArray, - id: string, - attributes: Readonly>, -) => - snapshots.some( - (snapshot) => - snapshot.id === id && - Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), - ); - -const findHistogramSnapshot = ( - snapshots: ReadonlyArray, - id: string, - attributes: Readonly>, -) => - snapshots.find( - (snapshot): snapshot is Extract => - snapshot.type === "Histogram" && - snapshot.id === id && - Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value), - ); - -describe("withMetrics", () => { - it.effect("supports pipe-style usage", () => - Effect.gen(function* () { - const counter = Metric.counter("with_metrics_pipe_total"); - const timer = Metric.timer("with_metrics_pipe_duration"); - - const result = yield* Effect.succeed("ok").pipe( - withMetrics({ - counter, - timer, - attributes: { - operation: "pipe", - }, - }), - ); - - assert.equal(result, "ok"); - - const snapshots = yield* Metric.snapshot; - assert.equal( - hasMetricSnapshot(snapshots, "with_metrics_pipe_total", { - operation: "pipe", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", { - operation: "pipe", - }), - true, - ); - }), - ); - - it.effect("supports direct invocation", () => - Effect.gen(function* () { - const counter = Metric.counter("with_metrics_direct_total"); - - yield* withMetrics(Effect.fail("boom"), { - counter, - attributes: { - operation: "direct", - }, - }).pipe(Effect.exit); - - const snapshots = yield* Metric.snapshot; - assert.equal( - hasMetricSnapshot(snapshots, "with_metrics_direct_total", { - operation: "direct", - outcome: "failure", - }), - true, - ); - }), - ); - - it.effect("evaluates attributes lazily after the wrapped effect runs", () => - Effect.gen(function* () { - const counter = Metric.counter("with_metrics_lazy_total"); - const timer = Metric.timer("with_metrics_lazy_duration"); - let provider = ProviderDriverKind.make("unknown"); - const lazyInittedProvider = ProviderDriverKind.make("codex"); - - yield* Effect.sync(() => { - provider = lazyInittedProvider; - }).pipe( - withMetrics({ - counter, - timer, - attributes: () => ({ - provider, - operation: "lazy", - }), - }), - ); - - const snapshots = yield* Metric.snapshot; - assert.equal( - hasMetricSnapshot(snapshots, "with_metrics_lazy_total", { - provider: lazyInittedProvider, - operation: "lazy", - outcome: "success", - }), - true, - ); - assert.equal( - hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", { - provider: lazyInittedProvider, - operation: "lazy", - }), - true, - ); - }), - ); - - it.effect("counts interrupted work with an interrupt outcome and its duration", () => - Effect.gen(function* () { - const counter = Metric.counter("with_metrics_interrupt_total"); - const timer = Metric.timer("with_metrics_interrupt_duration"); - const started = yield* Deferred.make(); - - const fiber = yield* Deferred.succeed(started, undefined).pipe( - Effect.andThen(Effect.never), - withMetrics({ counter, timer, attributes: { operation: "interrupt" } }), - Effect.forkChild, - ); - yield* Deferred.await(started); - yield* TestClock.adjust(Duration.millis(5)); - yield* Fiber.interrupt(fiber); - - const snapshots = yield* Metric.snapshot; - assert.equal( - hasMetricSnapshot(snapshots, "with_metrics_interrupt_total", { - operation: "interrupt", - outcome: "interrupt", - }), - true, - ); - const duration = findHistogramSnapshot(snapshots, "with_metrics_interrupt_duration", { - operation: "interrupt", - }); - assert.equal(duration?.state.count, 1); - assert.equal(duration?.state.sum, 5); - }), - ); - - it.effect("measures durations on the monotonic clock, not the wall clock", () => - Effect.gen(function* () { - const timer = Metric.timer("with_metrics_monotonic_duration"); - const started = yield* Deferred.make(); - const finish = yield* Deferred.make(); - - const fiber = yield* Deferred.succeed(started, undefined).pipe( - Effect.andThen(Deferred.await(finish)), - withMetrics({ timer, attributes: { operation: "monotonic" } }), - Effect.forkChild, - ); - yield* Deferred.await(started); - yield* TestClock.adjust(Duration.millis(10)); - yield* TestClock.setTime(0); - yield* Deferred.succeed(finish, undefined); - yield* Fiber.join(fiber); - - const snapshots = yield* Metric.snapshot; - const duration = findHistogramSnapshot(snapshots, "with_metrics_monotonic_duration", { - operation: "monotonic", - }); - assert.equal(duration?.state.count, 1); - assert.equal(duration?.state.sum, 10); - }), - ); - - it.effect("records timer durations from nanosecond clock readings", () => - Effect.gen(function* () { - const duration = Duration.nanos(1_500_000n); - const timer = Metric.timer("with_metrics_nanos_duration"); - - yield* Effect.gen(function* () { - const fiber = yield* Effect.sleep(duration).pipe( - withMetrics({ - timer, - attributes: { - operation: "nanos", - }, - }), - Effect.forkChild, - ); - - yield* Effect.yieldNow; - yield* TestClock.adjust(duration); - yield* Fiber.join(fiber); - }).pipe(Effect.provide(TestClock.layer())); - - const snapshots = yield* Metric.snapshot; - const snapshot = findHistogramSnapshot(snapshots, "with_metrics_nanos_duration", { - operation: "nanos", - }); - - assert.equal(snapshot?.state.count, 1); - assert.equal(snapshot?.state.sum, 1.5); - }), - ); -}); diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts index 091ff5234d7e6..be92b47a5bdee 100644 --- a/apps/server/src/observability/Metrics.ts +++ b/apps/server/src/observability/Metrics.ts @@ -39,6 +39,42 @@ export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", { description: "Time for the provider adapter to start a turn, not how long the turn runs.", }); +// OTLP carries the unit, and Prometheus names the series by it: a unitless gauge gains `_ratio`. +export const serverResidentBytes = Metric.gauge("t3_server_resident_bytes", { + description: "Resident memory of the server process.", + attributes: { unit: "By" }, +}); + +export const serverHeapUsedBytes = Metric.gauge("t3_server_heap_used_bytes", { + description: "JavaScript heap in use by the server process.", + attributes: { unit: "By" }, +}); + +export const serverCpuUtilization = Metric.gauge("t3_server_cpu_utilization", { + description: "CPU time the server used per second over the last sample; 1 is one full core.", +}); + +export const serverEventLoopUtilization = Metric.gauge("t3_server_event_loop_utilization", { + description: "Share of the last sample the server's event loop spent busy.", +}); + +export const serverEventLoopDelayMax = Metric.gauge("t3_server_event_loop_delay_max", { + description: "Longest event loop delay over the last sample.", + attributes: { unit: "ms" }, +}); + +export const runsTotal = Metric.counter("t3_runs_total", { + description: "Runs that finished, by outcome. A later rollback does not count again.", +}); + +export const runDuration = Metric.timer("t3_run_duration", { + description: "Wall time of a run, from when it started to its terminal status.", +}); + +export const runQueueWait = Metric.timer("t3_run_queue_wait", { + description: "Time a run waited between being requested and starting.", +}); + export const gitCommandsTotal = Metric.counter("t3_git_commands_total", { description: "Total git commands executed by the server runtime.", }); @@ -101,12 +137,13 @@ export interface WithMetricsOptions { ) => Readonly>; } -const recordMetrics = ( - options: WithMetricsOptions, - startedAt: bigint, - exit: Exit.Exit, -) => - Effect.gen(function* () { +const recordMetrics = + /* Instrumentation must not create its own span for every recorded operation. */ + Effect.fnUntraced(function* ( + options: WithMetricsOptions, + startedAt: bigint, + exit: Exit.Exit, + ) { const duration = Duration.nanos((yield* Clock.monotonicTimeNanos) - startedAt); const baseAttributes = typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {}); @@ -134,8 +171,7 @@ const recordMetrics = ( } }); -// Durations come from the monotonic clock, so wall-clock corrections cannot skew them, and -// metrics are recorded in an exit finalizer, so interrupted work is counted as "interrupt". +// Monotonic timing ignores clock corrections; exit finalizers count interruptions. const withMetricsImpl = ( effect: Effect.Effect, options: WithMetricsOptions, diff --git a/apps/server/src/observability/Observability.ts b/apps/server/src/observability/Observability.ts index 05c382ea38281..343851e3d1d11 100644 --- a/apps/server/src/observability/Observability.ts +++ b/apps/server/src/observability/Observability.ts @@ -23,8 +23,7 @@ export const layer = Layer.unwrap( const traces = config.otlpTracesExport; const metrics = config.otlpMetricsExport; - // The trace serializer stays in the returned context because the browser - // trace forwarder exports on the same signal. + // Keep serialization in context for the browser trace forwarder's exporter. const layerSerialization = SharedObservability.layerOtlpSerialization(traces.protocol); const resource = ServerConfig.otlpResource(config, yield* HostProcess.Hostname); const attribution = yield* ResourceAttribution.ResourceAttribution; @@ -32,8 +31,7 @@ export const layer = Layer.unwrap( const layerTraceReferences = Layer.mergeAll( Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel), Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled), - // Keeps each SQL statement's span current while it waits for a connection, - // so the client can record the lock wait on it. + // Preserve SQL spans while awaiting connections so lock waits can be recorded on them. Layer.succeed(Statement.SpanPropagationEnabled, true), HttpObservability.layer, ); diff --git a/apps/server/src/observability/OtlpEndpointCheck.test.ts b/apps/server/src/observability/OtlpEndpointCheck.test.ts index 47d4ad76a6fe3..a197c55ae9a91 100644 --- a/apps/server/src/observability/OtlpEndpointCheck.test.ts +++ b/apps/server/src/observability/OtlpEndpointCheck.test.ts @@ -71,22 +71,6 @@ const check = (input: Parameters { - it.effect("posts an empty export for the signal with the T3 headers", () => { - const { requests, layer } = checkWith(200, { - otlpMetricsUrl: "http://collector:4318/v1/metrics", - otlpMetricsExport: { ...DEFAULT_SIGNAL_EXPORT, headers: { authorization: "Bearer t3" } }, - }); - return Effect.gen(function* () { - const result = yield* check({ signal: "metrics", url: "http://collector:4318/v1/metrics" }); - - assert.strictEqual(result._tag, "Accepted"); - assert.lengthOf(requests, 1); - assert.strictEqual(requests[0]?.url, "http://collector:4318/v1/metrics"); - assert.strictEqual(requests[0]?.headers.authorization, "Bearer t3"); - assert.strictEqual(requests[0]?.body, `{"resourceMetrics":[]}`); - }).pipe(Effect.provide(layer)); - }); - it.effect("keeps T3 credentials paired with each running signal endpoint", () => { const signalExport = { ...DEFAULT_SIGNAL_EXPORT, headers: { "x-api-key": "secret" } }; const { requests, layer } = checkWith(200, { @@ -130,15 +114,6 @@ describe("OtlpEndpointCheck", () => { }).pipe(Effect.provide(layer)); }); - it.effect("releases the request once the status is known", () => { - const { requests, layer } = checkWith(200); - return Effect.gen(function* () { - yield* check({ signal: "traces", url: "http://collector:4318/v1/traces" }); - - assert.isTrue(requests[0]?.signal.aborted); - }).pipe(Effect.provide(layer)); - }); - it.effect("keeps endpoint URLs and credentials out of traces", () => { const url = "https://collector.example.com/v1/logs?api_key=query-secret"; const { requests, layer } = checkWith(200, { @@ -204,24 +179,6 @@ describe("OtlpEndpointCheck", () => { ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - it.effect("reports the status a receiver rejects the export with", () => { - const { layer } = checkWith(401); - return Effect.gen(function* () { - const result = yield* check({ signal: "traces", url: "http://collector:4318/v1/traces" }); - - assert.deepStrictEqual(result, { _tag: "Rejected", status: 401 }); - }).pipe(Effect.provide(layer)); - }); - - it.effect("reports an endpoint that cannot be reached", () => { - const { layer } = checkWith(null); - return Effect.gen(function* () { - const result = yield* check({ signal: "logs", url: "http://localhost:1/v1/logs" }); - - assert.deepStrictEqual(result, { _tag: "Unreachable", timedOut: false }); - }).pipe(Effect.provide(layer)); - }); - it.effect("keeps OTEL endpoint credentials off other endpoints", () => { const otelUrl = "https://otel.example.com/v1/traces"; const otelExport = { ...DEFAULT_SIGNAL_EXPORT, headers: { "x-api-key": "secret" } }; @@ -232,6 +189,7 @@ describe("OtlpEndpointCheck", () => { ...OtelEnvironment.none, traces: OtelEnvironment.OtelSignal.Export({ url: otelUrl, + variable: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", protocol: otelExport.protocol, headers: otelExport.headers, }), diff --git a/apps/server/src/observability/OtlpEndpointCheck.ts b/apps/server/src/observability/OtlpEndpointCheck.ts index 6a136a2ff7aba..cb764f4557d92 100644 --- a/apps/server/src/observability/OtlpEndpointCheck.ts +++ b/apps/server/src/observability/OtlpEndpointCheck.ts @@ -58,9 +58,7 @@ const make = Effect.gen(function* () { return emptyExport(serialization, signal); }).pipe(Effect.provide(layerOtlpSerialization(signalExport.protocol))); const startedAt = yield* Clock.currentTimeMillis; - // Only the status matters. The scope aborts the request once it is read, so a receiver - // that keeps its body open cannot hold the connection. Tracing stays off, as it does for - // real exports, because request spans record the URL and custom credential headers. + // Close after reading status so open bodies cannot hang; disable tracing to keep URLs and credentials out of spans. const response = yield* HttpClient.withScope(httpClient) .post(url, { body, headers }) .pipe( diff --git a/apps/server/src/observability/RpcInstrumentation.test.ts b/apps/server/src/observability/RpcInstrumentation.test.ts deleted file mode 100644 index 84827fa180455..0000000000000 --- a/apps/server/src/observability/RpcInstrumentation.test.ts +++ /dev/null @@ -1,328 +0,0 @@ -import { assert, describe, it } from "@effect/vitest"; -import { - AuthEnvironmentMaintainScope, - AuthOrchestrationReadScope, - type AuthEnvironmentScope, - ScheduledTaskError, - ScheduledTaskId, - WS_METHODS, - WsRpcGroup, -} from "@t3tools/contracts"; -import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Metric from "effect/Metric"; -import * as Option from "effect/Option"; -import * as Stream from "effect/Stream"; -import * as Tracer from "effect/Tracer"; -import * as RpcTest from "effect/rpc/RpcTest"; -import * as TestClock from "effect/testing/TestClock"; - -import { RPC_REQUIRED_SCOPES } from "../auth/RpcAuthorization.ts"; -import * as RpcAuthorization from "../auth/RpcAuthorization.ts"; -import { RpcInstrumentation, rpcInstrumentationLayer } from "./RpcInstrumentation.ts"; - -type WsRpcMethod = keyof typeof RPC_REQUIRED_SCOPES; - -const groupOf = >(...tags: Tags) => - WsRpcGroup.omit( - ...[...WsRpcGroup.requests.keys()].filter( - (tag): tag is Exclude => - !(tags as ReadonlyArray).includes(tag), - ), - ).middleware(RpcInstrumentation); - -const connectionMiddleware = (scopes: ReadonlyArray) => - Layer.merge(RpcAuthorization.layer(scopes), rpcInstrumentationLayer); -const readOnlyConnection = connectionMiddleware([AuthOrchestrationReadScope]); -const taskId = ScheduledTaskId.make("scheduled-task:instrumented"); -const rpcSpanDefaults = { "rpc.transport": "websocket", "rpc.system": "effect-rpc" }; - -const withTelemetry = ( - test: (ended: ReadonlyArray) => Effect.Effect, -) => { - const ended: 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); - ended.push(span); - }; - return span; - }, - }); - return test(ended).pipe( - Effect.scoped, - Effect.withTracer(tracer), - Effect.provideService(Metric.MetricRegistry, new Map()), - ); -}; - -const rpcSpans = (ended: ReadonlyArray) => - ended.filter((span) => span.name.startsWith("ws.rpc.")); - -// RpcTest keeps Effect's own RpcServer/RpcClient spans, which ws.ts turns off with -// `disableTracing: true`. -const appSpans = (ended: ReadonlyArray) => - ended.filter((span) => span.attributes.get("rpc.system.name") !== "effect_rpc"); - -const exitTag = (span: Tracer.NativeSpan | undefined) => - span?.status._tag === "Ended" ? span.status.exit._tag : undefined; - -const parentSpanId = (span: Tracer.NativeSpan | undefined) => - span?.parent._tag === "Some" ? span.parent.value.spanId : undefined; - -const requestCount = ( - snapshots: ReadonlyArray, - method: string, - outcome: string, -) => - snapshots.find( - (snapshot): snapshot is Extract => - snapshot.type === "Counter" && - snapshot.id === "t3_rpc_requests_total" && - snapshot.attributes?.["method"] === method && - snapshot.attributes?.["outcome"] === outcome, - )?.state; - -const requestDuration = (snapshots: ReadonlyArray, method: string) => - snapshots.find( - (snapshot): snapshot is Extract => - snapshot.type === "Histogram" && - snapshot.id === "t3_rpc_request_duration" && - snapshot.attributes?.["method"] === method, - )?.state; - -describe("WS RPC instrumentation middleware", () => { - it.effect("records one span and request metric per call, including rejected calls", () => - withTelemetry((ended) => - Effect.gen(function* () { - const group = groupOf( - WS_METHODS.serverProbe, - WS_METHODS.scheduledTasksList, - WS_METHODS.serverRetryResourceTelemetry, - WS_METHODS.pullRequestsSubscribeRefreshes, - WS_METHODS.scheduledTasksSubscribe, - WS_METHODS.serverGetSettings, - ); - const client = yield* RpcTest.makeClient(group).pipe( - Effect.provide( - Layer.mergeAll( - group.toLayerHandler(WS_METHODS.serverProbe, () => - Effect.succeed({}).pipe(Effect.withSpan("serverProbe.child")), - ), - group.toLayerHandler(WS_METHODS.scheduledTasksList, () => - Effect.annotateCurrentSpan({ "scheduled_task.id": taskId }).pipe( - Effect.andThen(new ScheduledTaskError({ message: "List failed." })), - ), - ), - group.toLayerHandler(WS_METHODS.serverRetryResourceTelemetry, () => - Effect.die("authorization let a rejected call through"), - ), - group.toLayerHandler(WS_METHODS.pullRequestsSubscribeRefreshes, () => - Stream.make(1, 2), - ), - group.toLayerHandler(WS_METHODS.scheduledTasksSubscribe, () => - Stream.concat( - Stream.make({ tasks: [] }), - Stream.fail(new ScheduledTaskError({ message: "Subscription failed." })), - ), - ), - group.toLayerHandler(WS_METHODS.serverGetSettings, () => Effect.die("broken")), - readOnlyConnection, - ), - ), - ); - - assert.deepStrictEqual(yield* client[WS_METHODS.serverProbe]({}), {}); - const listError = yield* client[WS_METHODS.scheduledTasksList]({}).pipe(Effect.flip); - assert.equal(listError._tag, "ScheduledTaskError"); - const rejection = yield* client[WS_METHODS.serverRetryResourceTelemetry]({}).pipe( - Effect.flip, - ); - assert.equal(rejection._tag, "EnvironmentAuthorizationError"); - const refreshes = yield* Stream.runCollect( - client[WS_METHODS.pullRequestsSubscribeRefreshes]({}), - ); - assert.deepStrictEqual(Array.from(refreshes), [1, 2]); - const subscribeError = yield* Stream.runDrain( - client[WS_METHODS.scheduledTasksSubscribe]({}), - ).pipe(Effect.flip); - assert.equal(subscribeError._tag, "ScheduledTaskError"); - const settingsExit = yield* Effect.exit(client[WS_METHODS.serverGetSettings]({})); - assert.isTrue(Exit.hasDies(settingsExit)); - - assert.deepStrictEqual( - rpcSpans(ended).map((span) => [span.name, Object.fromEntries(span.attributes)]), - [ - [ - "ws.rpc.server.probe", - { - ...rpcSpanDefaults, - "rpc.method": WS_METHODS.serverProbe, - "rpc.aggregate": "server", - }, - ], - [ - "ws.rpc.scheduledTasks.list", - { - ...rpcSpanDefaults, - "rpc.method": WS_METHODS.scheduledTasksList, - "rpc.aggregate": "scheduledTasks", - "scheduled_task.id": taskId, - }, - ], - [ - "ws.rpc.server.retryResourceTelemetry", - { - ...rpcSpanDefaults, - "rpc.method": WS_METHODS.serverRetryResourceTelemetry, - "rpc.aggregate": "server", - }, - ], - [ - "ws.rpc.pullRequests.subscribeRefreshes", - { - ...rpcSpanDefaults, - "rpc.method": WS_METHODS.pullRequestsSubscribeRefreshes, - "rpc.aggregate": "pull-requests", - }, - ], - [ - "ws.rpc.scheduledTasks.subscribe", - { - ...rpcSpanDefaults, - "rpc.method": WS_METHODS.scheduledTasksSubscribe, - "rpc.aggregate": "scheduledTasks", - }, - ], - [ - "ws.rpc.server.getSettings", - { - ...rpcSpanDefaults, - "rpc.method": WS_METHODS.serverGetSettings, - "rpc.aggregate": "server", - }, - ], - ], - ); - assert.deepStrictEqual(rpcSpans(ended).map(exitTag), [ - "Success", - "Failure", - "Failure", - "Success", - "Failure", - "Failure", - ]); - const probeSpan = rpcSpans(ended)[0]; - const child = ended.find((span) => span.name === "serverProbe.child"); - assert.equal(parentSpanId(child), probeSpan?.spanId); - - const snapshots = yield* Metric.snapshot; - assert.deepStrictEqual( - [ - requestCount(snapshots, WS_METHODS.serverProbe, "success"), - requestCount(snapshots, WS_METHODS.scheduledTasksList, "failure"), - requestCount(snapshots, WS_METHODS.serverRetryResourceTelemetry, "failure"), - requestCount(snapshots, WS_METHODS.pullRequestsSubscribeRefreshes, "success"), - requestCount(snapshots, WS_METHODS.scheduledTasksSubscribe, "failure"), - requestCount(snapshots, WS_METHODS.serverGetSettings, "failure"), - ].map((state) => state?.count), - [1, 1, 1, 1, 1, 1], - ); - for (const method of group.requests.keys()) { - assert.equal(requestDuration(snapshots, method)?.count, 1); - } - }), - ), - ); - - it.effect("keeps a stream's span and duration open until the subscription is interrupted", () => - withTelemetry((ended) => - Effect.gen(function* () { - const waiting = yield* Deferred.make(); - const group = groupOf(WS_METHODS.pullRequestsSubscribeRefreshes); - const client = yield* RpcTest.makeClient(group).pipe( - Effect.provide( - Layer.mergeAll( - group.toLayerHandler(WS_METHODS.pullRequestsSubscribeRefreshes, () => - Stream.concat( - Stream.make(1), - Stream.fromEffect( - Deferred.succeed(waiting, undefined).pipe( - Effect.andThen(Effect.never), - Effect.withSpan("refreshes.wait"), - ), - ), - ), - ), - readOnlyConnection, - ), - ), - ); - - yield* TestClock.adjust(Duration.seconds(1)); - yield* TestClock.setTime(0); - const consumer = yield* Stream.runDrain( - client[WS_METHODS.pullRequestsSubscribeRefreshes]({}), - ).pipe(Effect.forkChild); - yield* Deferred.await(waiting); - yield* TestClock.adjust(Duration.millis(250)); - yield* TestClock.setTime(0); - assert.deepStrictEqual(appSpans(ended), []); - - yield* Fiber.interrupt(consumer); - - const [rpcSpan] = rpcSpans(ended); - assert.equal(rpcSpan?.name, "ws.rpc.pullRequests.subscribeRefreshes"); - assert.equal(exitTag(rpcSpan), "Failure"); - const waitSpan = ended.find((span) => span.name === "refreshes.wait"); - assert.equal(parentSpanId(waitSpan), rpcSpan?.spanId); - - const snapshots = yield* Metric.snapshot; - assert.equal( - requestCount(snapshots, WS_METHODS.pullRequestsSubscribeRefreshes, "interrupt")?.count, - 1, - ); - const duration = requestDuration(snapshots, WS_METHODS.pullRequestsSubscribeRefreshes); - assert.equal(duration?.count, 1); - assert.equal(duration?.sum, 250); - }), - ), - ); - - it.effect("records metrics but no spans for methods with tracing disabled", () => - withTelemetry((ended) => - Effect.gen(function* () { - const group = groupOf(WS_METHODS.serverSignalProcess); - const client = yield* RpcTest.makeClient(group).pipe( - Effect.provide( - Layer.mergeAll( - group.toLayerHandler(WS_METHODS.serverSignalProcess, (input) => - Effect.succeed({ - pid: input.pid, - signal: input.signal, - signaled: true, - message: Option.none(), - }).pipe(Effect.withSpan("signalProcess.child")), - ), - connectionMiddleware([AuthOrchestrationReadScope, AuthEnvironmentMaintainScope]), - ), - ), - ); - - const input = { pid: 4242, startTimeMs: 0, signal: "SIGINT" } as const; - assert.equal((yield* client[WS_METHODS.serverSignalProcess](input)).signaled, true); - - assert.deepStrictEqual(appSpans(ended), []); - const snapshots = yield* Metric.snapshot; - assert.equal(requestCount(snapshots, WS_METHODS.serverSignalProcess, "success")?.count, 1); - }), - ), - ); -}); diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 161694d55cb8f..499873f819796 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -9,10 +9,7 @@ import { rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts" type WsRpcMethod = RpcGroup.Rpcs["_tag"]; -/** - * Trace queries and dashboards group by these labels, so they keep their historical values - * even where they differ from the method prefix. - */ +// Trace queries and dashboards depend on these labels, including deviations from method prefixes. const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: "orchestration", @@ -24,6 +21,8 @@ const RPC_AGGREGATES = { [ORCHESTRATION_V2_WS_METHODS.searchThread]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: "orchestration", + [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: "orchestration", + [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: "orchestrationV2", [ORCHESTRATION_V2_WS_METHODS.launchThread]: "orchestration", [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: "orchestration", @@ -79,6 +78,7 @@ const RPC_AGGREGATES = { [WS_METHODS.serverGetResourceTelemetryHistory]: "server", [WS_METHODS.serverRetryResourceTelemetry]: "server", [WS_METHODS.serverCheckOtlpEndpoint]: "server", + [WS_METHODS.speechToTextCreateUploadUrl]: "server", [WS_METHODS.serverGetUsageSummary]: "server", [WS_METHODS.serverRefreshUsageRates]: "server", [WS_METHODS.serverSignalProcess]: "server", @@ -95,10 +95,12 @@ const RPC_AGGREGATES = { [WS_METHODS.scheduledTasksListWebhookDeliveries]: "scheduledTasks", [WS_METHODS.scheduledTasksGetWebhookDelivery]: "scheduledTasks", [WS_METHODS.secretsAnswerRequest]: "secrets", + [WS_METHODS.guestShareCreate]: "guest-share", [WS_METHODS.cloudGetRelayClientStatus]: "cloud", [WS_METHODS.cloudInstallRelayClient]: "cloud", [WS_METHODS.pullRequestsList]: "pull-requests", [WS_METHODS.pullRequestsListStats]: "pull-requests", + [WS_METHODS.pullRequestsFilterOptions]: "pull-requests", [WS_METHODS.pullRequestsSummary]: "pull-requests", [WS_METHODS.pullRequestsRouting]: "pull-requests", [WS_METHODS.pullRequestsRoutingIdentity]: "pull-requests", @@ -113,6 +115,7 @@ const RPC_AGGREGATES = { [WS_METHODS.pullRequestsThreadComments]: "pull-requests", [WS_METHODS.pullRequestsDiffFileContents]: "pull-requests", [WS_METHODS.pullRequestsFilesViewed]: "pull-requests", + [WS_METHODS.pullRequestsChangeBreakdown]: "pull-requests", [WS_METHODS.pullRequestsRunAction]: "pull-requests", [WS_METHODS.pullRequestsUpdate]: "pull-requests", [WS_METHODS.pullRequestsComment]: "pull-requests", @@ -137,6 +140,7 @@ const RPC_AGGREGATES = { [WS_METHODS.projectCloneRetry]: "source-control", [WS_METHODS.subscribeProjectClones]: "source-control", [WS_METHODS.projectsListEntries]: "workspace", + [WS_METHODS.projectsListIgnoredFiles]: "workspace", [WS_METHODS.projectsReadFile]: "workspace", [WS_METHODS.projectsSearchContents]: "workspace", [WS_METHODS.projectsSearchEntries]: "workspace", @@ -198,6 +202,7 @@ const RPC_AGGREGATES = { [WS_METHODS.subscribeDiscoveredLocalServers]: "preview", [WS_METHODS.deviceConfigure]: "device", [WS_METHODS.deviceTestHost]: "device", + [WS_METHODS.deviceEasAccount]: "device", [WS_METHODS.deviceList]: "device", [WS_METHODS.deviceOpen]: "device", [WS_METHODS.deviceClose]: "device", @@ -223,10 +228,7 @@ const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet = new Set([ WS_METHODS.serverSignalProcess, ]); -/** - * `ws.ts` adds it to the server's group after `RpcScopeAuthorization`, so it wraps - * authorization and also records rejected calls. - */ +/** Add after RpcScopeAuthorization to wrap authorization and record rejected calls. */ export class RpcInstrumentation extends RpcMiddleware.Service()( "t3/server/RpcInstrumentation", ) {} diff --git a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts b/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts deleted file mode 100644 index 170c3802e5b3f..0000000000000 --- a/apps/server/src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts +++ /dev/null @@ -1,252 +0,0 @@ -import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; -import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import { - EnvironmentId, - CommandId, - type ModelSelection, - MessageId, - ProjectId, - ProviderDriverKind, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; -import * as Console from "effect/Console"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as ResetCreditCoordinator from "../provider/resetCreditCoordinator.ts"; -import { FetchHttpClient } from "effect/http"; -import { describe } from "vite-plus/test"; - -import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; -import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; -import * as HostPowerMonitor from "../background/HostPowerMonitor.ts"; -import * as ServerConfig from "../config.ts"; -import * as SqlitePersistence from "../persistence/Sqlite.ts"; -import * as AntigravityInstallation from "../provider/AntigravityInstallation.ts"; -import * as CodexInstallation from "../provider/CodexInstallation.ts"; -import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; -import * as ModelManifest from "../provider/ModelManifest.ts"; -import * as ProviderInstanceRegistryHydration from "../provider/ProviderInstanceRegistryHydration.ts"; -import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; -import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; -import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; -import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; -import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; -import * as ServerSettings from "../serverSettings.ts"; -import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; -import * as VcsProcess from "../vcs/VcsProcess.ts"; -import * as Orchestrator from "./Orchestrator.ts"; -import * as ProviderTurnStartServiceTestkit from "./ProviderTurnStartService.testkit.ts"; -import * as RuntimeLayer from "./runtimeLayer.ts"; -import * as McpSessionRegistryTestkit from "../mcp/McpSessionRegistry.testkit.ts"; - -const layerPlatformTest = Layer.merge( - NodeServices.layer, - Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ - resolveLink: () => Effect.die("unused title link"), - }), -); - -const runAntigravityFixture = process.env.T3_ACP_ANTIGRAVITY_LIVE === "1"; -const liveAgentId = runAntigravityFixture - ? "antigravity-acp" - : process.env.T3_ACP_REGISTRY_LIVE_AGENT_ID?.trim() || "devin"; -const liveCommandPath = process.env.T3_ACP_REGISTRY_LIVE_COMMAND?.trim(); -const liveInstanceId = ProviderInstanceId.make("acpRegistry_live"); -const liveModelSelection = { - instanceId: liveInstanceId, - model: "default", -} satisfies ModelSelection; - -const layerServerConfig = ServerConfig.layerTest(process.cwd(), { - prefix: "t3-acp-registry-v2-live-", -}); - -const layerVcsDriverRegistry = VcsDriverRegistry.layer.pipe( - Layer.provide(VcsProcess.layer), - Layer.provide(layerServerConfig), - Layer.provide(layerPlatformTest), -); - -const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDriverRegistry)); - -const layerServerSettings = ServerSettings.layerTest({ - providerInstances: { - [liveInstanceId]: { - driver: ProviderDriverKind.make("acpRegistry"), - displayName: `ACP Registry: ${liveAgentId}`, - enabled: true, - config: { - agentId: liveAgentId, - ...(liveCommandPath ? { commandPath: liveCommandPath } : {}), - }, - }, - }, -}); -const layerBackgroundPolicy = BackgroundPolicy.layer.pipe( - Layer.provide(Layer.effect(HostPowerMonitor.HostPowerMonitor, HostPowerMonitor.make())), - Layer.provide(layerServerSettings), -); -const layerProviderInstanceRegistry = ProviderInstanceRegistryHydration.layer.pipe( - Layer.provide( - Layer.mergeAll( - layerServerConfig.pipe(Layer.provide(layerPlatformTest)), - layerServerSettings, - ServerSecretStore.layer.pipe( - Layer.provide(layerServerConfig), - Layer.provide(layerPlatformTest), - ), - NodeServices.layer, - FetchHttpClient.layer, - OpenCodeRuntime.layer.pipe( - Layer.provide(OpenCodeServerLedger.layerTest), - Layer.provide(layerPlatformTest), - ), - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ProviderLatestVersions.layer, - ModelManifest.layerTest, - AntigravityInstallation.AntigravityInstallation.layer.pipe( - Layer.provide(layerServerConfig.pipe(Layer.provide(layerPlatformTest))), - Layer.provide(FetchHttpClient.layer), - Layer.provide(layerPlatformTest), - ), - Layer.mock(CodexInstallation.CodexInstallation)({ - managedDirectory: "unused-managed-installation", - }), - Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { - getEnvironmentId: Effect.succeed( - EnvironmentId.make("00000000-0000-4000-8000-000000000001"), - ), - }), - ), - ), -); - -const layerLive = RuntimeLayer.layer.pipe( - Layer.provide(McpSessionRegistryTestkit.layer), - Layer.provide(SqlitePersistence.layerMemory), - Layer.provide(layerCheckpointStore), - Layer.provide(layerServerConfig), - Layer.provide(layerServerSettings), - Layer.provide(layerProviderInstanceRegistry), - Layer.provide(ResetCreditCoordinator.layer), - Layer.provide(layerBackgroundPolicy), - Layer.provide(ProviderTurnStartServiceTestkit.layer), - Layer.provide(layerPlatformTest), - Layer.provide(McpProviderSessions.layer), -); - -const waitForIdle = Effect.fn("AcpRegistryOrchestratorV2Live.waitForIdle")(function* ( - threadId: ThreadId, - expectedRunCount: number, -) { - const orchestrator = yield* Orchestrator.OrchestratorV2; - for (let attempt = 0; attempt < 900; attempt += 1) { - const projection = yield* orchestrator.getThreadProjection(threadId); - if ( - projection.runs.length >= expectedRunCount && - projection.runs.every( - (run) => !["queued", "starting", "running", "waiting"].includes(run.status), - ) - ) { - return projection; - } - yield* Effect.sleep("500 millis"); - } - return yield* Effect.die(new Error(`Timed out waiting for ACP Registry thread ${threadId}.`)); -}); - -describe.runIf(runAntigravityFixture || process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")( - "ACP Registry V2 live orchestrator", - () => { - it.live( - `runs and resumes ${runAntigravityFixture ? "Google Antigravity" : "a real registry agent"} through the production V2 harness`, - () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const projectId = ProjectId.make("project:acp-registry-live"); - const threadId = ThreadId.make("thread:acp-registry-live"); - const marker = "ACP_REGISTRY_LIVE_7H3Q"; - - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:acp-registry-live:create"), - threadId, - projectId, - title: `ACP Registry live: ${liveAgentId}`, - modelSelection: liveModelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - }); - yield* Console.log( - `ACP Registry thread created for '${liveAgentId}'; dispatching first prompt.`, - ); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:acp-registry-live:first"), - threadId, - messageId: MessageId.make("message:acp-registry-live:first"), - text: `Remember this opaque marker. Respond with exactly: ${marker}`, - attachments: [], - modelSelection: liveModelSelection, - dispatchMode: { type: "start_immediately" }, - }); - const firstProjection = yield* waitForIdle(threadId, 1); - const firstAssistant = firstProjection.messages.findLast( - (message) => message.role === "assistant", - )?.text; - - assert.deepEqual( - firstProjection.runs.map((run) => [run.providerInstanceId, run.status]), - [[liveInstanceId, "completed"]], - ); - assert.include(firstAssistant ?? "", marker); - - yield* Console.log("First ACP turn completed; dispatching continuation prompt."); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:acp-registry-live:second"), - threadId, - messageId: MessageId.make("message:acp-registry-live:second"), - text: "Return the opaque marker from the previous turn. Respond with only the marker.", - attachments: [], - modelSelection: liveModelSelection, - dispatchMode: { type: "start_immediately" }, - }); - const finalProjection = yield* waitForIdle(threadId, 2); - const finalAssistant = finalProjection.messages.findLast( - (message) => message.role === "assistant", - )?.text; - - assert.deepEqual( - finalProjection.runs.map((run) => [run.providerInstanceId, run.status]), - [ - [liveInstanceId, "completed"], - [liveInstanceId, "completed"], - ], - ); - assert.include(finalAssistant ?? "", marker); - assert.deepEqual(finalProjection.providerSessions.length, 2); - assert.isAtLeast(finalProjection.providerThreads.length, 1); - assert.deepEqual( - finalProjection.providerTurns.map((turn) => turn.status), - ["completed", "completed"], - ); - }).pipe(Effect.provide(layerLive), Effect.scoped), - 480_000, - ); - }, -); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 35c271ac0f0a1..73b66f2dc39c3 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4,10 +4,12 @@ import { normalizeDevinSessionUpdate, normalizeDevinToolCall, extractDevinSubagentUpdate, + makeAcpRegistryAdapterV2, } from "@t3tools/provider-acp-registry/testing"; +import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; +import { AcpRegistryCatalog } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; +import { decodeAcpReplayTranscript, makeAcpReplayRuntime } from "./AcpAdapterV2.testkit.ts"; // @effect-diagnostics nodeBuiltinImport:off -import * as NodeChildProcess from "node:child_process"; -import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -15,22 +17,19 @@ import { assert, describe, it } from "@effect/vitest"; import { CheckpointId, EnvironmentId, - MessageId, type ModelSelection, - NodeId, - ProjectId, ProviderDriverKind, ProviderInstanceId, ProviderSessionId, - ProviderThreadId, - RunAttemptId, - RunId, ThreadId, type OrchestrationV2ProviderThread, + type OrchestrationV2TurnItem, type ProviderOptionDescriptor, + type ProviderUserInputAnswers, } from "@t3tools/contracts"; import { GrokSettings } from "@t3tools/provider-grok/settings"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { deriveBlockedOnThreadWait } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -44,10 +43,8 @@ import * as Fiber from "effect/Fiber"; 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 Queue from "effect/Queue"; import * as Schema from "effect/Schema"; -import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as Scope from "effect/Scope"; import * as TestClock from "effect/testing/TestClock"; @@ -56,6 +53,7 @@ import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpProtocol from "effect-acp/protocol"; import type * as EffectAcpSchema from "effect-acp/compat"; +import { writeFakeCli } from "@t3tools/provider-testing/fakeCli"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; @@ -65,28 +63,22 @@ import { acpProviderOptionDescriptors, } from "@t3tools/provider-acp/server/sessionConfig"; import { - extractXAiAcpSubagentEndNotice, extractXAiAcpSubagentUpdate, + makeGrokAdapterV2, makeXAiPromptCompletionRuntime, normalizeXAiAcpToolCallState, registerXAiBackgroundTaskTracking, } from "@t3tools/provider-grok/testing"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; +import { makeTurnInput } from "./AcpAdapterV2.testkit.ts"; import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { AcpProviderCapabilitiesV2, - acpProviderItemNativeId, acpScopedNativeId, - acpCarryoverTerminalShouldClearContinuation, acpPostSettleContinuationOfferEvidence, - acpIsAppOwnedWakeTurn, - acpPostSettleMonitorPromptShouldSuppress, acpPostSettleWakeEvidence, - acpPostSettleWakeShouldBuffer, - acpProjectedCommandExitCode, acpToolCallDiffPatch, - acpTurnStartShouldPreserveContinuation, makeAcpAdapterV2, type AcpAdapterV2ExtensionContext, type AcpAdapterV2Flavor, @@ -94,13 +86,16 @@ import { type AcpAdapterV2SubagentUpdate, } from "@t3tools/provider-acp/server/adapter"; -import { makeGrokAdapterV2 } from "@t3tools/provider-grok/testing"; +import { appendUserInputAttachmentPaths } from "../../provider/userInputAttachments.ts"; + +import { makeGrokAcpAdapterFlavor } from "@t3tools/provider-grok/testing"; import { acpRegistryPromptFailure, registerMistralVibeAcpExtensions, } from "@t3tools/provider-acp-registry/testing"; const DEFAULT_GROK_SETTINGS = Schema.decodeSync(GrokSettings)({}); +const DROID_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({ agentId: "factory-droid" }); const layerHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)); @@ -113,24 +108,6 @@ const layerTest = Layer.mergeAll( const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test"); const decodeUnknownJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); -describe("acpProjectedCommandExitCode", () => { - const successOutput = { type: "Bash", exit_code: 0 }; - const failedOutput = { type: "Bash", exit_code: 1 }; - - it("omits exit codes for non-terminal and interrupted tool statuses", () => { - assert.equal(acpProjectedCommandExitCode("pending", successOutput), undefined); - assert.equal(acpProjectedCommandExitCode("running", successOutput), undefined); - assert.equal(acpProjectedCommandExitCode("interrupted", successOutput), undefined); - }); - - it("projects real exit codes only for completed and failed tools", () => { - assert.equal(acpProjectedCommandExitCode("completed", successOutput), 0); - assert.equal(acpProjectedCommandExitCode("completed", failedOutput), 1); - assert.equal(acpProjectedCommandExitCode("failed", failedOutput), 1); - assert.equal(acpProjectedCommandExitCode("completed", {}), undefined); - }); -}); - describe("acpToolCallDiffPatch", () => { it("builds a patch per file from ACP v1 oldText/newText, with /dev/null for a new file", () => { assert.equal( @@ -156,221 +133,8 @@ describe("acpToolCallDiffPatch", () => { ].join("\n"), ); }); - - it("keeps the ACP v2 patch text as sent", () => { - const text = "diff --git a/repo/a.ts b/repo/a.ts\n"; - assert.equal( - acpToolCallDiffPatch([ - { - type: "diff", - changes: [{ operation: "modify", path: "/repo/a.ts" }], - patch: { format: "git_patch", text }, - }, - ]), - text, - ); - }); - - it("drops the patch for a rewrite too large to diff cheaply", () => { - const lines = (prefix: string) => - Array.from({ length: 2_000 }, (_, index) => `${prefix} ${index}`).join("\n"); - assert.isUndefined( - acpToolCallDiffPatch([ - { type: "diff", path: "/repo/big.ts", oldText: lines("old"), newText: lines("new") }, - ]), - ); - }); -}); - -describe("ACP continuation ownership", () => { - it("preserves a continuation offered during non-buffered carryover handling", () => { - assert.isFalse( - acpCarryoverTerminalShouldClearContinuation({ - continuationOffered: true, - wakeBufferLength: 0, - }), - ); - assert.isFalse( - acpCarryoverTerminalShouldClearContinuation({ - continuationOffered: false, - wakeBufferLength: 1, - }), - ); - assert.isTrue( - acpCarryoverTerminalShouldClearContinuation({ - continuationOffered: false, - wakeBufferLength: 0, - }), - ); - }); - - it("preserves only user-raced offers that still own buffered wake traffic", () => { - assert.isTrue( - acpTurnStartShouldPreserveContinuation({ - continuationRequested: true, - isContinuationTurn: false, - wakeBufferLength: 1, - }), - ); - assert.isFalse( - acpTurnStartShouldPreserveContinuation({ - continuationRequested: true, - isContinuationTurn: false, - wakeBufferLength: 0, - }), - ); - assert.isFalse( - acpTurnStartShouldPreserveContinuation({ - continuationRequested: true, - isContinuationTurn: true, - wakeBufferLength: 1, - }), - ); - }); }); -const taskkillPlatformError = (method: string) => - PlatformError.systemError({ _tag: "Unknown", module: "taskkill-test", method }); - -function makeTaskkillSpawner(input: { - readonly exitCode?: number; - readonly exitFailure?: boolean; - readonly output?: string; - readonly outputFailure?: boolean; - readonly spawnFailure?: boolean; - readonly commands?: Array<{ readonly command: string; readonly args: ReadonlyArray }>; -}) { - return ChildProcessSpawner.make((command) => { - const value = command as unknown as { - readonly command: string; - readonly args: ReadonlyArray; - }; - input.commands?.push({ command: value.command, args: value.args }); - if (input.spawnFailure === true) return Effect.fail(taskkillPlatformError("spawn")); - const output = input.outputFailure - ? Stream.fail(taskkillPlatformError("output")) - : Stream.encodeText(Stream.make(input.output ?? "")); - return Effect.succeed( - ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(1234), - exitCode: input.exitFailure - ? Effect.fail(taskkillPlatformError("exitCode")) - : Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode ?? 0)), - isRunning: Effect.succeed(false), - kill: () => Effect.void, - unref: Effect.succeed(Effect.void), - stdin: Sink.drain, - stdout: Stream.empty, - stderr: Stream.empty, - all: output, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }), - ); - }); -} - -function processExists(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -const waitForProcesses = (pids: ReadonlyArray) => - Effect.gen(function* () { - while (!pids.every(processExists)) { - yield* Effect.sleep("10 millis"); - } - }).pipe(Effect.timeoutOption("2 seconds")); - -const waitForProcessesToExit = (pids: ReadonlyArray) => - Effect.gen(function* () { - while (pids.some(processExists)) { - yield* Effect.sleep("10 millis"); - } - }).pipe(Effect.timeoutOption("2 seconds")); - -function linuxProcessStart(pid: number): string | undefined { - try { - const stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); - const commandEnd = stat.lastIndexOf(")"); - return commandEnd < 0 - ? undefined - : stat - .slice(commandEnd + 2) - .trim() - .split(/\s+/)[19]; - } catch { - return undefined; - } -} - -function cleanupPublishedDetachedFixture(path: string): void { - let published: Array; - try { - published = NodeFS.readFileSync(path, "utf8") - .trim() - .split(/\s+/) - .map(Number) - .filter((pid) => Number.isSafeInteger(pid) && pid > 1); - } catch { - return; - } - const roots = published.filter((pid) => { - try { - return NodeFS.readFileSync(`/proc/${pid}/cmdline`, "utf8").includes(path); - } catch { - return false; - } - }); - const owned = new Map(); - const pending = [...roots]; - while (pending.length > 0) { - const pid = pending.shift(); - if (pid === undefined || owned.has(pid)) continue; - const start = linuxProcessStart(pid); - if (start === undefined) continue; - owned.set(pid, start); - try { - pending.push( - ...NodeFS.readFileSync(`/proc/${pid}/task/${pid}/children`, "utf8") - .trim() - .split(/\s+/) - .filter(Boolean) - .map(Number), - ); - } catch {} - } - for (const [pid, start] of [...owned.entries()].toReversed()) { - if (linuxProcessStart(pid) !== start) continue; - try { - process.kill(pid, "SIGKILL"); - } catch {} - } -} - -const waitForPublishedProcessIds = ( - fileSystem: FileSystem.FileSystem, - path: string, - count: number, -) => - Effect.gen(function* () { - while (true) { - const ids = (yield* fileSystem.readFileString(path)) - .trim() - .split(/\s+/) - .filter(Boolean) - .map(Number); - if (ids.length === count && ids.every((pid) => Number.isSafeInteger(pid) && pid > 1)) { - return ids; - } - yield* Effect.sleep("10 millis"); - } - }).pipe(Effect.timeoutOption("2 seconds")); - function makeMockRuntime(input: { readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly mockAgentPath: string; @@ -540,91 +304,138 @@ const pollProtocolMethods = (events: Queue.Queue>, +) { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-instruction-compaction"); + const threadId = ThreadId.make("thread-acp-instruction-compaction"); + yield* (yield* McpProviderSessions.McpProviderSessions).set({ + environmentId: EnvironmentId.make("environment-acp-instruction-compaction"), + threadId, + providerSessionId: "mcp-session-acp-instruction-compaction", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer instruction-compaction-token", + browserToolsAvailable: true, + }); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + supportsCompaction: true, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment, + wrapRuntime: (runtime) => ({ + ...runtime, + // Make compaction during prompt completion deterministic at the adapter boundary. + prompt: (payload, options) => + runtime.prompt(payload, options).pipe(Effect.tap(() => runtime.drainEvents)), + }), + }), }, + selfInvocation, + }); + 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-instruction-compaction"), modelSelection, - runtimePolicy: input.runtimePolicy, - }; + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const now = yield* DateTime.now; + let ordinal = 0; + return Effect.fnUntraced(function* (messageText: string, expectedStatus = "completed") { + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: ++ordinal, + messageText, + }), + ); + const terminal = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + assert.equal(Option.getOrThrow(terminal).status, expectedStatus); + while (true) { + const event = yield* Queue.take(protocolEvents); + if (event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt") { + return rawProtocolPromptTextBlocks(event); + } + } + }); +}); + +function assertReinjectedInstructions( + blocks: Array<{ type: "text"; text: string }>, + request: string, +) { + const text = blocks[0]?.text ?? ""; + assert.include(text, "T3 Code interaction mode: Default"); + assert.include(text, "T3 Code collaborative browser"); + assert.include(text, "T3 Code orchestration"); + assert.include(text, `\n${request}\n`); } describe("AcpAdapterV2", () => { - it.live.each(["failed", "recovered", "completed", "cancelled"] as const)( - "projects Mistral retry notices and their %s outcome", - (outcome) => + it.live.each(["details", "none"] as const)( + "fails the turn on an ACP v2 idle error with %s, settles its open tool, and accepts the next prompt", + (details) => Effect.gen(function* () { const path = yield* Path.Path; - const instanceId = ProviderInstanceId.make(`vibe-retry-${outcome}`); - const threadId = ThreadId.make(`thread-vibe-retry-${outcome}`); + const instanceId = ProviderInstanceId.make(`idle-error-${details}`); + const threadId = ThreadId.make(`thread-idle-error-${details}`); + const childSessionId = "mock-child-session-idle-error"; const adapter = yield* makeAcpAdapterV2({ instanceId, selfInvocation: yield* resolveSelfInvocation(), flavor: { - driver: ProviderDriverKind.make("acpRegistry"), + driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - registerExtensions: registerMistralVibeAcpExtensions, - promptFailure: (cause) => acpRegistryPromptFailure("mistral-vibe", cause), + extractBackgroundTaskId: (toolCall) => + toolCall.toolCallId === "tool-call-idle-error-monitor" + ? "idle-error-monitor" + : undefined, + extractSubagentUpdate: (toolCall) => + toolCall.toolCallId === "tool-call-idle-error-subagent" + ? { + nativeTaskId: "task-idle-error", + prompt: "child work", + title: "child work", + model: null, + status: toolCall.status === "completed" ? "completed" : "running", + childSessionId, + result: null, + suppressNormalTool: true, + } + : undefined, makeRuntime: makeMockRuntime({ childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, mockAgentPath: yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ), - environment: { T3_ACP_VIBE_RETRY_OUTCOME: outcome }, + environment: { T3_ACP_IDLE_ERROR: details }, }), }, }); @@ -636,7 +447,7 @@ describe("AcpAdapterV2", () => { const modelSelection = { instanceId, model: "default" } as const; const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make(`session-vibe-retry-${outcome}`), + providerSessionId: ProviderSessionId.make(`session-idle-error-${details}`), modelSelection, runtimePolicy, }); @@ -645,125 +456,432 @@ describe("AcpAdapterV2", () => { modelSelection, runtimePolicy, }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal, + }), + ); + return yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + }); + + const failedEvents = yield* runTurn(1); + const failed = failedEvents.at(-1); + assert.equal(failed?.type, "turn.terminal"); + if (failed?.type !== "turn.terminal" || failed.status !== "failed") { + return assert.fail("expected a failed terminal"); + } + assert.isTrue( + failed.childTurnsContinue, + "the run keeps ingesting work that outlives the failed prompt", ); - const events = yield* runtime.events.pipe( - Stream.takeUntil((event) => event.type === "turn.terminal"), - Stream.runCollect, + const lateSubagent = yield* runtime.events.pipe( + Stream.filter( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ), + Stream.runHead, + Effect.timeoutOption("2 seconds"), ); - const retries = events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "error" - ? [event.turnItem] - : [], + assert.isTrue( + Option.isSome(lateSubagent) && Option.isSome(lateSubagent.value), + "a subagent finishing after the failed prompt still reports to the run", ); - const running = retries.filter((item) => item.status === "running"); assert.deepEqual( - running.map((item) => item.retry?.attempt), - [1, 2], + failed.failure, + details === "details" + ? { + class: "provider_error", + message: "Missing Authentication header", + code: "-32000", + retryable: null, + } + : { + class: "provider_error", + message: "Provider turn failed.", + code: null, + retryable: null, + }, ); - assert.equal(new Set(retries.map((item) => item.id)).size, 1); - assert.include(running[0]!.failure.message, "Rate limit reached"); - assert.notInclude(running[0]!.failure.message, "private-key"); - const terminal = events.find((event) => event.type === "turn.terminal"); - assert.isDefined(terminal); - if (terminal?.type !== "turn.terminal") return yield* Effect.die("Missing terminal"); - if (outcome === "failed") { - assert.equal(terminal.status, "failed"); - assert.equal(terminal.failure?.class, "usage_limit"); - assert.include(terminal.failure?.message ?? "", "Rate limit exceeded for mistral"); - if (terminal.status === "failed") assert.equal(terminal.retry?.attempt, 2); - } else if (outcome === "cancelled") { - assert.equal(terminal.status, "cancelled"); - assert.equal(retries.at(-1)?.status, "cancelled"); - assert.equal(retries.at(-1)?.title, "Provider retry stopped"); - } else { - assert.equal(terminal.status, "completed"); - assert.equal(retries.at(-1)?.status, "completed"); - assert.equal(retries.at(-1)?.title, "Provider recovered"); - } + const toolItems = (nativeId: string) => + failedEvents.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId + ? [event.turnItem] + : [], + ); + const toolStatuses = toolItems("tool-call-idle-error-1").map((item) => item.status); + assert.include(toolStatuses, "running"); + assert.equal(toolStatuses.at(-1), "failed"); + assert.deepEqual( + toolItems("tool-call-idle-error-monitor").map((item) => item.status), + ["running"], + "a background monitor outlives the failed turn and keeps its running row", + ); + const childItems = toolItems("task-idle-error:tool:tool-call-idle-error-child"); + assert.deepEqual( + childItems.map((item) => item.status), + ["running"], + "a child-session tool keeps running in its own thread", + ); + assert.isTrue(childItems.every((item) => item.threadId !== threadId)); + assert.isEmpty( + toolItems("tool-call-idle-error-child"), + "the failed turn must not reproject the child tool as a root tool", + ); + + 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), ); - it("preserves legacy ids and scopes v2 ids by provider instance", () => { - const instanceId = ProviderInstanceId.make("acp-identity-test"); - assert.equal( - acpProviderItemNativeId({ instanceId, itemIdentityVersion: undefined, nativeId: "item-1" }), - "item-1", - ); - assert.equal( - acpProviderItemNativeId({ instanceId, itemIdentityVersion: 2, nativeId: "item-1" }), - acpScopedNativeId(instanceId, "item-1"), - ); - }); - - it.effect("starts the MCP bridge directly from the self-contained runtime", () => + // Factory Droid 0.243.0 sends an optional text companion for every AskUser choice. + const droidChoice = { + type: "string", + title: "Format", + description: "Which reply format?", + oneOf: [ + { const: "option_0", title: "JSON" }, + { const: "option_1", title: "Plain text" }, + { const: "other", title: "Other answer" }, + ], + }; + const droidSchema = { + type: "object", + properties: { + question_1: droidChoice, + question_1_other: { type: "string" }, + question_2: { ...droidChoice, title: "Alternative" }, + question_2_other: { type: "string" }, + }, + required: ["question_1", "question_2"], + }; + const droidQuestions = ["question_1", "question_2"].map((id, index) => ({ + id, + header: index === 0 ? "Format" : "Alternative", + question: "Which reply format?", + options: [ + { label: "JSON", description: "JSON", value: "option_0" }, + { label: "Plain text", description: "Plain text", value: "option_1" }, + ], + })); + + // regression: #20417 Droid AskUser answers were sent as a cancel + it.live.each([ + { + scenario: "preserves selected IDs and encodes custom answers", + schema: droidSchema, + questions: droidQuestions, + answers: { question_1: "option_1", question_2: "Markdown" }, + result: { + action: "accept", + content: { question_1: "option_1", question_2: "other", question_2_other: "Markdown" }, + }, + }, + { + scenario: "preserves selected labels and attachment paths in custom answers", + schema: droidSchema, + questions: droidQuestions, + withAttachments: true, + answers: { + question_1: "option_1", + question_2: "option_1\n\nAttached notes: keep this custom text", + }, + result: (directory: string) => ({ + action: "accept", + content: { + question_1: "other", + question_1_other: `Plain text\n\nAttached image "shot.png": ${JSON.stringify(NodePath.join(directory, "droid-shot.png"))}\nAttached file "spec.txt": ${JSON.stringify(NodePath.join(directory, "droid-spec.txt"))}`, + question_2: "other", + question_2_other: "option_1\n\nAttached notes: keep this custom text", + }, + }), + }, + { + scenario: "cancels without accepting answers", + schema: droidSchema, + questions: droidQuestions, + answers: undefined, + result: { action: "cancel" }, + }, + { + scenario: "falls back for an unrelated form", + schema: { type: "object", properties: { name: { type: "string" } } }, + questions: [{ id: "name", header: "Question 1", question: "Your answer?", options: [] }], + answers: { name: "Ada" }, + result: { action: "accept", content: { name: "Ada" } }, + }, + ])("Droid elicitation $scenario", ({ schema, questions, answers, result, withAttachments }) => Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation().pipe( - Effect.provideService(HostProcess.IsExecutable, true), + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-droid-form-" }); + const statusPath = path.join(directory, "status.json"); + const expectedResult = typeof result === "function" ? result(directory) : result; + let preparedAnswers: ProviderUserInputAnswers | undefined = answers; + if (withAttachments && answers !== undefined) { + yield* fileSystem.writeFileString(path.join(directory, "droid-shot.png"), "image"); + yield* fileSystem.writeFileString(path.join(directory, "droid-spec.txt"), "spec"); + preparedAnswers = yield* appendUserInputAttachmentPaths({ + answers, + attachmentsDir: directory, + attachmentsByQuestionId: { + question_1: [ + { + type: "image", + id: "droid-shot", + name: "shot.png", + mimeType: "image/png", + sizeBytes: 5, + }, + { + type: "file", + id: "droid-spec", + name: "spec.txt", + mimeType: "text/plain", + sizeBytes: 4, + }, + ], + }, + }); + } + const driver = ProviderDriverKind.make("acpRegistry"); + const transcript = yield* decodeAcpReplayTranscript( + { + provider: driver, + protocol: "acp.ndjson-jsonrpc", + version: "1", + scenario: "droid-form", + entries: [ + { + type: "expect_outbound", + frame: { kind: "request", method: "initialize", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/new", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/new", + result: { sessionId: "droid-session" }, + }, + }, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + { + type: "emit_inbound", + frame: { + kind: "request", + method: "elicitation/create", + params: { + mode: "form", + sessionId: "droid-session", + message: "Your answer?", + requestedSchema: schema, + }, + }, + }, + { + type: "expect_outbound", + frame: { + kind: "response", + method: "elicitation/create", + result: expectedResult, + }, + }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { stopReason: "end_turn" }, + }, + }, + { type: "runtime_exit", status: "success" }, + ], + }, + driver, ); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + const instanceId = ProviderInstanceId.make("droid-form-test"); + const adapter = yield* makeAcpRegistryAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + settings: DROID_SETTINGS, + environment: {}, + makeRuntime: makeAcpReplayRuntime({ + transcript, + statusPath, + fileSystem, + scriptPath: yield* path.fromFileUrl( + new URL("../../../scripts/acp-replay-agent.ts", import.meta.url), + ), + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + }), + }).pipe( + Effect.provide( + Layer.mock(AcpRegistryCatalog)({ resolve: () => Effect.die("runtime is injected") }), + ), ); - - const instanceId = ProviderInstanceId.make("acp-test-self-contained-mcp-bridge"); - const threadId = ThreadId.make("thread-acp-self-contained-mcp-bridge"); - yield* (yield* McpProviderSessions.McpProviderSessions).set({ - environmentId: EnvironmentId.make("environment-acp-self-contained-mcp-bridge"), + const threadId = ThreadId.make("droid-form-thread"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: directory, + }); + const runtime = yield* adapter.openSession({ threadId, - providerSessionId: "mcp-session-acp-self-contained-mcp-bridge", - providerInstanceId: instanceId, - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer self-contained-mcp-bridge-token", - browserToolsAvailable: false, - }); - - let runtimeInput: AcpAdapterV2RuntimeInput | undefined; - const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: (input) => - Effect.sync(() => { - runtimeInput = input; - }).pipe(Effect.andThen(makeRuntime(input))), - }, - selfInvocation, - }); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), + modelSelection, + runtimePolicy, + providerSessionId: ProviderSessionId.make("droid-form-session"), }); - const modelSelection = { instanceId, model: "default" } as const; - yield* adapter.openSession({ + const providerThread = yield* runtime.ensureThread({ threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-self-contained-mcp-bridge"), modelSelection, runtimePolicy, }); - - const mcpServer = runtimeInput?.mcpServers[0]; - if (mcpServer === undefined || !("command" in mcpServer)) { - return yield* Effect.die("ACP runtime must receive the t3-code stdio MCP server"); - } - assert.equal(mcpServer.command, process.execPath); - assert.deepEqual(mcpServer.args, ["acp-mcp-bridge"]); - assert.equal(runtimeInput?.processEnvironment?.T3_ACP_MCP_NODE, process.execPath); - assert.equal(runtimeInput?.processEnvironment?.T3_ACP_MCP_ENTRYPOINT, undefined); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + const item = Option.getOrThrow( + yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ), + Stream.runHead, + ), + ); + if (item.type !== "turn_item.updated" || item.turnItem.type !== "user_input_request") + return yield* Effect.die("Expected Droid question"); + assert.deepEqual(item.turnItem.questions, questions); + yield* runtime.respondToRuntimeRequest({ + requestId: item.turnItem.requestId, + ...(preparedAnswers === undefined ? {} : { answers: preparedAnswers }), + }); + const terminal = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + assert.equal(Option.getOrThrow(terminal).status, "completed"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.live.each(["failed", "recovered", "cancelled"] as const)( + "projects Mistral retry notices and their %s outcome", + (outcome) => + Effect.gen(function* () { + const path = yield* Path.Path; + const instanceId = ProviderInstanceId.make(`vibe-retry-${outcome}`); + const threadId = ThreadId.make(`thread-vibe-retry-${outcome}`); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ProviderDriverKind.make("acpRegistry"), + capabilities: AcpProviderCapabilitiesV2, + registerExtensions: registerMistralVibeAcpExtensions, + promptFailure: (cause) => acpRegistryPromptFailure("mistral-vibe", cause), + makeRuntime: makeMockRuntime({ + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + mockAgentPath: yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ), + environment: { T3_ACP_VIBE_RETRY_OUTCOME: outcome }, + }), + }, + }); + 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(`session-vibe-retry-${outcome}`), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const retries = events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? [event.turnItem] + : [], + ); + const running = retries.filter((item) => item.status === "running"); + assert.deepEqual( + running.map((item) => item.retry?.attempt), + [1, 2], + ); + assert.equal(new Set(retries.map((item) => item.id)).size, 1); + assert.include(running[0]!.failure.message, "Rate limit reached"); + assert.notInclude(running[0]!.failure.message, "private-key"); + const terminal = events.find((event) => event.type === "turn.terminal"); + assert.isDefined(terminal); + if (terminal?.type !== "turn.terminal") return yield* Effect.die("Missing terminal"); + if (outcome === "failed") { + assert.equal(terminal.status, "failed"); + assert.equal(terminal.failure?.class, "usage_limit"); + assert.include(terminal.failure?.message ?? "", "Rate limit exceeded for mistral"); + if (terminal.status === "failed") assert.equal(terminal.retry?.attempt, 2); + } else if (outcome === "cancelled") { + assert.equal(terminal.status, "cancelled"); + assert.equal(retries.at(-1)?.status, "cancelled"); + assert.equal(retries.at(-1)?.title, "Provider retry stopped"); + } else { + assert.equal(terminal.status, "completed"); + assert.equal(retries.at(-1)?.status, "completed"); + assert.equal(retries.at(-1)?.title, "Provider recovered"); + } + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.live("refreshes ACP prompt instructions when the interaction mode changes", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -892,6 +1010,52 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.live( + "reinjects ACP instructions after protocol compaction, including during reinjection", + () => + Effect.gen(function* () { + const runTurn = yield* makeInstructionCompactionHarness({ + T3_ACP_COMPACTION_PROMPT_ORDINALS: "2,4", + }); + yield* runTurn("Start work."); + yield* runTurn("Continue until context compacts."); + assert.deepEqual(yield* runTurn(" /repro-skill"), [ + { type: "text", text: " /repro-skill" }, + ]); + assertReinjectedInstructions( + yield* runTurn("Continue after compaction."), + "Continue after compaction.", + ); + assertReinjectedInstructions( + yield* runTurn("Continue after the second compaction."), + "Continue after the second compaction.", + ); + assert.equal((yield* runTurn("Finish work."))[0]?.text, "Finish work."); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.live( + "reinjects ACP instructions after successful native compact, but not failed compact", + () => + Effect.gen(function* () { + const runTurn = yield* makeInstructionCompactionHarness({ + T3_ACP_FAIL_PROMPT_ORDINAL: "2", + }); + yield* runTurn("Start work."); + assert.deepEqual(yield* runTurn("/compact", "failed"), [ + { type: "text", text: "/compact" }, + ]); + assert.equal( + (yield* runTurn("Continue after failure."))[0]?.text, + "Continue after failure.", + ); + assert.deepEqual(yield* runTurn("/compact"), [{ type: "text", text: "/compact" }]); + assert.deepEqual(yield* runTurn("/repro-skill"), [{ type: "text", text: "/repro-skill" }]); + assertReinjectedInstructions(yield* runTurn("Continue work."), "Continue work."); + assert.equal((yield* runTurn("Finish work."))[0]?.text, "Finish work."); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.live("reapplies a selection after a switch away from it failed partway", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -980,6 +1144,140 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + // regression: #21499 turns blocked only on T3 thread waits must show as waiting + it.effect.each(["agent_message_chunk"] as const)( + "keeps named ACP %s open while deriving thread wait execution state", + (sessionUpdate) => + Effect.gen(function* () { + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let handler: Parameters[0] | undefined; + const instanceId = ProviderInstanceId.make("acp-named-stream-wait"); + const path = yield* Path.Path; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner: yield* ChildProcessSpawner.ChildProcessSpawner, + mockAgentPath: yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ), + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (next) => + Effect.sync(() => { + handler = next; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(next))), + prompt: () => + Effect.gen(function* () { + assert.isDefined(handler); + const updates = [ + { + sessionUpdate, + messageId: "named-stream", + content: { type: "text", text: "Waiting for the child result" }, + }, + { + sessionUpdate: "tool_call", + toolCallId: "wait", + title: "Wait for the child", + status: "in_progress", + rawInput: { + server: "t3-code", + tool: "t3_thread_wait", + arguments: { threadId: "child" }, + }, + _meta: { is_mcp_tool_call: true }, + }, + { + sessionUpdate: "tool_call", + toolCallId: "command", + kind: "execute", + title: "Run command", + status: "in_progress", + rawInput: { command: "pwd" }, + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "command", + status: "completed", + }, + { + sessionUpdate: "tool_call_update", + toolCallId: "wait", + status: "completed", + }, + ] satisfies Array; + for (const update of updates) + yield* handler!({ sessionId: "mock-session-1", update }); + return { stopReason: "end_turn" as const }; + }), + }), + }), + }, + }); + const threadId = ThreadId.make("thread-acp-named-stream-wait"); + const modelSelection = { instanceId, model: "default" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("session-acp-named-stream-wait"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const input = makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }); + yield* runtime.startTurn(input); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const retained = new Map(); + const states: Array = []; + for (const event of events) { + if (event.type !== "turn_item.updated") continue; + const item = event.turnItem; + retained.set(item.id, item); + if (item.type !== "dynamic_tool" && item.type !== "command_execution") continue; + const streams = [...retained.values()].filter( + (entry) => entry.type === "assistant_message" || entry.type === "reasoning", + ); + assert.deepEqual( + streams.map((entry) => [entry.type, entry.status]), + [ + [ + sessionUpdate === "agent_message_chunk" ? "assistant_message" : "reasoning", + "running", + ], + ], + ); + states.push( + deriveBlockedOnThreadWait({ + activeRun: { id: input.runId, status: "running" }, + turnItems: [...retained.values()], + }), + ); + } + assert.deepEqual(states, [true, false, true, false]); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect("starts a new replay message after ACP v2 plan boundaries", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -1073,8 +1371,7 @@ describe("AcpAdapterV2", () => { ); type Runtime = AcpSessionRuntime.AcpSessionRuntime["Service"]; let handler: Parameters[0] | undefined; - // Devin streams a file write as it generates it: each update resends the - // whole file so far, a few characters longer, with no status. + // Devin resends the growing file without status on each update. const file = `${"x = 1\n".repeat(800)}END_OF_FILE\n`; const chunks = 200; const streamedWrite = ( @@ -2126,45 +2423,6 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("cleans detached fixtures when an assertion aborts the test scope", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const fileSystem = yield* FileSystem.FileSystem; - let published: ReadonlyArray = []; - const failed = yield* Effect.scoped( - Effect.gen(function* () { - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-forced-failure-command-", - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => cleanupPublishedDetachedFixture(commandPidPath)), - ); - const fixture = NodeChildProcess.spawn( - "bash", - [ - "-c", - 'sleep 120 & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"', - "bash", - commandPidPath, - ], - { detached: true, stdio: "ignore" }, - ); - fixture.unref(); - published = Option.getOrThrow( - yield* waitForPublishedProcessIds(fileSystem, commandPidPath, 2), - ); - return yield* Effect.fail("forced assertion failure"); - }), - ).pipe(Effect.exit); - - assert.isTrue(Exit.isFailure(failed)); - assert.isTrue( - Option.isSome(yield* waitForProcessesToExit(published)), - "detached cleanup finalizer must reap the Bash and sleep fixture", - ); - }).pipe(Effect.provide(layerTest)), - ); - it.live("replaces an unexpectedly terminated ACP runtime before the next turn", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -2240,207 +2498,7 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("reaps detached native work when the provider exits before explicit teardown", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-provider-exit-command-", - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => cleanupPublishedDetachedFixture(commandPidPath)), - ); - const instanceId = ProviderInstanceId.make("acp-test-provider-exit"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDescendantProcessGroups: true, - ownDetachedProcessGroup: true, - processGroupTerminationGrace: 0, - environment: { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_EXIT_AFTER_RUNNING_COMMAND_LAUNCH: "1", - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION: "1", - }, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-provider-exit-running-command"); - 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-provider-exit"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.exit, Effect.forkScoped); - - const published = yield* waitForPublishedProcessIds(fileSystem, commandPidPath, 3); - assert.isTrue(Option.isSome(published), "detached fixture must publish all process IDs"); - const pids = Option.getOrThrow(published); - assert.isTrue( - Option.isSome(yield* waitForProcessesToExit(pids)), - "provider termination must reap the detached launcher, Bash, and sleep processes", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("surfaces reduced guarantee when delegated cgroup containment is unavailable", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - let containment: - | AcpSessionRuntime.AcpSessionRuntime["Service"]["processContainment"] - | undefined; - const instanceId = ProviderInstanceId.make("acp-test-cgroup-unavailable"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - linuxCgroupController: null, - mockAgentPath, - ownDescendantProcessGroups: true, - ownDetachedProcessGroup: true, - wrapRuntime: (runtime) => { - containment = runtime.processContainment; - return runtime; - }, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-cgroup-unavailable"); - 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-cgroup-unavailable"), - modelSelection, - runtimePolicy, - }); - yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); - assert.equal(containment, "process-ledger-reduced-guarantee"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("cleans a cgroup lease when the pre-exec join wrapper fails", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - let createCalls = 0; - let cgroupExists = true; - let killCalls = 0; - let removeCalls = 0; - const cgroupController: AcpSessionRuntime.AcpLinuxCgroupController = { - create: () => { - createCalls += 1; - return { - contains: () => false, - exists: () => cgroupExists, - path: "/definitely-missing/t3-acp-cgroup", - relativePath: "/definitely-missing/t3-acp-cgroup", - kill: () => { - killCalls += 1; - }, - populated: () => false, - remove: () => { - removeCalls += 1; - cgroupExists = false; - }, - }; - }, - }; - const instanceId = ProviderInstanceId.make("acp-test-cgroup-join-failure"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - linuxCgroupController: cgroupController, - mockAgentPath, - ownDescendantProcessGroups: true, - ownDetachedProcessGroup: true, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-cgroup-join-failure"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const opened = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-cgroup-join-failure"), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope), Effect.exit); - assert.isTrue(Exit.isFailure(opened)); - yield* Scope.close(sessionScope, Exit.void); - assert.equal(createCalls, 1); - assert.isAtLeast(killCalls, 1); - assert.isAtLeast(removeCalls, 1); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("negotiates and executes optional native session forks through the ACP runtime", () => + it.effect("negotiates and executes optional native session forks through the ACP runtime", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -2858,61 +2916,6 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.effect("fails missing native ACP session ids through the typed start-turn error channel", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("acp-test-missing-native-thread"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-missing-native-thread"); - 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-missing-native-thread"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - const error = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread: { ...providerThread, nativeThreadRef: null }, - instanceId, - runtimePolicy, - now, - }), - ) - .pipe(Effect.flip); - - assert.equal(error._tag, "ProviderAdapterTurnStartError"); - assert.instanceOf(error.cause, ProviderAdapter.ProviderAdapterProtocolError); - assert.include(String(error.cause), "missing its ACP session id"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - it.effect("replaces the ACP session and clears conversation state on rollback", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -3223,90 +3226,45 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.effect("keeps the original ACP session usable when a staged replacement terminates", () => + it.live("settles a Grok background command that completed before an ACP v2 idle error", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - let runtimeOrdinal = 0; - const makeBaseRuntime = makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - }); - const makeRuntime: AcpAdapterV2Flavor["makeRuntime"] = (runtimeInput) => - Effect.gen(function* () { - const currentOrdinal = runtimeOrdinal + 1; - runtimeOrdinal = currentOrdinal; - const currentRuntime = yield* makeBaseRuntime(runtimeInput); - if (currentOrdinal === 1) return currentRuntime; - return { - ...currentRuntime, - start: () => - currentRuntime.start().pipe( - Effect.tap(() => - runtimeInput.onTermination( - new EffectAcpErrors.AcpTransportError({ - detail: "Forced staged rollback replacement termination", - cause: "test", - }), - ), - ), - ), - }; - }); - const instanceId = ProviderInstanceId.make("acp-test-rollback-failure-compensation"); - const adapter = yield* makeAcpAdapterV2({ + const instanceId = ProviderInstanceId.make("grok-idle-error-background"); + const adapter = yield* makeGrokAdapterV2({ instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime, - }, - selfInvocation, + settings: DEFAULT_GROK_SETTINGS, + environment: {}, + hostPlatform: yield* HostProcess.Platform, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_IDLE_ERROR: "grok-background" }, + })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)), }); - const threadId = ThreadId.make("thread-acp-rollback-failure-compensation"); + const threadId = ThreadId.make("grok-idle-error-background"); + const modelSelection = { instanceId, model: "default" } 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-rollback-failure-compensation", - ), + providerSessionId: ProviderSessionId.make("grok-idle-error-background"), modelSelection, runtimePolicy, }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, }); - - const rollback = yield* runtime - .rollbackThread({ - providerThread, - providerThreadTurns: [], - target: { - type: "thread_start", - checkpointId: CheckpointId.make("checkpoint-acp-rollback-failure-compensation"), - appRunOrdinal: 0, - }, - }) - .pipe(Effect.result); - assert.equal(rollback._tag, "Failure"); - yield* runtime.startTurn( makeTurnInput({ threadId, @@ -3316,77 +3274,36 @@ describe("AcpAdapterV2", () => { now: yield* DateTime.now, }), ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId( - instanceId, - `${providerThread.nativeThreadRef?.nativeId}:turn:1`, - ), - }); - while (true) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - assert.equal(event.status, "completed"); - break; - } - } + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.at(-1); + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : undefined, "failed"); + const command = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === "call-idle-error-background", + ); + assert.equal( + command?.type === "turn_item.updated" ? command.turnItem.status : undefined, + "completed", + ); }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.effect("closes an idle ACP session exactly once through the transition permit", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-idle-finalizer"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-idle-finalizer"), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - yield* pollProtocolMethods(protocolEvents); - yield* Scope.close(sessionScope, Exit.void); - const finalizerMethods = yield* pollProtocolMethods(protocolEvents); - assert.equal(finalizerMethods.filter((method) => method === "session/close").length, 1); - }).pipe(Effect.provide(layerTest)), - ); - - it.effect.each(["grok-build", "composer-2"])( - "Grok configures the native session for %s", - (model) => + // Oracle: Grok incident frames. Command completion must release the turn even + // when the CLI keeps the prompt RPC and process alive. Command polls stay visible. + it.live( + "completes a structured Grok background command from poll with an unanswered prompt RPC", + () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.unbounded(); - const instanceId = ProviderInstanceId.make("grok-test"); + const instanceId = ProviderInstanceId.make("grok-background-completion"); const adapter = yield* makeGrokAdapterV2({ instanceId, settings: DEFAULT_GROK_SETTINGS, @@ -3394,74 +3311,35 @@ describe("AcpAdapterV2", () => { hostPlatform: yield* HostProcess.Platform, selfInvocation: yield* resolveSelfInvocation(), makeRuntime: (input) => - makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents })(input).pipe( - Effect.flatMap(makeXAiPromptCompletionRuntime), - ), + makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_GROK_BACKGROUND_TASK_COMPLETION: "poll" }, + })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)), }); - yield* adapter.openSession({ - threadId: ThreadId.make(`grok-model-${model}`), - providerSessionId: ProviderSessionId.make(`grok-model-${model}`), - modelSelection: { instanceId, model }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }), + const threadId = ThreadId.make("grok-background-completion"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), }); - const requests = (yield* Queue.takeAll(protocolEvents)).map(rawProtocolRequest); - assert.equal( - requests.filter( - (request) => - request?.method === "session/set_config_option" && - typeof request.params === "object" && - request.params !== null && - "configId" in request.params && - request.params.configId === "model", - ).length, - model === "grok-build" ? 0 : 1, + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("grok-background-completion"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("Grok reapplies an explicit return to the session's setup-time model", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.unbounded(); - const instanceId = ProviderInstanceId.make("grok-test-switch-back"); - const adapter = yield* makeGrokAdapterV2({ - instanceId, - settings: DEFAULT_GROK_SETTINGS, - environment: {}, - hostPlatform: yield* HostProcess.Platform, - selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => - makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents })(input).pipe( - Effect.flatMap(makeXAiPromptCompletionRuntime), - ), - }); - const threadId = ThreadId.make("grok-model-switch-back"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("grok-model-switch-back"), - modelSelection: { instanceId, model: "composer-2" }, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: { instanceId, model: "composer-2" }, - runtimePolicy, - }); - for (const model of ["default", "composer-2"]) { yield* runtime.startTurn( makeTurnInput({ threadId, @@ -3469,170 +3347,219 @@ describe("AcpAdapterV2", () => { instanceId, runtimePolicy, now: yield* DateTime.now, - modelSelection: { instanceId, model }, }), ); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, + const observed = yield* Stream.fromQueue(events).pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, ); - } - const requests = (yield* Queue.takeAll(protocolEvents)).map(rawProtocolRequest); - assert.equal( - requests.filter( - (request) => - request?.method === "session/set_config_option" && - typeof request.params === "object" && - request.params !== null && - "configId" in request.params && - request.params.configId === "model", - ).length, - 3, - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), + const allEvents = [...observed]; + let next = yield* Queue.poll(events); + while (Option.isSome(next)) { + allEvents.push(next.value); + next = yield* Queue.poll(events); + } + const terminals = allEvents.filter((event) => event.type === "turn.terminal"); + assert.deepEqual( + terminals.map((event) => event.status), + ["completed"], + ); + const items = allEvents.flatMap((event) => + event.type === "turn_item.updated" ? [event.turnItem] : [], + ); + assert.isFalse(items.some((item) => item.type === "subagent")); + const command = items.findLast( + (item) => item.nativeItemRef?.nativeId === "call-fb9d0000-0000-0000-0000-000000000026-29", + ); + assert.equal(command?.type, "command_execution"); + assert.equal(command?.status, "completed"); + assert.isTrue( + items.some((item) => item.nativeItemRef?.nativeId === "call-background-poll"), + "command TaskOutput must retain its normal tool frame", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.effect("skips requested options that the active ACP session does not expose", () => + // Grok expands only a leading `/name`, so a picked leading `$name` + // must reach it in that form; anything else keeps the user's text. + it.live.each([ + { text: "$deploy ship it", sent: "/deploy ship it", native: true }, + { text: "ship $deploy", sent: "ship $deploy", native: false }, + { text: "$other ship it", sent: "$other ship it", native: false }, + ])("Grok sends $text with a picked skill as $sent", ({ text, sent, native }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-unsupported-option"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-unsupported-option"), - modelSelection: { - instanceId, - model: "default", - options: [{ id: "missing-option", value: "high" }], - }, - runtimePolicy, + const hostPlatform = yield* HostProcess.Platform; + // Stands in for `grok inspect --json`, the catalog behind the `$` picker. + const catalog = { skills: [{ name: "deploy", source: { path: "/s/deploy/SKILL.md" } }] }; + const grokPath = writeFakeCli({ + directory: yield* fileSystem.makeTempDirectoryScoped(), + name: "grok", + source: `process.stdout.write(${JSON.stringify(`${JSON.stringify(catalog)}\n`)});\n`, + platform: hostPlatform, }); - - assert.equal(runtime.providerSession.status, "ready"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("reconfigures a loaded ACP session from its own active setup metadata", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("grok-skill-mention"); + const adapter = yield* makeGrokAdapterV2({ instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }), - }, - selfInvocation, + settings: { ...DEFAULT_GROK_SETTINGS, binaryPath: grokPath }, + // The fake CLI needs `node` on its PATH. + environment: { ...process.env }, + hostPlatform, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents })(input).pipe( + Effect.flatMap(makeXAiPromptCompletionRuntime), + ), }); - const firstThreadId = ThreadId.make("thread-acp-active-setup:first"); - const secondThreadId = ThreadId.make("thread-acp-active-setup:second"); + const threadId = ThreadId.make("grok-skill-mention"); + const modelSelection = { instanceId, model: "default" } as const; const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", cwd: process.cwd(), }); - const initialSelection = { instanceId, model: "default" } satisfies ModelSelection; - const alternateSelection = { - instanceId, - model: "composer-2", - } satisfies ModelSelection; - const originalSelection = { - instanceId, - model: "gpt-5.3-codex[reasoning=medium,fast=false]", - } satisfies ModelSelection; const runtime = yield* adapter.openSession({ - threadId: firstThreadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-active-setup"), - modelSelection: initialSelection, + threadId, + providerSessionId: ProviderSessionId.make("grok-skill-mention"), + modelSelection, runtimePolicy, }); - const firstProviderThread = yield* runtime.ensureThread({ - threadId: firstThreadId, - modelSelection: initialSelection, + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, runtimePolicy, }); - const now = yield* DateTime.now; yield* runtime.startTurn( makeTurnInput({ - threadId: firstThreadId, - providerThread: firstProviderThread, + threadId, + providerThread, instanceId, runtimePolicy, - modelSelection: alternateSelection, - now, + now: yield* DateTime.now, + messageText: text, }), ); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), + const prompt = yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), Stream.runHead, ); + const blocks = rawProtocolPromptTextBlocks(Option.getOrThrow(prompt)); + if (native) { + // Same shape as a typed native command: one bare text block, no T3 instructions. + assert.deepEqual(blocks, [{ type: "text", text: sent }]); + } else { + assert.isTrue(blocks.some((block) => block.text.includes(sent))); + assert.isFalse(blocks.some((block) => block.text.trimStart().startsWith("/"))); + } + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); - const secondProviderThread: OrchestrationV2ProviderThread = { - ...firstProviderThread, - id: ProviderThreadId.make("provider-thread-acp-active-setup:second"), - appThreadId: secondThreadId, - nativeThreadRef: { - driver: ACP_TEST_DRIVER, - nativeId: "mock-session-2", - strength: "strong", - }, - status: "idle", - }; - yield* runtime.resumeThread({ - providerThread: secondProviderThread, - modelSelection: alternateSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId: secondThreadId, - providerThread: secondProviderThread, + // Command completion must release the turn even when the CLI keeps the prompt RPC and process + // alive. Kill calls stay visible. + it.live.each([ + { shape: "output_only", expectedCommand: { type: "command_execution", status: "completed" } }, + { shape: "variant_only", expectedCommand: { type: "command_execution", status: "completed" } }, + { shape: "killed", expectedCommand: { type: "command_execution", status: "completed" } }, + { + shape: "already_exited", + expectedCommand: { type: "command_execution", status: "completed" }, + }, + { + shape: "known_failure", + expectedCommand: { type: "command_execution", status: "failed", output: "known failure\n" }, + }, + ] as const)( + "completes a Grok KillTask command ($shape) and preserves any known result", + ({ shape, expectedCommand }) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("grok-kill-completion"); + const adapter = yield* makeGrokAdapterV2({ instanceId, + settings: DEFAULT_GROK_SETTINGS, + environment: {}, + hostPlatform: yield* HostProcess.Platform, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_GROK_KILL_TASK_SHAPE: shape }, + })(input).pipe(Effect.flatMap(makeXAiPromptCompletionRuntime)), + }); + const threadId = ThreadId.make("grok-kill-completion"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("grok-kill-completion"), + modelSelection, runtimePolicy, - modelSelection: originalSelection, - now, - ordinal: 2, - }), - ); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, - ); - - const modelConfigurationRequests = Array.from(yield* Queue.takeAll(protocolEvents)).filter( - (event) => - event.direction === "outgoing" && - rawProtocolMethod(event) === "session/set_config_option" && - rawProtocolRequestParam(event, "configId") === "model", - ); - assert.lengthOf(modelConfigurationRequests, 2); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ); + const observed = yield* Stream.fromQueue(events).pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const allEvents = [...observed]; + let next = yield* Queue.poll(events); + while (Option.isSome(next)) { + allEvents.push(next.value); + next = yield* Queue.poll(events); + } + const terminals = allEvents.filter((event) => event.type === "turn.terminal"); + assert.deepEqual( + terminals.map((event) => event.status), + ["completed"], + ); + const items = allEvents.flatMap((event) => + event.type === "turn_item.updated" ? [event.turnItem] : [], + ); + assert.isFalse(items.some((item) => item.type === "subagent")); + const command = items.findLast( + (item) => item.nativeItemRef?.nativeId === "kill-target-command", + ); + assert.deepInclude(command, expectedCommand); + assert.isTrue( + items.some((item) => item.nativeItemRef?.nativeId === "kill-command"), + "KillTask must retain its normal tool frame", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); it.effect("keeps an agent's empty-valued default choice selectable", () => @@ -4168,7 +4095,7 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("carries elicitation request identity through the completed stdout write", () => + it.live("auto-approves tagged MCP elicitations under full-access policy", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -4176,9 +4103,7 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const responseWritten = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-reordered-elicitation"); + const instanceId = ProviderInstanceId.make("acp-test-mcp-approval-elicitation"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { @@ -4187,101 +4112,21 @@ describe("AcpAdapterV2", () => { makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_ELICITATION: "1" }, - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseWritten, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), + environment: { T3_ACP_EMIT_MCP_TOOL_APPROVAL_ELICITATION: "1" }, }), }, selfInvocation, }); - const threadId = ThreadId.make("thread-acp-reordered-elicitation"); + const threadId = ThreadId.make("thread-acp-mcp-approval-elicitation"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", + 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-reordered-elicitation"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if (pending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected a pending elicitation request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ - requestId: pending.runtimeRequest.id, - answers: { approved: ["true"] }, - }) - .pipe(Effect.forkScoped); - - yield* Deferred.await(responseWritten); - assert.isUndefined(responseFiber.pollUnsafe()); - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(responseFiber); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("auto-approves tagged MCP elicitations under full-access policy", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("acp-test-mcp-approval-elicitation"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_MCP_TOOL_APPROVAL_ELICITATION: "1" }, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-mcp-approval-elicitation"); - 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-mcp-approval-elicitation"), + providerSessionId: ProviderSessionId.make("provider-session-acp-mcp-approval-elicitation"), modelSelection, runtimePolicy, }); @@ -4412,456 +4257,537 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("rejects delayed native response registration when normal close wins the permit", () => + it.live("treats a second hard Stop as success when the turn is already gone", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; const path = yield* Path.Path; const selfInvocation = yield* resolveSelfInvocation(); const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const registrationStarted = yield* Deferred.make(); - const releaseRegistration = yield* Deferred.make(); - const transportClosed = yield* Deferred.make(); - const releaseTransportClose = yield* Deferred.make(); - const responseLifecycle: Array = []; - const instanceId = ProviderInstanceId.make("acp-test-close-wins-registration"); + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, + interruptPromptOnCancel: false, + restartRuntimeAfterInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, + ownDetachedProcessGroup: true, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + protocolEvents, }), }, selfInvocation, - testHooks: { - afterNativeResponseTransportClosed: () => - Deferred.succeed(transportClosed, undefined).pipe( - Effect.andThen(Deferred.await(releaseTransportClose)), - ), - beforeNativeResponseAdmissionCheck: () => - Deferred.succeed(registrationStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRegistration)), - ), - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, }); - const threadId = ThreadId.make("thread-acp-close-wins-registration"); + const threadId = ThreadId.make("thread-acp-double-stop"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", + runtimeMode: "full-access", interactionMode: "default", cwd: process.cwd(), }); const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-close-wins-registration"), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-double-stop"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, + const now = yield* DateTime.now; + yield* runtime + .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now })) + .pipe(Effect.forkScoped); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + yield* runtime.interruptTurn({ + providerThread, + providerTurnId, + requestRuntimeRestart: true, + }); + const second = yield* Effect.exit( + runtime.interruptTurn({ providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, + providerTurnId, + requestRuntimeRestart: true, }), ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if (pending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected a pending permission request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(registrationStarted); - - const closeFiber = yield* Scope.close(sessionScope, Exit.void).pipe(Effect.forkScoped); - yield* Deferred.await(transportClosed); - yield* Deferred.succeed(releaseRegistration, undefined); - while (!responseLifecycle.includes("admission_rejected")) { - yield* Effect.yieldNow; - } - const responseExit = yield* Fiber.join(responseFiber); - if (Exit.isSuccess(responseExit)) { - assert.fail("normal close must reject a response delayed before transport registration"); + assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent"); + let terminal: string | null = null; + while (terminal === null) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + terminal = event.status; + } } - assert.include(Cause.pretty(responseExit.cause), "ACP session transport closed"); - assert.equal(responseLifecycle.filter((event) => event === "registered").length, 1); - assert.equal(responseLifecycle.filter((event) => event === "removed").length, 1); - assert.equal(responseLifecycle.filter((event) => event === "admission_rejected").length, 1); - yield* Deferred.succeed(releaseTransportClose, undefined); - yield* Fiber.join(closeFiber); + assert.equal(terminal, "interrupted"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("bounds a missing pending permission response acknowledgement", () => + it.effect("finalizes a settled turn held open for background work when interrupted", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; const path = yield* Path.Path; const selfInvocation = yield* resolveSelfInvocation(); const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const responseEnqueued = yield* Deferred.make(); - const releaseNativeHook = yield* Deferred.make(); - const responseLifecycle: Array = []; - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test-pending-response-timeout"); + const instanceId = ProviderInstanceId.make("acp-test"); + const promptSettled = yield* Deferred.make(); const adapter = yield* makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, + deferFinalizeForBackgroundWork: true, + extractSubagentUpdate: (toolCall) => + toolCall.toolCallId === "tool-call-generic-1" + ? { + nativeTaskId: "task-generic-1", + prompt: "background subagent", + title: "background subagent", + model: null, + status: "running", + childSessionId: null, + result: null, + } + : undefined, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { - T3_ACP_EMIT_TOOL_CALLS: "1", - T3_ACP_HANG_AFTER_PERMISSION: "1", - }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - protocolEvents, - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(releaseNativeHook, undefined).pipe( - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseNativeHook)), - Effect.andThen(onOutgoingResponse(requestId)), - ), + environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, }), }, selfInvocation, - testHooks: { - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, }); - const threadId = ThreadId.make("thread-acp-pending-response-timeout"); + const threadId = ThreadId.make("thread-acp-interrupt-background-hold"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", + runtimeMode: "full-access", interactionMode: "default", cwd: process.cwd(), }); const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-pending-response-timeout", - ), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - yield* pollProtocolMethods(protocolEvents); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-interrupt-background"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, }); + const now = yield* DateTime.now; yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending permission request"); - } - const responseExit = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.exit); - if (Exit.isSuccess(responseExit)) { - assert.fail("missing native response acknowledgement must fail the pending response"); - } - assert.include(Cause.pretty(responseExit.cause), "Native response acknowledgement timed out"); - assert.isTrue(yield* Deferred.isDone(responseEnqueued)); - assert.isFalse(yield* Deferred.isDone(releaseNativeHook)); - assert.isBelow(responseLifecycle.indexOf("removed"), responseLifecycle.indexOf("failed")); - assert.includeMembers(responseLifecycle, [ - "registered", - "removed", - "failed", - "timer_exited", - "timer_started", - "watcher_exited", - "watcher_started", - ]); + yield* Deferred.await(promptSettled); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - assert.isTrue(yield* Deferred.isDone(releaseNativeHook)); - yield* Effect.sleep("50 millis"); - assert.include(responseLifecycle, "late_noop"); - yield* Scope.close(sessionScope, Exit.void); - assert.notInclude(yield* pollProtocolMethods(protocolEvents), "session/close"); + yield* runtime.interruptTurn({ providerThread, providerTurnId }); + + let terminalStatus: string | null = null; + while (terminalStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + terminalStatus = event.status; + } + } + assert.equal(terminalStatus, "interrupted"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("defers caller cancellation until a pending response acknowledgement is bounded", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseNativeHook = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-pending-response-cancel"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_TOOL_CALLS: "1", - T3_ACP_HANG_AFTER_PERMISSION: "1", - }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(releaseNativeHook, undefined).pipe( - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseNativeHook)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-pending-response-cancel"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-pending-response-cancel"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, + it.effect( + "carries a live subagent lineage across an interrupt so the next turn can complete it", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-test"); + let subagentPhase: "spawn" | "complete" = "spawn"; + const promptSettled = yield* Deferred.make(); + const adapter = yield* makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + deferFinalizeForBackgroundWork: true, + extractSubagentUpdate: (toolCall) => + toolCall.toolCallId !== "tool-call-generic-1" + ? undefined + : subagentPhase === "spawn" + ? { + nativeTaskId: "task-generic-1", + prompt: "background subagent", + title: "background subagent", + model: null, + status: "running", + childSessionId: null, + result: null, + } + : { + nativeTaskId: "task-generic-1", + prompt: "", + title: null, + model: null, + status: "completed", + childSessionId: null, + result: "SUB_DONE", + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-subagent-carryover"); + 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-subagent-carryover"), + modelSelection, runtimePolicy, - now: yield* DateTime.now, - }), - ); - const pending = Option.getOrThrow( + }); + const events = yield* Queue.unbounded(); yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, - ), - ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending permission request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ requestId: pending.runtimeRequest.id, decision: "accept" }) - .pipe(Effect.forkScoped); - yield* Deferred.await(responseEnqueued); - const cancellationFiber = yield* Fiber.interrupt(responseFiber).pipe(Effect.forkScoped); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Effect.sleep("100 millis"); - assert.isUndefined(cancellationFiber.pollUnsafe()); - assert.isUndefined(interruptFiber.pollUnsafe()); - assert.isFalse(yield* Deferred.isDone(releaseNativeHook)); + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); + yield* Deferred.await(promptSettled); - yield* Fiber.join(cancellationFiber); - yield* Fiber.join(interruptFiber); - assert.isTrue(yield* Deferred.isDone(releaseNativeHook)); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); + const firstProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - it.live("waits for immediate allow and deny permission responses before hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); + let subagentTurnItemId: string | null = null; + let firstTerminalStatus: string | null = null; + while (firstTerminalStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { + subagentTurnItemId = event.turnItem.id; + } + if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { + firstTerminalStatus = event.status; + } + } + assert.equal(firstTerminalStatus, "interrupted"); + assert.notEqual(subagentTurnItemId, null); - for (const [name, sandboxPolicy] of [ - ["allow", undefined], - ["deny", { type: "readOnly" } as const], - ] as const) { - yield* Effect.gen(function* () { - const responseEnqueued = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make(`acp-test-${name}`); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make(`thread-acp-immediate-permission-${name}`); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - approvalPolicy: "never", - cwd: process.cwd(), - ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ + subagentPhase = "complete"; + const secondNow = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, - providerSessionId: ProviderSessionId.make( - `provider-session-acp-immediate-permission-${name}`, - ), - modelSelection, - runtimePolicy, + providerThread, + instanceId, + runtimePolicy, + now: secondNow, + ordinal: 2, + }), + ); + const secondProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + }); + let carriedItemStatus: string | null = null; + let secondTerminalStatus: string | null = null; + while (secondTerminalStatus === null) { + const event = yield* Queue.take(events); + if ( + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.id === subagentTurnItemId + ) { + carriedItemStatus = event.turnItem.status; + } + if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { + secondTerminalStatus = event.status; + } + } + assert.equal(carriedItemStatus, "completed"); + assert.equal(secondTerminalStatus, "completed"); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect( + "projects a child terminal in the completed-root finalization window exactly once", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const baseClock = yield* Clock.Clock; + const finalizationClockRead = yield* Deferred.make(); + const releaseFinalizationClockRead = yield* Deferred.make(); + let blockNextClockRead = false; + const blockingClock: Clock.Clock = { + ...baseClock, + currentTimeMillis: Effect.suspend(() => { + if (!blockNextClockRead) return baseClock.currentTimeMillis; + blockNextClockRead = false; + return Deferred.succeed(finalizationClockRead, undefined).pipe( + Effect.andThen(Deferred.await(releaseFinalizationClockRead)), + Effect.andThen(baseClock.currentTimeMillis), + ); + }), + }; + yield* Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("acp-test"); + const firstChildSessionId = "mock-child-session-finalize-window-first"; + const secondChildSessionId = "mock-child-session-finalize-window-second"; + let firstSubagentStatus: "running" | "completed" = "running"; + let secondSubagentStatus: "waiting" | "completed" = "waiting"; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: + | Parameters[0] + | undefined; + const promptSettled = yield* Deferred.make(); + const adapter = yield* makeAcpAdapterV2({ + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), + }, + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + deferFinalizeForBackgroundWork: true, + enablePostSettleContinuation: true, + extractSubagentUpdate: (toolCall) => { + if (toolCall.toolCallId === "tool-call-generic-1") { + return { + nativeTaskId: "task-finalize-window-first", + prompt: "first background subagent", + title: "first background subagent", + model: null, + status: firstSubagentStatus, + childSessionId: firstChildSessionId, + result: firstSubagentStatus === "completed" ? "FIRST_DONE" : null, + suppressNormalTool: true, + }; + } + if (toolCall.toolCallId === "tool-call-generic-2") { + return { + nativeTaskId: "task-finalize-window-second", + prompt: "second background subagent", + title: "second background subagent", + model: null, + status: secondSubagentStatus, + childSessionId: secondChildSessionId, + result: secondSubagentStatus === "completed" ? "SECOND_DONE" : null, + suppressNormalTool: true, + } as AcpAdapterV2SubagentUpdate; + } + return undefined; + }, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), + }), + }, + selfInvocation, + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-acp-subagent-finalize-window"); + 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-subagent-finalize-window", + ), + modelSelection, + runtimePolicy, }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die( + "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", + ); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, }); - const turnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkDetach); - yield* Deferred.await(responseEnqueued); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }), - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); + yield* Deferred.await(promptSettled); + yield* TestClock.adjust("1 second"); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + + firstSubagentStatus = "completed"; + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-generic-1", + title: "first background subagent", + kind: "other", + status: "completed", + rawOutput: { content: "FIRST_DONE" }, + }, + }).pipe(Effect.provideService(Clock.Clock, blockingClock)); + for (let attempt = 0; attempt < 10; attempt += 1) { + yield* Effect.yieldNow; + } + + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-generic-2", + title: "second background subagent", + kind: "other", + status: "in_progress", + rawOutput: {}, + }, + }); + assert.isTrue(yield* hasPendingBackgroundWork); + + while (Option.isSome(yield* Queue.poll(events))) {} + + blockNextClockRead = true; + const adjustFiber = yield* TestClock.adjust("3 seconds").pipe(Effect.forkScoped); + yield* Deferred.await(finalizationClockRead); + secondSubagentStatus = "completed"; + yield* sessionUpdateHandler!({ + sessionId: secondChildSessionId, + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-generic-2", + title: "second background subagent", + kind: "other", + status: "completed", + rawOutput: { content: "SECOND_DONE" }, + }, + }); + yield* Deferred.succeed(releaseFinalizationClockRead, undefined); + yield* Fiber.join(adjustFiber); + yield* Effect.yieldNow; yield* Effect.yieldNow; - assert.isUndefined(interruptFiber.pollUnsafe()); - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(interruptFiber); - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach); - }).pipe(Effect.scoped); - } - }).pipe(Effect.provide(layerTest), Effect.scoped), + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + let completedSubagentUpdates = 0; + let rootTerminalStatus: string | null = null; + let polled = yield* Queue.poll(events); + while (Option.isSome(polled)) { + const event = polled.value; + if ( + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.nativeItemRef?.nativeId === "task-finalize-window-second" && + event.turnItem.status === "completed" + ) { + completedSubagentUpdates += 1; + } + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + rootTerminalStatus = event.status; + } + polled = yield* Queue.poll(events); + } + assert.equal(rootTerminalStatus, "completed"); + assert.equal(completedSubagentUpdates, 1); + assert.isFalse( + yield* hasPendingBackgroundWork, + "finalize-window terminal must clear the carryover pin", + ); + }).pipe(Effect.provideService(Clock.Clock, blockingClock)); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("waits for immediate URL elicitation responses before hard teardown", () => + it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -4870,554 +4796,240 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const responseEnqueued = yield* Deferred.make(); - const releaseResponseAcknowledgement = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-url-elicitation"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_URL_ELICITATION: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseResponseAcknowledgement)), - Effect.andThen(onOutgoingResponse(requestId)), - ), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-immediate-url-elicitation"); - 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-immediate-url-elicitation"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const turnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkDetach); - yield* Deferred.await(responseEnqueued); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }), - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(interruptFiber.pollUnsafe()); - - yield* Deferred.succeed(releaseResponseAcknowledgement, undefined); - yield* Fiber.join(interruptFiber); - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("bounds a missing immediate response acknowledgement before hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const responseEnqueued = yield* Deferred.make(); - const releaseNativeHook = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test-missing-response-ack"); + const protocolEvents = yield* Queue.bounded(256); + const continuationRequests: Array = + []; + const instanceId = ProviderInstanceId.make("acp-test"); + const childSessionId = "019f44a6-4820-7402-925d-bc862ee711dd"; + let subagentPhase: "spawn" | "complete" = "spawn"; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, + enablePostSettleContinuation: true, + normalizeToolCall: normalizeXAiAcpToolCallState, + extractSubagentUpdate: (toolCall) => + extractXAiAcpSubagentUpdate(toolCall) ?? + (toolCall.toolCallId !== "tool-call-generic-1" + ? undefined + : subagentPhase === "spawn" + ? { + nativeTaskId: "task-generic-1", + prompt: "background subagent", + title: "background subagent", + model: null, + status: "running", + childSessionId, + result: null, + } + : { + nativeTaskId: "task-generic-1", + prompt: "", + title: null, + model: null, + status: "completed", + childSessionId, + result: "SUB_DONE", + }), makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(releaseNativeHook, undefined).pipe( - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - wrapOutgoingResponse: (onOutgoingResponse) => (requestId) => - Deferred.succeed(responseEnqueued, undefined).pipe( - Effect.andThen(Deferred.await(releaseNativeHook)), - Effect.andThen(onOutgoingResponse(requestId)), - ), + environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, + protocolEvents, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), }), }, selfInvocation, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }), + }, }); - const threadId = ThreadId.make("thread-acp-missing-response-ack"); + const threadId = ThreadId.make("thread-acp-completed-root-eager-carryover"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", - approvalPolicy: "never", cwd: process.cwd(), }); const modelSelection = { instanceId, model: "default" } as const; const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-missing-response-ack"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-completed-root-eager-carryover", + ), modelSelection, runtimePolicy, }); - const turnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkDetach); - yield* Deferred.await(responseEnqueued); - const startedAt = yield* Clock.currentTimeMillis; - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }), - requestRuntimeRestart: true, - }); - assert.isAtLeast((yield* Clock.currentTimeMillis) - startedAt, 1_500); - yield* Fiber.interrupt(turnFiber).pipe(Effect.forkDetach); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("rejects an elicitation response when hard teardown wins admission", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die( + "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", + ); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, ); - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_ELICITATION: "1" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: (pid) => - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseTeardown)), - Effect.andThen( - Effect.sync(() => { - process.kill(pid, "SIGTERM"); - }), - ), - ), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-teardown-wins-elicitation"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-teardown-wins-elicitation"), - modelSelection, - runtimePolicy, - }); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, }); + const now = yield* DateTime.now; yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - const pending = Option.getOrThrow( - yield* runtime.events.pipe( - Stream.filter( - (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", - ), - Stream.runHead, + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "incoming" && + event.stage === "raw" && + typeof event.payload === "string" && + event.payload.includes('"stopReason"'), ), + Stream.runHead, ); - if ( - pending.type !== "runtime_request.updated" || - pending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected a pending elicitation request"); - } - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: pending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const responseFiber = yield* runtime - .respondToRuntimeRequest({ - requestId: pending.runtimeRequest.id, - answers: { approved: ["true"] }, - }) - .pipe(Effect.exit, Effect.forkScoped); yield* Effect.yieldNow; - assert.isUndefined(responseFiber.pollUnsafe()); + yield* Effect.yieldNow; + yield* TestClock.adjust("1 second"); - yield* Deferred.succeed(releaseTeardown, undefined); - yield* Fiber.join(interruptFiber); - const responseExit = yield* Fiber.join(responseFiber); - if (Exit.isSuccess(responseExit)) { - assert.fail("teardown winning admission must reject the elicitation response"); + const firstProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + let firstTerminalStatus: string | null = null; + while (firstTerminalStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { + firstTerminalStatus = event.status; + } } - assert.include(Cause.pretty(responseExit.cause), "No pending ACP runtime request"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); + assert.equal(firstTerminalStatus, "completed"); + assert.isTrue(yield* hasPendingBackgroundWork); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - it.effect("releases an ACP turn when cancellation times out", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("acp-test"); - const protocolEvents = yield* Queue.bounded(256); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_PROMPT_DELAY_MS: "5000" }, - protocolEvents, - }), + // Grok reports spawn ACKs as completed tools with running subagents and non-empty prompts. + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-call-generic-1", + title: "spawn_subagent", + kind: "other", + status: "completed", + rawInput: { + description: "background subagent", + prompt: "background subagent", + subagent_type: "general-purpose", + }, + rawOutput: { + type: "Text", + text: [ + "Subagent started in background.", + `subagent_id: ${childSessionId}`, + "type: general-purpose", + "description: background subagent", + "", + `Use get_command_or_subagent_output with task_ids=["${childSessionId}"] and timeout_ms to wait for results.`, + ].join("\n"), + }, }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-cancel-timeout"); - 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-cancel-timeout"), - modelSelection, - runtimePolicy, }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, + + subagentPhase = "complete"; + yield* sessionUpdateHandler!({ + sessionId: childSessionId, + update: { + sessionUpdate: "tool_call_update" as const, + toolCallId: "tool-call-generic-1", + title: "background subagent", + kind: "other" as const, + status: "completed" as const, + rawOutput: { content: "SUB_DONE" }, + }, }); - const now = yield* DateTime.now; - const firstTurn = makeTurnInput({ + yield* Effect.yieldNow; + yield* Effect.yieldNow; + + let eagerCompletedUpdates = 0; + let eagerRunningUpdates = 0; + let polled = yield* Queue.poll(events); + while (Option.isSome(polled)) { + const event = polled.value; + if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { + if (event.turnItem.status === "completed") eagerCompletedUpdates += 1; + if (event.turnItem.status === "running") eagerRunningUpdates += 1; + } + polled = yield* Queue.poll(events); + } + assert.equal(eagerCompletedUpdates, 1, "completed root must project before any attach"); + assert.equal(eagerRunningUpdates, 0); + assert.lengthOf(continuationRequests, 1); + assert.isTrue(yield* hasPendingBackgroundWork, "buffered spawn ACK still requires a drain"); + + const continuationNow = yield* DateTime.now; + const continuationInput = makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, - now, - }); - yield* runtime.startTurn(firstTurn); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + now: continuationNow, + ordinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + messageText: "Background task completed.", }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId }) - .pipe(Effect.flip, Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/cancel", - ), - Stream.runHead, - ); - yield* TestClock.adjust("10 seconds"); - const interruptError = yield* Fiber.join(interruptFiber); - assert.equal(interruptError._tag, "ProviderAdapterInterruptError"); - - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now, - ordinal: 2, - }), + yield* runtime.startTurn(continuationInput); + yield* Effect.yieldNow; + let replayedLineages = 0; + let replayedSubagentUpdates = 0; + let replayedTurnItems = 0; + polled = yield* Queue.poll(events); + while (Option.isSome(polled)) { + const event = polled.value; + if (event.type === "app_thread.created") { + replayedLineages += 1; + } + if (event.type === "subagent.updated" && event.subagent.runId === continuationInput.runId) { + replayedSubagentUpdates += 1; + } + if ( + event.type === "turn_item.updated" && + event.turnItem.runId === continuationInput.runId + ) { + replayedTurnItems += 1; + } + polled = yield* Queue.poll(events); + } + assert.equal(replayedLineages, 0, "buffered spawn ACK must not create a second lineage"); + assert.equal( + replayedSubagentUpdates, + 0, + "buffered spawn ACK must not re-open the terminal subagent", ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, + assert.equal( + replayedTurnItems, + 0, + "buffered spawn ACK must not create a continuation-owned turn item", ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("treats a second hard Stop as success when the turn is already gone", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: false, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-double-stop"); - 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-double-stop"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn(makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now })) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }); - const second = yield* Effect.exit( - runtime.interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }), - ); - assert.isTrue(Exit.isSuccess(second), "duplicate hard Stop must be idempotent"); - let terminal: string | null = null; - while (terminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminal = event.status; - } - } - assert.equal(terminal, "interrupted"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("finalizes a settled turn held open for background work when interrupted", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("acp-test"); - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId === "tool-call-generic-1" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : undefined, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-interrupt-background-hold"); - 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-interrupt-background"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId }); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); + assert.isFalse(yield* hasPendingBackgroundWork); }).pipe(Effect.provide(layerTest), Effect.scoped), ); it.effect( - "carries a live subagent lineage across an interrupt so the next turn can complete it", + "user attach flushes a deferred terminal but leaves wake traffic for its continuation", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -5427,8 +5039,13 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); + const continuationRequests: Array = + []; + const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH"; const instanceId = ProviderInstanceId.make("acp-test"); let subagentPhase: "spawn" | "complete" = "spawn"; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; const promptSettled = yield* Deferred.make(); const adapter = yield* makeAcpAdapterV2({ testHooks: { @@ -5440,6 +5057,7 @@ describe("AcpAdapterV2", () => { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, deferFinalizeForBackgroundWork: true, + enablePostSettleContinuation: true, extractSubagentUpdate: (toolCall) => toolCall.toolCallId !== "tool-call-generic-1" ? undefined @@ -5466,11 +5084,24 @@ describe("AcpAdapterV2", () => { childProcessSpawner, mockAgentPath, environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), }), }, selfInvocation, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }), + }, }); - const threadId = ThreadId.make("thread-acp-subagent-carryover"); + const threadId = ThreadId.make("thread-acp-carryover-root-session-continuation"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -5479,10 +5110,18 @@ describe("AcpAdapterV2", () => { const modelSelection = { instanceId, model: "default" } as const; const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-subagent-carryover"), + providerSessionId: ProviderSessionId.make( + "provider-session-acp-carryover-root-session-continuation", + ), modelSelection, runtimePolicy, }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die( + "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", + ); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; const events = yield* Queue.unbounded(); yield* runtime.events.pipe( Stream.runForEach((event) => Queue.offer(events, event)), @@ -5505,72 +5144,189 @@ describe("AcpAdapterV2", () => { }); yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - let subagentTurnItemId: string | null = null; let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { firstTerminalStatus = event.status; } } assert.equal(firstTerminalStatus, "interrupted"); - assert.notEqual(subagentTurnItemId, null); + assert.isTrue( + yield* hasPendingBackgroundWork, + "carryover live subagent must pin hasPendingBackgroundWork after root settle", + ); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); subagentPhase = "complete"; - const secondNow = yield* DateTime.now; + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-generic-1", + title: "background subagent", + kind: "other", + status: "completed", + rawOutput: { content: "SUB_DONE" }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: bufferedAssistantText }, + }, + }); + yield* Effect.yieldNow; + yield* Effect.yieldNow; + + let completedBeforeDrain = 0; + let polled = yield* Queue.poll(events); + while (Option.isSome(polled)) { + const event = polled.value; + if ( + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.status === "completed" + ) { + completedBeforeDrain += 1; + } + polled = yield* Queue.poll(events); + } + assert.equal( + completedBeforeDrain, + 0, + "interrupted root-session terminal must wait for an observable attach", + ); + assert.lengthOf( + continuationRequests, + 1, + "root-session post-settle subagent terminal must offer a continuation", + ); + assert.isTrue( + yield* hasPendingBackgroundWork, + "interrupted unprojected terminal must pin hasPendingBackgroundWork until attach", + ); + + const userTurnNow = yield* DateTime.now; yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, - now: secondNow, + now: userTurnNow, ordinal: 2, + messageText: "What finished while the prior turn was settling?", }), ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ + yield* TestClock.adjust("3 seconds"); + yield* Effect.yieldNow; + yield* Effect.yieldNow; + + const userProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), }); - let carriedItemStatus: string | null = null; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { + let userTurnTerminal: string | null = null; + let completedSubagentTurnItems = 0; + let bufferedTextSeenInUserTurn = false; + while (userTurnTerminal === null) { const event = yield* Queue.take(events); if ( event.type === "turn_item.updated" && event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId + event.turnItem.status === "completed" ) { - carriedItemStatus = event.turnItem.status; + completedSubagentTurnItems += 1; } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; + if ( + event.type === "message.updated" && + event.message.role === "assistant" && + event.message.text.includes(bufferedAssistantText) + ) { + bufferedTextSeenInUserTurn = true; + } + if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) { + userTurnTerminal = event.status; } } - assert.equal(carriedItemStatus, "completed"); - assert.equal(secondTerminalStatus, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "pins hasPendingBackgroundWork while carryover holds a live subagent after root settle", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + assert.equal(userTurnTerminal, "completed"); + assert.equal( + completedSubagentTurnItems, + 1, + "user attach must project the deferred terminal subagent turn item once", ); - const instanceId = ProviderInstanceId.make("acp-test"); - let subagentPhase: "spawn" | "complete" = "spawn"; - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { + assert.isFalse(bufferedTextSeenInUserTurn, "user attach must not drain wake traffic"); + assert.isTrue( + yield* hasPendingBackgroundWork, + "wake traffic must remain pinned for the already-dispatched continuation", + ); + + const continuationNow = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: continuationNow, + ordinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + messageText: "Background task completed.", + }), + ); + yield* TestClock.adjust("3 seconds"); + const continuationProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"), + }); + let continuationTerminal: string | null = null; + let bufferedTextSeenInContinuation = false; + while (continuationTerminal === null) { + const event = yield* Queue.take(events); + if ( + event.type === "message.updated" && + event.message.role === "assistant" && + event.message.text.includes(bufferedAssistantText) + ) { + bufferedTextSeenInContinuation = true; + } + if ( + event.type === "turn.terminal" && + event.providerTurnId === continuationProviderTurnId + ) { + continuationTerminal = event.status; + } + } + assert.equal(continuationTerminal, "completed"); + assert.isTrue( + bufferedTextSeenInContinuation, + "queued continuation must drain the wake content after the user run", + ); + assert.isFalse(yield* hasPendingBackgroundWork); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect( + "preserveRuntimeOnSettledInterrupt keeps the process alive and carries subagents through a settled steering interrupt", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-test"); + let subagentPhase: "spawn" | "complete" = "spawn"; + let cancelCalled = false; + let runtimeOrdinalSeen = 0; + const promptSettled = yield* Deferred.make(); + const adapter = yield* makeAcpAdapterV2({ + testHooks: { afterPromptSettledWithBackgroundWork: () => Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), }, @@ -5579,7 +5335,10 @@ describe("AcpAdapterV2", () => { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, + restartRuntimeAfterInterrupt: true, + restartRuntimeOnEveryInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, + preserveRuntimeOnSettledInterrupt: true, extractSubagentUpdate: (toolCall) => toolCall.toolCallId !== "tool-call-generic-1" ? undefined @@ -5605,13 +5364,19 @@ describe("AcpAdapterV2", () => { makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, + environment: (runtimeOrdinal) => { + runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); + return { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }; + }, + wrapCancel: (cancel) => + Effect.sync(() => { + cancelCalled = true; + }).pipe(Effect.andThen(cancel)), }), }, selfInvocation, - continuationRequests: { offer: () => Effect.void }, }); - const threadId = ThreadId.make("thread-acp-carryover-pending-pin"); + const threadId = ThreadId.make("thread-acp-settled-soft-steer"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -5620,16 +5385,10 @@ describe("AcpAdapterV2", () => { const modelSelection = { instanceId, model: "default" } as const; const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-carryover-pending-pin"), + providerSessionId: ProviderSessionId.make("provider-session-acp-settled-soft-steer"), modelSelection, runtimePolicy, }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; const events = yield* Queue.unbounded(); yield* runtime.events.pipe( Stream.runForEach((event) => Queue.offer(events, event)), @@ -5651,19 +5410,24 @@ describe("AcpAdapterV2", () => { nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); + assert.isFalse( + cancelCalled, + "settled soft steer must not send session/cancel (the real Grok CLI kills background subagents on cancel)", + ); + let subagentTurnItemId: string | null = null; let firstTerminalStatus: string | null = null; while (firstTerminalStatus === null) { const event = yield* Queue.take(events); + if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { + subagentTurnItemId = event.turnItem.id; + } if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { firstTerminalStatus = event.status; } } assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "carryover live subagent must pin hasPendingBackgroundWork after root settle", - ); + assert.notEqual(subagentTurnItemId, null); subagentPhase = "complete"; const secondNow = yield* DateTime.now; @@ -5681,22 +5445,32 @@ describe("AcpAdapterV2", () => { driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), }); + let carriedItemStatus: string | null = null; let secondTerminalStatus: string | null = null; while (secondTerminalStatus === null) { const event = yield* Queue.take(events); + if ( + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.id === subagentTurnItemId + ) { + carriedItemStatus = event.turnItem.status; + } if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { secondTerminalStatus = event.status; } } + assert.equal(carriedItemStatus, "completed"); assert.equal(secondTerminalStatus, "completed"); - assert.isFalse( - yield* hasPendingBackgroundWork, - "hasPendingBackgroundWork must clear after carryover subagent terminals", + assert.equal( + runtimeOrdinalSeen, + 1, + "settled soft steer must not respawn the ACP runtime process", ); }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.effect("handles a child terminal after carryover rehydrate", () => + it.live("preserveRuntimeOnSettledInterrupt does not soften a mid-prompt steering interrupt", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -5705,75 +5479,27 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const secondPromptWireReturned = yield* Deferred.make(); - const releaseSecondPromptCompletion = yield* Deferred.make(); + const protocolEvents = yield* Queue.bounded(256); const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "mock-child-session-active-carryover"; - let promptCount = 0; - let subagentPhase: "spawn" | "complete" = "spawn"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptSettled = yield* Deferred.make(); const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }, + restartRuntimeAfterInterrupt: true, + restartRuntimeOnEveryInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, + preserveRuntimeOnSettledInterrupt: true, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: (payload) => - Effect.gen(function* () { - const currentPrompt = ++promptCount; - const result = yield* runtime.prompt(payload); - if (currentPrompt === 2) { - yield* Deferred.succeed(secondPromptWireReturned, undefined); - yield* Deferred.await(releaseSecondPromptCompletion); - } - return result; - }), - }), + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + protocolEvents, }), }, selfInvocation, - continuationRequests: { offer: () => Effect.void }, }); - const threadId = ThreadId.make("thread-acp-active-carryover-pending-pin"); + const threadId = ThreadId.make("thread-acp-unsettled-steer-stays-hard"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -5783,145 +5509,180 @@ describe("AcpAdapterV2", () => { const runtime = yield* adapter.openSession({ threadId, providerSessionId: ProviderSessionId.make( - "provider-session-acp-active-carryover-pending-pin", + "provider-session-acp-unsettled-steer-stays-hard", ), modelSelection, runtimePolicy, }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy, }); const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ + const providerTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } + const interruptExit = yield* runtime + .interruptTurn({ providerThread, providerTurnId }) + .pipe(Effect.exit); + if (Exit.isSuccess(interruptExit)) { + assert.fail("mid-prompt steering interrupt must still take the hard teardown path"); } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue(yield* hasPendingBackgroundWork); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); - const secondNow = yield* DateTime.now; - const secondTurnFiber = yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ) - .pipe(Effect.forkScoped); - yield* Deferred.await(secondPromptWireReturned); - assert.isTrue( - yield* hasPendingBackgroundWork, - "rehydrated live subagent must pin from activeTurn", + it.live("direct Stop quarantine drops late background task mutations from the stopped run", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - while (Option.isSome(yield* Queue.poll(events))) {} - - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, + const protocolEvents = yield* Queue.bounded(256); + const instanceId = ProviderInstanceId.make("acp-test"); + const capturedMutation: { + current: + | ((mutation: { + readonly sessionId: string; + readonly taskId: string; + readonly status: "running" | "completed" | "failed"; + }) => Effect.Effect) + | null; + } = { current: null }; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + restartRuntimeAfterInterrupt: true, + terminateRuntimeProcessGroupOnInterrupt: true, + preserveRuntimeOnSettledInterrupt: true, + registerExtensions: (context) => + Effect.sync(() => { + capturedMutation.current = context.applyBackgroundTaskMutation; + }), + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + ownDetachedProcessGroup: true, + protocolEvents, + }), }, + selfInvocation, + continuationRequests: { offer: () => Effect.void }, }); - subagentPhase = "spawn"; - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "in_progress", - rawOutput: {}, - }, + const threadId = ThreadId.make("thread-acp-stop-quarantine-late-task"); + 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-stop-quarantine-late-task"), + modelSelection, + runtimePolicy, + }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die( + "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", + ); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); + const applyMutation = capturedMutation.current; + if (applyMutation === null) { + return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); + } + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-pre-stop", + status: "running", + }); + assert.isTrue( + yield* hasPendingBackgroundWork, + "a running background task mutation on the root session must track before Stop", + ); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-pre-stop", + status: "completed", }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; assert.isFalse( yield* hasPendingBackgroundWork, - "active-turn pin must clear after the child-session terminal is projected", + "a completed background task mutation must clear pending background work", ); - let completedSubagentUpdates = 0; - let resurrectedSubagentUpdates = 0; - let normalChildToolUpdates = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if (event.type === "turn_item.updated") { - if (event.turnItem.type === "subagent") { - if (event.turnItem.status === "completed") { - completedSubagentUpdates += 1; - } - if ( - event.turnItem.status === "running" && - event.turnItem.nativeItemRef?.nativeId === "task-generic-1" - ) { - resurrectedSubagentUpdates += 1; - } - } else if (event.turnItem.nativeItemRef?.nativeId === "tool-call-generic-1") { - normalChildToolUpdates += 1; - } + + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + yield* runtime.interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }); + let terminalStatus: string | null = null; + while (terminalStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + terminalStatus = event.status; } - polled = yield* Queue.poll(events); } - assert.equal(completedSubagentUpdates, 1); - assert.equal(resurrectedSubagentUpdates, 0); - assert.equal(normalChildToolUpdates, 0); + assert.equal(terminalStatus, "interrupted"); - yield* Deferred.succeed(releaseSecondPromptCompletion, undefined); - yield* Fiber.join(secondTurnFiber); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-late-after-stop", + status: "running", + }); + assert.isFalse( + yield* hasPendingBackgroundWork, + "direct Stop quarantine must drop residual background task mutations from the stopped run", + ); }).pipe(Effect.provide(layerTest), Effect.scoped), ); it.effect( - "projects a child terminal in the completed-root finalization window exactly once", + "does not pin hasPendingBackgroundWork when a late TaskOutput re-reports an in-turn-handled task", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -5931,284 +5692,46 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const baseClock = yield* Clock.Clock; - const finalizationClockRead = yield* Deferred.make(); - const releaseFinalizationClockRead = yield* Deferred.make(); - let blockNextClockRead = false; - const blockingClock: Clock.Clock = { - ...baseClock, - currentTimeMillis: Effect.suspend(() => { - if (!blockNextClockRead) return baseClock.currentTimeMillis; - blockNextClockRead = false; - return Deferred.succeed(finalizationClockRead, undefined).pipe( - Effect.andThen(Deferred.await(releaseFinalizationClockRead)), - Effect.andThen(baseClock.currentTimeMillis), - ); - }), - }; - yield* Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("acp-test"); - const firstChildSessionId = "mock-child-session-finalize-window-first"; - const secondChildSessionId = "mock-child-session-finalize-window-second"; - let firstSubagentStatus: "running" | "completed" = "running"; - let secondSubagentStatus: "waiting" | "completed" = "waiting"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: - | Parameters[0] - | undefined; - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => { - if (toolCall.toolCallId === "tool-call-generic-1") { - return { - nativeTaskId: "task-finalize-window-first", - prompt: "first background subagent", - title: "first background subagent", - model: null, - status: firstSubagentStatus, - childSessionId: firstChildSessionId, - result: firstSubagentStatus === "completed" ? "FIRST_DONE" : null, - suppressNormalTool: true, - }; - } - if (toolCall.toolCallId === "tool-call-generic-2") { - return { - nativeTaskId: "task-finalize-window-second", - prompt: "second background subagent", - title: "second background subagent", - model: null, - status: secondSubagentStatus, - childSessionId: secondChildSessionId, - result: secondSubagentStatus === "completed" ? "SECOND_DONE" : null, - suppressNormalTool: true, - } as AcpAdapterV2SubagentUpdate; - } - return undefined; + const protocolEvents = yield* Queue.bounded(256); + const continuationRequests: Array = + []; + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + extractBackgroundTaskId: (toolCall) => + toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, + extractBackgroundTaskCompletion: (toolCall) => + toolCall.toolCallId === "tool-call-fetch-1" + ? [ + { + taskId: "task-monitor-1", + status: toolCall.status === "completed" ? "completed" : "running", + appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", + }, + ] + : [], + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { + T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1", }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-subagent-finalize-window"); - 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-subagent-finalize-window", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - yield* TestClock.adjust("1 second"); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - firstSubagentStatus = "completed"; - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "first background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "FIRST_DONE" }, - }, - }).pipe(Effect.provideService(Clock.Clock, blockingClock)); - for (let attempt = 0; attempt < 10; attempt += 1) { - yield* Effect.yieldNow; - } - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-2", - title: "second background subagent", - kind: "other", - status: "in_progress", - rawOutput: {}, - }, - }); - assert.isTrue(yield* hasPendingBackgroundWork); - - while (Option.isSome(yield* Queue.poll(events))) {} - - blockNextClockRead = true; - const adjustFiber = yield* TestClock.adjust("3 seconds").pipe(Effect.forkScoped); - yield* Deferred.await(finalizationClockRead); - secondSubagentStatus = "completed"; - yield* sessionUpdateHandler!({ - sessionId: secondChildSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-2", - title: "second background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SECOND_DONE" }, - }, - }); - yield* Deferred.succeed(releaseFinalizationClockRead, undefined); - yield* Fiber.join(adjustFiber); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let completedSubagentUpdates = 0; - let rootTerminalStatus: string | null = null; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.nativeItemRef?.nativeId === "task-finalize-window-second" && - event.turnItem.status === "completed" - ) { - completedSubagentUpdates += 1; - } - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - rootTerminalStatus = event.status; - } - polled = yield* Queue.poll(events); - } - assert.equal(rootTerminalStatus, "completed"); - assert.equal(completedSubagentUpdates, 1); - assert.isFalse( - yield* hasPendingBackgroundWork, - "finalize-window terminal must clear the carryover pin", - ); - }).pipe(Effect.provideService(Clock.Clock, blockingClock)); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "defers an interrupted pending-spawn carryover terminal until the next observable attach", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const promptSettled = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "mock-child-session-post-settle"; - let subagentPhase: "spawn" | "complete" = "spawn"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "pending", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); + protocolEvents, + }), + }, + selfInvocation, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); }), }, }); - const threadId = ThreadId.make("thread-acp-carryover-child-session-post-settle"); + const threadId = ThreadId.make("thread-acp-already-handled-wake-pin"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -6218,7 +5741,7 @@ describe("AcpAdapterV2", () => { const runtime = yield* adapter.openSession({ threadId, providerSessionId: ProviderSessionId.make( - "provider-session-acp-carryover-child-session-post-settle", + "provider-session-acp-already-handled-wake-pin", ), modelSelection, runtimePolicy, @@ -6243,248 +5766,47 @@ describe("AcpAdapterV2", () => { yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ + const providerTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { + let terminalStatus: string | null = null; + while (terminalStatus === null) { const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + terminalStatus = event.status; } } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "carryover live subagent must pin hasPendingBackgroundWork after root settle", - ); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + assert.equal(terminalStatus, "completed"); - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "incoming" && + event.stage === "raw" && + typeof event.payload === "string" && + event.payload.includes("MONITOR_LISTING_TOKEN_LATE"), + ), + Stream.runHead, + ); yield* Effect.yieldNow; yield* Effect.yieldNow; - let completedBeforeAttach = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedBeforeAttach += 1; - } - polled = yield* Queue.poll(events); - } - assert.equal( - completedBeforeAttach, - 0, - "closed interrupted subscription must not be treated as projected", - ); - assert.isTrue( - yield* hasPendingBackgroundWork, - "terminal carryover must stay pinned until an attach can project it", - ); + yield* Effect.yieldNow; + assert.lengthOf( continuationRequests, 0, - "child-session completion must not open a root continuation", + "already-handled late TaskOutput must not open a continuation run", ); - - const attachNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: attachNow, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Attach deferred completion.", - }), + assert.isFalse( + yield* hasPendingBackgroundWork, + "wake buffer must not stay non-empty and pin idle release after an already-handled re-report", ); - const attachProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let attachTerminal: string | null = null; - let completedAfterAttach = 0; - while (attachTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedAfterAttach += 1; - } - if (event.type === "turn.terminal" && event.providerTurnId === attachProviderTurnId) { - attachTerminal = event.status; - } - } - assert.equal(attachTerminal, "completed"); - assert.equal(completedAfterAttach, 1); - assert.isFalse(yield* hasPendingBackgroundWork); }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.effect("finishes a settled root's carryover subagent from its structured end", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "019f44a6-4820-7402-925d-bc862ee711dd"; - let finishSubagent: AcpAdapterV2ExtensionContext["finishSubagent"] | undefined; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - }, - registerExtensions: (context) => - Effect.sync(() => { - finishSubagent = context.finishSubagent; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - }), - }, - selfInvocation, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-carryover-subagent-finished"); - 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-carryover-finished"), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die("post-settle continuation must expose hasPendingBackgroundWork"); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let rootStatus: string | null = null; - while (rootStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - rootStatus = event.status; - } - } - assert.equal(rootStatus, "completed"); - assert.isTrue(yield* hasPendingBackgroundWork); - assert.isDefined(finishSubagent); - const subagentStatuses = Effect.gen(function* () { - yield* Effect.yieldNow; - yield* Effect.yieldNow; - const statuses: Array<[string, string | null]> = []; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - statuses.push([event.turnItem.status, event.turnItem.result]); - } - polled = yield* Queue.poll(events); - } - return statuses; - }); - yield* subagentStatuses; - - yield* finishSubagent!({ - sessionId: "some-other-session", - childSessionId, - status: "completed", - result: "WRONG_PARENT", - }); - assert.deepEqual(yield* subagentStatuses, [], "non-root notices must be dropped"); - assert.isTrue(yield* hasPendingBackgroundWork); - - yield* finishSubagent!({ - sessionId: "mock-session-1", - childSessionId, - status: "failed", - result: "tool crashed", - }); - assert.deepEqual( - yield* subagentStatuses, - [["failed", "tool crashed"]], - "the completed root still owns the run, so the carryover end projects at once", - ); - assert.isFalse( - yield* hasPendingBackgroundWork, - "a finished carryover subagent stops pinning", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => + it.effect("keeps a buffered continuation current when a user turn starts before dispatch", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -6493,55 +5815,42 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); const continuationRequests: Array = []; - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "019f44a6-4820-7402-925d-bc862ee711dd"; - let subagentPhase: "spawn" | "complete" = "spawn"; + const userPromptStarted = yield* Deferred.make(); + const releaseUserPrompt = yield* Deferred.make(); + const bufferedAssistantText = "BUFFERED_WAKE_QUEUED_AFTER_USER"; + let promptOrdinal = 0; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; + const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, + deferFinalizeForBackgroundWork: true, enablePostSettleContinuation: true, - normalizeToolCall: normalizeXAiAcpToolCallState, - extractSubagentUpdate: (toolCall) => - extractXAiAcpSubagentUpdate(toolCall) ?? - (toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }), makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => Effect.sync(() => { sessionUpdateHandler = handler; }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: (payload) => + Effect.gen(function* () { + promptOrdinal += 1; + const currentPromptOrdinal = promptOrdinal; + const result = yield* runtime.prompt(payload); + if (currentPromptOrdinal === 2) { + yield* Deferred.succeed(userPromptStarted, undefined); + yield* Deferred.await(releaseUserPrompt); + } + return result; + }), }), }), }, @@ -6553,7 +5862,7 @@ describe("AcpAdapterV2", () => { }), }, }); - const threadId = ThreadId.make("thread-acp-completed-root-eager-carryover"); + const threadId = ThreadId.make("thread-acp-buffered-continuation-user-race"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -6563,7 +5872,7 @@ describe("AcpAdapterV2", () => { const runtime = yield* adapter.openSession({ threadId, providerSessionId: ProviderSessionId.make( - "provider-session-acp-completed-root-eager-carryover", + "provider-session-acp-buffered-continuation-user-race", ), modelSelection, runtimePolicy, @@ -6584,24 +5893,15 @@ describe("AcpAdapterV2", () => { modelSelection, runtimePolicy, }); - const now = yield* DateTime.now; yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* TestClock.adjust("1 second"); - const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), @@ -6614,120 +5914,102 @@ describe("AcpAdapterV2", () => { } } assert.equal(firstTerminalStatus, "completed"); - assert.isTrue(yield* hasPendingBackgroundWork); assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - // A production Grok spawn ACK has raw tool status completed but extracts - // as a running subagent with its original non-empty prompt. yield* sessionUpdateHandler!({ sessionId: "mock-session-1", update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-generic-1", - title: "spawn_subagent", - kind: "other", - status: "completed", - rawInput: { - description: "background subagent", - prompt: "background subagent", - subagent_type: "general-purpose", - }, - rawOutput: { - type: "Text", - text: [ - "Subagent started in background.", - `subagent_id: ${childSessionId}`, - "type: general-purpose", - "description: background subagent", - "", - `Use get_command_or_subagent_output with task_ids=["${childSessionId}"] and timeout_ms to wait for results.`, - ].join("\n"), - }, - }, - }); - - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update" as const, - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other" as const, - status: "completed" as const, - rawOutput: { content: "SUB_DONE" }, + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: bufferedAssistantText }, }, }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + assert.lengthOf(continuationRequests, 1); + const continuationRequest = continuationRequests[0]!; + assert.isDefined(continuationRequest.dispatchIfCurrent); - let eagerCompletedUpdates = 0; - let eagerRunningUpdates = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - if (event.turnItem.status === "completed") eagerCompletedUpdates += 1; - if (event.turnItem.status === "running") eagerRunningUpdates += 1; + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageText: "User turn won the continuation dispatch race.", + }), + ); + yield* Deferred.await(userPromptStarted); + let continuationDispatched = false; + const dispatchOutcome = yield* continuationRequest.dispatchIfCurrent!( + Effect.sync(() => { + continuationDispatched = true; + }), + ); + assert.isTrue( + Option.isSome(dispatchOutcome), + "queue_after_active dispatch must remain current while the user run is active", + ); + assert.isTrue(continuationDispatched); + yield* Deferred.succeed(releaseUserPrompt, undefined); + + const userProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + }); + let userTerminalStatus: string | null = null; + while (userTerminalStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) { + userTerminalStatus = event.status; } - polled = yield* Queue.poll(events); } - assert.equal(eagerCompletedUpdates, 1, "completed root must project before any attach"); - assert.equal(eagerRunningUpdates, 0); - assert.lengthOf(continuationRequests, 1); - assert.isTrue(yield* hasPendingBackgroundWork, "buffered spawn ACK still requires a drain"); + assert.equal(userTerminalStatus, "completed"); + assert.isTrue( + yield* hasPendingBackgroundWork, + "the queued continuation must retain ownership of its buffered wake traffic", + ); - const continuationNow = yield* DateTime.now; - const continuationInput = makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: continuationNow, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Background task completed.", + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + messageText: "Background task completed.", + }), + ); + yield* TestClock.adjust("3 seconds"); + const continuationProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"), }); - yield* runtime.startTurn(continuationInput); - yield* Effect.yieldNow; - let replayedLineages = 0; - let replayedSubagentUpdates = 0; - let replayedTurnItems = 0; - polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if (event.type === "app_thread.created") { - replayedLineages += 1; - } - if (event.type === "subagent.updated" && event.subagent.runId === continuationInput.runId) { - replayedSubagentUpdates += 1; - } + let continuationTerminalStatus: string | null = null; + let bufferedTextSeen = false; + while (continuationTerminalStatus === null) { + const event = yield* Queue.take(events); if ( - event.type === "turn_item.updated" && - event.turnItem.runId === continuationInput.runId + event.type === "message.updated" && + event.message.role === "assistant" && + event.message.text.includes(bufferedAssistantText) ) { - replayedTurnItems += 1; + bufferedTextSeen = true; + } + if (event.type === "turn.terminal" && event.providerTurnId === continuationProviderTurnId) { + continuationTerminalStatus = event.status; } - polled = yield* Queue.poll(events); } - assert.equal(replayedLineages, 0, "buffered spawn ACK must not create a second lineage"); - assert.equal( - replayedSubagentUpdates, - 0, - "buffered spawn ACK must not re-open the terminal subagent", - ); - assert.equal( - replayedTurnItems, - 0, - "buffered spawn ACK must not create a continuation-owned turn item", - ); + 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), ); it.effect( - "user attach flushes a deferred terminal but leaves wake traffic for its continuation", + "staggered pre-settle completion keeps midTurn marks until last background task ends post-finalize", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -6737,57 +6019,58 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); + const protocolEvents = yield* Queue.bounded(256); const continuationRequests: Array = []; - const bufferedAssistantText = "BUFFERED_WAKE_AFTER_USER_ATTACH"; - const instanceId = ProviderInstanceId.make("acp-test"); - let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; - const promptSettled = yield* Deferred.make(); + const promptGate = yield* Deferred.make(); + const capturedMutation: { + current: + | ((mutation: { + readonly sessionId: string; + readonly taskId: string; + readonly status: "running" | "completed" | "failed"; + }) => Effect.Effect) + | null; + } = { current: null }; + const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, + extractBackgroundTaskId: (toolCall) => { + if (toolCall.toolCallId === "tool-call-monitor-a") return "task-monitor-a"; + if (toolCall.toolCallId === "tool-call-monitor-b") return "task-monitor-b"; + return undefined; + }, + extractBackgroundToolMutation: (text) => { + if (text.includes('Monitor "task-monitor-a" ended')) { + return [{ taskId: "task-monitor-a", status: "completed", appendOutput: "" }]; + } + if (text.includes('Monitor "task-monitor-b" ended')) { + return [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }]; + } + return []; + }, + registerExtensions: (context) => + Effect.sync(() => { + capturedMutation.current = context.applyBackgroundTaskMutation; + }), makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + protocolEvents, wrapRuntime: (runtime) => ({ ...runtime, handleSessionUpdate: (handler) => Effect.sync(() => { sessionUpdateHandler = handler; }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => Deferred.await(promptGate), }), }), }, @@ -6799,7 +6082,7 @@ describe("AcpAdapterV2", () => { }), }, }); - const threadId = ThreadId.make("thread-acp-carryover-root-session-continuation"); + const threadId = ThreadId.make("thread-acp-staggered-midturn-keep-until-last"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -6809,17 +6092,11 @@ describe("AcpAdapterV2", () => { const runtime = yield* adapter.openSession({ threadId, providerSessionId: ProviderSessionId.make( - "provider-session-acp-carryover-root-session-continuation", + "provider-session-acp-staggered-midturn-keep-until-last", ), modelSelection, runtimePolicy, }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; const events = yield* Queue.unbounded(); yield* runtime.events.pipe( Stream.runForEach((event) => Queue.offer(events, event)), @@ -6831,184 +6108,115 @@ describe("AcpAdapterV2", () => { runtimePolicy, }); const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "carryover live subagent must pin hasPendingBackgroundWork after root settle", - ); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: bufferedAssistantText }, - }, - }); + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); yield* Effect.yieldNow; yield* Effect.yieldNow; + assert.isDefined(sessionUpdateHandler); + const applyMutation = capturedMutation.current; + if (applyMutation === null) { + return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); + } - let completedBeforeDrain = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedBeforeDrain += 1; - } - polled = yield* Queue.poll(events); + for (const [toolCallId, title] of [ + ["tool-call-monitor-a", "Monitor: staggered A"], + ["tool-call-monitor-b", "Monitor: staggered B"], + ] as const) { + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId, + title, + kind: "execute", + status: "pending", + rawInput: {}, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId, + status: "in_progress", + }, + }); } - assert.equal( - completedBeforeDrain, - 0, - "interrupted root-session terminal must wait for an observable attach", - ); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-monitor-a", + status: "running", + }); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-monitor-b", + status: "running", + }); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-monitor-a", + status: "completed", + }); assert.lengthOf( continuationRequests, - 1, - "root-session post-settle subagent terminal must offer a continuation", - ); - assert.isTrue( - yield* hasPendingBackgroundWork, - "interrupted unprojected terminal must pin hasPendingBackgroundWork until attach", - ); - - const userTurnNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: userTurnNow, - ordinal: 2, - messageText: "What finished while the prior turn was settling?", - }), + 0, + "pre-settle unhandled completion must not offer while the turn is active", ); - yield* TestClock.adjust("3 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - const userProviderTurnId = idAllocator.derive.providerTurn({ + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); + const providerTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - let userTurnTerminal: string | null = null; - let completedSubagentTurnItems = 0; - let bufferedTextSeenInUserTurn = false; - while (userTurnTerminal === null) { + let terminalStatus: string | null = null; + while (terminalStatus === null) { const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes(bufferedAssistantText) - ) { - bufferedTextSeenInUserTurn = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) { - userTurnTerminal = event.status; + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + terminalStatus = event.status; } } - assert.equal(userTurnTerminal, "completed"); - assert.equal( - completedSubagentTurnItems, - 1, - "user attach must project the deferred terminal subagent turn item once", - ); - assert.isFalse(bufferedTextSeenInUserTurn, "user attach must not drain wake traffic"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "wake traffic must remain pinned for the already-dispatched continuation", + assert.equal(terminalStatus, "completed"); + assert.lengthOf( + continuationRequests, + 0, + "finalize must not offer while B is still running", ); - const continuationNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: continuationNow, - ordinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Background task completed.", + const bEndNotice = { + sessionId: "mock-session-1", + update: { + sessionUpdate: "user_message_chunk" as const, + content: { + type: "text" as const, + text: 'Monitor "task-monitor-b" ended: [monitor ended: exit 0]', + }, + }, + }; + assert.isFalse( + acpPostSettleWakeEvidence(bEndNotice, { + extractBackgroundToolMutation: (text) => + text.includes('Monitor "task-monitor-b" ended') + ? [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }] + : [], }), + "mutation-only end-notice must not count as post-settle wake evidence", ); - yield* TestClock.adjust("3 seconds"); - const continuationProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"), - }); - let continuationTerminal: string | null = null; - let bufferedTextSeenInContinuation = false; - while (continuationTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes(bufferedAssistantText) - ) { - bufferedTextSeenInContinuation = true; - } - if ( - event.type === "turn.terminal" && - event.providerTurnId === continuationProviderTurnId - ) { - continuationTerminal = event.status; - } - } - assert.equal(continuationTerminal, "completed"); - assert.isTrue( - bufferedTextSeenInContinuation, - "queued continuation must drain the wake content after the user run", + yield* sessionUpdateHandler!(bEndNotice); + yield* Effect.yieldNow; + yield* Effect.yieldNow; + assert.lengthOf( + continuationRequests, + 1, + "exactly one continuation when the last running task ends post-finalize with kept midTurn marks", ); - assert.isFalse(yield* hasPendingBackgroundWork); }).pipe(Effect.provide(layerTest), Effect.scoped), ); it.effect( - "projects a carryover terminal when an in-turn-handled tool is re-reported post-settle", + "two-turn in-turn monitors never open a wake run or retain turn-1 injected-turn ack chatter", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -7018,89 +6226,106 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); + const protocolEvents = yield* Queue.bounded(256); const continuationRequests: Array = []; - const promptWireReturned = yield* Deferred.make(); - const releasePromptCompletion = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - let subagentPhase: "spawn" | "complete" = "spawn"; type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; let sessionUpdateHandler: Parameters[0] | undefined; - const promptSettled = yield* Deferred.make(); + const promptGates: Array> = []; + const capturedMutation: { + current: + | ((mutation: { + readonly sessionId: string; + readonly taskId: string; + readonly status: "running" | "completed" | "failed"; + }) => Effect.Effect) + | null; + } = { current: null }; + const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-generic-1" ? "task-generic-1" : undefined, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: (payload) => - Effect.gen(function* () { - const result = yield* runtime.prompt(payload); - yield* Deferred.succeed(promptWireReturned, undefined); - yield* Deferred.await(releasePromptCompletion); - return result; - }), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-carryover-already-handled-re-report"); - 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-carryover-already-handled-re-report", + extractBackgroundTaskId: (toolCall) => { + if (toolCall.toolCallId === "tool-call-monitor-1") return "task-monitor-1"; + if (toolCall.toolCallId === "tool-call-monitor-2") return "task-monitor-2"; + return undefined; + }, + extractBackgroundToolMutation: (text) => { + if (text.includes('Monitor "task-monitor-1" ended')) { + return [{ taskId: "task-monitor-1", status: "completed", appendOutput: "" }]; + } + if (text.includes('Monitor "task-monitor-2" ended')) { + return [{ taskId: "task-monitor-2", status: "completed", appendOutput: "" }]; + } + return []; + }, + extractBackgroundTaskCompletion: (toolCall) => { + if (toolCall.toolCallId === "tool-call-fetch-1") { + return [ + { + taskId: "task-monitor-1", + status: toolCall.status === "completed" ? "completed" : "running", + appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", + }, + ]; + } + if (toolCall.toolCallId === "tool-call-fetch-2") { + return [ + { + taskId: "task-monitor-2", + status: toolCall.status === "completed" ? "completed" : "running", + appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN_2" : "", + }, + ]; + } + return []; + }, + registerExtensions: (context) => + Effect.sync(() => { + capturedMutation.current = context.applyBackgroundTaskMutation; + }), + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + protocolEvents, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + const gate = yield* Deferred.make(); + promptGates.push(gate); + return yield* Deferred.await(gate); + }), + }), + }), + }, + selfInvocation, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }), + }, + }); + const threadId = ThreadId.make("thread-acp-multiturn-in-turn-monitor-no-wake"); + 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-multiturn-in-turn-monitor-no-wake", ), modelSelection, runtimePolicy, @@ -7122,6040 +6347,299 @@ describe("AcpAdapterV2", () => { runtimePolicy, }); const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptWireReturned); + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); + while (promptGates.length < 1) { + yield* Effect.yieldNow; + } assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + const applyMutation = capturedMutation.current; + if (applyMutation === null) { + return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); + } + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-call-monitor-1", + title: "Monitor: first turn", + kind: "execute", + status: "pending", + rawInput: {}, + }, + }); yield* sessionUpdateHandler!({ sessionId: "mock-session-1", update: { sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", + toolCallId: "tool-call-monitor-1", + status: "in_progress", + }, + }); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-monitor-1", + status: "running", + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-call-fetch-1", + title: "get_command_or_subagent_output", kind: "other", + status: "pending", + rawInput: { task_id: "task-monitor-1" }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-fetch-1", status: "completed", - rawOutput: { content: "IN_TURN_RESULT" }, + rawOutput: { output: "MONITOR_LISTING_TOKEN" }, }, }); - yield* Deferred.succeed(releasePromptCompletion, undefined); - yield* Deferred.await(promptSettled); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Monitor listing ready in-turn." }, + }, + }); + yield* applyMutation({ + sessionId: "mock-session-1", + taskId: "task-monitor-1", + status: "completed", + }); + assert.lengthOf(continuationRequests, 0); + yield* Deferred.succeed(promptGates[0]!, { stopReason: "end_turn" }); const firstProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { + let firstTerminal: string | null = null; + while (firstTerminal === null) { const event = yield* Queue.take(events); if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; + firstTerminal = event.status; } } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "live carryover must remain pending after the superseded root settles", - ); + assert.equal(firstTerminal, "completed"); - subagentPhase = "complete"; yield* sessionUpdateHandler!({ sessionId: "mock-session-1", update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, + sessionUpdate: "user_message_chunk", + content: { + type: "text", + text: 'Monitor "task-monitor-1" ended', + }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_thought_chunk", + content: { + type: "text", + text: "That monitor event is the same run I already summarized.", + }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { + type: "text", + text: "That monitor event is the same run I already summarized above.", + }, }, }); yield* Effect.yieldNow; yield* Effect.yieldNow; - - let completedSubagentTurnItems = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - polled = yield* Queue.poll(events); - } - assert.equal( - completedSubagentTurnItems, - 0, - "an interrupted root's non-buffered re-report must wait for an observable attach", - ); assert.lengthOf( continuationRequests, 0, - "an in-turn-handled re-report must not offer a continuation", + "turn-1 injected-turn acks must not open a continuation", ); - assert.isTrue( + assert.isFalse( yield* hasPendingBackgroundWork, - "the unprojected terminal carryover must remain pinned", + "turn-1 injected-turn ack chatter must not remain as wake buffer evidence", ); - const attachNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: attachNow, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Attach deferred completion.", - }), - ); - const attachProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let attachTerminal: string | null = null; - while (attachTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - if (event.type === "turn.terminal" && event.providerTurnId === attachProviderTurnId) { - attachTerminal = event.status; - } + yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + }), + ) + .pipe(Effect.forkScoped); + while (promptGates.length < 2) { + yield* Effect.yieldNow; + } + if (sessionUpdateHandler === undefined || capturedMutation.current === null) { + return yield* Effect.die("extensions and session handler must be wired for turn 2"); } - assert.equal(completedSubagentTurnItems, 1); - assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - it.effect("projects an interrupted root-session end notice at the next attach", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const promptSettled = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "019f5470-bf92-7a90-afb3-5a6cea5b34a3"; - let subagentPhase: "spawn" | "complete" = "spawn"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractSubagentEndNotice: (text) => { - const parsed = extractXAiAcpSubagentEndNotice(text); - if (parsed !== undefined) return parsed; - if (!text.includes(childSessionId)) return undefined; - if (/completed successfully/i.test(text)) { - return { childSessionId, status: "completed" as const }; - } - return undefined; - }, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-carryover-root-end-notice"); - 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-carryover-root-end-notice"), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "carryover live subagent must pin hasPendingBackgroundWork after root settle", - ); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "user_message_chunk", - content: { - type: "text", - text: `Background subagent "${childSessionId}" (general-purpose: "background subagent") completed successfully.`, - }, - }, - }); - // Do not use Effect.timeout under TestClock; poll after yielding so a - // missed projection fails the assertion instead of hanging the suite. - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - let completedSubagentTurnItems = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - polled = yield* Queue.poll(events); - } - assert.equal( - completedSubagentTurnItems, - 0, - "root-session end notice must remain memory-only after interrupted settle", - ); - assert.lengthOf( - continuationRequests, - 0, - "root-session end notice must not open a continuation", - ); - assert.isTrue( - yield* hasPendingBackgroundWork, - "hasPendingBackgroundWork must retain the unprojected end notice", - ); - - const attachNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: attachNow, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Attach deferred completion.", - }), - ); - const attachProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let attachTerminal: string | null = null; - while (attachTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - if (event.type === "turn.terminal" && event.providerTurnId === attachProviderTurnId) { - attachTerminal = event.status; - } - } - assert.equal(completedSubagentTurnItems, 1); - assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "preserves wakeBuffer when a child-session completes while a continuation is pending", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const continuationRequests: Array = - []; - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "mock-child-session-pending-continuation"; - const bufferedAssistantText = "POST_SETTLE_BUFFERED_ASSISTANT_TEXT"; - let subagentPhase: "spawn" | "complete" = "spawn"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), + yield* sessionUpdateHandler({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call", + toolCallId: "tool-call-monitor-2", + title: "Monitor: second turn", + kind: "execute", + status: "pending", + rawInput: {}, }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), + }); + yield* sessionUpdateHandler({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-monitor-2", + status: "in_progress", }, }); - const threadId = ThreadId.make("thread-acp-carryover-child-pending-continuation"); - 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-carryover-child-pending-continuation", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "carryover live subagent must pin hasPendingBackgroundWork after root settle", - ); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ + yield* capturedMutation.current({ sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, + taskId: "task-monitor-2", + status: "running", }); - yield* sessionUpdateHandler!({ + yield* sessionUpdateHandler({ sessionId: "mock-session-1", update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: bufferedAssistantText }, - }, - }); - assert.lengthOf( - continuationRequests, - 1, - "root-session terminal must offer a continuation before child completion", - ); - assert.isTrue( - yield* hasPendingBackgroundWork, - "pending continuation must keep hasPendingBackgroundWork pinned", - ); - - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", + sessionUpdate: "tool_call", + toolCallId: "tool-call-fetch-2", + title: "get_command_or_subagent_output", kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - let completedBeforeDrain = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedBeforeDrain += 1; - } - polled = yield* Queue.poll(events); - } - assert.equal( - completedBeforeDrain, - 0, - "interrupted child-session terminal must wait for the continuation attach", - ); - assert.isTrue( - yield* hasPendingBackgroundWork, - "child-session must not clear the pin while wakeBuffer still has delivery", - ); - - const continuationNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: continuationNow, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Background task completed.", - }), - ); - yield* TestClock.adjust("3 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - const continuationProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let continuationTerminal: string | null = null; - let completedSubagentTurnItems = 0; - let bufferedTextSeen = false; - while (continuationTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes(bufferedAssistantText) - ) { - bufferedTextSeen = true; - } - if ( - event.type === "turn.terminal" && - event.providerTurnId === continuationProviderTurnId - ) { - continuationTerminal = event.status; - } - } - assert.equal(continuationTerminal, "completed"); - assert.isTrue( - bufferedTextSeen, - "continuation drain must project buffered post-settle assistant text (buffer not wiped)", - ); - assert.equal( - completedSubagentTurnItems, - 1, - "continuation drain must project the terminal subagent turn item once", - ); - assert.isFalse( - yield* hasPendingBackgroundWork, - "pin must clear after the continuation drains, not when the child session completed", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "projects once when root-session then child-session complete the same carryover subagent", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const continuationRequests: Array = - []; - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "mock-child-session-root-then-child"; - let subagentPhase: "spawn" | "complete" = "spawn"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-carryover-root-then-child"); - 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-carryover-root-then-child", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "carryover live subagent must pin hasPendingBackgroundWork after root settle", - ); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); - assert.lengthOf( - continuationRequests, - 1, - "root-session terminal must still offer a continuation", - ); - - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - let completedBeforeDrain = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedBeforeDrain += 1; - } - polled = yield* Queue.poll(events); - } - assert.equal( - completedBeforeDrain, - 0, - "interrupted root-then-child completion must defer to the continuation attach", - ); - - const continuationNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: continuationNow, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Background task completed.", - }), - ); - yield* TestClock.adjust("3 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - const continuationProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let continuationTerminal: string | null = null; - let completedSubagentTurnItems = 0; - while (continuationTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedSubagentTurnItems += 1; - } - if ( - event.type === "turn.terminal" && - event.providerTurnId === continuationProviderTurnId - ) { - continuationTerminal = event.status; - } - } - assert.equal(continuationTerminal, "completed"); - assert.equal( - completedSubagentTurnItems, - 1, - "root-then-child completion must project the terminal subagent turn item exactly once", - ); - assert.isFalse( - yield* hasPendingBackgroundWork, - "hasPendingBackgroundWork must end false after the continuation drains", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "preserveRuntimeOnSettledInterrupt keeps the process alive and carries subagents through a settled steering interrupt", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const instanceId = ProviderInstanceId.make("acp-test"); - let subagentPhase: "spawn" | "complete" = "spawn"; - let cancelCalled = false; - let runtimeOrdinalSeen = 0; - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - restartRuntimeAfterInterrupt: true, - restartRuntimeOnEveryInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }; - }, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-settled-soft-steer"); - 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-settled-soft-steer"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - assert.isFalse( - cancelCalled, - "settled soft steer must not send session/cancel (the real Grok CLI kills background subagents on cancel)", - ); - - let subagentTurnItemId: string | null = null; - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.notEqual(subagentTurnItemId, null); - - subagentPhase = "complete"; - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let carriedItemStatus: string | null = null; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - carriedItemStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(carriedItemStatus, "completed"); - assert.equal(secondTerminalStatus, "completed"); - assert.equal( - runtimeOrdinalSeen, - 1, - "settled soft steer must not respawn the ACP runtime process", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("preserveRuntimeOnSettledInterrupt does not soften a mid-prompt steering interrupt", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - restartRuntimeOnEveryInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-unsettled-steer-stays-hard"); - 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-unsettled-steer-stays-hard", - ), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - const interruptExit = yield* runtime - .interruptTurn({ providerThread, providerTurnId }) - .pipe(Effect.exit); - if (Exit.isSuccess(interruptExit)) { - 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), - ); - - it.live( - "soft mid-prompt interrupt cancels in place, reuses the runtime, and tracks cancel-backgrounded work", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const instanceId = ProviderInstanceId.make("acp-test"); - let cancelCalled = false; - let runtimeOrdinalSeen = 0; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - registerExtensions: ({ runtime: extensionRuntime, applyBackgroundTaskMutation }) => - registerXAiBackgroundTaskTracking(extensionRuntime, applyBackgroundTaskMutation), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG_FIRST_PROMPT: "1", - T3_ACP_EMIT_TASK_BACKGROUNDED_AFTER_CANCEL: "1", - }; - }, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-soft-mid-prompt-steer"); - 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-soft-mid-prompt-steer"), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("tool-call-running-1"), - ), - Stream.runHead, - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - assert.isTrue( - cancelCalled, - "soft mid-prompt interrupt must send session/cancel to detach the running work", - ); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - let backgroundTracked = false; - for (let attempt = 0; attempt < 80 && !backgroundTracked; attempt += 1) { - backgroundTracked = yield* hasPendingBackgroundWork; - if (!backgroundTracked) { - yield* Effect.sleep("25 millis"); - } - } - assert.isTrue( - backgroundTracked, - "cancel-backgrounded task must be tracked as running background work", - ); - - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(secondTerminalStatus, "completed"); - assert.equal( - runtimeOrdinalSeen, - 1, - "soft mid-prompt interrupt must not respawn the ACP runtime process", - ); - - let backgroundPending = true; - for (let attempt = 0; attempt < 50 && backgroundPending; attempt += 1) { - backgroundPending = yield* hasPendingBackgroundWork; - if (backgroundPending) { - yield* Effect.sleep("100 millis"); - } - } - assert.isFalse( - backgroundPending, - "tracked background task must clear after _x.ai/task_completed", - ); - assert.lengthOf( - continuationRequests, - 0, - "a cancel-backgrounded task completion must not wake a synthetic continuation run", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("direct Stop quarantine drops late background task mutations from the stopped run", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - ownDetachedProcessGroup: true, - protocolEvents, - }), - }, - selfInvocation, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-stop-quarantine-late-task"); - 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-stop-quarantine-late-task"), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-pre-stop", - status: "running", - }); - assert.isTrue( - yield* hasPendingBackgroundWork, - "a running background task mutation on the root session must track before Stop", - ); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-pre-stop", - status: "completed", - }); - assert.isFalse( - yield* hasPendingBackgroundWork, - "a completed background task mutation must clear pending background work", - ); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); - - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-late-after-stop", - status: "running", - }); - assert.isFalse( - yield* hasPendingBackgroundWork, - "direct Stop quarantine must drop residual background task mutations from the stopped run", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("production Grok interrupt flags still hard-kill and respawn on user Stop", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - let runtimeOrdinalSeen = 0; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - registerExtensions: ({ runtime: extensionRuntime, applyBackgroundTaskMutation }) => - registerXAiBackgroundTaskTracking(extensionRuntime, applyBackgroundTaskMutation), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; - }, - ownDetachedProcessGroup: true, - protocolEvents, - }), - }, - selfInvocation, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-production-stop-hard-kill"); - 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-production-stop-hard-kill"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); - - // Effect 4 Queue.takeAll waits for at least one element when empty. After - // the session/prompt stream drain the protocol queue is often empty, so - // takeAll would hang forever. - yield* Queue.clear(protocolEvents); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "user Stop must respawn the runtime and reload the session on the next turn", - ); - assert.equal( - runtimeOrdinalSeen, - 2, - "user Stop with production Grok flags must replace the ACP runtime process", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - // it.live: ownDetachedProcessGroup teardown uses wall-clock sleeps; under - // it.effect the interrupt timeout on context.completed still needs real time - // after the soft steer clears the turn. - it.live( - "Stop after settled soft steer contains the orphan runtime and respawns without subagent carryover", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - let subagentPhase: "spawn" | "complete" = "spawn"; - let cancelCalled = false; - let runtimeOrdinalSeen = 0; - const childSessionId = "mock-child-session-1"; - const authoritativeSubagentText = "authoritative subagent carryover text"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptSettled = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - testHooks: { - afterPromptSettledWithBackgroundWork: () => - Deferred.succeed(promptSettled, undefined).pipe(Effect.asVoid), - }, - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = Math.max(runtimeOrdinalSeen, runtimeOrdinal); - return { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }; - }, - ownDetachedProcessGroup: true, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-stop-after-soft-steer-orphan"); - 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-stop-after-soft-steer-orphan", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "agent_message", - messageId: "child-message-1", - content: [{ type: "text", text: authoritativeSubagentText }], - }, - }); - let subagentTurnItemId: string | null = null; - let authoritativeTextSeen = false; - for (let attempt = 0; attempt < 64; attempt += 1) { - const maybeEvent = yield* Queue.take(events).pipe(Effect.timeoutOption("50 millis")); - if (Option.isNone(maybeEvent)) break; - const event = maybeEvent.value; - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if ( - event.type === "message.updated" && - event.message.text.includes(authoritativeSubagentText) - ) { - authoritativeTextSeen = true; - break; - } - } - assert.isTrue( - authoritativeTextSeen, - "pre-steer child session upsert must project as subagent assistant text", - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }); - assert.isFalse( - cancelCalled, - "settled soft steer must not send session/cancel before the later Stop", - ); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentTurnItemId = event.turnItem.id; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.notEqual(subagentTurnItemId, null); - assert.equal( - runtimeOrdinalSeen, - 1, - "soft steer must leave the original ACP runtime process alive", - ); - - const stopExit = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.exit); - if (Exit.isFailure(stopExit)) { - assert.fail( - `cleared-turn Stop must contain the orphan runtime, not fail: ${Cause.pretty(stopExit.cause)}`, - ); - } - - let subagentStopStatus: string | null = null; - let subagentStopResult: string | null | undefined; - let subagentStopProviderThreadId: string | null | undefined; - let subagentUpdatedResult: string | null | undefined; - for (let attempt = 0; attempt < 64; attempt += 1) { - const maybeEvent = yield* Queue.take(events).pipe(Effect.timeoutOption("50 millis")); - if (Option.isNone(maybeEvent)) break; - const event = maybeEvent.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - subagentStopStatus = event.turnItem.status; - subagentStopResult = event.turnItem.result; - subagentStopProviderThreadId = event.turnItem.providerThreadId; - if (subagentStopStatus === "interrupted") break; - } - if ( - event.type === "subagent.updated" && - event.subagent.status === "interrupted" && - event.subagent.result === authoritativeSubagentText - ) { - subagentUpdatedResult = event.subagent.result; - } - } - assert.equal( - subagentStopStatus, - "interrupted", - "orphan Stop must emit interrupted terminal for turn-1 carryover subagent", - ); - assert.equal( - subagentStopResult, - authoritativeSubagentText, - "orphan Stop must merge authoritative assistant text into the interrupted result", - ); - assert.equal( - subagentStopProviderThreadId, - providerThread.id, - "orphan Stop parent-level events must use the spawn-time parent provider thread id", - ); - assert.equal( - subagentUpdatedResult, - authoritativeSubagentText, - "orphan Stop subagent.updated must also carry the authoritative result", - ); - - yield* Queue.clear(protocolEvents); - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && - (rawProtocolMethod(event) === "session/resume" || - rawProtocolMethod(event) === "session/new"), - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "orphan containment must force a runtime respawn before the next turn", - ); - assert.equal( - runtimeOrdinalSeen, - 2, - "Stop after soft steer must replace the orphan ACP runtime process", - ); - - subagentPhase = "complete"; - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let carriedItemStatus: string | null = null; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.id === subagentTurnItemId - ) { - carriedItemStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.isNull( - carriedItemStatus, - "Stop quarantine must drop turn-1 subagent carryover on the respawned runtime", - ); - assert.equal(secondTerminalStatus, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("Direct Stop projects an interrupt-deferred terminal exactly once", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const childSessionId = "mock-child-session-direct-stop-deferred-terminal"; - let subagentPhase: "spawn" | "complete" = "spawn"; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - ownDetachedProcessGroup: true, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - continuationRequests: { offer: () => Effect.void }, - }); - const threadId = ThreadId.make("thread-acp-direct-stop-deferred-terminal"); - 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-direct-stop-deferred-terminal", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId }); - let rootTerminal: string | null = null; - while (rootTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - rootTerminal = event.status; - } - } - assert.equal(rootTerminal, "interrupted"); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - subagentPhase = "complete"; - yield* sessionUpdateHandler!({ - sessionId: childSessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-generic-1", - title: "background subagent", - kind: "other", - status: "completed", - rawOutput: { content: "SUB_DONE" }, - }, - }); - yield* Effect.yieldNow; - let completedBeforeStop = 0; - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - const event = polled.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedBeforeStop += 1; - } - polled = yield* Queue.poll(events); - } - assert.equal(completedBeforeStop, 0); - assert.isTrue( - yield* hasPendingBackgroundWork, - "interrupt-deferred terminal must pin until hard-stop projection", - ); - - const stopExit = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.exit); - if (Exit.isFailure(stopExit)) { - assert.fail(`Direct Stop must contain the orphan runtime: ${Cause.pretty(stopExit.cause)}`); - } - - let completedAfterStop = 0; - for (let attempt = 0; attempt < 64; attempt += 1) { - const maybeEvent = yield* Queue.take(events).pipe(Effect.timeoutOption("50 millis")); - if (Option.isNone(maybeEvent)) break; - const event = maybeEvent.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - completedAfterStop += 1; - } - } - assert.equal(completedAfterStop, 1); - assert.isFalse(yield* hasPendingBackgroundWork); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "settled soft interrupt skips cancel when prompt wire is settled before completion callback", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - let subagentPhase: "spawn" | "complete" = "spawn"; - let cancelCalled = false; - const promptPhases: Array = []; - const promptWireReturned = yield* Deferred.make(); - const releasePromptCompletion = yield* Deferred.make(); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - preserveRuntimeOnSettledInterrupt: true, - extractSubagentUpdate: (toolCall) => - toolCall.toolCallId !== "tool-call-generic-1" - ? undefined - : subagentPhase === "spawn" - ? { - nativeTaskId: "task-generic-1", - prompt: "background subagent", - title: "background subagent", - model: null, - status: "running", - childSessionId: null, - result: null, - } - : { - nativeTaskId: "task-generic-1", - prompt: "", - title: null, - model: null, - status: "completed", - childSessionId: null, - result: "SUB_DONE", - }, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1" }, - protocolEvents, - wrapCancel: (cancel) => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(cancel)), - wrapRuntime: (runtime) => ({ - ...runtime, - prompt: (payload) => - Effect.gen(function* () { - promptPhases.push("prompt-start"); - const result = yield* runtime.prompt(payload); - promptPhases.push("wire-returned"); - yield* Deferred.succeed(promptWireReturned, undefined); - yield* Deferred.await(releasePromptCompletion); - promptPhases.push("completion-released"); - return result; - }), - }), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-settled-soft-admission-race"); - 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-settled-soft-admission-race", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptWireReturned); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"stopReason"'), - ), - Stream.runHead, - ); - assert.deepEqual(promptPhases, ["prompt-start", "wire-returned"]); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId: firstProviderTurnId }) - .pipe(Effect.forkScoped); - yield* Deferred.succeed(releasePromptCompletion, undefined); - for (let attempt = 0; attempt < 20; attempt += 1) { - if (promptPhases.includes("completion-released")) break; - yield* Effect.yieldNow; - } - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); - - assert.includeMembers(promptPhases, [ - "prompt-start", - "wire-returned", - "completion-released", - ]); - assert.isFalse( - cancelCalled, - "settled soft steer must skip session/cancel once the prompt wire has settled", - ); - - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.equal(subagentPhase, "spawn"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "does not pin hasPendingBackgroundWork when a late TaskOutput re-reports an in-turn-handled task", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-fetch-1" - ? [ - { - taskId: "task-monitor-1", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", - }, - ] - : [], - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE: "1", - }, - protocolEvents, - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-already-handled-wake-pin"); - 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-already-handled-wake-pin", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("MONITOR_LISTING_TOKEN_LATE"), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - assert.lengthOf( - continuationRequests, - 0, - "already-handled late TaskOutput must not open a continuation run", - ); - assert.isFalse( - 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), - ); - - it.effect( - "keeps a dispatched continuation offer sticky until a turn starts or the worker drops it", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-sticky-continuation-dispatch"); - 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-sticky-continuation-dispatch", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - const lateTool = (toolCallId: string) => - sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId, - title: "Late tool result", - kind: "other", - status: "completed", - rawOutput: { output: toolCallId }, - }, - }); - yield* lateTool("first-late-result"); - assert.lengthOf(continuationRequests, 1); - const first = continuationRequests[0]!; - assert.isDefined(first.dispatchIfCurrent); - assert.isTrue(Option.isSome(yield* first.dispatchIfCurrent!(Effect.void))); - - yield* lateTool("second-frame-before-dispatched-turn-starts"); - assert.lengthOf( - continuationRequests, - 1, - "late frames must not enqueue duplicate continuations during dispatch-to-start", - ); - - assert.isDefined(first.clearIfCurrent); - yield* first.clearIfCurrent!(); - yield* lateTool("new-result-after-worker-drop"); - assert.lengthOf(continuationRequests, 2); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("keeps a buffered continuation current when a user turn starts before dispatch", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const continuationRequests: Array = - []; - const userPromptStarted = yield* Deferred.make(); - const releaseUserPrompt = yield* Deferred.make(); - const bufferedAssistantText = "BUFFERED_WAKE_QUEUED_AFTER_USER"; - let promptOrdinal = 0; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: (payload) => - Effect.gen(function* () { - promptOrdinal += 1; - const currentPromptOrdinal = promptOrdinal; - const result = yield* runtime.prompt(payload); - if (currentPromptOrdinal === 2) { - yield* Deferred.succeed(userPromptStarted, undefined); - yield* Deferred.await(releaseUserPrompt); - } - return result; - }), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-buffered-continuation-user-race"); - 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-buffered-continuation-user-race", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ); - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "completed"); - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: bufferedAssistantText }, - }, - }); - assert.lengthOf(continuationRequests, 1); - const continuationRequest = continuationRequests[0]!; - assert.isDefined(continuationRequest.dispatchIfCurrent); - - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 2, - messageText: "User turn won the continuation dispatch race.", - }), - ); - yield* Deferred.await(userPromptStarted); - let continuationDispatched = false; - const dispatchOutcome = yield* continuationRequest.dispatchIfCurrent!( - Effect.sync(() => { - continuationDispatched = true; - }), - ); - assert.isTrue( - Option.isSome(dispatchOutcome), - "queue_after_active dispatch must remain current while the user run is active", - ); - assert.isTrue(continuationDispatched); - yield* Deferred.succeed(releaseUserPrompt, undefined); - - const userProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let userTerminalStatus: string | null = null; - while (userTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === userProviderTurnId) { - userTerminalStatus = event.status; - } - } - assert.equal(userTerminalStatus, "completed"); - assert.isTrue( - yield* hasPendingBackgroundWork, - "the queued continuation must retain ownership of its buffered wake traffic", - ); - - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Background task completed.", - }), - ); - yield* TestClock.adjust("3 seconds"); - const continuationProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"), - }); - let continuationTerminalStatus: string | null = null; - let bufferedTextSeen = false; - while (continuationTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes(bufferedAssistantText) - ) { - bufferedTextSeen = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === continuationProviderTurnId) { - continuationTerminalStatus = event.status; - } - } - 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), - ); - - it.effect( - "holds a settled turn until the injected monitor report streams instead of finalizing into it", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const triggerDir = yield* fileSystem.makeTempDirectoryScoped(); - const triggerPath = path.join(triggerDir, "report-trigger"); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, - extractBackgroundToolMutation: (text) => - text.includes('Monitor "task-monitor-1" ended') - ? [{ taskId: "task-monitor-1", status: "completed", appendOutput: "" }] - : [], - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-fetch-1" - ? [ - { - taskId: "task-monitor-1", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", - }, - ] - : [], - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW: "1", - T3_ACP_INJECTED_REPORT_TRIGGER_PATH: triggerPath, - }, - protocolEvents, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-injected-report-hold"); - 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-injected-report"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - - let reportSeen = false; - const trackReport = (event: ProviderAdapter.ProviderAdapterV2Event): void => { - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text.includes("MONITOR_REPORT_TOKEN") - ) { - reportSeen = true; - } - }; - let hydrated = false; - while (!hydrated) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "completed" && - (event.turnItem.output ?? "").includes("MONITOR_LISTING_TOKEN") - ) { - hydrated = true; - } - } - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - yield* TestClock.adjust("3 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - let drained = yield* Queue.poll(events); - while (Option.isSome(drained)) { - trackReport(drained.value); - assert.notEqual( - drained.value.type, - "turn.terminal", - "deferred finalize must hold while the injected-turn report is owed", - ); - drained = yield* Queue.poll(events); - } - - yield* fileSystem.writeFileString(triggerPath, "go"); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("MONITOR_REPORT_TOKEN"), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* TestClock.adjust("3 seconds"); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - trackReport(event); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.isTrue( - reportSeen, - "the injected-turn report must project before the turn finalizes", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "settle-without-report held turn with mid-hold ext completion does not open a wake after the injected report", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const triggerDir = yield* fileSystem.makeTempDirectoryScoped(); - const triggerPath = path.join(triggerDir, "report-trigger"); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, - extractBackgroundToolMutation: (text) => - text.includes('Monitor "task-monitor-1" ended') - ? [{ taskId: "task-monitor-1", status: "completed", appendOutput: "" }] - : [], - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-fetch-1" - ? [ - { - taskId: "task-monitor-1", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", - }, - ] - : [], - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { - T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW: "1", - T3_ACP_INJECTED_REPORT_TRIGGER_PATH: triggerPath, - }, - protocolEvents, - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-settle-hold-ext-complete-no-wake"); - 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-settle-hold-ext-complete-no-wake", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - - let reportSeen = false; - const trackReport = (event: ProviderAdapter.ProviderAdapterV2Event): void => { - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text.includes("MONITOR_REPORT_TOKEN") - ) { - reportSeen = true; - } - }; - let hydrated = false; - while (!hydrated) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "completed" && - (event.turnItem.output ?? "").includes("MONITOR_LISTING_TOKEN") - ) { - hydrated = true; - } - } - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-1", - status: "completed", - }); - assert.lengthOf( - continuationRequests, - 0, - "ext completion during the settled-held window must not offer mid-hold", - ); - - yield* TestClock.adjust("3 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - let drained = yield* Queue.poll(events); - while (Option.isSome(drained)) { - trackReport(drained.value); - assert.notEqual( - drained.value.type, - "turn.terminal", - "deferred finalize must hold while the injected-turn report is owed", - ); - drained = yield* Queue.poll(events); - } - - yield* fileSystem.writeFileString(triggerPath, "go"); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes("MONITOR_REPORT_TOKEN"), - ), - Stream.runHead, - ); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* TestClock.adjust("3 seconds"); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - trackReport(event); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.isTrue( - reportSeen, - "the injected-turn report must project before the turn finalizes", - ); - assert.lengthOf( - continuationRequests, - 0, - "settle-without-report with mid-hold ext completion must not open a wake after the report streams", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "pre-settle ext completion arm is cleared when the report precedes its end notice", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGate = yield* Deferred.make(); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-1" ? "task-monitor-1" : undefined, - extractBackgroundToolMutation: (text) => - text.includes('Monitor "task-monitor-1" ended') - ? [{ taskId: "task-monitor-1", status: "completed", appendOutput: "" }] - : [], - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-pre-settle-arm-cleared-by-report"); - 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-pre-settle-arm-cleared-by-report", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isDefined(sessionUpdateHandler); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-1", - title: "Monitor: pre-settle complete", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-1", - status: "in_progress", - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-1", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-1", - status: "completed", - }); - assert.lengthOf( - continuationRequests, - 0, - "pre-settle unhandled completion must not offer while the turn is active", - ); - - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.lengthOf( - continuationRequests, - 0, - "settle must hold for deferred background work; midTurn alone must not offer mid-hold", - ); - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "user_message_chunk", - content: { - type: "text", - text: 'Monitor "task-monitor-1" ended: [monitor ended: exit 0]', - }, - }, - }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - let reportSeen = false; - const trackReport = (event: ProviderAdapter.ProviderAdapterV2Event): void => { - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "assistant_message" && - event.turnItem.text.includes("MONITOR_REPORT_TOKEN") - ) { - reportSeen = true; - } - if ( - event.type === "message.updated" && - event.message.text.includes("MONITOR_REPORT_TOKEN") - ) { - reportSeen = true; - } - }; - let drained = yield* Queue.poll(events); - while (Option.isSome(drained)) { - trackReport(drained.value); - assert.notEqual( - drained.value.type, - "turn.terminal", - "turn must stay open while hydration hold / quiet window remain", - ); - drained = yield* Queue.poll(events); - } - assert.isTrue(reportSeen, "injected report must project into the held turn"); - - yield* TestClock.adjust("60 seconds"); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* TestClock.adjust("3 seconds"); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - trackReport(event); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.lengthOf( - continuationRequests, - 0, - "pre-settle arm must be cleared when the injected report streams; no duplicate wake", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "staggered pre-settle completion keeps midTurn marks until last background task ends post-finalize", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGate = yield* Deferred.make(); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => { - if (toolCall.toolCallId === "tool-call-monitor-a") return "task-monitor-a"; - if (toolCall.toolCallId === "tool-call-monitor-b") return "task-monitor-b"; - return undefined; - }, - extractBackgroundToolMutation: (text) => { - if (text.includes('Monitor "task-monitor-a" ended')) { - return [{ taskId: "task-monitor-a", status: "completed", appendOutput: "" }]; - } - if (text.includes('Monitor "task-monitor-b" ended')) { - return [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }]; - } - return []; - }, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-staggered-midturn-keep-until-last"); - 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-staggered-midturn-keep-until-last", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isDefined(sessionUpdateHandler); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - for (const [toolCallId, title] of [ - ["tool-call-monitor-a", "Monitor: staggered A"], - ["tool-call-monitor-b", "Monitor: staggered B"], - ] as const) { - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId, - title, - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId, - status: "in_progress", - }, - }); - } - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-a", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-b", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-a", - status: "completed", - }); - assert.lengthOf( - continuationRequests, - 0, - "pre-settle unhandled completion must not offer while the turn is active", - ); - - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.lengthOf( - continuationRequests, - 0, - "finalize must not offer while B is still running", - ); - - const bEndNotice = { - sessionId: "mock-session-1", - update: { - sessionUpdate: "user_message_chunk" as const, - content: { - type: "text" as const, - text: 'Monitor "task-monitor-b" ended: [monitor ended: exit 0]', - }, - }, - }; - assert.isFalse( - acpPostSettleWakeEvidence(bEndNotice, { - extractBackgroundToolMutation: (text) => - text.includes('Monitor "task-monitor-b" ended') - ? [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }] - : [], - }), - "mutation-only end-notice must not count as post-settle wake evidence", - ); - yield* sessionUpdateHandler!(bEndNotice); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.lengthOf( - continuationRequests, - 1, - "exactly one continuation when the last running task ends post-finalize with kept midTurn marks", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "staggered pre-settle completion does not keep midTurn marks when the turn is interrupted", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGate = yield* Deferred.make(); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => { - if (toolCall.toolCallId === "tool-call-monitor-a") return "task-monitor-a"; - if (toolCall.toolCallId === "tool-call-monitor-b") return "task-monitor-b"; - return undefined; - }, - extractBackgroundToolMutation: (text) => { - if (text.includes('Monitor "task-monitor-a" ended')) { - return [{ taskId: "task-monitor-a", status: "completed", appendOutput: "" }]; - } - if (text.includes('Monitor "task-monitor-b" ended')) { - return [{ taskId: "task-monitor-b", status: "completed", appendOutput: "" }]; - } - return []; - }, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-staggered-midturn-clear-on-interrupt"); - 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-staggered-midturn-clear-on-interrupt", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isDefined(sessionUpdateHandler); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - for (const [toolCallId, title] of [ - ["tool-call-monitor-a", "Monitor: staggered interrupt A"], - ["tool-call-monitor-b", "Monitor: staggered interrupt B"], - ] as const) { - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId, - title, - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId, - status: "in_progress", - }, - }); - } - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-a", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-b", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-a", - status: "completed", - }); - assert.lengthOf(continuationRequests, 0); - - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.lengthOf( - continuationRequests, - 0, - "settle must hold for deferred background tools; no mid-hold offer", - ); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ providerThread, providerTurnId }); - - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "interrupted"); - assert.lengthOf( - continuationRequests, - 0, - "interrupted finalize must not offer a continuation", - ); - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "user_message_chunk", - content: { - type: "text", - text: 'Monitor "task-monitor-b" ended: [monitor ended: exit 0]', - }, - }, - }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.lengthOf( - continuationRequests, - 0, - "interrupted turns must clear midTurn marks; B ending post-finalize must not offer", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "two-turn in-turn monitors never open a wake run or retain turn-1 injected-turn ack chatter", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGates: Array> = []; - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => { - if (toolCall.toolCallId === "tool-call-monitor-1") return "task-monitor-1"; - if (toolCall.toolCallId === "tool-call-monitor-2") return "task-monitor-2"; - return undefined; - }, - extractBackgroundToolMutation: (text) => { - if (text.includes('Monitor "task-monitor-1" ended')) { - return [{ taskId: "task-monitor-1", status: "completed", appendOutput: "" }]; - } - if (text.includes('Monitor "task-monitor-2" ended')) { - return [{ taskId: "task-monitor-2", status: "completed", appendOutput: "" }]; - } - return []; - }, - extractBackgroundTaskCompletion: (toolCall) => { - if (toolCall.toolCallId === "tool-call-fetch-1") { - return [ - { - taskId: "task-monitor-1", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN" : "", - }, - ]; - } - if (toolCall.toolCallId === "tool-call-fetch-2") { - return [ - { - taskId: "task-monitor-2", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "MONITOR_LISTING_TOKEN_2" : "", - }, - ]; - } - return []; - }, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => - Effect.gen(function* () { - const gate = yield* Deferred.make(); - promptGates.push(gate); - return yield* Deferred.await(gate); - }), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-multiturn-in-turn-monitor-no-wake"); - 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-multiturn-in-turn-monitor-no-wake", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - while (promptGates.length < 1) { - yield* Effect.yieldNow; - } - assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-1", - title: "Monitor: first turn", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-1", - status: "in_progress", - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-1", - status: "running", - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-fetch-1", - title: "get_command_or_subagent_output", - kind: "other", - status: "pending", - rawInput: { task_id: "task-monitor-1" }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-fetch-1", - status: "completed", - rawOutput: { output: "MONITOR_LISTING_TOKEN" }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Monitor listing ready in-turn." }, - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-1", - status: "completed", - }); - assert.lengthOf(continuationRequests, 0); - - yield* Deferred.succeed(promptGates[0]!, { stopReason: "end_turn" }); - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let firstTerminal: string | null = null; - while (firstTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminal = event.status; - } - } - assert.equal(firstTerminal, "completed"); - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "user_message_chunk", - content: { - type: "text", - text: 'Monitor "task-monitor-1" ended', - }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_thought_chunk", - content: { - type: "text", - text: "That monitor event is the same run I already summarized.", - }, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { - type: "text", - text: "That monitor event is the same run I already summarized above.", - }, - }, - }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.lengthOf( - continuationRequests, - 0, - "turn-1 injected-turn acks must not open a continuation", - ); - assert.isFalse( - yield* hasPendingBackgroundWork, - "turn-1 injected-turn ack chatter must not remain as wake buffer evidence", - ); - - yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 2, - }), - ) - .pipe(Effect.forkScoped); - while (promptGates.length < 2) { - yield* Effect.yieldNow; - } - if (sessionUpdateHandler === undefined || capturedMutation.current === null) { - return yield* Effect.die("extensions and session handler must be wired for turn 2"); - } - - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-2", - title: "Monitor: second turn", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-2", - status: "in_progress", - }, - }); - yield* capturedMutation.current({ - sessionId: "mock-session-1", - taskId: "task-monitor-2", - status: "running", - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-fetch-2", - title: "get_command_or_subagent_output", - kind: "other", - status: "pending", - rawInput: { task_id: "task-monitor-2" }, - }, - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-fetch-2", - status: "completed", - rawOutput: { output: "MONITOR_LISTING_TOKEN_2" }, - }, - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Second monitor listing ready in-turn." }, - }, - }); - yield* capturedMutation.current({ - sessionId: "mock-session-1", - taskId: "task-monitor-2", - status: "completed", - }); - assert.lengthOf( - continuationRequests, - 0, - "mid-turn task_completed for an in-turn-handled monitor must not open a wake run", - ); - - yield* Deferred.succeed(promptGates[1]!, { stopReason: "end_turn" }); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let secondTerminal: string | null = null; - while (secondTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminal = event.status; - } - } - assert.equal(secondTerminal, "completed"); - assert.lengthOf( - continuationRequests, - 0, - "no continuation must be offered across the multiturn in-turn monitor sequence", - ); - assert.isFalse( - yield* hasPendingBackgroundWork, - "wake buffer must not retain turn-1 or turn-2 in-turn-handled ack residue", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("a wake names work that ended while the previous wake was queued", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; - const promptGate = yield* Deferred.make(); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - deferFinalizeForBackgroundWork: true, - registerExtensions: (context) => - Effect.sync(() => { - applyMutation = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-wake-report-while-queued"); - 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-wake-report-while-queued"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const awaitTerminal = (ordinal: number) => - Effect.gen(function* () { - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, `mock-session-1:turn:${ordinal}`), - }); - while (true) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - return event.status; - } - } - }); - yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - }), - ) - .pipe(Effect.forkScoped); - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - assert.equal(yield* awaitTerminal(1), "completed"); - if (applyMutation === undefined || sessionUpdateHandler === undefined) { - return yield* Effect.die("extensions and session handler must be wired"); - } - const endCommand = (taskId: string, label: string) => - applyMutation!({ - sessionId: "mock-session-1", - taskId, - status: "completed", - report: { kind: "command", label }, - }); - const agentText = (text: string) => - sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }, - }); - - yield* endCommand("task-a", "sleep a"); - yield* agentText("A_DONE"); - assert.lengthOf(continuationRequests, 1); - assert.equal(continuationRequests[0]?.notification?.summary, 'Command "sleep a" finished'); - yield* endCommand("task-b", "sleep b"); - assert.lengthOf(continuationRequests, 1); - - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - messageText: "Background task completed.", - }), - ); - yield* TestClock.adjust("3 seconds"); - assert.equal(yield* awaitTerminal(2), "completed"); - - yield* agentText("B_DONE"); - assert.lengthOf(continuationRequests, 2); - assert.deepEqual(continuationRequests[1]?.notification, { - source: { kind: "command" }, - outcome: "completed", - summary: 'Command "sleep b" finished', - }); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("mid-turn completed mutation defers offer until finalize only when unhandled", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGates: Array> = []; - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-unhandled" - ? "task-monitor-unhandled" - : toolCall.toolCallId === "tool-call-monitor-handled" - ? "task-monitor-handled" - : undefined, - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-fetch-handled" - ? [ - { - taskId: "task-monitor-handled", - status: toolCall.status === "completed" ? "completed" : "running", - appendOutput: toolCall.status === "completed" ? "HANDLED_LISTING" : "", - }, - ] - : [], - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => - Effect.gen(function* () { - const gate = yield* Deferred.make(); - promptGates.push(gate); - return yield* Deferred.await(gate); - }), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-mid-turn-dirty-wake-buffer"); - 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-mid-turn-dirty-wake-buffer", - ), - modelSelection, - runtimePolicy, - }); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die( - "ACP runtime must expose hasPendingBackgroundWork when post-settle continuation is enabled.", - ); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - while (promptGates.length < 1) { - yield* Effect.yieldNow; - } - yield* Deferred.succeed(promptGates[0]!, { stopReason: "end_turn" }); - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let firstTerminal: string | null = null; - while (firstTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminal = event.status; - } - } - assert.equal(firstTerminal, "completed"); - assert.isDefined(sessionUpdateHandler); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "stale wake residue from prior turn" }, - }, - }); - assert.isTrue(yield* hasPendingBackgroundWork, "thought residue must dirty the wake buffer"); - assert.lengthOf(continuationRequests, 0); - - yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 2, - }), - ) - .pipe(Effect.forkScoped); - while (promptGates.length < 2) { - yield* Effect.yieldNow; - } - assert.isFalse( - yield* hasPendingBackgroundWork, - "user-turn start must drop prior-turn wake residue", - ); - const applyMutation = capturedMutation.current; - if (applyMutation === null || sessionUpdateHandler === undefined) { - return yield* Effect.die("extensions and session handler must be wired for turn 2"); - } - - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-unhandled", - title: "Monitor: unhandled", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-unhandled", - status: "in_progress", - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-unhandled", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-unhandled", - status: "completed", - }); - assert.lengthOf( - continuationRequests, - 0, - "mid-turn completed mutation must not offer while the root turn is active", - ); - - yield* Deferred.succeed(promptGates[1]!, { stopReason: "end_turn" }); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let secondTerminal: string | null = null; - while (secondTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminal = event.status; - } - } - assert.equal(secondTerminal, "completed"); - assert.lengthOf( - continuationRequests, - 1, - "post-finalize must offer when mid-turn completion was never handled in-turn", - ); - - const firstOffer = continuationRequests[0]!; - if (firstOffer.clearIfCurrent !== undefined) { - yield* firstOffer.clearIfCurrent(); - } - continuationRequests.length = 0; - yield* runtime - .startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 3, - }), - ) - .pipe(Effect.forkScoped); - while (promptGates.length < 3) { - yield* Effect.yieldNow; - } - if (sessionUpdateHandler === undefined || capturedMutation.current === null) { - return yield* Effect.die("handler must remain wired for turn 3"); - } - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-handled", - title: "Monitor: handled", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-handled", - status: "in_progress", - }, - }); - yield* capturedMutation.current({ - sessionId: "mock-session-1", - taskId: "task-monitor-handled", - status: "running", - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-fetch-handled", - title: "get_command_or_subagent_output", - kind: "other", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-fetch-handled", - status: "completed", - rawOutput: { output: "HANDLED_LISTING" }, - }, - }); - yield* capturedMutation.current({ - sessionId: "mock-session-1", - taskId: "task-monitor-handled", - status: "completed", - }); - assert.lengthOf(continuationRequests, 0, "handled mid-turn completion must not offer"); - yield* Deferred.succeed(promptGates[2]!, { stopReason: "end_turn" }); - const thirdProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:3"), - }); - let thirdTerminal: string | null = null; - while (thirdTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === thirdProviderTurnId) { - thirdTerminal = event.status; - } - } - assert.equal(thirdTerminal, "completed"); - assert.lengthOf( - continuationRequests, - 0, - "post-finalize must not offer when the mid-turn completion was handled in-turn", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect( - "mid-turn unhandled background completion still offers exactly one continuation after finalize", - () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGate = yield* Deferred.make(); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-late" ? "task-monitor-late" : undefined, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-mid-turn-unhandled-offers-after-finalize"); - 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-mid-turn-unhandled-offers-after-finalize", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isDefined(sessionUpdateHandler); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-late", - title: "Monitor: late complete", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-late", - status: "in_progress", - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-late", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-late", - status: "completed", - }); - assert.lengthOf( - continuationRequests, - 0, - "mid-turn unhandled completion must not offer while the turn is active", - ); - - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let terminalStatus: string | null = null; - while (terminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { - terminalStatus = event.status; - } - } - assert.equal(terminalStatus, "completed"); - assert.lengthOf( - continuationRequests, - 1, - "exactly one continuation must be offered after finalize for mid-turn unhandled completion", - ); - const beforeWhitespace = yield* runtime.readThreadSnapshot({ providerThread }); - yield* Queue.clear(events); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: " \n\t " }, - }, - }); - const lateEvents: Array = []; - let lateEvent = yield* Queue.poll(events); - while (Option.isSome(lateEvent)) { - lateEvents.push(lateEvent.value); - lateEvent = yield* Queue.poll(events); - } - assert.isFalse( - lateEvents.some((event) => event.type === "message.updated"), - "whitespace-only late chunks must not append assistant history", - ); - const afterWhitespace = yield* runtime.readThreadSnapshot({ providerThread }); - assert.deepEqual( - afterWhitespace.messages, - beforeWhitespace.messages, - "whitespace-only late chunks must not mutate the loaded history snapshot", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("empty-drain continuation turn waits the quiet window so late frames can attach", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGate = yield* Deferred.make(); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-late" ? "task-monitor-late" : undefined, - isPersistentBackgroundTool: () => true, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-empty-drain-continuation-quiet"); - 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-empty-drain-continuation-quiet", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isDefined(sessionUpdateHandler); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-late", - title: "Monitor: late complete", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-late", - status: "in_progress", - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-late", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-late", - status: "completed", - }); - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - const rootProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let rootTerminal: string | null = null; - while (rootTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === rootProviderTurnId) { - rootTerminal = event.status; - } - } - assert.equal(rootTerminal, "completed"); - assert.lengthOf(continuationRequests, 1, "midTurn-only evidence must offer one continuation"); - - const rootInput = makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 2, - }); - yield* runtime - .startTurn({ - ...rootInput, - message: { - ...rootInput.message, - createdBy: "agent", - creationSource: "provider", - text: "Background task completed.", - }, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - const continuationProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let polled = yield* Queue.poll(events); - while (Option.isSome(polled)) { - assert.notEqual( - polled.value.type === "turn.terminal" && - polled.value.providerTurnId === continuationProviderTurnId - ? "turn.terminal" - : "", - "turn.terminal", - "empty-drain continuation must not finalize immediately", - ); - polled = yield* Queue.poll(events); - } - - assert.isDefined(sessionUpdateHandler); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "LATE_WAKE_FRAME_TOKEN" }, - }, - }); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; - polled = yield* Queue.poll(events); - let lateFrameSeen = false; - while (Option.isSome(polled)) { - if ( - polled.value.type === "turn_item.updated" && - polled.value.turnItem.type === "assistant_message" && - polled.value.turnItem.text.includes("LATE_WAKE_FRAME_TOKEN") - ) { - lateFrameSeen = true; - } - if ( - polled.value.type === "turn.terminal" && - polled.value.providerTurnId === continuationProviderTurnId - ) { - assert.fail("continuation must not finalize before the quiet window elapses"); - } - polled = yield* Queue.poll(events); - } - assert.isTrue(lateFrameSeen, "late wake frame must attach to the continuation run"); - - yield* TestClock.adjust("3 seconds"); - let continuationTerminal: string | null = null; - while (continuationTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === continuationProviderTurnId) { - continuationTerminal = event.status; - } - } - assert.equal(continuationTerminal, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("empty-drain continuation turn finalizes after the quiet window with no frames", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - let sessionUpdateHandler: Parameters[0] | undefined; - const promptGate = yield* Deferred.make(); - const capturedMutation: { - current: - | ((mutation: { - readonly sessionId: string; - readonly taskId: string; - readonly status: "running" | "completed" | "failed"; - }) => Effect.Effect) - | null; - } = { current: null }; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - deferFinalizeForBackgroundWork: true, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-monitor-late" ? "task-monitor-late" : undefined, - isPersistentBackgroundTool: () => true, - registerExtensions: (context) => - Effect.sync(() => { - capturedMutation.current = context.applyBackgroundTaskMutation; - }), - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - wrapRuntime: (runtime) => ({ - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - sessionUpdateHandler = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - prompt: () => Deferred.await(promptGate), - }), - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-empty-drain-continuation-no-wedge"); - 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-empty-drain-continuation-no-wedge", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isDefined(sessionUpdateHandler); - const applyMutation = capturedMutation.current; - if (applyMutation === null) { - return yield* Effect.die("registerExtensions must capture applyBackgroundTaskMutation"); - } - - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call", - toolCallId: "tool-call-monitor-late", - title: "Monitor: late complete", - kind: "execute", - status: "pending", - rawInput: {}, - }, - }); - yield* sessionUpdateHandler!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "tool-call-monitor-late", - status: "in_progress", - }, - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-late", - status: "running", - }); - yield* applyMutation({ - sessionId: "mock-session-1", - taskId: "task-monitor-late", - status: "completed", - }); - yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); - const rootProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - let rootTerminal: string | null = null; - while (rootTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === rootProviderTurnId) { - rootTerminal = event.status; - } - } - assert.equal(rootTerminal, "completed"); - assert.lengthOf(continuationRequests, 1); - - const rootInput = makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: yield* DateTime.now, - ordinal: 2, - }); - yield* runtime - .startTurn({ - ...rootInput, - message: { - ...rootInput.message, - createdBy: "agent", - creationSource: "provider", - text: "Background task completed.", - }, - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - const continuationProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - yield* TestClock.adjust("3 seconds"); - let continuationTerminal: string | null = null; - while (continuationTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === continuationProviderTurnId) { - continuationTerminal = event.status; - } - } - assert.equal(continuationTerminal, "completed"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("restarts the ACP child process before the next prompt after interrupt", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - protocolEvents, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-restart-after-interrupt"); - 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-restart-after-interrupt"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId( - instanceId, - `${providerThread.nativeThreadRef?.nativeId}:turn:1`, - ), - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/cancel", - ), - Stream.runHead, - ); - - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "post-interrupt startTurn should respawn the runtime and replay session/resume", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.effect("Windows teardown is one-shot explicitly with independent finalizer cleanup", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const runtimeScope = yield* Scope.make(); - const taskkillCommands: Array<{ - readonly command: string; - readonly args: ReadonlyArray; - }> = []; - const taskkillSpawner = makeTaskkillSpawner({ exitCode: 0, commands: taskkillCommands }); - const spawner = ChildProcessSpawner.make((command) => { - const value = command as unknown as { readonly command: string }; - return value.command === "taskkill" - ? taskkillSpawner.spawn(command) - : childProcessSpawner.spawn(command); - }); - const context = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: process.cwd(), - env: { T3_ACP_SESSION_LIFECYCLE: "1" }, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-acp-test", version: "0.0.0" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - }).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))), - ).pipe(Effect.provideService(Scope.Scope, runtimeScope)); - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(context), - ); - assert.isDefined(runtime.terminateProcessGroup); - yield* Effect.all([runtime.terminateProcessGroup!, runtime.terminateProcessGroup!], { - concurrency: "unbounded", - }); - assert.equal(taskkillCommands.length, 1); - yield* Scope.close(runtimeScope, Exit.void); - // The scope finalizer picks its kill path from the host, not processGroupPlatform, - // so only a Windows host sends it through taskkill a second time. - const finalizerTaskkills = (yield* HostProcess.Platform) === "win32" ? 1 : 0; - assert.equal(taskkillCommands.length, 1 + finalizerTaskkills); - assert.deepEqual(taskkillCommands.at(-1), taskkillCommands[0]); - }).pipe(Effect.provide(layerTest)), - ); - - it("accepts only taskkill exit code zero as successful tree termination", () => { - assert.isTrue(AcpSessionRuntime.windowsTaskkillResultIsSuccess(0, "")); - assert.isFalse( - AcpSessionRuntime.windowsTaskkillResultIsSuccess( - 128, - "FEHLER: Der Prozess wurde nicht gefunden.", - ), - ); - assert.isFalse(AcpSessionRuntime.windowsTaskkillResultIsSuccess(128, "")); - assert.isFalse(AcpSessionRuntime.windowsTaskkillResultIsSuccess(1, "localized failure")); - assert.isFalse(AcpSessionRuntime.windowsTaskkillResultIsSuccess(255, "")); - }); - - it.effect("runs the default taskkill path and preserves every failure mode", () => - Effect.gen(function* () { - const commands: Array<{ readonly command: string; readonly args: ReadonlyArray }> = - []; - yield* AcpSessionRuntime.terminateWindowsProcessTreeWithTaskkill(4321).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - makeTaskkillSpawner({ exitCode: 0, commands }), - ), - ); - assert.deepEqual(commands, [{ command: "taskkill", args: ["/PID", "4321", "/T", "/F"] }]); - - for (const fixture of [ - { exitCode: 128, output: 'ERROR: The process "4321" not found.' }, - { exitCode: 128, output: "FEHLER: Prozess nicht gefunden." }, - { exitCode: 128, output: "" }, - { exitCode: 128, output: "ERROR: Access is denied." }, - { exitCode: 1, output: "generic failure" }, - ]) { - const failed = yield* AcpSessionRuntime.terminateWindowsProcessTreeWithTaskkill(4321).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - makeTaskkillSpawner(fixture), - ), - Effect.exit, - ); - if (Exit.isSuccess(failed)) assert.fail(`taskkill ${fixture.exitCode} must fail`); - const error = Cause.squash(failed.cause); - assert.instanceOf(error, AcpSessionRuntime.AcpProcessGroupTerminationError); - const termination = error as AcpSessionRuntime.AcpProcessGroupTerminationError; - assert.equal( - termination.detail, - `taskkill exited ${fixture.exitCode} for ACP process tree 4321`, - ); - assert.equal(termination.pid, 4321); - assert.equal(termination.exitCode, fixture.exitCode); - if (fixture.output.length > 0) { - assert.equal(termination.cause, fixture.output); - } - } - - for (const fixture of [ - { spawnFailure: true }, - { outputFailure: true }, - { exitFailure: true }, - ]) { - const failed = yield* AcpSessionRuntime.terminateWindowsProcessTreeWithTaskkill(4321).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - makeTaskkillSpawner(fixture), - ), - Effect.exit, - ); - if (Exit.isSuccess(failed)) assert.fail("taskkill infrastructure failure must fail"); - const error = Cause.squash(failed.cause); - assert.instanceOf(error, AcpSessionRuntime.AcpProcessGroupTerminationError); - assert.equal( - (error as AcpSessionRuntime.AcpProcessGroupTerminationError).detail, - "Failed to run taskkill for ACP process tree 4321", - ); - } - }), - ); - - it.effect("Windows process-tree teardown surfaces taskkill failure", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const context = yield* Layer.build( - AcpSessionRuntime.layer({ - spawn: { command: process.execPath, args: [mockAgentPath], cwd: process.cwd() }, - cwd: process.cwd(), - clientInfo: { name: "t3-acp-test", version: "0.0.0" }, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Effect.fail( - new AcpSessionRuntime.AcpProcessGroupTerminationError({ - detail: "mock taskkill failure", - }), - ), - }).pipe( - Layer.provide( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - ), - ), - ); - const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(context), - ); - const error = yield* Effect.flip(runtime.terminateProcessGroup!); - assert.equal(error.detail, "mock taskkill failure"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("poisons the session when hard teardown defects and blocks replacement work", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-failed-teardown-command-", - }); - const residualCallbackDir = yield* fileSystem.makeTempDirectoryScoped(); - const residualCallbackResponseLogPath = path.join(residualCallbackDir, "responses.log"); - const residualCallbackTriggerPath = path.join(residualCallbackDir, "trigger"); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - let terminatorCallCount = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Effect.gen(function* () { - terminatorCallCount += 1; - yield* Deferred.succeed(teardownStarted, undefined); - yield* Deferred.await(releaseTeardown); - return yield* Effect.die("mock taskkill defect"); - }), - environment: { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_RESIDUAL_CALLBACK_RESPONSE_LOG_PATH: residualCallbackResponseLogPath, - T3_ACP_RESIDUAL_CALLBACK_TRIGGER_PATH: residualCallbackTriggerPath, - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - }, - protocolEvents, - }), - }, - selfInvocation, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-failed-hard-teardown"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - const modelSelection = { instanceId, model: "default" } as const; - const sessionScope = yield* Scope.make(); - const runtime = yield* adapter - .openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-failed-hard-teardown"), - modelSelection, - runtimePolicy, - }) - .pipe(Effect.provideService(Scope.Scope, sessionScope)); - const adapterEvents = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(adapterEvents, event)), - Effect.forkIn(sessionScope), - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - while ((yield* fileSystem.readFileString(commandPidPath)).trim().length === 0) { - yield* Effect.yieldNow; - } - const [commandRootPid, commandSleepPid] = (yield* fileSystem.readFileString(commandPidPath)) - .trim() - .split(/\s+/) - .map(Number); - assert.isTrue( - Option.isSome(yield* waitForProcesses([commandRootPid!, commandSleepPid!])), - "declared failed-teardown Bash and sleep PIDs must both become live", - ); - yield* pollProtocolMethods(protocolEvents); - - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const startFiber = yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.exit, Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(startFiber.pollUnsafe()); - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); - yield* Deferred.succeed(releaseTeardown, undefined); - assert.notInclude(methodsDuringTeardown, "session/resume"); - assert.notInclude(methodsDuringTeardown, "session/prompt"); - - const interruptExit = yield* Fiber.join(interruptFiber); - if (Exit.isSuccess(interruptExit)) assert.fail("hard teardown failure must fail interrupt"); - assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); - assert.isTrue( - Option.isSome(yield* waitForProcesses([commandRootPid!, commandSleepPid!])), - "failed teardown must leave both declared Bash and sleep PIDs live", - ); - - while (Option.isSome(yield* Queue.poll(adapterEvents))) {} - yield* fileSystem.writeFileString(residualCallbackTriggerPath, "go"); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "incoming" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"method":"session/request_permission"'), - ), - Stream.runHead, - ); - assert.isTrue( - Option.isNone(yield* Queue.poll(adapterEvents)), - "residual callbacks must not mutate or emit adapter projection after poison", - ); - assert.isFalse( - yield* fileSystem.exists(residualCallbackResponseLogPath), - "permission and elicitation callbacks must remain unresolved after poison", - ); - assert.lengthOf( - continuationRequests, - 0, - "residual callbacks must not offer a continuation after poison", - ); - - const startExit = yield* Fiber.join(startFiber); - if (Exit.isSuccess(startExit)) assert.fail("poisoned session must reject startTurn"); - assert.include(Cause.pretty(startExit.cause), "session is poisoned"); - const resumeExit = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.exit); - if (Exit.isSuccess(resumeExit)) assert.fail("poisoned session must reject resumeThread"); - assert.include(Cause.pretty(resumeExit.cause), "session is poisoned"); - const snapshotExit = yield* runtime.readThreadSnapshot({ providerThread }).pipe(Effect.exit); - if (Exit.isSuccess(snapshotExit)) { - assert.fail("poisoned session must reject readThreadSnapshot"); - } - assert.include(Cause.pretty(snapshotExit.cause), "session is poisoned"); - const forkExit = yield* runtime - .forkThread({ - sourceProviderThread: providerThread, - targetThreadId: ThreadId.make("thread-acp-poisoned-fork"), - }) - .pipe(Effect.exit); - if (Exit.isSuccess(forkExit)) assert.fail("poisoned session must reject forkThread"); - assert.include(Cause.pretty(forkExit.cause), "session is poisoned"); - yield* pollProtocolMethods(protocolEvents); - const retryInterruptExit = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.exit); - if (Exit.isSuccess(retryInterruptExit)) { - assert.fail("poisoned session must reject a repeated hard interrupt"); - } - const firstInterruptError = Cause.squash(interruptExit.cause) as Error; - const retryInterruptError = Cause.squash(retryInterruptExit.cause) as Error; - assert.strictEqual(retryInterruptError.cause, firstInterruptError.cause); - assert.equal(terminatorCallCount, 1); - const methodsAfterPoison = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(methodsAfterPoison, "initialize"); - assert.notInclude(methodsAfterPoison, "session/cancel"); - assert.notInclude(methodsAfterPoison, "session/fork"); - assert.notInclude(methodsAfterPoison, "session/resume"); - assert.notInclude(methodsAfterPoison, "session/prompt"); - assert.isTrue(processExists(commandRootPid!)); - assert.isTrue(processExists(commandSleepPid!)); - yield* Scope.close(sessionScope, Exit.void); - assert.isTrue( - Option.isSome(yield* waitForProcessesToExit([commandRootPid!, commandSleepPid!])), - "finalizer cleanup must reap both declared Bash and sleep PIDs", - ); - assert.isFalse(processExists(commandRootPid!)); - assert.isFalse(processExists(commandSleepPid!)); - const finalizerMethods = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(finalizerMethods, "session/close"); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("durably poisons start and resume when required hard teardown is unavailable", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, - protocolEvents, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-missing-hard-teardown"); - 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-missing-hard-teardown"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - const interruptExit = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.exit); - if (Exit.isSuccess(interruptExit)) assert.fail("missing hard teardown must fail interrupt"); - assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); - - const startExit = yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.exit); - if (Exit.isSuccess(startExit)) assert.fail("poisoned session must reject startTurn"); - assert.include(Cause.pretty(startExit.cause), "session is poisoned"); - const resumeExit = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .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), - ); - - it.live("holds concurrent startTurn behind successful hard teardown and reloads once", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - let runtimeOrdinalSeen = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: true, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseTeardown)), - ), - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = runtimeOrdinal; - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; - }, - protocolEvents, - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-concurrent-hard-teardown"); - 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-concurrent-hard-teardown"), - modelSelection, - runtimePolicy, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* pollProtocolMethods(protocolEvents); - const interruptFiber = yield* runtime - .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const startFiber = yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(startFiber.pollUnsafe()); - assert.equal(runtimeOrdinalSeen, 1); - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(methodsDuringTeardown, "session/resume"); - assert.notInclude(methodsDuringTeardown, "session/prompt"); - - yield* Deferred.succeed(releaseTeardown, undefined); - yield* Fiber.join(interruptFiber); - yield* Fiber.join(startFiber); - assert.equal(runtimeOrdinalSeen, 2); - const replacementMethods = yield* pollProtocolMethods(protocolEvents); - assert.equal(replacementMethods.filter((method) => method === "session/resume").length, 1); - if (!replacementMethods.includes("session/prompt")) { - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - } - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("quarantines old-runtime callbacks after successful hard teardown", () => - Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const continuationRequests: Array = - []; - const responseLifecycle: Array = []; - type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - type HandlerRecord = { - sessionUpdate?: Parameters[0]; - permission?: Parameters[0]; - elicitation?: Parameters[0]; - requestUserInput?: AcpAdapterV2ExtensionContext["requestUserInput"]; - }; - const handlerRecords: HandlerRecord[] = []; - const runtimeInputs: AcpAdapterV2RuntimeInput[] = []; - const oldPromptCompletion = yield* Deferred.make(); - const transportDrained = yield* Deferred.make(); - const releaseTransportDrain = yield* Deferred.make(); - let extensionOrdinal = 0; - let runtimeOrdinalSeen = 0; - const instanceId = ProviderInstanceId.make("acp-test"); - const makeRuntime = makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => Effect.void, - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = runtimeOrdinal; - return { T3_ACP_HANG_PROMPT_FOREVER: "1" }; - }, - protocolEvents, - wrapRuntime: (runtime, runtimeOrdinal) => { - const record: HandlerRecord = {}; - handlerRecords[runtimeOrdinal - 1] = record; - return { - ...runtime, - handleSessionUpdate: (handler) => - Effect.sync(() => { - record.sessionUpdate = handler; - }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), - handleRequestPermission: (handler) => - Effect.sync(() => { - record.permission = handler; - }).pipe(Effect.andThen(runtime.handleRequestPermission(handler))), - handleElicitation: (handler) => - Effect.sync(() => { - record.elicitation = handler; - }).pipe(Effect.andThen(runtime.handleElicitation(handler))), - ...(runtimeOrdinal === 1 - ? { - prompt: (payload) => - Effect.gen(function* () { - yield* runtime.prompt(payload).pipe(Effect.ignore, Effect.forkDetach); - return yield* Deferred.await(oldPromptCompletion); - }), - } - : {}), - }; - }, - }); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - registerExtensions: ({ requestUserInput }) => - Effect.sync(() => { - handlerRecords[extensionOrdinal++]!.requestUserInput = requestUserInput; - }), - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: (runtimeInput) => - Effect.sync(() => { - runtimeInputs.push(runtimeInput); - }).pipe(Effect.andThen(makeRuntime(runtimeInput))), - }, - selfInvocation, - testHooks: { - afterHardTeardownTransportDrained: () => - Deferred.succeed(transportDrained, undefined).pipe( - Effect.andThen(Deferred.await(releaseTransportDrain)), - ), - onNativeResponseLifecycle: (event) => - Effect.sync(() => { - responseLifecycle.push(event.type); - }), - }, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make("thread-acp-successful-teardown-callback-quarantine"); - 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-successful-teardown-callback-quarantine", - ), - modelSelection, - runtimePolicy, - }); - const adapterEvents = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(adapterEvents, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - const permissionRequest = { - sessionId: "mock-session-1", - toolCall: { - toolCallId: "stale-generation-1-permission", - title: "Stale generation 1 permission", - }, - options: [{ optionId: "allow", name: "Allow", kind: "allow_once" as const }], - }; - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(transportDrained); - const oldHandlers = handlerRecords[0]!; - assert.isDefined(oldHandlers.permission); - const heldInboundFiber = yield* oldHandlers.permission!(permissionRequest, { - requestId: "post-drain-stale-permission-id", - method: "session/request_permission", - }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - assert.isUndefined(heldInboundFiber.pollUnsafe()); - yield* Deferred.succeed(releaseTransportDrain, undefined); - yield* Fiber.join(interruptFiber); - yield* Effect.yieldNow; - assert.isUndefined(heldInboundFiber.pollUnsafe()); - assert.notInclude(responseLifecycle, "registered"); - assert.notInclude(responseLifecycle, "watcher_started"); - assert.isFalse( - (yield* Queue.takeAll(adapterEvents)).some( - (event) => event.type === "runtime_request.updated", - ), - "post-drain inbound callback must not emit a runtime request", - ); - assert.equal(runtimeOrdinalSeen, 1); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", - ), - Stream.runHead, - ); - assert.equal(runtimeOrdinalSeen, 2); - const replacementHandlers = handlerRecords[1]!; - assert.isDefined(oldHandlers.sessionUpdate); - assert.isDefined(oldHandlers.permission); - assert.isDefined(oldHandlers.elicitation); - assert.isDefined(oldHandlers.requestUserInput); - assert.isDefined(replacementHandlers.sessionUpdate); - assert.isDefined(replacementHandlers.permission); - assert.isDefined(replacementHandlers.elicitation); - assert.isDefined(replacementHandlers.requestUserInput); - assert.lengthOf(runtimeInputs, 2); - while (Option.isSome(yield* Queue.poll(adapterEvents))) {} - - yield* oldHandlers.sessionUpdate!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "stale generation 1 assistant" }, - }, - }); - yield* oldHandlers.sessionUpdate!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "tool_call_update", - toolCallId: "stale-generation-1-tool", - title: "Stale generation 1 tool", - kind: "other", - status: "completed", - rawOutput: { output: "stale continuation evidence" }, - }, - }); - const oldPermissionFiber = yield* oldHandlers.permission!(permissionRequest, { - requestId: "stale-generation-1-permission-id", - method: "session/request_permission", - }).pipe(Effect.exit, Effect.forkScoped); - const oldElicitationFiber = yield* oldHandlers.elicitation!( - { + status: "pending", + rawInput: { task_id: "task-monitor-2" }, + }, + }); + yield* sessionUpdateHandler({ sessionId: "mock-session-1", - message: "Stale generation 1 elicitation", - mode: "form", - requestedSchema: { - type: "object", - properties: { approved: { type: "boolean", title: "Approved" } }, + update: { + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-fetch-2", + status: "completed", + rawOutput: { output: "MONITOR_LISTING_TOKEN_2" }, }, - }, - { - requestId: "stale-generation-1-elicitation-id", - method: "session/elicitation", - }, - ).pipe(Effect.exit, Effect.forkScoped); - const oldXAiUserInputFiber = yield* oldHandlers.requestUserInput!( - { - nativeItemId: "stale-generation-1-xai-item", - nativeRequestId: "stale-generation-1-xai-request", - questions: [ - { - id: "approved", - header: "Approve", - question: "Approve stale generation 1?", - options: [{ label: "yes", description: "Approve" }], - }, - ], - }, - { - requestId: "stale-generation-1-xai-transport-id", - method: "_x.ai/ask_user_question", - }, - ).pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.succeed(oldPromptCompletion, { stopReason: "end_turn" }); - yield* Effect.sleep("100 millis"); - assert.isTrue(Option.isNone(yield* Queue.poll(adapterEvents))); - assert.isUndefined(oldPermissionFiber.pollUnsafe()); - assert.isUndefined(oldElicitationFiber.pollUnsafe()); - assert.isUndefined(oldXAiUserInputFiber.pollUnsafe()); - assert.lengthOf(continuationRequests, 0); - - yield* replacementHandlers.sessionUpdate!({ - sessionId: "mock-session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "live generation 2 assistant" }, - }, - }); - let replacementMessageSeen = false; - while (!replacementMessageSeen) { - const event = yield* Queue.take(adapterEvents); - replacementMessageSeen = - event.type === "message.updated" && event.message.text.includes("live generation 2"); - } - const replacementPermission = yield* replacementHandlers.permission!(permissionRequest, { - requestId: "live-generation-2-permission-id", - method: "session/request_permission", - }); - assert.equal(replacementPermission.outcome.outcome, "selected"); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-permission-id"); - const urlElicitation = { - elicitationId: "replacement-url-id", - message: "Open replacement URL", - mode: "url" as const, - sessionId: "mock-session-1", - url: "https://example.com/replacement", - }; - yield* replacementHandlers.elicitation!(urlElicitation, { - requestId: "live-generation-2-url-id", - method: "session/elicitation", - }); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-url-id"); - - const replacementUserInputFiber = yield* replacementHandlers.requestUserInput!( - { - nativeItemId: "live-generation-2-xai-item", - nativeRequestId: "shared-request-id", - questions: [ - { - id: "approved", - header: "Approve", - question: "Approve live generation 2?", - options: [{ label: "yes", description: "Approve" }], - }, - ], - }, - { - requestId: "live-generation-2-transport-id", - method: "_x.ai/ask_user_question", - }, - ).pipe(Effect.forkScoped); - let replacementRequest: ProviderAdapter.ProviderAdapterV2Event | undefined; - while (replacementRequest === undefined) { - const event = yield* Queue.take(adapterEvents); - if (event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending") { - replacementRequest = event; - } - } - if (replacementRequest.type !== "runtime_request.updated") { - return yield* Effect.die("Expected generation 2 xAI user input request"); - } - const responseFiber = yield* runtime - .respondToRuntimeRequest({ - requestId: replacementRequest.runtimeRequest.id, - answers: { approved: ["yes"] }, - }) - .pipe(Effect.forkScoped); - const replacementUserInput = yield* Fiber.join(replacementUserInputFiber); - assert.deepEqual(replacementUserInput.answers, { approved: ["yes"] }); - yield* replacementUserInput.acknowledgeNativeResponse; - yield* runtimeInputs[0]!.onOutgoingResponse!("stale-generation-1-transport-id"); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-wrong-method-id"); - yield* Effect.yieldNow; - assert.isUndefined(responseFiber.pollUnsafe()); - yield* runtimeInputs[1]!.onOutgoingResponse!("live-generation-2-transport-id"); - yield* Fiber.join(responseFiber); + }); + yield* sessionUpdateHandler({ + sessionId: "mock-session-1", + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Second monitor listing ready in-turn." }, + }, + }); + yield* capturedMutation.current({ + sessionId: "mock-session-1", + taskId: "task-monitor-2", + status: "completed", + }); + assert.lengthOf( + continuationRequests, + 0, + "mid-turn task_completed for an in-turn-handled monitor must not open a wake run", + ); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: idAllocator.derive.providerTurn({ + yield* Deferred.succeed(promptGates[1]!, { stopReason: "end_turn" }); + const secondProviderTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }), - requestRuntimeRestart: true, - }); - }).pipe(Effect.provide(layerTest), Effect.scoped), + }); + let secondTerminal: string | null = null; + while (secondTerminal === null) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { + secondTerminal = event.status; + } + } + assert.equal(secondTerminal, "completed"); + assert.lengthOf( + continuationRequests, + 0, + "no continuation must be offered across the multiturn in-turn monitor sequence", + ); + assert.isFalse( + yield* hasPendingBackgroundWork, + "wake buffer must not retain turn-1 or turn-2 in-turn-handled ack residue", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("keeps stale deferred cleanup inert while replacement requests remain live", () => + it.effect("a wake names work that ended while the previous wake was queued", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const idAllocator = yield* IdAllocator.IdAllocatorV2; const path = yield* Path.Path; const selfInvocation = yield* resolveSelfInvocation(); const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const protocolEvents = yield* Queue.bounded(256); + const continuationRequests: Array = + []; + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + let applyMutation: AcpAdapterV2ExtensionContext["applyBackgroundTaskMutation"] | undefined; + const promptGate = yield* Deferred.make(); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - restartRuntimeAfterInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, + enablePostSettleContinuation: true, + deferFinalizeForBackgroundWork: true, + registerExtensions: (context) => + Effect.sync(() => { + applyMutation = context.applyBackgroundTaskMutation; + }), makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => Effect.void, - environment: { T3_ACP_EMIT_TOOL_CALLS: "1" }, - protocolEvents, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => Deferred.await(promptGate), + }), }), }, selfInvocation, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }), + }, }); - const threadId = ThreadId.make("thread-acp-stale-deferred-cleanup"); + const threadId = ThreadId.make("thread-acp-wake-report-while-queued"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", + 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-stale-deferred-cleanup"), + providerSessionId: ProviderSessionId.make("provider-session-acp-wake-report-while-queued"), modelSelection, runtimePolicy, }); @@ -13169,71 +6653,303 @@ describe("AcpAdapterV2", () => { modelSelection, runtimePolicy, }); - const now = yield* DateTime.now; + const awaitTerminal = (ordinal: number) => + Effect.gen(function* () { + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, `mock-session-1:turn:${ordinal}`), + }); + while (true) { + const event = yield* Queue.take(events); + if (event.type === "turn.terminal" && event.providerTurnId === providerTurnId) { + return event.status; + } + } + }); + yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); + assert.equal(yield* awaitTerminal(1), "completed"); + if (applyMutation === undefined || sessionUpdateHandler === undefined) { + return yield* Effect.die("extensions and session handler must be wired"); + } + const endCommand = (taskId: string, label: string) => + applyMutation!({ + sessionId: "mock-session-1", + taskId, + status: "completed", + report: { kind: "command", label }, + }); + const agentText = (text: string) => + sessionUpdateHandler!({ + sessionId: "mock-session-1", + update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }, + }); + + yield* endCommand("task-a", "sleep a"); + yield* agentText("A_DONE"); + assert.lengthOf(continuationRequests, 1); + assert.equal(continuationRequests[0]?.notification?.summary, 'Command "sleep a" finished'); + yield* endCommand("task-b", "sleep b"); + assert.lengthOf(continuationRequests, 1); + yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ); - const oldPending = yield* Queue.take(events).pipe( - Effect.repeat({ - until: (event) => - event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + ordinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + messageText: "Background task completed.", }), ); - if ( - oldPending.type !== "runtime_request.updated" || - oldPending.runtimeRequest.providerTurnId === null - ) { - return yield* Effect.die("Expected the old runtime permission request"); - } - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: oldPending.runtimeRequest.providerTurnId, - requestRuntimeRestart: true, + yield* TestClock.adjust("3 seconds"); + assert.equal(yield* awaitTerminal(2), "completed"); + + yield* agentText("B_DONE"); + assert.lengthOf(continuationRequests, 2); + assert.deepEqual(continuationRequests[1]?.notification, { + source: { kind: "command" }, + outcome: "completed", + summary: 'Command "sleep b" finished', }); - const staleResponse = yield* runtime - .respondToRuntimeRequest({ - requestId: oldPending.runtimeRequest.id, - decision: "accept", - }) - .pipe(Effect.exit); - if (Exit.isSuccess(staleResponse)) { - assert.fail("teardown must synchronously remove the old pending request"); - } - while (Option.isSome(yield* Queue.poll(events))) {} + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect.each([ + { status: "completed" as const, exitCode: 0 }, + { status: "failed" as const, exitCode: 1 }, + ])( + "retains early Grok $status command completion across sparse notifications and replayed ACKs", + ({ status, exitCode }) => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + let taskCompleted: + | ((payload: unknown) => Effect.Effect) + | undefined; + const promptStarted = yield* Deferred.make(); + const promptGate = yield* Deferred.make(); + const promptHeld = yield* Deferred.make(); + const finalizeScheduled = yield* Deferred.make(); + const continuationOffered = yield* Deferred.make(); + const continuationRequests: Array = + []; + const instanceId = ProviderInstanceId.make("acp-test"); + const grokFlavor = makeGrokAcpAdapterFlavor( + { + instanceId, + settings: DEFAULT_GROK_SETTINGS, + environment: {}, + hostPlatform: yield* HostProcess.Platform, + selfInvocation, + }, + yield* HostProcess.HomeDirectory, + ); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + testHooks: { + afterPromptSettledWithBackgroundWork: () => + Deferred.succeed(promptHeld, undefined).pipe(Effect.asVoid), + onDeferredFinalizeScheduled: (debounce) => + Deferred.succeed(finalizeScheduled, debounce).pipe(Effect.asVoid), + }, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + deferFinalizeForBackgroundWork: true, + normalizeToolCall: grokFlavor.normalizeToolCall!, + extractBackgroundTaskId: grokFlavor.extractBackgroundTaskId!, + isBackgroundCommandTool: grokFlavor.isBackgroundCommandTool!, + registerExtensions: ({ runtime, applyBackgroundTaskMutation }) => + registerXAiBackgroundTaskTracking(runtime, applyBackgroundTaskMutation), + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + handleExtNotification: (method, schema, handler) => + Effect.sync(() => { + if (method === "x.ai/task_completed") { + taskCompleted = (payload) => + handler(Schema.decodeUnknownSync(schema)(payload)); + } + }).pipe(Effect.andThen(runtime.handleExtNotification(method, schema, handler))), + prompt: () => + Deferred.succeed(promptStarted, undefined).pipe( + Effect.andThen(Deferred.await(promptGate)), + ), + }), + }), + }, + continuationRequests: { + offer: (request) => + Effect.sync(() => continuationRequests.push(request)).pipe( + Effect.andThen(Deferred.succeed(continuationOffered, undefined)), + Effect.asVoid, + ), + }, + }); + const threadId = ThreadId.make("thread-acp-early-command"); + 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-early-command"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(promptStarted); + assert.isDefined(sessionUpdateHandler); + assert.isDefined(taskCompleted); + const update = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdateHandler!({ sessionId: "mock-session-1", update }); + const complete = (taskId: string, snapshot?: { output?: string; exit_code?: number }) => + taskCompleted!({ + sessionId: "mock-session-1", + update: { sessionUpdate: "task_completed", task_id: taskId, task_snapshot: snapshot }, + }); + for (const taskId of ["early", "blocker"]) { + yield* update({ + sessionUpdate: "tool_call", + toolCallId: taskId, + title: `Run ${taskId}`, + kind: "execute", + status: "completed", + rawInput: { command: `echo ${taskId}` }, + rawOutput: { type: "BackgroundTaskStarted", task_id: taskId }, + }); + } + // Progress removes the ACK carrying the task identity before a reportless completion. + yield* update({ + sessionUpdate: "tool_call_update", + toolCallId: "early", + status: "in_progress", + rawOutput: { type: "Text", text: "Command progress" }, + }); + yield* complete("early", { exit_code: exitCode, output: "EARLY_BG_DONE\n" }); + // The real decoder treats this exit-code-free duplicate as completed, even after failure. + yield* complete("early"); + assert.lengthOf(continuationRequests, 0); - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), - ); - let replacementPending: ProviderAdapter.ProviderAdapterV2Event | undefined; - while (replacementPending === undefined) { - const event = yield* Queue.take(events); - if (event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending") { - replacementPending = event; + let backgroundItem: ProviderAdapter.ProviderAdapterV2Event | undefined; + let checkpoint = 0; + const assertCommand = Effect.fnUntraced(function* (expectedStatus: string, output: string) { + const title = `Checkpoint ${++checkpoint}`; + // A later tool event fences the emitted updates without waiting for a terminal that may never come. + yield* update({ sessionUpdate: "tool_call_update", toolCallId: "blocker", title }); + while (true) { + const event = yield* Queue.take(events); + if (event.type !== "turn_item.updated") continue; + if (event.turnItem.nativeItemRef?.nativeId === "early") backgroundItem = event; + if ( + event.turnItem.nativeItemRef?.nativeId === "blocker" && + event.turnItem.title === title + ) + break; + } + assert.equal(backgroundItem?.type, "turn_item.updated"); + if (backgroundItem?.type !== "turn_item.updated") return; + assert.equal(backgroundItem.turnItem.status, expectedStatus); + assert.equal(backgroundItem.turnItem.type, "command_execution"); + if (backgroundItem.turnItem.type === "command_execution") { + assert.equal(backgroundItem.turnItem.output ?? "", output); + } + }); + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); + yield* Deferred.await(promptHeld); + yield* assertCommand(status, "EARLY_BG_DONE\n"); + assert.lengthOf(continuationRequests, 0, "the other command still holds the root open"); + + const replayAck = () => + update({ + sessionUpdate: "tool_call_update", + toolCallId: "early", + status: "completed", + rawOutput: { type: "BackgroundTaskStarted", task_id: "early" }, + }); + yield* replayAck(); + yield* assertCommand(status, "EARLY_BG_DONE\n"); + // Sparse ACP updates must retain the command result after projection replaces the ACK. + for (const sparseStatus of ["completed", "in_progress"] as const) { + yield* update({ + sessionUpdate: "tool_call_update", + toolCallId: "early", + status: sparseStatus, + }); + yield* assertCommand(status, "EARLY_BG_DONE\n"); } - } - if (replacementPending.type !== "runtime_request.updated") { - return yield* Effect.die("Expected the replacement runtime permission request"); - } - assert.notEqual(replacementPending.runtimeRequest.id, oldPending.runtimeRequest.id); - yield* runtime.respondToRuntimeRequest({ - requestId: replacementPending.runtimeRequest.id, - decision: "accept", - }); - let replacementTerminal = false; - while (!replacementTerminal) { - const event = yield* Queue.take(events); - if ( - event.type === "runtime_request.updated" && - event.runtimeRequest.id === oldPending.runtimeRequest.id - ) { - assert.fail("stale deferred cleanup must not emit into generation 2"); + if (status === "completed") { + for (const output of ["", "UPDATED_OUTPUT\n"]) { + yield* complete("early", { output }); + yield* replayAck(); + yield* assertCommand(status, output); + } } - replacementTerminal = event.type === "turn.terminal"; - } - }).pipe(Effect.provide(layerTest), Effect.scoped), + yield* complete("blocker", { exit_code: 0, output: "BLOCKER_DONE\n" }); + yield* TestClock.adjust(yield* Deferred.await(finalizeScheduled)); + while (true) { + const event = yield* Queue.take(events); + if (event.type !== "turn.terminal") continue; + assert.equal(event.status, "completed"); + break; + } + yield* Deferred.await(continuationOffered); + yield* complete("early"); + yield* complete("blocker"); + assert.lengthOf( + continuationRequests, + 1, + "duplicate completions must not offer another continuation", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); - it.live("resolves owner cancellation and concurrent resume waiters after hard teardown", () => + it.live("durably poisons start and resume when required hard teardown is unavailable", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const idAllocator = yield* IdAllocator.IdAllocatorV2; @@ -13243,37 +6959,24 @@ describe("AcpAdapterV2", () => { new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); const protocolEvents = yield* Queue.bounded(256); - const teardownStarted = yield* Deferred.make(); - const releaseTeardown = yield* Deferred.make(); - let runtimeOrdinalSeen = 0; const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: true, restartRuntimeAfterInterrupt: true, terminateRuntimeProcessGroupOnInterrupt: true, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - ownDetachedProcessGroup: true, - processGroupPlatform: "win32", - windowsProcessTreeTerminator: () => - Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseTeardown)), - ), - environment: (runtimeOrdinal) => { - runtimeOrdinalSeen = runtimeOrdinal; - return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; - }, + environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" }, protocolEvents, }), }, selfInvocation, }); - const threadId = ThreadId.make("thread-acp-concurrent-resume-teardown"); + const threadId = ThreadId.make("thread-acp-missing-hard-teardown"); const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -13282,9 +6985,7 @@ describe("AcpAdapterV2", () => { const modelSelection = { instanceId, model: "default" } as const; const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-concurrent-resume-teardown", - ), + providerSessionId: ProviderSessionId.make("provider-session-acp-missing-hard-teardown"), modelSelection, runtimePolicy, }); @@ -13299,72 +7000,41 @@ describe("AcpAdapterV2", () => { makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), ) .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - yield* pollProtocolMethods(protocolEvents); + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); const providerTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - const interruptFiber = yield* runtime + const interruptExit = yield* runtime .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) - .pipe(Effect.forkScoped); - yield* Deferred.await(teardownStarted); - const resumeFiber = yield* runtime - .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.forkScoped); - const secondResumeFiber = yield* runtime + .pipe(Effect.exit); + if (Exit.isSuccess(interruptExit)) assert.fail("missing hard teardown must fail interrupt"); + assert.include(Cause.pretty(interruptExit.cause), "session is poisoned"); + + const startExit = yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ) + .pipe(Effect.exit); + if (Exit.isSuccess(startExit)) assert.fail("poisoned session must reject startTurn"); + assert.include(Cause.pretty(startExit.cause), "session is poisoned"); + const resumeExit = yield* runtime .resumeThread({ providerThread, modelSelection, runtimePolicy }) - .pipe(Effect.forkScoped); - const snapshotProviderThread = { - ...providerThread, - nativeThreadRef: { - ...providerThread.nativeThreadRef!, - nativeId: "mock-session-snapshot", - }, - }; - const snapshotFiber = yield* runtime - .readThreadSnapshot({ providerThread: snapshotProviderThread }) - .pipe(Effect.forkScoped); - const forkFiber = yield* runtime - .forkThread({ - sourceProviderThread: providerThread, - targetThreadId: ThreadId.make("thread-acp-concurrent-fork-after-teardown"), - }) - .pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(resumeFiber.pollUnsafe()); - assert.isUndefined(secondResumeFiber.pollUnsafe()); - assert.isUndefined(snapshotFiber.pollUnsafe()); - assert.isUndefined(forkFiber.pollUnsafe()); - assert.equal(runtimeOrdinalSeen, 1); - const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); - assert.notInclude(methodsDuringTeardown, "session/resume"); - assert.notInclude(methodsDuringTeardown, "session/fork"); - const cancelInterruptOwner = yield* Fiber.interrupt(interruptFiber).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* Effect.yieldNow; - assert.isUndefined(cancelInterruptOwner.pollUnsafe()); - yield* Deferred.succeed(releaseTeardown, undefined); - yield* Fiber.join(cancelInterruptOwner); - yield* Fiber.join(resumeFiber); - yield* Fiber.join(secondResumeFiber); - yield* Fiber.join(snapshotFiber); - yield* Fiber.join(forkFiber); - assert.equal(runtimeOrdinalSeen, 2); - const methodsAfterRestart = yield* pollProtocolMethods(protocolEvents); - assert.equal(methodsAfterRestart.filter((method) => method === "session/resume").length, 2); - assert.equal(methodsAfterRestart.filter((method) => method === "session/fork").length, 1); + .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), ); - it.live("direct Stop skips uninterruptible ACP cancel and recovers after native teardown", () => + it.live("holds concurrent startTurn behind successful hard teardown and reloads once", () => Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const path = yield* Path.Path; const selfInvocation = yield* resolveSelfInvocation(); @@ -13372,261 +7042,100 @@ describe("AcpAdapterV2", () => { new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); const protocolEvents = yield* Queue.bounded(256); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-direct-stop-command-", - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => cleanupPublishedDetachedFixture(commandPidPath)), - ); - let cancelCalled = false; + const teardownStarted = yield* Deferred.make(); + const releaseTeardown = yield* Deferred.make(); + let runtimeOrdinalSeen = 0; const instanceId = ProviderInstanceId.make("acp-test"); const adapter = yield* makeAcpAdapterV2({ instanceId, flavor: { driver: ACP_TEST_DRIVER, capabilities: AcpProviderCapabilitiesV2, - enablePostSettleContinuation: true, - extractBackgroundTaskId: (toolCall) => - toolCall.toolCallId === "tool-call-running-1" ? "task-running-1" : undefined, - extractBackgroundTaskCompletion: (toolCall) => - toolCall.toolCallId === "tool-call-output-1" - ? [{ taskId: "task-running-1", status: "running", appendOutput: "" }] - : [], interruptPromptOnCancel: true, restartRuntimeAfterInterrupt: true, terminateRuntimeProcessGroupOnInterrupt: true, makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, - ownDescendantProcessGroups: true, ownDetachedProcessGroup: true, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 - ? { - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1", - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - T3_ACP_RUNNING_COMMAND_IGNORE_TERM: "1", - T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION: "1", - } - : {}, + processGroupPlatform: "win32", + windowsProcessTreeTerminator: () => + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseTeardown)), + ), + environment: (runtimeOrdinal) => { + runtimeOrdinalSeen = runtimeOrdinal; + return runtimeOrdinal === 1 ? { T3_ACP_HANG_PROMPT_FOREVER: "1" } : {}; + }, protocolEvents, - wrapCancel: () => - Effect.sync(() => { - cancelCalled = true; - }).pipe(Effect.andThen(Effect.never)), }), }, selfInvocation, - continuationRequests: { offer: () => Effect.void }, }); - const threadId = ThreadId.make("thread-acp-direct-stop-running-command"); + const threadId = ThreadId.make("thread-acp-concurrent-hard-teardown"); 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-direct-stop-running-command", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - - let runningMonitorSeen = false; - let runningTaskOutputSeen = false; - while (!runningMonitorSeen || !runningTaskOutputSeen) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - (event.turnItem.status === "running" || event.turnItem.status === "pending") - ) { - if (event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1") { - runningMonitorSeen = true; - } - if (event.turnItem.nativeItemRef?.nativeId === "tool-call-output-1") { - runningTaskOutputSeen = true; - } - } - } - const [commandLauncherPid, commandRootPid, commandSleepPid] = Option.getOrThrow( - yield* waitForPublishedProcessIds(fileSystem, commandPidPath, 3), - ); - assert.isTrue( - Option.isSome( - yield* waitForProcesses([commandLauncherPid!, commandRootPid!, commandSleepPid!]), - ), - "declared direct Stop launcher, Bash, and sleep PIDs must become live", - ); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* Queue.takeAll(events); - const interruptFiber = yield* runtime - .interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - const interruptCompleted = yield* Fiber.join(interruptFiber).pipe( - Effect.timeoutOption("3 seconds"), - ); - assert.isTrue(Option.isSome(interruptCompleted), "hung ACP cancel must not block teardown"); - assert.isFalse(cancelCalled, "hard process-group teardown must skip ACP cancel"); - yield* Effect.sleep("250 millis"); - assert.isFalse(processExists(commandLauncherPid!)); - assert.isFalse(processExists(commandRootPid!)); - assert.isFalse(processExists(commandSleepPid!)); - - let terminalStatus: string | null = null; - let openToolTerminalStatus: string | null = null; - let openToolInterruptedExitCode: number | undefined = 42; - let lateAfterCancelSeen = false; - let runningMonitorAfterInterrupt = false; - while (terminalStatus === null || openToolTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1" && - event.turnItem.status === "running" - ) { - runningMonitorAfterInterrupt = true; - if (event.turnItem.type === "command_execution") { - assert.equal( - event.turnItem.exitCode, - undefined, - "mid-stream exit_code 0 must not project while the command is still running", - ); - } - } - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - (event.turnItem.status === "failed" || - event.turnItem.status === "cancelled" || - event.turnItem.status === "interrupted" || - event.turnItem.status === "completed") - ) { - openToolTerminalStatus = event.turnItem.status; - openToolInterruptedExitCode = event.turnItem.exitCode; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - terminalStatus = event.status; - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - lateAfterCancelSeen = true; - } - } - assert.equal(terminalStatus, "interrupted"); - assert.equal(openToolTerminalStatus, "interrupted"); - assert.equal( - openToolInterruptedExitCode, - undefined, - "interrupted commands must not retain a mid-stream exit_code 0", - ); - assert.isFalse(runningMonitorAfterInterrupt); - assert.isFalse(yield* runtime.hasPendingBackgroundWork!); - assert.isFalse( - lateAfterCancelSeen, - "late post-Stop assistant text must not attach to the stopped run", - ); - - yield* Effect.sleep("200 millis"); + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-concurrent-hard-teardown"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), + ) + .pipe(Effect.forkScoped); yield* Effect.yieldNow; yield* Effect.yieldNow; - let residual = yield* Queue.poll(events); - while (Option.isSome(residual)) { - const event = residual.value; - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1" - ) { - assert.notEqual(event.turnItem.status, "running"); - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - lateAfterCancelSeen = true; - } - residual = yield* Queue.poll(events); - } - assert.isFalse(lateAfterCancelSeen, "quarantine must drop residual stopped-run events"); - - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const loadAfterRestart = yield* Stream.fromQueue(protocolEvents).pipe( - Stream.filter( - (event) => - event.direction === "outgoing" && rawProtocolMethod(event) === "session/resume", - ), - Stream.runHead, - ); - assert.isTrue( - Option.isSome(loadAfterRestart), - "Direct Stop follow-up must respawn the ACP runtime", - ); - - const secondProviderTurnId = idAllocator.derive.providerTurn({ + yield* Effect.yieldNow; + const providerTurnId = idAllocator.derive.providerTurn({ driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), }); - let secondTerminal: string | null = null; - let stoppedRunTextOnFollowUp = false; - while (secondTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - stoppedRunTextOnFollowUp = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminal = event.status; - } + yield* pollProtocolMethods(protocolEvents); + const interruptFiber = yield* runtime + .interruptTurn({ providerThread, providerTurnId, requestRuntimeRestart: true }) + .pipe(Effect.forkScoped); + yield* Deferred.await(teardownStarted); + const startFiber = yield* runtime + .startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 2 }), + ) + .pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* Effect.yieldNow; + assert.isUndefined(startFiber.pollUnsafe()); + assert.equal(runtimeOrdinalSeen, 1); + const methodsDuringTeardown = yield* pollProtocolMethods(protocolEvents); + assert.notInclude(methodsDuringTeardown, "session/resume"); + assert.notInclude(methodsDuringTeardown, "session/prompt"); + + yield* Deferred.succeed(releaseTeardown, undefined); + yield* Fiber.join(interruptFiber); + yield* Fiber.join(startFiber); + assert.equal(runtimeOrdinalSeen, 2); + const replacementMethods = yield* pollProtocolMethods(protocolEvents); + assert.equal(replacementMethods.filter((method) => method === "session/resume").length, 1); + if (!replacementMethods.includes("session/prompt")) { + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt", + ), + Stream.runHead, + ); } - assert.equal(secondTerminal, "completed"); - assert.isFalse( - stoppedRunTextOnFollowUp, - "stopped-run residual text must not attach to the follow-up run", - ); }).pipe(Effect.provide(layerTest), Effect.scoped), ); @@ -13691,482 +7200,98 @@ describe("AcpAdapterV2", () => { interactionMode: "default", cwd: process.cwd(), }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-acp-direct-stop-subagent-hold", - ), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), - ); - yield* Deferred.await(promptSettled); - - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - yield* runtime.interruptTurn({ - providerThread, - providerTurnId: firstProviderTurnId, - requestRuntimeRestart: true, - }); - - let subagentStatus: string | null = null; - let firstTerminalStatus: string | null = null; - while (firstTerminalStatus === null) { - const event = yield* Queue.take(events); - if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { - subagentStatus = event.turnItem.status; - } - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminalStatus = event.status; - } - } - assert.equal(firstTerminalStatus, "interrupted"); - assert.equal(subagentStatus, "interrupted"); - - subagentPhase = "complete"; - const secondNow = yield* DateTime.now; - yield* runtime.startTurn( - makeTurnInput({ - threadId, - providerThread, - instanceId, - runtimePolicy, - now: secondNow, - ordinal: 2, - }), - ); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let carriedCompleted = false; - let secondTerminalStatus: string | null = null; - while (secondTerminalStatus === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.status === "completed" - ) { - carriedCompleted = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminalStatus = event.status; - } - } - assert.equal(secondTerminalStatus, "completed"); - assert.isFalse( - carriedCompleted, - "Direct Stop must not carry a stopped subagent into the follow-up run", - ); - }).pipe(Effect.provide(layerTest), Effect.scoped), - ); - - it.live("restart_active terminates native work and reloads a clean runtime", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; - const selfInvocation = yield* resolveSelfInvocation(); - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const protocolEvents = yield* Queue.bounded(256); - const commandPidPath = yield* fileSystem.makeTempFileScoped({ - prefix: "t3-acp-restart-active-command-", - }); - yield* Effect.addFinalizer(() => - Effect.sync(() => cleanupPublishedDetachedFixture(commandPidPath)), - ); - const instanceId = ProviderInstanceId.make("acp-test"); - const adapter = yield* makeAcpAdapterV2({ - instanceId, - flavor: { - driver: ACP_TEST_DRIVER, - capabilities: AcpProviderCapabilitiesV2, - interruptPromptOnCancel: true, - restartRuntimeAfterInterrupt: true, - restartRuntimeOnEveryInterrupt: true, - terminateRuntimeProcessGroupOnInterrupt: true, - makeRuntime: makeMockRuntime({ - childProcessSpawner, - mockAgentPath, - ownDescendantProcessGroups: true, - ownDetachedProcessGroup: true, - processGroupTerminationGrace: 0, - environment: (runtimeOrdinal) => - runtimeOrdinal === 1 - ? { - T3_ACP_EXIT_ON_CANCEL: "1", - T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL: "1", - T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG: "1", - T3_ACP_RUNNING_COMMAND_PID_PATH: commandPidPath, - T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION: "1", - } - : {}, - protocolEvents, - wrapCancel: (cancel) => cancel.pipe(Effect.andThen(Effect.sleep("250 millis"))), - }), - }, - selfInvocation, - }); - const threadId = ThreadId.make("thread-acp-restart-active-in-process"); - 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-restart-active-in-process"), - modelSelection, - runtimePolicy, - }); - const events = yield* Queue.unbounded(); - yield* runtime.events.pipe( - Stream.runForEach((event) => Queue.offer(events, event)), - Effect.forkScoped, - ); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, - }); - const now = yield* DateTime.now; - yield* runtime - .startTurn( - makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now, ordinal: 1 }), - ) - .pipe(Effect.forkScoped); - - let runningToolSeen = false; - while (!runningToolSeen) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - (event.turnItem.status === "running" || event.turnItem.status === "pending") - ) { - runningToolSeen = true; - } - } - const [commandLauncherPid, commandRootPid, commandSleepPid] = Option.getOrThrow( - yield* waitForPublishedProcessIds(fileSystem, commandPidPath, 3), - ); - assert.isTrue( - Option.isSome( - yield* waitForProcesses([commandLauncherPid!, commandRootPid!, commandSleepPid!]), - ), - "declared restart_active launcher, Bash, and sleep PIDs must become live", - ); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make( + "provider-session-acp-direct-stop-subagent-hold", + ), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* runtime.startTurn( + makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }), + ); + yield* Deferred.await(promptSettled); - const firstProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), - }); - const interruptFiber = yield* runtime - .interruptTurn({ + const firstProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:1"), + }); + yield* runtime.interruptTurn({ providerThread, providerTurnId: firstProviderTurnId, - }) - .pipe(Effect.forkScoped); - yield* Fiber.join(interruptFiber); - yield* Effect.sleep("250 millis"); - assert.isFalse(processExists(commandLauncherPid!)); - assert.isFalse(processExists(commandRootPid!)); - assert.isFalse(processExists(commandSleepPid!)); + requestRuntimeRestart: true, + }); - let firstTerminal: string | null = null; - while (firstTerminal === null) { - const event = yield* Queue.take(events); - if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { - firstTerminal = event.status; + let subagentStatus: string | null = null; + let firstTerminalStatus: string | null = null; + while (firstTerminalStatus === null) { + const event = yield* Queue.take(events); + if (event.type === "turn_item.updated" && event.turnItem.type === "subagent") { + subagentStatus = event.turnItem.status; + } + if (event.type === "turn.terminal" && event.providerTurnId === firstProviderTurnId) { + firstTerminalStatus = event.status; + } } - } - assert.equal(firstTerminal, "interrupted"); + assert.equal(firstTerminalStatus, "interrupted"); + assert.equal(subagentStatus, "interrupted"); - yield* Queue.takeAll(protocolEvents); - yield* runtime - .startTurn( + subagentPhase = "complete"; + const secondNow = yield* DateTime.now; + yield* runtime.startTurn( makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, - now, + now: secondNow, ordinal: 2, }), - ) - .pipe(Effect.forkScoped); - let loadSeen = false; - let promptSeen = false; - while (!loadSeen || !promptSeen) { - const event = yield* Queue.take(protocolEvents); - if (event.direction !== "outgoing") continue; - const method = rawProtocolMethod(event); - loadSeen ||= method === "session/resume"; - promptSeen ||= method === "session/prompt"; - } - assert.isTrue(loadSeen, "restart_active must replay session/resume on a new ACP process"); - assert.isTrue(promptSeen, "replacement prompt must start after reload"); - const secondProviderTurnId = idAllocator.derive.providerTurn({ - driver: ACP_TEST_DRIVER, - nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), - }); - let staleEventSeen = false; - let secondTerminal: string | null = null; - while (secondTerminal === null) { - const event = yield* Queue.take(events); - if ( - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === "tool-call-running-1" - ) { - staleEventSeen = true; - } - if ( - event.type === "message.updated" && - event.message.role === "assistant" && - event.message.text.includes("late after cancel") - ) { - staleEventSeen = true; - } - if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { - secondTerminal = event.status; + ); + const secondProviderTurnId = idAllocator.derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId(instanceId, "mock-session-1:turn:2"), + }); + let carriedCompleted = false; + let secondTerminalStatus: string | null = null; + while (secondTerminalStatus === null) { + const event = yield* Queue.take(events); + if ( + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.status === "completed" + ) { + carriedCompleted = true; + } + if (event.type === "turn.terminal" && event.providerTurnId === secondProviderTurnId) { + secondTerminalStatus = event.status; + } } - } - assert.equal(secondTerminal, "completed"); - assert.isFalse(staleEventSeen, "interrupted runtime events must not attach to attempt 2"); - }).pipe(Effect.provide(layerTest), Effect.scoped), + assert.equal(secondTerminalStatus, "completed"); + assert.isFalse( + carriedCompleted, + "Direct Stop must not carry a stopped subagent into the follow-up run", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), ); }); -describe("acpPostSettleWakeEvidence", () => { - const sessionId = "session-wake"; - - it("accepts assistant text and tool updates as wake evidence", () => { - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Subagent finished. SUBAGENT_DONE" }, - }, - }), - ); - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call", - toolCallId: "call-1", - title: "get_command_or_subagent_output", - status: "pending", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - }); - - it("rejects monitor end chatter and background mutations", () => { - assert.isFalse( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { - type: "text", - text: 'Monitor "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" ended', - }, - }, - }), - ); - assert.isFalse( - acpPostSettleWakeEvidence( - { - sessionId, - update: { - sessionUpdate: "user_message_chunk", - content: { type: "text", text: "task-1 completed" }, - }, - }, - { - extractBackgroundToolMutation: () => [ - { - taskId: "task-1", - status: "completed", - appendOutput: "", - }, - ], - }, - ), - ); - }); -}); - describe("acpPostSettleContinuationOfferEvidence", () => { const sessionId = "session-wake-offer"; - it("offers on assistant text and terminal tool status", () => { - assert.isTrue( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Background shell finished." }, - }, - }), - ); - assert.isTrue( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-1", - title: "run_terminal_command", - status: "completed", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - assert.isTrue( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-2", - title: "run_terminal_command", - status: "failed", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - }); - - it("does not offer on thought-only chunks", () => { - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "Still reasoning about the monitor output…" }, - }, - }), - ); - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "agent_thought_chunk", - content: { type: "text", text: "Still reasoning about the monitor output…" }, - }, - }), - ); - }); - - it("does not offer on whitespace-only assistant chunks", () => { - const notification = { - sessionId, - update: { - sessionUpdate: "agent_message_chunk" as const, - content: { type: "text" as const, text: " \n\t " }, - }, - }; - assert.isFalse(acpPostSettleWakeEvidence(notification)); - assert.isFalse(acpPostSettleContinuationOfferEvidence(notification)); - }); - - it("buffers in-progress tool updates without offering", () => { - assert.isTrue( - acpPostSettleWakeEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-1", - title: "run_terminal_command", - status: "in_progress", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-1", - title: "run_terminal_command", - status: "in_progress", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "tool_call", - toolCallId: "call-1", - title: "run_terminal_command", - status: "pending", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - }), - ); - }); - - it("does not offer filtered monitor chatter", () => { - assert.isFalse( - acpPostSettleContinuationOfferEvidence({ - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { - type: "text", - text: 'Monitor "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" ended', - }, - }, - }), - ); - }); - it("does not offer on a normalized monitor start ACK despite raw completed status", () => { const monitorStartAck = { sessionId, @@ -14194,74 +7319,3 @@ describe("acpPostSettleContinuationOfferEvidence", () => { ); }); }); - -describe("acpPostSettleWakeShouldBuffer", () => { - const sessionId = "session-wake-buffer"; - - it("drops agent progress chatter while background work is running", () => { - for (const sessionUpdate of ["agent_message_chunk", "agent_thought_chunk"] as const) { - assert.isFalse( - acpPostSettleWakeShouldBuffer( - { - sessionId, - update: { - sessionUpdate, - content: { type: "text", text: "Still running." }, - }, - }, - true, - ), - ); - } - }); - - it("retains tool state while running and agent output after completion", () => { - const agentMessage = { - sessionId, - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "Monitor finished successfully." }, - }, - } as const; - const toolUpdate = { - sessionId, - update: { - sessionUpdate: "tool_call_update", - toolCallId: "call-monitor", - title: "monitor", - status: "in_progress", - kind: "other", - content: [], - locations: [], - rawInput: {}, - }, - } as const; - - assert.isTrue(acpPostSettleWakeShouldBuffer(toolUpdate, true)); - assert.isTrue(acpPostSettleWakeShouldBuffer(agentMessage, false)); - }); -}); - -describe("acpIsAppOwnedWakeTurn", () => { - it("recognizes only the orchestrator-injected app-owned wake", () => { - assert.isTrue(acpIsAppOwnedWakeTurn({ createdBy: "agent", creationSource: "server" })); - assert.isFalse(acpIsAppOwnedWakeTurn({ createdBy: "agent", creationSource: "provider" })); - assert.isFalse(acpIsAppOwnedWakeTurn({ createdBy: "user", creationSource: "web" })); - assert.isFalse(acpIsAppOwnedWakeTurn({ createdBy: "user", creationSource: "mcp" })); - assert.isFalse(acpIsAppOwnedWakeTurn({ createdBy: "user", creationSource: "server" })); - }); -}); - -describe("acpPostSettleMonitorPromptShouldSuppress", () => { - it("suppresses running monitor prompts but not terminal notices", () => { - assert.isTrue( - acpPostSettleMonitorPromptShouldSuppress({ taskId: "task-active", status: "running" }), - ); - assert.isFalse( - acpPostSettleMonitorPromptShouldSuppress({ taskId: "task-ended", status: "completed" }), - ); - assert.isFalse( - acpPostSettleMonitorPromptShouldSuppress({ taskId: "task-failed", status: "failed" }), - ); - }); -}); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts index 421cc95924553..bb74f75bd3463 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts @@ -1,8 +1,19 @@ import { + MessageId, + type ModelSelection, + NodeId, + ProjectId, + type ProviderInstanceId, + RunAttemptId, + RunId, + type OrchestrationV2ProviderThread, + type ThreadId, ProviderDriverKind, ProviderReplayEntry, type ProviderReplayTranscript, } from "@t3tools/contracts"; +import type * as DateTime from "effect/DateTime"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as Effect from "effect/Effect"; import * as Crypto from "effect/Crypto"; import * as FileSystem from "effect/FileSystem"; @@ -181,6 +192,7 @@ export function makeAcpReplayRuntime(input: { readonly scriptPath: string; readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly fileSystem: FileSystem.FileSystem; + readonly customModels?: AcpSessionRuntime.AcpSessionRuntimeOptions["customModels"]; readonly cancelMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["cancelMeta"]; readonly initializeMeta?: AcpSessionRuntime.AcpSessionRuntimeOptions["initializeMeta"]; readonly replayGate?: ProviderReplayGate; @@ -191,8 +203,7 @@ export function makeAcpReplayRuntime(input: { EffectAcpErrors.AcpError, Crypto.Crypto | Scope.Scope > { - // Recorded transcripts outgrow the kernel's 128 KiB limit on one environment - // variable, so the agent reads the transcript from a file beside its status. + // Transcripts exceed the kernel's 128 KiB per-environment-variable limit. const transcriptPath = `${input.statusPath}.transcript.json`; return (runtimeInput) => Effect.gen(function* () { @@ -222,6 +233,7 @@ export function makeAcpReplayRuntime(input: { }, }, authMethodId: "replay", + ...(input.customModels === undefined ? {} : { customModels: input.customModels }), ...(input.cancelMeta === undefined ? {} : { cancelMeta: input.cancelMeta }), ...(input.initializeMeta === undefined ? {} : { initializeMeta: input.initializeMeta }), ...(input.replayGate === undefined @@ -238,3 +250,66 @@ export function makeAcpReplayRuntime(input: { ); }); } + +export function makeTurnInput(input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly instanceId: ProviderInstanceId; + readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly now: DateTime.Utc; + readonly ordinal?: number; + readonly modelSelection?: ModelSelection; + readonly messageCreatedBy?: "user" | "agent"; + readonly messageCreationSource?: "web" | "mobile" | "mcp" | "provider" | "server"; + readonly messageText?: string; +}): ProviderAdapter.ProviderAdapterV2TurnInput { + const ordinal = input.ordinal ?? 1; + const suffix = `${input.threadId}:${ordinal}`; + const modelSelection = + input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const); + return { + appThread: { + createdBy: "user", + creationSource: "web", + id: input.threadId, + projectId: ProjectId.make(`project:${input.threadId}`), + title: "ACP adapter test", + providerInstanceId: input.instanceId, + modelSelection, + runtimeMode: "approval-required", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: input.providerThread.id, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: input.threadId, + }, + forkedFrom: null, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId: input.threadId, + runId: RunId.make(`run:${suffix}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt:${suffix}`), + rootNodeId: NodeId.make(`node:${suffix}`), + providerThread: input.providerThread, + message: { + createdBy: input.messageCreatedBy ?? "user", + creationSource: input.messageCreationSource ?? "web", + messageId: MessageId.make(`message:${suffix}`), + text: input.messageText ?? "test prompt", + attachments: [], + }, + modelSelection, + runtimePolicy: input.runtimePolicy, + }; +} diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 565a3cac2f1f8..fab0020b7e03e 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1,12 +1,26 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; -import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts"; +import { + MessageId, + NodeId, + ProjectId, + RunAttemptId, + RunId, + type ModelSelection, + ProviderInstanceId, + ProviderSessionId, + ThreadId, +} from "@t3tools/contracts"; +import { pendingBackgroundTurnItems } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -import * as Deferred from "effect/Deferred"; +import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; +import * as DateTime from "effect/DateTime"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; 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"; import * as HttpClient from "effect/http/HttpClient"; @@ -14,14 +28,15 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as EffectAcpErrors from "effect-acp/errors"; -import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; +import { + makeProviderReplayGate, + type ProviderReplayGate, +} from "@t3tools/provider-testing/replayGate"; +import type { ProviderContinuationRequest } from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as ServerSettings from "../../serverSettings.ts"; -import type { - AcpRegistryAvailableCommands, - AcpRegistryLiveConfiguration, -} from "@t3tools/provider-acp-registry/testing"; +import type { AcpRegistryLiveConfiguration } from "@t3tools/provider-acp-registry/testing"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; import { ACP_SESSION_MODE_OPTION_ID } from "@t3tools/provider-acp/server/sessionConfig"; @@ -31,17 +46,17 @@ import { decodeAcpReplayTranscript, makeAcpReplayCompletenessAssertion, makeAcpReplayRuntime, + makeTurnInput, } from "./AcpAdapterV2.testkit.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; -import { BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2 } from "../builtInProviderAdapterDrivers.ts"; import { AcpRegistryAdapterV2Driver } from "@t3tools/provider-acp-registry/server"; import { ACP_REGISTRY_PROVIDER, makeAcpRegistryAdapterV2, acpRegistryPromptFailure, + acpRegistryProbeResult, } from "@t3tools/provider-acp-registry/testing"; -const registryUrl = "https://registry.test/registry.json"; const decodeAcpRegistryAdapterSettings = Schema.decodeUnknownEffect( AcpRegistryAdapterV2Driver.configSchema, ); @@ -97,6 +112,305 @@ const layerTest = Layer.mergeAll( ServerSettings.layerTest(), ); +const CLAUDE_ROOT_SESSION = "claude-session"; + +/** Replay frames of Claude Agent (claude-agent-acp 0.90.0) on ACP v2. */ +const claudeFrames = { + open: [ + { type: "expect_outbound", frame: { kind: "request", method: "initialize", params: "" } }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "initialize", + result: { + protocolVersion: 2, + info: { name: "@agentclientprotocol/claude-agent-acp", version: "0.90.0" }, + capabilities: { session: {} }, + authMethods: [], + }, + }, + }, + { type: "expect_outbound", frame: { kind: "request", method: "session/new", params: "" } }, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/new", + result: { sessionId: CLAUDE_ROOT_SESSION }, + }, + }, + ], + update: (sessionId: string, sessionUpdate: Record) => ({ + type: "emit_inbound", + frame: { + kind: "notification", + method: "session/update", + params: { sessionId, update: sessionUpdate }, + }, + }), + childState: (parent: string, child: string, state: string) => + claudeFrames.update(parent, { + sessionUpdate: "subagent_update", + sessionId: child, + state: { state }, + }), + /** A prompt Claude takes in and works on. */ + prompt: (ordinal: number) => [ + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "user_message", + messageId: `user-${ordinal}`, + content: [{ type: "text", text: "test prompt" }], + }), + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + result: { messageId: `user-${ordinal}` }, + }, + }, + claudeFrames.update(CLAUDE_ROOT_SESSION, { sessionUpdate: "state_update", state: "running" }), + ], + idle: (stopReason: string) => + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "state_update", + state: "idle", + stopReason, + }), + closeRequest: { + type: "expect_outbound", + frame: { + kind: "request", + method: "session/close", + params: { sessionId: CLAUDE_ROOT_SESSION }, + }, + }, + closed: { + type: "emit_inbound", + frame: { kind: "response", method: "session/close", result: {} }, + }, +}; + +const openClaudeReplaySession = Effect.fn("openClaudeReplaySession")(function* ( + entries: ReadonlyArray, + replayGate?: ProviderReplayGate, + continuationEnabled = true, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const replayDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-lifecycle-" }); + const transcript = yield* decodeAcpReplayTranscript( + { + provider: ACP_REGISTRY_PROVIDER, + protocol: "acp.ndjson-jsonrpc", + version: "1", + scenario: "claude-lifecycle", + entries: entries as never, + }, + ACP_REGISTRY_PROVIDER, + ); + const offers: Array = []; + const offered = yield* Queue.unbounded(); + const continuationRequests = { + offer: (request: ProviderContinuationRequest) => + Effect.sync(() => { + offers.push(request); + }).pipe(Effect.andThen(Queue.offer(offered, undefined)), Effect.asVoid), + }; + const instanceId = ProviderInstanceId.make("claude-lifecycle"); + let onTermination: NonNullable< + AcpSessionRuntime.AcpSessionRuntimeOptions["onTermination"] + > = () => Effect.die("Runtime has not started"); + const replayRuntime = makeAcpReplayRuntime({ + transcript, + statusPath: path.join(replayDir, "status.json"), + scriptPath: yield* path.fromFileUrl( + new URL("../../../scripts/acp-replay-agent.ts", import.meta.url), + ), + childProcessSpawner, + fileSystem, + ...(replayGate === undefined ? {} : { replayGate }), + }); + const adapterOptions = { + selfInvocation: yield* resolveSelfInvocation(), + instanceId, + settings: yield* decodeAcpRegistryAdapterSettings({ agentId: "claude-acp" }), + environment: {}, + ...(continuationEnabled ? { continuationRequests } : {}), + makeRuntime: (runtimeInput: Parameters[0]) => { + onTermination = runtimeInput.onTermination; + return replayRuntime(runtimeInput); + }, + }; + const adapter = yield* makeAcpRegistryAdapterV2(adapterOptions).pipe( + Effect.provide(layerInjectedRuntimeCatalog), + ); + const threadId = ThreadId.make("thread-claude-lifecycle"); + const modelSelection = { instanceId, model: "default" } as const; + const runtimeMode = "approval-required"; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode, + interactionMode: "default", + cwd: replayDir, + }); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("session-claude-lifecycle"), + modelSelection, + runtimePolicy, + }); + yield* Effect.addFinalizer(() => Effect.sync(() => replayGate?.releaseAll())); + if (continuationEnabled) { + assert.isDefined( + runtime.hasPendingBackgroundWork, + "Claude ACP v2 must report background work after foreground idle", + ); + } + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const now = yield* DateTime.now; + const turnInput = ( + ordinal: number, + options: { readonly continuation?: boolean } = {}, + ): ProviderAdapter.ProviderAdapterV2TurnInput => ({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make(`project-claude-lifecycle`), + title: "Claude Agent", + providerInstanceId: instanceId, + modelSelection, + runtimeMode, + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make(`run-claude-lifecycle-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`attempt-claude-lifecycle-${ordinal}`), + rootNodeId: NodeId.make(`node-claude-lifecycle-${ordinal}`), + providerThread, + message: { + ...(options.continuation === true + ? { createdBy: "agent" as const, creationSource: "provider" as const } + : { createdBy: "user" as const, creationSource: "web" as const }), + messageId: MessageId.make(`message-claude-lifecycle-${ordinal}`), + text: "test prompt", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const until = (predicate: (event: ProviderAdapter.ProviderAdapterV2Event) => boolean) => + Effect.gen(function* () { + const seen: Array = []; + while (true) { + const event = yield* Queue.take(events); + seen.push(event); + if (predicate(event)) return seen; + } + }); + const throughMarker = (title: string) => + until( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.nativeMetadata?.title === title, + ); + const terminal = until((event) => event.type === "turn.terminal").pipe( + Effect.map((seen) => { + const event = seen.at(-1)!; + if (event.type !== "turn.terminal") throw new Error("Missing terminal"); + return event; + }), + ); + return { + runtime, + providerThread, + turnInput, + until, + throughMarker, + terminal, + offers, + offered, + terminate: () => + onTermination( + new EffectAcpErrors.AcpTransportError({ + detail: "Injected fixture process exit", + cause: "test", + }), + ), + }; +}); + +const claudeMarker = (title: string) => + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "session_info_update", + title, + }); +const claudeChild = [ + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "agent-1", + name: "Agent", + title: "Review", + kind: "think", + status: "in_progress", + rawInput: { prompt: "Review the code", description: "Review", run_in_background: true }, + }), + claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "running"), + claudeFrames.update("child-1", { + sessionUpdate: "session_message", + messageId: "agent-1", + senderSessionId: CLAUDE_ROOT_SESSION, + recipientSessionId: "child-1", + content: [{ type: "text", text: "Review the code" }], + }), + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "agent-1", + status: "completed", + _meta: { claudeCode: { toolResponse: { isAsync: true } } }, + }), +]; + +const claudeUnrelatedChildren = [ + claudeFrames.childState("unknown-parent", "unrelated-child", "running"), + claudeFrames.update("unrelated-child", { + sessionUpdate: "session_message", + messageId: "agent-1", + senderSessionId: "unknown-parent", + content: [{ type: "text", text: "Unrelated delegation" }], + }), + claudeFrames.update("unlinked-child", { + sessionUpdate: "agent_message_chunk", + messageId: "unlinked-reply", + content: { type: "text", text: "Unlinked output" }, + }), +]; + describe("AcpRegistryAdapterV2", () => { it("preserves and sanitizes structured ACP errors without exposing arbitrary defects", () => { const limit = new EffectAcpErrors.AcpRequestError({ @@ -125,22 +439,8 @@ describe("AcpRegistryAdapterV2", () => { assert.notInclude(rejected.message, "private-key"); assert.notInclude(rejected.message, "token=secret"); }); - it("is registered as a generic provider driver with schema defaults", () => { - assert.isTrue(BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2.has(ACP_REGISTRY_PROVIDER)); - assert.equal(AcpRegistryAdapterV2Driver.driverKind, ACP_REGISTRY_PROVIDER); - assert.deepEqual(AcpRegistryAdapterV2Driver.defaultConfig(), { - source: "registry", - commandArgs: [], - enabled: true, - agentId: "", - commandPath: "", - authMethodId: "", - distribution: "auto", - customModels: [], - }); - }); - describe("the agent's own mode picker", () => { + describe("the agent's own pickers", () => { type Frame = Record; const outbound = (method: string, params: unknown = ""): Frame => ({ type: "expect_outbound", @@ -159,16 +459,31 @@ describe("AcpRegistryAdapterV2", () => { options: ["ask", "auto"].map((value) => ({ value, name: value })), }); - const openWithStoredModePick = Effect.fn("openWithStoredModePick")(function* (input: { + const openWithStoredPicks = Effect.fn("openWithStoredPicks")(function* (input: { readonly setup: unknown; - readonly modeFrames: ReadonlyArray; - readonly storedModePick: string; + readonly pickFrames: ReadonlyArray; + readonly customModels?: ReadonlyArray; + readonly storedModel?: string; + readonly storedModePick?: string; + readonly turnModels?: ReadonlyArray; }) { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // Scope release gives the replay agent at most a second to exit, so the status + // read below waits for the agent itself instead of racing its last write. + const agentExits: Array> = []; + const childProcessSpawner = ChildProcessSpawner.make((command) => + spawner + .spawn(command) + .pipe( + Effect.tap((handle) => + Effect.sync(() => agentExits.push(Effect.ignore(handle.exitCode))), + ), + ), + ); const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const replayDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-acp-registry-mode-pick-", + prefix: "t3-acp-registry-stored-picks-", }); const statusPath = path.join(replayDir, "status.json"); const transcript = yield* decodeAcpReplayTranscript( @@ -176,7 +491,7 @@ describe("AcpRegistryAdapterV2", () => { provider: ACP_REGISTRY_PROVIDER, protocol: "acp.ndjson-jsonrpc", version: "1", - scenario: "stored-mode-pick", + scenario: "stored-picks", entries: [ outbound("initialize"), answer("initialize", { @@ -186,21 +501,24 @@ describe("AcpRegistryAdapterV2", () => { }), outbound("session/new"), answer("session/new", { sessionId: "agent-session", ...(input.setup as object) }), - ...input.modeFrames, + ...input.pickFrames, ] as never, }, ACP_REGISTRY_PROVIDER, ); - const instanceId = ProviderInstanceId.make("acp-registry-mode-pick"); + const instanceId = ProviderInstanceId.make("acp-registry-stored-picks"); + let published: AcpRegistryLiveConfiguration | undefined; const adapter = yield* makeAcpRegistryAdapterV2({ selfInvocation: yield* resolveSelfInvocation(), instanceId, settings: yield* decodeAcpRegistryAdapterSettings({ agentId: "fixture-agent", authMethodId: "test", + customModels: input.customModels ?? [], }), environment: {}, makeRuntime: makeAcpReplayRuntime({ + customModels: input.customModels, transcript, statusPath, scriptPath: yield* path.fromFileUrl( @@ -209,35 +527,97 @@ describe("AcpRegistryAdapterV2", () => { childProcessSpawner, fileSystem, }), - }).pipe(Effect.provide(layerInjectedRuntimeCatalog)); - yield* adapter - .openSession({ - threadId: ThreadId.make("thread-acp-registry-mode-pick"), - providerSessionId: ProviderSessionId.make("provider-session-mode-pick"), - modelSelection: { - instanceId, - model: "default", - options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }], - }, - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: replayDir, - }), - }) - .pipe(Effect.scoped); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerInjectedRuntimeCatalog, + Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({ + withForegroundStartup: (_startupKey, effect) => effect, + publishLiveConfiguration: (_instanceId, configuration) => + Effect.sync(() => { + published = configuration; + }), + }), + ), + ), + ); + const threadId = ThreadId.make("thread-acp-registry-stored-picks"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "approval-required", + interactionMode: "default", + cwd: replayDir, + }); + const stored: ModelSelection = { + instanceId, + model: input.storedModel ?? "default", + ...(input.storedModePick === undefined + ? {} + : { options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: input.storedModePick }] }), + }; + const configurations: Array = []; + yield* Effect.gen(function* () { + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-stored-picks"), + modelSelection: stored, + runtimePolicy, + }); + configurations.push(published); + if (input.turnModels === undefined) return; + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: stored, + runtimePolicy, + }); + const now = yield* DateTime.now; + let current = stored; + for (const [index, model] of input.turnModels.entries()) { + const target: ModelSelection = { instanceId, model }; + const plan = yield* adapter.planSelectionTransition({ + current, + target, + sessionCapabilities: runtime.providerSession.capabilities, + }); + assert.equal(plan.type, "apply_on_next_turn"); + yield* runtime.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: index + 1, + modelSelection: target, + }), + ); + yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type === "turn.terminal") { + assert.equal(event.status, "completed", event.failure?.message); + } + }), + ), + ); + configurations.push(published); + current = target; + } + }).pipe(Effect.scoped); + yield* Effect.all(agentExits, { discard: true }); yield* makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript); + return { configurations }; }); it.effect("switches an agent that only advertises modes with session/set_mode", () => - openWithStoredModePick({ + openWithStoredPicks({ setup: { modes: { currentModeId: "default", availableModes: ["default", "autoEdit"].map((id) => ({ id, name: id })), }, }, - modeFrames: [ + pickFrames: [ outbound("session/set_mode", { sessionId: "agent-session", modeId: "autoEdit" }), answer("session/set_mode", {}), ], @@ -246,9 +626,9 @@ describe("AcpRegistryAdapterV2", () => { ); it.effect("switches a mode config option under its own id", () => - openWithStoredModePick({ + openWithStoredPicks({ setup: { configOptions: [permissionModeOption("ask")] }, - modeFrames: [ + pickFrames: [ outbound("session/set_config_option", { sessionId: "agent-session", configId: "permission-mode", @@ -259,215 +639,1206 @@ describe("AcpRegistryAdapterV2", () => { storedModePick: "auto", }).pipe(Effect.provide(layerTest), Effect.scoped), ); + + const modelOption = (id: string, currentValue: string, grouped = false) => ({ + id, + name: "Model", + category: "model", + type: "select", + currentValue, + options: grouped + ? [{ group: "models", name: "Models", options: [{ value: "default", name: "Default" }] }] + : [{ value: "auto", name: "Auto" }], + }); + const configOptionUpdate = (configOptions: ReadonlyArray): Frame => ({ + type: "emit_inbound", + frame: { + kind: "notification", + method: "session/update", + params: { + sessionId: "agent-session", + update: { sessionUpdate: "config_option_update", configOptions }, + }, + }, + }); + const prompt = (...updates: ReadonlyArray): ReadonlyArray => [ + outbound("session/prompt"), + ...updates, + answer("session/prompt", { stopReason: "end_turn" }), + ]; + const setModel = (modelId: string): ReadonlyArray => [ + outbound("session/set_model", { sessionId: "agent-session", modelId }), + answer("session/set_model", {}), + ]; + + it.effect( + "discovers session models and switches through live model configuration changes", + () => + Effect.gen(function* () { + const flatOption = (current: string) => modelOption("live-model", current); + const groupedOption = (current: string) => + modelOption("replacement-model", current, true); + const { configurations } = yield* openWithStoredPicks({ + setup: { + models: { + currentModelId: "hermes", + availableModels: ["hermes", "auto", "default"].map((modelId) => ({ + modelId, + name: modelId, + })), + }, + }, + customModels: ["custom-model"], + storedModel: "default", + turnModels: [ + "hermes", + "custom-model", + "auto", + "default", + "hermes", + "custom-model", + "auto", + "custom-model", + "default", + "hermes", + ], + pickFrames: [ + ...setModel("default"), + ...setModel("hermes"), + ...prompt(), + ...setModel("custom-model"), + ...prompt(), + ...setModel("auto"), + ...prompt(), + ...setModel("default"), + ...prompt(), + ...setModel("hermes"), + ...prompt(configOptionUpdate([flatOption("hermes")])), + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "live-model", + value: "custom-model", + }), + answer("session/set_config_option", { configOptions: [flatOption("custom-model")] }), + ...prompt(), + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "live-model", + value: "auto", + }), + answer("session/set_config_option", { configOptions: [flatOption("auto")] }), + ...prompt(configOptionUpdate([groupedOption("auto")])), + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "replacement-model", + value: "custom-model", + }), + answer("session/set_config_option", { + configOptions: [groupedOption("custom-model")], + }), + ...prompt(), + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "replacement-model", + value: "default", + }), + answer("session/set_config_option", { configOptions: [groupedOption("default")] }), + ...prompt(configOptionUpdate([])), + ...setModel("hermes"), + ...prompt(), + ], + }); + assert.deepEqual( + configurations.map((configuration) => ({ + models: configuration?.models.map((model) => model.id), + current: configuration?.currentModelId, + })), + [ + { models: ["hermes", "auto", "default"], current: "default" }, + { models: ["hermes", "auto", "default"], current: "hermes" }, + { models: ["hermes", "auto", "default"], current: null }, + { models: ["hermes", "auto", "default"], current: "auto" }, + { models: ["hermes", "auto", "default"], current: "default" }, + { models: ["auto"], current: null }, + { models: ["auto"], current: null }, + { models: ["default"], current: null }, + { models: ["default"], current: null }, + { models: ["hermes", "auto", "default"], current: "default" }, + { models: ["hermes", "auto", "default"], current: "hermes" }, + ], + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + // regression: #19519 models come from session model state, not a hardcoded list + it.effect("leaves unadvertised model IDs alone in both model selection protocols", () => + Effect.gen(function* () { + const { configurations } = yield* openWithStoredPicks({ + setup: { + models: { + currentModelId: "hermes", + availableModels: ["hermes", "other"].map((modelId) => ({ modelId, name: modelId })), + }, + }, + storedModel: "default", + turnModels: [ + "auto", + "removed-model", + "other", + "default", + "auto", + "hermes", + "removed-model", + ], + pickFrames: [ + ...prompt(), + ...prompt(), + ...setModel("other"), + ...prompt( + configOptionUpdate([ + { + ...modelOption("live-model", "other"), + options: [{ value: "other", name: "Other" }], + }, + ]), + ), + ...prompt(), + ...prompt(), + ...prompt( + configOptionUpdate([ + { + ...modelOption("replacement-model", "other", true), + options: [ + { + group: "models", + name: "Models", + options: [{ value: "other", name: "Other" }], + }, + ], + }, + ]), + ), + ...prompt(), + ], + }); + assert.deepEqual( + configurations.map((configuration) => configuration?.currentModelId), + ["hermes", "hermes", "hermes", "other", "other", "other", "other", "other"], + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + const modelOptions = [ + { id: "fast", name: "Fast", category: "model", type: "boolean", currentValue: false }, + { + id: " ", + name: "Unnamed", + category: "model", + type: "select", + currentValue: "unaddressable", + options: [{ value: "unaddressable", name: "Unaddressable" }], + }, + { + id: "provider", + name: "Provider", + category: "model", + type: "select", + currentValue: "gateway", + options: [ + { + group: "hosted", + name: "Hosted", + options: [ + { value: "gateway", name: "Gateway" }, + { value: "codex", name: "Codex" }, + ], + }, + ], + }, + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "later-model", + options: [{ value: "later-model", name: "Later model" }], + }, + ] as const; + + it.effect("opens a model from the catalog by writing the first usable model select", () => + Effect.gen(function* () { + const setup = { sessionId: "agent-session", configOptions: modelOptions }; + const catalog = acpRegistryProbeResult(ProviderInstanceId.make("acp-registry-mode-pick"), { + sessionId: setup.sessionId, + initializeResult: { protocolVersion: 1 }, + sessionSetupResult: { + ...setup, + // The catalog uses the normalized groupId; ACP v1 sends group on the wire. + configOptions: modelOptions.map((option) => + option.id === "provider" + ? { + ...option, + options: [{ ...option.options[0], groupId: option.options[0].group }], + } + : option, + ), + }, + modelConfigId: "provider", + }); + assert.deepEqual(catalog.models, [ + { id: "gateway", name: "Gateway", description: null }, + { id: "codex", name: "Codex", description: null }, + ]); + assert.equal(catalog.currentModelId, "gateway"); + const model = catalog.models[1]?.id; + assert.isDefined(model); + const opened = yield* openWithStoredPicks({ + setup, + pickFrames: [ + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "provider", + value: "codex", + }), + answer("session/set_config_option", { + configOptions: modelOptions.map((option) => + option.id === "provider" ? { ...option, currentValue: "codex" } : option, + ), + }), + ], + storedModel: model, + }); + assert.equal(opened.configurations.at(-1)?.currentModelId, "codex"); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); }); - it.effect("offers client terminals to Devin only and client fs to no registry agent", () => + // regression: #21618 Claude Agent needs ACP v2 for native background lifecycle + it.effect("launches Claude Agent on ACP v2 unless its instance environment decides", () => Effect.gen(function* () { - const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const path = yield* Path.Path; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const advertisedCapabilities = Effect.fn("advertisedCapabilities")(function* ( - agentId: string, + const launchSwitch = Effect.fn("launchSwitch")(function* ( + config: Record, + environment: NodeJS.ProcessEnv = {}, ) { - let clientCapabilities: unknown; - const instanceId = ProviderInstanceId.make(`acp-registry-capabilities-${agentId}`); + let launched: NodeJS.ProcessEnv | undefined; + const instanceId = ProviderInstanceId.make("acp-registry-launch-environment"); const adapter = yield* makeAcpRegistryAdapterV2({ selfInvocation: yield* resolveSelfInvocation(), instanceId, - settings: yield* decodeAcpRegistryAdapterSettings({ agentId, authMethodId: "test" }), - environment: {}, - makeRuntime: (input) => - Effect.gen(function* () { - clientCapabilities = input.clientCapabilities; - const { processEnvironment: _processEnvironment, ...runtimeInput } = input; - const context = yield* Layer.build( - AcpSessionRuntime.layer({ - ...runtimeInput, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_SESSION_LIFECYCLE: "1" }, - }, - authMethodId: "test", - }).pipe( - Layer.provide( - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner), - ), - ), - ); - return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe( - Effect.provide(context), - ); + settings: yield* decodeAcpRegistryAdapterSettings(config), + environment, + }).pipe( + Effect.provide( + Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({ + resolve: (_settings, _cwd, launchEnvironment) => { + launched = launchEnvironment; + return Effect.fail( + new AcpRegistrySupport.AcpRegistryError({ + reason: "runner_unavailable", + detail: "Recorded the launch environment.", + }), + ); + }, }), - }).pipe(Effect.provide(layerInjectedRuntimeCatalog)); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), - }); - yield* adapter.openSession({ - threadId: ThreadId.make(`thread-acp-registry-capabilities-${agentId}`), - providerSessionId: ProviderSessionId.make(`provider-session-capabilities-${agentId}`), - modelSelection: { instanceId, model: "default" }, - runtimePolicy, - }); - return clientCapabilities; + ), + ); + yield* adapter + .openSession({ + threadId: ThreadId.make("thread-acp-registry-launch-environment"), + providerSessionId: ProviderSessionId.make("provider-session-launch-environment"), + modelSelection: { instanceId, model: "default" }, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }), + }) + .pipe(Effect.flip); + return launched?.CLAUDE_AGENT_ACP_EXPERIMENTAL_V2; }); - assert.deepInclude(yield* advertisedCapabilities("devin"), { - fs: { readTextFile: false, writeTextFile: false }, - terminal: true, - }); - assert.deepInclude(yield* advertisedCapabilities("gemini"), { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - }); + assert.equal(yield* launchSwitch({ agentId: "claude-acp" }), "1"); + assert.equal( + yield* launchSwitch( + { source: "local", commandPath: "/opt/bin/claude-agent-acp" }, + { PATH: "/opt/bin" }, + ), + "1", + ); + assert.equal( + yield* launchSwitch({ agentId: "claude-acp" }, { CLAUDE_AGENT_ACP_EXPERIMENTAL_V2: "0" }), + "0", + ); + assert.isUndefined(yield* launchSwitch({ agentId: "gemini" })); + const fallback = yield* openClaudeReplaySession( + [ + ...claudeFrames.open, + claudeFrames.prompt(1)[0], + claudeChild[0], + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "agent-1", + status: "completed", + }), + ...claudeFrames.prompt(1).slice(1), + claudeFrames.idle("end_turn"), + claudeFrames.closeRequest, + claudeFrames.closed, + ], + undefined, + false, + ); + assert.isUndefined( + fallback.runtime.hasPendingBackgroundWork, + "an adapter without a continuation dispatcher must use ordinary prompt completion", + ); + yield* fallback.runtime.startTurn(fallback.turnInput(1)); + const completed = yield* fallback.until((event) => event.type === "turn.terminal"); + assert.isTrue( + completed.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "agent-1", + ), + ); + 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), ); - it.effect("opens a real ACP child process resolved from registry configuration", () => + it.effect("settles Claude's accepted foreground reply while retaining child output", () => Effect.gen(function* () { - const path = yield* Path.Path; - const host = yield* ProviderHost.ProviderHost; - const mockAgentPath = yield* path.fromFileUrl( - new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), - ); - const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ - cacheDir: host.paths.providerStatusCacheDir, - toolsDir: host.paths.baseDir + "/tools", - registryUrl, - }); - const settings = yield* decodeAcpRegistryAdapterSettings({ - agentId: "fixture-agent", - commandPath: process.execPath, - authMethodId: "test", - }); - let startupActive = false; - let startupCount = 0; - const instanceId = ProviderInstanceId.make("acp-registry-fixture"); - const commandsPublished = yield* Deferred.make<{ - readonly instanceId: ProviderInstanceId; - readonly commands: AcpRegistryAvailableCommands; - }>(); - const configurationPublished = yield* Deferred.make(); - const adapter = yield* makeAcpRegistryAdapterV2({ - selfInvocation: yield* resolveSelfInvocation(), - instanceId, - settings, - environment: { - T3_ACP_SESSION_LIFECYCLE: "1", - T3_ACP_COMMAND_ADVERTISEMENT_DELAY_MS: "750", - }, - }).pipe( - Effect.provide( - Layer.mergeAll( - Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({ - withForegroundStartup: (agentId, effect) => - Effect.acquireUseRelease( - Effect.sync(() => { - assert.equal(agentId, "fixture-agent"); - startupActive = true; - startupCount += 1; - }), - () => effect, - () => - Effect.sync(() => { - startupActive = false; - }), - ), - runBackgroundProbe: (_agentId, effect) => effect.pipe(Effect.map(Option.some)), - withSessionMutation: (effect) => effect, - clearAvailableCommands: () => Effect.void, - publishAvailableCommands: (publishedInstanceId, commands) => - Deferred.succeed(commandsPublished, { - instanceId: publishedInstanceId, - commands, - }).pipe(Effect.asVoid), - getAvailableCommands: () => Effect.succeed(Option.none()), - watchAvailableCommands: () => Effect.never, - clearLiveConfiguration: () => Effect.void, - publishLiveConfiguration: (_publishedInstanceId, configuration) => - Deferred.succeed(configurationPublished, configuration).pipe(Effect.asVoid), - getLiveConfiguration: () => Effect.succeed(Option.none()), - watchLiveConfiguration: () => Effect.never, - requestUrlAuthentication: () => Effect.succeed(false), - acceptUrlAuthentication: () => Effect.succeed(false), - getUrlAuthAction: () => Effect.succeed(Option.none()), - watchUrlAuthAction: () => Effect.never, + const gate = makeProviderReplayGate(["accepted", "child-output", "wake"]); + const { update, idle, prompt } = claudeFrames; + const session = yield* openClaudeReplaySession( + [ + ...claudeFrames.open, + prompt(1)[0], + idle("end_turn"), + claudeMarker("before acceptance"), + { ...prompt(1)[1], label: "accepted" }, + ...prompt(1).slice(2), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "agent-1", + name: "Agent", + title: "Review", + kind: "think", + status: "pending", + rawInput: { description: "Review" }, + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "malformed-agent", + name: "Agent", + title: "Incomplete agent", + kind: "think", + status: "pending", + rawInput: { description: "Never receives a prompt" }, + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "failed-task", + name: "Task", + title: "Malformed task", + kind: "think", + status: "failed", + rawInput: { description: "Missing prompt" }, + }), + ...claudeChild.slice(0, 2), + update("child-1", { + sessionUpdate: "agent_message_chunk", + messageId: "early-reply", + content: { type: "text", text: "First review result." }, + }), + claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"), + ...claudeChild.slice(2), + update("child-1", { sessionUpdate: "state_update", state: "running" }), + ...claudeUnrelatedChildren, + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "agent_message_chunk", + messageId: "reply", + content: { type: "text", text: "The review is running." }, + }), + idle("end_turn"), + { + ...update("child-1", { + sessionUpdate: "agent_message_chunk", + messageId: "child-reply", + content: { type: "text", text: "Found the regression." }, }), - Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({ - resolve: (configuredSettings, cwd, environment) => - Effect.sync(() => assert.isTrue(startupActive)).pipe( - Effect.andThen(resolver.resolve(configuredSettings, cwd, environment)), - Effect.map((resolved) => ({ - ...resolved, - spawn: { - ...resolved.spawn, - args: [mockAgentPath], - }, - })), - ), + label: "child-output", + }, + update("child-1", { + sessionUpdate: "usage_update", + used: 2_500, + size: 10_000, + cost: { amount: 0.42, currency: "USD" }, + }), + update("child-1", { + sessionUpdate: "session_info_update", + title: "Child review", + updatedAt: "2026-10-19T00:00:00Z", + }), + update("child-1", { + sessionUpdate: "state_update", + state: "idle", + stopReason: "end_turn", + usage: { totalTokens: 3_000, inputTokens: 2_500, outputTokens: 500, thoughtTokens: 0 }, + }), + claudeMarker("child output"), + { + ...update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "user_message", + messageId: "wake-user", + content: [{ type: "text", text: "Continue the review." }], }), - ), - ), + label: "wake", + }, + idle("end_turn"), + claudeMarker("continuation idle"), + claudeFrames.closeRequest, + claudeFrames.closed, + ], + gate, ); - const threadId = ThreadId.make("thread-acp-registry-fixture"); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: process.cwd(), + yield* session.runtime.startTurn(session.turnInput(1)); + const beforeAcceptance = yield* session.throughMarker("before acceptance"); + assert.isFalse(beforeAcceptance.some((event) => event.type === "turn.terminal")); + gate.release("accepted"); + const foreground = yield* session.until((event) => event.type === "turn.terminal"); + const foregroundTerminal = foreground.at(-1)!; + if (foregroundTerminal.type !== "turn.terminal") + throw new Error("Missing foreground terminal"); + assert.equal(foregroundTerminal.status, "completed"); + const earlyResult = foreground.findLast( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ); + assert.isDefined(earlyResult, "a child can finish before its spawn acknowledgement"); + if (earlyResult?.type !== "subagent.updated") throw new Error("Missing early result"); + assert.equal(earlyResult.subagent.result, "First review result."); + const earlyItem = foreground.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.status === "completed", + ); + if (earlyItem?.type !== "turn_item.updated" || earlyItem.turnItem.type !== "subagent") + throw new Error("Missing early parent item"); + assert.equal(earlyItem.turnItem.result, "First review result."); + assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!); + gate.release("child-output"); + const childOutput = yield* session.throughMarker("child output"); + const message = childOutput.find( + (event) => + event.type === "message.updated" && event.message.text === "Found the regression.", + ); + assert.isDefined(message, "child output survives foreground completion"); + if (message?.type !== "message.updated") throw new Error("Missing child output"); + assert.notEqual(message.message.threadId, session.turnInput(1).threadId); + const childThreads = childOutput.flatMap((event) => + event.type === "provider_thread.updated" && + event.providerThread.appThreadId === message.message.threadId + ? [event.providerThread] + : [], + ); + assert.deepEqual( + childThreads.map((thread) => thread.contextUsage), + [ + { usedTokens: 2_500, maxTokens: 10_000, cost: { amount: 0.42, currency: "USD" } }, + { usedTokens: 2_500, maxTokens: 10_000, cost: { amount: 0.42, currency: "USD" } }, + { usedTokens: 3_000 }, + ], + ); + assert.deepEqual(childThreads.at(-1)?.nativeMetadata, { + title: "Child review", + updatedAt: "2026-10-19T00:00:00Z", }); - const modelSelection = { instanceId, model: "default" } as const; - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-acp-registry-fixture"), - modelSelection, - runtimePolicy, + assert.isFalse(childOutput.some((event) => event.type === "turn.terminal")); + assert.isTrue( + childOutput.some( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ), + ); + const latestChild = childOutput.findLast((event) => event.type === "subagent.updated"); + if (latestChild?.type !== "subagent.updated") throw new Error("Missing current child result"); + assert.equal(latestChild.subagent.result, "Found the regression."); + const rootItems = new Map( + [...foreground, ...childOutput].flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.threadId === session.turnInput(1).threadId + ? [[event.turnItem.id, event.turnItem] as const] + : [], + ), + ); + const generic = [...rootItems.values()].filter((item) => item.type === "dynamic_tool"); + assert.isFalse( + generic.some((item) => item.nativeItemRef?.nativeId === "agent-1"), + "native subagents never project a duplicate generic tool", + ); + const malformed = generic.find((item) => item.nativeItemRef?.nativeId === "malformed-agent"); + assert.isDefined(malformed, "unclassified tools still project on foreground completion"); + assert.equal(malformed?.status, "completed"); + const failed = generic.find((item) => item.nativeItemRef?.nativeId === "failed-task"); + assert.isDefined(failed, "unclassified terminal tools retain ordinary failures"); + assert.equal(failed?.status, "failed"); + assert.isFalse( + [...rootItems.values()].some((item) => item.type === "user_message"), + "the submitted root prompt is already owned by the app", + ); + assert.deepEqual(pendingBackgroundTurnItems({ turnItems: [...rootItems.values()] }), []); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + gate.release("wake"); + yield* Queue.take(session.offered); + yield* session.throughMarker("continuation idle"); + const offer = session.offers[0]!; + yield* offer.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + const continuation = yield* session.until((event) => event.type === "turn.terminal"); + const terminal = continuation.at(-1)!; + if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal"); + assert.equal( + terminal.status, + "completed", + "buffered acceptance preserves the latest live idle", + ); + assert.isFalse( + continuation.some( + (event) => event.type === "turn_item.updated" && event.turnItem.type === "user_message", + ), + "autonomous root echoes only signal acceptance", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect.each([ + { kind: "approval", stopReason: "end_turn", status: "completed" }, + { kind: "question", stopReason: "error", status: "failed" }, + ] as const)("continues Claude's background $kind and preserves $status idle", (testCase) => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["wake", "stop-request", "refused-response"]); + const method = + testCase.kind === "approval" ? "session/request_permission" : "elicitation/create"; + const params = + testCase.kind === "approval" + ? { + sessionId: "child-1", + title: "Run tests?", + subject: { + type: "tool_call", + toolCall: { + toolCallId: "test-command", + name: "Bash", + title: "Run tests", + kind: "execute", + status: "pending", + rawInput: { command: "vp test run" }, + }, + }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }], + } + : { + sessionId: "child-1", + mode: "form", + message: "Which file?", + requestedSchema: { + type: "object", + properties: { file: { type: "string", title: "File", enum: ["a.ts", "b.ts"] } }, + required: ["file"], + }, + }; + const session = yield* openClaudeReplaySession( + [ + ...claudeFrames.open, + ...claudeFrames.prompt(1), + ...claudeChild, + claudeFrames.idle("end_turn"), + { + ...claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "state_update", + state: "running", + }), + label: "wake", + }, + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "user_message", + messageId: "wake-user", + content: [{ type: "text", text: "Continue the review." }], + }), + claudeFrames.closeRequest, + { type: "emit_inbound", frame: { kind: "request", method, params } }, + { + type: "emit_inbound", + label: "refused-response", + frame: { + kind: "response", + method: "session/close", + error: { code: -32603, message: "Close refused" }, + }, + }, + { + type: "expect_outbound", + frame: { + kind: "response", + method, + result: + testCase.kind === "approval" + ? { outcome: { outcome: "selected", optionId: "allow" } } + : { action: "accept", content: { file: "a.ts" } }, + }, + }, + claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"), + ...claudeUnrelatedChildren, + claudeFrames.update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "state_update", + state: "idle", + stopReason: testCase.stopReason, + ...(testCase.status === "failed" + ? { error: { code: -32603, message: "API Error: 529 overloaded" } } + : {}), + }), + { + type: "emit_inbound", + label: "stop-request", + frame: { kind: "request", method, params }, + }, + claudeFrames.closeRequest, + claudeFrames.closed, + { + type: "expect_outbound", + frame: { + kind: "response", + method, + result: + testCase.kind === "approval" + ? { outcome: { outcome: "cancelled" } } + : { action: "cancel" }, + }, + }, + claudeMarker("detached request cancelled"), + ], + gate, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + assert.equal((yield* session.terminal).status, "completed"); + assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!); + gate.release("wake"); + yield* Queue.take(session.offered); + const offer = session.offers[0]!; + assert.isDefined(offer.dispatchIfCurrent); + yield* offer.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(2, { continuation: true })); + const started = yield* session.until( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + const running = started.at(-1)!; + if (running.type !== "provider_turn.updated") throw new Error("Missing active continuation"); + const closing = yield* session.runtime + .interruptTurn({ + providerThread: session.providerThread, + providerTurnId: running.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.addFinalizer(() => Effect.sync(() => gate.releaseAll())); + const seen = yield* session.until( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + ); + assert.isFalse( + seen.some( + (event) => event.type === "turn_item.updated" && event.turnItem.type === "user_message", + ), + ); + const request = seen.at(-1)!; + if (request.type !== "runtime_request.updated") throw new Error("Missing request"); + assert.isTrue( + seen.some( + (event) => + event.type === "node.updated" && + event.node.id === request.runtimeRequest.nodeId && + event.node.runId === session.turnInput(2).runId, + ), + ); + yield* Effect.promise(() => gate.waitForReached("refused-response")); + gate.release("refused-response"); + assert.isTrue(Exit.isFailure(yield* Fiber.join(closing))); + assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!); + yield* session.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + ...(testCase.kind === "approval" + ? { decision: "accept" as const } + : { answers: { file: "a.ts" } }), }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection, - runtimePolicy, + const terminal = yield* session.terminal; + assert.equal(terminal.status, testCase.status); + if (terminal.status === "failed") { + assert.include(terminal.failure?.message ?? "", "529 overloaded"); + assert.isUndefined(terminal.childTurnsContinue); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + } + gate.release("stop-request"); + yield* Queue.take(session.offered); + yield* session.runtime.interruptTurn({ + providerThread: session.providerThread, + providerTurnId: terminal.providerTurnId, + requestRuntimeRestart: true, }); + const cancelled = yield* session.throughMarker("detached request cancelled"); + assert.isFalse( + cancelled.some( + (event) => + event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending", + ), + "detached requests are cancelled before turn admission", + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); - assert.equal(runtime.providerSession.driver, "acpRegistry"); - assert.equal(startupCount, 1); - assert.isFalse(startupActive); - assert.equal(providerThread.nativeThreadRef?.nativeId, "mock-session-1"); - assert.equal(providerThread.nativeMetadata?.itemIdentityVersion, 2); - assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot); - assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread); - assert.deepEqual(yield* Deferred.await(commandsPublished), { - instanceId, - commands: { - slashCommands: [ + it.effect.each(["error", "end_turn"])( + "hands live Claude child tools to the next run after %s and keeps nested output in the child", + (stopReason) => + Effect.gen(function* () { + const { update, childState, idle, prompt } = claudeFrames; + const gate = makeProviderReplayGate(["nested-output", "nested-idle"]); + const session = yield* openClaudeReplaySession( + [ + ...claudeFrames.open, + ...prompt(1), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "agent-1", + name: "Agent", + title: "Review", + kind: "think", + status: "in_progress", + rawInput: { prompt: "Review the code", description: "Review" }, + }), + ...claudeChild.slice(1, -1), + update("child-1", { + sessionUpdate: "tool_call_update", + toolCallId: "child-tool", + name: "Bash", + title: "Read package", + kind: "execute", + status: "in_progress", + rawInput: { command: "cat package.json" }, + }), + update("child-1", { + sessionUpdate: "agent_message_chunk", + messageId: "progress", + content: { type: "text", text: "Review in progress." }, + }), + idle(stopReason), + ...prompt(2), + childState(CLAUDE_ROOT_SESSION, "child-1", "running"), + update("child-1", { + sessionUpdate: "session_message", + messageId: "resume-child", + senderSessionId: CLAUDE_ROOT_SESSION, + recipientSessionId: "child-1", + content: [{ type: "text", text: "Continue the review." }], + }), + claudeMarker("resumed"), + childState("child-1", "grandchild", "running"), + childState(CLAUDE_ROOT_SESSION, "child-1", "idle"), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "tool_call_update", + toolCallId: "agent-1", + name: "Agent", + status: "completed", + rawInput: { prompt: "Review the code", description: "Review" }, + }), + idle("end_turn"), { - name: "review", - description: "Review the current changes", - input: { hint: "focus" }, + ...update("grandchild", { + sessionUpdate: "terminal_update", + terminalId: "nested-terminal", + command: "/usr/bin/node /srv/t3/bin.ts acp-mcp-call orchestrator_capabilities {}", + }), + label: "nested-output", }, - ], - skills: [ + update("grandchild", { + sessionUpdate: "terminal_output_chunk", + terminalId: "nested-terminal", + data: Buffer.from("{}\n").toString("base64"), + }), + update("grandchild", { + sessionUpdate: "terminal_update", + terminalId: "nested-terminal", + exitStatus: { exitCode: 0 }, + }), + update("grandchild", { + sessionUpdate: "tool_call_update", + toolCallId: "terminal-tool", + name: "Bash", + title: "Run nested command", + kind: "execute", + status: "in_progress", + content: [{ type: "terminal", terminalId: "nested-terminal" }], + }), + update("grandchild", { + sessionUpdate: "tool_call_update", + toolCallId: "nested-tool", + name: "Bash", + title: "Read nested package", + kind: "execute", + status: "in_progress", + rawInput: { command: "cat nested/package.json" }, + }), + update("grandchild", { + sessionUpdate: "agent_message_chunk", + messageId: "nested-reply", + content: { type: "text", text: "Nested output" }, + }), + update(CLAUDE_ROOT_SESSION, { + sessionUpdate: "user_message", + messageId: "nested-wake", + content: [{ type: "text", text: "Continue the review." }], + }), + idle("end_turn"), + claudeMarker("nested"), { - name: "workspace-skill", - description: "Run the workspace skill", - path: "acp://skill/workspace-skill", - scope: "agent", - enabled: true, + ...childState("child-1", "grandchild", "idle"), + label: "nested-idle", }, + claudeMarker("nested idle"), + ...prompt(4), + update("child-1", { + sessionUpdate: "session_message", + messageId: "second-review", + senderSessionId: CLAUDE_ROOT_SESSION, + recipientSessionId: "child-1", + content: [{ type: "text", text: "Review the fix." }], + }), + childState(CLAUDE_ROOT_SESSION, "child-1", "running"), + update("child-1", { + sessionUpdate: "agent_message_chunk", + messageId: "nested-reply", + content: { type: "text", text: "The fix is correct." }, + }), + childState(CLAUDE_ROOT_SESSION, "child-1", "idle"), + idle("end_turn"), + claudeFrames.closeRequest, + claudeFrames.closed, ], - }, - }); - const configuration = yield* Deferred.await(configurationPublished); - assert.equal(configuration.currentModelId, "default"); - assert.deepInclude(configuration.models[0], { - id: "default", - name: "Auto", - description: null, + gate, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + const settled = yield* session.terminal; + assert.equal(settled.status, stopReason === "error" ? "failed" : "completed"); + if (settled.status === "failed") assert.isTrue(settled.childTurnsContinue); + yield* session.runtime.startTurn(session.turnInput(2)); + const resumed = yield* session.throughMarker("resumed"); + const row = resumed.find((event) => event.type === "subagent.updated"); + assert.isDefined(row); + if (row?.type !== "subagent.updated") throw new Error("Missing resumed child"); + assert.equal(row.subagent.runId, session.turnInput(2).runId); + assert.equal( + row.subagent.result, + "Review in progress.", + "live handoff retains current execution progress", + ); + assert.lengthOf( + resumed.filter( + (event) => + event.type === "message.updated" && + event.message.threadId === row.subagent.childThreadId && + event.message.role === "user" && + event.message.text === "Continue the review.", + ), + 1, + "child resume prompts remain visible once", + ); + const openTools = resumed.filter( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.status === "running", + ); + assert.lengthOf(openTools, 1, "handoff announces each open child tool once"); + const foreground = yield* session.until((event) => event.type === "turn.terminal"); + assert.isTrue( + foreground.some( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ), + "the foreground Agent tool terminalizes its visible owner", + ); + assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!); + gate.release("nested-output"); + const childOutput = yield* session.throughMarker("nested"); + yield* Queue.take(session.offered); + assert.lengthOf(session.offers, 1); + yield* session.offers[0]!.dispatchIfCurrent!(Effect.void); + yield* session.runtime.startTurn(session.turnInput(3, { continuation: true })); + const continued = yield* session.until((event) => event.type === "turn.terminal"); + const terminal = continued.at(-1)!; + if (terminal.type !== "turn.terminal") throw new Error("Missing continuation terminal"); + assert.equal(terminal.status, "completed"); + const nested = [...childOutput, ...continued]; + const messages = nested.filter( + (event) => event.type === "message.updated" && event.message.text === "Nested output", + ); + assert.lengthOf(messages, 1); + if (messages[0]?.type === "message.updated") { + assert.equal(messages[0].message.threadId, row.subagent.childThreadId); + } + const nestedTool = nested.find( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === + "agent-1:session:grandchild:tool:nested-tool", + ); + assert.isDefined(nestedTool); + if (nestedTool?.type === "turn_item.updated") { + assert.equal(nestedTool.turnItem.threadId, row.subagent.childThreadId); + if (nestedTool.turnItem.type === "dynamic_tool") + assert.deepEqual(nestedTool.turnItem.input, { command: "cat nested/package.json" }); + } + assert.isTrue( + nested.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === + "agent-1:session:grandchild:tool:terminal-tool" && + event.turnItem.threadId === row.subagent.childThreadId && + event.turnItem.toolName === "t3-code.orchestrator_capabilities", + ), + "embedded agent-terminal commands preserve nested MCP identity", + ); + assert.isTrue(yield* session.runtime.hasPendingBackgroundWork!); + gate.release("nested-idle"); + const finished = yield* session.throughMarker("nested idle"); + assert.isTrue( + finished.some( + (event) => event.type === "subagent.updated" && event.subagent.status === "completed", + ), + ); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + assert.lengthOf(session.offers, 1, "nested frames make progress in one continuation"); + const firstResult = finished.findLast((event) => event.type === "subagent.updated"); + if (firstResult?.type !== "subagent.updated") + throw new Error("Missing first review result"); + assert.equal( + firstResult.subagent.result, + "Review in progress.", + "reopening the visible owner for a running descendant keeps its execution result", + ); + yield* session.runtime.startTurn(session.turnInput(4)); + const reviewed = yield* session.until((event) => event.type === "turn.terminal"); + const currentResult = reviewed.findLast((event) => event.type === "subagent.updated"); + if (currentResult?.type !== "subagent.updated") + throw new Error("Missing second review result"); + assert.equal(currentResult.subagent.id, row.subagent.id); + assert.equal(currentResult.subagent.childThreadId, row.subagent.childThreadId); + assert.equal(currentResult.subagent.result, "The fix is correct."); + const currentItem = reviewed.findLast( + (event) => event.type === "turn_item.updated" && event.turnItem.type === "subagent", + ); + if (currentItem?.type !== "turn_item.updated" || currentItem.turnItem.type !== "subagent") + throw new Error("Missing current parent item"); + assert.equal(currentItem.turnItem.result, "The fix is correct."); + assert.lengthOf( + reviewed.filter( + (event) => + event.type === "message.updated" && event.message.text === "The fix is correct.", + ), + 1, + "a new execution does not append the previous execution's text", + ); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect("fails active Claude work and releases its children when the process exits", () => + Effect.gen(function* () { + const session = yield* openClaudeReplaySession([ + ...claudeFrames.open, + ...claudeFrames.prompt(1), + ...claudeChild, + claudeMarker("child ready"), + ]); + yield* session.runtime.startTurn(session.turnInput(1)); + yield* session.throughMarker("child ready"); + yield* session.terminate(); + const terminal = yield* session.terminal; + assert.equal(terminal.status, "failed"); + assert.equal(terminal.failure?.class, "transport_error"); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + const settled = yield* openClaudeReplaySession([ + ...claudeFrames.open, + ...claudeFrames.prompt(1), + ...claudeChild, + claudeFrames.childState("child-1", "grandchild", "running"), + claudeFrames.update("grandchild", { + sessionUpdate: "tool_call_update", + toolCallId: "nested-tool", + name: "Bash", + kind: "execute", + status: "in_progress", + rawInput: { command: "cat package.json" }, + }), + claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"), + claudeFrames.idle("end_turn"), + ]); + yield* settled.runtime.startTurn(settled.turnInput(1)); + const foreground = yield* settled.until((event) => event.type === "turn.terminal"); + const completed = foreground.at(-1)!; + if (completed.type !== "turn.terminal") throw new Error("Missing settled root terminal"); + assert.equal(completed.status, "completed"); + assert.isTrue(yield* settled.runtime.hasPendingBackgroundWork!); + yield* settled.terminate(); + assert.isFalse( + yield* settled.runtime.hasPendingBackgroundWork!, + "exit releases visible owners held open by nested work", + ); + const exited = yield* settled.until( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "subagent" && + event.turnItem.status === "failed", + ); + assert.isTrue( + exited.some( + (event) => event.type === "subagent.updated" && event.subagent.status === "failed", + ), + ); + const items = new Map( + [...foreground, ...exited].flatMap((event) => + event.type === "turn_item.updated" ? [[event.turnItem.id, event.turnItem] as const] : [], + ), + ); + assert.deepEqual(pendingBackgroundTurnItems({ turnItems: [...items.values()] }), []); + assert.isTrue( + exited.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.status === "interrupted", + ), + ); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect("keeps Claude activity after a refused Stop and closes it on retry", () => + Effect.gen(function* () { + const gate = makeProviderReplayGate(["close-response", "queued-close-response"]); + const session = yield* openClaudeReplaySession( + [ + ...claudeFrames.open, + ...claudeFrames.prompt(1), + ...claudeChild, + claudeMarker("before Stop"), + claudeFrames.closeRequest, + claudeFrames.update("child-1", { + sessionUpdate: "agent_message_chunk", + messageId: "closing-reply", + content: { type: "text", text: "Finished during close." }, + }), + claudeFrames.childState(CLAUDE_ROOT_SESSION, "child-1", "idle"), + claudeFrames.idle("end_turn"), + claudeMarker("idle during close"), + { + type: "emit_inbound", + label: "close-response", + frame: { + kind: "response", + method: "session/close", + error: { code: -32603, message: "Close refused" }, + }, + }, + ...claudeFrames.prompt(2), + claudeMarker("before retry"), + claudeFrames.closeRequest, + claudeFrames.idle("cancelled"), + claudeFrames.closed, + ], + gate, + ); + yield* session.runtime.startTurn(session.turnInput(1)); + const started = yield* session.throughMarker("before Stop"); + const running = started.findLast((event) => event.type === "provider_turn.updated"); + if (running?.type !== "provider_turn.updated") throw new Error("Missing active turn"); + const stop = { + providerThread: session.providerThread, + providerTurnId: running.providerTurn.id, + requestRuntimeRestart: true, + }; + const closing = yield* session.runtime + .interruptTurn(stop) + .pipe(Effect.exit, Effect.forkScoped); + yield* Effect.addFinalizer(() => Effect.sync(() => gate.releaseAll())); + const idle = yield* session.throughMarker("idle during close"); + gate.release("close-response"); + const refused = yield* Fiber.join(closing); + assert.isTrue(Exit.isFailure(refused), "a refused close must not report a successful Stop"); + const terminal = idle.findLast((event) => event.type === "turn.terminal"); + assert.equal( + terminal?.type === "turn.terminal" ? terminal.status : null, + "completed", + "idle during a refused close must settle the foreground turn", + ); + const result = idle.findLast((event) => event.type === "subagent.updated"); + if (result?.type !== "subagent.updated") throw new Error("Missing child close-time result"); + assert.equal(result.subagent.status, "completed"); + assert.equal(result.subagent.result, "Finished during close."); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + yield* session.runtime.startTurn(session.turnInput(2)); + const retry = yield* session.throughMarker("before retry"); + const retryRunning = retry.findLast((event) => event.type === "provider_turn.updated"); + if (retryRunning?.type !== "provider_turn.updated") + throw new Error("Missing active retry turn"); + yield* session.runtime.interruptTurn({ + ...stop, + providerTurnId: retryRunning.providerTurn.id, }); + assert.equal((yield* session.terminal).status, "interrupted"); + assert.isFalse(yield* session.runtime.hasPendingBackgroundWork!); + + const queued = yield* openClaudeReplaySession( + [ + ...claudeFrames.open, + { + type: "expect_outbound", + frame: { kind: "request", method: "session/prompt", params: "" }, + }, + claudeMarker("before queued Stop"), + claudeFrames.closeRequest, + { + type: "emit_inbound", + frame: { + kind: "response", + method: "session/prompt", + error: { code: -32800, message: "Request cancelled" }, + }, + }, + { ...claudeFrames.closed, label: "queued-close-response" }, + ], + gate, + ); + yield* queued.runtime.startTurn(queued.turnInput(3)); + const pending = yield* queued.throughMarker("before queued Stop"); + const queuedRunning = pending.findLast((event) => event.type === "provider_turn.updated"); + if (queuedRunning?.type !== "provider_turn.updated") + throw new Error("Missing queued provider turn"); + const queuedClosing = yield* queued.runtime + .interruptTurn({ + providerThread: queued.providerThread, + providerTurnId: queuedRunning.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + const queuedTerminal = yield* queued.terminal; + gate.release("queued-close-response"); + yield* Fiber.join(queuedClosing); + assert.equal(queuedTerminal.providerTurnId, queuedRunning.providerTurn.id); + assert.equal(queuedTerminal.status, "interrupted"); + assert.isNull(queuedTerminal.failure); + assert.isFalse(yield* queued.runtime.hasPendingBackgroundWork!); }).pipe(Effect.provide(layerTest), Effect.scoped), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 2ded59be7fc38..16d657bc192c6 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -11,6 +11,7 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; +import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -27,6 +28,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts"; +import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import { @@ -72,24 +74,6 @@ describe("AntigravityAdapterV2 flavor", () => { assert.isTrue(flavor.subagentsIdleOnTurnCompletion); }); - it("maps runtime modes to the agent's native permission modes", () => { - const mode = (runtimeMode: "approval-required" | "auto-accept-edits" | "full-access") => - flavor.sessionModeForPolicy?.( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode, - interactionMode: "default", - cwd: "/workspace", - }), - ); - assert.equal(mode("approval-required"), "default"); - assert.equal(mode("auto-accept-edits"), "auto_edit"); - assert.equal(mode("full-access"), "yolo"); - }); - - it("exposes Antigravity's /compact command through the v2 compaction path", () => { - assert.isTrue(flavor.supportsCompaction); - }); - it("routes interaction_* permission requests to the question card", () => { const question = flavor.extractPermissionQuestion?.( permissionRequest("interaction_1", [ @@ -113,17 +97,21 @@ describe("AntigravityAdapterV2 flavor", () => { ); }); - it("advertises only the approval decisions the request can honor", () => { - const options = flavor.approvalOptions?.( - permissionRequest("tool_1", [ - { optionId: "once", name: "Allow", kind: "allow_once" }, - { optionId: "deny", name: "Deny", kind: "reject_once" }, + it("keeps the question card to the agent's own options so a typed answer cannot be sent", () => { + const question = flavor.extractPermissionQuestion?.( + permissionRequest("interaction_2", [ + { optionId: "opt-main", name: "main", kind: "allow_once" }, + { optionId: "opt-dev", name: "dev", kind: "allow_once" }, ]), ); + assert.strictEqual(question?.question.allowCustomAnswer, false); assert.deepEqual( - options?.map((option) => option.decision), - ["accept", "decline", "cancel"], + question?.question.options.map((option) => option.value), + ["opt-main", "opt-dev"], ); + assert.deepEqual(question?.respond({ interaction_2: "opt-dev" }), { + outcome: { outcome: "selected", optionId: "opt-dev" }, + }); }); }); @@ -406,107 +394,282 @@ describe("AntigravityAdapterV2 workspace changes", () => { ); }); -describe("AntigravityAdapterV2 client file system under restrictive policies", () => { - it.effect("serves in-workspace reads and writes and still refuses outside paths", () => +describe("AntigravityAdapterV2 html_render pages", () => { + it.effect("shows the page html_render published when the agent reports only a summary", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const crypto = yield* Crypto.Crypto; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; - const policies = [ - { - name: "read-only sandbox", - policy: { - runtimeMode: "full-access", - approvalPolicy: "never", - sandboxPolicy: { type: "readOnly" }, - }, - }, - { name: "approval-required", policy: { runtimeMode: "approval-required" } }, - ] as const; - for (const { name, policy } of policies) { - let readTextFile: Parameters[0] | undefined; - let writeTextFile: Parameters[0] | undefined; - const instanceId = ProviderInstanceId.make(`antigravity-restrictive-${policy.runtimeMode}`); - const adapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => - makeAntigravityAcpRuntime({ - ...input, - childProcessSpawner, - spawn: { - command: process.execPath, - args: [mockAgentPath], - cwd: input.cwd, - env: { T3_ACP_ANTIGRAVITY: "1" }, - }, - }).pipe( - Effect.provideService(Crypto.Crypto, crypto), - Effect.map((runtime): RuntimeService => ({ - ...runtime, - handleReadTextFile: (handler) => - Effect.sync(() => { - readTextFile = handler; - }).pipe(Effect.andThen(runtime.handleReadTextFile(handler))), - handleWriteTextFile: (handler) => - Effect.sync(() => { - writeTextFile = handler; - }).pipe(Effect.andThen(runtime.handleWriteTextFile(handler))), - })), - ), - withProcess: (_stop, task) => task, - defaultModel: Effect.succeed(undefined), - }); - const workspace = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-ag-restrictive-", - }); - const outside = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-ag-restrictive-outside-", - }); - yield* fileSystem.writeFileString(path.join(workspace, "existing.ts"), "existing"); - const threadId = ThreadId.make(`thread-antigravity-restrictive-${policy.runtimeMode}`); - const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - ...policy, - interactionMode: "default", - cwd: workspace, - }); - const modelSelection = { instanceId, model: "gemini-test-low" } as const; - const session = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - `provider-session-antigravity-restrictive-${policy.runtimeMode}`, + let sessionUpdate: Parameters[0] | undefined; + const instanceId = ProviderInstanceId.make("antigravity-html-render-test"); + const threadId = ThreadId.make("thread-antigravity-html-render"); + const page = (name: string) => ({ + attachmentId: `${threadId}-${name}-html`, + title: "Revenue", + height: 240, + }); + // Long enough that Antigravity bounds the html the adapter sees. + const rows = Array.from({ length: 500 }, (_, row) => `Row ${row}`); + const report = { html: `${rows.join("")}
`, title: "Revenue", height: 240 }; + const failed = { ...report, html: "

Revenue

" }; + const errored = { ...report, html: "

Revenue error

" }; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(Crypto.Crypto, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + // agy_acp_server 1.3/1.4 without a permission prompt: the call is + // titled "Running " and completes with the step's summary + // in place of the MCP result. + prompt: () => + Effect.gen(function* () { + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const calls = [ + ["published", report], + ["unpublished", { ...report, html: "

Costs

" }], + ["failed", failed], + ["error", errored], + ] as const; + for (const [toolCallId, rawInput] of calls) { + yield* send({ + sessionUpdate: "tool_call", + toolCallId, + title: "Running html_render", + kind: "other", + status: "in_progress", + rawInput, + }); + } + yield* mcpSessions.recordHtmlRender(threadId, report, page("report")); + yield* mcpSessions.recordHtmlRender(threadId, failed, page("failed")); + yield* mcpSessions.recordHtmlRender(threadId, errored, page("error")); + for (const [toolCallId, status] of [ + ["unpublished", "completed"], + ["failed", "failed"], + ["published", "completed"], + ["published", "completed"], + ] as const) { + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId, + status, + rawOutput: `Summary of ${toolCallId}`, + }); + } + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "error", + status: "completed", + rawOutput: { result: { isError: true, content: [] } }, + }); + for (const [name, rawInput] of [ + ["failed", failed], + ["error", errored], + ] as const) { + const toolCallId = `${name}-retry`; + yield* send({ + sessionUpdate: "tool_call", + toolCallId, + title: "Running html_render", + kind: "other", + status: "in_progress", + rawInput, + }); + yield* mcpSessions.recordHtmlRender(threadId, rawInput, page(toolCallId)); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: name, + status: name === "failed" ? "failed" : "completed", + rawOutput: + name === "failed" + ? "Summary of failed" + : { result: { isError: true, content: [] } }, + }); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId, + status: "completed", + rawOutput: `Summary of ${toolCallId}`, + }); + } + yield* mcpSessions.recordHtmlRender(threadId, report, page("replacement")); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "published", + status: "completed", + rawOutput: { htmlRender: page("replacement") }, + }); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "published", + status: "completed", + rawOutput: "Summary of published", + }); + return { stopReason: "end_turn" as const }; + }), + })), ), + withProcess: (_stop, task) => task, + defaultModel: Effect.succeed(undefined), + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-html-render"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + yield* session.startTurn({ + appThread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project-antigravity-html-render"), + title: "Antigravity html_render", + providerInstanceId: instanceId, modelSelection, - runtimePolicy, - }); - yield* session.ensureThread({ threadId, modelSelection, runtimePolicy }); - if (readTextFile === undefined || writeTextFile === undefined) { - return yield* Effect.die("Antigravity sessions must serve client file requests"); - } - const context = (method: string) => ({ requestId: `test-${method}`, method }); - const read = yield* readTextFile( - { sessionId: "mock-session-1", path: path.join(workspace, "existing.ts") }, - context("fs/read_text_file"), - ); - assert.equal(read.content, "existing", name); - const written = path.join(workspace, "src", "edited.ts"); - yield* writeTextFile( - { sessionId: "mock-session-1", path: written, content: "edited" }, - context("fs/write_text_file"), + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + threadId, + runId: RunId.make("run-antigravity-html-render"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-html-render"), + rootNodeId: NodeId.make("node-antigravity-html-render"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-html-render"), + text: "chart the revenue", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + const tool = (nativeId: string) => { + const event = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, ); - assert.equal(yield* fileSystem.readFileString(written), "edited", name); - const outsideWrite = yield* writeTextFile( - { sessionId: "mock-session-1", path: path.join(outside, "x.ts"), content: "x" }, - context("fs/write_text_file"), - ).pipe(Effect.exit); - assert.isTrue(Exit.isFailure(outsideWrite), name); - assert.isFalse(yield* fileSystem.exists(path.join(outside, "x.ts")), name); + if (event?.type !== "turn_item.updated" || event.turnItem.type !== "dynamic_tool") { + return undefined; + } + const item = event.turnItem; + return { + status: item.status, + toolName: item.toolName, + page: htmlRenderFromToolItem(item), + output: item.output, + }; + }; + + assert.deepEqual(tool("published"), { + status: "completed", + toolName: "t3-code.html_render", + page: page("replacement"), + output: { htmlRender: page("replacement") }, + }); + assert.deepEqual(tool("unpublished"), { + status: "completed", + toolName: "t3-code.html_render", + page: undefined, + output: "Summary of unpublished", + }); + assert.deepEqual(tool("failed"), { + status: "failed", + toolName: "t3-code.html_render", + page: undefined, + output: "Summary of failed", + }); + assert.deepEqual(tool("error"), { + status: "completed", + toolName: "t3-code.html_render", + page: undefined, + output: [], + }); + assert.deepEqual( + events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "published" && + event.turnItem.status === "completed" + ? [htmlRenderFromToolItem(event.turnItem)] + : [], + ), + [page("report"), page("report"), page("replacement"), page("replacement")], + ); + for (const name of ["failed-retry", "error-retry"]) { + assert.deepEqual(tool(name), { + status: "completed", + toolName: "t3-code.html_render", + page: page(name), + output: { htmlRender: page(name) }, + }); } + 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), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 62b2ec6eac11f..3ec304b0a9a59 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -81,10 +81,7 @@ export interface AntigravityAdapterV2Options { readonly continuationRequests?: Parameters[0]["continuationRequests"]; } -/** - * ACP 1.1.1 exposes subagent invocations as ordinary `start_subagent` tools without child - * session ids. - */ +/** ACP 1.1.1 reports `start_subagent` tools without child session ids. */ const extractAntigravitySubagentUpdate: NonNullable = ( toolCall, ) => { @@ -120,8 +117,8 @@ export function makeAntigravityAcpAdapterFlavor( ): AcpAdapterV2Flavor { const antigravityClientFileRoots = (cwd: string | null) => cwd === null ? [options.host.paths.attachmentsDir] : [cwd, options.host.paths.attachmentsDir]; - const makeRuntime = (input: AcpAdapterV2RuntimeInput) => - Effect.gen(function* () { + const makeRuntime = Effect.fn("AntigravityAdapterV2.makeRuntime")( + function* (input: AcpAdapterV2RuntimeInput) { const scope = yield* Scope.fork(yield* Effect.scope); const runtime = yield* options .withProcess( @@ -144,36 +141,37 @@ export function makeAntigravityAcpAdapterFlavor( ), ), }; - }).pipe( - Effect.provideService(Crypto.Crypto, options.crypto), - Effect.mapError((cause): EffectAcpErrors.AcpError => - cause._tag === "ProviderSetupError" - ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause }) - : cause, - ), - ); + }, + Effect.provideService(Crypto.Crypto, options.crypto), + Effect.mapError((cause): EffectAcpErrors.AcpError => + cause._tag === "ProviderSetupError" + ? new EffectAcpErrors.AcpTransportError({ detail: cause.detail, cause }) + : cause, + ), + ); return { driver: ANTIGRAVITY_PROVIDER, runtimeHarness: "Antigravity", capabilities: AntigravityProviderCapabilitiesV2, makeRuntime, - // Loading history replays every tool call; resume restores the session - // without the replay and is what the official client does. + // Loading history replays tool calls; resume avoids replay. preferResumeSession: true, subagentsIdleOnTurnCompletion: true, ...(options.onSessionEvent === undefined ? {} : { onSessionEvent: options.onSessionEvent }), - applyModelSelection: ({ runtime, modelSelection }) => - Effect.gen(function* () { - const defaultModel = yield* options.defaultModel; - return yield* applyAntigravityAcpModelSelection({ - runtime, - model: - modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model, - defaultModel, - mapError: (cause) => cause, - }); - }), + applyModelSelection: Effect.fn("AntigravityAdapterV2.applyModelSelection")(function* ({ + runtime, + modelSelection, + }) { + const defaultModel = yield* options.defaultModel; + return yield* applyAntigravityAcpModelSelection({ + runtime, + model: + modelSelection.model === ANTIGRAVITY_DEFAULT_MODEL ? undefined : modelSelection.model, + defaultModel, + mapError: (cause) => cause, + }); + }), sessionModeForPolicy: (policy) => antigravityPermissionMode(policy.runtimeMode), clientFileSystem: { readTextFile: (request, cwd) => @@ -196,16 +194,7 @@ export function makeAntigravityAcpAdapterFlavor( const question = extractAntigravityUserInputQuestion(request); if (question === undefined) return undefined; return { - question: { - id: question.id, - header: question.header, - question: question.question, - options: question.options.map((option) => ({ - label: option.label, - description: option.description, - })), - multiSelect: false, - }, + question, respond: (answers) => makeAntigravityUserInputResponse(request, answers), }; }, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index fb5e867af78aa..9dc129c7aa0d8 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -1,10 +1,12 @@ // @effect-diagnostics nodeBuiltinImport:off -- workflow fixtures use files and the fake Claude CLI uses Node streams import * as NodeEvents from "node:events"; import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeStream from "node:stream"; +import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; +import { beforeEach, vi } from "vite-plus/test"; + import type { Query as ClaudeQuery, SDKMessage, @@ -26,12 +28,14 @@ import { ChatAttachmentId, ChatFileAttachment, ChatImageAttachment, + CheckpointId, ClaudeSettings, EnvironmentId, MessageId, type ModelSelection, NodeId, type OrchestrationV2AppThread, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ProviderThread, ProjectId, ProviderInstanceId, @@ -46,7 +50,6 @@ import { ThreadId, } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; -import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -58,9 +61,9 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; -import * as Scheduler from "effect/Scheduler"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -101,6 +104,19 @@ import { projectionFor, } from "../testkit/fixtures/shared.ts"; +vi.mock("@anthropic-ai/claude-agent-sdk", async (importOriginal) => ({ + ...(await importOriginal()), + resolveSettings: vi.fn(), +})); + +beforeEach(() => { + vi.mocked(ClaudeSdk.resolveSettings).mockReset().mockResolvedValue({ + effective: {}, + provenance: {}, + sources: [], + }); +}); + const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({}); const AUTO_COMPACT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({ autoCompactWindow: "300000", @@ -216,47 +232,6 @@ function makeClaudeTestTurnInput(input: { } describe("ClaudeAdapterV2 runtime query policy", () => { - it.each([false, true])("requests thinking summaries with resume=%s", (resume) => { - const options = ClaudeAdapterV2.makeClaudeQueryOptions({ - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - nativeThreadId: "thinking-thread", - resume, - cwd: "/workspace", - }); - assert.deepEqual(options.thinking, { type: "adaptive", display: "summarized" }); - assert.equal(options.extraArgs?.["thinking-display"], "summarized"); - assert.include(options.settings, { showThinkingSummaries: true }); - }); - - it("preserves an explicit omitted thinking display", () => { - const options = ClaudeAdapterV2.makeClaudeQueryOptions({ - modelSelection: CLAUDE_TEST_MODEL_SELECTION, - nativeThreadId: "thinking-thread", - resume: false, - cwd: "/workspace", - settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs: "--thinking-display omitted" }, - }); - assert.isUndefined(options.thinking); - assert.equal(options.extraArgs?.["thinking-display"], "omitted"); - assert.notInclude(options.settings ?? {}, { showThinkingSummaries: true }); - }); - - it("does not enable thinking when the model option disables it", () => { - const options = ClaudeAdapterV2.makeClaudeQueryOptions({ - modelSelection: { - ...CLAUDE_TEST_MODEL_SELECTION, - model: "claude-haiku-4-5", - options: [{ id: "thinking", value: false }], - }, - nativeThreadId: "thinking-thread", - resume: false, - cwd: "/workspace", - }); - assert.isUndefined(options.thinking); - assert.isUndefined(options.extraArgs?.["thinking-display"]); - assert.include(options.settings, { alwaysThinkingEnabled: false }); - }); - it.each([ ["--permission-mode acceptEdits", "acceptEdits"], ["--dangerously-skip-permissions", "bypassPermissions"], @@ -275,34 +250,74 @@ describe("ClaudeAdapterV2 runtime query policy", () => { assert.isUndefined(options.extraArgs?.["dangerously-skip-permissions"]); }); - it("passes automatic compaction and resume-dialog controls to the SDK", () => { - const onUserDialog = async () => ({ - behavior: "completed" as const, - result: "continue" as const, + it("gives delegated children Claude's subagent prompt cache TTL", () => { + const lineage = (relationshipToParent: "fork" | "subagent" | null) => ({ + lineage: { + parentThreadId: null, + relationshipToParent, + rootThreadId: ThreadId.make("thread-root"), + }, }); + const env = { PATH: "/bin" }; + const ttl = (environment: NodeJS.ProcessEnv, ...args: Parameters) => + ClaudeAdapterV2.claudeQueryEnvironment(environment, lineage(...args), "5m") + .CLAUDE_CODE_PROMPT_CACHE_TTL; + assert.equal(ttl(env, "subagent"), "5m"); + assert.isUndefined(ttl(env, null)); + assert.isUndefined(ttl(env, "fork")); + assert.equal(ttl({ ...env, CLAUDE_CODE_PROMPT_CACHE_TTL: "1h" }, "subagent"), "1h"); + assert.strictEqual( + ClaudeAdapterV2.claudeQueryEnvironment(env, lineage("subagent"), undefined), + env, + ); + }); + + it("pins Claude's auto tool search on through flag settings", () => { + const override = ClaudeAdapterV2.claudeToolSearchOverride; + for (const value of ["auto", "auto:10", "auto:99.5", "auto:x", "auto:Infinity"]) { + assert.equal(override(value), "true", value); + } + for (const value of [ + undefined, + "true", + "false", + "auto:0", + "auto:-5", + "auto:100", + "auto:1e2", + "auto:1_000", + "auto:1,000", + "AUTO", + ]) { + assert.isUndefined(override(value), String(value)); + } + const options = ClaudeAdapterV2.makeClaudeQueryOptions({ modelSelection: CLAUDE_TEST_MODEL_SELECTION, - nativeThreadId: "native-thread-auto-compact", - resume: true, + nativeThreadId: "native-tool-search", + resume: false, cwd: "/workspace", - settings: AUTO_COMPACT_CLAUDE_SETTINGS, - onUserDialog, - supportedDialogKinds: ["resume_return"], + sdkSettings: { env: { OTHER: "kept" } }, + toolSearchOverride: "true", + }); + assert.deepEqual((options.settings as { env?: Record }).env, { + OTHER: "kept", + ENABLE_TOOL_SEARCH: "true", }); - - assert.equal((options.settings as { autoCompactWindow?: number }).autoCompactWindow, 300_000); - assert.equal(options.onUserDialog, onUserDialog); - assert.deepEqual(options.supportedDialogKinds, ["resume_return"]); }); it("projects AskUserQuestion input with question text as the answer key", () => { + const preview = "\n **Proposed change**\n\n```ts\n\tconst enabled = true;\n```\n "; assert.deepEqual( ClaudeAdapterV2.claudeUserInputQuestions({ questions: [ { header: "Approach", question: "Which approach?", - options: [{ label: "Simple", description: "Use fewer moving parts" }], + options: [ + { label: "Simple", description: "Use fewer moving parts", preview }, + { label: "Safe", description: "Keep the current setup" }, + ], multiSelect: true, }, ], @@ -312,7 +327,10 @@ describe("ClaudeAdapterV2 runtime query policy", () => { id: "Which approach?", header: "Approach", question: "Which approach?", - options: [{ label: "Simple", description: "Use fewer moving parts" }], + options: [ + { label: "Simple", description: "Use fewer moving parts", preview }, + { label: "Safe", description: "Keep the current setup" }, + ], multiSelect: true, }, ], @@ -331,27 +349,6 @@ describe("ClaudeAdapterV2 runtime query policy", () => { ); }); - it("normalizes Claude todo and proposed-plan tool input", () => { - assert.deepEqual( - ClaudeAdapterV2.claudeTodoSteps({ - todos: [ - { content: "Inspect", status: "completed" }, - { content: "Implement", status: "in_progress" }, - ], - }), - [ - { id: "todo-0", text: "Inspect", status: "completed" }, - { id: "todo-1", text: "Implement", status: "running" }, - ], - ); - assert.equal( - ClaudeAdapterV2.claudeProposedPlan({ plan: " # Plan\nShip it " }), - "# Plan\nShip it", - ); - assert.isTrue(ClaudeAdapterV2.ClaudeProviderCapabilitiesV2.planning.emitsTodoList); - assert.isTrue(ClaudeAdapterV2.ClaudeProviderCapabilitiesV2.planning.emitsProposedPlan); - }); - it("maps canonical read-only never policy to Claude dontAsk with read-only tools", () => { const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ @@ -375,29 +372,6 @@ describe("ClaudeAdapterV2 runtime query policy", () => { }); }); - it("maps canonical read-only on-request policy to Claude default with callbacks", () => { - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - approvalPolicy: "on-request", - sandboxPolicy: { - type: "readOnly", - access: { type: "fullAccess" }, - networkAccess: false, - }, - }), - ); - - assert.deepEqual(queryPolicy, { - permissionMode: "default", - tools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS, - allowedTools: ClaudeAdapterV2.CLAUDE_READ_ONLY_ALLOWED_TOOLS, - installPermissionCallback: true, - }); - }); - it("does not auto-allow reads for canonical restricted read-only never policy", () => { const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ @@ -440,90 +414,45 @@ describe("ClaudeAdapterV2 runtime query policy", () => { }); }); - it("maps Auto runtime mode to Claude's AI-reviewed permission mode", () => { - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "auto", - interactionMode: "default", - cwd: "/workspace", - }), - ); - - assert.deepEqual(queryPolicy, { - permissionMode: "auto", - installPermissionCallback: false, - }); - }); - - it("keeps approval-required mode interactive with danger-full-access sandboxing", () => { - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: "/workspace", - sandboxPolicy: { - type: "dangerFullAccess", - }, - }), - ); - - assert.deepEqual(queryPolicy, { - permissionMode: "default", - installPermissionCallback: true, + it("keeps approval checks when Full access must fall back to an allowed Claude mode", () => { + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", + approvalPolicy: "never", }); - }); - it("installs the permission callback for approval-required plan mode", () => { - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "plan", - cwd: "/workspace", + assert.deepEqual( + ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy, { + bypassDisabled: true, + autoDisabled: false, }), + { permissionMode: "auto", installPermissionCallback: true }, ); - - assert.deepEqual(queryPolicy, { - permissionMode: "plan", - installPermissionCallback: true, - }); - }); - - it("honors never approvals for approval-required workspace-write policy", () => { - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "approval-required", - interactionMode: "default", - cwd: "/workspace", - approvalPolicy: "never", - sandboxPolicy: { - type: "workspaceWrite", - }, + assert.deepEqual( + ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy, { + bypassDisabled: true, + autoDisabled: true, }), + { permissionMode: "default", installPermissionCallback: true }, ); - - assert.deepEqual(queryPolicy, { - permissionMode: "dontAsk", - installPermissionCallback: false, - }); }); - it("honors never approvals for externally sandboxed policy", () => { + it("keeps approval-required mode interactive with danger-full-access sandboxing", () => { const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "approval-required", interactionMode: "default", cwd: "/workspace", - approvalPolicy: "never", sandboxPolicy: { - type: "externalSandbox", + type: "dangerFullAccess", }, }), ); assert.deepEqual(queryPolicy, { - permissionMode: "bypassPermissions", - allowDangerouslySkipPermissions: true, - installPermissionCallback: false, + permissionMode: "default", + installPermissionCallback: true, }); }); }); @@ -553,54 +482,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { browserToolsAvailable: true, }); - it("leaves an absent allowlist absent when no MCP session exists", () => { - const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({ - mcpSession: undefined, - readOnlySandbox: false, - }); - - assert.deepEqual(overrides, {}); - }); - - it("preserves an explicit allowlist when no MCP session exists", () => { - const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({ - mcpSession: undefined, - readOnlySandbox: false, - allowedTools: ["Read"], - }); - - assert.deepEqual(overrides, { allowedTools: ["Read"] }); - }); - - it("pre-approves all t3-code tools when attaching an MCP session without an allowlist", () => { - const threadId = ThreadId.make("thread-claude-mcp-no-allowlist"); - const mcpSession = mcpSessionFor(threadId); - const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({ - mcpSession, - readOnlySandbox: false, - }); - - assert.deepEqual(overrides, { - allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD], - mcpServers: T3_MCP_SERVERS, - }); - }); - - it("extends an explicit allowlist with the t3-code wildcard", () => { - const threadId = ThreadId.make("thread-claude-mcp-with-allowlist"); - const mcpSession = mcpSessionFor(threadId); - const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({ - mcpSession, - readOnlySandbox: false, - allowedTools: ["Read", "mcp__t3-code__*"], - }); - - assert.deepEqual(overrides, { - allowedTools: ["Read", "mcp__t3-code__*"], - mcpServers: T3_MCP_SERVERS, - }); - }); - it("pre-approves only read-only t3-code tools in a read-only sandbox", () => { const threadId = ThreadId.make("thread-claude-mcp-read-only"); const mcpSession = mcpSessionFor(threadId); @@ -620,50 +501,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD)); }); - it("pre-approves only read-only t3-code tools in a read-only sandbox without an allowlist", () => { - const threadId = ThreadId.make("thread-claude-mcp-read-only-no-allowlist"); - const mcpSession = mcpSessionFor(threadId); - const overrides = ClaudeAdapterV2.claudeMcpQueryOverrides({ - mcpSession, - readOnlySandbox: true, - }); - - assert.deepEqual(overrides.allowedTools, [ - ...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS, - ]); - }); - - it("keys live-query reuse on the MCP-derived pre-approvals", () => { - const threadId = ThreadId.make("thread-claude-mcp-query-key"); - const mcpSession = mcpSessionFor(threadId); - const queryPolicy = ClaudeAdapterV2.claudeRuntimeQueryPolicyForRuntimePolicy( - ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - approvalPolicy: "on-request", - sandboxPolicy: { - type: "readOnly", - access: { type: "fullAccess" }, - networkAccess: false, - }, - }), - ); - - const readOnlyKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey( - queryPolicy, - ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: true }), - ); - const fullAccessKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey( - queryPolicy, - ClaudeAdapterV2.claudeMcpQueryOverrides({ mcpSession, readOnlySandbox: false }), - ); - const detachedKey = ClaudeAdapterV2.claudeEffectiveQueryPolicyKey(queryPolicy, {}); - - assert.notEqual(readOnlyKey, fullAccessKey); - assert.notEqual(fullAccessKey, detachedKey); - }); - it("invalidates live-query reuse when MCP credentials rotate", () => { const threadId = ThreadId.make("thread-claude-mcp-credential-rotation"); const mcpSession = mcpSessionFor(threadId); @@ -763,180 +600,73 @@ describe("ClaudeAdapterV2 native protocol logging", () => { assert.equal(systemPrompt.type, "preset"); assert.equal(systemPrompt.preset, "claude_code"); assert.include(systemPrompt.append ?? "", "Use `delegate_task`"); + assert.include(systemPrompt.append ?? "", "call `t3_background_wait`"); const logged = ClaudeAdapterV2.loggedClaudeQueryOptions(options); assert.equal(logged.hasMcpServers, true); assert.notInclude(JSON.stringify(logged), "secret-claude-token"); }); - - it.effect("writes Claude Agent SDK protocol frames to the native provider log", () => - Effect.gen(function* () { - const writes: Array<{ - readonly event: unknown; - readonly threadId: ThreadId | null; - }> = []; - const logger: ProviderEventLoggers.EventNdjsonLogger = { - filePath: "/tmp/events.log", - write: (event, threadId) => - Effect.sync(() => { - writes.push({ event, threadId }); - }), - close: () => Effect.void, - }; - const threadId = ThreadId.make("thread-1"); - const providerSessionId = ProviderSessionId.make("provider-session-1"); - const protocolLogger = ClaudeAdapterV2.makeClaudeAgentSdkProtocolLogger({ - nativeEventLogger: logger, - threadId, - providerSessionId, - }); - - assert.notEqual(protocolLogger, undefined); - if (protocolLogger === undefined) { - return; - } - - yield* protocolLogger({ - direction: "incoming", - stage: "decoded", - payload: { - type: "stream_event", - uuid: "00000000-0000-0000-0000-000000000001", - session_id: "native-thread", - parent_tool_use_id: null, - event: { - type: "content_block_delta", - index: 0, - delta: { - type: "text_delta", - get text(): string { - throw new Error("streaming text must not be inspected"); - }, - }, - }, - }, - }); - yield* protocolLogger({ - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.interrupt", - }, - }); - - assert.equal(writes.length, 1); - assert.equal(writes[0]?.threadId, threadId); - assert.deepEqual(writes[0]?.event, { - provider: "claudeAgent", - protocol: ClaudeAdapterV2.CLAUDE_AGENT_SDK_QUERY_PROTOCOL, - kind: "protocol", - providerSessionId, - event: { - direction: "outgoing", - stage: "decoded", - payload: { - type: "query.interrupt", - }, - }, - }); - }), - ); - - it("logs query options without leaking environment values or callback functions", () => { - const options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions = { - model: "claude-sonnet-4-6", - tools: { - type: "preset", - preset: "claude_code", - }, - permissionMode: "default", - sessionId: "native-thread-1", - cwd: "/workspace", - env: { - ANTHROPIC_API_KEY: "secret", - }, - extraArgs: { - "append-system-prompt": "secret launch prompt", - }, - canUseTool: (_toolName, input, callbackOptions) => - Promise.resolve({ - behavior: "allow", - updatedInput: input, - toolUseID: callbackOptions.toolUseID, - decisionClassification: "user_temporary", - }), - }; - - assert.deepEqual(ClaudeAdapterV2.loggedClaudeQueryOptions(options), { - model: "claude-sonnet-4-6", - tools: { - type: "preset", - preset: "claude_code", - }, - permissionMode: "default", - sessionId: "native-thread-1", - cwd: "/workspace", - hasCanUseTool: true, - hasEnvironment: true, - hasExtraArgs: true, - }); - assert.notInclude( - JSON.stringify(ClaudeAdapterV2.loggedClaudeQueryOptions(options)), - "secret launch prompt", - ); - }); }); describe("ClaudeAdapterV2 context usage", () => { - it("projects assistant usage against the selected context window", () => { + it("dates cache expiry from the request start, not the response end", () => { const usage = ClaudeAdapterV2.claudeProviderTurnTokenUsage( { - input_tokens: 42_000, - cache_creation_input_tokens: 2_000, - cache_read_input_tokens: 5_000, - output_tokens: 1_000, + input_tokens: 1, + output_tokens: 1, + cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 300 }, }, CLAUDE_TEST_MODEL_SELECTION, - "2026-08-29T00:00:00.000Z", + "2026-08-29T00:03:00.000Z", + "", + DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"), ); + assert.strictEqual(usage.promptCacheExpiresAt, "2026-08-29T00:05:00.000Z"); + }); +}); - assert.deepEqual(usage, { - usedTokens: 50_000, - maxTokens: 200_000, - inputTokens: 49_000, - cachedInputTokens: 5_000, - outputTokens: 1_000, - reasoningOutputTokens: 0, - updatedAt: "2026-08-29T00:00:00.000Z", +describe("ClaudeAdapterV2 approval presentation", () => { + it("marks asks that full access could not auto-allow and keeps the CLI's reason", () => { + const presentation = ClaudeAdapterV2.claudeApprovalPresentation({ + permissionMode: "bypassPermissions", + prompt: 'Claude wants to run rm -r -- "$rr/$h"', + callbackOptions: { + decisionReason: "\u001b[33mDangerous rm on a path built from a variable\u001b[39m", + suppressAlwaysAllowRule: true, + }, + }); + assert.deepEqual(presentation, { + reason: "Dangerous rm on a path built from a variable", + fullAccessOverride: "provider_check", + options: [ + { decision: "decline", label: "Decline" }, + { decision: "accept", label: "Approve" }, + ], }); }); - it("reports the prompt cache TTL the response wrote", () => { - const ttlFor = (cache_creation: { - ephemeral_1h_input_tokens: number; - ephemeral_5m_input_tokens: number; - }) => - ClaudeAdapterV2.claudeProviderTurnTokenUsage( - { input_tokens: 1, output_tokens: 1, cache_creation }, - CLAUDE_TEST_MODEL_SELECTION, - "2026-08-29T00:00:00.000Z", - ).promptCacheTtlMs; + it("attributes a bypass ask to the user's ask rule when one matched", () => { + const presentation = ClaudeAdapterV2.claudeApprovalPresentation({ + permissionMode: "bypassPermissions", + prompt: "Claude wants to run git push", + callbackOptions: { + matchedAskRule: { source: "userSettings", toolName: "Bash", ruleContent: "git push:*" }, + }, + }); + assert.deepEqual(presentation, { fullAccessOverride: "ask_rule" }); + }); - assert.strictEqual( - ttlFor({ ephemeral_1h_input_tokens: 2_000, ephemeral_5m_input_tokens: 300 }), - 60 * 60_000, - ); - assert.strictEqual( - ttlFor({ ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 300 }), - 5 * 60_000, - ); - assert.strictEqual( - ttlFor({ ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 0 }), - undefined, - ); + it("adds nothing to ordinary approvals outside full access", () => { + const presentation = ClaudeAdapterV2.claudeApprovalPresentation({ + permissionMode: "default", + prompt: "Run make?", + callbackOptions: { decisionReason: "Run make?" }, + }); + assert.deepEqual(presentation, {}); }); }); describe("ClaudeAdapterV2 session permissions", () => { + // regression: #15892 an explicit user refusal must stay user_reject, not a tool failure it("keeps explicit user refusals classified as user_reject", () => { const result = ClaudeAdapterV2.permissionResultFromDecision({ toolName: "Bash", @@ -1119,10 +849,164 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => { ); }); +describe("ClaudeAdapterV2 append-system-prompt-file launch argument", () => { + const startTurnWithLaunchArgs = Effect.fnUntraced(function* (launchArgs: string, cwd: string) { + const fileSystem = yield* FileSystem.FileSystem; + const opened: Array = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: { ...DEFAULT_CLAUDE_SETTINGS, launchArgs }, + environment: {}, + attachmentsDir: yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-append-" }), + fileSystem, + path: yield* Path.Path, + crypto: yield* Crypto.Crypto, + idAllocator: yield* IdAllocator.IdAllocatorV2, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-append-file"), + open: (input) => + Effect.sync(() => { + opened.push(input.options); + return { + messages: Stream.never, + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }; + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd, + }); + const threadId = ThreadId.make("thread-claude-append-file"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-append-file"), + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CLAUDE_TEST_MODEL_SELECTION, + runtimePolicy, + }); + const exit = yield* runtime + .startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-append-file"), + text: "What is the sentinel?", + attachments: [], + runtimePolicy, + }), + ) + .pipe(Effect.exit); + return { exit, opened }; + }); + + const appendSystemPrompt = (options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined) => + (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), + ), + ), + ), + ); + + // regression: #20413 malformed append-system-prompt launch args fail before a query opens + it.effect.each([ + [ + "--append-system-prompt-file missing.md", + (cwd: string) => + new ClaudeAdapterV2.ClaudeAppendSystemPromptFileError({ + path: NodePath.join(cwd, "missing.md"), + }).message, + ], + [ + "--append-system-prompt-file", + () => + new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({ + flag: "--append-system-prompt-file", + }).message, + ], + [ + "--append-system-prompt-file=", + () => + new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({ + flag: "--append-system-prompt-file", + }).message, + ], + [ + "--append-system-prompt", + () => + new ClaudeAdapterV2.ClaudeAppendSystemPromptMissingValueError({ + flag: "--append-system-prompt", + }).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), + ), + ), + ), + ); +}); + describe("ClaudeAdapterV2 approval cancellation", () => { it.effect("observes an approval signal that was already aborted", () => Effect.gen(function* () { - const decision = yield* Deferred.make(); + const decision = yield* Deferred.make<{ + decision: ProviderApprovalDecision; + feedback?: string; + }>(); const controller = new AbortController(); controller.abort(); @@ -1131,29 +1015,7 @@ describe("ClaudeAdapterV2 approval cancellation", () => { controller.signal, ); - assert.equal(result, "cancel"); - }), - ); - - it.effect("removes the cancellation listener after approval resolves", () => - Effect.gen(function* () { - const decision = yield* Deferred.make(); - const controller = new AbortController(); - let removes = 0; - const removeEventListener = controller.signal.removeEventListener.bind(controller.signal); - controller.signal.removeEventListener = (...args) => { - removes += 1; - return removeEventListener(...args); - }; - const fiber = yield* Effect.forkChild( - ClaudeAdapterV2.awaitClaudeApprovalDecision(decision, controller.signal), - ); - yield* Effect.yieldNow; - yield* Deferred.succeed(decision, "accept"); - const result = yield* Fiber.join(fiber); - - assert.equal(result, "accept"); - assert.equal(removes, 1); + assert.deepEqual(result, { decision: "cancel" }); }), ); }); @@ -1228,52 +1090,107 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio }); describe("ClaudeAdapterV2 executable path", () => { - it.effect.each([ - { source: "the default", environment: [], hostEnvironment: {}, expected: undefined }, - { - source: "an instance opt-in", - environment: [{ name: "CLAUDE_CODE_ENABLE_TODO_TOOLS", value: "1", sensitive: false }], - hostEnvironment: {}, - expected: "1", - }, - { - source: "a host opt-in", - environment: [], - hostEnvironment: { CLAUDE_CODE_ENABLE_TODO_TOOLS: "1" }, - expected: "1", - }, - ])("expands the executable path and respects $source for task tools", (testCase) => + it.effect("follows a bare claude on Windows to the npm package executable", () => Effect.scoped( Effect.gen(function* () { - const path = yield* Path.Path; - const { executablePaths, taskToolEnvironment } = yield* captureSdkExecutablePaths( - "~/bin/claude", - testCase.environment, + const npmDir = "C:\\Users\\dev\\AppData\\Roaming\\npm"; + const packageExe = `${npmDir}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`; + const { executablePaths } = yield* captureSdkExecutablePaths("claude").pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(SpawnExecutableResolution, () => `${npmDir}\\claude.cmd`), + Effect.provideService(ClaudeExecutableFileCheck, (filePath) => filePath === packageExe), ); - assert.deepEqual(executablePaths, [path.join(NodeOS.homedir(), "bin", "claude")]); - assert.deepEqual(taskToolEnvironment, [testCase.expected]); + assert.deepEqual(executablePaths, [packageExe]); }), ).pipe( - Effect.provideService(HostProcess.Environment, testCase.hostEnvironment), Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); +}); - it.effect("follows a bare claude on Windows to the npm package executable", () => +describe("ClaudeAdapterV2 resumeThread", () => { + it.effect("fails for a transcript without messages so a fresh session replaces it", () => Effect.scoped( Effect.gen(function* () { - const npmDir = "C:\\Users\\dev\\AppData\\Roaming\\npm"; - const packageExe = `${npmDir}\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude.exe`; - const { executablePaths } = yield* captureSdkExecutablePaths("claude").pipe( - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => `${npmDir}\\claude.cmd`), - Effect.provideService(ClaudeExecutableFileCheck, (filePath) => filePath === packageExe), + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-empty-session-", + }); + const projectDir = path.join(configDir, "projects", "-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(projectDir, "native-thread-empty.jsonl"), + [ + `{"type":"last-prompt","lastPrompt":"hello","sessionId":"native-thread-empty"}`, + `{"type":"atis-latch","atis":"","sessionId":"native-thread-empty"}`, + `{"type":"cost-state","sessionId":"native-thread-empty","totalCostUSD":0}`, + "", + ].join("\n"), ); + yield* fileSystem.writeFileString( + path.join(projectDir, "native-thread-saved.jsonl"), + `{"type":"user","message":{"role":"user","content":"hello"},"sessionId":"native-thread-saved"}\n`, + ); + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CLAUDE_SETTINGS, + environment: { CLAUDE_CONFIG_DIR: configDir }, + attachmentsDir: configDir, + fileSystem, + path, + crypto: yield* Crypto.Crypto, + idAllocator: yield* IdAllocator.IdAllocatorV2, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-empty"), + open: () => Effect.die("unused"), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + const threadId = ThreadId.make("thread-claude-empty-session"); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-claude-empty-session"), + 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, + }); - assert.deepEqual(executablePaths, [packageExe]); + const error = yield* Effect.flip(runtime.resumeThread({ providerThread })); + assert.equal(error._tag, "ProviderAdapterResumeThreadError"); + + const saved = yield* runtime.resumeThread({ + providerThread: { + ...providerThread, + nativeThreadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: "native-thread-saved", + strength: "strong", + }, + }, + }); + assert.equal(saved.nativeThreadRef?.nativeId, "native-thread-saved"); + + const missing = yield* runtime.resumeThread({ + providerThread: { + ...providerThread, + nativeThreadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: "native-thread-missing", + strength: "strong", + }, + }, + }); + assert.equal(missing.nativeThreadRef?.nativeId, "native-thread-missing"); }), ).pipe( Effect.provide( @@ -1351,22 +1268,6 @@ describe("ClaudeAdapterV2 resume compaction", () => { assert.isFunction(callback); const canUseTool = openedOptions?.canUseTool; assert.isFunction(canUseTool); - const ordinaryToolResult = yield* Effect.promise(() => - canUseTool!( - "Bash", - { command: "pwd" }, - { - signal: new AbortController().signal, - toolUseID: "tool-bash-full-access", - requestId: "request-bash-full-access", - }, - ), - ); - assert.deepEqual(ordinaryToolResult, { - behavior: "allow", - updatedInput: { command: "pwd" }, - toolUseID: "tool-bash-full-access", - }); const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`; const questionRequestEvent = yield* runtime.events.pipe( Stream.filter((event) => event.type === "runtime_request.updated"), @@ -1510,265 +1411,207 @@ describe("ClaudeAdapterV2 resume compaction", () => { }); describe("ClaudeAdapterV2 attachments", () => { - it.effect("forwards images and references generic files on sends and steering", () => + it.effect.each([ + { + name: "ordinary text", + prompt: "What’s in this image?", + expectedText: "Ultrathink:\nWhat’s in this image?", + command: undefined, + ultrathink: true, + }, + { + name: "mid-sentence skill", + prompt: "please $implement fixes\n\nThen report the result", + expectedText: "Ultrathink:\nplease /implement fixes\n\nThen report the result", + command: "/implement fixes\n\nThen report the result", + ultrathink: true, + }, + { + name: "prompt-leading skill", + prompt: "$implement fixes", + expectedText: "/implement fixes", + command: undefined, + ultrathink: false, + }, + ])( + "preserves $name with images and files on sends and steering", + ({ prompt, expectedText, command, ultrathink }) => + 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 = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome }, + environment: {}, + attachmentsDir, + fileSystem, + path: yield* Path.Path, + crypto: yield* Crypto.Crypto, + idAllocator, + queryRunner: { + allocateSessionId: Effect.succeed("native-thread-claude-attachments"), + open: () => + Effect.succeed({ + messages: Stream.never, + offer: (message) => + Effect.sync(() => { + offeredMessages.push(message); + }), + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => 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]), + ); + yield* fileSystem.writeFile( + path.join(attachmentsDir, attachmentRelativePath(document)!), + Uint8Array.from([5, 6, 7, 8]), + ); + const attemptId = RunAttemptId.make("attempt-claude-attachments"); + const now = yield* DateTime.now; + + yield* runtime.startTurn( + makeClaudeTestTurnInput({ + threadId, + providerThread, + now, + attemptId, + modelSelection, + text: prompt, + attachments: [attachment, document], + }), + ); + + const expectedImageBlock = { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: "AQIDBA==", + }, + } 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}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`; + const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes }; + const expectedContent = command + ? [ + requestBlock, + expectedImageBlock, + { type: "text" as const, text: command + attachmentNotes }, + ] + : [expectedImageBlock, 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: [attachment, document], + }, + }); + + assert.equal(offeredMessages[1]?.priority, "now"); + assert.deepEqual(offeredMessages[1]?.message.content, expectedContent); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); +}); + +describe("ClaudeAdapterV2 native fork", () => { + it.effect("forks at the source assistant cursor and resumes the forked session", () => Effect.scoped( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; - const path = yield* Path.Path; const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-attachments-", + prefix: "t3-claude-v2-fork-attachments-", }); - const offeredMessages: Array = []; + const openedQueries: Array = []; + const forkCalls: Array = []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - crypto: yield* Crypto.Crypto, - idAllocator, - queryRunner: { - allocateSessionId: Effect.succeed("native-thread-claude-attachments"), - open: () => - Effect.succeed({ - messages: Stream.never, - offer: (message) => - Effect.sync(() => { - offeredMessages.push(message); - }), - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.void, - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => 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: 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 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]), - ); - yield* fileSystem.writeFile( - path.join(attachmentsDir, attachmentRelativePath(document)!), - Uint8Array.from([5, 6, 7, 8]), - ); - const attemptId = RunAttemptId.make("attempt-claude-attachments"); - const now = yield* DateTime.now; - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId, - text: "What's in this image?", - attachments: [attachment, document], - }), - ); - - const expectedImageBlock = { - type: "image", - source: { - type: "base64", - media_type: "image/png", - data: "AQIDBA==", - }, - } as const; - const expectedAttachmentPath = path.join( - attachmentsDir, - attachmentRelativePath(attachment)!, - ); - const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); - assert.deepEqual(offeredMessages[0]?.message.content, [ - expectedImageBlock, - { - type: "text", - text: `Ultrathink:\nWhat's in this image?\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`, - }, - ]); - - 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: "Focus on the diagram labels.", - attachments: [attachment, document], - }, - }); - - assert.equal(offeredMessages[1]?.priority, "now"); - assert.deepEqual(offeredMessages[1]?.message.content, [ - expectedImageBlock, - { - type: "text", - text: `Ultrathink:\nFocus on the diagram labels.\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`, - }, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("rejects unsupported image types before opening a provider query", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-unsupported-attachment-", - }); - let openCount = 0; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, - attachmentsDir, - fileSystem, - path: yield* Path.Path, - crypto: yield* Crypto.Crypto, - idAllocator, - queryRunner: { - allocateSessionId: Effect.succeed("native-thread-claude-unsupported-attachment"), - open: () => - Effect.sync(() => { - openCount += 1; - return { - messages: Stream.never, - offer: () => Effect.void, - setModel: () => Effect.void, - applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, - backgroundTasks: () => Effect.succeed(false), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Effect.void, - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-unsupported-attachment"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-claude-unsupported-attachment", - ), - 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 attachment = ChatImageAttachment.make({ - type: "image", - id: ChatAttachmentId.make( - "thread-claude-unsupported-12345678-1234-1234-1234-123456789abc", - ), - name: "diagram.svg", - mimeType: "image/svg+xml", - sizeBytes: 4, - }); - const now = yield* DateTime.now; - - const error = yield* runtime - .startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-unsupported-attachment"), - text: "Inspect this image.", - attachments: [attachment], - }), - ) - .pipe(Effect.flip); - - assert.equal(error._tag, "ProviderAdapterTurnStartError"); - assert.include(String(error.cause), "Unsupported Claude image attachment type"); - assert.equal(openCount, 0); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); -}); - -describe("ClaudeAdapterV2 native fork", () => { - it.effect("forks at the source assistant cursor and resumes the forked session", () => - 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 openedQueries: Array = []; - const forkCalls: Array<{ - readonly sessionId: string; - readonly options: unknown; - readonly threadId: ThreadId; - readonly providerSessionId: ProviderSessionId; - }> = []; - const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ - instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CLAUDE_SETTINGS, - environment: {}, + environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" }, attachmentsDir, fileSystem, path: yield* Path.Path, @@ -1860,6 +1703,7 @@ describe("ClaudeAdapterV2 native fork", () => { dir: "/workspace", upToMessageId: "assistant-message-cursor", }, + environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" }, threadId: targetThreadId, providerSessionId, }, @@ -1979,7 +1823,6 @@ function makeFakeClaudeCli(answerSetServers = true) { }); return child; }; - // The SDK closes the CLI by ending its stdin. const closed = () => stdins.length > 0 && stdins.every((stdin) => stdin.writableEnded); return { spawn, spawns, controlRequests, closed }; } @@ -2033,18 +1876,6 @@ describe("ClaudeAdapterV2 MCP credential channel", () => { assert.notInclude(spawned, "dummy-mcp-credential"); }), ); - - it.effect("closes the CLI when it never answers the MCP registration", () => - Effect.gen(function* () { - const cli = makeFakeClaudeCli(false); - const opening = yield* openWith(cli).pipe(Effect.result, Effect.forkChild); - yield* TestClock.adjust("90 seconds"); - const opened = yield* Fiber.join(opening); - - assert.equal(opened._tag, "Failure"); - assert.isTrue(cli.closed()); - }), - ); }); describe("ClaudeAdapterV2 native session identity", () => { @@ -2122,15 +1953,6 @@ describe("ClaudeAdapterV2 native session identity", () => { ), ); - it.effect("creates the native session on the first provider turn", () => - Effect.gen(function* () { - const openedQueries = yield* openTurnWithOrdinal(1); - assert.equal(openedQueries.length, 1); - assert.equal(openedQueries[0]?.options.sessionId, "native-session-identity"); - assert.equal(openedQueries[0]?.options.resume, undefined); - }), - ); - it.effect( "resumes the native session on a fresh session instance when prior provider turns exist", () => @@ -2208,8 +2030,15 @@ describe("ClaudeAdapterV2 background wake turns", () => { }); const makeAssistantErrorFrame = (input: { readonly uuid: string; - readonly error: "authentication_failed" | "rate_limit" | "server_error" | undefined; + readonly error: + | "authentication_failed" + | "invalid_request" + | "rate_limit" + | "server_error" + | undefined; + readonly text?: string; readonly parentToolUseId?: string | null; + readonly apiErrorParams?: unknown; }) => claudeSdkFrame({ type: "assistant", @@ -2218,7 +2047,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { id: `msg_${input.uuid}`, type: "message", role: "assistant", - content: [{ type: "text", text: "Claude could not complete this request." }], + content: [{ type: "text", text: input.text ?? "Claude could not complete this request." }], stop_reason: null, stop_sequence: null, usage: { @@ -2230,6 +2059,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { }, parent_tool_use_id: input.parentToolUseId ?? null, ...(input.error === undefined ? {} : { error: input.error }), + ...(input.apiErrorParams === undefined ? {} : { api_error_params: input.apiErrorParams }), uuid: input.uuid, session_id: WAKE_NATIVE_SESSION, }); @@ -2310,7 +2140,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { }); const STALE_TASK_NOTIFICATION_RESULT_TEXT = "Stale task-notification origin text that must not appear."; - // Shape seen live after interrupt recovery: zero turns, no terminal_reason. const staleTaskNotificationResult = makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000106", result: STALE_TASK_NOTIFICATION_RESULT_TEXT, @@ -2319,20 +2148,32 @@ describe("ClaudeAdapterV2 background wake turns", () => { terminalReason: null, }); - const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect => + // Harnesses notify after every recorded event, continuation, or prompt, so a + // wait re-checks exactly when the state it reads changes. Subscribing before + // the first check means a change that lands in between is not lost. + const makeChangeSignal = Effect.gen(function* () { + const changes = yield* PubSub.unbounded(); + const until = (predicate: () => boolean): Effect.Effect => + Effect.scoped( + Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(changes); + while (!predicate()) yield* PubSub.take(subscription); + }), + ); + return { notify: PubSub.publish(changes, undefined), until }; + }); + + // Fixed quiet windows for asserting that nothing happens after input the + // harness cannot observe being handled (a shut-down query, a replaced process). + const yieldTicks = (ticks: number): Effect.Effect => Effect.gen(function* () { - for (let attempt = 0; attempt < 5000; attempt++) { - if (predicate()) { - return; - } - yield* Effect.yieldNow; - } - return yield* Effect.die(`Timed out waiting for ${label}.`); + for (let tick = 0; tick < ticks; tick++) yield* Effect.yieldNow; }); const makeWakeHarnessWithOptions = (options?: { readonly close?: (sdkMessages: Queue.Queue) => Effect.Effect; readonly interrupt?: Effect.Effect; + readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"]; readonly stopTask?: ( taskId: string, ) => Effect.Effect; @@ -2344,6 +2185,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { readonly nativeSessionId?: string; readonly settings?: ClaudeSettings; readonly freshQueueOnReopen?: boolean; + readonly forkSession?: ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerShape["forkSession"]; + readonly allocateSessionId?: Effect.Effect; }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -2360,10 +2203,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { ) { const processed = yield* Deferred.make(); processedMessages.set(message, processed); - yield* Queue.offer(sdkMessages, message); + yield* Queue.offer(processQueues.at(-1) ?? sdkMessages, message); if (offered !== undefined) yield* Deferred.succeed(offered, undefined); yield* Deferred.await(processed); }); + const changes = yield* makeChangeSignal; const offeredMessages: Array = []; const permissionModeChanges: Array = []; const liveSelectionChanges: Array = []; @@ -2383,6 +2227,18 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* Queue.unbounded< Extract >(); + const runtimeRequestReceipts = + yield* Queue.unbounded< + Extract + >(); + const planReceipts = + yield* Queue.unbounded< + Extract + >(); + const providerThreadReceipts = + yield* Queue.unbounded< + Extract + >(); let openedOptions: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions | undefined; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, @@ -2397,25 +2253,54 @@ describe("ClaudeAdapterV2 background wake turns", () => { offer: (request) => Effect.sync(() => { continuationRequests.push(request); - }).pipe(Effect.andThen(Queue.offer(continuationReceipts, request))), + }).pipe( + Effect.andThen(Queue.offer(continuationReceipts, request)), + Effect.andThen(changes.notify), + ), }, queryRunner: { - allocateSessionId: Effect.succeed(options?.nativeSessionId ?? WAKE_NATIVE_SESSION), + allocateSessionId: + options?.allocateSessionId ?? + Effect.succeed(options?.nativeSessionId ?? WAKE_NATIVE_SESSION), open: (input) => Effect.gen(function* () { openedOptions = input.options; + const processMessages = + options?.freshQueueOnReopen === true && processQueues.length > 0 + ? yield* Queue.unbounded() + : sdkMessages; + const messages = Stream.fromQueue(processMessages).pipe( + Stream.flatMap((message) => + Stream.make(message).pipe( + Stream.concat( + Stream.fromEffect( + Effect.suspend(() => { + const processed = processedMessages.get(message); + return processed === undefined + ? Effect.void + : Deferred.succeed(processed, undefined); + }), + ).pipe(Stream.drain), + ), + ), + ), + ); if (options?.freshQueueOnReopen === true && processQueues.length > 0) { - const processMessages = yield* Queue.unbounded(); processQueues.push(processMessages); return { - messages: Stream.fromQueue(processMessages), + messages, offer: (message: SDKUserMessage) => Effect.sync(() => { offeredMessages.push(message); - }), + }).pipe(Effect.andThen(changes.notify)), setModel: () => Effect.void, applyFlagSettings: () => Effect.void, - setPermissionMode: () => Effect.void, + setPermissionMode: (mode) => + Effect.sync(() => { + permissionModeChanges.push(mode); + }).pipe( + Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void), + ), backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)), stopTask: options?.stopTask ?? (() => Effect.void), interrupt: Effect.void, @@ -2424,26 +2309,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { } processQueues.push(sdkMessages); return { - messages: Stream.fromQueue(sdkMessages).pipe( - Stream.flatMap((message) => - Stream.make(message).pipe( - Stream.concat( - Stream.fromEffect( - Effect.suspend(() => { - const processed = processedMessages.get(message); - return processed === undefined - ? Effect.void - : Deferred.succeed(processed, undefined); - }), - ).pipe(Stream.drain), - ), - ), - ), - ), + messages, offer: (message) => Effect.sync(() => { offeredMessages.push(message); - }), + }).pipe(Effect.andThen(changes.notify)), setModel: (model) => Effect.sync(() => { liveSelectionChanges.push({ model }); @@ -2455,14 +2325,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { setPermissionMode: (mode) => Effect.sync(() => { permissionModeChanges.push(mode); - }), + }).pipe(Effect.andThen(() => options?.setPermissionMode?.(mode) ?? Effect.void)), backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)), stopTask: options?.stopTask ?? (() => Effect.void), interrupt: options?.interrupt ?? Effect.void, close: options?.close?.(sdkMessages) ?? Effect.void, }; }), - forkSession: () => Effect.die("unused forkSession"), + forkSession: options?.forkSession ?? (() => Effect.die("unused forkSession")), subagentLaunchToolUseId: () => Effect.succeed(options?.subagentLaunchToolUseId ?? null), assertComplete: Effect.void, }, @@ -2490,9 +2360,19 @@ describe("ClaudeAdapterV2 background wake turns", () => { if (event.type === "turn.terminal") { yield* Queue.offer(terminalReceipts, event); } + if (event.type === "runtime_request.updated") { + yield* Queue.offer(runtimeRequestReceipts, event); + } + if (event.type === "plan.updated") { + yield* Queue.offer(planReceipts, event); + } + if (event.type === "provider_thread.updated") { + yield* Queue.offer(providerThreadReceipts, event); + } if (event.type === "turn_item.updated" && event.turnItem.type === "system_notice") { yield* Queue.offer(systemNoticeReceipts, event); } + yield* changes.notify; }), ), Effect.forkScoped, @@ -2509,6 +2389,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { event.type === "turn.terminal", ); return { + attachmentsDir, runtime, providerThread, threadId, @@ -2529,953 +2410,1470 @@ describe("ClaudeAdapterV2 background wake turns", () => { terminalReceipts, subagentReceipts, systemNoticeReceipts, + runtimeRequestReceipts, + planReceipts, + providerThreadReceipts, getOpenedOptions: () => openedOptions, terminalEvents, hasPendingBackgroundWork, + until: changes.until, + awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count), + awaitContinuation: (count: number) => + changes.until(() => continuationRequests.length >= count), }; }); const makeWakeHarness = makeWakeHarnessWithOptions(); - it.effect.each([ - { isError: false, title: "Check weather" }, - { isError: true, title: "Check weather" }, - { isError: false, title: undefined }, - ])("keeps late MCP display metadata with %j", ({ isError, title }) => - 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("mcp-presentation"), - text: "Check the weather", - attachments: [], - }), - ); - const toolName = "mcp__weather__get_weather"; - const id = "weather-call"; - yield* Effect.promise(() => - harness.getOpenedOptions()!.canUseTool!( - toolName, - { city: "Berlin" }, - { - signal: new AbortController().signal, - toolUseID: id, - requestId: "weather-request", - }, + describe("Claude settings restrictions", () => { + it.effect("resolves cached managed policy from the configured home through the real SDK", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-" }); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-remote-cwd-" }); + const remoteFile = path.join(home, "remote-settings.json"); + const sdk = yield* Effect.promise(() => + vi.importActual("@anthropic-ai/claude-agent-sdk"), + ); + vi.mocked(ClaudeSdk.resolveSettings).mockImplementation(sdk.resolveSettings); + const open = Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home }, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-cached-managed-policy"), + text: "Run git status.", + attachments: [], + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd, + }), + }), + ); + return harness.getOpenedOptions()!; + }), + ); + yield* fileSystem.writeFileString( + remoteFile, + JSON.stringify({ + permissions: { disableBypassPermissionsMode: "disable" }, + disableAutoMode: "disable", + managedSourcesBehavior: "merge", + }), + ); + const restricted = yield* open; + assert.equal(restricted.permissionMode, "default"); + assert.isUndefined(restricted.allowDangerouslySkipPermissions); + yield* fileSystem.remove(remoteFile); + assert.equal((yield* open).permissionMode, "bypassPermissions"); + yield* fileSystem.writeFileString(remoteFile, "{ invalid json"); + assert.equal((yield* open).permissionMode, "auto"); + yield* fileSystem.remove(remoteFile); + yield* fileSystem.makeDirectory(remoteFile); + assert.equal((yield* open).permissionMode, "auto"); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "assistant", - uuid: "weather-assistant", - session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - id: "weather-message", - type: "message", - role: "assistant", - model: "claude-sonnet-4-6", - content: [{ type: "tool_use", id, name: toolName, input: { city: "Berlin" } }], - }, - tool_use_meta: [ - { - id, - display_name: title, - server_display_name: "Weather", - icon_url: "https://example.com/weather.png", - }, - ], - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "user", - uuid: "weather-result", - session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: id, - content: "Weather result", - is_error: isError, - }, - ], - }, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "weather-terminal", result: "Weather checked" }), - ); - yield* Queue.take(harness.terminalReceipts); - const items = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" - ? [event.turnItem] - : [], - ); - assert.deepEqual( - items.map((item) => item.status), - ["running", "running", isError ? "failed" : "completed"], - ); - assert.isNull(items[0]?.title); - for (const item of items.slice(1)) { - assert.equal(item.title, title ?? "get weather"); - assert.deepEqual(item.toolIcon, { - _tag: "themed-logo", - logoUrl: "https://example.com/weather.png", - }); - assert.deepEqual(item.toolSource, { - key: "mcp:weather", - name: "Weather", - kind: "integration", - icon: { _tag: "themed-logo", logoUrl: "https://example.com/weather.png" }, - }); - assert.deepEqual(item.input, { city: "Berlin" }); - } - assert.equal(new Set(items.map((item) => item.id)).size, 1); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), - ), - ); + ); - 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) => + it.effect("asks before restricted Full access tools and follows policy across turns", () => + Effect.gen(function* () { + const resolveSettings = vi + .mocked(ClaudeSdk.resolveSettings) + .mockImplementation(async (options) => ({ + effective: + options?.cwd === "/unrestricted" + ? {} + : { + permissions: { + disableBypassPermissionsMode: "disable", + ...(options?.cwd === "/restricted-worktree" + ? { disableAutoMode: "disable" as const } + : {}), + }, + }, + provenance: {}, + sources: [], + })); + const harness = yield* makeWakeHarnessWithOptions({ + close: Queue.shutdown, + freshQueueOnReopen: true, + setPermissionMode: (mode) => + mode === "bypassPermissions" + ? Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "setPermissionMode", + cause: new Error( + "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration", + ), + }), + ) + : Effect.void, + }); + const now = yield* DateTime.now; + let ordinal = 0; + const start = (cwd: string, runtimeMode: "full-access" | "auto" = "full-access") => + harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make(`attempt-normal-background:${ordinal}`), - text: `Request ${ordinal}`, - attachments: [], + attemptId: RunAttemptId.make(`attempt-policy-${++ordinal}`), providerTurnOrdinal: ordinal, - modelSelection, - }); - const settle = Effect.gen(function* () { - yield* harness.offerAndWait(turnOneResult); - yield* Queue.take(harness.terminalReceipts); + text: "Run git status.", + attachments: [], + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode, + interactionMode: "default", + cwd, + }), + }), + ); + const finish = Effect.gen(function* () { + yield* harness.offerAndWait( + makeResultFrame({ uuid: `policy-result-${ordinal}`, result: "Done." }), + ); + yield* Queue.take(harness.terminalReceipts); + }); + const notices = () => + harness.events.filter( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice", + ); + + yield* start("/restricted-worktree", "auto"); + assert.equal(harness.getOpenedOptions()?.permissionMode, "auto"); + yield* finish; + assert.equal(notices().length, 0); + assert.equal(resolveSettings.mock.calls.length, 0); + + yield* start("/restricted"); + const openedOptions = harness.getOpenedOptions()!; + const decision = yield* Effect.promise(() => + openedOptions.canUseTool!( + "Bash", + { command: "git status" }, + { + signal: new AbortController().signal, + toolUseID: "policy-command", + requestId: "request-policy-command", + }, + ), + ).pipe(Effect.forkScoped); + const first = yield* Effect.raceFirst( + Queue.take(harness.runtimeRequestReceipts).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", + "Full access must not auto-allow a policy-restricted command", + ); + if (first.type !== "request") return; + assert.equal(first.event.runtimeRequest.kind, "command"); + yield* harness.runtime.respondToRuntimeRequest({ + requestId: first.event.runtimeRequest.id, + decision: "decline", + }); + assert.equal((yield* Fiber.join(decision))?.behavior, "deny"); + assert.equal(openedOptions.permissionMode, "auto"); + assert.isUndefined(openedOptions.allowDangerouslySkipPermissions); + + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "plan", + uuid: "policy-enter-plan", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* finish; + assert.equal(notices().length, 1); + yield* start("/restricted"); + assert.strictEqual(harness.getOpenedOptions(), openedOptions); + assert.deepEqual(harness.permissionModeChanges, ["auto"]); + assert.equal(resolveSettings.mock.calls.length, 1); + yield* finish; + + yield* start("/restricted-worktree"); + assert.equal(harness.getOpenedOptions()?.permissionMode, "default"); + assert.isUndefined(harness.getOpenedOptions()?.allowDangerouslySkipPermissions); + assert.equal(resolveSettings.mock.calls.length, 2); + yield* finish; + + yield* start("/unrestricted"); + assert.equal(harness.getOpenedOptions()?.permissionMode, "bypassPermissions"); + assert.equal(harness.getOpenedOptions()?.allowDangerouslySkipPermissions, true); + // Forwarded asks (including ask rules and settings fallback) still need a decision + // before queued init/status frames arrive. + for (const { phase, frame } of [ + { + phase: "init", + frame: claudeSdkFrame({ + type: "system", + subtype: "init", + permissionMode: "bypassPermissions", + uuid: "policy-cli-init", + session_id: WAKE_NATIVE_SESSION, + }), + }, + { + phase: "status", + frame: claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "default", + uuid: "policy-cli-downgrade", + session_id: WAKE_NATIVE_SESSION, + }), + }, + ]) { + const forwardedDecision = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + "Bash", + { command: "git status" }, + { + signal: new AbortController().signal, + toolUseID: `forwarded-before-${phase}`, + requestId: `request-forwarded-before-${phase}`, + }, + ), + ).pipe(Effect.forkScoped); + const forwardedFirst = yield* Effect.raceFirst( + Queue.take(harness.runtimeRequestReceipts).pipe( + Effect.map((event) => ({ type: "request", event }) as const), + ), + Fiber.join(forwardedDecision).pipe( + Effect.map((result) => ({ type: "decision", result }) as const), + ), + ); + assert.equal( + forwardedFirst.type, + "request", + `CLI-forwarded Bash must ask before the queued ${phase} frame reaches the adapter`, + ); + if (forwardedFirst.type !== "request") return; + assert.equal(forwardedFirst.event.runtimeRequest.kind, "command"); + yield* harness.runtime.respondToRuntimeRequest({ + requestId: forwardedFirst.event.runtimeRequest.id, + decision: "decline", }); - yield* harness.runtime.startTurn(turn(1, normal)); - const originalOptions = harness.getOpenedOptions(); - yield* harness.offerAndWait(wakeTaskStarted); - yield* settle; - assert.isTrue(yield* harness.hasPendingBackgroundWork); + assert.equal((yield* Fiber.join(forwardedDecision))?.behavior, "deny"); + yield* harness.offerAndWait(frame); + } + yield* finish; + const unrestrictedOptions = harness.getOpenedOptions(); + yield* start("/unrestricted"); + assert.strictEqual(harness.getOpenedOptions(), unrestrictedOptions); + assert.deepEqual( + harness.permissionModeChanges, + ["auto"], + "A CLI policy downgrade must not be restored to bypass on the next turn", + ); + assert.equal(resolveSettings.mock.calls.length, 3); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "plan", + uuid: "policy-restricted-enter-plan", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* finish; + assert.equal(notices().length, 1); - yield* harness.runtime.startTurn( - turn(2, { ...normal, options: [{ id: "fastMode", value: false }] }), + for (const phase of ["restore", "reuse"]) { + const started = yield* start("/unrestricted").pipe(Effect.exit); + assert.isTrue( + Exit.isSuccess(started), + `A rejected bypass restore must not fail the ${phase} turn`, + ); + assert.strictEqual(harness.getOpenedOptions(), unrestrictedOptions); + assert.deepEqual(harness.permissionModeChanges, ["auto", "bypassPermissions", "default"]); + assert.equal(harness.offeredMessages.length, ordinal); + const restoredDecision = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + "Bash", + { command: "git status" }, + { + signal: new AbortController().signal, + toolUseID: `forwarded-after-plan-${phase}`, + requestId: `request-after-plan-${phase}`, + }, + ), + ).pipe(Effect.forkScoped); + const restoredFirst = yield* Effect.raceFirst( + Queue.take(harness.runtimeRequestReceipts).pipe( + Effect.map((event) => ({ type: "request", event }) as const), + ), + Fiber.join(restoredDecision).pipe( + Effect.map((result) => ({ type: "decision", result }) as const), + ), ); - yield* settle; - assert.deepEqual(harness.liveSelectionChanges, []); + assert.equal(restoredFirst.type, "request"); + if (restoredFirst.type !== "request") return; + assert.equal(restoredFirst.event.runtimeRequest.kind, "command"); + yield* harness.runtime.respondToRuntimeRequest({ + requestId: restoredFirst.event.runtimeRequest.id, + decision: "decline", + }); + assert.equal((yield* Fiber.join(restoredDecision))?.behavior, "deny"); + yield* finish; + assert.equal(harness.terminalEvents().at(-1)?.status, "completed"); + } + assert.equal(notices().length, 1); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + // regression: #21806 bypass policy reads the custom home and project, never ambient ~/.claude + it.effect( + "combines a normalized custom home with project policy without reading the ambient user tier", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-policy-home-", + }); + yield* fileSystem.makeDirectory(path.join(home, "profile")); + yield* fileSystem.writeFileString( + path.join(home, "profile", "settings.json"), + `{ + // Claude accepts comments and trailing commas. + "permissions": { "disableBypassPermissionsMode": "disable", }, + }`, + ); + const resolveSettings = vi.mocked(ClaudeSdk.resolveSettings).mockResolvedValue({ + effective: { disableAutoMode: "disable" }, + provenance: {}, + sources: [{ source: "project", settings: { disableAutoMode: "disable" } }], + }); + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: " ~/profile " }, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, home)); yield* harness.runtime.startTurn( - turn(3, { - ...normal, - options: [ - { id: "effort", value: "ultracode" }, - { id: "fastMode", value: true }, - ], + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-custom-home"), + text: "Run git status.", + attachments: [], }), ); - yield* settle; - yield* harness.runtime.startTurn(turn(4, { ...normal, model: "claude-sonnet-4-6" })); - yield* settle; - assert.deepEqual(harness.liveSelectionChanges, [ - { model: "claude-opus-5-5" }, - { effortLevel: "xhigh", fastMode: true, ultracode: true }, - { model: "claude-sonnet-4-6" }, - { effortLevel: "high", fastMode: null, ultracode: null }, + assert.equal(harness.getOpenedOptions()?.permissionMode, "default"); + assert.isUndefined(harness.getOpenedOptions()?.allowDangerouslySkipPermissions); + assert.deepEqual(resolveSettings.mock.calls[0]?.[0]?.settingSources, [ + "project", + "local", ]); - 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, 4); - assert.isTrue(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), - ); + ); - it.effect.each(["completed", "interrupted"] as const)( - "projects Claude thinking blocks when %s", - (status) => - 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("reasoning-attempt"), - text: "Check the plan", - attachments: [], - }), - ); - const stream = (event: unknown, parent: string | null = null) => - claudeSdkFrame({ - type: "stream_event", - event, - parent_tool_use_id: parent, - session_id: WAKE_NATIVE_SESSION, - uuid: "stream-frame", + // regression: #21806 only a missing custom settings file is benign; bad policy fails + it.effect( + "distinguishes missing custom settings from unreadable, malformed, or unresolved policy", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-policy-failure-", }); - const snapshot = (id: string, uuid: string, thinking: string) => - claudeSdkFrame({ - type: "assistant", - uuid, - session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - id, - model: "claude-sonnet-4-6", - content: [{ type: "thinking", thinking, signature: "secret-signature" }], - }, + const settingsFile = path.join(home, "settings.json"); + const open = Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home }, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-settings-failure"), + text: "Run git status.", + attachments: [], + }), + ); + return harness.getOpenedOptions()!; + }), + ); + assert.equal((yield* open).permissionMode, "bypassPermissions"); + yield* fileSystem.makeDirectory(settingsFile); + const unreadable = yield* open; + assert.equal(unreadable.permissionMode, "auto"); + assert.isUndefined(unreadable.allowDangerouslySkipPermissions); + yield* fileSystem.remove(settingsFile, { recursive: true }); + yield* fileSystem.writeFileString(settingsFile, "{ invalid json"); + assert.equal((yield* open).permissionMode, "auto"); + yield* fileSystem.remove(settingsFile); + const resolveSettings = vi + .mocked(ClaudeSdk.resolveSettings) + .mockClear() + .mockRejectedValueOnce(new Error("Cannot resolve managed settings")) + .mockResolvedValue({ effective: {}, provenance: {}, sources: [] }); + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home }, + close: Queue.shutdown, + freshQueueOnReopen: true, }); - const frames = [ - stream({ type: "message_start", message: { id: "thought-message" } }), - stream({ - type: "content_block_start", - index: 2, - content_block: { type: "thinking", thinking: "" }, - }), - stream({ - type: "content_block_delta", - index: 2, - delta: { type: "thinking_delta", thinking: "First " }, - }), - stream({ - type: "content_block_delta", - index: 2, - delta: { type: "thinking_delta", thinking: "thought" }, - }), - stream({ - type: "content_block_delta", - index: 2, - delta: { type: "signature_delta", signature: "secret-signature" }, - }), - stream({ type: "content_block_stop", index: 2 }), - snapshot("thought-message", "first-snapshot", "Authoritative first thought"), - snapshot("thought-message", "first-snapshot", "Authoritative first thought"), - stream({ - type: "content_block_start", - index: 4, - content_block: { type: "thinking", thinking: "Second thought" }, - }), - stream({ type: "content_block_stop", index: 4 }), - snapshot("thought-message", "second-snapshot", ""), - snapshot("completion-only", "third-snapshot", "Completion only"), - snapshot("redacted", "empty-snapshot", ""), - stream({ type: "message_start", message: { id: "child-message" } }, "child-tool"), - stream( - { - type: "content_block_start", - index: 0, - content_block: { type: "thinking", thinking: "Child thought" }, - }, - "child-tool", - ), - stream({ type: "message_start", message: { id: "partial-message" } }), - stream({ - type: "content_block_start", - index: 0, - content_block: { type: "thinking", thinking: "Partial thought" }, - }), - makeResultFrame({ - uuid: "reasoning-result", - result: "", - ...(status === "interrupted" ? { terminalReason: "aborted_streaming" as const } : {}), - }), - ]; - for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, status); - const latest = new Map( - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "reasoning" - ? [[event.turnItem.id, event.turnItem] as const] - : [], + for (const ordinal of [1, 2]) { + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-settings-recovery-${ordinal}`), + providerTurnOrdinal: ordinal, + text: "Run git status.", + attachments: [], + }), + ); + const options = harness.getOpenedOptions()!; + assert.equal( + options.permissionMode, + ordinal === 1 ? "auto" : "bypassPermissions", + "A transient resolver failure must only downgrade the failing turn", + ); + if (ordinal === 1) assert.isUndefined(options.allowDangerouslySkipPermissions); + else assert.equal(options.allowDangerouslySkipPermissions, true); + assert.equal(resolveSettings.mock.calls.length, ordinal); + yield* harness.offerAndWait( + makeResultFrame({ uuid: `settings-recovery-result-${ordinal}`, result: "Done." }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + } + assert.equal(harness.offeredMessages.length, 2); + assert.equal( + resolveSettings.mock.calls[0]?.[0]?.cwd, + resolveSettings.mock.calls[1]?.[0]?.cwd, + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), + ), + ); + + it.effect("pins tool search on when the user's Claude settings choose auto", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-tool-search-", + }); + const openedToolSearch = ( + settingsJson: string, + cwd = CLAUDE_TEST_RUNTIME_POLICY.cwd, + environment?: NodeJS.ProcessEnv, + ) => + Effect.scoped( + Effect.gen(function* () { + yield* fileSystem.writeFileString(path.join(home, "settings.json"), settingsJson); + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: home }, + ...(environment === undefined ? {} : { environment }), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-tool-search"), + text: "Run git status.", + attachments: [], + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + ...CLAUDE_TEST_RUNTIME_POLICY, + cwd, + }), + }), + ); + const settings = harness.getOpenedOptions()?.settings; + return typeof settings === "object" ? settings.env?.ENABLE_TOOL_SEARCH : undefined; + }), + ); + assert.equal(yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"auto"}}'), "true"); + assert.isUndefined(yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"false"}}')); + assert.isUndefined(yield* openedToolSearch("{}")); + + // Claude Code keeps the local file at the repository root, the main checkout's root in a + // worktree, and that file beats the user's settings. + const repo = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-repo-" }); + const worktree = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-wt-" }); + const worktreeGitDir = path.join(repo, ".git", "worktrees", "wt"); + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); + yield* fileSystem.writeFileString( + path.join(worktree, ".git"), + `gitdir: ${worktreeGitDir}\n`, + ); + yield* fileSystem.makeDirectory(path.join(repo, ".claude")); + yield* fileSystem.makeDirectory(path.join(repo, "packages", "app"), { recursive: true }); + const rootLocal = (value: string) => + fileSystem.writeFileString( + path.join(repo, ".claude", "settings.local.json"), + `{"env":{"ENABLE_TOOL_SEARCH":"${value}"}}`, + ); + const userAuto = '{"env":{"ENABLE_TOOL_SEARCH":"auto"}}'; + yield* rootLocal("auto"); + assert.equal(yield* openedToolSearch("{}", worktree), "true"); + yield* rootLocal("false"); + assert.isUndefined(yield* openedToolSearch(userAuto, worktree)); + assert.isUndefined(yield* openedToolSearch(userAuto, path.join(repo, "packages", "app"))); + + // Project settings beat user settings, and the process env applies only when no file sets it. + const project = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-project-" }); + yield* fileSystem.makeDirectory(path.join(project, ".claude")); + yield* fileSystem.writeFileString( + path.join(project, ".claude", "settings.json"), + '{"env":{"ENABLE_TOOL_SEARCH":"auto"}}', ); - assert.deepEqual( - [...latest.values()].map((item) => item.text), - ["Authoritative first thought", "Second thought", "Completion only", "Partial thought"], + assert.equal( + yield* openedToolSearch('{"env":{"ENABLE_TOOL_SEARCH":"false"}}', project), + "true", ); - assert.equal(new Set([...latest.values()].map((item) => item.ordinal)).size, 4); - for (const item of latest.values()) { - assert.equal(item.streaming, false); - assert.isNotNull(item.completedAt); - } - assert.isFalse( - harness.events.some( - (event) => event.type === "message.updated" && event.message.role === "assistant", - ), + assert.equal( + yield* openedToolSearch("{}", CLAUDE_TEST_RUNTIME_POLICY.cwd, { + ENABLE_TOOL_SEARCH: "auto", + }), + "true", ); - for (const item of latest.values()) assert.notInclude(item.text, "secret-signature"); }).pipe( - Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ); + ); + }); - const plan = "Planning the check"; - const update = "Found it: the memory file is the cause."; - it.effect.each([ - { - model: "claude-opus-5-5", - texts: [plan, update], - expected: ["reasoning", "assistant_message"], - }, - { - model: "claude-fable-5-1", - texts: [plan, update], - expected: ["reasoning", "assistant_message"], - }, - { model: "claude-opus-5", texts: [plan, update], expected: ["reasoning", "reasoning"] }, - { model: "claude-sonnet-4-6", texts: [plan, update], expected: ["reasoning", "reasoning"] }, - { model: "claude-opus-5-5", texts: [plan], expected: ["reasoning"] }, - { model: "claude-opus-5-5", texts: [plan, " \n "], expected: ["reasoning", "reasoning"] }, - { model: "claude-opus-5-5", texts: [" \n ", update], expected: ["reasoning", "reasoning"] }, - ] as const)( - "shows $model thinking $texts before a tool call as $expected", - ({ model, texts, expected }) => + describe("Plan-mode tool approval", () => { + const openPlanTurn = Effect.fn("openPlanTurn")(function* ( + runtimeMode: "auto" | "full-access", + approvalPolicy?: "never", + ) { + const harness = yield* makeWakeHarness; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode, + interactionMode: "plan", + cwd: "/workspace", + ...(approvalPolicy === undefined ? {} : { approvalPolicy }), + }); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-plan-write"), + text: "Investigate before implementing.", + attachments: [], + runtimePolicy, + }); + yield* harness.runtime.startTurn({ + ...input, + appThread: { ...input.appThread, runtimeMode, interactionMode: "plan" }, + }); + assert.equal(harness.getOpenedOptions()?.permissionMode, "plan"); + const canUseTool = harness.getOpenedOptions()?.canUseTool; + assert.isDefined(canUseTool); + return { ...harness, canUseTool: canUseTool! }; + }); + + const requestWrite = Effect.fn("requestPlanWrite")(function* ( + turn: Effect.Success>, + toolName: string, + toolInput: Record, + options?: { toolUseID: string; agentID?: string }, + ) { + const decision = yield* Effect.promise(() => + turn.canUseTool(toolName, toolInput, { + signal: new AbortController().signal, + toolUseID: options?.toolUseID ?? "tool-plan-write", + requestId: "request-plan-write", + ...(options?.agentID === undefined ? {} : { agentID: options.agentID }), + }), + ).pipe(Effect.forkScoped); + const first = yield* Effect.raceFirst( + Queue.take(turn.runtimeRequestReceipts).pipe( + Effect.map((event) => ({ type: "request", event }) as const), + ), + Fiber.join(decision).pipe(Effect.map((result) => ({ type: "decision", result }) as const)), + ); + return { first, decision }; + }); + + it.effect.each([ + { + runtimeMode: "auto", + toolName: "Edit", + toolInput: { + file_path: "/workspace/target.txt", + old_string: "before", + new_string: "after", + }, + kind: "file-change", + decision: "accept", + behavior: "allow", + }, + { + runtimeMode: "full-access", + toolName: "Bash", + toolInput: { command: "echo after > target.txt" }, + kind: "command", + decision: "cancel", + behavior: "deny", + }, + ] as const)( + "asks before $toolName in $runtimeMode Plan, then respects $decision", + ({ runtimeMode, toolName, toolInput, kind, decision, behavior }) => + Effect.gen(function* () { + const turn = yield* openPlanTurn(runtimeMode); + const permission = yield* requestWrite(turn, toolName, toolInput); + assert.equal(permission.first.type, "request", "the planned write bypassed approval"); + if (permission.first.type !== "request") return; + const request = permission.first.event.runtimeRequest; + assert.equal(request.status, "pending"); + assert.equal(request.kind, kind); + yield* turn.runtime.respondToRuntimeRequest({ requestId: request.id, decision }); + const result = yield* Fiber.join(permission.decision); + assert.equal(result?.behavior, behavior); + if (result?.behavior === "allow") { + assert.deepEqual(result.updatedInput, toolInput); + assert.equal(result.toolUseID, "tool-plan-write"); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect("denies Plan writes without asking when approvals are never allowed", () => 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("thinking-before-tool-attempt"), - text: "Check the memory file", - attachments: [], - }), - ); - const snapshot = (uuid: string, content: ReadonlyArray) => - claudeSdkFrame({ - type: "assistant", - uuid, - session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { id: "reply-message", model, content }, + const turn = yield* openPlanTurn("full-access", "never"); + const permission = yield* requestWrite(turn, "Bash", { + command: "echo after > target.txt", + }); + assert.equal(permission.first.type, "decision", "Never raised an approval request"); + if (permission.first.type !== "decision") return; + assert.equal(permission.first.result?.behavior, "deny"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect( + "returns approval feedback to the requesting tool without sending a parent prompt", + () => + Effect.gen(function* () { + const turn = yield* openPlanTurn("full-access"); + const parentPermission = yield* requestWrite( + turn, + "Bash", + { command: "git status" }, + { toolUseID: "parent-command" }, + ); + assert.equal(parentPermission.first.type, "request"); + if (parentPermission.first.type !== "request") return; + const permission = yield* requestWrite( + turn, + "Bash", + { command: "rm -f $W/*/*.obj" }, + { toolUseID: "child-command", agentID: "child-worker" }, + ); + assert.equal(permission.first.type, "request"); + if (permission.first.type !== "request") return; + const request = permission.first.event.runtimeRequest; + assert.equal(request.responseCapability.type, "live"); + assert.isTrue( + request.responseCapability.type === "live" && + request.responseCapability.supportsFeedback, + ); + yield* turn.runtime.respondToRuntimeRequest({ + requestId: request.id, + decision: "decline", + feedback: "Run it in a safer manner.", }); - const frames = [ - ...texts.map((thinking, index) => - snapshot(`thinking-snapshot-${index}`, [ - { type: "thinking", thinking, signature: "sig" }, - ]), + const result = yield* Fiber.join(permission.decision); + assert.equal(result?.behavior, "deny"); + if (result?.behavior === "deny") { + assert.include(result.message, "Run it in a safer manner."); + assert.notProperty(result, "interrupt"); + } + assert.equal(turn.offeredMessages.length, 1); + yield* turn.runtime.respondToRuntimeRequest({ + requestId: parentPermission.first.event.runtimeRequest.id, + decision: "accept", + }); + const parentResult = yield* Fiber.join(parentPermission.decision); + assert.equal(parentResult?.behavior, "allow"); + if (parentResult?.behavior === "allow") + assert.equal(parentResult.toolUseID, "parent-command"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), - snapshot("tool-snapshot", [ - { type: "tool_use", id: "tool-1", name: "Bash", input: { command: "ls" } }, - ]), - makeResultFrame({ uuid: "thinking-before-tool-result", result: "" }), - ]; - for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); - yield* Queue.take(harness.terminalReceipts); - const latest = new Map( - harness.events.flatMap((event) => - event.type === "turn_item.updated" && - (event.turnItem.type === "reasoning" || event.turnItem.type === "assistant_message") - ? [[event.turnItem.id, event.turnItem] as const] - : [], + ), + ); + + it.effect("still captures ExitPlanMode when Plan approvals are never allowed", () => + Effect.gen(function* () { + const turn = yield* openPlanTurn("full-access", "never"); + const markdown = "# Proposed work\n\nFix the calculation after approval."; + const result = yield* Effect.promise(() => + turn.canUseTool( + "ExitPlanMode", + { plan: markdown }, + { + signal: new AbortController().signal, + toolUseID: "tool-plan-capture", + requestId: "request-plan-capture", + }, ), ); - const items = [...latest.values()]; - assert.deepEqual( - items.map((item) => item.type), - [...expected], - ); - assert.deepEqual( - items.map((item) => item.text), - [...texts], - ); + assert.equal(result?.behavior, "deny"); + if (result?.behavior === "deny") + assert.include(result.message, "captured your proposed plan"); + const event = yield* Queue.take(turn.planReceipts); + assert.equal(event.plan.kind, "proposed_plan"); + assert.equal(event.plan.kind === "proposed_plan" ? event.plan.markdown : "", markdown); }).pipe( Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ); + ); + }); - it.effect.each(["cancelled", "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" ? "cancelled" : "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), - ), - ), - ), - ); - - it.effect.each( - (["aborted_tools", "aborted_streaming"] as const).flatMap((terminalReason) => - [true, false].map((steered) => ({ terminalReason, steered })), - ), - )("handles $terminalReason with active steering=$steered", ({ terminalReason, steered }) => - Effect.scoped( + it.effect( + "carries earlier user-only skill instructions on sends and steering with attachments", + () => Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attemptId = RunAttemptId.make("attempt-steering-abort"); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const homePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skill-dispatch-" }); + for (const [name, userOnly] of [ + ["interrogate", true], + ["implement", true], + ["review", false], + ] as const) { + const directory = path.join(homePath, "skills", name); + yield* fs.makeDirectory(directory, { recursive: true }); + yield* fs.writeFileString( + path.join(directory, "SKILL.md"), + `---\nname: ${name}\ndisable-model-invocation: ${userOnly}\n---\nFollow the ${name} instructions.\n`, + ); + } + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath }, + }); const input = makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId, - text: "Audit the settings pages.", + attemptId: RunAttemptId.make("skill-dispatch"), + text: "$interrogate then $review then $implement the fixes", attachments: [], + runtimePolicy: { ...CLAUDE_TEST_RUNTIME_POLICY, cwd: homePath }, }); 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"); - } - yield* Queue.offer( - harness.sdkMessages, - 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, - }, + + const leadingText = `Ultrathink:\n/interrogate [The user invoked this skill. Follow the instructions at: ${path.join(homePath, "skills", "interrogate", "SKILL.md")}] then /review then /implement the fixes`; + assert.deepEqual(harness.offeredMessages[0]?.message.content, [ + { type: "text", text: leadingText }, + { type: "text", text: "/implement the fixes" }, + ]); + + const attachment = ChatFileAttachment.make({ + type: "file", + id: ChatAttachmentId.make("skill-dispatch-12345678-1234-1234-1234-123456789abc"), + name: "requirements.pdf", + mimeType: "application/pdf", + sizeBytes: 4, + }); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + 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}`, }), - ); - 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); - assert.equal(terminal.status, steered ? "completed" : "interrupted"); - if (steered) { - 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: "complete", - hasSubagents: false, - inputTokens: 603 + 2847 + 11455, - outputTokens: 46, - cachedInputTokens: 11455, - cacheCreationTokens: 2847, - }, - ); - } - assert.lengthOf(harness.terminalEvents(), 1); + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("skill-dispatch-steer"), + text: input.message.text, + attachments: [attachment], + }, + }); + const attachmentNote = `\n\n[Attached file "requirements.pdf" is saved at: ${path.join(harness.attachmentsDir, attachmentRelativePath(attachment)!)}]`; + assert.equal(harness.offeredMessages[1]?.priority, "now"); + assert.deepEqual(harness.offeredMessages[1]?.message.content, [ + { type: "text", text: `${leadingText}${attachmentNote}` }, + { type: "text", text: `/implement the fixes${attachmentNote}` }, + ]); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), ); - it.effect("announces usage-limit pauses once per window and again on a new turn", () => + // regression: #15475 MCP title arriving after the tool starts must survive to completion + it.effect.each([ + { isError: false, title: "Check weather" }, + { isError: true, title: "Check weather" }, + { isError: false, title: undefined }, + ])("keeps late MCP display metadata with %j", ({ isError, title }) => Effect.gen(function* () { const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const resetsAt = Math.floor(DateTime.toEpochMillis(now) / 1000) + 7_200; - const limit = (rateLimitType: "five_hour" | "seven_day" = "five_hour") => + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("mcp-presentation"), + text: "Check the weather", + attachments: [], + }), + ); + const toolName = "mcp__weather__get_weather"; + const id = "weather-call"; + const permission = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + toolName, + { city: "Berlin" }, + { + signal: new AbortController().signal, + toolUseID: id, + requestId: "weather-request", + }, + ), + ).pipe(Effect.forkScoped); + const request = yield* Queue.take(harness.runtimeRequestReceipts); + yield* harness.runtime.respondToRuntimeRequest({ + requestId: request.runtimeRequest.id, + decision: "accept", + }); + yield* Fiber.join(permission); + yield* harness.offerAndWait( claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { status: "rejected", rateLimitType, resetsAt }, - uuid: "00000000-0000-4000-8000-000000000601", + type: "assistant", + uuid: "weather-assistant", session_id: WAKE_NATIVE_SESSION, - }); - const start = (ordinal: number) => - harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make(`attempt-claude-limit-${ordinal}`), - providerTurnOrdinal: ordinal, - text: "Continue.", - attachments: [], - }), - ); - yield* start(1); - yield* Queue.offer(harness.sdkMessages, limit()); - const pause = (yield* Queue.take(harness.systemNoticeReceipts)).turnItem; - assert.equal(pause.type, "system_notice"); - if (pause.type !== "system_notice") return; - assert.equal( - pause.message, - "Claude usage limit reached. This turn is paused until the 5-hour limit resets in 2h.", - ); - assert.lengthOf(harness.terminalEvents(), 0); - yield* Queue.offerAll(harness.sdkMessages, [ - limit(), - limit("seven_day"), - limit(), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000602", - result: "Recovered.", - }), - ]); - yield* Queue.take(harness.terminalReceipts); - const notices = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "system_notice" - ? [event.turnItem] - : [], - ); - assert.lengthOf(notices(), 2); - yield* start(2); - yield* Queue.offerAll(harness.sdkMessages, [ - limit(), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000603", - result: "Done.", + parent_tool_use_id: null, + message: { + id: "weather-message", + type: "message", + role: "assistant", + model: "claude-sonnet-4-6", + content: [{ type: "tool_use", id, name: toolName, input: { city: "Berlin" } }], + }, + tool_use_meta: [ + { + id, + display_name: title, + server_display_name: "Weather", + icon_url: "https://example.com/weather.png", + }, + ], }), - ]); - yield* Queue.take(harness.terminalReceipts); - assert.lengthOf(notices(), 3); - assert.notEqual(notices()[0]?.id, notices()[2]?.id); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("keeps usage warnings and provisioned overage silent", () => - 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-overage"), - text: "Continue.", - attachments: [], + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "user", + uuid: "weather-result", + session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: id, + content: "Weather result", + is_error: isError, + }, + ], + }, }), ); - for (const rate_limit_info of [ - { status: "allowed_warning" }, - { status: "rejected", overageStatus: "allowed" }, - { status: "rejected", overageStatus: "allowed_warning" }, - { status: "rejected", isUsingOverage: true }, - { status: "rejected", overageInUse: true }, - ]) { - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info, - session_id: WAKE_NATIVE_SESSION, - uuid: "00000000-0000-4000-8000-000000000604", - }), - ); - } yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000605", - result: "Done.", - }), + makeResultFrame({ uuid: "weather-terminal", result: "Weather checked" }), ); yield* Queue.take(harness.terminalReceipts); - assert.isFalse( - harness.events.some( - (event) => event.type === "turn_item.updated" && event.turnItem.type === "system_notice", - ), + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + items.map((item) => item.status), + ["running", "running", isError ? "failed" : "completed"], ); + assert.isNull(items[0]?.title); + for (const item of items.slice(1)) { + assert.equal(item.title, title ?? "get weather"); + assert.deepEqual(item.toolIcon, { + _tag: "themed-logo", + logoUrl: "https://example.com/weather.png", + }); + assert.deepEqual(item.toolSource, { + key: "mcp:weather", + name: "Weather", + kind: "integration", + icon: { _tag: "themed-logo", logoUrl: "https://example.com/weather.png" }, + }); + assert.deepEqual(item.input, { city: "Berlin" }); + } + assert.equal(new Set(items.map((item) => item.id)).size, 1); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - it.effect("names an expired Claude login instead of the terminal API error", () => - Effect.gen(function* () { - const configDir = "/synthetic/Claude config"; - // The adapter resolves the cwd on the host, which adds a drive letter on Windows. - const cwd = NodePath.resolve("/synthetic/project"); - const harness = yield* makeWakeHarnessWithOptions({ - environment: { CLAUDE_CONFIG_DIR: configDir }, - }); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-auth-failure"), - text: "Continue.", - attachments: [], - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd, - }), - }), - ); - yield* Queue.offerAll(harness.sdkMessages, [ - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000606", - error: "authentication_failed", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000607", - result: "API Error", - terminalReason: "api_error", - }), - ]); + 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); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.include(terminal.failure.message, "run `claude auth login`"); - assert.include(terminal.failure.message, configDir); - // The message quotes its paths, which escapes Windows separators. - assert.include(terminal.failure.message, JSON.stringify(cwd)); - assert.notInclude(terminal.failure.message, "repeated API errors"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + 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: "ultracode" }, + { id: "fastMode", value: true }, + ], + }), + ); + yield* settle; + yield* harness.runtime.startTurn(turn(4, { ...normal, model: "claude-sonnet-4-6" })); + yield* settle; + assert.deepEqual(harness.liveSelectionChanges, [ + { model: "claude-opus-5-5" }, + { effortLevel: "xhigh", 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, 4); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), ), - ), ); - it.effect("shows a 403 permission error instead of the login hint", () => - 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-permission-denied"), - text: "Continue.", - attachments: [], - }), - ); - // Claude CLI 2.1.288 labels a 403 authentication_failed too. - const cliText = - "Failed to authenticate. API Error: 403 Your organization does not have access to this model."; - yield* Queue.offerAll(harness.sdkMessages, [ - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000608", - error: "authentication_failed", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000609", - result: cliText, - isError: true, - apiErrorStatus: 403, - terminalReason: "api_error", - }), - ]); - - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.equal(terminal.failure.message, cliText); - assert.equal(terminal.failure.code, "api_error_403"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect.each([ - { recovered: false, expected: "Claude usage limit reached" }, - { recovered: true, expected: "Claude gave up after repeated API errors" }, - ])("tracks whether a rejected usage window recovered ($recovered)", ({ recovered, expected }) => - 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-window-${recovered}`), - text: "Continue.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { status: "rejected", rateLimitType: "five_hour" }, - uuid: "00000000-0000-4000-8000-000000000608", - session_id: WAKE_NATIVE_SESSION, - }), - ); - if (recovered) { - yield* Queue.offer( - harness.sdkMessages, + it.effect.each(["completed", "interrupted"] as const)( + "projects Claude thinking blocks when %s", + (status) => + 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("reasoning-attempt"), + text: "Check the plan", + attachments: [], + }), + ); + const stream = (event: unknown, parent: string | null = null) => claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { status: "allowed", rateLimitType: "five_hour" }, - uuid: "00000000-0000-4000-8000-000000000609", + type: "stream_event", + event, + parent_tool_use_id: parent, + session_id: WAKE_NATIVE_SESSION, + uuid: "stream-frame", + }); + const snapshot = (id: string, uuid: string, thinking: string) => + claudeSdkFrame({ + type: "assistant", + uuid, session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { + id, + model: "claude-sonnet-4-6", + content: [{ type: "thinking", thinking, signature: "secret-signature" }], + }, + }); + const frames = [ + stream({ type: "message_start", message: { id: "thought-message" } }), + stream({ + type: "content_block_start", + index: 2, + content_block: { type: "thinking", thinking: "" }, + }), + stream({ + type: "content_block_delta", + index: 2, + delta: { type: "thinking_delta", thinking: "First " }, + }), + stream({ + type: "content_block_delta", + index: 2, + delta: { type: "thinking_delta", thinking: "thought" }, + }), + stream({ + type: "content_block_delta", + index: 2, + delta: { type: "signature_delta", signature: "secret-signature" }, + }), + stream({ type: "content_block_stop", index: 2 }), + snapshot("thought-message", "first-snapshot", "Authoritative first thought"), + snapshot("thought-message", "first-snapshot", "Authoritative first thought"), + stream({ + type: "content_block_start", + index: 4, + content_block: { type: "thinking", thinking: "Second thought" }, + }), + stream({ type: "content_block_stop", index: 4 }), + snapshot("thought-message", "second-snapshot", ""), + snapshot("completion-only", "third-snapshot", "Completion only"), + snapshot("redacted", "empty-snapshot", ""), + stream({ type: "message_start", message: { id: "child-message" } }, "child-tool"), + stream( + { + type: "content_block_start", + index: 0, + content_block: { type: "thinking", thinking: "Child thought" }, + }, + "child-tool", + ), + stream({ type: "message_start", message: { id: "partial-message" } }), + stream({ + type: "content_block_start", + index: 0, + content_block: { type: "thinking", thinking: "Partial thought" }, + }), + makeResultFrame({ + uuid: "reasoning-result", + result: "", + ...(status === "interrupted" ? { terminalReason: "aborted_streaming" as const } : {}), }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, status); + const latest = new Map( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "reasoning" + ? [[event.turnItem.id, event.turnItem] as const] + : [], + ), ); - } - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000610", - result: "API Error", - terminalReason: "api_error", - }), - ); + assert.deepEqual( + [...latest.values()].map((item) => item.text), + ["Authoritative first thought", "Second thought", "Completion only", "Partial thought"], + ); + assert.equal(new Set([...latest.values()].map((item) => item.ordinal)).size, 4); + for (const item of latest.values()) { + assert.equal(item.streaming, false); + assert.isNotNull(item.completedAt); + } + assert.isFalse( + harness.events.some( + (event) => event.type === "message.updated" && event.message.role === "assistant", + ), + ); + for (const item of latest.values()) assert.notInclude(item.text, "secret-signature"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.include(terminal.failure.message, expected); - assert.equal(terminal.failure.class, recovered ? "provider_error" : "usage_limit"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + // regression: #15892 non-execution metadata is carried through, not guessed from result text + it.effect.each(["cancelled", "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" ? "cancelled" : "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), + ), + ), ), - ), ); - it.effect.each([ - { - name: "fails a /compact the usage limit stopped", - limited: true, - compaction: "failed", - compact: true, - status: "failed", - }, - { - name: "completes an unlimited failed /compact", - limited: false, - compaction: "failed", - compact: true, - status: "completed", - }, - { - name: "completes a successful limited /compact", - limited: true, - compaction: "success", - compact: true, - status: "completed", - }, - { - name: "completes a failed automatic compaction", - limited: true, - compaction: "failed", - compact: false, - status: "completed", - }, - ] as const)("$name", ({ name, limited, compaction, compact, status }) => + it.effect.each( + (["aborted_tools", "aborted_streaming"] as const).flatMap((terminalReason) => + [true, false].map((steered) => ({ terminalReason, steered })), + ), + )("handles $terminalReason with active steering=$steered", ({ terminalReason, steered }) => + Effect.scoped( + Effect.gen(function* () { + 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, + 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"); + } + yield* Queue.offer( + harness.sdkMessages, + 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 (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); + assert.equal(terminal.status, steered ? "completed" : "interrupted"); + if (steered) { + 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: "complete", + hasSubagents: false, + inputTokens: 603 + 2847 + 11455, + outputTokens: 46, + cachedInputTokens: 11455, + cacheCreationTokens: 2847, + }, + ); + } + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + + it.effect("announces usage-limit pauses once per window and again on a new turn", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const resetsAt = 1791991200; - const compactError = - "Error during compaction: You've hit your session limit · resets 5:20pm (Europe/Berlin)."; + const resetsAt = Math.floor(DateTime.toEpochMillis(now) / 1000) + 7_200; + const limit = (rateLimitType: "five_hour" | "seven_day" = "five_hour") => + claudeSdkFrame({ + type: "rate_limit_event", + rate_limit_info: { status: "rejected", rateLimitType, resetsAt }, + uuid: "00000000-0000-4000-8000-000000000601", + session_id: WAKE_NATIVE_SESSION, + }); + const start = (ordinal: number) => + harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-claude-limit-${ordinal}`), + providerTurnOrdinal: ordinal, + text: "Continue.", + attachments: [], + }), + ); + yield* start(1); + yield* Queue.offer(harness.sdkMessages, limit()); + const pause = (yield* Queue.take(harness.systemNoticeReceipts)).turnItem; + assert.equal(pause.type, "system_notice"); + if (pause.type !== "system_notice") return; + assert.equal( + pause.message, + "Claude usage limit reached. This turn is paused until the 5-hour limit resets in 2h.", + ); + assert.lengthOf(harness.terminalEvents(), 0); + yield* Queue.offerAll(harness.sdkMessages, [ + limit(), + limit("seven_day"), + limit(), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000602", + result: "Recovered.", + }), + ]); + yield* Queue.take(harness.terminalReceipts); + const notices = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice" + ? [event.turnItem] + : [], + ); + assert.lengthOf(notices(), 2); + yield* start(2); + yield* Queue.offerAll(harness.sdkMessages, [ + limit(), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000603", + result: "Done.", + }), + ]); + yield* Queue.take(harness.terminalReceipts); + assert.lengthOf(notices(), 3); + assert.notEqual(notices()[0]?.id, notices()[2]?.id); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect("keeps a later future-window event-supplied Claude reset over the embedded reset", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make(`attempt-claude-compaction-${name}`), - text: compact ? "/compact" : "Continue.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-embedded-limit-event"), + text: "Continue.", attachments: [], }), ); - // Claude reports a compaction's outcome on a status frame. A /compact - // then ends with a success result naming the command and no terminal - // reason, even when the compaction failed (#19327). The automatic case - // omits the terminal reason too, so only the missing command keeps it - // completed. - const result = makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000613", - result: compact ? "" : "Done.", - numTurns: compact ? 0 : 1, - terminalReason: null, - }); yield* Queue.offerAll(harness.sdkMessages, [ - ...(limited - ? [ - claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { status: "rejected", rateLimitType: "five_hour", resetsAt }, - uuid: "00000000-0000-4000-8000-000000000611", - session_id: WAKE_NATIVE_SESSION, - }), - ] - : []), claudeSdkFrame({ - type: "system", - subtype: "status", - status: null, - compact_result: compaction, - ...(compaction === "failed" - ? { compact_error: limited ? compactError : "Not enough messages to compact." } - : {}), - uuid: "00000000-0000-4000-8000-000000000612", + type: "rate_limit_event", + rate_limit_info: { + status: "rejected", + rateLimitType: "future_window", + resetsAt: 1791807600, + }, + uuid: "00000000-0000-4000-8000-000000000683", session_id: WAKE_NATIVE_SESSION, }), - compact ? claudeSdkFrame({ ...result, local_command: "compact" }) : result, + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000684", + error: "rate_limit", + apiErrorParams: { + rate_limit_info: { + status: "rejected", + rateLimitType: "five_hour", + resetsAt: 1791804000, + }, + }, + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000685", + result: "Usage limit reached.", + isError: true, + apiErrorStatus: 429, + terminalReason: "api_error", + }), ]); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, status); + assert.equal(terminal.status, "failed"); if (terminal.status !== "failed") return; assert.equal(terminal.failure.class, "usage_limit"); - assert.equal(terminal.failure.message, compactError); - assert.equal( - terminal.failure.resetAt, - DateTime.formatIso(DateTime.makeUnsafe(resetsAt * 1000)), - ); + assert.equal(terminal.failure.resetAt, "2026-10-12T12:20:00.000Z"); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -3484,19 +3882,54 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); it.effect.each([ - { name: "parent limit", parentErrors: ["rate_limit"], expectedLimit: true }, { - name: "parent limit then nested response", - parentErrors: ["rate_limit", "nested-ok"], - expectedLimit: true, + name: "an unflagged result with surrounding whitespace", + isError: false, + result: " API Error: 400 Request rejected by a safeguard.\n", + expected: "API Error: 400 Request rejected by a safeguard.", }, - { name: "nested limit", parentErrors: ["nested-limit"], expectedLimit: false }, { - name: "parent limit then parent response", - parentErrors: ["rate_limit", "ok"], - expectedLimit: false, + name: "a secret crossing the truncation boundary", + isError: true, + result: `API Error: 400 ${"x".repeat(440)} {"token":"${"synthetic-secret".repeat(100)}"} ${"y".repeat(100)}`, + expected: `API Error: 400 ${"x".repeat(440)} {"token":"[REDACTED]"} `.padEnd(500, "y"), }, - ])("classifies retried terminal API failures after $name", ({ parentErrors, expectedLimit }) => + { + name: "ordinary assistant text", + isError: true, + result: "I found three files.", + expected: "Claude gave up after repeated API errors.", + }, + { + name: "a listed non-diagnostic error", + isError: true, + result: "API Error: 400 Request rejected.", + errors: ["[ede_diagnostic] internal detail", "Tool execution failed: EACCES"], + expected: "Tool execution failed: EACCES", + }, + { + name: "an HTTP 529 overload", + isError: true, + result: "API Error: 529 Specific overload detail.", + apiErrorStatus: 529, + expected: "Claude API is overloaded (529). Try again shortly.", + }, + { + name: "an HTTP 429 rate limit", + isError: true, + result: "API Error: 429 Specific rate limit detail.", + apiErrorStatus: 429, + expected: "Claude API rate limit reached. Try again later.", + }, + { + name: "a different terminal reason", + isError: true, + result: "API Error: 400 Request rejected.", + terminalReason: "prompt_too_long" as const, + expected: + "Claude stopped: the prompt exceeds the model's context window. Run /compact or start a new thread.", + }, + ])("reports terminal API error text for $name", (input) => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; @@ -3505,40 +3938,32 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make(`attempt-claude-retry-${parentErrors.join("-")}`), + attemptId: RunAttemptId.make("attempt-claude-specific-api-error"), text: "Continue.", attachments: [], }), ); - for (const [index, evidence] of parentErrors.entries()) { - yield* Queue.offer( - harness.sdkMessages, - makeAssistantErrorFrame({ - uuid: `00000000-0000-4000-8000-00000000062${index}`, - error: evidence.includes("limit") ? "rate_limit" : undefined, - parentToolUseId: evidence.startsWith("nested") ? "nested-tool" : null, - }), - ); - } + const apiErrorStatus = input.apiErrorStatus ?? 400; yield* Queue.offer( harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000629", - result: "API Error", - isError: true, - terminalReason: "api_error", + uuid: "00000000-0000-4000-8000-000000000699", + result: input.result, + terminalReason: input.terminalReason ?? "api_error", + apiErrorStatus, + isError: input.isError, + ...(input.errors === undefined ? {} : { errors: input.errors }), }), ); const terminal = yield* Queue.take(harness.terminalReceipts); assert.equal(terminal.status, "failed"); if (terminal.status !== "failed") return; - assert.equal(terminal.failure.class, expectedLimit ? "usage_limit" : "provider_error"); + assert.equal(terminal.failure.message, input.expected); + assert.equal(terminal.failure.code, `api_error_${apiErrorStatus}`); assert.equal( - terminal.failure.message, - expectedLimit - ? "Claude usage limit reached. Send the message again once the limit resets." - : "Claude gave up after repeated API errors.", + terminal.failure.class, + apiErrorStatus === 429 ? "usage_limit" : "provider_error", ); }).pipe( Effect.provide( @@ -3547,57 +3972,49 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each([ - { status: 503, cooldown: "4m 6s", seconds: 246 }, - { status: 503, cooldown: "1h 2m 3s", seconds: 3723 }, - { status: 503, cooldown: "7s", seconds: 7 }, - { status: 503, cooldown: "0s", seconds: 0 }, - { status: 503, cooldown: "unknown", seconds: 0 }, - { status: 503, cooldown: "999999999999999999999999h", seconds: 0 }, - { status: 503, cooldown: "4m 6s", seconds: 0, errorType: "overloaded_error" }, - { status: 401, cooldown: "4m 6s", seconds: 0 }, - ])("recovers wrapped gateway limits with status $status and cooldown $cooldown", (input) => + it.effect("names an expired Claude login instead of the terminal API error", () => Effect.gen(function* () { - const harness = yield* makeWakeHarness; + const configDir = "/synthetic/Claude config"; + // The adapter resolves the cwd on the host, which adds a drive letter on Windows. + const cwd = NodePath.resolve("/synthetic/project"); + const harness = yield* makeWakeHarnessWithOptions({ + environment: { CLAUDE_CONFIG_DIR: configDir }, + }); const now = yield* DateTime.now; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-gateway-limit"), + attemptId: RunAttemptId.make("attempt-claude-auth-failure"), text: "Continue.", attachments: [], + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd, + }), }), ); yield* Queue.offerAll(harness.sdkMessages, [ makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000652", - error: "server_error", + uuid: "00000000-0000-4000-8000-000000000606", + error: "authentication_failed", }), makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000653", - result: `API Error: ${input.status} [claude/claude-opus-5-5] [429]: {"type":"error","error":{"type":"${input.errorType ?? "rate_limit_error"}","message":"Please try again later."}} (reset after ${input.cooldown}).`, + uuid: "00000000-0000-4000-8000-000000000607", + result: "API Error: 401 Credentials expired.", terminalReason: "api_error", - isError: true, - apiErrorStatus: input.status, }), ]); + const terminal = yield* Queue.take(harness.terminalReceipts); assert.equal(terminal.status, "failed"); if (terminal.status !== "failed") return; - assert.equal(terminal.failure.class, input.seconds > 0 ? "usage_limit" : "provider_error"); - if (input.seconds > 0) { - assert.equal(terminal.failure.retryable, true); - assert.equal( - terminal.failure.resetAt, - DateTime.formatIso( - DateTime.makeUnsafe(DateTime.toEpochMillis(now) + input.seconds * 1_000), - ), - ); - } else { - assert.isUndefined(terminal.failure.resetAt); - } + assert.include(terminal.failure.message, "run `claude auth login`"); + assert.include(terminal.failure.message, configDir); + assert.include(terminal.failure.message, JSON.stringify(cwd)); + assert.notInclude(terminal.failure.message, "repeated API errors"); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -3605,115 +4022,42 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each([429, 401, 503, 529])( - "classifies the current Claude API status %s after rate-limit evidence", - (apiErrorStatus) => - 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-status-${apiErrorStatus}`), - text: "Continue.", - attachments: [], - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantErrorFrame({ - uuid: "00000000-0000-4000-8000-000000000650", - error: "rate_limit", - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000651", - result: "API Error", - terminalReason: "api_error", - isError: true, - apiErrorStatus, - }), - ); - const terminal = yield* Queue.take(harness.terminalReceipts); - assert.equal(terminal.status, "failed"); - if (terminal.status !== "failed") return; - assert.equal( - terminal.failure.class, - apiErrorStatus === 429 ? "usage_limit" : "provider_error", - ); - if (apiErrorStatus !== 429) - assert.notInclude(terminal.failure.message.toLowerCase(), "usage limit"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("keeps the measured context when a usage limit ends the turn", () => + it.effect("shows a 403 permission error instead of the login hint", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-limit-context"), + now, + attemptId: RunAttemptId.make("attempt-claude-permission-denied"), text: "Continue.", attachments: [], }), ); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000660", text: "Working." }), - ); - // The CLI answers a 429 with a locally generated frame that reports no usage. - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "assistant", - message: { - model: "", - id: "00000000-0000-4000-8000-000000000661", - type: "message", - role: "assistant", - content: [{ type: "text", text: "You've hit your session limit" }], - stop_reason: "stop_sequence", - stop_sequence: "", - usage: { - input_tokens: 0, - output_tokens: 0, - cache_creation_input_tokens: 0, - cache_read_input_tokens: 0, - }, - }, - parent_tool_use_id: null, - error: "rate_limit", - uuid: "00000000-0000-4000-8000-000000000661", - session_id: WAKE_NATIVE_SESSION, + // Claude CLI 2.1.288 labels a 403 authentication_failed too. + const cliText = + "Failed to authenticate. API Error: 403 Your organization does not have access to this model."; + yield* Queue.offerAll(harness.sdkMessages, [ + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000608", + error: "authentication_failed", }), - ); - yield* Queue.offer( - harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000662", - result: "You've hit your session limit", - terminalReason: "api_error", + uuid: "00000000-0000-4000-8000-000000000609", + result: cliText, isError: true, - apiErrorStatus: 429, + apiErrorStatus: 403, + terminalReason: "api_error", }), - ); + ]); + const terminal = yield* Queue.take(harness.terminalReceipts); assert.equal(terminal.status, "failed"); - const reportedContext = harness.events.flatMap((event) => - event.type === "provider_turn.updated" && event.providerTurn.tokenUsage - ? [event.providerTurn.tokenUsage.usedTokens] - : [], - ); - assert.deepEqual(reportedContext, [2]); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.message, cliText); + assert.equal(terminal.failure.code, "api_error_403"); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -3721,916 +4065,1010 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("surfaces a Claude safety model fallback without failing the turn", () => + const lastProviderTurn = (events: ReadonlyArray) => { + const event = events.findLast((candidate) => candidate.type === "provider_turn.updated"); + if (event?.type !== "provider_turn.updated") { + throw new Error("Expected a provider turn update."); + } + return event.providerTurn; + }; + const makeRollbackHarness = makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + }); + + it.effect.each([ + { kind: "fork with inherited head", fork: true, headMessageId: "remapped-inherited-head" }, + { kind: "fork without recorded head", fork: true, headMessageId: undefined }, + { kind: "ordinary thread", fork: false, headMessageId: undefined }, + ])("rolls back the first run of a $kind", ({ fork, headMessageId }) => 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("claude-safety-fallback-attempt"), - text: "Continue the audit", - attachments: [], - }), - ); - const notice = "Safeguards flagged this message. Switched to Opus 4.8."; - const uuid = "00000000-0000-4000-8000-000000000301"; - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "model_refusal_fallback", - trigger: "refusal", - direction: "retry", - original_model: "claude-fable-5", - fallback_model: "claude-opus-4-8", - request_id: "request-safety-fallback", - api_refusal_category: "cyber", - api_refusal_explanation: null, - content: notice, - session_id: WAKE_NATIVE_SESSION, - uuid, - }), + let allocations = 0; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + freshQueueOnReopen: true, + allocateSessionId: Effect.sync(() => + allocations++ === 0 ? WAKE_NATIVE_SESSION : "fresh-native-session", + ), + forkSession: () => + Effect.succeed({ + sessionId: WAKE_NATIVE_SESSION, + ...(headMessageId === undefined ? {} : { headMessageId }), + }), + }); + const providerThread = fork + ? yield* harness.runtime.forkThread({ + sourceProviderThread: { + ...harness.providerThread, + nativeThreadRef: { + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeId: "source-native-session", + strength: "strong", + }, + }, + targetThreadId: harness.threadId, + }) + : harness.providerThread; + const turnInput = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("first-run"), + text: "This run will be rolled back.", + attachments: [], + nativeThreadHasTurns: false, + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "own-run-message", text: "Discard this answer." }), ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000302", - result: "Audit complete.", - }), + yield* harness.offerAndWait( + makeResultFrame({ uuid: "own-run-result", result: "Discard this answer." }), ); - yield* Queue.take(harness.terminalReceipts); - const notices = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "system_notice" - ? [event.turnItem] - : [], + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + const completed = harness.events.findLast( + (event) => event.type === "provider_thread.updated", ); - assert.lengthOf(notices, 1); - assert.equal(notices[0]?.message, notice); - assert.equal(notices[0]?.status, "completed"); - assert.equal(notices[0]?.nativeItemRef?.nativeId, uuid); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isFalse( - harness.events.some( - (event) => event.type === "turn_item.updated" && event.turnItem.type === "error", - ), + assert.equal(completed?.type, "provider_thread.updated"); + if (completed?.type !== "provider_thread.updated") return; + assert.equal(completed.providerThread.firstRunOrdinal, 1); + + const rolledBack = yield* harness.runtime.rollbackThread({ + providerThread: completed.providerThread, + target: { + type: "thread_start", + checkpointId: CheckpointId.make("checkpoint-before-first-run"), + appRunOrdinal: 0, + }, + providerThreadTurns: [lastProviderTurn(harness.events)], + }); + assert.equal( + rolledBack.providerThread.forkedFrom?.providerThreadId, + providerThread.forkedFrom?.providerThreadId, ); + yield* harness.runtime.startTurn({ + ...turnInput, + attemptId: RunAttemptId.make("after-rollback"), + providerThread: rolledBack.providerThread, + providerTurnOrdinal: 2, + nativeThreadHasTurns: false, + }); + const options = harness.getOpenedOptions(); + assert.equal(harness.processQueues.length, 2); + if (headMessageId !== undefined) { + assert.equal(rolledBack.providerThread.nativeThreadRef?.nativeId, WAKE_NATIVE_SESSION); + assert.equal(rolledBack.providerThread.nativeConversationHeadRef?.nativeId, headMessageId); + assert.equal(options?.resume, WAKE_NATIVE_SESSION); + assert.equal(options?.resumeSessionAt, headMessageId); + assert.isUndefined(options?.sessionId); + } else { + assert.equal(rolledBack.providerThread.nativeThreadRef?.nativeId, "fresh-native-session"); + assert.isNull(rolledBack.providerThread.nativeConversationHeadRef); + assert.equal(options?.sessionId, "fresh-native-session"); + assert.isUndefined(options?.resume); + assert.isUndefined(options?.resumeSessionAt); + } }).pipe( - Effect.scoped, Effect.provide( - Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); it.effect( - "runs native compaction and keeps its context watermark separate from billed usage", + "rolls back to the main-thread assistant message when a subagent frame comes last", () => Effect.gen(function* () { - const harness = yield* makeWakeHarness; + const harness = yield* makeRollbackHarness; const now = yield* DateTime.now; - const compact = harness.runtime.compactThread; - assert.isDefined(compact); - if (compact === undefined) return; - yield* compact( + const mainUuid = "00000000-0000-4000-8000-000000000641"; + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("claude-native-compact-attempt"), - text: " /COMPACT ", + attemptId: RunAttemptId.make("attempt-claude-cursor-main"), + text: "Continue.", attachments: [], }), ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "compact_boundary", - compact_metadata: { trigger: "manual", pre_tokens: 1500, post_tokens: 400 }, - uuid: "00000000-0000-4000-8000-000000000201", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000202", - result: "Compacted conversation.", + yield* Queue.offerAll(harness.sdkMessages, [ + makeAssistantTextFrame({ uuid: mainUuid, text: "Delegating." }), + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000642", + error: undefined, + parentToolUseId: "toolu_subagent", }), - ); + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000643", result: "Done." }), + ]); yield* Queue.take(harness.terminalReceipts); - assert.deepEqual(harness.offeredMessages[0]?.message.content, "/compact"); - const compaction = harness.events.find( - (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", - ); - assert.isDefined(compaction); - if (compaction?.type === "turn_item.updated" && compaction.turnItem.type === "compaction") { - assert.equal(compaction.turnItem.beforeTokenCount, 1500); - assert.equal(compaction.turnItem.afterTokenCount, 400); - assert.equal(compaction.turnItem.status, "completed"); - } - const watermark = harness.events.find( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.tokenUsage?.usedTokens === 400, - ); - assert.isDefined(watermark); - const completed = harness.events.findLast( - (event) => event.type === "provider_turn.updated", - ); - assert.equal(completed?.type, "provider_turn.updated"); - if (completed?.type === "provider_turn.updated") { - assert.deepEqual(completed.providerTurn.turnTokenUsage, { - usageScope: "main_agent", - usageStatus: "complete", - hasSubagents: false, - inputTokens: 1, - outputTokens: 1, - cachedInputTokens: 0, - cacheCreationTokens: 0, - }); - } + const providerTurn = lastProviderTurn(harness.events); + assert.equal(providerTurn.nativeTurnRef?.nativeId, mainUuid); + const rolledBack = yield* harness.runtime.rollbackThread({ + providerThread: harness.providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint-claude-cursor-main"), + appRunOrdinal: 1, + providerTurn, + }, + providerThreadTurns: [ + providerTurn, + { + ...providerTurn, + id: ProviderTurnId.make("provider-turn-claude-cursor-next"), + ordinal: 2, + }, + ], + }); + assert.equal(rolledBack.providerThread.nativeConversationHeadRef?.nativeId, mainUuid); }).pipe( - Effect.scoped, Effect.provide( - Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - it.effect("titles Claude reads, searches, and skills on tool completion", () => + it.effect("never records a subagent uuid for a turn with no main-thread assistant message", () => Effect.gen(function* () { - const harness = yield* makeWakeHarness; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + freshQueueOnReopen: true, + }); const now = yield* DateTime.now; + const subagentUuid = "00000000-0000-4000-8000-000000000644"; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-read-images"), - text: "Read the files", + attemptId: RunAttemptId.make("attempt-claude-cursor-subagent-only"), + text: "Background task completed.", attachments: [], }), ); - const tools = [ - { id: "image", name: "Read", input: { file_path: " /workspace/reference.png " } }, - { id: "text", name: "Read", input: { file_path: "/workspace/README.md" } }, - { id: "search", name: "Grep", input: { pattern: "TODO", path: "/workspace/src" } }, - { id: "skill", name: "Skill", input: { skill: "full-send" } }, + yield* Queue.offerAll(harness.sdkMessages, [ + makeAssistantErrorFrame({ + uuid: subagentUuid, + error: undefined, + parentToolUseId: "toolu_subagent", + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000645", result: "Done." }), + ]); + yield* Queue.take(harness.terminalReceipts); + + const providerTurn = lastProviderTurn(harness.events); + assert.notEqual(providerTurn.nativeTurnRef?.nativeId, subagentUuid); + const rollbackTo = (providerThreadTurns: ReadonlyArray) => + harness.runtime.rollbackThread({ + providerThread: harness.providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint-claude-cursor-subagent-only"), + appRunOrdinal: 1, + providerTurn, + }, + providerThreadTurns, + }); + + const latest = yield* rollbackTo([providerTurn]); + assert.isNull(latest.providerThread.nativeConversationHeadRef); + const error = yield* rollbackTo([ + providerTurn, { - id: "write", - name: "Write", - input: { file_path: "/workspace/output.png", content: "text" }, + ...providerTurn, + id: ProviderTurnId.make("provider-turn-claude-cursor-next"), + ordinal: 2, }, - ]; - yield* Queue.offer( - harness.sdkMessages, + ]).pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterRollbackThreadError); + assert.include(String(error.cause), "no SDK assistant message cursor"); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: latest.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-cursor-subagent-only-next"), + text: "Continue.", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + const reopenedQueue = harness.processQueues[1]; + assert.isDefined(reopenedQueue); + if (reopenedQueue === undefined) return; + yield* Queue.offerAll(reopenedQueue, [ + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000646", + text: "Continuing.", + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000647", result: "Done." }), + ]); + const next = yield* Queue.take(harness.terminalReceipts); + assert.equal(next.status, "completed"); + assert.isUndefined(harness.getOpenedOptions()?.resumeSessionAt); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect.each([ + { + name: "fails a /compact the usage limit stopped", + limited: true, + compaction: "failed", + compact: true, + status: "failed", + }, + { + name: "completes an unlimited failed /compact", + limited: false, + compaction: "failed", + compact: true, + status: "completed", + }, + { + name: "completes a successful limited /compact", + limited: true, + compaction: "success", + compact: true, + status: "completed", + }, + { + name: "completes a failed automatic compaction", + limited: true, + compaction: "failed", + compact: false, + status: "completed", + }, + ] as const)("$name", ({ name, limited, compaction, compact, status }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const resetsAt = 1791991200; + const compactError = + "Error during compaction: You've hit your session limit · resets 5:20pm (Europe/Berlin)."; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-claude-compaction-${name}`), + text: compact ? "/compact" : "Continue.", + attachments: [], + }), + ); + // Failed /compact reports success without a terminal reason; status frames carry outcomes, including automatic compaction. + const result = makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000613", + result: compact ? "" : "Done.", + numTurns: compact ? 0 : 1, + terminalReason: null, + }); + yield* Queue.offerAll(harness.sdkMessages, [ + ...(limited + ? [ + claudeSdkFrame({ + type: "rate_limit_event", + rate_limit_info: { status: "rejected", rateLimitType: "five_hour", resetsAt }, + uuid: "00000000-0000-4000-8000-000000000611", + session_id: WAKE_NATIVE_SESSION, + }), + ] + : []), claudeSdkFrame({ - type: "assistant", - uuid: "00000000-0000-4000-8000-000000000601", + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000610", session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - id: "msg_image_reads", - model: "claude-sonnet-4-6", - 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, - }, - }, }), - ); - yield* Queue.offer( - harness.sdkMessages, claudeSdkFrame({ - type: "user", - uuid: "00000000-0000-4000-8000-000000000602", + type: "system", + subtype: "status", + status: null, + compact_result: compaction, + ...(compaction === "failed" + ? { compact_error: limited ? compactError : "Not enough messages to compact." } + : {}), + uuid: "00000000-0000-4000-8000-000000000612", session_id: WAKE_NATIVE_SESSION, - parent_tool_use_id: null, - message: { - role: "user", - content: tools.map((tool) => ({ - type: "tool_result", - tool_use_id: tool.id, - content: "ok", - })), - }, }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000603", result: "Read files" }), - ); - yield* Queue.take(harness.terminalReceipts); - const items = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.status === "completed" + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: "Compaction finished; turn continues.", + level: "warning", + uuid: "00000000-0000-4000-8000-000000000614", + session_id: WAKE_NATIVE_SESSION, + }), + ]); + yield* Queue.take(harness.systemNoticeReceipts); + const updates = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" ? [event.turnItem] : [], ); - const image = items.find((item) => item.nativeItemRef?.nativeId === "image"); - assert.equal(image?.type, "dynamic_tool"); - if (image?.type === "dynamic_tool") - assert.equal(image.viewedImagePath, "/workspace/reference.png"); - assert.equal(image?.title, "Read /workspace/reference.png"); + assert.lengthOf(updates, 2); + const [running, settled] = updates; + assert.equal(running?.status, "running"); + assert.equal(settled?.status, compaction === "success" ? "completed" : "failed"); assert.equal( - items.find((item) => item.nativeItemRef?.nativeId === "text")?.title, - "Read /workspace/README.md", + settled?.type === "compaction" ? settled.summary : undefined, + compaction === "failed" + ? limited + ? compactError + : "Not enough messages to compact." + : undefined, + ); + assert.equal(settled?.id, running?.id); + assert.equal(settled?.ordinal, running?.ordinal); + assert.deepEqual(settled?.startedAt, running?.startedAt); + assert.isNotNull(settled?.completedAt); + assert.isEmpty(harness.terminalEvents()); + + yield* Queue.offerAll( + harness.sdkMessages, + compact + ? [ + // Claude Code echoes the command's stdout as a synthetic assistant message. + claudeSdkFrame({ + ...makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000615", + text: "Compacted.", + }), + local_command_source: "Compacted.", + }), + claudeSdkFrame({ ...result, local_command: "compact" }), + ] + : [result], + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], + ), + updates, ); + assert.equal(terminal.status, status); assert.equal( - items.find((item) => item.nativeItemRef?.nativeId === "search")?.title, - "Searched TODO in src", + harness.events.some( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message", + ), + !compact, ); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.class, "usage_limit"); + assert.equal(terminal.failure.message, compactError); assert.equal( - items.find((item) => item.nativeItemRef?.nativeId === "skill")?.title, - "Skill: full-send", + terminal.failure.resetAt, + DateTime.formatIso(DateTime.makeUnsafe(resetsAt * 1000)), ); - for (const item of items.filter((item) => item.nativeItemRef?.nativeId !== "image")) - assert.notProperty(item, "viewedImagePath"); }).pipe( - Effect.scoped, Effect.provide( - Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - 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: [], + it.effect("keeps an unreported /compact failure's reason on the compaction, not as a reply", () => + 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-compaction-unreported"), + text: "/compact", + attachments: [], + }), + ); + // Claude can refuse a /compact without a compact_result: the only reason is the result text. + yield* Queue.offerAll(harness.sdkMessages, [ + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000620", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + ...makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000622", + text: "Not enough messages to compact.", }), - ); - 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* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "status", - status: null, - permissionMode: "plan", - uuid: "00000000-0000-4000-8000-000000000508", - session_id: WAKE_NATIVE_SESSION, + local_command_source: + "Not enough messages to compact.", + }), + claudeSdkFrame({ + ...makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000621", + result: "Not enough messages to compact.", + numTurns: 0, + terminalReason: null, }), - ); + local_command: "compact", + }), + ]); + yield* Queue.take(harness.terminalReceipts); + const settled = harness.events + .flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], + ) + .at(-1); + assert.equal(settled?.status, "failed"); + assert.equal(settled?.summary, "Not enough messages to compact."); + assert.isFalse( + harness.events.some( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message", + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect.each([ + { name: "parent limit", parentErrors: ["rate_limit"], expectedLimit: true }, + { + name: "parent limit then nested response", + parentErrors: ["rate_limit", "nested-ok"], + expectedLimit: true, + }, + { name: "nested limit", parentErrors: ["nested-limit"], expectedLimit: false }, + { + name: "parent limit then parent response", + parentErrors: ["rate_limit", "ok"], + expectedLimit: false, + }, + ])("classifies retried terminal API failures after $name", ({ parentErrors, expectedLimit }) => + 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-retry-${parentErrors.join("-")}`), + text: "Continue.", + attachments: [], + }), + ); + for (const [index, evidence] of parentErrors.entries()) { yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000503", - result: "Todo recorded.", + makeAssistantErrorFrame({ + uuid: `00000000-0000-4000-8000-00000000062${index}`, + error: evidence.includes("limit") ? "rate_limit" : undefined, + parentToolUseId: evidence.startsWith("nested") ? "nested-tool" : null, + ...(evidence.includes("limit") + ? { + apiErrorParams: { + rate_limit_info: { + status: "rejected", + rateLimitType: "five_hour", + resetsAt: 1790298600, + }, + }, + } + : {}), }), ); - yield* Queue.take(harness.terminalReceipts); + } + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000629", + result: "API Error", + isError: true, + terminalReason: "api_error", + }), + ); - 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", - }, + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.class, expectedLimit ? "usage_limit" : "provider_error"); + assert.equal( + terminal.failure.resetAt, + expectedLimit ? "2026-09-25T01:10:00.000Z" : undefined, + ); + assert.equal( + terminal.failure.message, + expectedLimit + ? "Claude usage limit reached. Send the message again once the limit resets." + : "Claude gave up after repeated API errors.", + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect.each([ + { status: 503, cooldown: "4m 6s", seconds: 246 }, + { status: 503, cooldown: "1h 2m 3s", seconds: 3723 }, + { status: 503, cooldown: "7s", seconds: 7 }, + { status: 503, cooldown: "0s", seconds: 0 }, + { status: 503, cooldown: "unknown", seconds: 0 }, + { status: 503, cooldown: "999999999999999999999999h", seconds: 0 }, + { status: 503, cooldown: "4m 6s", seconds: 0, errorType: "overloaded_error" }, + { status: 401, cooldown: "4m 6s", seconds: 0 }, + ])("recovers wrapped gateway limits with status $status and cooldown $cooldown", (input) => + 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-gateway-limit"), + text: "Continue.", + attachments: [], + }), + ); + yield* Queue.offerAll(harness.sdkMessages, [ + makeAssistantErrorFrame({ + uuid: "00000000-0000-4000-8000-000000000652", + error: "server_error", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000653", + result: `API Error: ${input.status} [claude/claude-opus-5-5] [429]: {"type":"error","error":{"type":"${input.errorType ?? "rate_limit_error"}","message":"Please try again later."}} (reset after ${input.cooldown}).`, + terminalReason: "api_error", + isError: true, + apiErrorStatus: input.status, + }), + ]); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status !== "failed") return; + assert.equal(terminal.failure.class, input.seconds > 0 ? "usage_limit" : "provider_error"); + if (input.seconds > 0) { + assert.equal(terminal.failure.retryable, true); + assert.equal( + terminal.failure.resetAt, + DateTime.formatIso( + DateTime.makeUnsafe(DateTime.toEpochMillis(now) + input.seconds * 1_000), ), ); - 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, - 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, 2); - 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", - ), - ); - assert.deepEqual( - [...plans.values()] - .filter((plan) => plan.kind === "todo_list") - .map((plan) => plan.status), - ["superseded", "completed"], - ); - const proposedPlan = [...plans.values()].find((plan) => plan.kind === "proposed_plan"); - assert.equal(proposedPlan?.status, "active"); - assert.deepEqual(harness.permissionModeChanges, ["bypassPermissions"]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), + } else { + assert.isUndefined(terminal.failure.resetAt); + } + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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 }, - ): 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: "Task tool finished.", - is_error: options?.isError ?? false, - }, - ...(options?.extraToolResult - ? [{ type: "tool_result", tool_use_id: "unrelated-tool", content: "ok" }] - : []), - ], - }, - tool_use_result: tool.output, - parent_tool_use_id: parentToolUseId, - uuid: nextUuid(), - session_id: WAKE_NATIVE_SESSION, - }), - ]; - } - - const makeTaskToolHarness = Effect.gen(function* () { - const harness = yield* makeWakeHarness; - let sequence = 600; - let turn = 0; - const nextUuid = () => `00000000-0000-4000-8000-${String(++sequence).padStart(12, "0")}`; - const startTurn = Effect.fnUntraced(function* () { - turn++; + it.effect("keeps the measured context when a usage limit ends the turn", () => + 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-task-tools-${turn}`), - providerTurnOrdinal: turn, - text: "Update the task list.", + attemptId: RunAttemptId.make("attempt-limit-context"), + text: "Continue.", attachments: [], }), ); - }); - const call = Effect.fnUntraced(function* ( - tool: TaskToolCall, - options?: { parentToolUseId?: string; isError?: boolean; extraToolResult?: boolean }, - ) { - 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." }), + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000660", text: "Working." }), ); - yield* Queue.take(harness.terminalReceipts); - }); - const plans = () => - harness.events.flatMap((event) => - event.type === "plan.updated" && event.plan.kind === "todo_list" ? [event.plan] : [], + // The CLI answers a 429 with a locally generated frame that reports no usage. + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "", + id: "00000000-0000-4000-8000-000000000661", + type: "message", + role: "assistant", + content: [{ type: "text", text: "You've hit your session limit" }], + stop_reason: "stop_sequence", + stop_sequence: "", + usage: { + input_tokens: 0, + output_tokens: 0, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }, + }, + parent_tool_use_id: null, + error: "rate_limit", + uuid: "00000000-0000-4000-8000-000000000661", + session_id: WAKE_NATIVE_SESSION, + }), ); - return { startTurn, call, finishTurn, plans }; - }); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000662", + result: "You've hit your session limit", + terminalReason: "api_error", + isError: true, + apiErrorStatus: 429, + }), + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + const reportedContext = harness.events.flatMap((event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage + ? [event.providerTurn.tokenUsage.usedTokens] + : [], + ); + assert.deepEqual(reportedContext, [2]); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); - 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"] }, - }); + const usageStreamFrame = (event: unknown, parentToolUseId: string | null = null) => + claudeSdkFrame({ + type: "stream_event", + event, + parent_tool_use_id: parentToolUseId, + session_id: WAKE_NATIVE_SESSION, + uuid: "usage-stream-frame", + }); + const usageSnapshotFrame = (id: string, uuid: string, usage: unknown) => + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id, + type: "message", + role: "assistant", + content: [{ type: "text", text: "Working." }], + stop_reason: null, + stop_sequence: null, + usage, + }, + parent_tool_use_id: null, + uuid, + session_id: WAKE_NATIVE_SESSION, + }); + const zeroUsage = { + input_tokens: 0, + output_tokens: 0, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 0, + }; + const reportedContextTokens = (events: ReadonlyArray) => + events.flatMap((event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage + ? [event.providerTurn.tokenUsage.usedTokens] + : [], + ); - it.effect("persists a todo_list from inline Claude task-tool frames", () => + it.effect("reports context from final stream usage when the request starts at zero", () => 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: [ + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-zero-start-usage"), + text: "Continue.", + attachments: [], + }), + ); + // Some Anthropic-compatible proxies report zero usage at message_start + // and the real counts on the final message_delta. + const frames = [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_first", usage: zeroUsage }, + }), + usageSnapshotFrame("msg_first", "00000000-0000-4000-8000-000000000670", zeroUsage), + usageStreamFrame( { - 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, - }, - }, + type: "message_delta", + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { ...zeroUsage, input_tokens: 999_999, output_tokens: 9 }, }, - ...[ - ...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), + "child-tool", ), - ), - ); - - 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")); - } + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { ...zeroUsage, input_tokens: 37_939, output_tokens: 184 }, + }), + usageSnapshotFrame("msg_first", "00000000-0000-4000-8000-000000000671", zeroUsage), + usageStreamFrame({ + type: "message_start", + message: { id: "msg_second", usage: zeroUsage }, + }), + usageSnapshotFrame("msg_second", "00000000-0000-4000-8000-000000000672", zeroUsage), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { input_tokens: null, output_tokens: 12 }, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000673", result: "Done." }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [38_123]); }).pipe( - Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - it.effect.each(["success false", "error result", "unknown id"] as const)( - "does not emit a plan update for TaskUpdate with %s", - (reason) => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Inspect")); - yield* harness.call( - updateTask( - { taskId: reason === "unknown id" ? "missing" : "1", status: "completed" }, - reason !== "success false", - ), - { isError: reason === "error result" }, - ); - yield* harness.finishTurn(); - assert.lengthOf(harness.plans(), 1); - assert.deepEqual(harness.plans()[0]?.steps, [ - { id: "task-1", text: "Inspect", status: "pending" }, - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("replaces task state with TaskList, including an empty list", () => + it.effect("merges cumulative stream usage into the message_start counts", () => 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: [] }, - ], - }, + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, autoCompactWindow: "150000" }, }); - 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), - ), - ), - ); - - it.effect("keeps subagent TaskCreate, TaskUpdate and TaskList out of the main plan", () => - Effect.gen(function* () { - const harness = yield* makeTaskToolHarness; - yield* harness.startTurn(); - yield* harness.call(createTask("1", "Main task")); - const child = { parentToolUseId: "tool-parent-agent" }; - yield* harness.call(createTask("2", "Child task"), child); - yield* harness.call(updateTask({ taskId: "1", status: "completed" }), child); - yield* harness.call({ name: "TaskList", input: {}, output: { tasks: [] } }, child); - yield* harness.call(updateTask({ taskId: "1", status: "in_progress" })); - yield* harness.finishTurn(); - assert.lengthOf(harness.plans(), 2); - assert.deepEqual(harness.plans().at(-1)?.steps, [ - { id: "task-1", text: "Main task", status: "running" }, - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - 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(), []); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-merged-stream-usage"), + text: "Continue.", + attachments: [], + }), + ); + const startUsage = { + input_tokens: 10, + output_tokens: 1, + cache_creation_input_tokens: 200, + cache_read_input_tokens: 1_000, + }; + const frames = [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_native", usage: startUsage }, + }), + usageSnapshotFrame("msg_native", "00000000-0000-4000-8000-000000000680", startUsage), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: null, stop_sequence: null }, + usage: { input_tokens: null, output_tokens: 20 }, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { + input_tokens: 25, + output_tokens: 50, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 1_000, + }, + }), + usageSnapshotFrame("msg_native", "00000000-0000-4000-8000-000000000681", startUsage), + claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "auto", pre_tokens: 1_075, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-000000000682", + session_id: WAKE_NATIVE_SESSION, + }), + usageSnapshotFrame("msg_native", "00000000-0000-4000-8000-000000000684", startUsage), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage: { input_tokens: null, output_tokens: 60 }, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000683", result: "Done." }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [1_211, 1_230, 1_075, 400]); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage + ? [event.providerTurn.tokenUsage.autoCompactThreshold] + : [], + ), + [150_000, 150_000, 150_000, 150_000], + ); }).pipe( - Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - it.effect("resolves API retries on resumed assistant activity", () => - Effect.scoped( + it.effect.each([ + { autoCompactWindow: "", model: "claude-sonnet-4-6", threshold: undefined }, + { autoCompactWindow: "150000", model: "claude-sonnet-4-6", threshold: 150_000 }, + { autoCompactWindow: "200000", model: "claude-sonnet-4-6", threshold: undefined }, + { autoCompactWindow: "650000", model: "claude-sonnet-4-6", threshold: undefined }, + { autoCompactWindow: "650000", model: "uncatalogued-model", threshold: 650_000 }, + ])( + "ignores stale snapshots after compaction and reports threshold $autoCompactWindow for $model", + ({ autoCompactWindow, model, threshold }) => Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, autoCompactWindow }, + }); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-api-retry"), - text: "Open github.com.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-snapshot-usage-compaction"), + text: "Continue.", attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model }, }), ); - - yield* Queue.offer( - harness.sdkMessages, + const usage = { ...zeroUsage, input_tokens: 1_000, output_tokens: 75 }; + const frames = [ + usageSnapshotFrame("msg_fallback", "00000000-0000-4000-8000-000000000790", usage), 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", + subtype: "compact_boundary", + compact_metadata: { trigger: "auto", pre_tokens: 1_075, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-000000000791", session_id: WAKE_NATIVE_SESSION, }), - ); - const retryItems = () => + usageSnapshotFrame("msg_fallback", "00000000-0000-4000-8000-000000000792", usage), + // A new request after the boundary reports the compacted context. + usageSnapshotFrame("msg_after", "00000000-0000-4000-8000-000000000793", { + ...zeroUsage, + input_tokens: 450, + output_tokens: 10, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000794", result: "Done." }), + ]; + for (const frame of frames) yield* Queue.offer(harness.sdkMessages, frame); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [1_075, 400, 460]); + assert.deepEqual( harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.retry !== undefined - ? [event.turnItem] + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage + ? [event.providerTurn.tokenUsage.autoCompactThreshold] : [], - ); - yield* awaitUntil(() => retryItems().length === 1, "Claude retry item"); - 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, - }); - - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000202", - text: "Opening GitHub.", - }), - ); - yield* awaitUntil(() => retryItems().length === 2, "resolved Claude retry item"); - 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, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000203", - result: "Opened GitHub.", - }), + ), + [threshold, threshold, threshold], ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "recovered Claude turn"); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), + ); + + it.effect("shows a hook-dropped Claude prompt once and skips info-level lines", () => + 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("claude-hook-dropped-prompt-attempt"), + text: "Deploy to production", + attachments: [], + }), + ); + const notice = "Prompt dropped by a hook: Deploys are frozen until Monday."; + const uuid = "00000000-0000-4000-8000-000000000305"; + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: "Started in the background: agent-1", + level: "info", + session_id: WAKE_NATIVE_SESSION, + uuid: "00000000-0000-4000-8000-000000000307", + }), + ); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: notice, + level: "warning", + prevent_continuation: true, + session_id: WAKE_NATIVE_SESSION, + uuid, + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000306", + result: notice, + numTurns: 0, + terminalReason: null, + }), + ); + yield* Queue.take(harness.terminalReceipts); + const notices = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice" + ? [event.turnItem] + : [], + ); + assert.lengthOf(notices, 1); + assert.equal(notices[0]?.message, notice); + assert.equal(notices[0]?.status, "completed"); + assert.equal(notices[0]?.nativeItemRef?.nativeId, uuid); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.isFalse( + harness.events.some( + (event) => event.type === "message.updated" && event.message.role === "assistant", + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), ), ); - it.effect("carries exhausted retry progress into the terminal provider error", () => - Effect.scoped( + it.effect( + "runs native compaction and keeps its context watermark separate from billed usage", + () => Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - yield* harness.runtime.startTurn( + const compact = harness.runtime.compactThread; + assert.isDefined(compact); + if (compact === undefined) return; + yield* compact( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-api-retry-exhausted"), - text: "Open github.com.", + attemptId: RunAttemptId.make("claude-native-compact-attempt"), + text: " /COMPACT ", attachments: [], }), ); @@ -4638,616 +5076,661 @@ describe("ClaudeAdapterV2 background wake turns", () => { harness.sdkMessages, claudeSdkFrame({ type: "system", - subtype: "api_retry", - attempt: 10, - max_retries: 10, - retry_delay_ms: 38_010, - error_status: 529, - error: "overloaded", - uuid: "00000000-0000-4000-8000-000000000203", + subtype: "compact_boundary", + compact_metadata: { trigger: "manual", pre_tokens: 1500, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-000000000201", session_id: WAKE_NATIVE_SESSION, }), ); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000204", - result: "Claude is temporarily overloaded.", - isError: true, - apiErrorStatus: 529, + uuid: "00000000-0000-4000-8000-000000000202", + result: "Compacted conversation.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed Claude turn"); + yield* Queue.take(harness.terminalReceipts); - const terminal = harness.terminalEvents()[0]; - assert.equal(terminal?.status, "failed"); - if (terminal?.status !== "failed") return; - assert.deepEqual(terminal.retry, { - attempt: 10, - maxAttempts: 10, - retryDelayMs: 38_010, - }); - assert.isDefined(terminal.retryStartedAt); - assert.equal(terminal.failure.code, "api_error_529"); + assert.deepEqual(harness.offeredMessages[0]?.message.content, "/compact"); + const compaction = harness.events.find( + (event) => event.type === "turn_item.updated" && event.turnItem.type === "compaction", + ); + assert.isDefined(compaction); + if (compaction?.type === "turn_item.updated" && compaction.turnItem.type === "compaction") { + assert.equal(compaction.turnItem.beforeTokenCount, 1500); + assert.equal(compaction.turnItem.afterTokenCount, 400); + assert.equal(compaction.turnItem.status, "completed"); + } + const watermark = harness.events.find( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.tokenUsage?.usedTokens === 400, + ); + assert.isDefined(watermark); + const completed = harness.events.findLast( + (event) => event.type === "provider_turn.updated", + ); + assert.equal(completed?.type, "provider_turn.updated"); + if (completed?.type === "provider_turn.updated") { + assert.deepEqual(completed.providerTurn.turnTokenUsage, { + usageScope: "main_agent", + usageStatus: "complete", + hasSubagents: false, + inputTokens: 1, + outputTokens: 1, + cachedInputTokens: 0, + cacheCreationTokens: 0, + }); + } }).pipe( + Effect.scoped, Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), ), ), - ), ); - it.effect.each([ - "api_error", - "malformed_tool_use_exhausted", - "budget_exhausted", - "structured_output_retry_exhausted", - "tool_deferred_unavailable", - "turn_setup_failed", - "blocking_limit", - "rapid_refill_breaker", - "prompt_too_long", - "image_error", - "model_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: [], - }), - ); + it.effect("shows automatic compaction before its boundary and completes the same item", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const observeCompactions = Effect.fnUntraced(function* (uuid: string) { + // A later notice receipt confirms the event subscriber consumed preceding updates. yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000205", - result: "Provider failure details.", - isError: false, - ...(terminalReason === "overloaded_status" - ? { apiErrorStatus: 529 } - : { terminalReason }), + claudeSdkFrame({ + type: "system", + subtype: "informational", + content: "Context checkpoint", + level: "warning", + session_id: WAKE_NATIVE_SESSION, + uuid, }), ); - 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, - terminalReason === "blocking_limit" ? "usage_limit" : "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, + yield* Queue.take(harness.systemNoticeReceipts); + return harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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 and clears on empty snapshot", - () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const emptyRoster = claudeSdkFrame({ + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("claude-auto-compact-attempt"), + text: "Continue working.", + attachments: [], + }), + ); + for (const index of [1, 2]) { + yield* harness.offerAndWait( + claudeSdkFrame({ type: "system", - subtype: "background_tasks_changed", - tasks: [], - uuid: "00000000-0000-4000-8000-000000000202", + subtype: "status", + status: "compacting", + uuid: `00000000-0000-4000-8000-00000000021${index}`, 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, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - - const afterStart = providerThreadRosterEvents(harness.events).filter( - (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, - ); - assert.isAtLeast(afterStart.length, 1); - assert.equal( - (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0]?.taskId, - WAKE_TASK_ID, - ); - - // A subagent's own background shell keeps the subagent waiting on it. - 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", - }, - ], - uuid: "00000000-0000-4000-8000-000000000203", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* awaitUntil( - () => - providerThreadRosterEvents(harness.events).some( - (event) => - event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1", - ), - "subagent shell roster", - ); + }), + ); + } + const beforeBoundary = yield* observeCompactions("00000000-0000-4000-8000-000000000215"); + assert.lengthOf(beforeBoundary, 1); + const running = beforeBoundary[0]!; + assert.equal(running.status, "running"); + assert.isNull(running.completedAt); + assert.isNotNull(running.startedAt); + + yield* TestClock.adjust(1_000); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + compact_result: "success", + uuid: "00000000-0000-4000-8000-000000000222", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const reported = yield* observeCompactions("00000000-0000-4000-8000-000000000223"); + assert.lengthOf(reported, 2); + assert.equal(reported[1]?.id, running.id); + assert.equal(reported[1]?.status, "completed"); + assert.isUndefined(reported[1]?.afterTokenCount); + assert.isEmpty(harness.terminalEvents()); + yield* TestClock.adjust(1_000); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-000000000213", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const afterBoundary = yield* observeCompactions("00000000-0000-4000-8000-000000000216"); + assert.lengthOf(afterBoundary, 3); + const completed = afterBoundary[2]!; + assert.equal(completed.status, "completed"); + assert.equal(completed.id, running.id); + assert.equal(completed.ordinal, running.ordinal); + assert.deepEqual(completed.startedAt, running.startedAt); + assert.equal(completed.beforeTokenCount, 1500); + assert.equal(completed.afterTokenCount, 400); + assert.deepEqual(completed.completedAt, reported[1]?.completedAt); - yield* Queue.offer(harness.sdkMessages, emptyRoster); - yield* awaitUntil( - () => - providerThreadRosterEvents(harness.events).some( - (event) => - event.providerThread.status === "idle" && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, - ), - "empty roster clear", - ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "manual", pre_tokens: 2000, post_tokens: 500 }, + uuid: "00000000-0000-4000-8000-000000000217", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000218", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const nextCompactions = yield* observeCompactions("00000000-0000-4000-8000-000000000219"); + assert.lengthOf(nextCompactions, 5); + const boundaryOnly = nextCompactions[3]!; + const nextRunning = nextCompactions[4]!; + assert.equal(boundaryOnly.status, "completed"); + assert.notEqual(boundaryOnly.id, completed.id); + assert.isAbove(boundaryOnly.ordinal, completed.ordinal); + assert.equal(boundaryOnly.beforeTokenCount, 2000); + assert.equal(boundaryOnly.afterTokenCount, 500); + assert.equal(nextRunning.status, "running"); + assert.notEqual(nextRunning.id, boundaryOnly.id); + assert.isAbove(nextRunning.ordinal, boundaryOnly.ordinal); - 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.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "default", + uuid: "00000000-0000-4000-8000-000000000233", + session_id: WAKE_NATIVE_SESSION, + }), + ); + assert.deepEqual( + yield* observeCompactions("00000000-0000-4000-8000-000000000234"), + nextCompactions, + ); - 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: [], + let retryRunning = nextRunning; + for (const [index, outcome] of [ + { compact_result: "failed", compact_error: "Temporary compaction failure." }, + {}, + ].entries()) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + ...outcome, + uuid: `00000000-0000-4000-8000-00000000024${index}`, + session_id: WAKE_NATIVE_SESSION, }), ); - 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, + const stopped = yield* observeCompactions(`00000000-0000-4000-8000-00000000025${index}`); + assert.lengthOf(stopped, 6 + index * 2); + const settled = stopped.at(-1)!; + assert.equal(settled.id, retryRunning.id); + assert.equal(settled.ordinal, retryRunning.ordinal); + assert.deepEqual(settled.startedAt, retryRunning.startedAt); + assert.equal( + settled.status, + outcome.compact_result === "failed" ? "failed" : "interrupted", + ); + assert.equal( + settled.title, + outcome.compact_result === "failed" + ? "Context compaction failed" + : "Context compaction stopped", + ); + assert.isNotNull(settled.completedAt); + assert.isEmpty(harness.terminalEvents()); + + yield* harness.offerAndWait( claudeSdkFrame({ type: "system", - subtype: "background_tasks_changed", - tasks: [ - { - task_id: longRunning.taskId, - task_type: "local_bash", - description: "Monitor 0", - }, - ], - uuid: nextUuid(), + subtype: "status", + status: "compacting", + uuid: `00000000-0000-4000-8000-00000000026${index}`, session_id: WAKE_NATIVE_SESSION, }), ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: nextUuid(), result: "Watching." }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); + const retried = yield* observeCompactions(`00000000-0000-4000-8000-00000000027${index}`); + assert.lengthOf(retried, stopped.length + 1); + retryRunning = retried.at(-1)!; + assert.equal(retryRunning.status, "running"); + assert.notEqual(retryRunning.id, settled.id); + assert.isAbove(retryRunning.ordinal, settled.ordinal); + } - const roster = providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks; - assert.deepEqual(roster, [ - { taskId: longRunning.taskId, kind: "monitor", description: "Monitor 0" }, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "auto", pre_tokens: 3000, post_tokens: 600 }, + uuid: "00000000-0000-4000-8000-000000000220", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const allCompactions = yield* observeCompactions("00000000-0000-4000-8000-000000000221"); + assert.lengthOf(allCompactions, 10); + assert.equal(allCompactions[9]?.id, retryRunning.id); + assert.equal(allCompactions[9]?.ordinal, retryRunning.ordinal); + assert.equal(allCompactions[9]?.status, "completed"); + assert.equal(allCompactions[9]?.beforeTokenCount, 3000); + assert.equal(allCompactions[9]?.afterTokenCount, 600); + + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000214", + result: "Work complete.", + }), + ); + yield* Queue.take(harness.terminalReceipts); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], ), + allCompactions, + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - it.effect("stops background work after the turn settled", () => - Effect.scoped( + it.effect.each([ + { outcome: "result", turnStatus: "completed", itemStatus: "failed" }, + { outcome: "interrupt", turnStatus: "interrupted", itemStatus: "interrupted" }, + { outcome: "query_exit", turnStatus: "failed", itemStatus: "failed" }, + ] as const)( + "settles unfinished compaction before the $outcome terminal receipt", + ({ outcome, turnStatus, itemStatus }) => Effect.gen(function* () { - let closes = 0; const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => - Effect.sync(() => { - closes++; - }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + close: (sdkMessages) => Queue.shutdown(sdkMessages), }); - const now = yield* DateTime.now; - const attemptId = RunAttemptId.make("attempt-claude-settled-stop"); + const attemptId = RunAttemptId.make(`claude-compact-${outcome}`); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, + now: yield* DateTime.now, attemptId, - text: "Run the build in the background.", + text: "Continue.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread; - assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID); - 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* awaitUntil( - () => - (providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks?.length ?? 0) === 0, - "roster clear after Stop", + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000221", + session_id: WAKE_NATIVE_SESSION, + }), ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); + if (outcome === "query_exit") { + yield* Queue.shutdown(harness.sdkMessages); + } else if (outcome === "interrupt") { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + }); + } else { + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000222", + result: "Stopped before the boundary.", + }), + ); + } + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, turnStatus); + const updates = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], + ); + assert.lengthOf(updates, 2); + const [running, settled] = updates; + assert.equal(running?.status, "running"); + assert.equal(settled?.status, itemStatus); + assert.equal(settled?.id, running?.id); + assert.equal(settled?.ordinal, running?.ordinal); + assert.deepEqual(settled?.startedAt, running?.startedAt); + assert.isNotNull(settled?.completedAt); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), ); - it.effect("a settled Stop with no CLI process left succeeds and clears the roster", () => - Effect.scoped( + it.effect.each(["claude-haiku-4-5-20251001", "claude-sonnet-4-6"])( + "renegotiates auto only when switching API models after fallback to default: %s", + (nextModel) => Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions(); - const now = yield* DateTime.now; + const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); + const modelSelection = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-haiku-4-5-20251001", + }; + const turnInput = { + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attachments: [], + modelSelection, + runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + ...CLAUDE_TEST_RUNTIME_POLICY, + runtimeMode: "auto", + }), + }; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-settled-stop-no-process"), - text: "Run the build in the background.", - attachments: [], + ...turnInput, + attemptId: RunAttemptId.make("attempt-claude-auto-fallback-1"), + text: "Hello.", }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + const openedOptions = harness.getOpenedOptions(); + assert.equal(openedOptions?.permissionMode, "auto"); + yield* harness.offerAndWait(claudeSdkFrame({ ...wakeTurnInit, permissionMode: "default" })); yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - const settledThread = providerThreadRosterEvents(harness.events).at(-1)?.providerThread; - assert.equal(settledThread?.pendingBackgroundTasks?.[0]?.taskId, WAKE_TASK_ID); - - yield* Queue.shutdown(harness.sdkMessages); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 50, "query exit"); + yield* Queue.take(harness.terminalReceipts); - yield* harness.runtime.interruptTurn({ - providerThread: settledThread ?? harness.providerThread, - providerTurnId: harness.terminalEvents()[0]!.providerTurnId, - requestRuntimeRestart: true, - }); - yield* awaitUntil( - () => - (providerThreadRosterEvents(harness.events).at(-1)?.providerThread - .pendingBackgroundTasks?.length ?? 0) === 0, - "roster clear after Stop", + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + ...turnInput, + modelSelection: { ...modelSelection, model: nextModel }, + attemptId: RunAttemptId.make("attempt-claude-auto-fallback-2"), + providerTurnOrdinal: 2, + text: "Continue.", + }), ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); + if (nextModel === modelSelection.model) { + assert.strictEqual(harness.getOpenedOptions(), openedOptions); + assert.lengthOf(harness.processQueues, 1); + } else { + const resumedOptions = harness.getOpenedOptions(); + assert.notStrictEqual(resumedOptions, openedOptions); + assert.equal(resumedOptions?.model, nextModel); + assert.equal(resumedOptions?.resume, WAKE_NATIVE_SESSION); + assert.isUndefined(resumedOptions?.sessionId); + assert.equal(resumedOptions?.permissionMode, "auto"); + assert.lengthOf(harness.processQueues, 2); + } + assert.lengthOf(harness.offeredMessages, 2); + assert.deepEqual(harness.permissionModeChanges, []); + assert.deepEqual(harness.liveSelectionChanges, []); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), ); - it.effect("a settled Stop leaves a turn that replaced the closing process alone", () => + it.effect("preserves typed Claude plans and todos through generic tool completion", () => Effect.scoped( Effect.gen(function* () { - 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, - crypto: yield* Crypto.Crypto, - idAllocator, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - 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), - 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), - 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); - }), - ), - 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; + 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* runtime.startTurn( + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ - threadId, - providerThread, + threadId: harness.threadId, + providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-settled-stop-replaced-a"), - text: "Run the build in the background.", + attemptId: RunAttemptId.make("attempt-claude-plan-lifecycle-1"), + text: "Plan the work.", attachments: [], }), ); - yield* Queue.offer(processQueues[0]!, wakeTaskStarted); - yield* Queue.offer(processQueues[0]!, turnOneResult); - yield* awaitUntil(() => terminals().length === 1, "first turn terminal"); - 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( - 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", + yield* Queue.offer( + harness.sdkMessages, + assistantTools("00000000-0000-4000-8000-000000000501", [ + { + id: "tool-todo-1", + name: "TodoWrite", + input: { todos: [{ content: "Inspect", status: "in_progress" }] }, }, - }), + ]), ); - assert.lengthOf(processQueues, 2); - const replacementTaskId = "replacement-task"; yield* Queue.offer( - processQueues[1]!, - claudeSdkFrame({ - ...wakeTaskStarted, - task_id: replacementTaskId, - uuid: "00000000-0000-4000-8000-000000000905", - }), + harness.sdkMessages, + assistantTools("00000000-0000-4000-8000-000000000501", [ + { + id: "tool-todo-1", + name: "TodoWrite", + input: { todos: [{ content: "Inspect", status: "in_progress" }] }, + }, + ]), ); - yield* awaitUntil( - () => - providerThreadRosterEvents(events).at(-1)?.providerThread.pendingBackgroundTasks?.[0] - ?.taskId === replacementTaskId, - "replacement roster", + yield* Queue.offer( + harness.sdkMessages, + toolResults("00000000-0000-4000-8000-000000000502", ["tool-todo-1"]), ); - - yield* Queue.shutdown(processQueues[0]!); - yield* Fiber.join(stop); - assert.isTrue(yield* hasPendingBackgroundWork); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 50, "late roster events"); - const latestThread = providerThreadRosterEvents(events).at(-1)?.providerThread; - assert.equal(latestThread?.status, "active"); - assert.deepEqual( - latestThread?.pendingBackgroundTasks?.map((task) => task.taskId), - [replacementTaskId], + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, permissionMode: "bypassPermissions" }), ); - yield* Queue.offer( - processQueues[1]!, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000906", - result: "Started another build.", + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + permissionMode: "plan", + uuid: "00000000-0000-4000-8000-000000000508", + session_id: WAKE_NATIVE_SESSION, }), ); - yield* awaitUntil(() => terminals().length === 2, "replacement turn terminal"); - yield* Queue.offer( - processQueues[1]!, + yield* harness.offerAndWait( claudeSdkFrame({ - ...wakeNotification, - task_id: replacementTaskId, - uuid: "00000000-0000-4000-8000-000000000907", + ...wakeTurnInit, + uuid: "00000000-0000-4000-8000-000000000509", + permissionMode: "plan", }), ); yield* Queue.offer( - processQueues[1]!, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000908", - text: WAKE_ASSISTANT_TEXT, + 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* awaitUntil(() => continuationRequests.length === 1, "replacement wake"); + 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), @@ -5256,325 +5739,647 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("clears the roster when a turn fails", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const failedResult = claudeSdkFrame({ - type: "result", - subtype: "error_during_execution", - duration_ms: 10, - duration_api_ms: 10, - is_error: true, - num_turns: 1, - result: "boom", - stop_reason: "end_turn", - total_cost_usd: 0, + 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, }, - modelUsage: {}, - permission_denials: [], - errors: ["boom"], - terminal_reason: "model_error", - uuid: "00000000-0000-4000-8000-000000000203", - session_id: WAKE_NATIVE_SESSION, - }); + }, + 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-roster-fail"), - text: "Run the build in the background.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-claude-task-tools-${turn}`), + providerTurnOrdinal: turn, + text: "Update the task list.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* awaitUntil( - () => - providerThreadRosterEvents(harness.events).some( - (event) => (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, - ), - "roster after task_started", + }); + 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, + }), ); - yield* Queue.offer(harness.sdkMessages, failedResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "failed"); + return { configDir, startTurn, call, launchSubagent, finishTurn, plans }; + }); - const afterFailure = providerThreadRosterEvents(harness.events).at(-1); - assert.deepEqual(afterFailure?.providerThread.pendingBackgroundTasks ?? [], []); - assert.isFalse(yield* harness.hasPendingBackgroundWork); + 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), ), ), + ); + + 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), + ), ), ); + 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), + ), + ), + ); + it.effect( - "clears the replaced sibling native thread roster when openQuery switches processes", + "publishes an empty task list when the first TaskUpdate after restart deletes the last task", () => - Effect.scoped( - Effect.gen(function* () { - 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; - // Real two-process model: each openQuery owns its own message queue. - // A shared queue would mask 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, - crypto: yield* Crypto.Crypto, - 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), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(queue), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => 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); - }), - ), - Effect.forkScoped, + 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), + ), + ), + ); + + 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), + ), + ), + ); + + 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), + ), + ), + ); + + 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), + ), + ), + ); + + // 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), + ), + ), + ); + + 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] + : [], ); - 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.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, + }); - yield* runtime.startTurn( + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000202", + text: "Opening GitHub.", + }), + ); + 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, + 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), + ), + ), + ), + ); + + 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: appThreadA, - providerThread: providerThreadA, + threadId: harness.threadId, + providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-roster-iso-a"), - text: "Background work on A.", + attemptId: RunAttemptId.make("attempt-structured-terminal-failure"), + text: "Complete the task.", 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, + harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000302", - result: "A settled with background work.", + uuid: "00000000-0000-4000-8000-000000000205", + result: "Provider failure details.", + isError: false, + ...(terminalReason === "overloaded_status" + ? { apiErrorStatus: 529 } + : { terminalReason }), }), ); - yield* awaitUntil( - () => - events.some( - (event) => - event.type === "turn.terminal" && - event.providerThreadId === providerThreadA.id && - event.status === "completed", - ), - "thread A terminal", + 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.", + ), ); - const rosterAAfterSettle = providerThreadRosterEvents(events).findLast( - (event) => event.providerThread.id === providerThreadA.id, - )?.providerThread.pendingBackgroundTasks; - assert.deepEqual(rosterAAfterSettle ?? [], [ - { taskId: taskA, description: "work on A", kind: "command" }, - ]); - 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* awaitUntil( - () => - providerThreadRosterEvents(events).some( - (event) => - event.providerThread.id === providerThreadA.id && - event.providerThread.status === "idle" && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, - ), - "sibling A roster cleared idle on process replacement", - ); - 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* awaitUntil( - () => - providerThreadRosterEvents(events).some( - (event) => - event.providerThread.id === providerThreadB.id && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0, - ), - "thread B roster populated", - ); - 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* awaitUntil( - () => - events.some( - (event) => - event.type === "turn.terminal" && - event.providerThreadId === providerThreadB.id && - event.status === "failed", - ), - "thread B failed terminal", + assert.equal( + terminal.failure.code, + terminalReason === "overloaded_status" ? "api_error_529" : terminalReason, ); - - 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), @@ -5583,65 +6388,93 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each(["full-access", "approval-required"] as const)( - "keeps a queued wake turn's tool callback with its continuation in %s mode", - (runtimeMode) => + // 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), + ), + ), + ); + + 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 and clears on empty snapshot", + () => 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", + const emptyRoster = claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [], + uuid: "00000000-0000-4000-8000-000000000202", session_id: WAKE_NATIVE_SESSION, }); @@ -5650,146 +6483,57 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: firstAttempt, + attemptId: RunAttemptId.make("attempt-claude-roster-fallback"), 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* 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); + assert.equal( + (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0]?.taskId, + WAKE_TASK_ID, ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - 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, + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [ + { + task_id: "subagent-shell", + task_type: "local_bash", + description: "sleep 150", + parent_task_id: "agent-1", + }, + ], + uuid: "00000000-0000-4000-8000-000000000203", + session_id: WAKE_NATIVE_SESSION, }), ); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* Queue.offer(harness.sdkMessages, planToolUse); - // The SDK asks for permission only after streaming the tool_use. - yield* awaitUntil( - () => Queue.sizeUnsafe(harness.sdkMessages) === 0, - "the tool_use frame to be consumed", + yield* harness.until(() => + providerThreadRosterEvents(harness.events).some( + (event) => + event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1", + ), ); - let settleYields = 0; - yield* awaitUntil(() => settleYields++ >= 50, "the tool_use frame to be handled"); - 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* Queue.offer(harness.sdkMessages, emptyRoster); + yield* harness.until(() => + providerThreadRosterEvents(harness.events).some( + (event) => + event.providerThread.status === "idle" && + (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0, ), ); - 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* awaitUntil( - () => harness.continuationRequests.length === 1, - "continuation request", - ); - - 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* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal"); - - 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* awaitUntil(() => harness.terminalEvents().length === 3, "continuation terminal"); - - 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"], - ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -5798,84 +6542,123 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("stores a Bash result's stdout and stderr as command output", () => + 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 attemptId = RunAttemptId.make("attempt-claude-bash-output"); - const bashToolUseId = "toolu_01BashOutput"; + 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, - text: "Run it.", + attemptId: RunAttemptId.make("attempt-claude-awaited-roster"), + text: "Run the tests in the background and the dev server.", 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, - }), + 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], + ], + ); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* Queue.take(harness.terminalReceipts); + + // 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 leaves the roster, a reused id starts unmarked. 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, - }, - }), + roster(["dev-server"], "00000000-0000-4000-8000-000000000303"), ); + yield* nextRoster((tasks) => tasks.length === 1); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000792", result: "Done." }), + roster(["dev-server", WAKE_TASK_ID], "00000000-0000-4000-8000-000000000304"), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); + assert.deepStrictEqual(marks(yield* nextRoster((tasks) => tasks.length === 2)), [ + ["dev-server", false], + [WAKE_TASK_ID, false], + ]); - const bash = harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.nativeItemRef?.nativeId === bashToolUseId, + 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], + ], ); - assert.equal( - bash?.type === "turn_item.updated" && bash.turnItem.type === "command_execution" - ? bash.turnItem.output - : undefined, - "On branch main\nwarning: dirty", + 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], + ], ); }).pipe( Effect.provide( @@ -5885,222 +6668,134 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("answers an approval a held wake turn raises without waiting for the echo", () => + 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; - 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* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: userAttempt, - text: "Second.", - attachments: [], - providerTurnOrdinal: 2, - runtimePolicy: approvalPolicy, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - 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, - }), - ); - yield* awaitUntil( - () => Queue.sizeUnsafe(harness.sdkMessages) === 0, - "the tool_use frame to be consumed", - ); - let settleYields = 0; - yield* awaitUntil(() => settleYields++ >= 50, "the tool_use frame to be held"); - 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* awaitUntil( - () => harness.events.some((event) => event.type === "runtime_request.updated"), - "the approval request", - ); - 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), - ), - ), - ), - ); - - it.effect("drops a zero-turn task-notification result while awaiting a prompt echo", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const firstAttempt = RunAttemptId.make("attempt-claude-echo-debris-1"); - const secondAttempt = RunAttemptId.make("attempt-claude-echo-debris-2"); - const stamp = (frame: SDKMessage, promptIndex: number) => - claudeSdkFrame({ - ...frame, - user_message_uuid: harness.promptUuid(promptIndex), - }); + 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: firstAttempt, - text: "First.", + 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, - stamp( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000760", text: "One." }), - 0, - ), - ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000761", result: "One." }), - 0, - ), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: secondAttempt, - text: "Second.", - attachments: [], - providerTurnOrdinal: 2, + 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, - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000764", text: "Stale." }), - ); - yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000762", text: "Two." }), - 1, - ), - ); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000763", result: "Two." }), - 1, - ), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal"); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.lengthOf(harness.continuationRequests, 0); - assert.deepEqual( - harness.events.flatMap((event) => - event.type === "message.updated" && event.message.role === "assistant" - ? [event.message.text] - : [], - ), - ["One.", "Stale.", "Two."], - ); - assert.isFalse( - harness.events.some( - (event) => - event.type === "message.updated" && - event.message.text === STALE_TASK_NOTIFICATION_RESULT_TEXT, - ), + 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" }, + ]); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -6109,76 +6804,49 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("releases output held for a prompt echo when the stream ends", () => + it.effect("stops background work after the turn settled", () => Effect.scoped( Effect.gen(function* () { + let closes = 0; const harness = yield* makeWakeHarnessWithOptions({ - close: (sdkMessages) => Queue.shutdown(sdkMessages), + close: (sdkMessages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(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] - : [], - ); - + const attemptId = RunAttemptId.make("attempt-claude-settled-stop"); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: firstAttempt, - text: "First.", + attemptId, + text: "Run the build in the background.", 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* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); + 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); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: secondAttempt, - text: "Second.", - attachments: [], - providerTurnOrdinal: 2, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000703", text: "Two." }), - ); - let heldYields = 0; - yield* awaitUntil(() => heldYields++ >= 50, "unechoed frame to be held"); - assert.deepEqual(assistantTexts(), ["One."]); + yield* harness.runtime.interruptTurn({ + providerThread: settledThread ?? harness.providerThread, + providerTurnId: harness.terminalEvents()[0]!.providerTurnId, + requestRuntimeRestart: true, + }); - yield* Queue.shutdown(harness.sdkMessages); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal"); - assert.deepEqual(assistantTexts(), ["One.", "Two."]); - assert.equal(harness.terminalEvents()[1]?.status, "failed"); + 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), @@ -6187,119 +6855,180 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("gives the same run attempt a fresh prompt uuid on every offer", () => + it.effect("a settled Stop leaves a turn that replaced the closing process alone", () => Effect.scoped( Effect.gen(function* () { - const original = yield* makeWakeHarness; - const copy = yield* makeWakeHarness; - const now = yield* DateTime.now; - for (const harness of [original, copy]) { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-shared-copy"), - text: "Continue where you left off.", - attachments: [], - }), - ); + 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, + crypto: yield* Crypto.Crypto, + 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), + 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), + 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."); } - assert.notEqual(original.promptUuid(0), copy.promptUuid(0)); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("fails a prompt Claude completes without starting a turn for it", () => - Effect.scoped( - Effect.gen(function* () { - // Claude answers a prompt whose uuid its transcript already holds with - // a lone completed lifecycle frame and never runs a turn for it. - const harness = yield* makeWakeHarness; + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const terminals = () => events.filter((event) => event.type === "turn.terminal"); const now = yield* DateTime.now; - yield* harness.runtime.startTurn( + + yield* runtime.startTurn( makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, + threadId, + providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-duplicate-prompt"), - text: "Bump this PR to the latest main.", + attemptId: RunAttemptId.make("attempt-claude-settled-stop-replaced-a"), + text: "Run the build in the background.", 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* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); - 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), - ), - ), - ), - ); + 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); - 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( + const stop = yield* runtime + .interruptTurn({ + providerThread: settledThread ?? providerThread, + providerTurnId: settledTurn!.providerTurnId, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkScoped); + yield* Deferred.await(firstCloseRequested); + + yield* runtime.startTurn( makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, + threadId, + providerThread: { ...providerThread, status: "active" }, now, - attemptId: RunAttemptId.make("attempt-claude-started-prompt"), - text: "Bump this PR to the latest main.", + 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", + }, }), ); - const lifecycle = (state: string, uuid: string) => - claudeSdkFrame({ - type: "command_lifecycle", - command_uuid: harness.promptUuid(0), - state, - uuid, - session_id: WAKE_NATIVE_SESSION, - }); + assert.lengthOf(processQueues, 2); + const replacementTaskId = "replacement-task"; yield* Queue.offer( - harness.sdkMessages, - lifecycle("queued", "00000000-0000-4000-8000-000000000791"), + processQueues[1]!, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: replacementTaskId, + uuid: "00000000-0000-4000-8000-000000000905", + }), ); - yield* Queue.offer( - harness.sdkMessages, - lifecycle("started", "00000000-0000-4000-8000-000000000792"), + yield* changes.until( + () => + providerThreadRosterEvents(events).at(-1)?.providerThread.pendingBackgroundTasks?.[0] + ?.taskId === replacementTaskId, ); - // The CLI can report the prompt completed before its turn's result. + + 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( - harness.sdkMessages, - lifecycle("completed", "00000000-0000-4000-8000-000000000793"), + processQueues[1]!, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000906", + result: "Started another build.", + }), ); + yield* changes.until(() => terminals().length === 2); yield* Queue.offer( - harness.sdkMessages, + processQueues[1]!, claudeSdkFrame({ - ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000794", result: "Done." }), - user_message_uuid: harness.promptUuid(0), + ...wakeNotification, + task_id: replacementTaskId, + uuid: "00000000-0000-4000-8000-000000000907", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); + 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), @@ -6308,531 +7037,548 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - 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: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - assert.lengthOf(harness.continuationRequests, 0); - - yield* Queue.offer(harness.sdkMessages, wakeNotification); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 50, "notification-only quiet window"); - assert.lengthOf(harness.continuationRequests, 0); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - - yield* Queue.offer(harness.sdkMessages, wakeAssistant); - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); - 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* Queue.offer(harness.sdkMessages, wakeResult); - let settleYields = 0; - yield* awaitUntil(() => settleYields++ >= 50, "wake result to settle into the buffer"); - 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), - ), - ), - ), - ); - - it.effect("starts the wake run when Claude opens the wake turn, before its output", () => - 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-init-1"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - - 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* awaitUntil(() => harness.terminalEvents().length === 2, "wake run terminal"); - 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), - ), - ), - ), - ); - - it.effect("does not offer a continuation for notification-only opaque work", () => - 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-notification-only"), - text: "Start opaque background work.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - - yield* Queue.offer(harness.sdkMessages, wakeNotification); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 100, "notification-only quiet window"); - assert.lengthOf(harness.continuationRequests, 0); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-notification-only-continuation"), - text: "Background task completed.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - yield* awaitUntil( - () => harness.terminalEvents().length === 2, - "notification-only continuation terminal", - ); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.lengthOf(harness.offeredMessages, 1); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("carries a rejected wake rate limit into the continuation failure", () => - 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); - - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "rate_limit_event", - rate_limit_info: { - status: "rejected", - rateLimitType: "five_hour", - resetsAt, - overageStatus: "rejected", + 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, + crypto: yield* Crypto.Crypto, + idAllocator, + continuationRequests: { + offer: () => Effect.void, }, - 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", - }), - ); - 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-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"); - 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), - ), - ), - ), - ); - - it.effect("leaves buffered wake messages for the continuation queued behind a user turn", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; + 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), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Queue.shutdown(queue), + }; + }), + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => 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( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-wake-4a"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* Queue.offer(harness.sdkMessages, wakeResult); - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); + 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" }, + ]); + assert.isTrue(yield* hasPendingBackgroundWork); + assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadA)); + assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadB)); - 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* 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)); - yield* awaitUntil(() => harness.offeredMessages.length === 2, "user prompt offered"); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isTrue(yield* harness.hasPendingBackgroundWork); + 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( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000105", - result: "The build passed; nothing else pending.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal"); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - assert.isFalse( - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === WAKE_RESULT_TEXT, - ), - ); + 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", + ), + ); - 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* awaitUntil(() => harness.terminalEvents().length === 3, "continuation terminal"); - 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), + 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), ), - ); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), ); - it.effect("terminalizes an agent server wake from a positive task-notification result", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const wakeText = "The background command completed."; + 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: RunAttemptId.make("attempt-claude-agent-server-wake"), - text: "Background task completed.", - attachments: [], - messageCreatedBy: "agent", - messageCreationSource: "server", - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-00000000010b", - text: wakeText, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-00000000010c", - result: wakeText, - numTurns: 154, - origin: { kind: "task-notification" }, - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "server wake terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); + 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: RunAttemptId.make("attempt-claude-agent-server-next"), - text: "What finished?", - attachments: [], - providerTurnOrdinal: 2, - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-00000000010d", - result: "The background command finished.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "queued turn terminal"); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); + 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); - it.effect("terminalizes a user mobile turn from a positive task-notification result", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const fallbackText = "The ordinary mobile turn completed."; + 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: RunAttemptId.make("attempt-claude-mobile-notif-origin"), - text: "Complete this task.", - attachments: [], - messageCreationSource: "mobile", - }), - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-00000000010e", - result: fallbackText, - numTurns: 60, - origin: { kind: "task-notification" }, - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "mobile turn terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isTrue( - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === fallbackText, + 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), ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), ); - it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () => + it.effect("stores a Bash result's stdout and stderr as command output", () => Effect.scoped( 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 attemptId = RunAttemptId.make("attempt-claude-bash-output"); + const bashToolUseId = "toolu_01BashOutput"; 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, + text: "Run it.", attachments: [], }), ); - yield* awaitUntil(() => harness.offeredMessages.length === 1, "recovery prompt offered"); - - // Live interleaving seen after interrupt recovery: a stale stopped - // task_notification and its task-notification-origin result arrive - // before the real root assistant 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", + 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, staleTaskNotificationResult); - yield* Queue.offer( - harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-00000000010a", - text: probeAssistantText, - }), - ); - - yield* awaitUntil( - () => hasMessageText(probeAssistantText), - "probe assistant after stale task-notification result", - ); - assert.lengthOf(harness.terminalEvents(), 0); - assert.isFalse(hasMessageText(staleResultText)); - yield* Queue.offer( harness.sdkMessages, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000108", - text: recoveryAssistantText, + 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-000000000109", - result: recoveryAssistantText, - }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000792", result: "Done." }), ); + yield* harness.awaitTerminal(1); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "user turn terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isTrue(hasMessageText(recoveryAssistantText)); - assert.isFalse(hasMessageText(staleResultText)); + 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), @@ -6841,180 +7587,194 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("terminalizes a zero-turn task-notification result in a provider continuation", () => + it.effect("answers an approval a held wake turn raises without waiting for the echo", () => Effect.scoped( 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-zero-continuation-1"), - text: "Run the build in the background.", + attemptId: firstAttempt, + text: "First.", attachments: [], + runtimePolicy: approvalPolicy, }), ); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - yield* Queue.offer(harness.sdkMessages, wakeNotification); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-00000000010f", - result: "Wake result with no model turns.", - numTurns: 0, - origin: { kind: "task-notification" }, - }), + 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* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); + yield* harness.awaitTerminal(1); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-zero-continuation-2"), - text: "Background task completed.", + attemptId: userAttempt, + text: "Second.", attachments: [], providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", + runtimePolicy: approvalPolicy, }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); - assert.equal(harness.terminalEvents()[1]?.status, "completed"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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* awaitUntil( - () => harness.terminalEvents().length === 1, - "interrupted terminal", - ).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), + 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", + ); + 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), ), ), + ), ); - it.effect("drops zero-turn task-notification debris racing interrupt", () => + it.effect("releases output held for a prompt echo when the stream ends", () => 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), + close: (sdkMessages) => Queue.shutdown(sdkMessages), }); - const idAllocator = yield* IdAllocator.IdAllocatorV2; const now = yield* DateTime.now; - const attemptId = RunAttemptId.make("attempt-claude-interrupt-zero-notif"); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }); - const staleText = "Zero-turn debris must not leak."; + 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.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId, - text: "Stop this task.", + attemptId: firstAttempt, + text: "First.", 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-000000000116", - result: staleText, - numTurns: 0, - origin: { kind: "task-notification" }, - }), + stamp( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000701", text: "One." }), + 0, + ), ); - let debrisYields = 0; - yield* awaitUntil(() => debrisYields++ >= 50, "zero-turn debris consumed"); - yield* Deferred.succeed(closeGate, undefined); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal"); - assert.lengthOf(harness.terminalEvents(), 1); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - assert.isFalse( - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === staleText, + 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), @@ -7023,36 +7783,38 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("fails a positive task-notification error result", () => + it.effect("fails a prompt Claude completes without starting a turn for it", () => Effect.scoped( 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-positive-notif-error"), - text: "Run the task.", + attemptId: RunAttemptId.make("attempt-claude-duplicate-prompt"), + text: "Bump this PR to the latest main.", attachments: [], }), ); yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000117", - result: "The task failed.", - numTurns: 7, - origin: { kind: "task-notification" }, - subtype: "error_during_execution", - isError: true, - errors: ["The task failed."], + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(0), + state: "completed", + uuid: "00000000-0000-4000-8000-000000000790", + session_id: WAKE_NATIVE_SESSION, }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "failed"); + 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), @@ -7061,28 +7823,52 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("settles a continuation turn immediately when no wake output is buffered", () => + // 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-wake-3"), - text: "Background task completed.", + attemptId: RunAttemptId.make("attempt-claude-started-prompt"), + text: "Bump this PR to the latest main.", attachments: [], - messageCreatedBy: "agent", - messageCreationSource: "provider", }), ); - - yield* awaitUntil(() => harness.terminalEvents().length === 1, "spurious terminal"); + 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"); - assert.lengthOf(harness.offeredMessages, 0); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -7091,162 +7877,84 @@ 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), + 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 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 }; - }; + 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), + ), + ), + ), + ); - it.effect("a subagent re-run in the foreground does not join a later wake", () => + it.effect("starts the wake run when Claude opens the wake turn, before its output", () => Effect.scoped( Effect.gen(function* () { const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const taskId = "task-foreground-rerun"; - const toolUseId = "toolu_foreground_rerun"; - const userTurn = (attempt: string, providerTurnOrdinal: number) => - harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make(attempt), - text: "Go on.", - attachments: [], - providerTurnOrdinal, - }), - ); - const result = (uuid: string) => makeResultFrame({ uuid, result: "Done." }); - const ended = (uuid: string) => - makeSubagentNotificationFrame({ taskId, toolUseId, summary: "AUDITED", uuid }); - yield* userTurn("attempt-rerun-1", 1); - yield* Queue.offer( - harness.sdkMessages, - makeSubagentTaskStartedFrame({ - taskId, - toolUseId, - uuid: "00000000-0000-4000-8000-000000000901", + 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, result("00000000-0000-4000-8000-000000000902")); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000903")); - yield* awaitUntil(() => harness.continuationRequests.length === 1, "subagent wake"); - yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000904")); + 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-rerun-2"), + attemptId: RunAttemptId.make("attempt-claude-wake-init-2"), text: "Background task completed.", attachments: [], providerTurnOrdinal: 2, @@ -7254,31 +7962,17 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "wake terminal"); - - yield* userTurn("attempt-rerun-3", 3); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - ...makeSubagentTaskStartedFrame({ - taskId, - toolUseId, - uuid: "00000000-0000-4000-8000-000000000905", - }), - is_backgrounded: false, - }), - ); - yield* Queue.offer(harness.sdkMessages, ended("00000000-0000-4000-8000-000000000906")); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, result("00000000-0000-4000-8000-000000000907")); - yield* awaitUntil(() => harness.terminalEvents().length === 3, "third turn terminal"); + assert.lengthOf(harness.terminalEvents(), 1); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - yield* Queue.offer(harness.sdkMessages, wakeAssistant); - yield* awaitUntil(() => harness.continuationRequests.length === 2, "command wake"); - assert.equal( - harness.continuationRequests[1]?.notification?.summary, - `Command "${WAKE_TASK_DESCRIPTION}" finished`, + 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( @@ -7288,188 +7982,178 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("a turn that fails to start does not expire a queued wake's report", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const userTurn = ( - attempt: string, - providerTurnOrdinal: number, - attachments: ProviderAdapter.ProviderAdapterV2TurnInput["message"]["attachments"] = [], - ) => - harness.runtime.startTurn( + 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), - text: "Go on.", - attachments, - providerTurnOrdinal, + 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); - yield* userTurn("attempt-failed-start-1", 1); - yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); - yield* Queue.offer(harness.sdkMessages, turnOneResult); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - yield* Queue.offer(harness.sdkMessages, wakeNotification); - let notificationYields = 0; - yield* awaitUntil(() => notificationYields++ >= 50, "notification to be recorded"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - - const missing = ChatImageAttachment.make({ - type: "image", - id: ChatAttachmentId.make("thread-claude-wake-12345678-1234-1234-1234-123456789abc"), - name: "gone.png", - mimeType: "image/png", - sizeBytes: 4, - }); - const failed = yield* Effect.exit(userTurn("attempt-failed-start-2", 2, [missing])); - assert.isTrue(Exit.isFailure(failed)); + 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* userTurn("attempt-failed-start-3", 2); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000911", result: "Answered." }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal"); + // 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* Queue.offer(harness.sdkMessages, wakeAssistant); - yield* awaitUntil(() => harness.continuationRequests.length === 1, "command wake"); - assert.equal( - harness.continuationRequests[0]?.notification?.summary, - `Command "${WAKE_TASK_DESCRIPTION}" finished`, - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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), + ), ), ), - ), ); - it.effect("keeps a subagent a queued wake turn launches with its continuation", () => + it.effect("leaves buffered wake messages for the continuation queued behind a user turn", () => Effect.scoped( Effect.gen(function* () { - const TASK_ID = "a-wake-launched-subagent"; - const TOOL_USE_ID = "toolu_01WakeLaunchedAgent"; const harness = yield* makeWakeHarness; const now = yield* DateTime.now; - const firstAttempt = RunAttemptId.make("attempt-claude-wake-subagent-1"); - const userAttempt = RunAttemptId.make("attempt-claude-wake-subagent-2"); - const continuationAttempt = RunAttemptId.make("attempt-claude-wake-subagent-3"); - const runOf = (attemptId: RunAttemptId) => RunId.make(`run-${attemptId}`); - 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, + attemptId: RunAttemptId.make("attempt-claude-wake-4a"), text: "Run the build in the background.", attachments: [], }), ); - yield* Queue.offer(harness.sdkMessages, stamp(wakeTaskStarted, 0)); - yield* Queue.offer( - harness.sdkMessages, - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000770", result: "STARTED" }), - 0, - ), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); + 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: userAttempt, - text: "Reply with exactly: USER_REPLY", + attemptId: RunAttemptId.make("attempt-claude-wake-4b"), + text: "How is the build going?", attachments: [], providerTurnOrdinal: 2, }), ); - const wakeFrames = [ - wakeNotification, - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_wake_agent", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: TOOL_USE_ID, - name: "Agent", - input: { description: "Audit recent commits", prompt: "Audit them." }, - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000771", - session_id: WAKE_NATIVE_SESSION, - }), - makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000772", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000773", - text: "AUDIT_DONE", - }), - makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: "AUDIT_DONE", - uuid: "00000000-0000-4000-8000-000000000774", - }), - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [{ type: "tool_result", tool_use_id: TOOL_USE_ID, content: "AUDIT_DONE" }], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000775", - session_id: WAKE_NATIVE_SESSION, + + 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.", }), - wakeResult, - stamp( - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000776", - text: "USER_REPLY", - }), - 1, - ), - stamp( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000777", result: "USER_REPLY" }), - 1, + ); + 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, ), - ]; - for (const frame of wakeFrames) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.terminalEvents().length === 2, "user turn terminal"); + ); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: continuationAttempt, + attemptId: RunAttemptId.make("attempt-claude-wake-4c"), text: "Background task completed.", attachments: [], providerTurnOrdinal: 3, @@ -7477,29 +8161,22 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 3, "continuation terminal"); - - const subagentRuns = harness.events.flatMap((event) => - event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID - ? [event.subagent.runId] - : [], - ); - assert.isNotEmpty(subagentRuns); - assert.isTrue(subagentRuns.every((runId) => runId === runOf(continuationAttempt))); - const finalSubagent = harness.events.findLast( - (event) => - event.type === "subagent.updated" && event.subagent.nativeTaskRef?.nativeId === TASK_ID, - ); - assert.equal( - finalSubagent?.type === "subagent.updated" && finalSubagent.subagent.status, - "completed", + 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, + ), ); - const userRunItems = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.runId === runOf(userAttempt) - ? [event.turnItem.type] - : [], + assert.isFalse( + harness.events.some( + (event) => + event.type !== "provider_thread.updated" && + JSON.stringify(event).includes(WAKE_TASK_ID), + ), ); - assert.deepEqual([...new Set(userRunItems)], ["assistant_message"]); + assert.isFalse(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -7508,113 +8185,414 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("routes a subagent that starts while the root turn is idle", () => + it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () => Effect.scoped( Effect.gen(function* () { - const TASK_ID = "task-idle-subagent"; - const TOOL_USE_ID = "toolu-idle-subagent"; - const FINAL_REPORT = "Idle auditor done."; 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, + ); + yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-idle-subagent-1"), - text: "Wait for background work.", + attemptId: RunAttemptId.make("attempt-claude-stale-notif-1"), + text: "Continue after interrupt.", attachments: [], }), ); + yield* harness.until(() => harness.offeredMessages.length === 1); + + // After interrupt recovery, stale task notifications and their results can precede the root stream. yield* Queue.offer( harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000331", - result: "Waiting in the background.", + 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* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); - - const idleFrames = [ - makeSubagentTaskStartedFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000332", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000333", - text: "Idle auditor working.", - bashToolUseId: "toolu-idle-bash", - }), - makeSubagentToolResultFrame({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000334", - toolUseId: "toolu-idle-bash", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000335", - text: FINAL_REPORT, + yield* Queue.offer(harness.sdkMessages, staleTaskNotificationResult); + yield* Queue.offer( + harness.sdkMessages, + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-00000000010a", + text: probeAssistantText, }), - makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: FINAL_REPORT, - uuid: "00000000-0000-4000-8000-000000000336", + ); + + 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, }), - ]; - for (const frame of idleFrames) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); + ); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000337", - result: "The idle auditor finished.", + 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), + ), + ), + ), + ); + + 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), + ), + ), + ), + ); + + it.effect("settles a continuation turn immediately when no wake output is buffered", () => + 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-idle-subagent-2"), + attemptId: RunAttemptId.make("attempt-claude-wake-3"), text: "Background task completed.", attachments: [], - providerTurnOrdinal: 2, messageCreatedBy: "agent", messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); - const routing = subagentRouting(harness.events, ["toolu-idle-bash"]); - assert.isDefined(routing.childThreadId); - assert.deepEqual( - [...(routing.toolThreadIds.get("toolu-idle-bash") ?? [])], - [routing.childThreadId], - ); - assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ - "Idle auditor working.", - FINAL_REPORT, - ]); - assert.deepEqual(routing.assistantTexts(harness.threadId), [ - "Waiting in the background.", - "The idle auditor finished.", - ]); - 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), + 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), + ), + ), + ), + ); + + 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.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-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.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* 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), + ), ), ), - ), ); it.effect("streams a background subagent's work while the root turn is idle", () => @@ -7660,7 +8638,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); + yield* harness.awaitTerminal(1); for (const frame of [ makeSubagentToolResultFrame({ @@ -7685,18 +8663,16 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => { + yield* harness.until(() => { const event = latestToolItem(IDLE_BASH); return event?.type === "turn_item.updated" && event.turnItem.status === "running"; - }, "idle Bash call"); - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "subagent.updated" && - event.subagent.progress === "Reading the last commits", - ), - "idle progress", + }); + 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."]); @@ -7725,7 +8701,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); + yield* harness.awaitContinuation(1); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ @@ -7746,7 +8722,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + yield* harness.awaitTerminal(2); const finalRouting = subagentRouting(harness.events, [STRADDLING_BASH, IDLE_BASH]); assert.deepEqual(finalRouting.assistantTexts(finalRouting.childThreadId), [ @@ -7810,7 +8786,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); + yield* harness.awaitTerminal(1); for (const frame of [ claudeSdkFrame({ @@ -7864,12 +8840,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil( - () => - harness.events.some( - (event) => event.type === "message.updated" && event.message.text === "OUTER_WORKING", - ), - "outer work while the nested start waits", + 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 [ @@ -7903,15 +8877,13 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "subagent.updated" && - event.subagent.progress === "Waiting on the nested check", - ), - "outer progress", + 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, @@ -7933,7 +8905,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + yield* harness.awaitTerminal(2); assert.isFalse( harness.events.some( @@ -8035,13 +9007,13 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); + 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* awaitUntil(() => harness.terminalEvents().length === 2, "second turn terminal"); + yield* harness.awaitTerminal(2); for (const frame of [ makeSubagentNotificationFrame({ @@ -8063,13 +9035,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "message.updated" && event.message.text === "OUTER_AFTER_NESTED", - ), - "outer work after the nested call returns", + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "message.updated" && event.message.text === "OUTER_AFTER_NESTED", + ), ); assert.isFalse( @@ -8094,124 +9064,84 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("ends a subagent's open call when the CLI exits while the root turn is idle", () => - Effect.scoped( - Effect.gen(function* () { - const TOOL_USE_ID = "toolu-idle-exit"; - const BASH = "toolu-idle-exit-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}`] - : [], + 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.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-idle-exit"), - text: "Audit in the background.", - attachments: [], - }), - ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: "task-idle-exit", - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000981", - }), - ...makeSubagentAssistantFrames({ + 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, - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000983", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); - assert.deepEqual(bashStatuses(), ["command_execution:running"]); - - yield* Queue.shutdown(harness.sdkMessages); - yield* awaitUntil(() => bashStatuses().length === 2, "call ended"); - assert.deepEqual(bashStatuses(), ["command_execution:running", "command_execution:failed"]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("ends a subagent's open call when Stop's close of the CLI times out", () => - Effect.scoped( - Effect.gen(function* () { - const TOOL_USE_ID = "toolu-idle-close-timeout"; - const BASH = "toolu-idle-close-timeout-bash"; - const harness = yield* makeWakeHarnessWithOptions(); - 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.offerAndWait(frame); + } + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000983", + result: "Auditing in the background.", + }), ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-claude-idle-close-timeout"), - text: "Audit in the background.", - attachments: [], - }), - ); - for (const frame of [ - makeSubagentTaskStartedFrame({ - taskId: "task-idle-close-timeout", - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000985", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000986", - bashToolUseId: BASH, - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000987", - result: "Auditing in the background.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); - assert.deepEqual(bashStatuses(), ["command_execution:running"]); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + assert.deepEqual(bashStatuses(), ["command_execution:running"]); - const stop = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: harness.terminalEvents()[0]!.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(stop); - assert.deepEqual(bashStatuses(), [ - "command_execution:running", - "command_execution:interrupted", - ]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + 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), + ), ), ), - ), ); it.effect.each(["before", "after"] as const)( @@ -8257,7 +9187,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); + yield* harness.awaitTerminal(1); for (const frame of makeSubagentAssistantFrames({ parentToolUseId: OUTER_TOOL_USE_ID, @@ -8266,7 +9196,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { })) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => bashItems().length === 1, "idle Bash call"); + yield* harness.until(() => bashItems().length === 1); const bashResultFrame = makeSubagentToolResultFrame({ parentToolUseId: OUTER_TOOL_USE_ID, @@ -8335,14 +9265,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil( - () => harness.continuationRequests.length === 1, - "continuation request", - ); + yield* harness.awaitContinuation(1); yield* Queue.shutdown(harness.sdkMessages); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 50, "query exit"); + yield* yieldTicks(50); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, @@ -8364,7 +9290,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "The audit finished.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + yield* harness.awaitTerminal(2); const input = JSON.stringify("git log -5"); assert.deepEqual(bashItems(), [ @@ -8434,7 +9360,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); + yield* harness.awaitTerminal(1); yield* Queue.offer( harness.sdkMessages, @@ -8452,7 +9378,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* awaitUntil(() => sendItems().length >= 1, "idle SendMessage call"); + yield* harness.until(() => sendItems().length >= 1); for (const frame of [ claudeSdkFrame({ @@ -8486,15 +9412,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil( - () => harness.continuationRequests.length === 1, - "continuation request", - ); + yield* harness.awaitContinuation(1); const beforeExit = sendItems(); yield* Queue.shutdown(harness.sdkMessages); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 50, "query exit"); + yield* yieldTicks(50); yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, @@ -8516,7 +9438,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "The audit finished.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + yield* harness.awaitTerminal(2); const input = JSON.stringify(SEND_INPUT); assert.deepEqual(beforeExit, [`dynamic_tool:running:${input}`]); @@ -8532,82 +9454,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("releases held frames before the notification that first names the tool use", () => - Effect.scoped( - Effect.gen(function* () { - const TASK_ID = "task-late-tool-use"; - const TOOL_USE_ID = "toolu-late-tool-use"; - 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-late-tool-use"), - text: "Run an auditor.", - attachments: [], - }), - ); - const frames = [ - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: TASK_ID, - description: "Audit recent commits", - task_type: "local_agent", - prompt: "Audit the last five commits.", - uuid: "00000000-0000-4000-8000-000000000341", - session_id: WAKE_NATIVE_SESSION, - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000342", - text: "Working.", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000344", - messageId: "msg_late_final", - text: "Part one.", - }), - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000345", - messageId: "msg_late_final", - text: "Part two.", - }), - makeSubagentNotificationFrame({ - taskId: TASK_ID, - toolUseId: TOOL_USE_ID, - summary: "Part one.\n\nPart two.", - uuid: "00000000-0000-4000-8000-000000000346", - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000347", - result: "The auditor finished.", - }), - ]; - for (const frame of frames) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); - - const routing = subagentRouting(harness.events, []); - assert.deepEqual(routing.assistantTexts(routing.childThreadId), [ - "Working.", - "Part one.", - "Part two.", - ]); - assert.deepEqual(routing.assistantTexts(harness.threadId), ["The auditor finished."]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - it.effect.each([ ["", "none"], [" behind another subagent's start without one", "before"], @@ -8658,7 +9504,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "launch turn terminal"); + yield* harness.awaitTerminal(1); const otherStartFrame = claudeSdkFrame({ type: "system", @@ -8712,10 +9558,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil( - () => harness.continuationRequests.length === 1, - "continuation request", - ); + yield* harness.awaitContinuation(1); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ @@ -8736,7 +9579,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + yield* harness.awaitTerminal(2); const routing = subagentRouting(harness.events, [BASH]); const childTexts = routing.assistantTexts(routing.childThreadId); @@ -8778,71 +9621,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("does not resolve a newer API retry when replaying a held subagent frame", () => - Effect.scoped( - Effect.gen(function* () { - const TOOL_USE_ID = "toolu-retry-subagent"; - 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-retry-subagent"), - text: "Run an auditor.", - attachments: [], - }), - ); - const frames = [ - ...makeSubagentAssistantFrames({ - parentToolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000351", - text: "Held before registration.", - }), - 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-000000000352", - session_id: WAKE_NATIVE_SESSION, - }), - makeSubagentTaskStartedFrame({ - taskId: "task-retry-subagent", - toolUseId: TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000353", - }), - ]; - for (const frame of frames) { - yield* Queue.offer(harness.sdkMessages, frame); - } - const childTexts = () => { - const routing = subagentRouting(harness.events, []); - return routing.childThreadId === undefined - ? [] - : routing.assistantTexts(routing.childThreadId); - }; - yield* awaitUntil(() => childTexts().length === 1, "replayed subagent text"); - const retryStatuses = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.retry !== undefined - ? [event.turnItem.status] - : [], - ); - assert.deepEqual(retryStatuses, ["running"]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - it.effect("holds subagent frames that precede task_started and shows its result once", () => Effect.scoped( Effect.gen(function* () { @@ -8862,8 +9640,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); const frames = [ - // The SDK can forward child frames before the task_started that - // registers their subagent. + // Child frames can precede the task_started that registers their subagent. ...makeSubagentAssistantFrames({ parentToolUseId: TOOL_USE_ID, uuid: "00000000-0000-4000-8000-000000000321", @@ -8912,7 +9689,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { for (const frame of frames) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); + yield* harness.awaitTerminal(1); const routing = subagentRouting(harness.events, ["toolu-early-bash"]); assert.isDefined(routing.childThreadId); @@ -9096,98 +9873,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { }; }); - it.effect.each([ - [false, "no notification"], - [true, "no notification"], - [false, "stop fails"], - [false, "stop hangs"], - ] as const)("never infers an outcome from Stop, owner settled %s and %s", ([idle, failure]) => - Effect.scoped( - Effect.gen(function* () { - const requested = yield* Deferred.make(); - const fixture = yield* makeStopFixture({ - stopTask: () => - Deferred.succeed(requested, undefined).pipe( - Effect.andThen( - failure === "stop fails" - ? new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "stopTask", - cause: "Task is no longer live", - }) - : failure === "stop hangs" - ? Effect.never - : Effect.void, - ), - ), - }); - if (idle) yield* fixture.finishParent(); - const stopping = yield* fixture.stop().pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(requested); - yield* TestClock.adjust("2 seconds"); - const result = yield* Fiber.join(stopping); - assert.isTrue(Exit.isFailure(result)); - assert.equal( - fixture.events.findLast((event) => event.type === "subagent.updated")?.subagent.status, - "running", - ); - assert.isTrue(yield* fixture.hasPendingBackgroundWork); - yield* fixture.notify("completed"); - assert.equal((yield* Queue.take(fixture.subagentReceipts)).subagent.status, "completed"); - assert.isFalse(yield* fixture.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect.each([1, 2, 3, 4, 5, 6, 7, 8])( - "accepts completion during Stop at scheduler step %s", - (pauseAt) => - Effect.scoped( - Effect.gen(function* () { - const fixture = yield* makeStopFixture(); - const resumptions = yield* Queue.unbounded<() => void>(); - const scheduler = yield* Scheduler.Scheduler; - const dispatcher = scheduler.makeDispatcher(); - let checks = 0; - const stopping = yield* fixture.stop().pipe( - Effect.provideService(Scheduler.Scheduler, { - executionMode: scheduler.executionMode, - shouldYield: () => ++checks === pauseAt, - makeDispatcher: () => ({ - scheduleTask: (task, priority) => { - if (checks === pauseAt) Queue.offerUnsafe(resumptions, task); - else dispatcher.scheduleTask(task, priority); - }, - flush: () => dispatcher.flush(), - }), - }), - Effect.exit, - Effect.forkScoped, - ); - const resume = yield* Queue.take(resumptions); - yield* fixture.notify("completed"); - const completed = yield* Queue.take(fixture.subagentReceipts); - yield* Effect.sync(resume); - yield* TestClock.adjust("2 seconds"); - assert.deepEqual( - yield* Fiber.join(stopping), - Exit.succeed({ - status: "completed" as const, - completedAt: completed.subagent.completedAt!, - result: "Native outcome.", - }), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - it.effect("retains native confirmation after the synchronous Agent tool result", () => Effect.scoped( Effect.gen(function* () { @@ -9224,65 +9909,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each(["completed", "failed", "stopped"] as const)( - "applies idle %s once, preserves a genuine resume, and only confirms native outcomes", - (status) => - Effect.scoped( - Effect.gen(function* () { - let stops = 0; - const fixture = yield* makeStopFixture({ - stopTask: () => Effect.sync(() => void stops++), - }); - yield* fixture.finishParent(); - yield* TestClock.adjust("1 second"); - yield* fixture.notify(status); - const completed = yield* Queue.take(fixture.subagentReceipts); - const expected = status === "stopped" ? "cancelled" : status; - assert.equal(completed.subagent.status, expected); - assert.lengthOf(fixture.offeredMessages, 1); - assert.isFalse(yield* fixture.hasPendingBackgroundWork); - assert.deepEqual(yield* fixture.stop(), { - status: expected, - completedAt: completed.subagent.completedAt!, - result: "Native outcome.", - }); - assert.equal(stops, 0); - yield* TestClock.adjust("1 second"); - yield* fixture.start("toolu-resume"); - assert.isUndefined(yield* fixture.stop(completed.subagent.completedAt!)); - assert.equal(stops, 0); - const stopping = yield* fixture.stop().pipe(Effect.exit, Effect.forkScoped); - yield* Queue.take(fixture.requests); - const beforeReplay = fixture.events.length; - yield* fixture.replay(); - const reopened = yield* Queue.take(fixture.subagentReceipts); - assert.equal(reopened.subagent.status, "running"); - assert.isNull(reopened.subagent.completedAt); - assert.isFalse( - fixture.events - .slice(beforeReplay) - .some( - (event) => event.type === "subagent.updated" && event.subagent.status !== "running", - ), - ); - yield* TestClock.adjust("2 seconds"); - assert.isTrue(Exit.isFailure(yield* Fiber.join(stopping))); - assert.equal(stops, 1); - yield* fixture.notify("completed", "Resumed outcome.", "toolu-resume"); - const resumed = yield* Queue.take(fixture.subagentReceipts); - assert.equal(resumed.subagent.result, "Resumed outcome."); - assert.isAbove( - DateTime.toEpochMillis(resumed.subagent.completedAt!), - DateTime.toEpochMillis(completed.subagent.completedAt!), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - it.effect.each([ [false, "stopped"], [true, "stopped"], @@ -9397,7 +10023,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each(["requested", "observed-before", "observed-after", "inherit", "unknown"] as const)( + it.effect.each([ + "requested", + "observed-before", + "observed-after", + "synthetic-after", + "inherit", + "unknown", + ] as const)( "records the subagent model from %s without inheriting the parent override", (source) => Effect.scoped( @@ -9406,7 +10039,9 @@ describe("ClaudeAdapterV2 background wake turns", () => { const now = yield* DateTime.now; const toolUseId = "toolu-subagent-model"; const parentModel = "claude-opus-4-6"; - const observedModel = "claude-haiku-4-5-20251001"; + // 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, @@ -9475,142 +10110,34 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - if (source === "observed-after") yield* Queue.offer(harness.sdkMessages, observed); + 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), - ), - ), - ), - ); - - it.effect.each([ - { agentModel: "opus", slug: "claude-opus-5-5", requested: undefined, expected: "max" }, - { agentModel: "opus", slug: "claude-opus-5-5", requested: "low", expected: "low" }, - { agentModel: "haiku-4.5", slug: "claude-haiku-4-5", requested: undefined, expected: null }, - ])( - "records the effort a $agentModel subagent runs at (Agent effort $requested)", - ({ agentModel, slug, requested, expected }) => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const now = yield* DateTime.now; - const toolUseId = "toolu-subagent-effort"; - const parentSelection = { - instanceId: CLAUDE_TEST_MODEL_SELECTION.instanceId, - model: "claude-opus-4-6", - options: [ - { id: "effort", value: "max" }, - { id: "fastMode", value: false }, - ], - } satisfies ModelSelection; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-subagent-effort"), - text: "Spawn a subagent.", - attachments: [], - modelSelection: parentSelection, - }), - ); - for (const frame of [ - claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: null, - message: { - model: parentSelection.model, - id: "msg_subagent_effort_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: toolUseId, - name: "Agent", - input: { - description: "Research", - subagent_type: "general-purpose", - model: agentModel, - ...(requested === undefined ? {} : { effort: requested }), - prompt: "Research the topic.", - }, - }, - ], - }, - uuid: "00000000-0000-4000-8000-000000000211", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: "task-subagent-effort", - tool_use_id: toolUseId, - description: "Research", - task_type: "local_agent", - uuid: "00000000-0000-4000-8000-000000000212", - session_id: WAKE_NATIVE_SESSION, - }), - claudeSdkFrame({ - type: "assistant", - parent_tool_use_id: toolUseId, - message: { - model: slug, - id: "msg_subagent_effort_observed", - type: "message", - role: "assistant", - content: [{ type: "text", text: "Researching." }], - }, - uuid: "00000000-0000-4000-8000-000000000213", - session_id: WAKE_NATIVE_SESSION, - }), - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000214", - result: "Spawned the subagent.", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } + ); yield* Queue.take(harness.terminalReceipts); - - const subagentSelection = { - instanceId: parentSelection.instanceId, - model: slug, - ...(expected === null ? {} : { options: [{ id: "effort", value: expected }] }), - }; - const child = harness.events.find((event) => event.type === "app_thread.created"); - assert.deepEqual(child?.appThread.modelSelection, subagentSelection); const subagents = harness.events.filter((event) => event.type === "subagent.updated"); - assert.deepEqual( - subagents.map((event) => event.subagent.modelSelection), - subagents.map(() => subagentSelection), + 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), @@ -9882,7 +10409,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* awaitUntil(() => subagentEvents().length === 1, "subagent node created"); + yield* harness.until(() => subagentEvents().length === 1); yield* Queue.offer( harness.sdkMessages, @@ -9906,10 +10433,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* awaitUntil( - () => subagentEvents().at(-1)?.subagent.status === "completed", - "subagent terminal", - ); + yield* harness.until(() => subagentEvents().at(-1)?.subagent.status === "completed"); assert.equal(subagentEvents().at(-1)?.subagent.result, "First line.\nSecond line."); @@ -9920,7 +10444,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "Delegation completed.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn terminal"); + yield* harness.awaitTerminal(1); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -9980,7 +10504,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); yield* Queue.offer(harness.sdkMessages, subagentTaskStarted); - yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created"); + yield* harness.until(() => subagentEvents().length >= 1); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ @@ -9988,11 +10512,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "Spawned the subagent in the background.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); + yield* harness.awaitTerminal(1); assert.isTrue(yield* harness.hasPendingBackgroundWork); yield* Queue.offer(harness.sdkMessages, subagentStoppedNotification); - yield* awaitUntil(() => harness.continuationRequests.length === 1, "continuation request"); + yield* harness.awaitContinuation(1); yield* Queue.offer( harness.sdkMessages, @@ -10014,7 +10538,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + yield* harness.awaitTerminal(2); assert.equal(subagentEvents().at(-1)?.subagent.status, "cancelled"); assert.isFalse(yield* harness.hasPendingBackgroundWork); @@ -10103,7 +10627,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); yield* Queue.offer(harness.sdkMessages, subagentTaskStarted); - yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created"); + yield* harness.until(() => subagentEvents().length >= 1); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ @@ -10111,13 +10635,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "Spawned the subagent in the background.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "first turn terminal"); + yield* harness.awaitTerminal(1); yield* Queue.offer(harness.sdkMessages, firstNotification); - yield* awaitUntil( - () => harness.continuationRequests.length === 1, - "first continuation request", - ); + yield* harness.awaitContinuation(1); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ @@ -10138,7 +10659,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "continuation terminal"); + 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); @@ -10171,9 +10692,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); yield* Queue.offer(harness.sdkMessages, resumeTaskStarted); - // Shaped like the recorded SendMessage ACK in - // claude_background_subagent_lifecycle: the text block is the JSON of - // tool_use_result, and "message" names the agent's short id. const resumeAck = { success: true, message: `Resuming agent ${SUBAGENT_TASK_ID.slice(0, 7)}`, @@ -10221,10 +10739,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* Queue.offer(harness.sdkMessages, frame); } yield* Queue.offer(harness.sdkMessages, secondNotification); - yield* awaitUntil( - () => harness.continuationRequests.length === 2, - "second continuation request", - ); + yield* harness.awaitContinuation(2); assert.equal(harness.continuationRequests[1]?.detail, SECOND_SUMMARY); assert.isTrue(yield* harness.hasPendingBackgroundWork); @@ -10248,10 +10763,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil( - () => harness.terminalEvents().length === 3, - "resume continuation terminal", - ); + yield* harness.awaitTerminal(3); const statuses = subagentEvents().map((event) => event.subagent.status); const firstCompleted = statuses.indexOf("completed"); @@ -10298,6 +10810,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { 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({ @@ -10320,7 +10833,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { offer: (request) => Effect.sync(() => { continuationRequests.push(request); - }), + }).pipe(Effect.andThen(changes.notify)), }, queryRunner: { allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), @@ -10361,7 +10874,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { Stream.runForEach((event) => Effect.sync(() => { events.push(event); - }), + }).pipe(Effect.andThen(changes.notify)), ), Effect.forkScoped, ); @@ -10395,321 +10908,82 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); yield* Queue.offer(firstProcess, turnOneResult); - yield* awaitUntil( - () => events.some((event) => event.type === "turn.terminal"), - "first 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* awaitUntil( - () => - providerThreadRosterEvents(events).some( - (event) => - event.providerThread.status === "active" && - (event.providerThread.pendingBackgroundTasks?.length ?? 0) === 0 && - event.providerThread.updatedAt !== undefined, - ), - "roster cleared on process replace while remaining active", - ); - 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"); - - const secondProcess = processQueues[1]!; - yield* Queue.offer(secondProcess, wakeNotification); - let settleYields = 0; - yield* awaitUntil(() => settleYields++ >= 50, "stale notification settle"); - assert.lengthOf(continuationRequests, 0); - - yield* Queue.offer( - secondProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000602", - result: "Process restart turn finished.", - }), - ); - yield* awaitUntil( - () => events.filter((event) => event.type === "turn.terminal").length === 2, - "second turn terminal", - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect( - "preserves buffered local_bash notification classification across model/policy query replacement", - () => - Effect.scoped( - Effect.gen(function* () { - 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, - crypto: yield* Crypto.Crypto, - idAllocator, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - 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), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }; - }), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => 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); - }), - ), - 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-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* awaitUntil( - () => events.some((event) => event.type === "turn.terminal"), - "first turn terminal", - ); - assert.isTrue(yield* hasPendingBackgroundWork); - - yield* Queue.offer(firstProcess, wakeNotification); - let quietYields = 0; - yield* awaitUntil(() => quietYields++ >= 50, "notification-only quiet window"); - 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* awaitUntil( - () => events.filter((event) => event.type === "turn.terminal").length === 2, - "user turn terminal after replace", - ); - assert.isFalse(yield* hasPendingBackgroundWork); - assert.lengthOf(continuationRequests, 0); - - yield* Queue.offer(secondProcess, wakeResult); - yield* awaitUntil(() => continuationRequests.length === 1, "continuation after result"); - 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* awaitUntil( - () => events.filter((event) => event.type === "turn.terminal").length === 3, - "continuation terminal after buffered drain", - ); - 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), + 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( + (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), ), ), + ), ); it.effect( - "does not opaque-misclassify a buffered subagent notification across model/policy query replacement", + "preserves buffered local_bash notification classification across model/policy query replacement", () => Effect.scoped( Effect.gen(function* () { - const SUBAGENT_TASK_ID = "task-buffer-replace-subagent"; - const SUBAGENT_TOOL_USE_ID = "toolu-buffer-replace-subagent"; - const SUBAGENT_SUMMARY = "SUB_BUFFER_REPLACE_DONE"; - const subagentTaskStarted = 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 return SUB_BUFFER_REPLACE_DONE.", - uuid: "00000000-0000-4000-8000-000000000801", - session_id: WAKE_NATIVE_SESSION, - }); - const subagentNotification = claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: SUBAGENT_TASK_ID, - tool_use_id: SUBAGENT_TOOL_USE_ID, - status: "completed", - output_file: "/tmp/task-buffer-replace-subagent.output", - summary: SUBAGENT_SUMMARY, - uuid: "00000000-0000-4000-8000-000000000802", - session_id: WAKE_NATIVE_SESSION, - }); - const subagentAsyncAck = claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { - type: "tool_result", - tool_use_id: SUBAGENT_TOOL_USE_ID, - content: [{ type: "text", text: "Async agent launched successfully." }], - }, - ], - }, - parent_tool_use_id: null, - uuid: "00000000-0000-4000-8000-000000000803", - session_id: WAKE_NATIVE_SESSION, - tool_use_result: { - isAsync: true, - status: "async_launched", - agentId: SUBAGENT_TASK_ID, - prompt: "Research then return SUB_BUFFER_REPLACE_DONE.", - }, - }); - + const changes = yield* makeChangeSignal; const fileSystem = yield* FileSystem.FileSystem; const idAllocator = yield* IdAllocator.IdAllocatorV2; const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-subagent-buffer-replace-", + prefix: "t3-claude-v2-buffer-replace-", }); const processQueues: Array> = []; const events: Array = []; @@ -10728,7 +11002,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { offer: (request) => Effect.sync(() => { continuationRequests.push(request); - }), + }).pipe(Effect.andThen(changes.notify)), }, queryRunner: { allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), @@ -10753,12 +11027,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { assertComplete: Effect.void, }, }); - const threadId = ThreadId.make("thread-claude-subagent-buffer-replace"); + const threadId = ThreadId.make("thread-claude-buffer-replace"); const runtime = yield* adapter.openSession({ threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-claude-subagent-buffer-replace", - ), + providerSessionId: ProviderSessionId.make("provider-session-claude-buffer-replace"), modelSelection: CLAUDE_TEST_MODEL_SELECTION, runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, }); @@ -10771,7 +11043,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { Stream.runForEach((event) => Effect.sync(() => { events.push(event); - }), + }).pipe(Effect.andThen(changes.notify)), ), Effect.forkScoped, ); @@ -10781,15 +11053,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); } const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const subagentEvents = () => - events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "subagent.updated" } - > => event.type === "subagent.updated", - ); const now = yield* DateTime.now; yield* runtime.startTurn( @@ -10797,33 +11060,21 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId, providerThread, now, - attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-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, subagentTaskStarted); - yield* awaitUntil(() => subagentEvents().length >= 1, "subagent node created"); - assert.equal(subagentEvents()[0]?.subagent.status, "running"); - yield* Queue.offer(firstProcess, subagentAsyncAck); - yield* Queue.offer( - firstProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000804", - result: "Spawned the subagent in the background.", - }), - ); - yield* awaitUntil( - () => events.some((event) => event.type === "turn.terminal"), - "first turn terminal", - ); + 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, subagentNotification); - yield* awaitUntil(() => continuationRequests.length === 1, "continuation after notify"); - assert.equal(continuationRequests[0]?.detail, SUBAGENT_SUMMARY); + yield* Queue.offer(firstProcess, wakeNotification); + yield* yieldTicks(50); + assert.lengthOf(continuationRequests, 0); const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; yield* runtime.startTurn( @@ -10831,8 +11082,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { threadId, providerThread: { ...providerThread, status: "active" }, now, - attemptId: RunAttemptId.make("attempt-claude-subagent-buffer-replace-user"), - text: "Switch model while the subagent completes.", + attemptId: RunAttemptId.make("attempt-claude-buffer-replace-user"), + text: "Switch model while background work completes.", attachments: [], providerTurnOrdinal: 2, modelSelection: alternateModel, @@ -10843,31 +11094,25 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* Queue.offer( secondProcess, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000805", + uuid: "00000000-0000-4000-8000-000000000701", result: "User turn finished after model switch.", }), ); - yield* awaitUntil( + yield* changes.until( () => events.filter((event) => event.type === "turn.terminal").length === 2, - "user turn terminal after replace", ); assert.isFalse(yield* hasPendingBackgroundWork); - assert.equal(subagentEvents().at(-1)?.subagent.status, "completed"); - assert.lengthOf(continuationRequests, 1); + assert.lengthOf(continuationRequests, 0); - yield* Queue.offer( - secondProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000806", - result: "The subagent finished with SUB_BUFFER_REPLACE_DONE.", - }), - ); + 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-subagent-buffer-replace-cont"), + attemptId: RunAttemptId.make("attempt-claude-buffer-replace-cont"), text: "Background task completed.", attachments: [], providerTurnOrdinal: 3, @@ -10876,24 +11121,29 @@ describe("ClaudeAdapterV2 background wake turns", () => { messageCreationSource: "provider", }), ); - yield* awaitUntil( + yield* changes.until( () => events.filter((event) => event.type === "turn.terminal").length === 3, - "continuation terminal after buffered subagent drain", ); - - const finalSubagent = subagentEvents().at(-1)?.subagent; - assert.equal(finalSubagent?.status, "completed"); - assert.equal(finalSubagent?.result, SUBAGENT_SUMMARY); - assert.equal(finalSubagent?.runId, subagentEvents()[0]?.subagent.runId); - const subagentNodeEvents = events.filter( - ( - event, - ): event is Extract => - event.type === "node.updated" && - event.node.kind === "subagent" && - event.node.nativeItemRef?.nativeId === SUBAGENT_TASK_ID, + 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.equal(subagentNodeEvents.at(-1)?.node.status, "completed"); assert.isFalse(yield* hasPendingBackgroundWork); }).pipe( Effect.provide( @@ -10906,6 +11156,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { it.effect("refuses a thinking change that would kill a running background subagent", () => Effect.scoped( 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; @@ -10966,7 +11217,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { Stream.runForEach((event) => Effect.sync(() => { events.push(event); - }), + }).pipe(Effect.andThen(changes.notify)), ), Effect.forkScoped, ); @@ -11006,7 +11257,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "Spawned the subagent in the background.", }), ); - yield* awaitUntil(() => terminals().length === 1, "first turn terminal"); + yield* changes.until(() => terminals().length === 1); const settledTurn = terminals()[0]!; const alternateModel = CLAUDE_TEST_RESTART_MODEL_SELECTION; @@ -11047,7 +11298,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { result: "Switched model.", }), ); - yield* awaitUntil(() => terminals().length === 2, "switched turn terminal"); + yield* changes.until(() => terminals().length === 2); yield* runtime.startTurn( makeClaudeTestTurnInput({ threadId, @@ -11068,152 +11319,151 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect( - "keeps the process and its roster when a model change meets a running background shell", - () => - Effect.scoped( - Effect.gen(function* () { - 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, - crypto: yield* Crypto.Crypto, - 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), - stopTask: () => Effect.void, - interrupt: Effect.void, - close: Queue.shutdown(sdkMessages), - }; - }); - }, - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => 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({ + // 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, + crypto: yield* Crypto.Crypto, + 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), + 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), + 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, - runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, - }); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }), - ), - 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; + providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-append-replacement-a"), + text: "What is the sentinel?", + attachments: [], + runtimePolicy, + }), + ); + 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-replace-open-fail-a"), - text: "Run the build in the background.", + attemptId: RunAttemptId.make("attempt-claude-append-replacement-b"), + text: "Switch model.", attachments: [], + providerTurnOrdinal: 2, + modelSelection: CLAUDE_TEST_RESTART_MODEL_SELECTION, + runtimePolicy, }), - ); - assert.equal(processQueues.length, 1); - yield* Queue.offer(processQueues[0]!, wakeTaskStarted); - yield* Queue.offer(processQueues[0]!, turnOneResult); - yield* awaitUntil( - () => events.some((event) => event.type === "turn.terminal"), - "first 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), - ), + ) + .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), ), ), + ), ); it.effect( - "clears buffered wake and continuation state when same-native-thread replacement open fails", + "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-wake-", + prefix: "t3-claude-v2-replace-open-fail-", }); let openCount = 0; const processQueues: Array> = []; const events: Array = []; - const continuationRequests: Array = - []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, @@ -11224,10 +11474,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { crypto: yield* Crypto.Crypto, idAllocator, continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), + offer: () => Effect.void, }, queryRunner: { allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), @@ -11257,229 +11504,79 @@ describe("ClaudeAdapterV2 background wake turns", () => { }; }); }, - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-replace-open-fail-wake"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make( - "provider-session-claude-replace-open-fail-wake", - ), - 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); - }), - ), - 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-wake-a"), - text: "Run the build in the background.", - attachments: [], - }), - ); - yield* Queue.offer(processQueues[0]!, wakeTaskStarted); - yield* Queue.offer(processQueues[0]!, turnOneResult); - yield* awaitUntil( - () => events.filter((event) => event.type === "turn.terminal").length === 1, - "first turn terminal", - ); - yield* Queue.offer(processQueues[0]!, wakeNotification); - yield* Queue.offer(processQueues[0]!, wakeAssistant); - yield* awaitUntil(() => continuationRequests.length === 1, "first continuation request"); - 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-wake-b"), - text: "Replace process but fail open.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: alternateModel, - }), - ) - .pipe(Effect.exit); - assert.isTrue(Exit.isFailure(failedStart)); - assert.isFalse(yield* hasPendingBackgroundWork); - - yield* runtime.startTurn( - makeClaudeTestTurnInput({ - threadId, - providerThread: { ...providerThread, status: "active" }, - now, - attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-wake-c"), - text: "Retry after the failed replacement.", - attachments: [], - providerTurnOrdinal: 2, - modelSelection: alternateModel, - }), - ); - const retryProcess = processQueues[1]!; - const retryTaskId = "task-wake-build-after-retry"; - yield* Queue.offer( - retryProcess, - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: retryTaskId, - tool_use_id: "toolu-wake-build-after-retry", - description: "npm run build after retry", - is_backgrounded: true, - task_type: "local_bash", - uuid: "00000000-0000-4000-8000-000000000901", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - retryProcess, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000902", - result: "Kicked off the retry build in the background.", - }), - ); - yield* awaitUntil( - () => events.filter((event) => event.type === "turn.terminal").length === 2, - "retry turn terminal", - ); - yield* Queue.offer( - retryProcess, - claudeSdkFrame({ - type: "system", - subtype: "task_notification", - task_id: retryTaskId, - tool_use_id: "toolu-wake-build-after-retry", - status: "completed", - output_file: "/tmp/task-wake-build-after-retry.log", - summary: "Retry build completed successfully", - uuid: "00000000-0000-4000-8000-000000000903", - session_id: WAKE_NATIVE_SESSION, - }), - ); - yield* Queue.offer( - retryProcess, - makeAssistantTextFrame({ - uuid: "00000000-0000-4000-8000-000000000904", - text: "The retry build has finished.", - }), - ); - yield* awaitUntil( - () => continuationRequests.length === 2, - "continuation request after retry", - ); - assert.equal(continuationRequests[1]?.detail, "Retry build completed successfully"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("does not invent process reset state on a first-ever failed open", () => - Effect.scoped( - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-claude-v2-first-open-fail-", - }); - 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, - crypto: yield* Crypto.Crypto, - idAllocator, - continuationRequests: { - offer: () => Effect.void, - }, - queryRunner: { - allocateSessionId: Effect.succeed(WAKE_NATIVE_SESSION), - open: () => - Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "open", - cause: "forced first open failure", - }), - ), - forkSession: () => Effect.die("unused forkSession"), - subagentLaunchToolUseId: () => Effect.succeed(null), - assertComplete: Effect.void, - }, - }); - const threadId = ThreadId.make("thread-claude-first-open-fail"); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("provider-session-claude-first-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); - }), - ), - Effect.forkScoped, - ); - const now = yield* DateTime.now; - const failedStart = yield* runtime - .startTurn( + forkSession: () => Effect.die("unused forkSession"), + subagentLaunchToolUseId: () => 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-first-open-fail"), - text: "First open fails.", + attemptId: RunAttemptId.make("attempt-claude-replace-open-fail-a"), + text: "Run the build in the background.", attachments: [], }), - ) - .pipe(Effect.exit); - assert.isTrue(Exit.isFailure(failedStart)); - assert.lengthOf(providerThreadRosterEvents(events), 0); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ); + 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), + ), ), ), - ), ); const WORKFLOW_TASK_ID = "task-workflow-run"; @@ -11559,6 +11656,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { readonly state: "queued" | "start" | "done"; readonly secondState?: "queued" | "start" | "done"; readonly startedAt?: number; + readonly lastProgressAt?: number; + readonly durationMs?: number; readonly label?: string; readonly prompt?: string; readonly model?: string; @@ -11584,6 +11683,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { model: input.model ?? "claude-opus-5[1m]", promptPreview: input.prompt ?? "Reply with exactly: A1", ...(input.startedAt === undefined ? {} : { startedAt: input.startedAt }), + ...(input.lastProgressAt === undefined ? {} : { lastProgressAt: input.lastProgressAt }), + ...(input.durationMs === undefined ? {} : { durationMs: input.durationMs }), ...(input.attempt === undefined ? {} : { attempt: input.attempt }), ...(input.state === "done" && input.omitResult !== true ? { resultPreview: "A1 excerpt" } @@ -11662,10 +11763,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* input.harness.offerAndWait( workflowSnapshot({ uuid: input.snapshotUuid, state: input.state ?? "start" }), ); - yield* awaitUntil( - () => workflowMemberEvents(input.harness.events, 2).length === 1, - "workflow members projected", - ); + yield* input.harness.until(() => workflowMemberEvents(input.harness.events, 2).length === 1); }); it.effect.each(["Agent", "Workflow"] as const)( @@ -11795,16 +11893,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* awaitUntil( - () => - workflowCoordinatorEvents(harness.events).length > 0 && - harness.events.some( - (event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === "task-plain-auditor", - ), - "workflow coordinator and auditor projected", - ); const subagentPrompt = (nativeTaskId: string) => { const subagent = harness.events.flatMap((event) => event.type === "subagent.updated" && @@ -11812,7 +11900,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ? [event.subagent] : [], )[0]; - assert.isDefined(subagent); const message = threadMessages(harness.events, subagent?.childThreadId).find( (event) => event.message.role === "user", )?.message; @@ -11831,12 +11918,18 @@ describe("ClaudeAdapterV2 background wake turns", () => { : 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, }); - // A brief is marked as not a script, so its text is never read as one. assert.deepEqual(subagentPrompt("task-plain-auditor"), { text: "Audit the last five commits.", messageMark: false, @@ -11850,75 +11943,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("scopes workflow member artifacts to the provider thread", () => - Effect.scoped( - Effect.gen(function* () { - const memberArtifacts: Array> = []; - const memberThreads: Array = []; - for (const nativeSessionId of ["workflow-session-a", "workflow-session-b"]) { - const harness = yield* makeWorkflowHarnessWithOptions({ nativeSessionId }); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make(`attempt-${nativeSessionId}`), - text: "Run the workflow.", - attachments: [], - }), - ); - for (const frame of [ - workflowToolUse, - workflowTaskStarted, - workflowLaunchAck(harness.transcriptDir), - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001203", state: "done" }), - ]) { - yield* harness.offerAndWait(claudeSdkFrame({ ...frame, session_id: nativeSessionId })); - } - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001204", result: "Done." }), - session_id: nativeSessionId, - }), - ); - yield* Queue.take(harness.terminalReceipts); - const member = workflowMemberEvents(harness.events, 1).at(-1)?.subagent; - assert.isDefined(member); - memberThreads.push(member?.childThreadId); - const ids = harness.events.flatMap((event) => { - if (event.type === "subagent.updated" && event.subagent.id === member?.id) - return [event.subagent.id]; - if (event.type === "node.updated" && event.node.threadId === member?.childThreadId) - return [event.node.id]; - if ( - event.type === "message.updated" && - event.message.threadId === member?.childThreadId - ) - return [event.message.id]; - if ( - event.type === "turn_item.updated" && - event.turnItem.threadId === member?.childThreadId - ) - return [event.turnItem.id]; - return []; - }); - assert.isAtLeast(new Set(ids).size, 6); - memberArtifacts.push(ids); - } - assert.notEqual(memberThreads[0], memberThreads[1]); - assert.deepEqual( - memberArtifacts[0]?.filter((id) => memberArtifacts[1]?.includes(id)), - [], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - it.effect("stops only a live workflow task and waits for its stopped notification", () => Effect.scoped( Effect.gen(function* () { @@ -12155,10 +12179,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { secondState: "queued", }), ); - yield* awaitUntil( - () => coordinatorTurnItems().length > turnItemsBeforeRepeat, - "repeated workflow snapshot", - ); + yield* harness.until(() => coordinatorTurnItems().length > turnItemsBeforeRepeat); assert.lengthOf(workflowMemberEvents(harness.events, 1), 2); assert.lengthOf(workflowMemberEvents(harness.events, 2), 1); @@ -12184,9 +12205,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { model: "claude-sonnet-4-6", }), ); - yield* awaitUntil( - () => coordinatorTurnItems().length > turnItemsBeforeMetadata, - "updated workflow member metadata", + // 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, @@ -12223,196 +12247,57 @@ describe("ClaudeAdapterV2 background wake turns", () => { 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), - ), - ), - ), - ); - - 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: {} }, - ], - }, - }), - ); - 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.isFalse( - harness.events.some( - (event) => - event.type === "app_thread.created" && - event.appThread.id === coordinator?.childThreadId, - ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("does not republish a workflow roster on progress-only frames", () => - 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-progress-only"), - text: "Run the alpha workflow.", - attachments: [], + 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", }), ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001120" }); - const coordinatorCount = () => workflowCoordinatorEvents(harness.events).length; - const offerProgressOnly = (index: number) => - Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ - type: "system", - subtype: "task_progress", - task_id: WORKFLOW_TASK_ID, - tool_use_id: WORKFLOW_TOOL_USE_ID, - description: "Member is working", - uuid: `00000000-0000-4000-8000-${String(1200 + index).padStart(12, "0")}`, - session_id: WAKE_NATIVE_SESSION, - }), - ); - - const inTurnCount = coordinatorCount(); - for (let index = 0; index < 5; index++) yield* offerProgressOnly(index); - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001121", state: "start" }), + 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* awaitUntil(() => coordinatorCount() > inTurnCount, "in-turn workflow snapshot"); - assert.equal(coordinatorCount(), inTurnCount + 1); + yield* harness.offerAndWait( + workflowNotification({ uuid: "00000000-0000-4000-8000-000000001008", status: "stopped" }), + ); yield* Queue.offer( harness.sdkMessages, makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001122", + uuid: "00000000-0000-4000-8000-000000001006", result: "Launched the workflow.", }), ); yield* Queue.take(harness.terminalReceipts); - - const betweenTurnCount = coordinatorCount(); - for (let index = 5; index < 10; index++) yield* offerProgressOnly(index); - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001123", state: "done" }), + 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", ); - yield* awaitUntil( - () => coordinatorCount() > betweenTurnCount, - "between-turn workflow snapshot", + assert.isNull( + stoppedRoot?.type === "node.updated" ? stoppedRoot.node.startedAt : undefined, ); - assert.equal(coordinatorCount(), betweenTurnCount + 1); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -12421,439 +12306,94 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("keeps resumed workflow tools open after stale interrupted cleanup", () => + it.effect("projects workflow member threads after resuming a restarted session", () => Effect.scoped( Effect.gen(function* () { - const clock = yield* Clock.Clock; - const cleanupPaused = yield* Deferred.make(); - const releaseCleanup = yield* Deferred.make(); - let readsUntilPause = 0; - yield* Effect.gen(function* () { - const harness = yield* makeWorkflowHarnessWithOptions({ - close: Queue.shutdown, - freshQueueOnReopen: true, - }); - const oldAttempt = RunAttemptId.make("attempt-workflow-stale-cleanup-old"); - const oldBash = "toolu-workflow-stale-cleanup-old-bash"; - const newBash = "toolu-workflow-stale-cleanup-new-bash"; - const resumeTool = "toolu-workflow-stale-cleanup-resume"; - const toolUpdates = (nativeId: string) => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === nativeId - ? [event.turnItem] - : [], - ); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: oldAttempt, - text: "Run the workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001150" }); - for (const frame of makeSubagentAssistantFrames({ - parentToolUseId: WORKFLOW_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000001151", - bashToolUseId: oldBash, - })) { - yield* harness.offerAndWait(frame); - } - yield* awaitUntil(() => toolUpdates(oldBash).length === 1, "old workflow tool running"); - readsUntilPause = 2; - const stop = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${oldAttempt}`, - }), - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(cleanupPaused); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(stop); - yield* Queue.take(harness.terminalReceipts); - const oldToolCount = toolUpdates(oldBash).length; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-workflow-stale-cleanup-new"), - text: "Resume the workflow.", - attachments: [], - providerTurnOrdinal: 2, - }), - ); - const resumedQueue = harness.processQueues[1]!; - yield* Queue.offer( - resumedQueue, - claudeSdkFrame({ - ...workflowTaskStarted, - tool_use_id: resumeTool, - prompt: "Resume the workflow.", - uuid: "00000000-0000-4000-8000-000000001152", - }), - ); - for (const frame of makeSubagentAssistantFrames({ - parentToolUseId: resumeTool, - uuid: "00000000-0000-4000-8000-000000001153", - bashToolUseId: newBash, - })) { - yield* Queue.offer(resumedQueue, frame); - } - yield* awaitUntil( - () => toolUpdates(newBash).length === 1, - "resumed workflow tool running", - ); - yield* Deferred.succeed(releaseCleanup, undefined); - yield* Queue.take(harness.terminalReceipts); - assert.lengthOf(toolUpdates(oldBash), oldToolCount); - assert.deepEqual( - toolUpdates(newBash).map((item) => item.status), - ["running"], - ); - yield* Queue.offer( - resumedQueue, - makeSubagentToolResultFrame({ - parentToolUseId: resumeTool, - uuid: "00000000-0000-4000-8000-000000001154", - toolUseId: newBash, - }), - ); - yield* awaitUntil( - () => toolUpdates(newBash).at(-1)?.status === "completed", - "resumed workflow tool completed", - ); - assert.equal(toolUpdates(newBash).at(-1)?.output, "ok"); - }).pipe( - Effect.provideService(Clock.Clock, { - ...clock, - currentTimeMillis: Effect.gen(function* () { - if (readsUntilPause > 0 && --readsUntilPause === 0) { - yield* Deferred.succeed(cleanupPaused, undefined); - yield* Deferred.await(releaseCleanup); - } - return yield* clock.currentTimeMillis; - }), - }), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect.each(["root result", "query close"] as const)( - "keeps a waiting continuation inactive until replay can handle %s", - (arrival) => - Effect.scoped( - Effect.gen(function* () { - const digestStarted = yield* Deferred.make(); - const releaseDigest = yield* Deferred.make(); - const closeStarted = yield* Deferred.make(); - let pauseDigest = false; - yield* Effect.gen(function* () { - const harness = yield* makeWorkflowHarnessWithOptions({ - freshQueueOnReopen: true, - close: (messages) => - Deferred.succeed(closeStarted, undefined).pipe( - Effect.andThen(Queue.shutdown(messages)), - ), - }); - const start = (attemptId: string, ordinal: number, continuation: boolean) => - harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: DateTime.makeUnsafe(0), - attemptId: RunAttemptId.make(attemptId), - providerTurnOrdinal: ordinal, - text: "Continue working.", - attachments: [], - ...(continuation - ? { messageCreatedBy: "agent", messageCreationSource: "provider" } - : {}), - }), - ); - yield* start("attempt-workflow-waiting-launch", 1, false); - yield* launchWorkflow({ - harness, - snapshotUuid: "00000000-0000-4000-8000-000000003200", - }); - const fileSystem = yield* FileSystem.FileSystem; - const liveTranscriptDir = NodePath.join(harness.transcriptDir, "live"); - yield* fileSystem.makeDirectory(liveTranscriptDir); - yield* fileSystem.writeFileString( - NodePath.join(liveTranscriptDir, "agent-a1.jsonl"), - '{"type":"assistant","uuid":"wf-line-2","message":{"role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"Live member answer"}]}}\n', - ); - const liveTaskId = "task-workflow-live-while-waiting"; - const liveToolUseId = "toolu-workflow-live-while-waiting"; - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - content: [{ type: "tool_use", id: liveToolUseId, name: "Workflow", input: {} }], - }, - parent_tool_use_id: null, - session_id: WAKE_NATIVE_SESSION, - uuid: "00000000-0000-4000-8000-000000003201", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowTaskStarted, - task_id: liveTaskId, - tool_use_id: liveToolUseId, - uuid: "00000000-0000-4000-8000-000000003202", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "user", - message: { - role: "user", - content: [ - { type: "tool_result", tool_use_id: liveToolUseId, content: "Launched." }, - ], - }, - tool_use_result: { - taskType: "local_workflow", - runId: "wf_live_while_waiting", - transcriptDir: liveTranscriptDir, - }, - parent_tool_use_id: null, - session_id: WAKE_NATIVE_SESSION, - uuid: "00000000-0000-4000-8000-000000003203", - }), - ); - const liveProgress = (state: "start" | "done", uuid: string) => - claudeSdkFrame({ - ...workflowSnapshot({ state, uuid }), - task_id: liveTaskId, - tool_use_id: liveToolUseId, - }); - yield* harness.offerAndWait( - liveProgress("start", "00000000-0000-4000-8000-000000003204"), - ); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000003205", - result: "Launched both workflows.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000003206", - status: "completed", - }), - ); - yield* Queue.take(harness.continuationReceipts); - yield* harness.offerAndWait(wakeTurnInit); - pauseDigest = true; - const progress = yield* harness - .offerAndWait(liveProgress("done", "00000000-0000-4000-8000-000000003207")) - .pipe(Effect.forkScoped); - yield* Deferred.await(digestStarted); - const replay = yield* start("attempt-workflow-waiting-replay", 2, true).pipe( - Effect.forkScoped({ startImmediately: true }), - ); - if (arrival === "query close") { - const stop = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: "turn:attempt-workflow-waiting-replay", - }), - requestRuntimeRestart: true, - }) - .pipe(Effect.forkScoped); - yield* Deferred.await(closeStarted); - yield* Deferred.succeed(releaseDigest, undefined); - yield* Fiber.join(progress); - yield* Fiber.join(stop); - assert.isTrue(Exit.isFailure(yield* Fiber.await(replay))); - } else { - const offered = yield* Deferred.make(); - const result = yield* harness - .offerAndWait(wakeResult, offered) - .pipe(Effect.forkScoped); - yield* Deferred.await(offered); - yield* Deferred.succeed(releaseDigest, undefined); - yield* Fiber.join(progress); - yield* Fiber.join(replay); - yield* Fiber.join(result); - yield* Queue.take(harness.terminalReceipts); - assert.lengthOf(harness.continuationRequests, 1); - } - yield* start("attempt-workflow-waiting-next-user", 3, false); - }).pipe( - 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), - ), - ), - ), - ); - - it.effect.each(["registry", "transcript"] as const)( - "does not replay stale idle progress over a completed workflow after awaiting %s", - (boundary) => - Effect.scoped( - Effect.gen(function* () { - const clock = yield* Clock.Clock; - const progressRead = yield* Deferred.make(); - const releaseProgress = yield* Deferred.make(); - let pauseNextRead = false; - yield* 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-claude-idle-race-launch"), - text: "Run the workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ - harness, - snapshotUuid: "00000000-0000-4000-8000-000000001060", - }); - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001061", - result: "Launched.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - yield* harness.offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001062", - status: "completed", - }), - ); - if (boundary === "registry") { - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001063", result: "Done." }), - ); - } - const continuationInput = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-idle-race-continuation"), - text: "Continue.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }); - pauseNextRead = true; - const progress = yield* harness - .offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001064", - state: boundary === "transcript" ? "done" : "start", - secondState: "start", - }), - ) - .pipe(Effect.forkScoped); - yield* Deferred.await(progressRead); - const continuation = yield* harness.runtime - .startTurn(continuationInput) - .pipe(Effect.forkScoped); - yield* Deferred.succeed(releaseProgress, undefined); - yield* Fiber.join(progress); - yield* Fiber.join(continuation); - if (boundary === "registry") { - yield* Queue.take(harness.terminalReceipts); - } else { - const lastMemberId = workflowMemberEvents(harness.events, 2)[0]?.subagent.id; - while (true) { - const event = yield* Queue.take(harness.subagentReceipts); - if (event.subagent.id === lastMemberId && event.subagent.status === "completed") - break; - } - } - if (boundary === "transcript") { - yield* harness.offerAndWait( - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001065", result: "Done." }), - ); - yield* Queue.take(harness.terminalReceipts); - } - assert.isFalse(yield* harness.hasPendingBackgroundWork); - assert.equal( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, - "completed", - ); - const member = workflowMemberEvents(harness.events, 2).at(-1)?.subagent; - assert.equal(member?.status, "completed"); - const root = harness.events.findLast( - (event) => - event.type === "node.updated" && event.node.threadId === member?.childThreadId, - ); - assert.equal(root?.type === "node.updated" ? root.node.status : null, "completed"); - const item = harness.events.findLast( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID, - ); - assert.equal( - item?.type === "turn_item.updated" ? item.turnItem.status : null, - "completed", - ); - }).pipe( - Effect.provideService(Clock.Clock, { - ...clock, - currentTimeMillis: Effect.gen(function* () { - if (boundary === "registry" && pauseNextRead) { - pauseNextRead = false; - yield* Deferred.succeed(progressRead, undefined); - yield* Deferred.await(releaseProgress); - } - return yield* clock.currentTimeMillis; - }), - }), - Effect.provideService(WorkflowAgentTranscriptReadObserver, () => - Effect.gen(function* () { - if (boundary === "transcript" && pauseNextRead) { - pauseNextRead = false; - yield* Deferred.succeed(progressRead, undefined); - yield* Deferred.await(releaseProgress); - } - }), - ), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + 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), ), ), + ), ); it.effect.each([ @@ -13292,392 +12832,22 @@ describe("ClaudeAdapterV2 background wake turns", () => { 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), - ), - ), - ), - ); - - it.effect.each([ - ["stopped", false, false, false], - ["failed", false, false, false], - ["completed", false, false, false], - ["stopped", true, false, false], - ["failed", true, false, false], - ["completed", true, false, false], - ["interrupted", false, false, false], - ["interrupted", true, false, false], - ["interrupt_timeout", true, false, false], - ["stop_buffered", true, false, false], - ["stop_buffered", true, false, "buffered"], - ["stop_buffered", true, false, "live"], - ["drain_buffered", true, false, "live"], - ["drain_buffered", true, false, "live_after_buffered"], - ["query_failed", false, false, false], - ["query_failed", true, false, false], - ["query_failed", true, false, "buffered"], - ["query_failed", true, true, false], - ] as const)( - "projects workflow members on %s, between turns=%s, after an unrelated failed turn=%s, resume=%s", - ([status, betweenTurns, afterFailedTurn, resumed]) => - Effect.scoped( - Effect.gen(function* () { - const interrupted = status === "interrupted" || status === "interrupt_timeout"; - const liveResume = resumed === "live" || resumed === "live_after_buffered"; - const expected = - status === "drain_buffered" - ? resumed === "live_after_buffered" - ? "completed" - : "running" - : status === "stopped" || interrupted || (status === "stop_buffered" && resumed) - ? "cancelled" - : status === "query_failed" - ? "failed" - : status === "stop_buffered" - ? "completed" - : status; - const harness = yield* makeWorkflowHarnessWithOptions({ - close: status === "interrupt_timeout" ? () => Effect.void : Queue.shutdown, - }); - const now = yield* DateTime.now; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-workflow-terminal"), - text: "Run the workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001010" }); - if (betweenTurns) { - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001013", - result: "Launched.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - if (afterFailedTurn || status === "interrupt_timeout") { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-unrelated-failed"), - providerTurnOrdinal: 2, - text: "Unrelated follow-up.", - attachments: [], - }), - ); - if (afterFailedTurn) { - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001015", - result: "Unrelated follow-up failed.", - terminalReason: "api_error", - isError: true, - }), - ); - yield* Queue.take(harness.terminalReceipts); - } - } - if (status === "query_failed") { - yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001014", - state: "start", - label: "Updated between turns", - }), - ); - } - } - const bufferedCompletion = - status === "stop_buffered" || status === "drain_buffered" || resumed; - if ((!interrupted && status !== "query_failed") || resumed) - yield* Queue.offer( - harness.sdkMessages, - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001011", - status: bufferedCompletion ? "completed" : status, - }), - ); - if (betweenTurns && ((status !== "query_failed" && !interrupted) || resumed)) { - yield* Queue.take(harness.continuationReceipts); - } - if (resumed) { - if (resumed === "live_after_buffered") { - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowTaskStarted, - tool_use_id: "toolu-workflow-earlier-resume", - prompt: "Earlier buffered resume.", - uuid: "00000000-0000-4000-8000-000000001019", - }), - ); - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001020", - status: "completed", - }), - tool_use_id: "toolu-workflow-earlier-resume", - }), - ); - } - if (liveResume) { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-workflow-live-resume"), - providerTurnOrdinal: 2, - text: "Continue the workflow.", - attachments: [], - }), - ); - } - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowTaskStarted, - tool_use_id: "toolu-workflow-resume", - prompt: "Continue the workflow.", - uuid: "00000000-0000-4000-8000-000000001016", - }), - ); - yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001017", - state: "start", - attempt: 2, - label: "Updated between turns", - }), - ); - if (liveResume) { - if (resumed === "live_after_buffered") { - yield* harness.offerAndWait( - claudeSdkFrame({ - ...workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001021", - status: "completed", - }), - tool_use_id: "toolu-workflow-resume", - summary: "Latest workflow result.", - }), - ); - } - yield* harness.offerAndWait( - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001018", - result: "Resumed the workflow.", - }), - ); - yield* Queue.take(harness.terminalReceipts); - } - } - if (betweenTurns && status !== "query_failed" && !interrupted && !bufferedCompletion) { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-workflow-terminal-wake"), - text: "Workflow finished.", - attachments: [], - providerTurnOrdinal: 2, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - } - if (interrupted || status === "stop_buffered") { - const interrupt = harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: - status === "interrupt_timeout" - ? "turn:attempt-unrelated-failed" - : liveResume - ? "turn:attempt-workflow-live-resume" - : "turn:attempt-workflow-terminal", - }), - ...(betweenTurns ? { requestRuntimeRestart: true } : {}), - }); - if (status === "interrupt_timeout") { - const stop = yield* interrupt.pipe(Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(stop); - assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - } else { - yield* interrupt; - } - } else if (status === "query_failed") { - yield* Queue.shutdown(harness.sdkMessages); - } else if (status === "drain_buffered") { - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-workflow-terminal-wake"), - text: "Workflow finished.", - attachments: [], - providerTurnOrdinal: 3, - messageCreatedBy: "agent", - messageCreationSource: "provider", - }), - ); - assert.equal( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, - expected, - ); - } else { - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000001012", - result: "Finished.", - }), - ); - } - if ( - betweenTurns && - (status === "query_failed" || interrupted || status === "stop_buffered") - ) { - const lastMemberId = workflowMemberEvents(harness.events, 2)[0]?.subagent.id; - while (true) { - const update = yield* Queue.take(harness.subagentReceipts); - if (update.subagent.id === lastMemberId && update.subagent.status !== "running") - break; - } - assert.isFalse(yield* harness.hasPendingBackgroundWork); - if (status === "query_failed") { - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.title, - "Updated between turns", - ); - } - } else { - yield* Queue.take(harness.terminalReceipts); - } - assert.equal(workflowCoordinatorEvents(harness.events).at(-1)?.subagent.status, expected); - if (status === "drain_buffered") - assert.equal(yield* harness.hasPendingBackgroundWork, expected === "running"); - if (resumed === "live_after_buffered") { - assert.equal( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.result, - "Latest workflow result.", - ); - } - if (resumed) { - assert.notEqual( - workflowCoordinatorEvents(harness.events).at(-1)?.subagent.result, - "Workflow finished.", - ); - } - for (const index of [1, 2]) { - const updates = workflowMemberEvents(harness.events, index); - const member = updates.at(-1)?.subagent; - assert.equal(member?.status, expected); - assert.deepEqual(member?.startedAt, updates[0]?.subagent.startedAt); - const root = harness.events.findLast( - (event) => - event.type === "node.updated" && event.node.threadId === member?.childThreadId, - ); - assert.equal(root?.type === "node.updated" ? root.node.status : null, expected); - } - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("reads a transcript that appears after a terminal workflow notification", () => - 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-late-terminal-answer"), - text: "Run the alpha workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ harness, snapshotUuid: "00000000-0000-4000-8000-000000001030" }); - const secondThreadId = workflowMemberEvents(harness.events, 2)[0]?.subagent.childThreadId; - yield* Queue.offer( - harness.sdkMessages, - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001031", state: "done" }), - ); - yield* awaitUntil( - () => threadMessages(harness.events, secondThreadId).length === 2, - "workflow member excerpt", - ); - const notification = workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001032", - status: "completed", - }); - yield* Queue.offer(harness.sdkMessages, notification); - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "subagent" && - event.turnItem.nativeItemRef?.nativeId === WORKFLOW_TASK_ID && - event.turnItem.status === "completed", - ), - "terminal workflow notification", - ); - NodeFS.writeFileSync( - NodePath.join(harness.transcriptDir, "agent-a2.jsonl"), - '{"type":"assistant","uuid":"wf-line-3","message":{"role":"assistant","stop_reason":"end_turn","id":"msg_late","content":[{"type":"text","text":"A2 final answer"}]}}\n', - ); - yield* Queue.offer( - harness.sdkMessages, - claudeSdkFrame({ ...notification, uuid: "00000000-0000-4000-8000-000000001033" }), - ); - yield* awaitUntil( - () => - threadMessages(harness.events, secondThreadId).at(-1)?.message.text === - "A2 final answer", - "late terminal transcript answer", - ); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001034", result: "Done." }), - ); - yield* Queue.take(harness.terminalReceipts); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + 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), + ), ), ), - ), ); it.effect("answers settled workflow members from a transcript, or the snapshot excerpt", () => @@ -13742,10 +12912,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { harness.sdkMessages, workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001009", state: "done" }), ); - yield* awaitUntil( - () => threadMessages(harness.events, secondThreadId).length === 2, - "settled workflow member answers", - ); + yield* harness.until(() => threadMessages(harness.events, secondThreadId).length === 2); const coordinator = workflowCoordinatorEvents(harness.events).at(-1)?.subagent; assert.deepEqual( @@ -13754,6 +12921,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); 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"], @@ -13771,14 +12942,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* harness.offerAndWait( workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001015", state: "done" }), ); - yield* awaitUntil( + yield* harness.until( () => workflowCoordinatorEvents(harness.events).length > coordinatorEventsBeforeRepeat, - "repeated settled workflow snapshot", ); - yield* awaitUntil( + yield* harness.until( () => threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 continued", - "continued workflow transcript answer", ); assert.lengthOf(workflowMemberEvents(harness.events, 2), memberEventsBeforeRepeat); assert.lengthOf(threadMessages(harness.events, secondThreadId), 2); @@ -13790,10 +12959,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* harness.offerAndWait( workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001016", state: "done" }), ); - yield* awaitUntil( - () => threadMessages(harness.events, secondThreadId).length === 3, - "late workflow transcript answer", - ); + 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, @@ -13814,29 +12980,33 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000001018", state: "done", attempt: 2, + startedAt: 1000, + durationMs: 500, + lastProgressAt: 4432, }), ); - yield* awaitUntil( - () => currentAssistantAnswers().join("\n\n").includes("Second answer"), - "two-turn workflow member answer", + 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.notDeepEqual( workflowMemberEvents(harness.events, 1).at(-1)?.subagent.startedAt, previousStartedAt, ); - yield* Queue.offer( - harness.sdkMessages, + yield* harness.offerAndWait( workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001019", state: "start", attempt: 3, }), ); - yield* awaitUntil( - () => workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status === "running", - "retried workflow member running", - ); + 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({ @@ -13857,11 +13027,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { attempt: 3, }), ); - yield* awaitUntil( + yield* harness.until( () => threadMessages(harness.events, firstThreadId).at(-1)?.message.text === "A1 retry answer", - "retried workflow member answer", ); assert.equal(currentAssistantAnswers().at(-1), "A1 retry answer"); NodeFS.rmSync(NodePath.join(harness.transcriptDir, "agent-a1.jsonl")); @@ -13873,11 +13042,10 @@ describe("ClaudeAdapterV2 background wake turns", () => { attempt: 4, }), ); - yield* awaitUntil( + yield* harness.until( () => workflowCoordinatorEvents(harness.events).at(-1)?.subagent.workflow?.agents[0] ?.attempt === 4, - "fourth workflow member attempt", ); const answersBeforeEmptyAttempt = currentAssistantAnswers(); yield* harness.offerAndWait( @@ -13902,7 +13070,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - // Line shapes copied from a Claude CLI 2.1.301 workflow member transcript. const transcriptLine = (entry: Record) => `${JSON.stringify({ isSidechain: true, agentId: "a1", timestamp: "2026-10-17T05:08:07.524Z", ...entry })}\n`; const memberAssistantLine = ( @@ -14156,8 +13323,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { Effect.scoped( Effect.gen(function* () { const harness = yield* makeWorkflowHarness; - // About 1.3 MB of early replies: more than the launch frame's read - // and the settled frame's read together, at 512 KB each. + // 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"), @@ -14206,150 +13372,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each([ - { before: "nothing" }, - { before: "text" }, - { before: "a line without a stop reason" }, - ] as const)( - "waits for a settled workflow member's reply to reach its transcript ($before before it)", - ({ before }) => - Effect.scoped( - Effect.gen(function* () { - // Claude Code flushes transcript lines every 100 ms, so a member's reply - // can land after the frame that settles it (seen with CLI 2.1.301). - let appendLateReply: (() => void) | undefined; - const lateReplyWritten = yield* Deferred.make(); - yield* Effect.gen(function* () { - const harness = yield* makeWorkflowHarness; - const transcriptPath = (agentId: string) => - NodePath.join(harness.transcriptDir, `agent-${agentId}.jsonl`); - // A member often says what it is about to do before its first tool call. - const toolCall = (agentId: string) => - memberAssistantLine( - `line-${agentId}-bash`, - `msg_${agentId}`, - [ - ...(before === "text" - ? [{ type: "text", text: `${agentId} lists the files.` }] - : []), - { - type: "tool_use", - id: `toolu_${agentId}`, - name: "Bash", - input: { command: "ls" }, - }, - ], - "tool_use", - ) + - memberToolResultLine(`line-${agentId}-result`, `toolu_${agentId}`, "README.md") + - // A line from a writer that leaves the field out entirely. - (before === "a line without a stop reason" - ? memberAssistantLine(`line-${agentId}-thinking`, `msg_${agentId}_reply`, [ - { type: "thinking", thinking: "Summarize the file.", signature: "sig" }, - ]) - : ""); - const early = (agentId: string) => - before === "text" ? [`${agentId} lists the files.`] : []; - const reply = (agentId: string) => - memberAssistantLine( - `line-${agentId}-reply`, - `msg_${agentId}_reply`, - [{ type: "text", text: `${agentId} found README.md` }], - "end_turn", - ); - NodeFS.writeFileSync(transcriptPath("a1"), toolCall("a1")); - NodeFS.writeFileSync(transcriptPath("a2"), toolCall("a2")); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-claude-workflow-member-late-flush"), - text: "Run the alpha workflow.", - attachments: [], - }), - ); - yield* launchWorkflow({ - harness, - snapshotUuid: "00000000-0000-4000-8000-000000001395", - }); - const texts = (index: number) => - threadMessages( - harness.events, - workflowMemberEvents(harness.events, index)[0]?.subagent.childThreadId, - ).map((event) => event.message.text); - - // The first member settles while the workflow runs on. - yield* harness.offerAndWait( - workflowSnapshot({ - uuid: "00000000-0000-4000-8000-000000001396", - state: "done", - secondState: "start", - }), - ); - assert.equal( - workflowMemberEvents(harness.events, 1).at(-1)?.subagent.status, - "completed", - ); - assert.deepEqual( - texts(1), - ["Reply with exactly: A1", ...early("a1")], - "no excerpt before the reply", - ); - NodeFS.appendFileSync(transcriptPath("a1"), reply("a1")); - yield* harness.offerAndWait( - workflowSnapshot({ uuid: "00000000-0000-4000-8000-000000001397", state: "done" }), - ); - assert.deepEqual(texts(1), [ - "Reply with exactly: A1", - ...early("a1"), - "a1 found README.md", - ]); - assert.deepEqual(texts(2), ["Reply with exactly: A2", ...early("a2")]); - - // The workflow ends right after the second member, before its reply lands. - appendLateReply = () => NodeFS.appendFileSync(transcriptPath("a2"), reply("a2")); - const notified = yield* harness - .offerAndWait( - workflowNotification({ - uuid: "00000000-0000-4000-8000-000000001398", - status: "completed", - }), - ) - .pipe(Effect.forkScoped); - yield* Deferred.await(lateReplyWritten); - for (let tick = 0; tick < 20 && texts(2).at(-1) !== "a2 found README.md"; tick += 1) { - yield* TestClock.adjust("100 millis"); - } - yield* Fiber.join(notified); - assert.deepEqual(texts(2), [ - "Reply with exactly: A2", - ...early("a2"), - "a2 found README.md", - ]); - yield* Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000001399", result: "Done." }), - ); - yield* Queue.take(harness.terminalReceipts); - }).pipe( - Effect.provideService(WorkflowAgentTranscriptReadObserver, (read) => { - // Lands just after the read that would have settled the member. - if (read.agentId !== "a2" || appendLateReply === undefined) return Effect.void; - const append = appendLateReply; - appendLateReply = undefined; - append(); - return Deferred.succeed(lateReplyWritten, undefined).pipe(Effect.asVoid); - }), - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - it.effect("re-reads a workflow member's transcript after a restart without new items", () => Effect.scoped( Effect.gen(function* () { @@ -14399,283 +13421,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect.each([ - { backgrounding: "succeeds" }, - { backgrounding: "fails" }, - { backgrounding: "never answers" }, - { backgrounding: "answers after the steer went out" }, - { backgrounding: "answers after the turn ended" }, - { backgrounding: "answers after the subagent ran again" }, - ] as const)( - "moves the root's foreground subagents to the background before a steer ($backgrounding)", - ({ backgrounding }) => - Effect.scoped( - Effect.gen(function* () { - const FOREGROUND_TOOL_USE_ID = "toolu-steer-foreground"; - const NESTED_TOOL_USE_ID = "toolu-steer-nested"; - const FINISHED_TOOL_USE_ID = "toolu-steer-finished"; - const calls: Array = []; - let beforeAnswer: Effect.Effect = Effect.void; - const harness = yield* makeWakeHarnessWithOptions({ - backgroundTasks: (toolUseId) => - Effect.sync(() => calls.push(toolUseId)).pipe( - Effect.andThen( - backgrounding === "answers after the turn ended" || - backgrounding === "answers after the subagent ran again" - ? Effect.suspend(() => beforeAnswer).pipe(Effect.as(true)) - : backgrounding === "fails" - ? Effect.fail( - new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ - method: "backgroundTasks", - cause: new Error("Background tasks are disabled in this session."), - }), - ) - : backgrounding === "never answers" - ? Effect.never - : backgrounding === "answers after the steer went out" - ? Effect.sleep("6 seconds").pipe(Effect.as(true)) - : Effect.succeed(true), - ), - ), - }); - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const attemptId = RunAttemptId.make("attempt-steer-foreground-subagent"); - const input = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId, - text: "Audit the repo with a subagent.", - attachments: [], - }); - yield* harness.runtime.startTurn(input); - if (backgrounding === "answers after the turn ended") { - beforeAnswer = Queue.offer( - harness.sdkMessages, - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a10", result: "Done." }), - ).pipe( - Effect.andThen(awaitUntil(() => harness.terminalEvents().length === 1, "turn end")), - ); - } - const foregroundTaskStarted = (task: { - readonly spawnDepth?: number; - readonly taskId: string; - readonly toolUseId: string; - readonly uuid: string; - }) => - claudeSdkFrame({ - type: "system", - subtype: "task_started", - task_id: task.taskId, - tool_use_id: task.toolUseId, - description: task.taskId, - subagent_type: "general-purpose", - is_backgrounded: false, - task_type: "local_agent", - prompt: "Audit.", - ...(task.spawnDepth === undefined ? {} : { spawn_depth: task.spawnDepth }), - uuid: task.uuid, - session_id: WAKE_NATIVE_SESSION, - }); - for (const frame of [ - foregroundTaskStarted({ - taskId: "task-steer-finished", - toolUseId: FINISHED_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a01", - }), - makeSubagentNotificationFrame({ - taskId: "task-steer-finished", - toolUseId: FINISHED_TOOL_USE_ID, - summary: "Finished before the steer.", - uuid: "00000000-0000-4000-8000-000000000a02", - }), - foregroundTaskStarted({ - taskId: "task-steer-foreground", - toolUseId: FOREGROUND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a03", - }), - claudeSdkFrame({ - type: "assistant", - message: { - model: "claude-sonnet-4-6", - id: "msg_steer_nested_launch", - type: "message", - role: "assistant", - content: [ - { - type: "tool_use", - id: NESTED_TOOL_USE_ID, - name: "Agent", - input: { description: "Nested check", prompt: "Check." }, - }, - ], - }, - parent_tool_use_id: FOREGROUND_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a04", - session_id: WAKE_NATIVE_SESSION, - }), - foregroundTaskStarted({ - taskId: "task-steer-nested", - toolUseId: NESTED_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a05", - }), - foregroundTaskStarted({ - taskId: "task-steer-deep", - toolUseId: "toolu-steer-deep", - spawnDepth: 2, - uuid: "00000000-0000-4000-8000-000000000a11", - }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - const latestSubagent = (taskId: string) => - harness.events - .flatMap((event) => - event.type === "subagent.updated" && - event.subagent.nativeTaskRef?.nativeId === taskId - ? [event.subagent] - : [], - ) - .at(-1); - yield* awaitUntil( - () => - latestSubagent("task-steer-nested")?.status === "running" && - latestSubagent("task-steer-deep")?.status === "running" && - latestSubagent("task-steer-foreground")?.status === "running" && - latestSubagent("task-steer-finished")?.status === "completed", - "subagents registered", - ); - - const offered = harness.offeredMessages.length; - const steer = 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-steer-foreground-subagent"), - text: "Also check the docs.", - attachments: [], - }, - }); - const RERUN_TOOL_USE_ID = "toolu-steer-rerun"; - if (backgrounding === "answers after the subagent ran again") { - beforeAnswer = harness - .offerAndWait( - makeSubagentNotificationFrame({ - taskId: "task-steer-foreground", - toolUseId: FOREGROUND_TOOL_USE_ID, - summary: "First run done.", - uuid: "00000000-0000-4000-8000-000000000a12", - }), - ) - .pipe( - Effect.andThen( - harness.offerAndWait( - foregroundTaskStarted({ - taskId: "task-steer-foreground", - toolUseId: RERUN_TOOL_USE_ID, - uuid: "00000000-0000-4000-8000-000000000a13", - }), - ), - ), - ); - } - const steering = yield* Effect.forkScoped(steer); - if ( - backgrounding === "never answers" || - backgrounding === "answers after the steer went out" - ) { - yield* awaitUntil(() => calls.length === 1, "background request"); - assert.equal(harness.offeredMessages.length, offered); - yield* TestClock.adjust("5 seconds"); - } - const steered = yield* Fiber.await(steering); - - assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]); - if (backgrounding === "answers after the turn ended") { - assert.isTrue(Exit.isFailure(steered)); - assert.equal(harness.offeredMessages.length, offered); - return; - } - assert.isTrue(Exit.isSuccess(steered)); - assert.equal(harness.offeredMessages.length, offered + 1); - assert.equal(harness.offeredMessages.at(-1)?.priority, "now"); - if (backgrounding === "never answers") { - for (let repeat = 1; repeat <= 2; repeat++) { - const again = yield* Effect.forkScoped(steer); - for (let tick = 0; tick < 100 && again.pollUnsafe() === undefined; tick++) { - yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; - } - assert.isTrue(Exit.isSuccess(yield* Fiber.await(again))); - assert.equal(harness.offeredMessages.length, offered + 1 + repeat); - } - assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]); - } - if (backgrounding === "answers after the steer went out") { - yield* TestClock.adjust("1 second"); - } else if ( - backgrounding !== "succeeds" && - backgrounding !== "answers after the subagent ran again" - ) { - return; - } - const reran = backgrounding === "answers after the subagent ran again"; - - for (const frame of [ - makeResultFrame({ - uuid: "00000000-0000-4000-8000-000000000a06", - result: "", - terminalReason: "aborted_tools", - }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a07", result: "Docs too." }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.terminalEvents().length === 1, "steered turn terminal"); - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-steer-next-turn"), - text: "Anything else?", - attachments: [], - providerTurnOrdinal: 2, - }), - ); - for (const frame of [ - makeSubagentNotificationFrame({ - taskId: "task-steer-foreground", - toolUseId: reran ? RERUN_TOOL_USE_ID : FOREGROUND_TOOL_USE_ID, - summary: "AUDITED", - uuid: "00000000-0000-4000-8000-000000000a08", - }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a09", result: "No." }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* awaitUntil(() => harness.terminalEvents().length === 2, "next turn terminal"); - yield* Queue.offer(harness.sdkMessages, wakeTurnInit); - yield* awaitUntil(() => harness.continuationRequests.length === 1, "subagent wake"); - assert.equal( - harness.continuationRequests[0]?.notification?.summary, - reran ? undefined : 'Subagent "task-steer-foreground" finished', - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - describe("native goals", () => { const syntheticFrame = (uuid: string, text: string) => claudeSdkFrame({ @@ -14761,37 +13506,130 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("keeps a goal active when a hook stops the turn before the goal passes", () => + it.effect( + "defers goal completion until an ambient subagent finishes and Claude checks again", + () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const condition = "the review finds no bugs"; + const taskId = "task-goal-review"; + const toolUseId = "toolu-goal-review"; + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("goal-background-attempt"), + text: `/goal ${condition}`, + attachments: [], + }), + ); + for (const frame of [ + syntheticFrame("goal-background-set", `Goal set: ${condition}`), + claudeSdkFrame({ + ...makeSubagentTaskStartedFrame({ taskId, toolUseId, uuid: "goal-review-start" }), + ambient: true, + skip_transcript: true, + }), + makeAssistantTextFrame({ + uuid: "goal-background-wait", + text: "Waiting for the review.", + }), + makeResultFrame({ uuid: "goal-background-result", result: "Waiting for the review." }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual(goalStatuses(harness.events).at(-1), { + objective: condition, + status: "active", + checks: 0, + }); + + yield* harness.offerAndWait( + makeSubagentNotificationFrame({ + taskId, + toolUseId, + summary: "No bugs found.", + uuid: "goal-review-done", + }), + ); + yield* harness.offerAndWait(wakeTurnInit); + yield* Queue.take(harness.continuationReceipts); + assert.equal(goalStatuses(harness.events).at(-1)?.status, "active"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("goal-background-wake"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "goal-background-wake-work", text: "No bugs found." }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "goal-background-wake-result", + result: "No bugs found.", + origin: { kind: "task-notification" }, + }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual(goalStatuses(harness.events).at(-1), { + objective: condition, + status: "complete", + checks: 0, + }); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect.each([ + { taskType: "mcp_task", status: "complete" }, + { taskType: undefined, status: "active" }, + ] as const)("leaves the goal $status with a running $taskType task", ({ taskType, status }) => Effect.gen(function* () { const harness = yield* makeWakeHarness; - const condition = "the deploy succeeds"; + const condition = "the docs build"; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("goal-hook-stop-attempt"), + attemptId: RunAttemptId.make("goal-task-type-attempt"), text: `/goal ${condition}`, attachments: [], }), ); for (const frame of [ - syntheticFrame("goal-hook-set", `Goal set: ${condition}`), - makeAssistantTextFrame({ uuid: "goal-hook-work", text: "Deploying." }), - makeResultFrame({ - uuid: "goal-hook-result", - result: "Deploying.", - terminalReason: "hook_stopped", + syntheticFrame("goal-task-type-set", `Goal set: ${condition}`), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-goal-docs", + description: "Watch the docs", + ...(taskType === undefined ? {} : { task_type: taskType }), + uuid: "goal-task-type-start", + session_id: WAKE_NATIVE_SESSION, }), + makeAssistantTextFrame({ uuid: "goal-task-type-work", text: "The docs build." }), + makeResultFrame({ uuid: "goal-task-type-result", result: "The docs build." }), ]) { yield* Queue.offer(harness.sdkMessages, frame); } - yield* Queue.take(harness.terminalReceipts); - assert.deepEqual(goalStatuses(harness.events).at(-1), { - objective: condition, - status: "active", - checks: 0, - }); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.equal(goalStatuses(harness.events).at(-1)?.status, status); }).pipe( Effect.scoped, Effect.provide( @@ -14847,8 +13685,7 @@ describe("ClaudeAdapterV2 query message stream", () => { let closed = false; let releaseRead = () => {}; const readStarted = Promise.withResolvers(); - // Never yields a message — the read stays pending until close() flips - // `closed` and releases the in-flight await. + // Keep the read pending until close() releases it. // oxlint-disable-next-line require-yield async function* sdkMessages(): AsyncGenerator { for (;;) { @@ -14885,9 +13722,7 @@ describe("ClaudeAdapterV2 query message stream", () => { ); yield* Effect.promise(() => readStarted.promise); - // Iterating query[Symbol.asyncIterator]() directly deadlocks here: - // the raw generator's return() queues behind the in-flight read and - // scope close never completes. + // The raw async generator's return() queues behind its pending read and deadlocks scope close. yield* Scope.close(scope, Exit.void); assert.isTrue(closed); }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index ec3ec5b052461..5240ee5ea7621 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -331,8 +331,7 @@ function isClaudeSdkReplayMessage(frame: unknown): frame is SDKMessage { type === "system" || type === "stream_event" || type === "rate_limit_event" || - // Undeclared in the SDK types: queued/started/completed for each prompt - // that carries a uuid. + // The SDK types omit command_lifecycle for prompt uuids. type === "command_lifecycle" ); } @@ -654,10 +653,7 @@ function makeReplayQueryRunner( }, }); - // Prompt uuids are derived from ids that differ between the recording and - // a replay run, so a matched prompt offer maps the recorded uuid to the - // replayed one, and inbound frames echoing or acknowledging it are - // rewritten to match. + // Prompt uuids differ on replay; rewrite inbound echoes and acknowledgements to match. const promptUuidReplacements = new Map(); const replayedPromptUuid = (value: string): string => promptUuidReplacements.get(value) ?? value; const withReplayedPromptUuids = (frame: unknown): unknown => { @@ -994,12 +990,7 @@ function layerClaudeAgentSdkReplay( ); } -/** - * While a foreground Bash call runs, Claude Code writes its output to a task - * file the adapter tails. A replay has no Claude Code process, so it writes the - * file each recorded `task_started` names, holding that call's recorded output, - * under a scenario-owned `CLAUDE_CODE_TMPDIR`. - */ +/** Replays write recorded Bash output to task_started files under a scenario-owned CLAUDE_CODE_TMPDIR. */ const writeReplayTaskOutputFiles = Effect.fn("ClaudeReplay.writeTaskOutputFiles")(function* ( transcript: ClaudeAgentSdkReplayTranscript, ) { @@ -1204,8 +1195,7 @@ function sanitizeSdkMessageForReplay(input: { session_id: message.session_id, }; } - // Like init's slash_commands, the recording account's commands and skills - // are local configuration, not protocol. + // Recorded commands and skills are account configuration. if (message.type === "system" && message.subtype === "commands_changed") { return { ...message, commands: [] }; } @@ -1499,12 +1489,8 @@ async function recordMessagesUntilToolUse(input: { } } -// The SDK package may not ship a Claude Code executable for this platform, so -// recordings prefer the installed `claude` binary when it resolves on PATH to -// something the SDK can spawn directly, and otherwise leave the SDK's own -// executable discovery in place. A Windows launcher shim (`claude.cmd` and -// friends) is not directly spawnable, so it only counts when -// resolveClaudeSdkExecutablePath can follow it to a real package entry. +// The SDK may lack a platform executable. Prefer installed Claude only when directly spawnable, +// including Windows shims resolved to package entries. const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingExecutablePath")( function* (environment: NodeJS.ProcessEnv) { const resolveExecutable = yield* SpawnExecutableResolution; @@ -1653,9 +1639,7 @@ async function recordClaudeStreamingQuery(input: { frame: makeClaudePromptOfferFrame(message), }); promptQueue.offer(message); - // A task notification that lands during a turn queues a wake turn the - // CLI can run before this prompt's turn, so results are told apart by - // origin rather than by arrival order. + // Wake turns can precede the prompt turn; identify results by origin. let promptSettled = false; let wakes = 0; const expectedWakes = input.backgroundWakeCounts?.[index] ?? 0; @@ -1667,8 +1651,7 @@ async function recordClaudeStreamingQuery(input: { } } if (input.backgroundWakeCounts !== undefined && input.offerNextPromptImmediately !== true) { - // Every turn opens with system:init; frames from still-running - // subagents are left for the next prompt's recording. + // system:init opens each turn; leave ongoing subagent frames for the next recording. while (isSystemInitFrame(await iterator.peekWithin(CLAUDE_RECORDING_WAKE_QUIET_MS))) { await recordTurn(index + 1); } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 339a99f3d3e47..9dea43bf9e710 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -26,8 +26,10 @@ import { type EffortLevel, type ForkSessionOptions, type ForkSessionResult, + getSessionMessages, getSubagentMessages, query, + resolveSettings as resolveClaudeSettings, type Options as ClaudeQueryOptions, type PermissionMode, type PermissionResult, @@ -49,18 +51,23 @@ import type { } from "@anthropic-ai/claude-agent-sdk/sdk-tools"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK takes a Node ChildProcess for the CLI. import * as NodeChildProcess from "node:child_process"; +import * as NodeUtil from "node:util"; import { parseCliArgs } from "@t3tools/shared/cliArgs"; +import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model"; import { + CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER, CLAUDE_RESUME_COMPACTION_NEVER_ANSWER, formatClaudeResumeCompactionQuestion, } from "@t3tools/shared/claudeCompaction"; import { type ChatAttachment, ClaudeSettings, + TrimmedNonEmptyString, defaultInstanceIdForDriver, + isCompactionCommandMessage, type ModelSelection, type OrchestrationV2ConversationMessage, type OrchestrationV2ExecutionNode, @@ -83,6 +90,8 @@ import { type OrchestrationV2TurnItem, type OrchestrationV2WebSearchResult, type ProviderApprovalDecision, + type ProviderApprovalFullAccessOverride, + type ProviderApprovalOption, ProviderDriverKind, type ProviderInstanceId, type ProviderRequestKind, @@ -90,9 +99,11 @@ import { type ProviderThreadId, type RunId, type ThreadId, + resolveIdleCompaction, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; @@ -110,21 +121,29 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { resolveClaudeSdkExecutablePath } from "../../provider/Drivers/ClaudeExecutable.ts"; -import { planClaudeSkillDispatch } from "../../provider/Drivers/ClaudeSkillDispatch.ts"; +import { + planClaudeSkillDispatch, + type ClaudeSkillTarget, +} from "../../provider/Drivers/ClaudeSkillDispatch.ts"; import { discoverClaudeSkills } from "../../provider/Drivers/ClaudeSkills.ts"; import { compileClaudeModelSelection, type CompiledClaudeModelSelection, } from "../../claudeModelOptions.ts"; import * as ServerConfig from "../../config.ts"; +import * as ServerSettings from "../../serverSettings.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe"; import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { claudeSignedOutMessage, makeClaudeEnvironment, + resolveClaudeHomePath, } from "../../provider/Drivers/ClaudeHome.ts"; import { BUNDLED_CLAUDE_MODEL_CATALOG, @@ -178,7 +197,7 @@ import { } from "@t3tools/provider-core/server/subagentProjection"; export const CLAUDE_PROVIDER = ProviderDriverKind.make("claudeAgent"); -export const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const; +const CLAUDE_AGENT_SDK_QUERY_PROTOCOL = "claude-agent-sdk.query" as const; function claudeContextWindow(modelSelection: ModelSelection): number | null { return ( @@ -200,6 +219,26 @@ function claudePromptCacheTtlMs( return undefined; } +// Claude caps the window at the model's context, so a setting at or above it never applies. +function claudeAutoCompactThreshold(autoCompactWindow: string, maxTokens: number | null) { + const threshold = Number(autoCompactWindow); + return threshold > 0 && (maxTokens === null || threshold < maxTokens) + ? { autoCompactThreshold: threshold } + : {}; +} + +function claudeMessageInputTokens(usage: { + readonly input_tokens: number; + readonly cache_creation_input_tokens?: number | null; + readonly cache_read_input_tokens?: number | null; +}): number { + return ( + usage.input_tokens + + (usage.cache_creation_input_tokens ?? 0) + + (usage.cache_read_input_tokens ?? 0) + ); +} + export function claudeProviderTurnTokenUsage( usage: { readonly input_tokens: number; @@ -210,56 +249,103 @@ export function claudeProviderTurnTokenUsage( }, modelSelection: ModelSelection, updatedAt: string, + autoCompactWindow = "", + requestedAt?: DateTime.Utc, ) { - const inputTokens = - usage.input_tokens + - (usage.cache_creation_input_tokens ?? 0) + - (usage.cache_read_input_tokens ?? 0); + const inputTokens = claudeMessageInputTokens(usage); const outputTokens = usage.output_tokens; const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation); + const maxTokens = claudeContextWindow(modelSelection); + // The cache lifetime starts with the request, not when its response ends. + const promptCacheExpiresAt = + promptCacheTtlMs === undefined || requestedAt === undefined + ? undefined + : DateTime.formatIso(DateTime.add(requestedAt, { milliseconds: promptCacheTtlMs })); return { usedTokens: inputTokens + outputTokens, - maxTokens: claudeContextWindow(modelSelection), + maxTokens, inputTokens, cachedInputTokens: usage.cache_read_input_tokens ?? 0, outputTokens, reasoningOutputTokens: 0, ...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }), + ...claudeAutoCompactThreshold(autoCompactWindow, maxTokens), + ...(promptCacheExpiresAt === undefined ? {} : { promptCacheExpiresAt }), updatedAt, }; } + +type ClaudeMessageUsage = Parameters[0]; + +// message_delta usage is per-message cumulative; null or absent fields retain message_start values and zeros replace them. +function mergeClaudeStreamUsage( + current: ClaudeMessageUsage, + delta: { + readonly input_tokens?: number | null; + readonly cache_creation_input_tokens?: number | null; + readonly cache_read_input_tokens?: number | null; + readonly output_tokens: number; + }, +): ClaudeMessageUsage { + return { + ...current, + input_tokens: delta.input_tokens ?? current.input_tokens, + cache_creation_input_tokens: + delta.cache_creation_input_tokens ?? current.cache_creation_input_tokens ?? null, + cache_read_input_tokens: + delta.cache_read_input_tokens ?? current.cache_read_input_tokens ?? null, + output_tokens: delta.output_tokens, + }; +} export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVIDER); const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({}); -// Entry extensions the Claude SDK runs through node instead of executing. const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"]; -// The SDK puts no deadline on control requests. The CLI answers -// mcp_set_servers once each server connected or hit its own 30 s timeout. +// The SDK has no control-request deadline; the CLI waits up to 30 s per MCP server. const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds"; +// Claude can consume a subagent result before the launching turn ends, leaving +// its notification with no native wake turn to answer the continuation. +const CLAUDE_WAKE_TURN_START_DEADLINE = "2 minutes"; // Claude Code flushes transcript writes every 100 ms, so a workflow member's // reply can land after the progress frame that settles it. Its transcript // stays the source of its answer this long after it settles. const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500; +// A steer waits at most this long, from its request, for its foreground +// subagents to move to the background before it is sent. +const BACKGROUND_MOVE_TIMEOUT_MS = 5_000; + +const CLAUDE_GROUP_WATCH_SCRIPT = [ + "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", + 'exec "$@" 3<&-', +].join("\n"); /** - * When the CLI exits it stops the MCP servers it started, but not their children: a plugin's - * `bun run start` wrapper dies and its `bun server.ts` keeps running, writing to a pipe nobody - * reads (#3089). Those stay in the CLI's group, so the rest of the group gets SIGKILL once the - * CLI exits for any reason. + * 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. */ -function spawnClaudeProcessGroup(options: ClaudeSpawnOptions): ClaudeSpawnedProcess { - const child = NodeChildProcess.spawn(options.command, options.args, { - cwd: options.cwd, - env: options.env, - signal: options.signal, - stdio: ["pipe", "pipe", "ignore"], - detached: true, - }); +export function spawnClaudeProcessGroup( + options: ClaudeSpawnOptions, + onExit?: () => void, +): ClaudeSpawnedProcess { + const child = NodeChildProcess.spawn( + "/bin/sh", + ["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args], + { + cwd: options.cwd, + env: options.env, + signal: options.signal, + stdio: ["pipe", "pipe", "ignore", "pipe"], + detached: true, + }, + ); child.once("exit", () => { try { signalProcessGroup(child.pid ?? 0, "SIGKILL"); } catch {} + onExit?.(); }); - return child; + // Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes. + return child as ClaudeSpawnedProcess; } export const ClaudeProviderCapabilitiesV2 = { @@ -452,6 +538,27 @@ export class ClaudeBackgroundWorkBlocksQueryReplacementError extends Schema.Tagg } } +export class ClaudeAppendSystemPromptFileError extends Schema.TaggedError()( + "ClaudeAppendSystemPromptFileError", + { + path: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return `Claude could not read the --append-system-prompt-file launch argument at ${this.path}. Fix the path in the Claude launch arguments, then send the message again.`; + } +} + +export class ClaudeAppendSystemPromptMissingValueError extends Schema.TaggedError()( + "ClaudeAppendSystemPromptMissingValueError", + { flag: Schema.Literals(["--append-system-prompt", "--append-system-prompt-file"]) }, +) { + override get message(): string { + return `The ${this.flag} launch argument has no ${this.flag === "--append-system-prompt" ? "text" : "file path"}. Add it after the flag in the Claude launch arguments, then send the message again.`; + } +} + export interface ClaudeAgentSdkQueryRunnerShape { readonly allocateSessionId: Effect.Effect; readonly open: ( @@ -459,7 +566,10 @@ export interface ClaudeAgentSdkQueryRunnerShape { ) => Effect.Effect; readonly forkSession: ( input: ClaudeAgentSdkSessionForkInput, - ) => Effect.Effect; + ) => Effect.Effect< + ForkSessionResult & { readonly headMessageId?: string }, + ClaudeAgentSdkQueryRunnerError + >; readonly subagentLaunchToolUseId: ( input: ClaudeAgentSdkSubagentLookupInput, ) => Effect.Effect; @@ -474,6 +584,7 @@ export class ClaudeAgentSdkQueryRunner extends Context.Service< export interface ClaudeAgentSdkSessionForkInput { readonly sessionId: string; readonly options: ForkSessionOptions; + readonly environment: NodeJS.ProcessEnv; readonly threadId: ThreadId; readonly providerSessionId: OrchestrationV2ProviderSession["id"]; } @@ -507,10 +618,7 @@ function closeClaudeQuery(queryRuntime: ClaudeQuery) { }); } -// Iterate the Query itself, not query[Symbol.asyncIterator]() (the raw -// sdkMessages generator). The raw generator's return() queues behind the -// in-flight read of the next CLI message and never settles while the CLI is -// idle, deadlocking stream interruption (and with it, session scope close). +// Iterate Query itself: the raw generator's return() queues behind a pending CLI read and deadlocks interruption. export function claudeQueryMessages(queryRuntime: ClaudeQuery): AsyncIterable { return { [Symbol.asyncIterator]: () => queryRuntime }; } @@ -680,7 +788,7 @@ export function loggedClaudeQueryOptions( }; } -export function makeClaudeAgentSdkProtocolLogger(input: { +function makeClaudeAgentSdkProtocolLogger(input: { readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined; readonly threadId: ThreadId; readonly providerSessionId: OrchestrationV2ProviderSession["id"]; @@ -707,17 +815,78 @@ export function makeClaudeAgentSdkProtocolLogger(input: { }; } +const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +const decodeClaudeHistoryFork = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }), + ), +); + +const claudeConfigDirOf = ( + path: Path.Path, + environment: NodeJS.ProcessEnv, + homeDirectory: string, +) => path.resolve(environment.CLAUDE_CONFIG_DIR ?? path.join(homeDirectory, ".claude")); + +// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a +// worker so concurrent providers keep the server's environment. +const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* ( + input: ClaudeAgentSdkSessionForkInput, +) { + const path = yield* Path.Path; + const fromSource = import.meta.url.endsWith(".ts"); + // A single executable hosts the worker itself; it has no sibling script. + const workerArguments = (yield* HostProcess.IsExecutable) + ? ["__claude-history"] + : [ + ...(fromSource ? ["--experimental-strip-types"] : []), + yield* path.fromFileUrl( + new URL( + fromSource ? "../../claude-history-worker.ts" : "./claude-history-worker.mjs", + import.meta.url, + ), + ), + ]; + const executablePath = yield* HostProcess.ExecutablePath; + const result = yield* spawnAndCollect( + executablePath, + ChildProcess.make( + executablePath, + [ + ...workerArguments, + "forkSession", + input.sessionId, + encodeClaudeHistoryOptions(input.options), + ], + { env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } }, + ), + ).pipe(Effect.timeout("30 seconds")); + if (result.code !== 0) { + return yield* new ClaudeAgentSdkQueryRunnerError({ + method: "forkSession", + cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`, + }); + } + return yield* decodeClaudeHistoryFork(result.stdout); +}); + export const layerQueryRunner: Layer.Layer< ClaudeAgentSdkQueryRunner, never, - Crypto.Crypto | ProviderEventLoggers.ProviderEventLoggers + | ChildProcessSpawner.ChildProcessSpawner + | Crypto.Crypto + | Path.Path + | ProviderEventLoggers.ProviderEventLoggers > = Layer.effect( ClaudeAgentSdkQueryRunner, Effect.gen(function* () { const crypto = yield* Crypto.Crypto; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers; const agentScope = yield* AgentScope; const platform = yield* HostProcess.Platform; + const runFork = Effect.runForkWith(yield* Effect.context()); return ClaudeAgentSdkQueryRunner.of({ allocateSessionId: crypto @@ -740,14 +909,9 @@ export const layerQueryRunner: Layer.Layer< ), Stream.toAsyncIterable, ); - // The SDK would pass `mcpServers` as an inline `--mcp-config` argument, - // which every local user can read. They go over the CLI's stdin control - // channel instead, so header credentials stay out of its argv and out - // of the environment every command the agent runs inherits. + // Send MCP credentials over stdin to keep them out of SDK argv and inherited command environments. const { mcpServers, ...queryOptions } = input.options; - // The SDK spawns a native binary as `path ...executableArgs ...sdkArgs`, - // which lets the agent scope wrapper go in front of the CLI. The SDK - // runs a script entry through node instead, so those launch unwrapped. + // The SDK can prepend a scope wrapper to native binaries; script entries run through node. const binaryPath = queryOptions.pathToClaudeCodeExecutable; const launch = binaryPath === undefined || @@ -768,10 +932,16 @@ export const layerQueryRunner: Layer.Layer< pathToClaudeCodeExecutable: launch.command, executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])], }; + const unit = launch?.unit; + const stopScope = + unit === undefined ? undefined : () => void runFork(agentScope.stop(unit)); // Windows has no process groups, so there the SDK spawns the CLI itself. const spawnClaudeCodeProcess = options.spawnClaudeCodeProcess ?? - (platform === "win32" ? undefined : spawnClaudeProcessGroup); + (platform === "win32" + ? undefined + : (spawnOptions: ClaudeSpawnOptions) => + spawnClaudeProcessGroup(spawnOptions, stopScope)); const queryRuntime = yield* Effect.uninterruptibleMask((restore) => Effect.try({ try: () => @@ -788,8 +958,7 @@ export const layerQueryRunner: Layer.Layer< restore( Effect.gen(function* () { if (mcpServers !== undefined) { - // Error texts and the CLI's mcp_status response can echo the headers, so - // only server names are logged. + // Errors and mcp_status can echo headers; log only server names. const failed = yield* Effect.tryPromise(() => queryRuntime.setMcpServers(mcpServers), ).pipe( @@ -981,10 +1150,23 @@ export const layerQueryRunner: Layer.Layer< options: input.options, }, }); - const result = yield* Effect.tryPromise({ - try: () => forkClaudeSession(input.sessionId, input.options), - catch: (cause) => queryRunnerError(cause, "forkSession"), - }); + const hostEnvironment = yield* HostProcess.Environment; + const homeDirectory = yield* HostProcess.HomeDirectory; + const usesHostConfig = + claudeConfigDirOf(path, input.environment, homeDirectory) === + claudeConfigDirOf(path, hostEnvironment, homeDirectory); + const fork: Effect.Effect< + ForkSessionResult & { readonly headMessageId?: string }, + unknown + > = usesHostConfig + ? Effect.tryPromise(() => forkClaudeSession(input.sessionId, input.options)) + : forkClaudeSessionInWorker(input).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(Path.Path, path), + ); + const result = yield* fork.pipe( + Effect.mapError((cause) => queryRunnerError(cause, "forkSession")), + ); yield* logProtocolEvent({ direction: "incoming", stage: "decoded", @@ -993,7 +1175,22 @@ export const layerQueryRunner: Layer.Layer< sessionId: result.sessionId, }, }); - return result; + // The SDK remaps copied UUIDs. Capture the inherited head before the + // fork's first run appends messages. + const headMessageId = usesHostConfig + ? yield* Effect.tryPromise({ + try: () => + getSessionMessages( + result.sessionId, + input.options.dir === undefined ? {} : { dir: input.options.dir }, + ), + catch: (cause) => queryRunnerError(cause, "getSessionMessages"), + }).pipe( + Effect.map((messages) => messages.at(-1)?.uuid), + Effect.orElseSucceed(() => undefined), + ) + : result.headMessageId; + return headMessageId === undefined ? result : { ...result, headMessageId }; }), subagentLaunchToolUseId: Effect.fn("ClaudeAgentSdkQueryRunner.subagentLaunchToolUseId")( function* (input: ClaudeAgentSdkSubagentLookupInput) { @@ -1037,11 +1234,7 @@ export const layerQueryRunner: Layer.Layer< type ClaudeFlagSettings = Parameters[0]; -/** - * Thinking is a launch flag (`--thinking`), so only a new process can change - * it. Clearing an explicit effort also needs one: the live reset goes to the - * model default, while a new process reads the user's settings files. - */ +/** Thinking requires a new process. Clearing effort also requires one to reload user settings instead of model defaults. */ function canApplyClaudeSelectionLive( live: CompiledClaudeModelSelection, next: CompiledClaudeModelSelection, @@ -1062,6 +1255,62 @@ function claudeLiveSelectionFlagSettings( }; } +// A delegated child is its own SDK session, so Claude Code gives it the main-conversation cache +// TTL. When the user sets Claude's subagentPromptCacheTtl, the child follows it like a native +// subagent would. An explicit CLAUDE_CODE_PROMPT_CACHE_TTL on the instance still wins. +export function claudeQueryEnvironment( + environment: NodeJS.ProcessEnv, + appThread: Pick, + subagentPromptCacheTtl: "5m" | "1h" | undefined, +): NodeJS.ProcessEnv { + if ( + appThread.lineage.relationshipToParent !== "subagent" || + subagentPromptCacheTtl === undefined || + environment.CLAUDE_CODE_PROMPT_CACHE_TTL !== undefined + ) { + return environment; + } + return { ...environment, CLAUDE_CODE_PROMPT_CACHE_TTL: subagentPromptCacheTtl }; +} + +// Claude Code's auto tool search sends every MCP schema in full while they fit under a share of the +// context window, which T3's tools do on 1M models. auto:0 already means on and auto:100 off. +export function claudeToolSearchOverride(value: string | undefined): "true" | undefined { + if (value === undefined) return undefined; + if (value === "auto") return "true"; + if (!value.startsWith("auto:")) return undefined; + const percent = parseClaudeInteger(value.slice("auto:".length)); + // Claude Code treats an unparsable auto:N as auto, and clamps N to 0..100. + if (Number.isNaN(percent)) return "true"; + const clamped = Math.min(100, Math.max(0, percent)); + return clamped > 0 && clamped < 100 ? "true" : undefined; +} + +// Claude Code 2.1.310's integer parsing for auto:N. Scientific notation counts only when it is an +// integer, grouped digits (1_000, 1,000, or 1 000) are joined, and anything else uses parseInt. +const CLAUDE_SCIENTIFIC_INTEGER = /^[+-]?(\d+(\.\d*)?|\.\d+)[eE][+-]?\d+$/; +const CLAUDE_GROUPED_INTEGER = /^[+-]?\d{1,3}([_,\u00A0\u202F ])\d{3}(?:\1\d{3})*$/; +function parseClaudeInteger(text: string): number { + const value = text.trim(); + if (value.length <= 32 && CLAUDE_SCIENTIFIC_INTEGER.test(value)) { + const number = Number(value); + return Number.isInteger(number) ? number : Number.NaN; + } + if (value.length <= 32 && CLAUDE_GROUPED_INTEGER.test(value)) { + return Number.parseInt(value.replace(/[_,\u00A0\u202F ]/g, ""), 10); + } + return Number.parseInt(value, 10); +} + +// Claude Code defers MCP tools behind ToolSearch, so the agent only finds +// t3_background_wait when the system prompt says when to reach for it. +const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = ` + +### Background work you wait on + +Before you end your turn to wait for a background command or Monitor you started, such as tests, a build, or a CI wait, call \`t3_background_wait\` with its task ID. The thread then stays in the user's Working list until that task ends, instead of returning to them early. Do not mark a dev server, a watcher, or anything else you leave running. +`; + export function makeClaudeQueryOptions(input: { readonly modelSelection: ModelSelection; readonly nativeThreadId: string; @@ -1081,13 +1330,25 @@ export function makeClaudeQueryOptions(input: { readonly onUserDialog?: ClaudeQueryOptions["onUserDialog"]; readonly supportedDialogKinds?: ClaudeQueryOptions["supportedDialogKinds"]; readonly allowDangerouslySkipPermissions?: boolean; + readonly appendSystemPromptFileText?: string; + // Flag settings, because a user's settings.json env beats the process env in Claude Code. + readonly toolSearchOverride?: "true"; }): ClaudeAgentSdkQueryOptions { const compiledSelection = compileClaudeModelSelection(input.modelSelection); const { "permission-mode": launchArgPermissionMode, "dangerously-skip-permissions": launchArgSkipPermissions, + "append-system-prompt": launchArgAppendSystemPrompt, + "append-system-prompt-file": _launchArgAppendSystemPromptFile, ...extraArgs } = input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags; + // Claude Code overwrites its CLI append text with the SDK's initialize + // appendSystemPrompt, so launch-argument text has to travel in that value. + // The CLI puts file text before inline text and trims one trailing newline. + const launchAppendSystemPrompt = [ + input.appendSystemPromptFileText?.replace(/\r?\n$/, ""), + launchArgAppendSystemPrompt, + ].filter((text): text is string => typeof text === "string" && text.length > 0); const requestThinkingSummaries = compiledSelection.settings.alwaysThinkingEnabled !== false && extraArgs["thinking-display"] !== "omitted"; @@ -1108,13 +1369,21 @@ export function makeClaudeQueryOptions(input: { : typeof input.sdkSettings === "object" && input.sdkSettings !== null ? ({ ...input.sdkSettings, ...selectionSettings } as ClaudeSdkSettings) : selectionSettings; - const effectiveQuerySettings = + const compactQuerySettings = input.settings?.autoCompactWindow === undefined || input.settings.autoCompactWindow.length === 0 ? querySettings : ({ ...(typeof querySettings === "object" && querySettings !== null ? querySettings : {}), autoCompactWindow: Number(input.settings.autoCompactWindow), } as ClaudeSdkSettings); + // A settings file path cannot take extra keys, so it goes through unchanged. + const effectiveQuerySettings = + input.toolSearchOverride === undefined || typeof compactQuerySettings === "string" + ? compactQuerySettings + : ({ + ...compactQuerySettings, + env: { ...compactQuerySettings?.env, ENABLE_TOOL_SEARCH: input.toolSearchOverride }, + } as ClaudeSdkSettings); const options: ClaudeAgentSdkQueryOptions = { model: compiledSelection.apiModelId, tools: claudeAgentSdkQueryToolsForSdk(selectedTools), @@ -1163,9 +1432,13 @@ export function makeClaudeQueryOptions(input: { systemPrompt: { type: "preset" as const, preset: "claude_code" as const, - append: + append: [ buildRuntimeInstructions({ harness: "Claude Code" }) + - (input.mcpServers === undefined ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS), + (input.mcpServers === undefined + ? "" + : T3_CODE_ORCHESTRATION_INSTRUCTIONS + CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS), + ...launchAppendSystemPrompt, + ].join("\n\n"), }, ...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }), }; @@ -1178,10 +1451,46 @@ export function makeClaudeQueryOptions(input: { return input.cwd === null ? withDirectories : { ...withDirectories, cwd: input.cwd }; } +/** + * Checks the append launch arguments the way the Claude CLI would and reads + * the file relative to the process cwd. makeClaudeQueryOptions folds these + * flags out of extraArgs, so a value the CLI would have rejected has to be + * rejected here or it silently disappears. + */ +const readClaudeAppendSystemPromptFile = Effect.fnUntraced(function* (input: { + readonly settings: ClaudeSettings | undefined; + readonly cwd: string | null; + readonly fileSystem: FileSystem.FileSystem; + readonly path: Path.Path; +}) { + if (input.settings === undefined) return undefined; + const flags = parseCliArgs(input.settings.launchArgs).flags; + // parseCliArgs gives null for a flag with no following value. An explicit + // `--append-system-prompt ""` is a value the CLI accepts, so it stays. + if (flags["append-system-prompt"] === null) { + return yield* new ClaudeAppendSystemPromptMissingValueError({ + flag: "--append-system-prompt", + }); + } + const file = flags["append-system-prompt-file"]; + if (file === undefined) return undefined; + // `--append-system-prompt-file=` is "" and names no file either. + if (file === null || file === "") { + return yield* new ClaudeAppendSystemPromptMissingValueError({ + flag: "--append-system-prompt-file", + }); + } + const filePath = input.path.resolve(input.cwd ?? ".", file); + return yield* input.fileSystem + .readFileString(filePath) + .pipe( + Effect.mapError((cause) => new ClaudeAppendSystemPromptFileError({ path: filePath, cause })), + ); +}); + export const CLAUDE_T3_MCP_TOOL_WILDCARD = "mcp__t3-code__*"; -// Must stay in sync with the Tool.Readonly annotations on OrchestratorToolkit; -// ClaudeAdapterV2.test.ts cross-checks this list against the toolkit. +// Keep in sync with OrchestratorToolkit Tool.Readonly annotations; ClaudeAdapterV2.test.ts checks this. export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__orchestrator_capabilities", "mcp__t3-code__list_scheduled_tasks", @@ -1204,18 +1513,11 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__html_render", ]; -// Claude Code aborts an HTTP MCP call after 60 s ("The operation timed out.") -// unless the server config sets `timeout`. T3's wait tools (t3_thread_wait, -// delegate_task mode=wait) legitimately block for up to an hour -// (MAX_WAIT_TIMEOUT_MS in OrchestratorMcpService), so the budget sits just -// above that and the server's own wait timeout is what ends a long call. +// T3 waits can block for an hour; exceed Claude's default 60 s timeout. export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000; -// The SDK's `allowedTools` only pre-approves tool calls; availability is the separate `tools` -// option. Attaching the t3-code MCP server therefore always pre-approves its tools (headless -// modes like `dontAsk` deny anything that is not pre-approved), but read-only sandboxes -// pre-approve only the annotated read-only orchestrator tools so a read-only session cannot -// silently spawn threads or scheduled tasks. +// allowedTools pre-approves calls; tools controls availability. Pre-approve T3 tools for headless modes, +// limited to annotated read-only tools in read-only sandboxes. export function claudeMcpQueryOverrides(input: { readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; @@ -1272,10 +1574,7 @@ function textFromClaudeContent(content: SDKAssistantMessage["message"]["content" return content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""); } -// Claude 5.1 and later return the text written ahead of a tool call as a -// thinking block, at most one per call, instead of a text block. Summarized -// display makes it look like reasoning, so only the second of two thinking -// blocks right before a tool call is treated as that text. +// Claude 5.1+ emits at most one pre-tool text block as thinking; treat only a second consecutive thinking block as text. function claudeWritesUpdatesAsThinking(model: string): boolean { const match = /claude-[a-z]+-(\d+)(?:-(\d{1,2}))?(?!\d)/u.exec(model); if (match === null) return false; @@ -1283,9 +1582,7 @@ function claudeWritesUpdatesAsThinking(model: string): boolean { return major > 5 || (major === 5 && Number(match[2] ?? 0) >= 1); } -// In SDK mode Claude reports `/goal` only through the transcript (its -// `active_goal` event is remote-only): synthetic command output names the -// goal, and each unmet evaluator check returns as Stop hook feedback. +// In SDK mode, /goal appears only in transcripts: command output names it and Stop hooks report unmet checks. const CLAUDE_GOAL_SET_PREFIX = "Goal set: "; const CLAUDE_GOAL_ACTIVE = /^Goal active: ([\s\S]+?) \((?:not yet evaluated|(\d+) turns?)\)/u; @@ -1373,6 +1670,7 @@ function makeProviderThread(input: { readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; readonly nativeThreadId: string; readonly forkedFrom?: NonNullable; + readonly nativeMetadata?: NonNullable; readonly now: DateTime.Utc; }): OrchestrationV2ProviderThread { return { @@ -1396,11 +1694,22 @@ function makeProviderThread(input: { lastRunOrdinal: null, handoffIds: [], forkedFrom: input.forkedFrom ?? null, + ...(input.nativeMetadata === undefined ? {} : { nativeMetadata: input.nativeMetadata }), createdAt: input.now, updatedAt: input.now, }; } +const decodeClaudeTranscriptLine = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Struct({ type: Schema.String })), +); + +const isClaudeConversationLine = (line: string): boolean => + Option.match(decodeClaudeTranscriptLine(line), { + onNone: () => false, + onSome: (entry) => entry.type === "user" || entry.type === "assistant", + }); + const getNativeThreadId = Effect.fnUntraced(function* ( providerThread: OrchestrationV2ProviderThread, ) { @@ -1491,7 +1800,7 @@ const resolveClaudeRollbackResumeSessionAt = Effect.fn( )(function* (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) { switch (input.target.type) { case "thread_start": - return null; + return input.providerThread.nativeMetadata?.forkHeadMessageId ?? null; case "provider_turn": { const target = input.target; if (target.providerTurn.providerThreadId !== input.providerThread.id) { @@ -1549,17 +1858,13 @@ function isSupportedClaudeImageMimeType( export function makeClaudeUserMessage(input: { readonly text: string; readonly priority?: SDKUserMessage["priority"]; - readonly skillNames?: ReadonlySet; + readonly skills?: ReadonlyMap; readonly uuid?: SDKUserMessage["uuid"]; }): SDKUserMessage { - // Claude Code expands a skill only from the LAST text block, and only when - // `/name` is its first character. A `$skill` chip anywhere in the prompt is - // therefore split into [leading text, "/name trailing text"] so the CLI runs - // it natively and the prose around it survives. + // Claude expands a skill only when `/name` starts the last text block. + // Keep the whole request before that block; see ClaudeSkillDispatch. const dispatch = - input.skillNames === undefined - ? undefined - : planClaudeSkillDispatch(input.text, input.skillNames); + input.skills === undefined ? undefined : planClaudeSkillDispatch(input.text, input.skills); return { type: "user", message: { @@ -1586,12 +1891,12 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: readonly uuid?: SDKUserMessage["uuid"]; readonly attachmentsDir: string; readonly fileSystem: FileSystem.FileSystem; - readonly skillNames?: ReadonlySet; + readonly skills?: ReadonlyMap; }) { if (input.attachments.length === 0) { return makeClaudeUserMessage({ text: input.text, - ...(input.skillNames === undefined ? {} : { skillNames: input.skillNames }), + ...(input.skills === undefined ? {} : { skills: input.skills }), ...(input.priority === undefined ? {} : { priority: input.priority }), ...(input.uuid === undefined ? {} : { uuid: input.uuid }), }); @@ -1605,9 +1910,9 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: }); const dispatch = - input.skillNames === undefined + input.skills === undefined ? undefined - : planClaudeSkillDispatch(textWithAttachmentPaths, input.skillNames); + : planClaudeSkillDispatch(textWithAttachmentPaths, input.skills); const content: Array = []; if (dispatch?.leadingText !== undefined) { content.push({ type: "text", text: dispatch.leadingText }); @@ -1641,6 +1946,7 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, detail: `Failed to read attachment '${attachment.id}'`, + reason: "attachment_unreadable", payload: cause, }), ), @@ -1655,8 +1961,7 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: }); } - // Images go before the command block: a text block after them still - // expands, a command block followed by an image does not. + // Images must precede the command block for skill expansion. if (dispatch) { content.push({ type: "text", text: dispatch.commandText }); } else if (textWithAttachmentPaths.length > 0) { @@ -1809,10 +2114,27 @@ export interface ClaudeRuntimeQueryPolicy { readonly installPermissionCallback: boolean; } +interface ClaudeBypassAvailability { + readonly bypassDisabled: boolean; + readonly autoDisabled: boolean; +} + +const CLAUDE_BYPASS_FULLY_AVAILABLE: ClaudeBypassAvailability = { + bypassDisabled: false, + autoDisabled: false, +}; + export function claudeRuntimeQueryPolicyForRuntimePolicy( runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + availability: ClaudeBypassAvailability = CLAUDE_BYPASS_FULLY_AVAILABLE, ): ClaudeRuntimeQueryPolicy { - const permissionMode = permissionModeForClaudeRuntimePolicy(runtimePolicy); + const requestedMode = permissionModeForClaudeRuntimePolicy(runtimePolicy); + const downgraded = requestedMode === "bypassPermissions" && availability.bypassDisabled; + const permissionMode = downgraded + ? availability.autoDisabled + ? "default" + : "auto" + : requestedMode; const readOnlyTools = sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy) === "readOnly" ? CLAUDE_READ_ONLY_ALLOWED_TOOLS @@ -1821,20 +2143,21 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy( readOnlyTools !== undefined && readOnlyPolicyAllowsGlobalReads(runtimePolicy) ? readOnlyTools : undefined; - // acceptEdits approves edits before the callback runs; everything else it - // leaves to the callback, which must ask rather than allow. + // acceptEdits approves edits before the callback; the callback must ask for everything else. const installPermissionCallback = - runtimePolicy.approvalPolicy === undefined + downgraded || + (runtimePolicy.approvalPolicy === undefined ? runtimePolicy.runtimeMode === "approval-required" || runtimePolicy.runtimeMode === "auto-accept-edits" - : runtimePolicy.approvalPolicy !== "never"; + : runtimePolicy.approvalPolicy !== "never"); if (permissionMode === "plan") { return { permissionMode, ...(readOnlyTools === undefined ? {} : { tools: readOnlyTools }), ...(allowedTools === undefined ? {} : { allowedTools }), - installPermissionCallback, + // Claude routes Plan-mode writes to the callback even in Auto or Full access. + installPermissionCallback: true, }; } @@ -1847,14 +2170,59 @@ export function claudeRuntimeQueryPolicyForRuntimePolicy( }; } -function shouldInstallClaudePermissionCallback(policy: ClaudeRuntimeQueryPolicy): boolean { - return policy.installPermissionCallback; +const ClaudeBypassSettings = Schema.StructWithRest( + Schema.Struct({ + disableAutoMode: Schema.optionalKey(Schema.Literal("disable")), + permissions: Schema.optionalKey( + Schema.StructWithRest( + Schema.Struct({ + disableBypassPermissionsMode: Schema.optionalKey(Schema.Literal("disable")), + disableAutoMode: Schema.optionalKey(Schema.Literal("disable")), + }), + [Schema.Record(Schema.String, Schema.Unknown)], + ), + ), + }), + [Schema.Record(Schema.String, Schema.Unknown)], +); +const decodeClaudeBypassSettings = Schema.decodeUnknownEffect( + fromLenientJson(ClaudeBypassSettings), +); + +const ClaudePromptCacheTtl = Schema.Literals(["5m", "1h"]); +const decodeClaudePromptCacheTtl = Schema.decodeUnknownOption(ClaudePromptCacheTtl); +const decodeClaudeSubagentCacheSettings = Schema.decodeUnknownEffect( + fromLenientJson( + Schema.StructWithRest( + Schema.Struct({ subagentPromptCacheTtl: Schema.optionalKey(ClaudePromptCacheTtl) }), + [Schema.Record(Schema.String, Schema.Unknown)], + ), + ), +); +const decodeClaudeEnvSettings = Schema.decodeUnknownEffect( + fromLenientJson( + Schema.StructWithRest( + Schema.Struct({ env: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)) }), + [Schema.Record(Schema.String, Schema.Unknown)], + ), + ), +); + +function claudeBypassAvailability( + settings: typeof ClaudeBypassSettings.Type, +): ClaudeBypassAvailability { + return { + bypassDisabled: settings.permissions?.disableBypassPermissionsMode === "disable", + autoDisabled: + settings.disableAutoMode === "disable" || settings.permissions?.disableAutoMode === "disable", + }; } function requiresClaudeApproval(context: ActiveClaudeTurnContext): boolean { - return shouldInstallClaudePermissionCallback( - claudeRuntimeQueryPolicyForRuntimePolicy(context.input.runtimePolicy), - ); + // CLI-forwarded requests need a person's decision even under bypass (ask rules, + // safety checks, or settings fallback). Do not wait for queued init/status updates. + const policy = context.queryPolicy; + return policy.installPermissionCallback || policy.permissionMode === "bypassPermissions"; } function claudeRuntimeQueryPolicyKey(policy: ClaudeRuntimeQueryPolicy): string { @@ -1867,9 +2235,7 @@ function claudeRuntimeQueryPolicyKey(policy: ClaudeRuntimeQueryPolicy): string { }); } -// Live-query reuse must key on the effective allowlist (including the -// MCP-derived pre-approvals), not just the runtime policy: policies that -// share a policy key can still differ in MCP pre-approvals. +// Live-query reuse must include MCP pre-approvals, which can differ for the same policy key. export function claudeEffectiveQueryPolicyKey( queryPolicy: ClaudeRuntimeQueryPolicy, mcpOverrides: { @@ -1931,7 +2297,7 @@ const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record< write: { itemType: "file_change", requestKind: "file-change" }, }; -export function classifyClaudeNativeTool(toolName: string): ClaudeToolClassification { +function classifyClaudeNativeTool(toolName: string): ClaudeToolClassification { const normalizedName = normalizedClaudeToolName(toolName); const known = CLAUDE_KNOWN_TOOL_CLASSIFICATIONS[normalizedName]; return known === undefined @@ -2026,13 +2392,21 @@ function commandInputFromClaudeTool(toolName: string, input: ClaudeNativeToolInp ); } -// Subagents project through the normal subagent lifecycle and must not be double-counted when -// background_tasks_changed includes them. +// background_tasks_changed can include subagents already counted by their lifecycle. const CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS: ReadonlyMap< string, Exclude > = new Map([["local_bash", "command"]]); +// Claude Code 2.1.292 defers its goal Stop hook for these subagent types. +// local_bash tasks defer it through the opaque-task roster. +const CLAUDE_GOAL_DEFERRING_TASK_TYPES: ReadonlySet = new Set([ + "local_agent", + "remote_agent", + "in_process_teammate", + "local_workflow", +]); + function isClaudeOpaqueBackgroundTaskType(taskType: string | null | undefined): boolean { return typeof taskType === "string" && CLAUDE_OPAQUE_BACKGROUND_TASK_KINDS.has(taskType); } @@ -2040,8 +2414,7 @@ function isClaudeOpaqueBackgroundTaskType(taskType: string | null | undefined): function claudePendingBackgroundTask(input: { readonly taskId: string; readonly taskType: string | null; - // Claude runs a Monitor as a local_bash task, so only the Monitor tool call - // that started it tells it apart from a background Bash command. + // Only the launching Monitor tool distinguishes a local_bash Monitor from background Bash. readonly startedByMonitor: boolean; readonly description: string | undefined; // Undeclared SDK field: the subagent whose own background work this is. @@ -2083,10 +2456,21 @@ function isClaudeTurnStartMessage(message: SDKMessage): boolean { return message.type === "system" && message.subtype === "init"; } +function isClaudeRootTurnFrame(message: SDKMessage): boolean { + return ( + isClaudeTurnStartMessage(message) || + ((message.type === "user" || message.type === "assistant" || message.type === "stream_event") && + message.parent_tool_use_id == null) + ); +} + function claudePendingBackgroundTasksFromRoster( roster: ReadonlyMap, + awaitedTaskIds: ReadonlySet, ): ReadonlyArray { - return Array.from(roster.values()); + return Array.from(roster.values(), (task) => + awaitedTaskIds.has(task.taskId) ? { ...task, awaited: true as const } : task, + ); } function parseClaudeBackgroundTaskEntry( @@ -2493,12 +2877,52 @@ function parentToolUseIdFromSdkMessage(message: SDKMessage): string | null { : null; } +const CLAUDE_NO_STANDING_GRANT_OPTIONS = [ + { decision: "decline", label: "Decline" }, + { decision: "accept", label: "Approve" }, +] satisfies ReadonlyArray; + +export function claudeApprovalPresentation(input: { + readonly permissionMode: PermissionMode; + readonly prompt: string; + readonly callbackOptions: Pick< + Parameters[2], + "decisionReason" | "matchedAskRule" | "suppressAlwaysAllowRule" + >; +}): { + readonly reason?: string; + readonly fullAccessOverride?: ProviderApprovalFullAccessOverride; + readonly options?: ReadonlyArray; +} { + // The reason can carry terminal escapes from the CLI's own prompt renderer. + const reason = NodeUtil.stripVTControlCharacters( + input.callbackOptions.decisionReason ?? "", + ).trim(); + // Bypass auto-allows everything it can, so any ask that still reaches the + // callback is one bypass refused. The SDK drops the CLI's decision_reason_type, + // leaving the matched ask rule as the only way to tell the two causes apart. + const fullAccessOverride: ProviderApprovalFullAccessOverride | undefined = + input.permissionMode !== "bypassPermissions" + ? undefined + : input.callbackOptions.matchedAskRule === undefined + ? "provider_check" + : "ask_rule"; + return { + ...(reason === "" || reason === input.prompt ? {} : { reason }), + ...(fullAccessOverride === undefined ? {} : { fullAccessOverride }), + ...(input.callbackOptions.suppressAlwaysAllowRule === true + ? { options: CLAUDE_NO_STANDING_GRANT_OPTIONS } + : {}), + }; +} + export function permissionResultFromDecision(input: { readonly toolName: string; readonly decision: ProviderApprovalDecision; readonly toolInput: Record; readonly toolUseID: string; readonly suggestions?: Parameters[2]["suggestions"]; + readonly feedback?: string; }): PermissionResult { if (input.decision === "accept" || input.decision === "acceptForSession") { return { @@ -2518,9 +2942,10 @@ export function permissionResultFromDecision(input: { return { behavior: "deny", message: - input.decision === "cancel" + input.feedback?.trim() || + (input.decision === "cancel" ? "User cancelled tool execution." - : "User declined tool execution.", + : "User declined tool execution."), toolUseID: input.toolUseID, decisionClassification: "user_reject", ...(input.decision === "cancel" ? { interrupt: true } : {}), @@ -2549,11 +2974,11 @@ function toSessionPermissionUpdates( } export const awaitClaudeApprovalDecision = Effect.fn("awaitClaudeApprovalDecision")(function* ( - decision: Deferred.Deferred, + decision: Deferred.Deferred, signal: AbortSignal, ) { - const cancellation = Effect.callback((resume) => { - const abort = () => resume(Effect.succeed("cancel")); + const cancellation = Effect.callback((resume) => { + const abort = () => resume(Effect.succeed({ decision: "cancel" })); signal.addEventListener("abort", abort, { once: true }); if (signal.aborted) { abort(); @@ -2576,10 +3001,7 @@ const awaitClaudeUserInputAnswers = Effect.fn("awaitClaudeUserInputAnswers")(fun return yield* Effect.raceFirst(Deferred.await(answers), cancellation); }); -/** - * "[ede_diagnostic] ..." entries are CLI-internal telemetry (the CLI hides them from its own UI - * too), so they must never become the error banner (#5557). - */ +/** Exclude CLI-internal "[ede_diagnostic] ..." telemetry from error banners. */ function resultUserFacingError(result: SDKResultMessage): string | undefined { const errors = "errors" in result && Array.isArray(result.errors) ? result.errors : []; if (result.subtype === "success" && !result.is_error) { @@ -2590,6 +3012,9 @@ function resultUserFacingError(result: SDKResultMessage): string | undefined { ); } +const CONTEXT_WINDOW_FULL_ERROR = + "Claude stopped: the prompt exceeds the model's context window. Run /compact or start a new thread."; + function terminalResultError( reason: SDKResultMessage["terminal_reason"], failureHint?: string, @@ -2608,11 +3033,12 @@ function terminalResultError( case "turn_setup_failed": return "Claude could not start the turn."; case "blocking_limit": - return "Claude stopped: a usage limit blocked the request."; + // blocking_limit also means context exhaustion; only rate-limit evidence sets the hint. + return failureHint ?? CONTEXT_WINDOW_FULL_ERROR; case "rapid_refill_breaker": return "Claude stopped: the context refilled too quickly after compaction."; case "prompt_too_long": - return "Claude stopped: the prompt exceeds the model's context window."; + return CONTEXT_WINDOW_FULL_ERROR; case "image_error": return "Claude stopped: an image in the conversation could not be processed."; case "model_error": @@ -2633,8 +3059,7 @@ function terminalStatusFromResult( OrchestrationV2ProviderTurn["status"], "completed" | "interrupted" | "failed" | "cancelled" > { - // The CLI can label an abort as success with is_error=false. Its explicit - // terminal reason takes precedence over that envelope. + // Explicit abort reasons override success envelopes with is_error=false. if ( message.terminal_reason === "aborted_tools" || message.terminal_reason === "aborted_streaming" @@ -2642,8 +3067,7 @@ function terminalStatusFromResult( return "interrupted"; } if (message.subtype === "success") { - // The SDK reports API-level failures (401 auth, 529 overloaded, …) as - // subtype "success" with is_error set; the turn produced no real work. + // The SDK can report API failures as subtype "success" with is_error set. return isOverloadedResult(message) || message.api_error_status === 429 || terminalResultError(message.terminal_reason, failureHint) !== undefined || @@ -2720,9 +3144,7 @@ function claudePromptLifecycle( return typeof uuid === "string" && typeof state === "string" ? { uuid, state } : null; } -// An echo names the prompts its turn consumed. Without one, only a process -// known to echo proves the turn foreign by its non-human origin; on a CLI that -// never echoes, that result can be the prompt turn's only result. +// Without an echo, non-human origin proves a foreign turn only on CLIs known to echo prompts. function isClaudeResultForOtherTurn(input: { readonly message: SDKResultMessage; readonly promptUuid: string; @@ -2746,6 +3168,30 @@ function isClaudeTaskNotificationOriginResult(message: SDKMessage): message is S return message.type === "result" && message.origin?.kind === "task-notification"; } +// The CLI throttles unchanged rate_limit_event frames, but repeats this +// undeclared payload on each blocked assistant response. +const isClaudeBlockedAssistantRateLimit = Schema.is( + Schema.Struct({ + api_error_params: Schema.Struct({ + rate_limit_info: Schema.Struct({ + status: Schema.Literal("rejected"), + rateLimitType: Schema.optionalKey(Schema.Unknown), + resetsAt: Schema.optionalKey(Schema.Unknown), + overageStatus: Schema.optionalKey(Schema.String), + isUsingOverage: Schema.optionalKey(Schema.Boolean), + overageInUse: Schema.optionalKey(Schema.Boolean), + }), + }), + }), +); + +function claudeUsageLimitResetAt(resetsAt: unknown): string | null { + const resetMs = typeof resetsAt === "number" ? resetsAt * 1000 : NaN; + return Number.isFinite(resetMs) && resetMs > 0 && resetMs < 8.64e15 + ? DateTime.formatIso(DateTime.makeUnsafe(resetMs)) + : null; +} + function providerFailureFromResult( message: SDKResultMessage, completedAt: DateTime.Utc, @@ -2779,17 +3225,21 @@ function providerFailureFromResult( } } const failureClass = - message.terminal_reason === "blocking_limit" || - (message.subtype === "success" && message.api_error_status === 429) || - usageLimited + (message.subtype === "success" && message.api_error_status === 429) || usageLimited ? "usage_limit" : "provider_error"; const listedError = resultUserFacingError(message); + const apiErrorMessage = + message.subtype === "success" && + message.terminal_reason === "api_error" && + message.result.trim().startsWith("API Error:") + ? makeProviderFailure({ message: message.result }).message.slice(0, 500) + : undefined; const structuredError = isOverloadedResult(message) ? "Claude API is overloaded (529). Try again shortly." : message.subtype === "success" && message.api_error_status === 429 ? "Claude API rate limit reached. Try again later." - : terminalResultError(message.terminal_reason, failureHint); + : terminalResultError(message.terminal_reason, failureHint ?? apiErrorMessage); if (message.subtype !== "success") { return makeProviderFailure({ message: listedError ?? structuredError ?? message.errors.join("\n"), @@ -2960,6 +3410,7 @@ function formatClaudeUsageLimitWait(waitMs: number): string { } interface ActiveClaudeTurnContext { + readonly queryPolicy: ClaudeRuntimeQueryPolicy; readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; readonly nativeThreadId: string; readonly nativeTurnId: string; @@ -2972,6 +3423,8 @@ interface ActiveClaudeTurnContext { fallbackText: string; fallbackNativeItemId: string; emittedNativeItemIds: Set; + // The CLI repeats a notice that ends a prompt as the turn's result text. + noticeTexts: Set; }; readonly reasoning: { messageId: string | null; @@ -2990,18 +3443,30 @@ interface ActiveClaudeTurnContext { { readonly startedAt: DateTime.Utc; readonly ordinal: number; text: string } >; }; + // Snapshots repeat message_start input, sometimes as zeros, so only fill gaps in streamed usage. + // Compaction clears usage without forgetting the root request. + // `requestedAt` starts the request's prompt cache lifetime. + streamUsage: { + readonly messageId: string; + requestedAt?: DateTime.Utc; + usage: ClaudeMessageUsage | null; + } | null; readonly toolCalls: Map; + // A successful status can precede the boundary that supplies its token counts. + compaction: Extract | null; readonly ignoredTaskIds: Set; readonly announcedUsageLimits: Set; authenticationFailureMessage: string | undefined; readonly rejectedRateLimitTypes: Set; readonly rateLimitResetTimes: Map; - latestAssistantRateLimited: boolean; + latestAssistantRateLimit: { + readonly type: string | null; + readonly resetAt: string | null; + } | null; // Set while this turn's latest compaction status reports a failure, with // Claude's error text when it sent one. compactionFailure: { readonly message: string | undefined } | null; - // Usage of the results that steers ended, oldest first. The final result's - // usage covers only its own segment, so the turn bills these as well. + // Steers end segments whose usage is excluded from the final result; bill them too, oldest first. readonly steeredSegmentUsage: Array; readonly subagentsByTaskId: Map; readonly subagentsByToolUseId: Map; @@ -3009,6 +3474,7 @@ interface ActiveClaudeTurnContext { readonly promptUuid: string | null; promptEcho: "pending" | "confirmed"; promptStarted: boolean; + nativeWakeStarted: boolean; gatedFramesBeforeEcho: number; readonly heldRootFrames: Array; } @@ -3022,6 +3488,7 @@ interface ActiveClaudeProviderRetry { interface ActiveClaudeSubagent { task: OrchestrationV2Subagent; + readonly nativeTaskType: string | undefined; readonly confirmedOutcome: ProviderAdapter.ProviderAdapterV2SubagentOutcome | undefined; readonly rootNodeId: OrchestrationV2ExecutionNode["id"]; readonly childThreadId: ThreadId; @@ -3038,17 +3505,18 @@ interface ActiveClaudeSubagent { } interface ClaudeLiveQueryContext { + readonly queryPolicy: ClaudeRuntimeQueryPolicy; readonly nativeThreadId: string; readonly query: ClaudeAgentSdkQuerySession; readonly queryPolicyKey: string; selection: CompiledClaudeModelSelection; readonly closed: Deferred.Deferred; lastTurn: ActiveClaudeTurnContext | null; - // Whether this CLI process echoes a prompt's uuid on the first frame of the turn answering it - // ("early") or only on its result. "acknowledged": the CLI confirmed it took a prompt's uuid - // before any echo, so it echoes, but a resume's own turns can still run ahead of that prompt. + // "early" echoes on the first frame; "acknowledged" confirms uuid acceptance, but resume turns can still precede the prompt. promptEchoMode: "unknown" | "acknowledged" | "early" | "result_only"; - readonly openedPermissionMode: PermissionMode; + // The CLI may fall back from the requested mode on its first init frame. + openedPermissionMode: PermissionMode; + receivedInit: boolean; permissionMode: PermissionMode; stopping: boolean; readonly subagentsFromEarlierProcesses: ReadonlySet; @@ -3068,7 +3536,6 @@ interface ActiveClaudeToolCall { readonly presentation?: ClaudeToolPresentation; } -/** Where a subagent's conversation items land: its child thread and root node. */ interface ClaudeSubagentProjectionTarget { readonly childThreadId: ThreadId; readonly childRootNodeId: OrchestrationV2ExecutionNode["id"]; @@ -3076,13 +3543,8 @@ interface ClaudeSubagentProjectionTarget { readonly toolCalls: Map; } -/** - * Whether a transcript line ends the assistant's turn. Claude Code writes each - * block of a message as its own line, `stop_reason: null` on all but the last, - * and text before a tool call (`tool_use`) is not the reply. A line without the - * field (no CLI writes one) keeps the turn open: waiting costs at most the flush - * window, while ending the turn early can lose the reply. - */ +/** Claude writes blocks separately with stop_reason null until the last. + * Missing stop_reason keeps the turn open; pre-tool text is not the reply. */ function isClaudeTranscriptTurnEnd(entry: unknown): boolean { if (field(entry, "type") !== "assistant") return false; const stopReason = field(field(entry, "message"), "stop_reason"); @@ -3176,12 +3638,17 @@ function rememberClaudeSubagentLaunch( } } +type ClaudeApprovalResponse = { + readonly decision: ProviderApprovalDecision; + readonly feedback?: string; +}; + type PendingClaudeRuntimeRequest = | { readonly type: "approval"; readonly requestId: OrchestrationV2RuntimeRequest["id"]; readonly requestKind: ProviderRequestKind; - readonly decision: Deferred.Deferred; + readonly decision: Deferred.Deferred; } | { readonly type: "user_input"; @@ -3214,11 +3681,15 @@ export function claudeUserInputQuestions( const optionRecord = option as Record; const label = typeof optionRecord.label === "string" ? optionRecord.label.trim() : ""; if (label.length === 0) return []; + const description = + typeof optionRecord.description === "string" ? optionRecord.description.trim() : ""; return [ { label, - description: - typeof optionRecord.description === "string" ? optionRecord.description.trim() : "", + description: description || label, + ...(typeof optionRecord.preview === "string" + ? { preview: optionRecord.preview } + : {}), }, ]; }) @@ -3250,7 +3721,7 @@ export function claudeSdkUserInputAnswers( ); } -export function claudeTodoSteps(input: unknown): ReadonlyArray { +function claudeTodoSteps(input: unknown): ReadonlyArray { const value = typeof input === "object" && input !== null && Reflect.get(input, "type") === "record" ? Reflect.get(input, "value") @@ -3327,12 +3798,20 @@ function applyClaudeTaskTool( } if (toolName === "TaskCreate") { const created = claudeTaskField(result, "task"); - const id = claudeTaskString(created, "id"); - const text = claudeTaskString(created, "subject") ?? claudeTaskString(input, "subject"); + const fromText = claudeCreatedTaskFromText(result); + const id = claudeTaskString(created, "id") ?? fromText?.id; + const text = + claudeTaskString(created, "subject") ?? + fromText?.subject ?? + claudeTaskString(input, "subject"); if (id === undefined || text === undefined) return undefined; return new Map(tasks).set(id, { text, status: "pending" }); } - if (toolName !== "TaskUpdate" || claudeTaskField(result, "success") === false) { + if ( + toolName !== "TaskUpdate" || + claudeTaskField(result, "success") === false || + (typeof result === "string" && !result.startsWith("Updated task #")) + ) { return undefined; } const id = claudeTaskString(input, "taskId") ?? claudeTaskString(result, "taskId"); @@ -3350,11 +3829,67 @@ function applyClaudeTaskTool( return new Map(tasks).set(id, { text, status }); } +// Subagent results carry no structured `tool_use_result`, only the text +// "Task #3 created successfully: ". +function claudeCreatedTaskFromText( + result: unknown, +): { readonly id: string; readonly subject: string } | undefined { + const match = + typeof result === "string" ? /^Task #(\S+) created successfully: (.+)$/s.exec(result) : null; + return match === null ? undefined : { id: match[1]!, subject: match[2]!.trim() }; +} + +const CLAUDE_TASK_TOOL_NAMES = new Set(["TaskCreate", "TaskUpdate", "TaskList"]); +const decodeClaudeTaskFile = Schema.decodeUnknownOption( + Schema.fromJsonString( + Schema.Struct({ + id: TrimmedNonEmptyString, + subject: TrimmedNonEmptyString, + status: Schema.Literals(["pending", "in_progress", "completed"]), + metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), + }), + ), +); + +const readClaudeTaskList = Effect.fnUntraced( + function* (input: { + readonly environment: NodeJS.ProcessEnv; + readonly cwd: string | null | undefined; + readonly nativeThreadId: string; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDirOverride = input.environment.CLAUDE_CONFIG_DIR?.trim(); + const configDir = configDirOverride + ? path.resolve(input.cwd ?? ".", configDirOverride) + : yield* resolveClaudeHomePath({ homePath: "" }); + const listId = input.environment.CLAUDE_CODE_TASK_LIST_ID?.trim() || input.nativeThreadId; + const directory = path.join(configDir, "tasks", listId.replace(/[^a-zA-Z0-9_-]/g, "-")); + const tasks = new Map>(); + const names = (yield* fileSystem.readDirectory(directory)) + .filter((name) => /^\d+\.json$/.test(name)) + .toSorted((left, right) => Number.parseInt(left, 10) - Number.parseInt(right, 10)); + for (const name of names) { + const contents = yield* fileSystem + .readFileString(path.join(directory, name)) + .pipe(Effect.orElseSucceed(() => "")); + const task = Option.getOrUndefined(decodeClaudeTaskFile(contents)); + if (task === undefined || task.metadata?._internal) continue; + tasks.set(task.id, { + text: task.subject, + status: task.status === "in_progress" ? "running" : task.status, + }); + } + return tasks; + }, + Effect.orElseSucceed((): ClaudeTaskList | undefined => undefined), +); + function claudeTaskSteps(tasks: ClaudeTaskList): ReadonlyArray { return [...tasks].map(([id, task]) => ({ id: `task-${id}`, ...task })); } -export function claudeProposedPlan(input: unknown): string | null { +function claudeProposedPlan(input: unknown): string | null { const value = typeof input === "object" && input !== null && Reflect.get(input, "type") === "record" ? Reflect.get(input, "value") @@ -3386,6 +3921,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( adapterOptions: ClaudeAdapterV2Options, ) { const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService); const { attachmentsDir, fileSystem, path, crypto, idAllocator, queryRunner } = adapterOptions; const subagentModelCatalog = scopeClaudeModelCatalog( BUNDLED_CLAUDE_MODEL_CATALOG, @@ -3394,8 +3930,137 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const continuationRequests = adapterOptions.continuationRequests ?? { offer: () => Effect.void, }; + const homePath = yield* resolveClaudeHomePath( + adapterOptions.settings, + adapterOptions.environment, + ).pipe(Effect.provideService(Path.Path, path)); + const hostEnvironment = yield* HostProcess.Environment; + const customHome = + adapterOptions.settings.homePath.trim().length > 0 || + adapterOptions.environment.CLAUDE_CONFIG_DIR !== hostEnvironment.CLAUDE_CONFIG_DIR; + const announcedBypassDowngrades = new Set(); + const readBypassSettings = (filePath: string) => + fileSystem.readFileString(filePath).pipe( + Effect.flatMap(decodeClaudeBypassSettings), + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed({})), + ); + const resolveBypassAvailability = Effect.fn("ClaudeAdapterV2.resolveBypassAvailability")( + function* (cwd: string | null) { + // resolveSettings does not initialize remote-cache eligibility in the SDK host. + // Keep the payload intact so the SDK also honors managedSourcesBehavior. + const remote = yield* readBypassSettings(path.join(homePath, "remote-settings.json")); + const home = customHome + ? yield* readBypassSettings(path.join(homePath, "settings.json")) + : {}; + const resolved = yield* Effect.tryPromise(() => + resolveClaudeSettings({ + ...(cwd === null ? {} : { cwd }), + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"], + serverManagedSettings: remote, + }), + ); + const cascade = claudeBypassAvailability(resolved.effective); + const user = claudeBypassAvailability(home); + const cached = claudeBypassAvailability(remote); + return { + bypassDisabled: cascade.bypassDisabled || user.bypassDisabled || cached.bypassDisabled, + autoDisabled: cascade.autoDisabled || user.autoDisabled || cached.autoDisabled, + }; + }, + ); + + // Claude Code's own subagent TTL setting, in its precedence order. Unset or unreadable means + // Anthropic's default applies. + const resolveSubagentPromptCacheTtl = Effect.fn("ClaudeAdapterV2.resolveSubagentPromptCacheTtl")( + function* (cwd: string | null) { + const fromEnvironment = decodeClaudePromptCacheTtl( + adapterOptions.environment.CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL, + ); + if (Option.isSome(fromEnvironment)) return fromEnvironment.value; + const resolved = yield* Effect.tryPromise(() => + resolveClaudeSettings({ + ...(cwd === null ? {} : { cwd }), + settingSources: customHome ? ["project", "local"] : ["user", "project", "local"], + }), + ).pipe(Effect.orElseSucceed(() => undefined)); + const home = customHome + ? yield* fileSystem.readFileString(path.join(homePath, "settings.json")).pipe( + Effect.flatMap(decodeClaudeSubagentCacheSettings), + Effect.orElseSucceed(() => ({ subagentPromptCacheTtl: undefined })), + ) + : undefined; + return resolved?.effective.subagentPromptCacheTtl ?? home?.subagentPromptCacheTtl; + }, + ); + + const readToolSearchSetting = (filePath: string) => + fileSystem.readFileString(filePath).pipe( + Effect.flatMap(decodeClaudeEnvSettings), + Effect.map((settings) => { + const value = settings.env?.ENABLE_TOOL_SEARCH; + return typeof value === "string" ? value : undefined; + }), + Effect.orElseSucceed(() => undefined), + ); + // A worktree's .git file points at
/.git/worktrees/, whose commondir leads back to + //
/.git. A bare repository has no main checkout, so its worktree keeps its own file. + const mainCheckoutRoot = (checkout: string) => + fileSystem.readFileString(path.join(checkout, ".git")).pipe( + Effect.flatMap((pointer) => { + const gitDir = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim(); + if (gitDir === undefined) return Effect.succeed(checkout); + const worktreeGitDir = path.resolve(checkout, gitDir); + return fileSystem.readFileString(path.join(worktreeGitDir, "commondir")).pipe( + Effect.map((commonDir) => { + const common = path.resolve(worktreeGitDir, commonDir.trim()); + return path.basename(common) === ".git" ? path.dirname(common) : checkout; + }), + ); + }), + Effect.orElseSucceed(() => checkout), + ); + // Claude Code keeps .claude/settings.local.json at the repository root, or in cwd outside a + // repository, on Windows, or when the root is home. Its owner check is skipped: missing it only + // leaves tool search on, Claude Code's default. + const localSettingsDirectory = Effect.fn("ClaudeAdapterV2.localSettingsDirectory")(function* ( + cwd: string, + ) { + if ((yield* HostProcess.Platform) === "win32") return cwd; + for (let directory = cwd; ; directory = path.dirname(directory)) { + const isCheckout = yield* fileSystem + .exists(path.join(directory, ".git")) + .pipe(Effect.orElseSucceed(() => false)); + if (isCheckout) { + const root = yield* mainCheckoutRoot(directory); + return root === (yield* HostProcess.HomeDirectory) ? cwd : root; + } + if (path.dirname(directory) === directory) return cwd; + } + }); + // Settings env beats the process env, local over project over user, and a local file an older + // Claude Code left in cwd applies under the root one. resolveSettings reads local from cwd only. + const resolveToolSearchOverride = Effect.fn("ClaudeAdapterV2.resolveToolSearchOverride")( + function* (cwd: string | null) { + const localDirectory = cwd === null ? null : yield* localSettingsDirectory(cwd); + const settingsFiles = [ + ...(cwd === null || localDirectory === null + ? [] + : [ + path.join(localDirectory, ".claude", "settings.local.json"), + ...(localDirectory === cwd ? [] : [path.join(cwd, ".claude", "settings.local.json")]), + path.join(cwd, ".claude", "settings.json"), + ]), + path.join(homePath, "settings.json"), + ]; + for (const settingsFile of settingsFiles) { + const value = yield* readToolSearchSetting(settingsFile); + if (value !== undefined) return claudeToolSearchOverride(value); + } + return claudeToolSearchOverride(adapterOptions.environment.ENABLE_TOOL_SEARCH); + }, + ); - const userInvocableSkillNames = (cwd: string | null) => + const userInvocableSkills = (cwd: string | null) => discoverClaudeSkills( adapterOptions.settings, cwd ?? undefined, @@ -3403,10 +4068,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ).pipe( Effect.map( (skills) => - new Set( + new Map( skills .filter((skill) => skill.enabled && skill.userInvocable !== false) - .map((skill) => skill.name), + .map((skill) => [skill.name, skill]), ), ), Effect.provideService(FileSystem.FileSystem, fileSystem), @@ -3431,7 +4096,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const events = yield* Queue.unbounded(); const activeTurn = yield* Ref.make(null); - // Foreground Bash calls whose output file is being tailed, by tool_use_id. const taskOutputTails = new Map< string, { readonly fiber: Fiber.Fiber; readonly stop: Deferred.Deferred } @@ -3449,8 +4113,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); }); const sdkMessageLock = yield* Semaphore.make(1); - // Survives turn settle: members mostly finish after the launching - // turn has ended, and each transition must be emitted exactly once. + // Members can finish after the launching turn; retain state to emit each transition once. const workflowMemberStates = yield* Ref.make( new Map< string, @@ -3459,14 +4122,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly attempt: number; readonly transcriptReadAttempts: number; readonly finalTranscriptRead: boolean; - // Where the next read of the member's transcript starts; every - // line before it is already projected into the member's thread. readonly agentId: string | undefined; readonly transcriptCursor: WorkflowAgentTranscriptCursor; readonly nextItemOrdinal: number; readonly toolCalls: Map; readonly textShown: boolean; - // The transcript reached the end of the member's last turn. readonly turnEnded: boolean; readonly resultShown: boolean; readonly result: string | undefined; @@ -3482,10 +4142,39 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const interruptedTurns = yield* Ref.make(new Set()); const steeredTurns = yield* Ref.make(new Set()); const queryContext = yield* Ref.make(null); + // A worktree handoff changes the project settings even within one session. + let bypassCache: { cwd: string | null; availability: ClaudeBypassAvailability } | null = + null; + const queryPolicyForTurn = Effect.fnUntraced(function* ( + turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, + ) { + if ( + permissionModeForClaudeRuntimePolicy(turnInput.runtimePolicy) !== "bypassPermissions" + ) { + return claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy); + } + const cwd = turnInput.runtimePolicy.cwd; + if (bypassCache === null || bypassCache.cwd !== cwd) { + const resolved = yield* resolveBypassAvailability(cwd).pipe(Effect.option); + if (Option.isNone(resolved)) { + return claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy, { + bypassDisabled: true, + autoDisabled: false, + }); + } + bypassCache = { cwd, availability: resolved.value }; + } + return claudeRuntimeQueryPolicyForRuntimePolicy( + turnInput.runtimePolicy, + bypassCache.availability, + ); + }); const openedNativeThreads = yield* Ref.make(new Set()); const latestPlanByKind = yield* Ref.make(new Map()); // Claude 5 task tools edit one list per native session, across turns. - const taskListsByNativeThread = yield* Ref.make(new Map()); + const taskListsByNativeThread = yield* Ref.make( + new Map(), + ); const planIdsByNativeItem = yield* Ref.make( new Map(), ); @@ -3495,9 +4184,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const pendingRuntimeRequests = yield* Ref.make( new Map(), ); - // Claude can settle a turn while a local_bash background task keeps running; the CLI - // later re-invokes the model (a "wake turn") on the same query stream with no active - // provider turn. + // Background local_bash tasks can trigger wake turns on the query stream with no active provider turn. const lastTurnRouteByNativeThread = yield* Ref.make( new Map< string, @@ -3507,6 +4194,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const pendingBackgroundTasksByNativeThread = yield* Ref.make( new Map>(), ); + // Survives roster REPLACE levels, which rebuild every entry without the agent's mark. + const awaitedBackgroundTasksByNativeThread = yield* Ref.make( + new Map>(), + ); // Wake eligibility is separate from the Waiting roster. It survives empty // background_tasks_changed levels (SDK: empty level can precede task_notification) and // is consumed when the first idle notification is buffered/offered so duplicates cannot @@ -3522,15 +4213,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); const goalsByNativeThread = new Map(); const goalCheckedTurns = new Set(); - // Subagent registry that survives turn settle: a background subagent - // (Agent with run_in_background) can complete after the root turn - // ended, and its task_notification must both count as wake evidence - // and hydrate the original subagent node instead of being dropped. + // Background subagents can finish after root settlement; retain their registry for wake evidence and hydration. const sessionSubagentsByTaskId = yield* Ref.make(new Map()); const sessionSubagentTaskIdsByToolUseId = yield* Ref.make(new Map()); - // Requests that move a running subagent to the background before a - // steer, by the tool call that started its run. Claude may never - // answer one, so a later steer waits on it rather than asking again. + // Claude may never answer a background move; later steers must wait on the same request. const backgroundMovesByToolUseId = new Map>(); const subagentToolCalls = new Map(); const pendingSubagentLaunchesByToolUseId = new Map(); @@ -3539,12 +4225,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( string, Deferred.Deferred >(); - // An idle outcome stays buffered for the parent's wake, but must not - // settle the child again after that child resumes. + // Buffered idle outcomes must not settle a resumed child again. const appliedSubagentOutcomes = new WeakSet(); - // Subagent frames can precede the task_started that registers their - // subagent (the same race rememberPendingClaudeSubagentLaunch covers). - // They wait here and replay once task_started registers the owner. + // Subagent frames can precede the task_started that registers their owner. const pendingSubagentFramesByToolUseId = yield* Ref.make( new Map>(), ); @@ -3554,10 +4237,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( { readonly messages: ReadonlyArray; readonly detail: string | null } >(), ); - // Claude's wake result carries no task id, and its wake can run after a prompt the user - // queued meanwhile, so reports survive one user turn and then expire: a notification - // Claude folded into its own turn cannot name a later wake. One Ref holds both, so a - // report cannot be stamped with a turn that has already been superseded. + // Wake results lack task ids and can follow queued prompts; retain reports for one user turn. + // Keep report stamps atomic with turn changes. const wakeReportsByNativeThread = yield* Ref.make<{ readonly userTurns: ReadonlyMap; readonly reports: ReadonlyMap< @@ -3566,8 +4247,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( >; }>({ userTurns: new Map(), reports: new Map() }); const backgroundedSubagentTaskIds = yield* Ref.make>(new Set()); - // Subagents another subagent started (spawn_depth above 1). Claude - // reports their end to the owning subagent, so it never wakes the root. + // Nested subagent completions notify their owner and never wake the root. const nestedSubagentTaskIds = yield* Ref.make>(new Set()); const isNestedSubagentTask = (taskId: string) => Ref.get(nestedSubagentTaskIds).pipe(Effect.map((ids) => ids.has(taskId))); @@ -3608,8 +4288,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const clearWakeReports = (nativeThreadId: string) => takeWakeReports(nativeThreadId).pipe(Effect.asVoid); - // An empty roster level can land before the task's notification, and - // the wake still needs to name the task. + // Empty roster levels can precede notifications; retain tasks for wake attribution. const lastKnownOpaqueTasks = yield* Ref.make( new Map(), ); @@ -3706,8 +4385,48 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); - // Claude emits retry progress but no recovered frame; the next - // assistant message is the first reliable evidence of recovery. + // Usage without input is a placeholder, not a context measurement. + const emitContextUsage = Effect.fnUntraced(function* ( + context: ActiveClaudeTurnContext, + usage: ClaudeMessageUsage, + requestStarted = false, + ) { + const now = yield* DateTime.now; + // Only message_start marks the request start; an assistant snapshot + // arrives after generation, so it leaves the cache expiry unknown. + if (requestStarted && context.streamUsage !== null) context.streamUsage.requestedAt = now; + const tokenUsage = claudeProviderTurnTokenUsage( + usage, + context.input.modelSelection, + DateTime.formatIso(now), + adapterOptions.settings.autoCompactWindow, + context.streamUsage?.requestedAt, + ); + if (tokenUsage.inputTokens <= 0) return; + yield* emitProviderEvent({ + type: "provider_turn.updated", + driver: CLAUDE_PROVIDER, + threadId: context.input.threadId, + providerTurn: { + id: context.providerTurnId, + providerThreadId: context.input.providerThread.id, + nodeId: context.input.rootNodeId, + runAttemptId: context.input.attemptId, + nativeTurnRef: { + driver: CLAUDE_PROVIDER, + nativeId: context.nativeTurnId, + strength: "strong", + }, + ordinal: context.providerTurnOrdinal, + status: "running", + startedAt: context.startedAt, + completedAt: null, + tokenUsage, + }, + }); + }); + + // Claude has no recovered frame; the next assistant message proves recovery. const completeProviderRetry = Effect.fn("ClaudeAdapterV2.completeProviderRetry")(function* ( context: ActiveClaudeTurnContext, updatedAt: DateTime.Utc, @@ -3744,8 +4463,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - const rememberProviderThread = (providerThread: OrchestrationV2ProviderThread) => - Effect.gen(function* () { + const rememberProviderThread = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (providerThread: OrchestrationV2ProviderThread) { const nativeThreadId = providerThread.nativeThreadRef?.nativeId; if (nativeThreadId === undefined || nativeThreadId === null) { return; @@ -3841,11 +4561,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.map((all) => taskIdSetForNativeThread(all, nativeThreadId).has(taskId)), ); - const isKnownOpaqueBackgroundTaskOnNativeThread = ( - nativeThreadId: string, - taskId: string, - ) => - Effect.gen(function* () { + const isKnownOpaqueBackgroundTaskOnNativeThread = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (nativeThreadId: string, taskId: string) { if (yield* hasPendingBackgroundTaskOnNativeThread(nativeThreadId, taskId)) { return true; } @@ -3868,11 +4586,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( taskIds, ); - const consumeWakeEligibilityForBufferedNotification = ( - nativeThreadId: string, - taskId: string, - ) => - Effect.gen(function* () { + const consumeWakeEligibilityForBufferedNotification = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (nativeThreadId: string, taskId: string) { yield* clearTaskIdFromNativeThreadSet( wakeEligibleBackgroundTasksByNativeThread, nativeThreadId, @@ -3901,12 +4617,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.get(pendingBackgroundTasksByNativeThread), input.nativeThreadId, ); + const awaitedTaskIds = taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + input.nativeThreadId, + ); const now = yield* DateTime.now; const providerThread: OrchestrationV2ProviderThread = { ...input.providerThread, providerSessionId: session.id, ...(input.status === undefined ? {} : { status: input.status }), - pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster), + pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster, awaitedTaskIds), ...(goalsByNativeThread.has(input.nativeThreadId) ? { goal: goalsByNativeThread.get(input.nativeThreadId) ?? null } : {}), @@ -3963,11 +4683,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return updated; }); - const replacePendingBackgroundTasks = ( - nativeThreadId: string, - tasks: ReadonlyArray, - ) => - Effect.gen(function* () { + const replacePendingBackgroundTasks = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* ( + nativeThreadId: string, + tasks: ReadonlyArray, + ) { yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => { const updated = new Map(current); if (tasks.length === 0) { @@ -3987,13 +4708,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( tasks.map((task) => task.taskId), ); } + const listed = new Set(tasks.map((task) => task.taskId)); + yield* Ref.update(awaitedBackgroundTasksByNativeThread, (current) => { + const awaited = current.get(nativeThreadId); + if (awaited === undefined) return current; + const kept = new Set([...awaited].filter((taskId) => listed.has(taskId))); + if (kept.size === awaited.size) return current; + const updated = new Map(current); + if (kept.size === 0) updated.delete(nativeThreadId); + else updated.set(nativeThreadId, kept); + return updated; + }); }); - const upsertPendingBackgroundTask = ( - nativeThreadId: string, - task: OrchestrationV2PendingBackgroundTask, - ) => - Effect.gen(function* () { + const upsertPendingBackgroundTask = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* ( + nativeThreadId: string, + task: OrchestrationV2PendingBackgroundTask, + ) { yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => { const roster = new Map(rosterForNativeThread(current, nativeThreadId)); roster.set(task.taskId, task); @@ -4018,23 +4751,34 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( updated.set(nativeThreadId, nextRoster); } return [true, updated] as const; - }); - - const clearPendingBackgroundTasksForNativeThread = (nativeThreadId: string) => - Effect.gen(function* () { - yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => { - if (!current.has(nativeThreadId)) { - return current; - } - const updated = new Map(current); + }).pipe( + Effect.tap(() => + clearTaskIdFromNativeThreadSet( + awaitedBackgroundTasksByNativeThread, + nativeThreadId, + taskId, + ), + ), + ); + + const clearPendingBackgroundTasksForNativeThread = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (nativeThreadId: string) { + yield* Ref.update(pendingBackgroundTasksByNativeThread, (current) => { + if (!current.has(nativeThreadId)) { + return current; + } + const updated = new Map(current); updated.delete(nativeThreadId); return updated; }); + yield* clearNativeThreadTaskIdSet(awaitedBackgroundTasksByNativeThread, nativeThreadId); yield* endClaudeMonitorTasks((_taskId, task) => task.nativeThreadId === nativeThreadId); }); - const clearWakeStateForNativeThread = (nativeThreadId: string) => - Effect.gen(function* () { + const clearWakeStateForNativeThread = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (nativeThreadId: string) { yield* clearWakeReports(nativeThreadId); yield* Ref.update(wakeBuffers, (current) => { if (!current.has(nativeThreadId)) { @@ -4054,8 +4798,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - // Process-scoped level: SDK emits nothing at CLI start, so both the Waiting roster and - // wake eligibility reset when a live query opens or is replaced for this native thread. + // The SDK emits no initial roster; reset roster and wake eligibility when opening a live query. const resetBackgroundTaskStateForNativeThreadProcess = Effect.fnUntraced(function* ( nativeThreadId: string, options?: { @@ -4173,7 +4916,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const buildToolCallArtifacts = (input: { - // Only a call in a run (runId set) needs its provider turn. readonly context: ActiveClaudeTurnContext | null; readonly nativeItemId: string; readonly toolName: string; @@ -4370,9 +5112,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - // The resume's task_started names only the SendMessage call, while the resumed run's - // frames carry the launch call as parent_tool_use_id, which only the CLI's session - // storage still records. + // Resume frames reference the launch call, but task_started names SendMessage; recover the mapping from CLI storage. const recoverResumedClaudeSubagent = Effect.fnUntraced(function* (resume: { readonly context: ActiveClaudeTurnContext; readonly nativeThreadId: string; @@ -4409,6 +5149,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const ids = claudeSubagentIds(resume.context, resume.taskId); const now = yield* DateTime.now; const subagent: ActiveClaudeSubagent = { + nativeTaskType: undefined, confirmedOutcome: undefined, childThread: null, task: { @@ -4558,12 +5299,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( : ((restarted ? null : previous?.startedAt) ?? (status === "running" ? now : null)); const completedAt = settled - ? ((restarted ? null : previous?.completedAt) ?? now) + ? member.completedAt !== undefined + ? DateTime.makeUnsafe(member.completedAt) + : ((restarted ? null : previous?.completedAt) ?? now) : null; const changed = restarted || previous?.status !== status || !Equal.equals(previous?.startedAt, startedAt) || + !Equal.equals(previous?.completedAt, completedAt) || previous?.result !== member.result || previous?.label !== member.label || previous?.prompt !== prompt || @@ -4576,8 +5320,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (input.coordinator.task.status === "running" ? (restarted ? 0 : (previous?.transcriptReadAttempts ?? 0)) < 3 : restarted || previous?.finalTranscriptRead !== true); - // The CLI forwards nothing a member says, so every frame while it - // runs reads what its transcript gained since the last one. const readLiveTranscript = status === "running" && transcriptDir !== undefined && agentId !== undefined; if (!changed && !readTranscript && !readLiveTranscript) continue; @@ -4712,8 +5454,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( toolCalls.clear(); }); if (restarted) yield* endOpenToolCalls(); - // A retry may rewrite the transcript in place, past the old cursor; - // re-reading from 0 re-emits only items already shown. + // Retries can rewrite transcripts past the cursor; rereading from zero repeats only already shown items. let transcriptCursor = previous === undefined || restarted || previous.agentId !== agentId ? initialWorkflowAgentTranscriptCursor @@ -4723,17 +5464,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( let turnEnded = !restarted && previous?.turnEnded === true; let transcriptRead = false; let lastReadAt = now; - // Text before a tool call is not the reply, so wait for the turn's end. + // Pre-tool text is not the reply; wait for turn end. const awaitingReply = () => settled && transcriptRead && !turnEnded && !resultShown; - // Milliseconds until a read started at `at` sees every line the - // member wrote before it settled. const flushWindowLeft = (at: DateTime.Utc) => completedAt === null ? 0 : WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS - (DateTime.toEpochMillis(at) - DateTime.toEpochMillis(completedAt)); - // Each read is capped, so keep reading until the transcript has no - // more complete lines; a settled member's answer may be past the cap. + // Drain capped reads; settled replies can lie beyond the cap. let transcriptDrained = true; if ( (readTranscript || readLiveTranscript) && @@ -4754,7 +5492,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), }), }).pipe(Effect.option); - // False once the coordinator was replaced mid-read. const drain = Effect.fnUntraced(function* () { lastReadAt = yield* DateTime.now; transcriptDrained = false; @@ -4768,7 +5505,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( transcriptCursor = read.value.cursor; for (const line of read.value.lines) { if (yield* projectSubagentTranscriptLine(target, line)) textShown = true; - // A later line (a retry, or a resumed member) reopens the turn. turnEnded = isClaudeTranscriptTurnEnd(line); } // A line longer than the cap can't advance; stop rather than spin. @@ -4777,8 +5513,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return true; }); if (!(yield* drain())) return; - // The coordinator sends nothing after its last frame, so wait out - // the flush window here rather than settle on the excerpt. + // The coordinator sends no more frames; wait out the transcript flush before using the excerpt. const waitLeft = flushWindowLeft(lastReadAt); if ( input.coordinator.task.status !== "running" && @@ -4791,11 +5526,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } } if (settled) { - // As for an ordinary subagent, a call still open once the member - // settles will never get its result. + // Open calls receive no results after their member settles. yield* endOpenToolCalls(); - // Only the progress excerpt is left when the transcript says - // nothing, read after its last writes had time to land. if ( !textShown && !resultShown && @@ -4890,6 +5622,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly model?: string; readonly effort?: string; readonly owner?: ActiveClaudeSubagent; + readonly nativeTaskType?: string; readonly progress?: string; readonly workflowFrame?: unknown; readonly workflowName?: string; @@ -4924,11 +5657,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existingSubagent.task.runId !== input.onlyIfRunningInRun) ) return; - // Status is monotone with one exception: task_started for a known - // task id is an authoritative CLI lifecycle event (SendMessage to a - // completed subagent resumes it and re-emits task_started with the - // same id), so it may re-open a terminal entry. A late or - // out-of-order task_progress must not. + // Only task_started may reopen a terminal task id on resume; late task_progress must not. const isReopen = input.reopen === true && existingSubagent !== undefined && @@ -4942,9 +5671,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { return; } - // A task_started under a tool call other than the current run's is - // a resume: SendMessage re-emits task_started for the same task id - // under its own tool_use_id, with the sent message as the prompt. + // Resume task_started uses the SendMessage tool_use_id and sent message as its prompt. const resumeToolUseId = input.reopen === true && existingSubagent !== undefined && @@ -5048,6 +5775,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } satisfies OrchestrationV2Subagent; const subagent = { task, + nativeTaskType: input.nativeTaskType ?? existingSubagent?.nativeTaskType, confirmedOutcome: input.nativeOutcome !== undefined ? confirmedSubagentOutcome(task) @@ -5072,13 +5800,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( lastAssistantMessageId: input.reopen === true ? null : (existingSubagent?.lastAssistantMessageId ?? null), } satisfies ActiveClaudeSubagent; - // The same terminal protection, applied atomically: a concurrent - // fiber (live stream vs continuation drain) may have terminalized - // the registry entry after this update's lookup read it. A resume - // re-open (task_started) bypasses it only when the registered entry - // is still the terminal generation the lookup resolved; if a - // concurrent fiber installed a newer terminal entry meanwhile, the - // re-open must not clobber its result. + // Ingestion can terminalize after lookup; reopen only that generation to preserve newer results. const accepted = yield* Ref.modify(sessionSubagentsByTaskId, (current) => { const registered = current.get(input.taskId); if ( @@ -5142,13 +5864,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( createdBy: "agent", creationSource: "provider", }); - if (existingSubagent === undefined) { - yield* emitProviderEvent({ - type: "app_thread.created", - driver: CLAUDE_PROVIDER, - appThread: childThread, - }); - } + // Recovery cannot tell whether the child thread was already persisted. + yield* emitProviderEvent({ + type: "app_thread.created", + driver: CLAUDE_PROVIDER, + appThread: childThread, + ...(existingSubagent === undefined ? {} : { createOnly: true }), + }); subagent.childThread = childThread; } @@ -5179,8 +5901,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }, }); } - // Ahead of the child thread's records: the run a resume attributes - // the subagent to adopts its child thread from this event. + // Emit before child records so the resumed run can adopt the child thread. yield* emitProviderEvent({ type: "subagent.updated", driver: CLAUDE_PROVIDER, @@ -5223,9 +5944,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( rootNodeId: childRootNodeId, role: "user", text: task.prompt, - // A workflow's prompt is its script; clients open the thread with - // the workflow's plan instead and keep the script collapsed. A - // brief says it is not one, so its text is never taken for one. + // Workflow prompts are collapsed scripts; clients open with the plan. A brief must not be mistaken for a script. ...(existingSubagent === undefined ? { workflowScript: task.workflow !== undefined } : {}), @@ -5412,7 +6131,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( [ ...(previousPlan === undefined || previousPlan.id === plan.id || - previousPlan.status === "completed" + (previousPlan.kind !== "todo_list" && previousPlan.status === "completed") ? [] : [ emitProviderEvent({ @@ -5461,8 +6180,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }) { const existing = findToolCall(input.context, input.nativeItemId); if (existing !== undefined) { - // The permission callback can start a call before its assistant - // frame arrives with the tool's display name and icon. + // Permission callbacks can start calls before assistant frames provide their display name and icon. if (input.presentation === undefined || existing.presentation !== undefined) { return existing; } @@ -5679,11 +6397,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } }); - /** - * Projects one transcript line of a subagent whose messages the CLI - * does not forward (a workflow member) the way a forwarded frame with - * its parent_tool_use_id is projected. Returns whether it carried text. - */ const projectSubagentTranscriptLine = Effect.fnUntraced(function* ( target: ClaudeSubagentProjectionTarget, line: unknown, @@ -5749,6 +6462,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly nativeRequestId: string; readonly requestKind: OrchestrationV2RuntimeRequest["kind"]; readonly prompt?: string; + readonly presentation?: ReturnType; readonly questions?: ReadonlyArray; }) { const createdAt = yield* DateTime.now; @@ -5808,6 +6522,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( responseCapability: { type: "live", providerSessionId, + ...(input.questions === undefined ? { supportsFeedback: true } : {}), }, createdAt, resolvedAt: null, @@ -5833,6 +6548,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( requestId, requestKind: input.requestKind as ProviderRequestKind, ...(input.prompt === undefined ? {} : { prompt: input.prompt }), + ...input.presentation, } : { type: "user_input_request" as const, @@ -5857,8 +6573,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const reasoningDeltas = yield* makeProviderTextDeltaCoalescer({ flushIntervalMs: 50, - emit: (update) => - Effect.gen(function* () { + emit: + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (update) { const context = yield* Ref.get(activeTurn); if (context === null || context.nativeTurnId !== update.turnId) return; const block = context.reasoning.blocks.get(update.itemId); @@ -5959,6 +6676,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly result?: SDKResultMessage; }) { yield* reasoningDeltas.flushTurn(input.context.nativeTurnId); + if (input.context.compaction?.status === "running") { + const reason = input.result?.subtype === "success" ? input.result.result.trim() : ""; + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: { + ...input.context.compaction, + status: input.status === "completed" ? "failed" : input.status, + title: + input.status === "completed" || input.status === "failed" + ? "Context compaction failed" + : "Context compaction stopped", + ...(reason === "" ? {} : { summary: reason }), + completedAt: input.completedAt, + updatedAt: input.completedAt, + }, + }); + } + input.context.compaction = null; if (input.status !== "completed") { const liveQuery = yield* Ref.get(queryContext); for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) { @@ -5969,8 +6705,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) continue; if (liveQuery !== null && !liveQuery.stopping) { - // Best effort and off the terminal path: an unanswered stop must - // not keep the turn from ending. + // An unanswered stop must not delay turn settlement. yield* liveQuery.query .stopTask(taskId) .pipe(Effect.timeout("15 seconds"), Effect.ignore, Effect.forkIn(sessionScope)); @@ -6131,8 +6866,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), }, }), - // Surface this native thread's roster before the root turn terminals so - // writeFinalRunEvents preserves it. + // Emit the roster before root settlement so writeFinalRunEvents preserves it. Effect.gen(function* () { const nativeThreadId = input.context.input.providerThread.nativeThreadRef?.nativeId ?? null; @@ -6156,6 +6890,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.get(pendingBackgroundTasksByNativeThread), nativeThreadId, ); + const awaitedTaskIds = + nativeThreadId === null + ? new Set() + : taskIdSetForNativeThread( + yield* Ref.get(awaitedBackgroundTasksByNativeThread), + nativeThreadId, + ); const clearConversationHead = input.status === "completed" && input.context.input.providerThread.nativeConversationHeadRef !== null; @@ -6163,13 +6904,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId === null ? undefined : goalsByNativeThread.get(nativeThreadId); const goalChecked = goalCheckedTurns.delete(input.context.providerTurnId); const terminalReason = input.result?.terminal_reason; + const liveQuery = yield* Ref.get(queryContext); if ( nativeThreadId !== null && goal?.status === "active" && goalChecked && input.status === "completed" && (terminalReason === undefined || terminalReason === "completed") && - roster.size === 0 + roster.size === 0 && + !( + liveQuery?.nativeThreadId === nativeThreadId && + (yield* liveProcessRunsBackgroundWork(liveQuery, { forGoalCheck: true })) + ) ) { goalsByNativeThread.set(nativeThreadId, { objective: goal.objective, @@ -6188,7 +6934,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( input.context.input.providerThread.firstRunOrdinal ?? input.context.input.runOrdinal, lastRunOrdinal: input.context.input.runOrdinal, - pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster(roster), + pendingBackgroundTasks: claudePendingBackgroundTasksFromRoster( + roster, + awaitedTaskIds, + ), status: input.status === "completed" ? "active" : "idle", updatedAt: input.completedAt, }; @@ -6266,11 +7015,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( cause?: Cause.Cause, ) { const current = yield* Ref.get(activeTurn); - const context = - current?.nativeThreadId === closedQuery.nativeThreadId ? current : closedQuery.lastTurn; + // A replacement query can reuse the native thread id; only this query's turn is ours. + const context = closedQuery.lastTurn; if (context === null) return; const interrupted = closedQuery.stopping || (yield* Ref.get(interruptedTurns)).has(context.providerTurnId); + // Finalization can yield to a replacement process; capture ownership and outcomes first. const subagents = yield* Ref.get(sessionSubagentsByTaskId); const buffered = (yield* Ref.get(wakeBuffers)).get(closedQuery.nativeThreadId)?.messages; if (current === context) { @@ -6290,9 +7040,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } else { yield* resetBackgroundTaskStateForNativeThreadProcess(closedQuery.nativeThreadId); } + // Preserve buffered outcomes before Stop clears the wake buffer. for (const [taskId, subagent] of subagents) { if ( - subagent.task.workflow === undefined || subagent.task.status !== "running" || closedQuery.subagentsFromEarlierProcesses.has(subagent) ) @@ -6418,9 +7168,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( entry.subtype === "task_started" && entry.task_id === message.task_id, )); - // A subagent launched while the root is idle (inside a native wake - // turn) must reach the continuation drain with its task_started, or - // its frames have no registered owner and are held indefinitely. + // Idle-wake task_started must reach the continuation drain before child frames can find their owner. const isNewSubagentTaskStarted = message.type === "system" && message.subtype === "task_started" && @@ -6514,10 +7262,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message.task_id, ); } - // Buffer it for replay, but do not open an opaque-task continuation until the turn's - // `init`, or native user, assistant, or result output, proves that Claude actually - // began the wake turn. Only root frames prove it: a background subagent keeps - // streaming its own frames while the root is idle. + // Open continuations only after root init, user, assistant, or result frames prove a wake began. + // Background child frames can stream while the root is idle. const buffered = (yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId); const hasBufferedNotification = buffered?.messages.some( @@ -6574,6 +7320,26 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); + // Untraced like the roster message handling: it runs for every streamed roster change. + const emitRosterUpdate = Effect.fnUntraced(function* ( + nativeThreadId: string, + activeContext: ActiveClaudeTurnContext | null, + ) { + const baseThread = + activeContext?.input.providerThread ?? + (yield* Ref.get(lastProviderThreadByNativeThread)).get(nativeThreadId); + if (baseThread === undefined) { + return; + } + const status = + activeContext === null + ? ("idle" as const) + : baseThread.status === "idle" + ? ("active" as const) + : baseThread.status; + yield* emitProviderThreadRoster({ nativeThreadId, providerThread: baseThread, status }); + }); + const applyBackgroundTaskRosterMessage = Effect.fnUntraced(function* (input: { readonly nativeThreadId: string; readonly message: SDKMessage; @@ -6647,24 +7413,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return false; } - const baseThread = - input.activeContext?.input.providerThread ?? - (yield* Ref.get(lastProviderThreadByNativeThread)).get(input.nativeThreadId); - if (baseThread === undefined) { - return true; - } - - const status = - input.activeContext === null - ? ("idle" as const) - : baseThread.status === "idle" - ? ("active" as const) - : baseThread.status; - yield* emitProviderThreadRoster({ - nativeThreadId: input.nativeThreadId, - providerThread: baseThread, - status, - }); + yield* emitRosterUpdate(input.nativeThreadId, input.activeContext); return true; }); @@ -6743,10 +7492,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } const message = input.message; - // Before any routing: a Monitor started during an idle wake turn - // reports its task before the drain replays the tool call. + // Track before routing: idle-wake Monitors report tasks before replaying their tool calls. yield* trackClaudeMonitorCalls(message); - // Before routing too: the wake gate reads it while the root is idle. + // Update before routing because the idle wake gate reads this. if ( message.type === "system" && message.subtype === "task_started" && @@ -6788,12 +7536,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const limitType = rateLimitInfo.rateLimitType ?? "unknown"; if (blocked) { context.rejectedRateLimitTypes.add(limitType); - const resetMs = (rateLimitInfo.resetsAt ?? NaN) * 1000; context.rateLimitResetTimes.set( limitType, - Number.isFinite(resetMs) && resetMs > 0 && resetMs < 8.64e15 - ? DateTime.formatIso(DateTime.makeUnsafe(resetMs)) - : null, + claudeUsageLimitResetAt(rateLimitInfo.resetsAt), ); } else if ( rateLimitInfo.status === "allowed" || @@ -6851,8 +7596,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (yield* settledTurnForSubagentFrame(liveQuery.nativeThreadId, message)); if (context === null) { yield* applyWorkflowProgressWithoutTurn(message); - // task_notification must buffer wake evidence while still tracked - // on the roster; clearing first would drop the wake pin. + // Buffer wake evidence before clearing the task from the roster. if (message.type === "system" && message.subtype === "task_notification") { yield* bufferWakeMessage({ nativeThreadId: liveQuery.nativeThreadId, message }); yield* applyBackgroundTaskRosterMessage({ @@ -6860,7 +7604,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message, activeContext: null, }); - // Record wake evidence first, while the child is still running. const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(message.task_id); const settled = settledTurnByNativeThread.get(liveQuery.nativeThreadId); const hasBufferedStart = @@ -6910,6 +7653,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (event.type === "message_start") { reasoning.messageId = event.message.id; reasoning.streamBlocks.clear(); + const usage: ClaudeMessageUsage | undefined = event.message.usage; + context.streamUsage = + usage === undefined ? null : { messageId: event.message.id, usage }; + if (usage !== undefined) yield* emitContextUsage(context, usage, true); + } else if (event.type === "message_delta") { + const usage: typeof event.usage | undefined = event.usage; + const stream = context.streamUsage; + if (stream?.usage && usage !== undefined) { + stream.usage = mergeClaudeStreamUsage(stream.usage, usage); + yield* emitContextUsage(context, stream.usage); + } } else if ( event.type === "content_block_start" && event.content_block.type === "thinking" && @@ -6956,8 +7710,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( !context.reasoning.snapshots.has(message.uuid) ) { context.reasoning.snapshots.add(message.uuid); - // The SDK emits one assistant snapshot per completed content block. - // Count thinking blocks separately so snapshots share the streamed ID. + // The SDK snapshots each completed block; count thinking blocks separately to preserve streamed ids. for (const block of message.message.content) { if (block.type !== "thinking") { const update = context.reasoning.lastThinking; @@ -7001,9 +7754,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } if (message.type === "assistant" && input.replayed !== true) { - context.nativeMessageCursor = message.uuid; if (message.parent_tool_use_id === null) { - context.latestAssistantRateLimited = message.error === "rate_limit"; + // Subagent uuids exist only in the sidechain transcript, so resume and fork cannot target them. + context.nativeMessageCursor = message.uuid; + context.latestAssistantRateLimit = + message.error === "rate_limit" ? { type: null, resetAt: null } : null; + if (message.error === "rate_limit" && isClaudeBlockedAssistantRateLimit(message)) { + const info = message.api_error_params.rate_limit_info; + const overageAllowed = + info.overageStatus === "allowed" || + info.overageStatus === "allowed_warning" || + info.isUsingOverage === true || + info.overageInUse === true; + if (!overageAllowed) { + context.latestAssistantRateLimit = { + type: typeof info.rateLimitType === "string" ? info.rateLimitType : "unknown", + resetAt: claudeUsageLimitResetAt(info.resetsAt), + }; + } + } if (message.error === "authentication_failed") { context.authenticationFailureMessage = claudeSignedOutMessage({ configDir: adapterOptions.environment.CLAUDE_CONFIG_DIR, @@ -7016,21 +7785,96 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if ( message.type === "system" && message.subtype === "status" && - message.compact_result !== undefined + (message.compact_result !== undefined || + (message.status === null && message.permissionMode === undefined)) ) { - context.compactionFailure = - message.compact_result === "failed" ? { message: message.compact_error } : null; + if (message.compact_result !== undefined) { + context.compactionFailure = + message.compact_result === "failed" ? { message: message.compact_error } : null; + } + if (context.compaction?.status === "running") { + const now = yield* DateTime.now; + context.compaction = { + ...context.compaction, + status: + message.compact_result === "success" + ? "completed" + : message.compact_result === "failed" + ? "failed" + : "interrupted", + title: + message.compact_result === "success" + ? "Context compacted" + : message.compact_result === "failed" + ? "Context compaction failed" + : "Context compaction stopped", + ...(message.compact_result === "failed" && message.compact_error + ? { summary: message.compact_error } + : {}), + completedAt: now, + updatedAt: now, + }; + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: context.compaction, + }); + if (message.compact_result !== "success") context.compaction = null; + } } - if (message.type === "system" && message.subtype === "compact_boundary") { + if ( + message.type === "system" && + (message.subtype === "compact_boundary" || + (message.subtype === "status" && message.status === "compacting")) + ) { + if (message.subtype === "status" && context.compaction?.status === "running") return; const now = yield* DateTime.now; const nativeItemId = message.uuid; + const compaction = + (message.subtype === "compact_boundary" ? context.compaction : null) ?? + ({ + id: idAllocator.derive.turnItemFromProviderItem({ + driver: CLAUDE_PROVIDER, + nativeItemId, + }), + threadId: context.input.threadId, + runId: context.input.runId, + nodeId: context.input.rootNodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef: { + driver: CLAUDE_PROVIDER, + nativeId: nativeItemId, + strength: "strong", + }, + parentItemId: null, + ordinal: yield* resolveItemOrdinal(context, nativeItemId), + type: "compaction", + driver: CLAUDE_PROVIDER, + status: "running", + title: "Compacting context", + startedAt: now, + completedAt: null, + updatedAt: now, + } satisfies OrchestrationV2TurnItem); + if (message.subtype === "status") { + context.compaction = compaction; + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: compaction, + }); + return; + } + if (context.streamUsage !== null) context.streamUsage.usage = null; const postTokens = message.compact_metadata.post_tokens; const afterTokenCount = typeof postTokens === "number" && Number.isFinite(postTokens) && postTokens > 0 ? Math.round(postTokens) : undefined; if (afterTokenCount !== undefined) { + const maxTokens = claudeContextWindow(context.input.modelSelection); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CLAUDE_PROVIDER, @@ -7051,7 +7895,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( completedAt: null, tokenUsage: { usedTokens: afterTokenCount, - maxTokens: claudeContextWindow(context.input.modelSelection), + maxTokens, + ...claudeAutoCompactThreshold( + adapterOptions.settings.autoCompactWindow, + maxTokens, + ), updatedAt: DateTime.formatIso(now), }, }, @@ -7061,28 +7909,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( type: "turn_item.updated", driver: CLAUDE_PROVIDER, turnItem: { - id: idAllocator.derive.turnItemFromProviderItem({ - driver: CLAUDE_PROVIDER, - nativeItemId, - }), - threadId: context.input.threadId, - runId: context.input.runId, - nodeId: context.input.rootNodeId, - providerThreadId: context.input.providerThread.id, - providerTurnId: context.providerTurnId, - nativeItemRef: { - driver: CLAUDE_PROVIDER, - nativeId: nativeItemId, - strength: "strong", - }, - parentItemId: null, - ordinal: yield* resolveItemOrdinal(context, nativeItemId), - type: "compaction", - driver: CLAUDE_PROVIDER, + ...compaction, status: "completed", title: "Context compacted", - startedAt: now, - completedAt: now, + completedAt: compaction.completedAt ?? now, updatedAt: now, ...(message.compact_metadata.pre_tokens === undefined ? {} @@ -7090,12 +7920,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ...(afterTokenCount === undefined ? {} : { afterTokenCount }), }, }); + context.compaction = null; return; } - if (message.type === "system" && message.subtype === "model_refusal_fallback") { + if ( + message.type === "system" && + (message.subtype === "model_refusal_fallback" || + (message.subtype === "informational" && message.level !== "info")) + ) { const now = yield* DateTime.now; const nativeItemId = message.uuid; + context.assistant.noticeTexts.add(message.content); yield* emitProviderEvent({ type: "turn_item.updated", driver: CLAUDE_PROVIDER, @@ -7175,44 +8011,35 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (message.type === "assistant" && input.replayed !== true) { const now = yield* DateTime.now; yield* completeProviderRetry(context, now); - // `` frames (usage limits, sign-in errors, /goal status) - // are generated by the CLI and report zero usage, not the context. + // CLI-generated frames report zero usage, not context usage. if ( message.parent_tool_use_id === null && message.message.usage !== undefined && message.message.model !== "" ) { - yield* emitProviderEvent({ - type: "provider_turn.updated", - driver: CLAUDE_PROVIDER, - threadId: context.input.threadId, - providerTurn: { - id: context.providerTurnId, - providerThreadId: context.input.providerThread.id, - nodeId: context.input.rootNodeId, - runAttemptId: context.input.attemptId, - nativeTurnRef: { - driver: CLAUDE_PROVIDER, - nativeId: context.nativeTurnId, - strength: "strong", - }, - ordinal: context.providerTurnOrdinal, - status: "running", - startedAt: context.startedAt, - completedAt: null, - tokenUsage: claudeProviderTurnTokenUsage( - message.message.usage, - context.input.modelSelection, - DateTime.formatIso(now), - ), - }, - }); + const snapshotUsage = message.message.usage; + const stream = context.streamUsage; + if (stream === null || stream.messageId !== message.message.id) { + context.streamUsage = { messageId: message.message.id, usage: snapshotUsage }; + yield* emitContextUsage(context, snapshotUsage); + } else if ( + stream.usage !== null && + claudeMessageInputTokens(stream.usage) <= 0 && + claudeMessageInputTokens(snapshotUsage) > 0 + ) { + stream.usage = { + ...snapshotUsage, + output_tokens: Math.max(snapshotUsage.output_tokens, stream.usage.output_tokens), + }; + yield* emitContextUsage(context, stream.usage); + } } const parentToolUseId = message.parent_tool_use_id; const snapshotModel = typeof message.message.model === "string" ? message.message.model.trim() : ""; + // "" identifies CLI notices, not the subagent model. const model = - snapshotModel.length === 0 + snapshotModel.length === 0 || snapshotModel === "" ? undefined : canonicalClaudeSubagentModel(subagentModelCatalog, snapshotModel); if (parentToolUseId !== null && model !== undefined) { @@ -7331,8 +8158,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( launch?.ownerToolUseId === undefined ? undefined : yield* resolveSubagentByToolUseId(context, launch.ownerToolUseId); - // With no model of its own, a nested subagent runs on its - // owner's (the SDK's default for a subagent's Agent call). + // Nested subagents default to their owner's model. const model = launch?.model ?? owner?.task.model ?? undefined; if ( message.is_backgrounded === true && @@ -7356,6 +8182,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* updateClaudeSubagentNode({ context, taskId: message.task_id, + ...(message.task_type === undefined ? {} : { nativeTaskType: message.task_type }), ...(message.tool_use_id === undefined ? {} : { toolUseId: message.tool_use_id }), ...(message.prompt === undefined ? {} : { prompt: message.prompt }), ...(model === undefined ? {} : { model }), @@ -7551,18 +8378,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( status: "running", }); } - // A resume task_started reuses the resuming tool call's - // tool_use_id (e.g. SendMessage), whose tool_result only - // acknowledges delivery. Only the Agent launch's tool_result may - // terminalize the subagent, and Agent tool_uses never enter - // toolCalls (they project as subagent rows instead). + // Resume tool results only acknowledge delivery; only Agent launch results may settle subagents. + // Agent tool_uses project as subagent rows and never enter toolCalls. if ( subagent !== undefined && findToolCall(context, toolResult.tool_use_id) === undefined ) { - // A background Agent launch resolves its tool_use immediately - // with an async-launch ACK while the task keeps running; only - // the eventual task_notification terminalizes the subagent. + // Background Agent launches ACK immediately; only task_notification settles them. if ( !isClaudeToolResultError(toolResult) && (runHandles !== undefined || isClaudeSubagentAsyncLaunchAck(output)) @@ -7598,19 +8420,47 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( output, completedAt: yield* DateTime.now, }); - if (parentToolUseId === null && !isClaudeToolResultError(toolResult)) { + // Subagents write to the session's shared task store, so their + // task tools update the parent turn's list. Failed or never-run + // calls changed nothing. + if ( + claudeToolNonExecutionKind(message, toolResult.tool_use_id) === undefined && + !isClaudeToolResultError(toolResult) && + CLAUDE_TASK_TOOL_NAMES.has(toolCall.toolName) + ) { const taskLists = yield* Ref.get(taskListsByNativeThread); - const taskList = applyClaudeTaskTool( - taskLists.get(liveQuery.nativeThreadId) ?? new Map(), - toolCall.toolName, - claudeNativeToolInputValue(toolCall.input), - claudeNativeToolOutputValue(output), + const knownTaskList = taskLists.get(liveQuery.nativeThreadId); + const outputValue = claudeNativeToolOutputValue(output); + // A structured TaskList already supplies a snapshot. Anything else, including + // a subagent's text-only TaskList, needs Claude's persisted list once; + // afterward the cache also records an unavailable store. + const storedTaskList = + !taskLists.has(liveQuery.nativeThreadId) && + !( + toolCall.toolName === "TaskList" && + Array.isArray(claudeTaskField(outputValue, "tasks")) + ) + ? yield* readClaudeTaskList({ + environment: adapterOptions.environment, + cwd: context.input.runtimePolicy.cwd, + nativeThreadId: liveQuery.nativeThreadId, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ) + : undefined; + const taskList = + applyClaudeTaskTool( + knownTaskList ?? storedTaskList ?? new Map(), + toolCall.toolName, + claudeNativeToolInputValue(toolCall.input), + outputValue, + ) ?? storedTaskList; + yield* Ref.set( + taskListsByNativeThread, + new Map(taskLists).set(liveQuery.nativeThreadId, taskList ?? knownTaskList), ); if (taskList !== undefined) { - yield* Ref.set( - taskListsByNativeThread, - new Map(taskLists).set(liveQuery.nativeThreadId, taskList), - ); yield* emitClaudePlanProjection({ context, nativeItemId: `claude-tasks:${context.providerTurnId}`, @@ -7669,6 +8519,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); return; } + // Claude Code echoes /compact's stdout ("Not enough messages to compact.") as a + // synthetic assistant message. The compaction item reports that outcome; it is not a + // reply. + if ( + message.type === "assistant" && + "local_command_source" in message && + isCompactionCommandMessage({ role: "user", ...context.input.message }) + ) { + return; + } if (assistantText !== null && assistantText.text.length > 0) { yield* emitAssistantTextArtifacts({ context, @@ -7720,10 +8580,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? null : resultTextFromSdkMessage(message); if ( + // A /compact's result text reports the compaction ("Not enough messages to + // compact."), which its compaction item already carries; it is not a reply. + !( + message.type === "result" && + message.subtype === "success" && + message.local_command === "compact" + ) && context.assistant.emittedNativeItemIds.size === 0 && context.assistant.fallbackText.length === 0 && resultText !== null && - resultText.text.length > 0 + resultText.text.length > 0 && + !context.assistant.noticeTexts.has(resultText.text) ) { context.assistant.fallbackText = resultText.text; context.assistant.fallbackNativeItemId = resultText.nativeItemId; @@ -7744,15 +8612,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const usageLimited = context.authenticationFailureMessage === undefined && - (context.rejectedRateLimitTypes.size > 0 || context.latestAssistantRateLimited) && + (context.rejectedRateLimitTypes.size > 0 || + context.latestAssistantRateLimit !== null) && (message.subtype !== "success" || message.api_error_status == null || message.api_error_status === 429) && (message.terminal_reason == null || message.terminal_reason === "api_error" || message.terminal_reason === "blocking_limit"); - // The CLI also labels a 403 authentication_failed. Logging in again - // can't grant a permission, so show the CLI's own text instead. + // The CLI also labels 403 authentication_failed; show its text because login cannot grant access. const permissionDenied = message.subtype === "success" && message.api_error_status === 403; const failureHint = permissionDenied @@ -7761,14 +8629,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (usageLimited ? "Claude usage limit reached. Send the message again once the limit resets." : undefined)); - // A /compact the usage limit stopped still ends in a success - // result. Failing the turn lets the usage-limit guard hold queued - // messages instead of sending them into the same limit (#19327). + // Usage-limited /compact reports success; fail it so queued messages wait for the limit to clear. const limitedCompaction = usageLimited && message.subtype === "success" && message.local_command === "compact" ? context.compactionFailure : null; const resetTimes = Array.from(context.rateLimitResetTimes.values()); + const assistantLimit = context.latestAssistantRateLimit; + if ( + assistantLimit?.type != null && + !context.rateLimitResetTimes.has(assistantLimit.type) + ) { + resetTimes.push(assistantLimit.resetAt); + } const resetAt = resetTimes.length > 0 && resetTimes.every((time) => time !== null) ? resetTimes.reduce((latest, time) => (time! > latest ? time! : latest), "") @@ -7872,6 +8745,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const message = input.message; const context = yield* Ref.get(activeTurn); const liveQuery = yield* Ref.get(queryContext); + if ( + context?.promptUuid === null && + liveQuery?.query === input.query && + isClaudeRootTurnFrame(message) + ) { + context.nativeWakeStarted = true; + } if ( context === null || context.promptUuid === null || @@ -7903,8 +8783,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (lifecycle.state === "started") { context.promptStarted = true; } - // Claude finishes a prompt whose uuid its transcript already - // holds without starting it, and no turn will ever answer it. + // Previously recorded prompt uuids complete without starting a turn. if (lifecycle.state === "completed" && !context.promptStarted) { yield* Effect.logWarning("orchestration-v2.claude-prompt-completed-without-turn", { providerTurnId: context.providerTurnId, @@ -7967,9 +8846,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } return; } - // Its output already streamed into this turn, so only its result - // stays out: settling here would end the turn before its prompt - // runs. The prompt's own turn ends it with an echoing result. + // Foreign output already streamed; exclude its result so only the prompt's own echoing result settles the turn. if (isClaudeTaskNotificationOriginResult(message)) { yield* clearWakeReports(liveQuery.nativeThreadId); } @@ -8034,11 +8911,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( toolName !== "ExitPlanMode" && (toolName === "AskUserQuestion" || requiresClaudeApproval(context)) ) { - // The SDK blocks on the answer, and the prompt echo cannot arrive - // until the held turn goes on, so the request is raised now and - // the held output goes with it to the pending prompt turn, as it - // did before this turn was held. ExitPlanMode is answered at once - // below, so its frames stay held. + // The SDK blocks prompt echoes on permission answers; release held output except for ExitPlanMode. yield* releaseHeldRootFrames(context); if (toolName !== "Agent") { yield* ensureToolCallStarted({ @@ -8137,6 +9010,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } satisfies PermissionResult; } + if ( + context.input.runtimePolicy.interactionMode === "plan" && + context.input.runtimePolicy.approvalPolicy === "never" + ) { + return { + behavior: "deny", + message: + "This tool requires approval in Plan mode, but approvals are disabled for this thread.", + toolUseID: callbackOptions.toolUseID, + } satisfies PermissionResult; + } + if (!requiresClaudeApproval(context)) { return { behavior: "allow", @@ -8157,8 +9042,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeRequestId, requestKind, prompt, + presentation: claudeApprovalPresentation({ + permissionMode: context.queryPolicy.permissionMode, + prompt, + callbackOptions, + }), }); - const decision = yield* Deferred.make(); + const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { const updated = new Map(current); updated.set(String(artifacts.request.id), { @@ -8205,7 +9095,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return permissionResultFromDecision({ toolName, - decision: resolvedDecision, + ...resolvedDecision, toolInput, toolUseID: callbackOptions.toolUseID, ...(callbackOptions.suggestions === undefined @@ -8226,6 +9116,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (request.dialogKind !== "resume_return") { return { behavior: "cancelled" as const }; } + const idleCompaction = Option.isSome(serverSettings) + ? yield* serverSettings.value.getSettings.pipe( + Effect.map((settings) => + resolveIdleCompaction(settings, adapterOptions.instanceId), + ), + Effect.orElseSucceed(() => adapterOptions.settings.idleCompaction), + ) + : adapterOptions.settings.idleCompaction; + if (idleCompaction === "off") { + return { behavior: "completed" as const, result: "continue" as const }; + } const ageMinutes = typeof request.payload.sessionAgeMinutes === "number" && Number.isFinite(request.payload.sessionAgeMinutes) @@ -8249,7 +9150,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( question, options: [ { - label: "Compact and continue", + label: CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER, description: "Resume with a summary and use fewer tokens.", }, { @@ -8283,7 +9184,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return { behavior: "completed" as const, result: - selection === "Compact and continue" + selection === CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER ? ("compact" as const) : selection === CLAUDE_RESUME_COMPACTION_NEVER_ANSWER ? ("never" as const) @@ -8294,6 +9195,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const liveProcessRunsBackgroundWork = Effect.fnUntraced(function* ( live: ClaudeLiveQueryContext, + options?: { readonly forGoalCheck?: boolean }, ) { if ( rosterForNativeThread( @@ -8308,6 +9210,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if ( subagent.task.status === "running" && !live.subagentsFromEarlierProcesses.has(subagent) && + (options?.forGoalCheck !== true || + subagent.nativeTaskType === undefined || + CLAUDE_GOAL_DEFERRING_TASK_TYPES.has(subagent.nativeTaskType)) && !buffered.some( (message) => message.type === "system" && @@ -8325,7 +9230,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, nativeThreadId: string, ) { - const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(turnInput.runtimePolicy); + const queryPolicy = yield* queryPolicyForTurn(turnInput); const mcpOverrides = claudeMcpQueryOverrides({ mcpSession: yield* mcpSessions.read(turnInput.threadId), readOnlySandbox: @@ -8338,8 +9243,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const compiledSelection = compileClaudeModelSelection(turnInput.modelSelection); const resumeSessionAt = yield* getNativeConversationHeadId(turnInput.providerThread); const existing = yield* Ref.get(queryContext); - // A continuation prompts nothing: it drains output the live process - // already produced, so it keeps that process whatever its selection. + // Continuations drain existing output without prompting; retain the live process regardless of selection. if ( existing !== null && existing.nativeThreadId === nativeThreadId && @@ -8353,7 +9257,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.queryPolicyKey === queryPolicyKey && !existing.stopping && existing.selection.queryIdentity !== compiledSelection.queryIdentity && - canApplyClaudeSelectionLive(existing.selection, compiledSelection) + canApplyClaudeSelectionLive(existing.selection, compiledSelection) && + (existing.selection.apiModelId === compiledSelection.apiModelId || + existing.openedPermissionMode === queryPolicy.permissionMode) ) { const live = existing; yield* live.query.setModel(compiledSelection.apiModelId).pipe( @@ -8374,19 +9280,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( existing.queryPolicyKey === queryPolicyKey && existing.selection.queryIdentity === compiledSelection.queryIdentity ) { - // Claude can switch its own mode mid-session (EnterPlanMode), and - // a denied ExitPlanMode leaves it there. Put the live process back - // in the thread's mode before the next prompt. - if (existing.permissionMode !== existing.openedPermissionMode) { - yield* existing.query.setPermissionMode(existing.openedPermissionMode); - existing.permissionMode = existing.openedPermissionMode; + // A denied ExitPlanMode leaves Claude in plan mode. Restore only from plan: + // Auto/default may reflect a policy restriction that forbids restoring bypass. + if (existing.permissionMode === "plan" && existing.openedPermissionMode !== "plan") { + existing.permissionMode = yield* existing.query + .setPermissionMode(existing.openedPermissionMode) + .pipe( + Effect.as(existing.openedPermissionMode), + Effect.catchTags({ + ClaudeAgentSdkQueryRunnerError: (error) => + existing.openedPermissionMode === "bypassPermissions" + ? existing.query + .setPermissionMode("default") + .pipe(Effect.as("default" as const)) + : Effect.fail(error), + }), + ); } return existing; } - // Background agents and shells run inside the CLI process, so a new selection would - // kill them and lose their results. Refuse until they finish or the user presses Stop, - // which closes the process. + // Selection changes kill CLI background work; refuse until it finishes or Stop closes the process. if ( existing !== null && existing.nativeThreadId === nativeThreadId && @@ -8396,6 +9310,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return yield* new ClaudeBackgroundWorkBlocksQueryReplacementError(); } + // Read before closing the live process so a bad path leaves it running. + const appendSystemPromptFileText = yield* readClaudeAppendSystemPromptFile({ + settings: adapterOptions.settings, + cwd: turnInput.runtimePolicy.cwd, + fileSystem, + path, + }); const closedExistingNativeThreadId = existing !== null ? existing.nativeThreadId : null; if (existing !== null) { yield* existing.query.close.pipe(Effect.ignore); @@ -8408,13 +9329,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } const openedWithResume = (yield* Ref.get(openedNativeThreads)).has(nativeThreadId); - // openedNativeThreads is per session instance and is lost when the - // provider session is idle-released. A prior turn on this native id - // requires resume; sessionId would fail with "already in use". + // Idle release loses openedNativeThreads; persisted turns still require resume to avoid "already in use". const hasPersistedProviderTurn = turnInput.nativeThreadHasTurns ?? turnInput.providerTurnOrdinal > 1; const shouldResume = resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn; + const toolSearchOverride = yield* resolveToolSearchOverride(turnInput.runtimePolicy.cwd); const queryOptions = makeClaudeQueryOptions({ modelSelection: turnInput.modelSelection, nativeThreadId, @@ -8423,7 +9343,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( cwd: turnInput.runtimePolicy.cwd, attachmentsDir, settings: adapterOptions.settings, - environment: adapterOptions.environment, + environment: claudeQueryEnvironment( + adapterOptions.environment, + turnInput.appThread, + turnInput.appThread.lineage.relationshipToParent === "subagent" + ? yield* resolveSubagentPromptCacheTtl(turnInput.runtimePolicy.cwd) + : undefined, + ), tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS, ...(mcpOverrides.allowedTools === undefined ? {} @@ -8440,6 +9366,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( canUseTool, onUserDialog, supportedDialogKinds: ["resume_return"], + ...(appendSystemPromptFileText === undefined ? {} : { appendSystemPromptFileText }), + ...(toolSearchOverride === undefined ? {} : { toolSearchOverride }), }); const querySession = yield* queryRunner .open({ @@ -8459,9 +9387,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( : Effect.void, ), ); - // Marked only after a successful open: a failed create must not - // leave the runtime believing the native session exists, or the - // retry would resume a session that was never created. + // Mark only successful opens; retries must not resume sessions that failed to create. yield* Ref.update(openedNativeThreads, (current) => { if (current.has(nativeThreadId)) { return current; @@ -8475,6 +9401,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); const closed = yield* Deferred.make(); const context: ClaudeLiveQueryContext = { + queryPolicy, nativeThreadId, query: querySession, queryPolicyKey, @@ -8483,6 +9410,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( lastTurn: null, promptEchoMode: "unknown", openedPermissionMode: queryOptions.permissionMode, + receivedInit: false, permissionMode: queryOptions.permissionMode, stopping: false, subagentsFromEarlierProcesses: new Set( @@ -8496,6 +9424,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Stream.runForEach((message) => sdkMessageLock.withPermits(1)( Effect.suspend(() => { + if ( + message.type === "system" && + message.subtype === "init" && + !context.receivedInit + ) { + context.openedPermissionMode = + message.permissionMode ?? context.openedPermissionMode; + context.receivedInit = true; + } if ( message.type === "system" && (message.subtype === "init" || message.subtype === "status") && @@ -8544,10 +9481,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const startedAt = yield* DateTime.now; const nativeThreadId = yield* getNativeThreadId(turnInput.providerThread); const nativeTurnId = `turn:${turnInput.attemptId}`; - // Fresh for every offer: Claude acks a prompt whose uuid its - // transcript already holds without running a turn, and a session - // can outlive this database (or be resumed from a copy of it), so - // a uuid derived from run ids can repeat. + // Use fresh uuids: native sessions can outlive this database, and Claude skips previously recorded prompts. const promptUuid = isClaudeProviderContinuationTurn(turnInput) ? null : yield* crypto.randomUUIDv4().pipe( @@ -8571,6 +9505,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, detail: `Claude provider turn ${currentTurn.providerTurnId} is still active.`, + reason: "previous_turn_active", }); } yield* Ref.update(lastTurnRouteByNativeThread, (current) => { @@ -8585,8 +9520,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (!goalsByNativeThread.has(nativeThreadId)) { goalsByNativeThread.set(nativeThreadId, turnInput.providerThread.goal ?? null); } + const userMessage = + promptUuid === null + ? null + : yield* makeClaudeUserMessageWithAttachments({ + text: applyClaudePromptEffortPrefix( + turnInput.message.text, + compileClaudeModelSelection(turnInput.modelSelection).promptEffort, + ), + attachments: turnInput.message.attachments, + attachmentsDir, + fileSystem, + skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd), + uuid: promptUuid, + }); + const querySession = yield* openQuery(turnInput, nativeThreadId); const context: ActiveClaudeTurnContext = { input: turnInput, + queryPolicy: querySession.queryPolicy, nativeThreadId, nativeTurnId, nativeMessageCursor: null, @@ -8598,6 +9549,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( fallbackText: "", fallbackNativeItemId: `assistant:${turnInput.runId}`, emittedNativeItemIds: new Set(), + noticeTexts: new Set(), }, reasoning: { messageId: null, @@ -8608,13 +9560,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( snapshots: new Set(), blocks: new Map(), }, + streamUsage: null, toolCalls: new Map(), + compaction: null, ignoredTaskIds: new Set(), announcedUsageLimits: new Set(), authenticationFailureMessage: undefined, rejectedRateLimitTypes: new Set(), rateLimitResetTimes: new Map(), - latestAssistantRateLimited: false, + latestAssistantRateLimit: null, compactionFailure: null, steeredSegmentUsage: [], subagentsByTaskId: new Map(), @@ -8623,27 +9577,58 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( promptUuid, promptEcho: isClaudeProviderContinuationTurn(turnInput) ? "confirmed" : "pending", promptStarted: false, + nativeWakeStarted: false, gatedFramesBeforeEcho: 0, heldRootFrames: [], }; - const userMessage = - promptUuid === null - ? null - : yield* makeClaudeUserMessageWithAttachments({ - text: applyClaudePromptEffortPrefix( - turnInput.message.text, - compileClaudeModelSelection(turnInput.modelSelection).promptEffort, - ), - attachments: turnInput.message.attachments, - attachmentsDir, - fileSystem, - skillNames: yield* userInvocableSkillNames(turnInput.runtimePolicy.cwd), - uuid: promptUuid, - }); - const querySession = yield* openQuery(turnInput, nativeThreadId); const attachTurn = Effect.gen(function* () { querySession.lastTurn = context; yield* Ref.set(activeTurn, context); + if ( + !isClaudeProviderContinuationTurn(turnInput) && + permissionModeForClaudeRuntimePolicy(turnInput.runtimePolicy) === + "bypassPermissions" && + context.queryPolicy.permissionMode !== "bypassPermissions" && + !announcedBypassDowngrades.has(turnInput.threadId) + ) { + announcedBypassDowngrades.add(turnInput.threadId); + if (announcedBypassDowngrades.size > 1000) { + const oldest = announcedBypassDowngrades.values().next().value; + if (oldest !== undefined) announcedBypassDowngrades.delete(oldest); + } + const nativeItemId = `bypass-policy-downgrade:${context.providerTurnId}`; + const notice = + "T3 could not confirm Claude bypass permissions here, so Full access is running with approval checks."; + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: { + id: idAllocator.derive.turnItemFromProviderItem({ + driver: CLAUDE_PROVIDER, + nativeItemId, + }), + threadId: turnInput.threadId, + runId: turnInput.runId, + nodeId: turnInput.rootNodeId, + providerThreadId: turnInput.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef: { + driver: CLAUDE_PROVIDER, + nativeId: nativeItemId, + strength: "weak", + }, + parentItemId: null, + ordinal: yield* resolveItemOrdinal(context, nativeItemId), + type: "system_notice", + status: "completed", + title: notice, + message: notice, + startedAt, + completedAt: startedAt, + updatedAt: startedAt, + }, + }); + } yield* emitProviderEvent({ type: "provider_turn.updated", driver: CLAUDE_PROVIDER, @@ -8660,8 +9645,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* querySession.query.offer(userMessage); return; } - // Transcript reads suspend replay. Hold live SDK frames until the whole - // buffer has been applied so starts, completions and the root result stay ordered. + // Transcript reads suspend replay; hold SDK frames until the buffer is applied to preserve order. yield* sdkMessageLock.withPermits(1)( Effect.gen(function* () { if ( @@ -8685,10 +9669,31 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* finalizeActiveTurn({ context, status: "completed", completedAt }); return; } - // Replay any result message last: a result finalizes the turn, and - // replaying it before the rest would drop them back into the wake - // buffer and request another continuation. - const resultMessages = drained.filter((entry) => entry.type === "result"); + // Replay results last to avoid rebuffering later frames. An empty turn's result must not settle a newer running turn. + const lastResultIndex = drained.findLastIndex((entry) => entry.type === "result"); + const tailResult = drained[lastResultIndex]; + const emptyTurnBeforeNextTurn = + tailResult?.type === "result" && + tailResult.num_turns === 0 && + !tailResult.is_error && + terminalStatusFromResult(tailResult) === "completed" && + drained + .slice(lastResultIndex + 1) + .some((entry) => isClaudeTurnStartMessage(entry)); + // The CLI can append empty task successes after a failure. Filter + // those for replay without changing the raw-tail successor guard. + const isEmptyTaskNotificationSuccess = (entry: SDKMessage) => + isClaudeTaskNotificationOriginResult(entry) && + entry.subtype === "success" && + !entry.is_error && + entry.num_turns === 0 && + entry.result.length === 0 && + terminalStatusFromResult(entry) === "completed"; + const replayResultIndex = drained.findLastIndex( + (entry) => entry.type === "result" && !isEmptyTaskNotificationSuccess(entry), + ); + const lastResult = + drained[replayResultIndex === -1 ? lastResultIndex : replayResultIndex]; const opaqueReplayTombstones = taskIdSetForNativeThread( yield* Ref.get(opaqueBackgroundTaskReplayTombstonesByNativeThread), nativeThreadId, @@ -8723,20 +9728,40 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return next; }); } - const lastResult = resultMessages.at(-1); - if (lastResult !== undefined) { + if (lastResult !== undefined && !emptyTurnBeforeNextTurn) { yield* handleSdkMessage({ query: querySession.query, message: lastResult }); return; } - const hasNativeWakeFrame = drained.some( - (entry) => - entry.type === "user" || - entry.type === "assistant" || - isClaudeTurnStartMessage(entry), - ); - if (hasOpaqueTaskNotification && !hasNativeWakeFrame) { + if (hasOpaqueTaskNotification && !context.nativeWakeStarted) { const completedAt = yield* DateTime.now; yield* finalizeActiveTurn({ context, status: "completed", completedAt }); + } else if (!context.nativeWakeStarted) { + yield* Effect.sleep(CLAUDE_WAKE_TURN_START_DEADLINE).pipe( + Effect.andThen( + sdkMessageLock.withPermits(1)( + Effect.gen(function* () { + if ( + (yield* Ref.get(activeTurn)) !== context || + (yield* Ref.get(queryContext)) !== querySession || + querySession.stopping || + context.nativeWakeStarted || + (yield* Ref.get(interruptedTurns)).has(context.providerTurnId) + ) + return; + yield* Effect.logWarning( + "orchestration-v2.claude-wake-turn-never-opened", + { + providerTurnId: context.providerTurnId, + nativeThreadId, + }, + ); + const completedAt = yield* DateTime.now; + yield* finalizeActiveTurn({ context, status: "completed", completedAt }); + }), + ), + ), + Effect.forkIn(sessionScope), + ); } }), ); @@ -8842,12 +9867,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); - // A steer is sent with priority "now", which cancels the root turn's - // running tool calls. A subagent the root launched in the foreground is - // one of them, so it moves to the background first and keeps running; - // its result arrives as a task notification like any background agent. + // Move subagents to the background before priority "now" steers cancel foreground tools. const backgroundForegroundSubagents = Effect.fnUntraced(function* ( live: ClaudeLiveQueryContext, + deadline: number, ) { const foreground: Array<{ readonly taskId: string; @@ -8903,11 +9926,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( backgroundMovesByToolUseId.set(toolUseId, move); moves.push(move); } - yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption("5 seconds")); + const remaining = deadline - (yield* Clock.currentTimeMillis); + yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption(Math.max(0, remaining))); }); const steerTurn = Effect.fn("ClaudeAdapterV2.steerTurn")( function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) { + // Measured from the request, not from when the moves are forked: + // building the message and the moves can take clock time a timer + // started later would not count, and the steer would wait past it. + const backgroundDeadline = + (yield* Clock.currentTimeMillis) + BACKGROUND_MOVE_TIMEOUT_MS; const existing = yield* Ref.get(queryContext); if (existing === null) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ @@ -8931,9 +9960,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( priority: "now", attachmentsDir, fileSystem, - skillNames: yield* userInvocableSkillNames(currentTurn.input.runtimePolicy.cwd), + skills: yield* userInvocableSkills(currentTurn.input.runtimePolicy.cwd), }); - yield* backgroundForegroundSubagents(existing); + yield* backgroundForegroundSubagents(existing, backgroundDeadline); // The turn can end while the moves are answered. A steer offered // then would start a new turn the orchestrator never asked for, so // the steer fails and the orchestrator starts the follow-up turn. @@ -9013,6 +10042,43 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); yield* Effect.addFinalizer(() => closeSession()); + // Metadata-only transcripts cannot be resumed or recreated; fail resumeThread to trigger a fresh session and handoff. + const hasEmptyClaudeTranscript = Effect.fn("ClaudeAdapterV2.hasEmptyClaudeTranscript")( + function* (nativeThreadId: string) { + const configuredDir = adapterOptions.environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; + const projectsDir = path.join( + configuredDir.length > 0 + ? path.resolve(session.cwd, configuredDir) + : path.join(yield* HostProcess.HomeDirectory, ".claude"), + "projects", + ); + // Any message in any transcript copy means Claude may still resume it. + let found = false; + for (const project of yield* fileSystem.readDirectory(projectsDir)) { + const transcriptPath = path.join(projectsDir, project, `${nativeThreadId}.jsonl`); + // Stray files beside the project dirs fail with ENOTDIR. + if ( + !(yield* fileSystem.exists(transcriptPath).pipe(Effect.orElseSucceed(() => false))) + ) { + continue; + } + const conversationLine = yield* fileSystem + .stream(transcriptPath) + .pipe( + Stream.decodeText, + Stream.splitLines, + Stream.filter(isClaudeConversationLine), + Stream.runHead, + ); + if (Option.isSome(conversationLine)) { + return false; + } + found = true; + } + return found; + }, + ); + const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { instanceId: adapterOptions.instanceId, driver: CLAUDE_PROVIDER, @@ -9048,19 +10114,20 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } return false; }), - hasPendingBackgroundWorkForThread: (providerThread) => - Effect.gen(function* () { - const nativeThreadId = providerThread.nativeThreadRef?.nativeId; - if (nativeThreadId === undefined || nativeThreadId === null) { - return false; - } - return ( - rosterForNativeThread( - yield* Ref.get(pendingBackgroundTasksByNativeThread), - nativeThreadId, - ).size > 0 - ); - }), + hasPendingBackgroundWorkForThread: Effect.fn( + "ClaudeAdapterV2.hasPendingBackgroundWorkForThread", + )(function* (providerThread) { + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; + if (nativeThreadId === undefined || nativeThreadId === null) { + return false; + } + return ( + rosterForNativeThread( + yield* Ref.get(pendingBackgroundTasksByNativeThread), + nativeThreadId, + ).size > 0 + ); + }), ensureThread: Effect.fn("ClaudeAdapterV2.ensureThread")( function* (threadInput: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) { const createdAt = yield* DateTime.now; @@ -9088,6 +10155,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), resumeThread: Effect.fn("ClaudeAdapterV2.resumeThread")( function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) { + const nativeThreadId = threadInput.providerThread.nativeThreadRef?.nativeId; + if ( + nativeThreadId !== undefined && + nativeThreadId !== null && + // A live process holds the conversation even before saving it. + (yield* Ref.get(queryContext))?.nativeThreadId !== nativeThreadId && + // An unreadable transcript leaves the resume to the CLI. + (yield* hasEmptyClaudeTranscript(nativeThreadId).pipe( + Effect.orElseSucceed(() => false), + )) + ) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Claude session ${nativeThreadId} has no conversation to resume.`, + }); + } const updatedAt = yield* DateTime.now; return { ...threadInput.providerThread, @@ -9116,36 +10199,69 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message: { ...turnInput.message, text: "/compact" }, }), steerTurn, - stopTask: ({ providerThread, taskId }) => - Effect.gen(function* () { - const liveQuery = yield* Ref.get(queryContext); - const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); - if ( - liveQuery === null || - liveQuery.stopping || - liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId || - task === undefined || - task.task.threadId !== providerThread.appThreadId || - task.task.workflow === undefined || - task.task.status !== "running" || - liveQuery.subagentsFromEarlierProcesses.has(task) - ) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver: CLAUDE_PROVIDER, - detail: "No running workflow task belongs to this provider thread", - }); + stopTask: Effect.fn("ClaudeAdapterV2.stopTask")(function* ({ providerThread, taskId }) { + const liveQuery = yield* Ref.get(queryContext); + const task = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); + if ( + liveQuery === null || + liveQuery.stopping || + liveQuery.nativeThreadId !== providerThread.nativeThreadRef?.nativeId || + task === undefined || + task.task.threadId !== providerThread.appThreadId || + task.task.workflow === undefined || + task.task.status !== "running" || + liveQuery.subagentsFromEarlierProcesses.has(task) + ) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: "No running workflow task belongs to this provider thread", + }); + } + yield* liveQuery.query.stopTask(taskId).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: "Workflow stop request failed", + cause, + }), + ), + ); + }), + awaitBackgroundTasks: Effect.fn("ClaudeAdapterV2.awaitBackgroundTasks")( + function* ({ providerThread, taskIds, awaited }) { + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; + if (nativeThreadId == null) return { matched: [] }; + const roster = rosterForNativeThread( + yield* Ref.get(pendingBackgroundTasksByNativeThread), + nativeThreadId, + ); + const matched = [...new Set(taskIds)].filter((taskId) => roster.has(taskId)); + if (matched.length === 0) return { matched }; + if (awaited) { + yield* addTaskIdsToNativeThreadSet( + awaitedBackgroundTasksByNativeThread, + nativeThreadId, + matched, + ); + } else { + for (const taskId of matched) { + yield* clearTaskIdFromNativeThreadSet( + awaitedBackgroundTasksByNativeThread, + nativeThreadId, + taskId, + ); + } } - yield* liveQuery.query.stopTask(taskId).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterProtocolError({ - driver: CLAUDE_PROVIDER, - detail: "Workflow stop request failed", - cause, - }), - ), + const active = yield* Ref.get(activeTurn); + yield* emitRosterUpdate( + nativeThreadId, + active?.nativeThreadId === nativeThreadId ? active : null, ); - }), + return { matched }; + }, + (effect) => sdkMessageLock.withPermits(1)(effect), + ), interruptTurn, stopSubagent: Effect.fn("ClaudeAdapterV2.stopSubagent")(function* (input) { const existing = yield* Ref.get(queryContext); @@ -9242,7 +10358,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), }); } - yield* Deferred.succeed(pending.decision, requestInput.decision); + yield* Deferred.succeed(pending.decision, { + decision: requestInput.decision, + ...(requestInput.feedback === undefined ? {} : { feedback: requestInput.feedback }), + }); }, (effect, requestInput) => effect.pipe( @@ -9278,8 +10397,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const nativeThreadId = yield* getNativeThreadId(rollbackInput.providerThread); yield* closeLiveQueryForNativeThread(nativeThreadId); const now = yield* DateTime.now; + const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput); - if (rollbackInput.target.type === "thread_start") { + if (rollbackInput.target.type === "thread_start" && resumeSessionAt === null) { const resetNativeThreadId = yield* queryRunner.allocateSessionId; return { providerThread: { @@ -9305,7 +10425,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }; } - const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput); return { providerThread: { ...rollbackInput.providerThread, @@ -9360,6 +10479,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const forked = yield* queryRunner.forkSession({ sessionId: sourceNativeThreadId, options: forkOptions, + environment: adapterOptions.environment, threadId: forkInput.targetThreadId, providerSessionId: input.providerSessionId, }); @@ -9382,6 +10502,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? {} : { providerTurnId: forkInput.providerTurnId }), }, + ...(forked.headMessageId === undefined + ? {} + : { nativeMetadata: { forkHeadMessageId: forked.headMessageId } }), now, }); }, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index a691d7e8459af..2ba8f78c451b5 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -8,83 +8,100 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; +import * as Deferred from "effect/Deferred"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import { vi } from "vite-plus/test"; -import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { AgentScope } from "@t3tools/shared/AgentScope"; +import { ProviderEventLoggers } from "@t3tools/provider-core/server/ProviderEventLoggers"; +import { signalProcessGroup } from "@t3tools/provider-core/server/processGroup"; import { - CLAUDE_AGENT_SDK_QUERY_PROTOCOL, ClaudeAgentSdkQueryRunner, layerQueryRunner, + spawnClaudeProcessGroup, } from "./ClaudeAdapterV2.ts"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); -it.effect("logs successful task stops for replay and omits failed stops", () => - Effect.gen(function* () { - const writes: unknown[] = []; - const stopTask = vi.fn(async (_taskId: string) => {}); - const query = vi.spyOn(ClaudeSdk, "query").mockReturnValue({ - stopTask, - } as unknown as ClaudeSdk.Query); - yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); - const threadId = ThreadId.make("thread-stop"); - const providerSessionId = ProviderSessionId.make("session-stop"); - yield* Effect.gen(function* () { +const FORK_SESSION_ID = "11111111-1111-4111-8111-111111111111"; + +const writeClaudeSession = Effect.fnUntraced(function* (configDir: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const projectDir = path.join(configDir, "projects", "-repo"); + const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({ + type: parentUuid === null ? "user" : "assistant", + uuid, + parentUuid, + sessionId: FORK_SESSION_ID, + cwd: "/repo", + isSidechain: false, + timestamp: "2026-10-01T00:00:00.000Z", + message, + }); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(projectDir, `${FORK_SESSION_ID}.jsonl`), + [ + entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }), + entry("aaaaaaaa-0000-4000-8000-000000000002", "aaaaaaaa-0000-4000-8000-000000000001", { + role: "assistant", + content: [{ type: "text", text: "hi" }], + }), + ] + .map((line) => JSON.stringify(line)) + .join("\n"), + ); + return projectDir; +}); + +const forkRunnerLayer = layerQueryRunner.pipe( + Layer.provide(Layer.succeed(ProviderEventLoggers, { native: undefined, canonical: undefined })), +); + +it.effect("forks a session stored under the instance's own CLAUDE_CONFIG_DIR", () => + Effect.scoped( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-fork-config-", + }); + const projectDir = yield* writeClaudeSession(configDir); + const hostConfigDir = process.env.CLAUDE_CONFIG_DIR; + const inProcessFork = vi.spyOn(ClaudeSdk, "forkSession"); + yield* Effect.addFinalizer(() => Effect.sync(() => inProcessFork.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; - const session = yield* runner.open({ - threadId, - providerSessionId, - options: { - sessionId: "native-session-stop", - model: "claude-sonnet-4-6", - tools: [], - permissionMode: "default", - }, + const forked = yield* runner.forkSession({ + sessionId: FORK_SESSION_ID, + options: { dir: "/repo" }, + environment: { ...process.env, CLAUDE_CONFIG_DIR: configDir }, + threadId: ThreadId.make("thread-fork-config-dir"), + providerSessionId: ProviderSessionId.make("session-fork-config-dir"), }); - writes.length = 0; - yield* session.stopTask("workflow-task"); - assert.deepEqual(stopTask.mock.calls, [["workflow-task"]]); - assert.deepEqual(writes, [ - { - provider: "claudeAgent", - protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL, - kind: "protocol", - providerSessionId, - event: { - direction: "outgoing", - stage: "decoded", - payload: { type: "query.stop_task", taskId: "workflow-task" }, - }, - }, - ]); - stopTask.mockRejectedValueOnce(new Error("Stop failed")); - assert.isTrue(Exit.isFailure(yield* Effect.exit(session.stopTask("failed-task")))); - assert.equal(writes.length, 1); - }).pipe( - Effect.provide( - layerQueryRunner.pipe( - Layer.provide( - Layer.succeed(ProviderEventLoggers, { - native: { - filePath: "/tmp/events.log", - write: (event) => - Effect.sync(() => { - writes.push(event); - }), - close: () => Effect.void, - }, - canonical: undefined, - }), - ), - ), - ), - ); - }).pipe(Effect.provide(NodeServices.layer)), -); + assert.notEqual(forked.sessionId, FORK_SESSION_ID); + const transcript = yield* fileSystem.readFileString( + path.join(projectDir, `${forked.sessionId}.jsonl`), + ); + assert.include(transcript, '"content":"hello"'); + assert.include(transcript, '"text":"hi"'); + const inheritedHead = transcript + .trim() + .split("\n") + .findLast((line) => line.includes('"type":"assistant"')) + ?.match(/"uuid"\s*:\s*"([^"]+)"/)?.[1]; + assert.isString(inheritedHead); + assert.equal(forked.headMessageId, inheritedHead); + assert.equal(process.env.CLAUDE_CONFIG_DIR, hostConfigDir); + assert.equal(inProcessFork.mock.calls.length, 0); + }).pipe(Effect.provide(forkRunnerLayer)), + ).pipe(Effect.provide(NodeServices.layer)), +); const realQueryRunner = layerQueryRunner.pipe( Layer.provide( Layer.succeed(ProviderEventLoggers, { @@ -119,9 +136,7 @@ const openFakeCli = (cli: string) => }); describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI process", () => { - // The CLI stops the MCP servers it started, but not their children: a - // plugin's `bun server.ts` outlives its `bun run` wrapper (#3089). The child - // holds a FIFO open, so its death reads as end-of-file here, with no polling. + // The leftover child holds a FIFO open; its death produces EOF without polling. it.effect("stops what the CLI left running when the session closes", () => Effect.gen(function* () { const cli = fakeClaudeCli( @@ -147,10 +162,59 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro const leftoverStopped = new Promise((resolve) => alive.once("close", () => resolve())); alive.resume(); - const session = yield* openFakeCli(cli); + const stopped = yield* Deferred.make(); + const session = yield* openFakeCli(cli).pipe( + Effect.provide( + realQueryRunner.pipe( + Layer.provide( + Layer.succeed(AgentScope, { + ...AgentScope.defaultValue(), + wrap: ({ command, args }) => + Effect.succeed({ command, args, unit: "t3code-claude-test.scope" }), + stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid), + }), + ), + ), + ), + ); yield* Effect.promise(() => leftoverStarted); yield* session.close; yield* Effect.promise(() => leftoverStopped); - }).pipe(Effect.provide(realQueryRunner)), + assert.strictEqual(yield* Deferred.await(stopped), "t3code-claude-test.scope"); + }), + ); + + // The CLI keeps running its turn after its pipes close, so a server that + // crashed would leave it working next to the session it resumes. + it.effect("stops the CLI when the server that started it goes away", () => + Effect.gen(function* () { + const cli = fakeClaudeCli(['dir=$(dirname "$0")', 'sleep 600 > "$dir/alive"'].join("\n")); + const dir = NodePath.dirname(cli); + NodeChildProcess.execFileSync("mkfifo", [NodePath.join(dir, "alive")]); + const child = spawnClaudeProcessGroup({ + command: cli, + args: [], + cwd: dir, + env: process.env, + signal: new AbortController().signal, + }) as NodeChildProcess.ChildProcess; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + try { + signalProcessGroup(child.pid ?? 0, "SIGKILL"); + } catch {} + NodeFS.rmSync(dir, { recursive: true, force: true }); + }), + ); + const alive = NodeFS.createReadStream(NodePath.join(dir, "alive")); + const turnStarted = new Promise((resolve) => alive.once("open", () => resolve())); + const turnStopped = new Promise((resolve) => alive.once("close", () => resolve())); + alive.resume(); + yield* Effect.promise(() => turnStarted); + + // A dying server's descriptors close; the kernel would do this for it. + for (const pipe of child.stdio) pipe?.destroy(); + yield* Effect.promise(() => turnStopped); + }), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts index bca0e4570549e..87992bab89169 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.test.ts @@ -12,7 +12,6 @@ import { tailClaudeTaskOutput } from "./ClaudeTaskOutputTail.ts"; const SESSION_ID = "0c91bb28-9e89-4889-bd22-3de9880233d3"; const TASK_ID = "bk6xreeye"; -// Claude Code's layout: ///tasks/.output. const makeTaskFile = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -21,8 +20,7 @@ const makeTaskFile = Effect.gen(function* () { return { root, tasks, file: path.join(tasks, `${TASK_ID}.output`) }; }); -// Live clock and a real file: this proves the tail follows the writer, which -// TestClock cannot interleave with filesystem IO. +// TestClock cannot interleave with real filesystem I/O; use the live clock. describe("tailClaudeTaskOutput", () => { it.live("follows a file that appears after the task starts, across split characters", () => Effect.scoped( @@ -39,7 +37,7 @@ describe("tailClaudeTaskOutput", () => { }).pipe(Effect.forkScoped); yield* fileSystem.makeDirectory(tasks, { recursive: true }); - // "é" is two bytes; the first write ends between them. + // Split the two-byte é across writes. const encoded = new TextEncoder().encode("café 1\n"); yield* fileSystem.writeFile(file, encoded.subarray(0, 4)); assert.equal(yield* Queue.take(chunks), "caf"); @@ -97,7 +95,6 @@ describe("tailClaudeTaskOutput", () => { ), }).pipe(Effect.forkScoped); yield* Deferred.await(first); - // Written right before the command exits, then the result arrives. yield* fileSystem.writeFileString(file, "one\ntwo\n"); yield* Deferred.succeed(stop, undefined); yield* Fiber.join(fiber); @@ -105,22 +102,4 @@ describe("tailClaudeTaskOutput", () => { }).pipe(Effect.provide(NodeServices.layer)), ), ); - - it.live("ends when stopped even if Claude Code never wrote the file", () => - Effect.scoped( - Effect.gen(function* () { - const { root } = yield* makeTaskFile; - const stop = yield* Deferred.make(); - const fiber = yield* tailClaudeTaskOutput({ - root, - sessionId: SESSION_ID, - taskId: TASK_ID, - stop, - onChunk: () => Effect.die("no file, no output"), - }).pipe(Effect.forkScoped); - yield* Deferred.succeed(stop, undefined); - yield* Fiber.join(fiber); - }).pipe(Effect.provide(NodeServices.layer)), - ), - ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts index fbe759e973a40..6ab23fddbe16c 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeTaskOutputTail.ts @@ -4,22 +4,13 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; -/** - * Live output for a foreground Claude Bash call. - * - * The Agent SDK sends no stdout until the tool result. Claude Code does write - * each running command's combined output to - * `/claude-///tasks/.output`, naming - * the task in its `task_started` frame (`task_type: "local_bash"`). This path is - * Claude Code's private layout, not SDK API, so every step degrades to "no live - * output": the row still gets its full output from the tool result. - */ +/** The SDK withholds stdout until tool results; tail task_started files for live output. + * The private Claude layout can change; failures omit live output and retain the final result. */ -/** How often the file is checked while its command runs. */ const CLAUDE_TASK_OUTPUT_POLL_MS = 250; -/** Give up looking for a file Claude Code never wrote (a newer layout, or Windows). */ +/** Bound discovery when Claude never writes the file. */ const MAX_LOCATE_ATTEMPTS = 40; -/** Bytes read per poll. A faster writer skips ahead: only the tail is shown anyway. */ +/** Skip ahead of fast writers; only the tail is displayed. */ const MAX_READ_BYTES = 256 * 1024; /** Claude Code's per-user temp root, or none where it has no uid (Windows). */ @@ -56,12 +47,7 @@ const locate = Effect.fn("ClaudeTaskOutputTail.locate")(function* (input: { return Option.none(); }); -/** - * Reads appended output until `stop` completes, then reads once more so the - * last bytes written before the command exited still reach live viewers. The - * caller completes `stop` when the tool result arrives or the turn ends, and - * awaits the returned effect. - */ +/** Complete stop on tool result or turn end, then await the effect; it performs a final read before returning. */ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(function* (input: { readonly root: string; readonly sessionId: string; @@ -70,7 +56,6 @@ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(funct readonly onChunk: (chunk: string) => Effect.Effect; }) { const fileSystem = yield* FileSystem.FileSystem; - // True once stopped: the next read is the last. const pause = Effect.raceFirst( Effect.sleep(CLAUDE_TASK_OUTPUT_POLL_MS).pipe(Effect.as(false)), Deferred.await(input.stop).pipe(Effect.as(true)), @@ -82,8 +67,6 @@ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(funct if (attempt + 1 >= MAX_LOCATE_ATTEMPTS || (yield* pause)) return; } const filePath = file.value; - // `stream: true` keeps a multi-byte character split across reads intact; - // invalid bytes become U+FFFD. let decoder = new TextDecoder("utf-8", { fatal: false }); let offset = 0; let last = yield* Deferred.isDone(input.stop); @@ -105,7 +88,7 @@ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(funct if (Option.isSome(bytes)) { // Skipped output must not splice two unrelated lines together. const skipped = start > offset; - // Bytes held from before the gap belong to a character we never finished reading. + // Reset partial UTF-8 bytes when skipping output. if (skipped) decoder = new TextDecoder("utf-8", { fatal: false }); offset = start + bytes.value.byteLength; const text = (skipped ? "\n" : "") + decoder.decode(bytes.value, { stream: true }); @@ -113,7 +96,6 @@ export const tailClaudeTaskOutput = Effect.fn("ClaudeTaskOutputTail.tail")(funct } } if (last) { - // A command that ended mid-character still shows a replacement character. const rest = decoder.decode(); if (rest.length > 0) yield* input.onChunk(rest); return; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index a16df458e2043..bd7b6f4208763 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1,5 +1,3 @@ -import * as NodeOS from "node:os"; - import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; import { makeProviderTextDeltaCoalescer, @@ -17,6 +15,7 @@ import { type OrchestrationV2AppThread, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, + type OrchestrationV2RuntimeRequest, type OrchestrationV2TurnItem, ProjectId, type ProviderApprovalDecision, @@ -30,11 +29,9 @@ import { TurnItemId, } from "@t3tools/contracts"; import { assert, describe, it } from "@effect/vitest"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as CodexClient from "effect-codex-app-server/client"; -import * as CodexError from "effect-codex-app-server/errors"; import * as CodexReplay from "effect-codex-app-server/replay"; +import type * as CodexSchema from "effect-codex-app-server/schema"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Crypto from "effect/Crypto"; @@ -45,8 +42,8 @@ import { MCP_APP_OUTPUT_KEY, readMcpAppReference } from "@t3tools/shared/mcpApp" import { resolveAttachmentPathById } from "../../attachmentStore.ts"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; +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 Stream from "effect/Stream"; @@ -54,7 +51,6 @@ import { TestClock } from "effect/testing"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import packageJson from "../../../package.json" with { type: "json" }; -import * as ServerConfig from "../../config.ts"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -67,96 +63,11 @@ import * as CodexAdapterV2 from "./CodexAdapterV2.ts"; import { makeReplayServerConfig, withCodexReplayChildMetadata } from "./CodexAdapterV2.testkit.ts"; import * as CodexAdapterV2Testkit from "./CodexAdapterV2.testkit.ts"; -const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); const replayTranscriptJson = Schema.fromJsonString(CodexReplay.CodexAppServerReplayTranscript); const encodeReplayTranscriptJson = Schema.encodeEffect(replayTranscriptJson); const decodeReplayTranscriptJson = Schema.decodeUnknownEffect(replayTranscriptJson); const encodeStringJson = Schema.encodeEffect(Schema.fromJsonString(Schema.String)); -describe("Codex context usage compatibility", () => { - const previous: ModelSelection = { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-6-astra", - }; - it("retains measured usage for reasoning-only changes in either direction", () => { - const low: ModelSelection = { ...previous, options: [{ id: "reasoningEffort", value: "low" }] }; - assert.isTrue(CodexAdapterV2.canReuseCodexContextUsage(previous, low)); - assert.isTrue(CodexAdapterV2.canReuseCodexContextUsage(low, previous)); - assert.isTrue( - CodexAdapterV2.canReuseCodexContextUsage(low, { - ...low, - options: [{ id: "reasoningEffort", value: "high" }], - }), - ); - }); - it("invalidates usage for model, instance, context-window and unknown option changes", () => { - for (const next of [ - { ...previous, model: "other-model" }, - { ...previous, instanceId: ProviderInstanceId.make("other-codex") }, - { ...previous, options: [{ id: "contextWindow", value: "32k" }] }, - { ...previous, options: [{ id: "customOption", value: "value" }] }, - ]) - assert.isFalse(CodexAdapterV2.canReuseCodexContextUsage(previous, next)); - }); -}); - -describe("CodexAdapterV2 file change approvals", () => { - it("uses nonblank reasons before sorted file operations and renamed paths", () => { - const fileChanges = { - "/tmp/removed.md": { type: "delete" as const, content: "gone" }, - "/tmp/added.ts": { type: "add" as const, content: "export {};" }, - "/tmp/moved.ts": { - type: "update" as const, - unified_diff: "@@", - move_path: "/tmp/renamed.ts", - }, - }; - assert.equal( - CodexAdapterV2.codexFileChangeApprovalPrompt({ - reason: " Update configuration. ", - fileChanges, - }), - "Update configuration.", - ); - assert.equal( - CodexAdapterV2.codexFileChangeApprovalPrompt({ reason: " ", fileChanges }), - "add /tmp/added.ts\nupdate /tmp/moved.ts -> /tmp/renamed.ts\ndelete /tmp/removed.md", - ); - }); - - it("falls back to a nonblank grant root and omits empty details", () => { - assert.equal( - CodexAdapterV2.codexFileChangeApprovalPrompt({ reason: " ", grantRoot: " /workspace " }), - "/workspace", - ); - assert.equal( - CodexAdapterV2.codexFileChangeApprovalPrompt({ fileChanges: {}, grantRoot: "/workspace" }), - "/workspace", - ); - assert.isUndefined( - CodexAdapterV2.codexFileChangeApprovalPrompt({ - reason: " ", - grantRoot: " ", - fileChanges: {}, - }), - ); - }); - - it("bounds large patch descriptions without losing the remaining count", () => { - const fileChanges = Object.fromEntries( - Array.from({ length: 25 }, (_, index) => [ - `/tmp/file-${String(index).padStart(2, "0")}.ts`, - { type: "add" as const, content: "" }, - ]), - ); - const detail = CodexAdapterV2.codexFileChangeApprovalPrompt({ fileChanges }); - assert.equal(detail?.split("\n").length, 21); - assert.isTrue(detail?.startsWith("add /tmp/file-00.ts") ?? false); - assert.isTrue(detail?.endsWith("+5 more") ?? false); - assert.notInclude(detail, "file-20.ts"); - }); -}); - describe("CodexAdapterV2 context usage", () => { it("uses the current context rather than cumulative processed tokens", () => { const usage = CodexAdapterV2.codexProviderTurnTokenUsage( @@ -193,64 +104,6 @@ describe("CodexAdapterV2 context usage", () => { }); describe("CodexAdapterV2 assistant message streaming", () => { - it.effect("makes accumulated assistant text visible after the bounded flush interval", () => - Effect.gen(function* () { - const updates = yield* Ref.make< - ReadonlyArray<{ - readonly turnId: string; - readonly itemId: string; - readonly text: string; - readonly completed: boolean; - }> - >([]); - const coalescer = yield* makeProviderTextDeltaCoalescer({ - flushIntervalMs: 50, - emit: (update) => Ref.update(updates, (current) => [...current, update]), - }); - - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "partial" }); - assert.deepEqual(yield* Ref.get(updates), []); - yield* Effect.yieldNow; - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; - - assert.deepEqual(yield* Ref.get(updates), [ - { - turnId: "turn-1", - itemId: "message-1", - text: "partial", - completed: false, - }, - ]); - }), - ); - - it.effect("coalesces multiple token deltas into one assistant update per interval", () => - Effect.gen(function* () { - const updates = yield* Ref.make>([]); - const coalescer = yield* makeProviderTextDeltaCoalescer({ - flushIntervalMs: 50, - emit: (update) => Ref.update(updates, (current) => [...current, update]), - }); - - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "one" }); - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: " two" }); - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: " three" }); - yield* Effect.yieldNow; - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; - - assert.deepEqual(yield* Ref.get(updates), [ - { - turnId: "turn-1", - itemId: "message-1", - text: "one two three", - completed: false, - }, - ]); - }), - ); - it.effect("flushes buffered text synchronously before item and turn completion", () => Effect.gen(function* () { const updates = yield* Ref.make>([]); @@ -278,122 +131,43 @@ describe("CodexAdapterV2 assistant message streaming", () => { assert.equal((yield* Ref.get(updates)).length, 2); }), ); +}); - it.effect("retains buffered text until completion updates are emitted", () => - Effect.gen(function* () { - const updates = yield* Ref.make>([]); - const failNext = yield* Ref.make(true); - const coalescer = yield* makeProviderTextDeltaCoalescer({ - flushIntervalMs: 50, - emit: (update) => - Ref.getAndSet(failNext, false).pipe( - Effect.flatMap((shouldFail) => - shouldFail - ? Effect.die("projection unavailable") - : Ref.update(updates, (current) => [...current, update]), - ), - ), - }); - - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "turn final" }); - const failedFlush = yield* coalescer.flushTurn("turn-1").pipe(Effect.exit); - assert.equal(failedFlush._tag, "Failure"); - yield* coalescer.flushTurn("turn-1"); - - yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "item final" }); - yield* Ref.set(failNext, true); - const failedComplete = yield* coalescer - .complete({ turnId: "turn-1", itemId: "message-2" }) - .pipe(Effect.exit); - assert.equal(failedComplete._tag, "Failure"); - const completedText = yield* coalescer.complete({ - turnId: "turn-1", - itemId: "message-2", - }); - - assert.equal(completedText, "item final"); - assert.deepEqual(yield* Ref.get(updates), [ - { turnId: "turn-1", itemId: "message-1", text: "turn final", completed: true }, - { turnId: "turn-1", itemId: "message-2", text: "item final", completed: true }, - ]); - }), - ); - - it.effect("can discard an empty completion without emitting an assistant update", () => - Effect.gen(function* () { - const updates = yield* Ref.make>([]); - const coalescer = yield* makeProviderTextDeltaCoalescer({ - flushIntervalMs: 50, - emit: (update) => Ref.update(updates, (current) => [...current, update]), - }); - - yield* coalescer.append({ turnId: "turn-1", itemId: "message-1", delta: "" }); - yield* Effect.yieldNow; - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; - const completedText = yield* coalescer.complete({ - turnId: "turn-1", - itemId: "message-1", - finalText: "", - emitEmpty: false, - }); - - assert.equal(completedText, ""); - assert.deepEqual(yield* Ref.get(updates), []); - - yield* coalescer.append({ turnId: "turn-1", itemId: "message-2", delta: "buffered" }); - assert.equal( - yield* coalescer.complete({ - turnId: "turn-1", - itemId: "message-2", - emitEmpty: false, - }), - "buffered", - ); - assert.deepEqual(yield* Ref.get(updates), [ - { - turnId: "turn-1", - itemId: "message-2", - text: "buffered", - completed: true, - }, - ]); - }), - ); - - it.effect("treats explicit empty final text as authoritative over buffered deltas", () => - Effect.gen(function* () { - const updates = yield* Ref.make>([]); - const coalescer = yield* makeProviderTextDeltaCoalescer({ - flushIntervalMs: 50, - emit: (update) => Ref.update(updates, (current) => [...current, update]), - }); - - yield* coalescer.append({ - turnId: "turn-1", - itemId: "message-1", - delta: "stale buffered text", - }); - const completedText = yield* coalescer.complete({ - turnId: "turn-1", - itemId: "message-1", - finalText: "", - }); +describe("CodexAdapterV2 runtime policy", () => { + it.effect.each([undefined, false, true])( + "selects native collaboration modes without prompt overrides with hasT3Mcp=%s", + (hasT3Mcp) => + Effect.gen(function* () { + for (const interactionMode of ["plan", "default"] as const) { + for (const reasoningEffort of [undefined, "high"] as const) { + const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId: "native-mode-switch", + codexInput: [{ type: "text", text: "test" }], + runtimePolicy: { runtimeMode: "full-access", interactionMode, cwd: null }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + ...(reasoningEffort === undefined + ? {} + : { options: [{ id: "reasoningEffort", value: reasoningEffort }] }), + }, + ...(hasT3Mcp === undefined ? {} : { hasT3Mcp }), + }); - assert.equal(completedText, ""); - assert.deepEqual(yield* Ref.get(updates), [ - { - turnId: "turn-1", - itemId: "message-1", - text: "", - completed: true, - }, - ]); - }), + assert.deepEqual(params.collaborationMode, { + mode: interactionMode, + settings: { + model: "gpt-5.4", + ...(reasoningEffort === undefined ? {} : { reasoning_effort: reasoningEffort }), + }, + }); + assert.equal(params.effort, reasoningEffort); + assert.equal(params.additionalContext !== undefined, hasT3Mcp === true); + } + } + }), ); -}); -describe("CodexAdapterV2 runtime policy", () => { it.effect("derives concrete Codex turn policies from every T3 runtime mode", () => Effect.gen(function* () { const build = ( @@ -433,31 +207,6 @@ describe("CodexAdapterV2 runtime policy", () => { }), ); - it.effect("preserves explicit Codex turn policy overrides", () => - Effect.gen(function* () { - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-override", - codexInput: [{ type: "text", text: "test" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "default", - cwd: null, - approvalPolicy: "on-request", - sandboxPolicy: { - type: "readOnly", - }, - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - }); - - assert.equal(params.approvalPolicy, "on-request"); - assert.equal(params.sandboxPolicy?.type, "readOnly"); - }), - ); - it.effect("sends MCP app model context as untrusted Codex context", () => Effect.gen(function* () { const policy = { runtimeMode: "full-access", interactionMode: "default", cwd: null } as const; @@ -488,4025 +237,1273 @@ describe("CodexAdapterV2 runtime policy", () => { assert.isDefined(withT3.additionalContext?.["t3_code_runtime"]); }), ); +}); - it.effect("adds default-mode developer instructions when the T3 MCP server is attached", () => - Effect.gen(function* () { - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-orchestration-instructions", - codexInput: [{ type: "text", text: "delegate this task" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "default", - cwd: null, - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - hasT3Mcp: true, - }); - - assert.equal(params.collaborationMode?.mode, "default"); - assert.include( - params.additionalContext?.t3_code_orchestration_01?.value ?? "", - "Use `delegate_task`", - ); - assert.include( - params.additionalContext?.t3_code_orchestration_02?.value ?? "", - "structured object, never as JSON text", - ); - }), - ); - - it.effect("omits default-mode collaboration settings without the T3 MCP server", () => - Effect.gen(function* () { - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-default-without-t3-mcp", - codexInput: [{ type: "text", text: "implement this task" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "default", - cwd: null, - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - hasT3Mcp: false, - }); - - assert.isUndefined(params.collaborationMode); - }), - ); - - it.effect("adds T3 plan-mode developer instructions when the T3 MCP server is attached", () => +describe("CodexAdapterV2 native protocol logging", () => { + it.effect("logs decoded app-server frames once with credentials redacted", () => Effect.gen(function* () { - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-plan-with-t3-mcp", - codexInput: [{ type: "text", text: "plan this task" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "plan", - cwd: null, - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - hasT3Mcp: true, + const writes: Array<{ + readonly event: unknown; + readonly threadId: ThreadId | null; + }> = []; + const logger: ProviderEventLoggers.EventNdjsonLogger = { + filePath: "/tmp/events.log", + write: (event, threadId) => + Effect.sync(() => { + writes.push({ event, threadId }); + }), + close: () => Effect.void, + }; + const threadId = ThreadId.make("thread-1"); + const providerSessionId = ProviderSessionId.make("provider-session-1"); + const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({ + nativeEventLogger: logger, + threadId, + providerSessionId, }); - assert.equal(params.collaborationMode?.mode, "plan"); - assert.include( - params.collaborationMode?.settings.developer_instructions ?? "", - "request_user_input", - ); - assert.include(params.additionalContext?.t3_code_tools?.value ?? "", "preview_status"); - }), - ); + assert.notEqual(protocolLogger, undefined); + if (protocolLogger === undefined) { + return; + } - it.effect("keeps Codex in plan mode without referencing unavailable T3 MCP tools", () => - Effect.gen(function* () { - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-plan-without-t3-mcp", - codexInput: [{ type: "text", text: "plan this task" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "plan", - cwd: null, - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", + yield* protocolLogger({ + direction: "incoming", + stage: "decoded", + payload: { + method: "thread/event", + params: { + id: "evt-1", + http_headers: { Authorization: "Bearer secret-codex-token" }, + usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, + }, }, - hasT3Mcp: false, }); - - assert.equal(params.collaborationMode?.mode, "plan"); - assert.notProperty(params.collaborationMode?.settings, "developer_instructions"); - }), - ); - - it.effect("compiles per-turn Codex model options and cwd from their owning inputs", () => - Effect.gen(function* () { - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-model-options", - codexInput: [{ type: "text", text: "test" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "plan", - cwd: "/workspace/model-options", - reasoningEffort: "low", - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - options: [ - { id: "reasoningEffort", value: "xhigh" }, - { id: "serviceTier", value: "priority" }, - ], - }, + yield* protocolLogger({ + direction: "incoming", + stage: "raw", + payload: + '{"method":"thread/event","params":{"http_headers":{"Authorization":"Bearer secret-codex-token"}}}\n', }); - assert.equal(params.model, "gpt-5.4"); - assert.equal(params.effort, "xhigh"); - assert.equal(params.serviceTier, "priority"); - assert.equal(params.cwd, "/workspace/model-options"); - assert.equal(params.collaborationMode?.settings.model, "gpt-5.4"); - assert.equal(params.collaborationMode?.settings.reasoning_effort, "xhigh"); - - const managed = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId: "native-model-options", - codexInput: [{ type: "text", text: "test" }], - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace/model-options", - }, - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - options: [{ id: "serviceTier", value: "priority" }], + assert.equal(writes.length, 1); + assert.equal(writes[0]?.threadId, threadId); + assert.deepEqual(writes[0]?.event, { + provider: "codex", + protocol: "codex.app-server", + kind: "protocol", + providerSessionId, + event: { + direction: "incoming", + stage: "decoded", + payload: { + method: "thread/event", + params: { + id: "evt-1", + http_headers: { Authorization: "[REDACTED]" }, + usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, + }, + }, }, - omitServiceTier: true, }); - assert.equal(managed.serviceTier, undefined); }), ); }); -describe("CodexAdapterV2 process spawning", () => { - it("injects cwd, model, and MCP authorization into thread-scoped params", () => { - const threadId = ThreadId.make("thread-codex-mcp"); - const mcpSession = { - environmentId: EnvironmentId.make("environment-codex-mcp"), - threadId, - providerSessionId: "mcp-session-codex", - providerInstanceId: ProviderInstanceId.make("codex"), - endpoint: "http://127.0.0.1:43123/mcp", - authorizationHeader: "Bearer secret-codex-token", - browserToolsAvailable: true, - }; - - assert.deepEqual( - CodexAdapterV2.codexThreadRuntimeParams({ - mcpSession, - modelSelection: { model: "gpt-5.4" }, - runtimePolicy: { - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace/thread-codex-mcp", +describe("CodexAdapterV2 rollback mapping", () => { + it.effect("derives native rollback count from durable provider turns", () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback"); + const providerThread: OrchestrationV2ProviderThread = { + id: providerThreadId, + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + providerInstanceId: ProviderInstanceId.make("codex"), + providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"), + appThreadId: ThreadId.make("thread-codex-rollback"), + ownerNodeId: null, + nativeThreadRef: { + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeId: "native-thread-codex-rollback", + strength: "strong", }, - }), - { - cwd: "/workspace/thread-codex-mcp", - model: "gpt-5.4", - config: { - "tools.update_plan.enabled": true, - // Codex waits up to 10 s, not 1 s, for MCP servers before the first request (#13437). - mcp_optional_startup_grace_ms: 10_000, - mcp_servers: { - "t3-code": { - url: "http://127.0.0.1:43123/mcp", - tool_timeout_sec: 3_900, - http_headers: { - Authorization: "Bearer secret-codex-token", - }, - }, - }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 3, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const providerTurn = ( + id: string, + ordinal: number, + status: OrchestrationV2ProviderTurn["status"], + ): OrchestrationV2ProviderTurn => ({ + id: ProviderTurnId.make(id), + providerThreadId, + nodeId: NodeId.make(`node-${id}`), + runAttemptId: RunAttemptId.make(`run-attempt-${id}`), + nativeTurnRef: { + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeId: `native-${id}`, + strength: "strong", }, - }, - ); - }); - - it.effect("resolves Windows command shims through the shared spawn policy", () => - Effect.gen(function* () { - const command = yield* CodexAdapterV2.makeCodexAppServerSpawnCommand({ - command: "codex", - args: ["app-server", "argument with spaces"], - cwd: "C:\\workspace", - env: { CUSTOM: "1" }, - extendEnv: true, - }); - - assert.isTrue(ChildProcess.isStandardCommand(command)); - if (!ChildProcess.isStandardCommand(command)) { - return; - } - assert.equal( - command.command, - '^"C:\\npm\\codex.cmd^" ^"app-server^" ^"argument^ with^ spaces^"', - ); - assert.deepEqual(command.args, []); - assert.equal(command.options.shell, true); - assert.equal(command.options.cwd, "C:\\workspace"); - assert.deepEqual(command.options.env, { CUSTOM: "1" }); - assert.equal(command.options.extendEnv, true); - }).pipe( - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(HostProcess.Environment, { - PATH: "C:\\Windows\\System32", - HOST_ONLY: "1", - }), - Effect.provideService(SpawnExecutableResolution, (_command, _platform, environment) => { - assert.equal(environment.HOST_ONLY, "1"); - assert.equal(environment.CUSTOM, "1"); - return "C:\\npm\\codex.cmd"; - }), - ), - ); - - it.effect("uses direct execution for native executables", () => - Effect.gen(function* () { - const command = yield* CodexAdapterV2.makeCodexAppServerSpawnCommand({ - command: "codex.exe", - args: ["app-server"], - }); - - assert.isTrue(ChildProcess.isStandardCommand(command)); - if (!ChildProcess.isStandardCommand(command)) { - return; - } - assert.equal(command.command, "C:\\bin\\codex.exe"); - assert.deepEqual(command.args, ["app-server"]); - assert.equal(command.options.shell, false); - }).pipe( - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => "C:\\bin\\codex.exe"), - ), - ); - - it.effect("launches the app-server with the configured launch arguments", () => - Effect.gen(function* () { - const spawnedArgs: Array> = []; - const spawner = ChildProcessSpawner.make((command) => { - if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args); - return Effect.fail( - PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }), - ); - }); - const factory = yield* CodexAdapterV2.CodexAppServerClientFactory.pipe( - Effect.provide(CodexAdapterV2.layerAppServerClientFactory), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ); - const open = (environment: NodeJS.ProcessEnv) => - factory - .open({ - instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, - threadId: ThreadId.make("thread-launch-args"), - providerSessionId: ProviderSessionId.make("provider-session-launch-args"), - runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", - }), - settings: { - ...DEFAULT_CODEX_SETTINGS, - launchArgs: " --strict-config -c model_reasoning_summary=detailed ", - }, - environment, - }) - .pipe(Effect.scoped, Effect.exit); - - yield* open({}); - yield* open({ T3CODE_CODEX_LAUNCH_ARGS: " --enable env-feature " }); - - assert.deepEqual(spawnedArgs, [ - ["app-server", "--strict-config", "-c", "model_reasoning_summary=detailed"], - ["app-server", "--enable", "env-feature"], - ]); - }).pipe(Effect.provideService(HostProcess.Platform, "linux")), - ); - - it.effect("expands ~ in the configured binary path before spawning", () => - Effect.gen(function* () { - const spawnedCommands: Array = []; - const spawner = ChildProcessSpawner.make((command) => { - if (ChildProcess.isStandardCommand(command)) spawnedCommands.push(command.command); - return Effect.fail( - PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }), - ); + ordinal, + status, + startedAt: now, + completedAt: status === "running" || status === "pending" ? null : now, }); - const path = yield* Path.Path; - const adapter = yield* CodexAdapterV2.createCodexAdapterV2({ - instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, - displayName: undefined, - environment: [], - enabled: true, - config: { ...DEFAULT_CODEX_SETTINGS, binaryPath: "~/bin/codex" }, - }).pipe( - Effect.provide( - Layer.mergeAll( - CodexAdapterV2.layerAppServerClientFactory, - ServerConfig.layerTest(process.cwd(), { prefix: "t3-codex-binary-home-" }), - ), - ), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ); - - yield* adapter - .openSession({ - threadId: ThreadId.make("thread-binary-home"), - providerSessionId: ProviderSessionId.make("provider-session-binary-home"), - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }) - .pipe(Effect.scoped, Effect.exit); - - assert.deepEqual(spawnedCommands, [path.join(NodeOS.homedir(), "bin", "codex")]); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - Effect.provideService(HostProcess.Platform, "linux"), - ), - ); -}); + const firstTurn = providerTurn("provider-turn-first", 1, "completed"); + const secondTurn = providerTurn("provider-turn-second", 2, "completed"); + const runningTurn = providerTurn("provider-turn-running", 3, "running"); + const interruptedTurn = providerTurn("provider-turn-interrupted", 4, "interrupted"); + const goalCommandTurn = { + ...providerTurn("provider-turn-goal-command", 5, "completed"), + nativeTurnRef: null, + }; -describe("CodexAdapterV2 dynamic tool projection", () => { - it.effect("keeps a failed Sky MCP call in Computer Use when its error has no metadata", () => - Effect.gen(function* () { - const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "mcpToolCall", - id: "failed-sky-js", - server: "node_repl", - tool: "js", - status: "failed", - arguments: { - title: "Restrict the breakpoint to Git actions", - code: "await sky.type_text({app:'T3 Code (Nightly)',text:'debug(ga.run)'});", + const numTurns = yield* CodexAdapterV2.resolveCodexRollbackTurnCount({ + providerThread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint-first"), + appRunOrdinal: 1, + providerTurn: firstTurn, }, - result: { content: [{ type: "text", text: "Illegal Unicode escape sequence" }] }, - }); - assert.equal(projection.title, "Restrict the breakpoint to Git actions"); - assert.equal(projection.toolSurface, "computer"); - assert.deepEqual(projection.toolSource, { - key: "computer-use", - name: "Computer Use", - kind: "computer", + providerThreadTurns: [goalCommandTurn, interruptedTurn, runningTurn, secondTurn, firstTurn], }); - }).pipe(Effect.provide(NodeServices.layer)), - ); - it.effect.each(["inProgress", "completed", "failed"] as const)( - "preserves a bare js action's title and computer surface when %s without result metadata", - (status) => - Effect.gen(function* () { - const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "dynamicToolCall", - id: "bare-js", - tool: "js", - status, - arguments: { code: "await sky.get_app_state(app);", title: "Read the desktop window" }, - contentItems: [], - success: status !== "failed", - }); - assert.equal(projection.title, "Read the desktop window"); - assert.equal(projection.toolSurface, "computer"); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect.each(["cua_repl", "node_repl"])( - "uses the %s call title while leaving other MCP titles as tool arguments", - (server) => - Effect.gen(function* () { - const call = { - type: "mcpToolCall" as const, - id: "inspect", - server, - tool: "js", - status: "completed" as const, - arguments: { - code: "await game.getAXStateAndScreenshot();", - title: "Inspect Saga music screen", - }, - result: { content: [] }, - }; - assert.equal( - (yield* CodexAdapterV2.projectCodexDynamicToolItem(call)).title, - "Inspect Saga music screen", - ); - assert.equal( - (yield* CodexAdapterV2.projectCodexDynamicToolItem({ - ...call, - arguments: { title: " " }, - })).title, - server === "cua_repl" ? "Computer use" : "Run JavaScript", - ); - assert.equal( - (yield* CodexAdapterV2.projectCodexDynamicToolItem({ ...call, server: "github" })).title, - "js", - ); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect.each(["inProgress", "completed", "failed"] as const)( - "presents ordinary MCP calls when %s", - (status) => - Effect.gen(function* () { - const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "mcpToolCall", - id: "weather-call", - server: "weather", - tool: "get_weather", - status, - arguments: { city: "Berlin" }, - }); - assert.equal(projection.title, "get weather"); - assert.deepEqual(projection.toolSource, { - key: "mcp:weather", - name: "weather", - kind: "integration", - }); - assert.deepEqual(projection.input, { city: "Berlin" }); - }).pipe(Effect.provide(NodeServices.layer)), + assert.equal(numTurns, 2); + }), ); +}); - it.effect("uses Codex connector names without reading a display title from arguments", () => - Effect.gen(function* () { - const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "mcpToolCall", - id: "connector-call", - server: "_apps", - tool: "connector_get_weather", - status: "completed", - arguments: { title: "Argument, not display metadata" }, - appContext: { - connectorId: "weather-app", - appName: "Weather", - actionName: "Check weather", - }, - result: { - content: [], - _meta: { source: { logoUrl: "https://example.com/weather.png" } }, - }, - }); - assert.equal(projection.title, "Check weather"); - assert.equal(projection.toolSource?.name, "Weather"); - assert.deepEqual(projection.toolIcon, { - _tag: "themed-logo", - logoUrl: "https://example.com/weather.png", - }); - assert.deepEqual(projection.toolSource?.icon, projection.toolIcon); - }).pipe(Effect.provide(NodeServices.layer)), - ); +describe("CodexAdapterV2 fork boundary", () => { + const providerThreadId = ProviderThreadId.make("provider-thread-codex-fork-boundary"); + const makeProviderThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({ + id: providerThreadId, + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + providerInstanceId: ProviderInstanceId.make("codex"), + providerSessionId: ProviderSessionId.make("provider-session-codex-fork-boundary"), + appThreadId: ThreadId.make("thread-codex-fork-boundary"), + ownerNodeId: null, + nativeThreadRef: { + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeId: "native-thread-codex-fork-boundary", + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 2, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }); + const makeProviderTurn = ( + id: string, + ordinal: number, + nativeId: string | null, + now: DateTime.Utc, + ): OrchestrationV2ProviderTurn => ({ + id: ProviderTurnId.make(id), + providerThreadId, + nodeId: NodeId.make(`node-${id}`), + runAttemptId: RunAttemptId.make(`run-attempt-${id}`), + nativeTurnRef: + nativeId === null + ? { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeId: null, strength: "none" } + : { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeId, strength: "strong" }, + ordinal, + status: "completed", + startedAt: now, + completedAt: now, + }); - it.effect("preserves native browser and app icons alongside MCP tool output", () => + it.effect("resolves the selected provider turn to an inclusive native fork boundary", () => Effect.gen(function* () { - const browser = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "mcpToolCall", - id: "browser", - server: "browser", - tool: "open", - status: "completed", - arguments: {}, - result: { - content: [], - _meta: { - "codex/toolSurface": { - kind: "browserUse", - browserFamily: "Chrome", - screenshot: { - pageUrl: "https://example.com/docs", - faviconUrl: "https://example.com/icon.png", - }, - }, - }, - }, - }); - assert.equal(browser.toolSurface, "browser"); - assert.deepEqual(browser.toolIcon, { - _tag: "website", - pageUrl: "https://example.com/docs", - faviconUrl: "https://example.com/icon.png", - }); - assert.equal(browser.toolSource?.name, "Chrome"); - const app = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "mcpToolCall", - id: "app", - server: "computer", - tool: "click", - status: "completed", - arguments: {}, - result: { - content: [], - _meta: { - "codex/toolSurface": { - kind: "computerUse", - app: { kind: "appId", appId: "com.apple.finder" }, - }, - }, - }, - }); - assert.deepEqual(app.toolIcon, { - _tag: "native-app", - app: { _tag: "app-id", appId: "com.apple.finder" }, - }); - assert.equal(app.toolSource?.name, "Finder"); - }).pipe(Effect.provide(NodeServices.layer)), - ); + const now = yield* DateTime.now; + const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now); + const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now); - it.effect("preserves MCP arguments and prefers structured output", () => - Effect.gen(function* () { - const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "mcpToolCall", - id: "call-create-threads", - server: "t3-code", - tool: "create_threads", - status: "completed", - arguments: { - threads: [{ title: "Fixture child", prompt: "fixture child prompt" }], - }, - result: { - content: [{ type: "text", text: '{"threads":[{"threadId":"thread:mcp:fixture:0"}]}' }], - structuredContent: { - threads: [{ threadId: "thread:mcp:fixture:0" }], - }, - }, + const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ + sourceProviderThread: makeProviderThread(now), + sourceProviderTurns: [firstTurn, secondTurn], + providerTurnId: firstTurn.id, + targetThreadId: ThreadId.make("thread-codex-fork-target"), }); - assert.deepEqual(projection, { - toolName: "t3-code.create_threads", - input: { - threads: [{ title: "Fixture child", prompt: "fixture child prompt" }], - }, - output: { - threads: [{ threadId: "thread:mcp:fixture:0" }], - }, - status: "completed", + assert.deepEqual(boundary, { + lastTurnId: "native-turn-first", + rollbackTurnCount: 0, }); - }).pipe(Effect.provide(NodeServices.layer)), + }), ); - it.effect("preserves namespaced dynamic tool output", () => + it.effect("keeps the rollback-count fallback when the boundary turn lacks a native id", () => Effect.gen(function* () { - const projection = yield* CodexAdapterV2.projectCodexDynamicToolItem({ - type: "dynamicToolCall", - id: "call-dynamic", - namespace: "workspace", - tool: "inspect", - status: "failed", - arguments: { path: "package.json" }, - contentItems: [{ type: "inputText", text: "inspection failed" }], - success: false, - }); + const now = yield* DateTime.now; + const firstTurn = makeProviderTurn("provider-turn-first", 1, null, now); + const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now); - assert.deepEqual(projection, { - toolName: "workspace.inspect", - input: { path: "package.json" }, - output: [{ type: "inputText", text: "inspection failed" }], - status: "failed", + const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ + sourceProviderThread: makeProviderThread(now), + sourceProviderTurns: [firstTurn, secondTurn], + providerTurnId: firstTurn.id, + targetThreadId: ThreadId.make("thread-codex-fork-target"), }); - }).pipe(Effect.provide(NodeServices.layer)), + + assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 1 }); + }), ); }); -describe("CodexAdapterV2 native protocol logging", () => { - it.effect("logs decoded app-server frames once with credentials redacted", () => - Effect.gen(function* () { - const writes: Array<{ - readonly event: unknown; - readonly threadId: ThreadId | null; - }> = []; - const logger: ProviderEventLoggers.EventNdjsonLogger = { - filePath: "/tmp/events.log", - write: (event, threadId) => - Effect.sync(() => { - writes.push({ event, threadId }); - }), - close: () => Effect.void, - }; - const threadId = ThreadId.make("thread-1"); - const providerSessionId = ProviderSessionId.make("provider-session-1"); - const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({ - nativeEventLogger: logger, - threadId, - providerSessionId, - }); +const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({}); +const CODEX_TEST_MODEL_SELECTION = { + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + model: "gpt-5.4", +} satisfies ModelSelection; +const CODEX_TEST_RUNTIME_POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: "/workspace", +}); - assert.notEqual(protocolLogger, undefined); - if (protocolLogger === undefined) { - return; - } +function makeCodexTestAppThread(input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly now: DateTime.Utc; +}): OrchestrationV2AppThread { + return { + createdBy: "user", + creationSource: "web", + id: input.threadId, + projectId: ProjectId.make(`project-${input.threadId}`), + title: "Codex continuation test", + providerInstanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: input.providerThread.id, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: input.threadId, + }, + forkedFrom: null, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; +} - yield* protocolLogger({ - direction: "incoming", - stage: "decoded", - payload: { - method: "thread/event", - params: { - id: "evt-1", - http_headers: { Authorization: "Bearer secret-codex-token" }, - usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, - }, - }, - }); - yield* protocolLogger({ - direction: "incoming", - stage: "raw", - payload: - '{"method":"thread/event","params":{"http_headers":{"Authorization":"Bearer secret-codex-token"}}}\n', - }); +function makeCodexTestTurnInput(input: { + readonly threadId: ThreadId; + readonly providerThread: OrchestrationV2ProviderThread; + readonly now: DateTime.Utc; + readonly attemptId: RunAttemptId; + readonly text: string; +}): ProviderAdapter.ProviderAdapterV2TurnInput { + return { + appThread: makeCodexTestAppThread(input), + threadId: input.threadId, + runId: RunId.make(`run-${input.attemptId}`), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: input.attemptId, + rootNodeId: NodeId.make(`node-${input.attemptId}`), + providerThread: input.providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`message-${input.attemptId}`), + text: input.text, + attachments: [], + }, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }; +} - assert.equal(writes.length, 1); - assert.equal(writes[0]?.threadId, threadId); - assert.deepEqual(writes[0]?.event, { - provider: "codex", - protocol: "codex.app-server", - kind: "protocol", - providerSessionId, - event: { - direction: "incoming", - stage: "decoded", - payload: { - method: "thread/event", - params: { - id: "evt-1", - http_headers: { Authorization: "[REDACTED]" }, - usage: { inputTokens: 12, outputTokens: 8, totalTokens: 20 }, +function makeCodexReplayTurn(input: { + readonly id: string; + readonly status: "inProgress" | "completed" | "interrupted" | "failed"; +}): Record { + const terminal = + input.status === "completed" || input.status === "interrupted" || input.status === "failed"; + return { + id: input.id, + items: [], + itemsView: "notLoaded", + status: input.status, + error: null, + startedAt: 1782622440, + completedAt: terminal ? 1782622450 : null, + durationMs: null, + }; +} + +function codexReplayPreamble(input: { + readonly nativeThreadId: string; + readonly nativeTurnId: string; + readonly prompt: string; + readonly sentPrompt?: string; +}): Array { + return [ + { + type: "expect_outbound", + label: "initialize", + frame: { + id: 1, + method: "initialize", + params: { + clientInfo: { name: "T3 Code", title: "T3 Code", version: packageJson.version }, + capabilities: { + experimentalApi: true, + optOutNotificationMethods: ["turn/diff/updated"], + extensions: { + "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] }, }, }, }, - }); - }), - ); - - it.effect("filters streaming frames before redaction without losing decode failures", () => - Effect.gen(function* () { - const writes: Array = []; - const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({ - nativeEventLogger: { - filePath: "/tmp/events.log", - write: (event) => - Effect.sync(() => { - writes.push(event); - }), - close: () => Effect.void, + }, + }, + { + type: "emit_inbound", + label: "initialize", + frame: { + id: 1, + result: { + userAgent: "T3 Code/0.156.1", + codexHome: "/tmp/codex-home", + platformFamily: "unix", + platformOs: "macos", }, - threadId: ThreadId.make("thread-1"), - providerSessionId: ProviderSessionId.make("provider-session-1"), - }); - assert.exists(protocolLogger); - if (protocolLogger === undefined) return; - - yield* protocolLogger({ - direction: "incoming", - stage: "decoded", - payload: { - method: "item/agentMessage/delta", - get params() { - throw new Error("delta must not be copied"); + }, + }, + { type: "expect_outbound", label: "initialized", frame: { method: "initialized" } }, + { + type: "expect_outbound", + label: "thread/start", + frame: { + id: 2, + method: "thread/start", + params: { config: CodexAdapterV2.CODEX_THREAD_CONFIG }, + }, + }, + { + type: "emit_inbound", + label: "thread/start", + frame: { + id: 2, + result: { + thread: { + id: input.nativeThreadId, + sessionId: input.nativeThreadId, + forkedFromId: null, + preview: "", + ephemeral: false, + modelProvider: "openai", + createdAt: 1782622440, + updatedAt: 1782622440, + status: { type: "idle" }, + path: `/tmp/${input.nativeThreadId}.jsonl`, + cwd: "/workspace", + cliVersion: "0.144.0", + source: "vscode", + threadSource: null, + agentNickname: null, + agentRole: null, + gitInfo: null, + name: null, + turns: [], }, + model: "gpt-5.4", + modelProvider: "openai", + serviceTier: null, + cwd: "/workspace", + instructionSources: [], + approvalPolicy: "on-request", + approvalsReviewer: "user", + sandbox: { type: "workspaceWrite", writableRoots: [], networkAccess: false }, + reasoningEffort: "medium", }, - }); - yield* protocolLogger({ - direction: "incoming", - stage: "raw", - get payload() { - throw new Error("raw frame must not be parsed"); + }, + }, + { + type: "expect_outbound", + label: "turn/start", + frame: { + id: 3, + method: "turn/start", + params: { + threadId: input.nativeThreadId, + input: [{ type: "text", text: input.sentPrompt ?? input.prompt }], + cwd: "/workspace", + model: "gpt-5.4", + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, + summary: "detailed", + collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, }, - }); - yield* protocolLogger({ - direction: "incoming", - stage: "decode_failed", - payload: { operation: "decode", method: "turn/completed", issueCount: 1 }, - }); + }, + }, + { + type: "emit_inbound", + label: "turn/start", + frame: { + id: 3, + result: { turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }) }, + }, + }, + { + type: "emit_inbound", + label: "turn/started", + frame: { + method: "turn/started", + params: { + threadId: input.nativeThreadId, + turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }), + }, + }, + }, + ]; +} - assert.equal(writes.length, 1); - assert.nestedPropertyVal(writes[0], "event.stage", "decode_failed"); - assert.nestedPropertyVal(writes[0], "event.payload.method", "turn/completed"); - }), - ); +function makeCodexReplayTranscript(input: { + readonly scenario: string; + readonly entries: ReadonlyArray; +}): CodexReplay.CodexAppServerReplayTranscript { + return { + provider: "codex", + protocol: "codex.app-server", + version: "0.144.0", + scenario: input.scenario, + entries: input.entries, + }; +} + +function withReplayRequestId( + entry: CodexReplay.CodexAppServerReplayEntry, + id: number, +): CodexReplay.CodexAppServerReplayEntry { + return entry.type !== "runtime_exit" && Predicate.isObject(entry.frame) + ? { ...entry, frame: { ...entry.frame, id } } + : entry; +} - it.effect("retains redacted failures when large payloads are summarized", () => +describe("CodexAdapterV2 session initialize", () => { + const openReplaySession = ( + transcript: CodexReplay.CodexAppServerReplayTranscript, + beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"], + ) => Effect.gen(function* () { - const writes: Array = []; - const protocolLogger = CodexAdapterV2.makeCodexAppServerProtocolLogger({ - nativeEventLogger: { - filePath: "/tmp/events.log", - write: (event) => - Effect.sync(() => { - writes.push(event); - }), - close: () => Effect.void, + const driver = yield* CodexReplay.makeReplayDriver( + transcript, + beforeEmitInbound === undefined ? {} : { beforeEmitInbound }, + ); + let initializeRequests = 0; + const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CODEX_SETTINGS, + environment: {}, + clientFactory: { + open: (openInput) => + Layer.build(CodexReplay.layerReplayWithDriver(driver)).pipe( + Effect.flatMap((context) => + Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)), + ), + Effect.map( + (client) => + ({ + ...client, + request: (method, params) => + Effect.sync(() => { + if (method === "initialize") initializeRequests++; + }).pipe(Effect.andThen(client.request(method, params))), + }) satisfies CodexClient.CodexAppServerClient["Service"], + ), + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterOpenSessionError({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + providerSessionId: openInput.providerSessionId, + cause, + }), + ), + ), }, - threadId: ThreadId.make("thread-1"), - providerSessionId: ProviderSessionId.make("provider-session-1"), + crypto: yield* Crypto.Crypto, + fileSystem: yield* FileSystem.FileSystem, + idAllocator: yield* IdAllocator.IdAllocatorV2, + serverConfig: yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie), }); - assert.exists(protocolLogger); - if (protocolLogger === undefined) return; - - yield* protocolLogger({ - direction: "incoming", - stage: "decoded", - payload: { - method: "error", - params: { - threadId: "native-thread", - turnId: "native-turn", - error: { - code: "unauthorized", - message: '{"message":"Unauthorized","Authorization":"Bearer secret-token"}', - }, - history: "x".repeat(128 * 1_024), - }, - }, + const runtime = yield* adapter.openSession({ + threadId: ThreadId.make(`thread-${transcript.scenario}`), + providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`), + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }); + return { + ensureThread: (threadId: string) => + runtime.ensureThread({ + threadId: ThreadId.make(threadId), + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }), + initializeRequests: () => initializeRequests, + }; + }); - const serialized = encodeUnknownJson(writes); - assert.equal(writes.length, 1); - assert.isBelow(serialized.length, 2_048); - assert.notInclude(serialized, "secret-token"); - assert.include(serialized, "[REDACTED]"); - assert.nestedPropertyVal(writes[0], "event.payload.params.error.code", "unauthorized"); - assert.nestedPropertyVal(writes[0], "event.payload.params.turnId", "native-turn"); - }), - ); -}); + const replayPreamble = (nativeThreadId: string) => + codexReplayPreamble({ nativeThreadId, nativeTurnId: "unused", prompt: "unused" }); -describe("CodexAdapterV2 rollback mapping", () => { - it.effect("derives native rollback count from durable provider turns", () => + it.effect("sends one initialize when two threads start on a fresh session at once", () => Effect.gen(function* () { - const now = yield* DateTime.now; - const providerThreadId = ProviderThreadId.make("provider-thread-codex-rollback"); - const providerThread: OrchestrationV2ProviderThread = { - id: providerThreadId, - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - providerInstanceId: ProviderInstanceId.make("codex"), - providerSessionId: ProviderSessionId.make("provider-session-codex-rollback"), - appThreadId: ThreadId.make("thread-codex-rollback"), - ownerNodeId: null, - nativeThreadRef: { - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeId: "native-thread-codex-rollback", - strength: "strong", - }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: 1, - lastRunOrdinal: 3, - handoffIds: [], - forkedFrom: null, - createdAt: now, - updatedAt: now, - }; - const providerTurn = ( - id: string, - ordinal: number, - status: OrchestrationV2ProviderTurn["status"], - ): OrchestrationV2ProviderTurn => ({ - id: ProviderTurnId.make(id), - providerThreadId, - nodeId: NodeId.make(`node-${id}`), - runAttemptId: RunAttemptId.make(`run-attempt-${id}`), - nativeTurnRef: { - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeId: `native-${id}`, - strength: "strong", - }, - ordinal, - status, - startedAt: now, - completedAt: status === "running" || status === "pending" ? null : now, - }); - const firstTurn = providerTurn("provider-turn-first", 1, "completed"); - const secondTurn = providerTurn("provider-turn-second", 2, "completed"); - const runningTurn = providerTurn("provider-turn-running", 3, "running"); - const interruptedTurn = providerTurn("provider-turn-interrupted", 4, "interrupted"); - const goalCommandTurn = { - ...providerTurn("provider-turn-goal-command", 5, "completed"), - nativeTurnRef: null, - }; + const initializeAwaitingResponse = yield* Deferred.make(); + const releaseInitialize = yield* Deferred.make(); + // Codex rejects a second initialize; the replay permits one handshake. + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "concurrent-initialize", + entries: [ + ...replayPreamble("concurrent-first").slice(0, 5), + ...replayPreamble("concurrent-second") + .slice(3, 5) + .map((entry) => withReplayRequestId(entry, 3)), + ], + }), + (entry) => + entry.label === "initialize" + ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe( + Effect.andThen(Deferred.await(releaseInitialize)), + ) + : Effect.void, + ); - const numTurns = yield* CodexAdapterV2.resolveCodexRollbackTurnCount({ - providerThread, - target: { - type: "provider_turn", - checkpointId: CheckpointId.make("checkpoint-first"), - appRunOrdinal: 1, - providerTurn: firstTurn, - }, - providerThreadTurns: [goalCommandTurn, interruptedTurn, runningTurn, secondTurn, firstTurn], - }); + const first = yield* session + .ensureThread("thread-concurrent-first") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(initializeAwaitingResponse); + const second = yield* session + .ensureThread("thread-concurrent-second") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(releaseInitialize, undefined); - assert.equal(numTurns, 2); - }), + const providerThreads = [yield* Fiber.join(first), yield* Fiber.join(second)]; + assert.equal(session.initializeRequests(), 1); + assert.sameMembers( + providerThreads.map((providerThread) => providerThread.nativeThreadRef?.nativeId), + ["concurrent-first", "concurrent-second"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), ); -}); -describe("CodexAdapterV2 fork boundary", () => { - const providerThreadId = ProviderThreadId.make("provider-thread-codex-fork-boundary"); - const makeProviderThread = (now: DateTime.Utc): OrchestrationV2ProviderThread => ({ - id: providerThreadId, - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - providerInstanceId: ProviderInstanceId.make("codex"), - providerSessionId: ProviderSessionId.make("provider-session-codex-fork-boundary"), - appThreadId: ThreadId.make("thread-codex-fork-boundary"), - ownerNodeId: null, - nativeThreadRef: { - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeId: "native-thread-codex-fork-boundary", - strength: "strong", - }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: 1, - lastRunOrdinal: 2, - handoffIds: [], - forkedFrom: null, - createdAt: now, - updatedAt: now, - }); - const makeProviderTurn = ( - id: string, - ordinal: number, - nativeId: string | null, - now: DateTime.Utc, - ): OrchestrationV2ProviderTurn => ({ - id: ProviderTurnId.make(id), - providerThreadId, - nodeId: NodeId.make(`node-${id}`), - runAttemptId: RunAttemptId.make(`run-attempt-${id}`), - nativeTurnRef: - nativeId === null - ? { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeId: null, strength: "none" } - : { driver: CodexAdapterV2.CODEX_DRIVER_KIND, nativeId, strength: "strong" }, - ordinal, - status: "completed", - startedAt: now, - completedAt: now, - }); - - it.effect("resolves the selected provider turn to an inclusive native fork boundary", () => + // regression: #16260 one-shot initializers raced; a failed handshake must be retried + it.effect("retries initialize after a failed handshake", () => Effect.gen(function* () { - const now = yield* DateTime.now; - const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now); - const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now); - - const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ - sourceProviderThread: makeProviderThread(now), - sourceProviderTurns: [firstTurn, secondTurn], - providerTurnId: firstTurn.id, - targetThreadId: ThreadId.make("thread-codex-fork-target"), - }); + const preamble = replayPreamble("initialize-retry"); + const entries: Array = [ + ...preamble.slice(0, 1), + { + type: "emit_inbound", + label: "initialize", + frame: { id: 1, error: { code: -32603, message: "Codex is not ready." } }, + }, + ...preamble.slice(0, 2).map((entry) => withReplayRequestId(entry, 2)), + ...preamble.slice(2, 3), + ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), + ]; + const session = yield* openReplaySession( + makeCodexReplayTranscript({ scenario: "initialize-retry", entries }), + ); - assert.deepEqual(boundary, { - lastTurnId: "native-turn-first", - rollbackTurnCount: 0, - }); - }), + const failure = yield* session.ensureThread("thread-initialize-retry").pipe(Effect.flip); + assert.equal(failure._tag, "ProviderAdapterEnsureThreadError"); + const providerThread = yield* session.ensureThread("thread-initialize-retry"); + assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-retry"); + assert.equal(session.initializeRequests(), 2); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), ); - it.effect("resolves the latest source turn to a native fork boundary without rollback", () => + it.effect("completes the handshake after a caller is interrupted mid-initialize", () => Effect.gen(function* () { - const now = yield* DateTime.now; - const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now); - const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now); + const initializeAwaitingResponse = yield* Deferred.make(); + const releaseInitialize = yield* Deferred.make(); + const preamble = replayPreamble("initialize-interrupted"); + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "initialize-interrupted", + entries: [ + ...preamble.slice(0, 2), + ...preamble.slice(0, 1).map((entry) => withReplayRequestId(entry, 2)), + { + type: "emit_inbound", + label: "initialize-rejected", + frame: { id: 2, error: { code: -32600, message: "Already initialized" } }, + }, + ...preamble.slice(2, 3), + ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), + ], + }), + (entry) => + entry.label === "initialize" + ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe( + Effect.andThen(Deferred.await(releaseInitialize)), + ) + : Effect.void, + ); - const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ - sourceProviderThread: makeProviderThread(now), - sourceProviderTurns: [firstTurn, secondTurn], - providerTurnId: secondTurn.id, - targetThreadId: ThreadId.make("thread-codex-fork-target"), - }); + const interrupted = yield* session + .ensureThread("thread-initialize-interrupted") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(initializeAwaitingResponse); + yield* Fiber.interrupt(interrupted); + yield* Deferred.succeed(releaseInitialize, undefined); - assert.deepEqual(boundary, { - lastTurnId: "native-turn-second", - rollbackTurnCount: 0, - }); - }), + const providerThread = yield* session.ensureThread("thread-initialize-interrupted"); + assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-interrupted"); + assert.equal(session.initializeRequests(), 2); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), ); +}); - it.effect("keeps the rollback-count fallback when the boundary turn lacks a native id", () => - Effect.gen(function* () { - const now = yield* DateTime.now; - const firstTurn = makeProviderTurn("provider-turn-first", 1, null, now); - const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now); - - const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ - sourceProviderThread: makeProviderThread(now), - sourceProviderTurns: [firstTurn, secondTurn], - providerTurnId: firstTurn.id, - targetThreadId: ThreadId.make("thread-codex-fork-target"), - }); - - assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 1 }); - }), - ); +describe("CodexAdapterV2 post-settle continuation", () => { + // The harness notifies after every recorded event or continuation, so a wait + // re-checks exactly when the state it reads changes. Subscribing before the + // first check means a change that lands in between is not lost. + const makeChangeSignal = Effect.gen(function* () { + const changes = yield* PubSub.unbounded(); + const until = (predicate: () => boolean): Effect.Effect => + Effect.scoped( + Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(changes); + while (!predicate()) yield* PubSub.take(subscription); + }), + ); + return { notify: PubSub.publish(changes, undefined), until }; + }); - it.effect("keeps the rollback-count fallback when the boundary turn has no native ref", () => + const makeCodexReplayHarness = ( + transcript: CodexReplay.CodexAppServerReplayTranscript, + onEvent: (event: ProviderAdapter.ProviderAdapterV2Event) => Effect.Effect = () => + Effect.void, + onRequest: (method: string, params: unknown) => Effect.Effect = () => Effect.void, + readChildMetadata?: Parameters[2], + ) => Effect.gen(function* () { - const now = yield* DateTime.now; - const firstTurn: OrchestrationV2ProviderTurn = { - ...makeProviderTurn("provider-turn-first", 1, "native-turn-first", now), - nativeTurnRef: null, + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const serverConfig = yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie); + const changes = yield* makeChangeSignal; + const continuationRequests: Array = + []; + const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = { + open: (openInput) => + Layer.build(CodexReplay.layerReplay(transcript)).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterOpenSessionError({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + providerSessionId: openInput.providerSessionId, + cause, + }), + ), + Effect.flatMap((context) => + Effect.service(CodexClient.CodexAppServerClient).pipe( + Effect.map((client) => + withCodexReplayChildMetadata(client, transcript, readChildMetadata), + ), + Effect.map( + (client) => + ({ + ...client, + request: (method, params) => + onRequest(method, params).pipe( + Effect.andThen(client.request(method, params)), + ), + }) satisfies CodexClient.CodexAppServerClient["Service"], + ), + Effect.provide(context), + ), + ), + ), }; - const secondTurn = makeProviderTurn("provider-turn-second", 2, "native-turn-second", now); - - const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ - sourceProviderThread: makeProviderThread(now), - sourceProviderTurns: [firstTurn, secondTurn], - providerTurnId: firstTurn.id, - targetThreadId: ThreadId.make("thread-codex-fork-target"), + const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CODEX_SETTINGS, + environment: {}, + clientFactory, + crypto: yield* Crypto.Crypto, + fileSystem, + idAllocator, + serverConfig, + continuationRequests: { + offer: (request) => + Effect.sync(() => { + continuationRequests.push(request); + }).pipe(Effect.andThen(changes.notify)), + }, }); - - assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 1 }); - }), - ); - - it.effect("forks at head without a boundary when no provider turn is selected", () => - Effect.gen(function* () { - const now = yield* DateTime.now; - - const boundary = yield* CodexAdapterV2.resolveCodexForkBoundary({ - sourceProviderThread: makeProviderThread(now), - targetThreadId: ThreadId.make("thread-codex-fork-target"), + const threadId = ThreadId.make(`thread-${transcript.scenario}`); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`), + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }); - - assert.deepEqual(boundary, { lastTurnId: undefined, rollbackTurnCount: 0 }); - }), - ); - - it.effect("fails with a typed error when the selected source turn is missing", () => - Effect.gen(function* () { - const now = yield* DateTime.now; - const firstTurn = makeProviderTurn("provider-turn-first", 1, "native-turn-first", now); - - const error = yield* Effect.flip( - CodexAdapterV2.resolveCodexForkBoundary({ - sourceProviderThread: makeProviderThread(now), - sourceProviderTurns: [firstTurn], - providerTurnId: ProviderTurnId.make("provider-turn-missing"), - targetThreadId: ThreadId.make("thread-codex-fork-target"), - }), + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + const events: Array = []; + const firstTerminal = yield* Deferred.make(); + yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + events.push(event); + }).pipe( + Effect.andThen( + event.type === "turn.terminal" + ? Deferred.succeed(firstTerminal, undefined) + : Effect.void, + ), + Effect.andThen(changes.notify), + Effect.andThen(onEvent(event)), + ), + ), + Effect.forkScoped, ); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("Codex adapter runtime must expose hasPendingBackgroundWork."); + } + const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; + const terminalEvents = () => + events.filter( + ( + event, + ): event is Extract => + event.type === "turn.terminal", + ); + const subagentUpdates = () => + events.filter( + ( + event, + ): event is Extract< + ProviderAdapter.ProviderAdapterV2Event, + { type: "subagent.updated" } + > => event.type === "subagent.updated", + ); + return { + runtime, + providerThread, + threadId, + serverConfig, + events, + continuationRequests, + terminalEvents, + subagentUpdates, + hasPendingBackgroundWork, + firstTerminal: Deferred.await(firstTerminal), + until: changes.until, + awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count), + }; + }); - assert.instanceOf(error, ProviderAdapter.ProviderAdapterForkThreadError); - assert.include(String(error.cause), "provider-turn-missing"); - }), - ); -}); - -describe("CodexAdapterV2 skill mentions", () => { - it("sends currency-sigil skill mentions as the $ mention Codex parses", () => { - const cases: ReadonlyArray = [ - ["€review do it", "$review do it"], - ["£ship", "$ship"], - ["please ¥review this diff", "please $review this diff"], - ["first line\n₹ship it", "first line\n$ship it"], - ["𑿝review then €2spec", "$review then $2spec"], - ["$review", "$review"], - ["costs €20", "costs €20"], - ["€5k", "€5k"], - ["budget €100M or €1e6", "budget €100M or €1e6"], - ["5€review", "5€review"], - ]; - for (const [text, expected] of cases) { - assert.equal(CodexAdapterV2.codexSkillMentionText(text), expected, text); - } - }); -}); - -describe("CodexAdapterV2 background command detail", () => { - it("summarizes command, exit code, and output tail", () => { - assert.equal( - CodexAdapterV2.codexBackgroundCommandDetail({ - command: "sleep 20 && echo CODEX_BG_WAKE_DONE", - exitCode: 0, - aggregatedOutput: "CODEX_BG_WAKE_DONE\n", - }), - "Background command completed (exit 0): sleep 20 && echo CODEX_BG_WAKE_DONE\n\n" + - "Output tail:\nCODEX_BG_WAKE_DONE", - ); - }); - - it("omits the output section and exit code when absent", () => { - assert.equal( - CodexAdapterV2.codexBackgroundCommandDetail({ - command: "sleep 20", - exitCode: null, - aggregatedOutput: null, - }), - "Background command completed: sleep 20", - ); - }); - - it("truncates long commands and keeps only the output tail", () => { - const detail = CodexAdapterV2.codexBackgroundCommandDetail({ - command: "x".repeat(300), - exitCode: 1, - aggregatedOutput: `${"y".repeat(2000)}TAIL`, - }); - assert.include(detail, `(exit 1): ${"x".repeat(200)}...`); - assert.include(detail, "Output tail:\n..."); - assert.include(detail, "TAIL"); - assert.notInclude(detail, "y".repeat(1001)); - }); -}); - -const DEFAULT_CODEX_SETTINGS = Schema.decodeSync(CodexSettings)({}); -const CODEX_TEST_MODEL_SELECTION = { - instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, - model: "gpt-5.4", -} satisfies ModelSelection; -const CODEX_TEST_RUNTIME_POLICY = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ - runtimeMode: "full-access", - interactionMode: "default", - cwd: "/workspace", -}); - -function makeCodexTestAppThread(input: { - readonly threadId: ThreadId; - readonly providerThread: OrchestrationV2ProviderThread; - readonly now: DateTime.Utc; -}): OrchestrationV2AppThread { - return { - createdBy: "user", - creationSource: "web", - id: input.threadId, - projectId: ProjectId.make(`project-${input.threadId}`), - title: "Codex continuation test", - providerInstanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - activeProviderThreadId: input.providerThread.id, - lineage: { - parentThreadId: null, - relationshipToParent: null, - rootThreadId: input.threadId, - }, - forkedFrom: null, - createdAt: input.now, - updatedAt: input.now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - deletedAt: null, - }; -} - -function makeCodexTestTurnInput(input: { - readonly threadId: ThreadId; - readonly providerThread: OrchestrationV2ProviderThread; - readonly now: DateTime.Utc; - readonly attemptId: RunAttemptId; - readonly text: string; -}): ProviderAdapter.ProviderAdapterV2TurnInput { - return { - appThread: makeCodexTestAppThread(input), - threadId: input.threadId, - runId: RunId.make(`run-${input.attemptId}`), - runOrdinal: 1, - providerTurnOrdinal: 1, - attemptId: input.attemptId, - rootNodeId: NodeId.make(`node-${input.attemptId}`), - providerThread: input.providerThread, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make(`message-${input.attemptId}`), - text: input.text, - attachments: [], - }, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }; -} - -function makeCodexReplayTurn(input: { - readonly id: string; - readonly status: "inProgress" | "completed" | "interrupted" | "failed"; -}): Record { - const terminal = - input.status === "completed" || input.status === "interrupted" || input.status === "failed"; - return { - id: input.id, - items: [], - itemsView: "notLoaded", - status: input.status, - error: null, - startedAt: 1782622440, - completedAt: terminal ? 1782622450 : null, - durationMs: null, - }; -} - -function codexReplayPreamble(input: { - readonly nativeThreadId: string; - readonly nativeTurnId: string; - readonly prompt: string; - readonly sentPrompt?: string; -}): Array { - return [ - { - type: "expect_outbound", - label: "initialize", - frame: { - id: 1, - method: "initialize", - params: { - clientInfo: { name: "T3 Code", title: "T3 Code", version: packageJson.version }, - capabilities: { - experimentalApi: true, - optOutNotificationMethods: ["turn/diff/updated"], - extensions: { - "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] }, - }, - }, - }, - }, - }, - { - type: "emit_inbound", - label: "initialize", - frame: { - id: 1, - result: { - userAgent: "T3 Code/0.156.1", - codexHome: "/tmp/codex-home", - platformFamily: "unix", - platformOs: "macos", - }, - }, - }, - { type: "expect_outbound", label: "initialized", frame: { method: "initialized" } }, - { - type: "expect_outbound", - label: "thread/start", - frame: { - id: 2, - method: "thread/start", - params: { config: CodexAdapterV2.CODEX_THREAD_CONFIG }, - }, - }, - { - type: "emit_inbound", - label: "thread/start", - frame: { - id: 2, - result: { - thread: { - id: input.nativeThreadId, - sessionId: input.nativeThreadId, - forkedFromId: null, - preview: "", - ephemeral: false, - modelProvider: "openai", - createdAt: 1782622440, - updatedAt: 1782622440, - status: { type: "idle" }, - path: `/tmp/${input.nativeThreadId}.jsonl`, - cwd: "/workspace", - cliVersion: "0.144.0", - source: "vscode", - threadSource: null, - agentNickname: null, - agentRole: null, - gitInfo: null, - name: null, - turns: [], - }, - model: "gpt-5.4", - modelProvider: "openai", - serviceTier: null, - cwd: "/workspace", - instructionSources: [], - approvalPolicy: "on-request", - approvalsReviewer: "user", - sandbox: { type: "workspaceWrite", writableRoots: [], networkAccess: false }, - reasoningEffort: "medium", - }, - }, - }, - { - type: "expect_outbound", - label: "turn/start", - frame: { - id: 3, - method: "turn/start", - params: { - threadId: input.nativeThreadId, - input: [{ type: "text", text: input.sentPrompt ?? input.prompt }], - cwd: "/workspace", - model: "gpt-5.4", - approvalPolicy: "never", - approvalsReviewer: "user", - sandboxPolicy: { type: "dangerFullAccess" }, - summary: "detailed", - }, - }, - }, - { - type: "emit_inbound", - label: "turn/start", - frame: { - id: 3, - result: { turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }) }, - }, - }, - { - type: "emit_inbound", - label: "turn/started", - frame: { - method: "turn/started", - params: { - threadId: input.nativeThreadId, - turn: makeCodexReplayTurn({ id: input.nativeTurnId, status: "inProgress" }), - }, - }, - }, - ]; -} - -function makeCodexReplayTranscript(input: { - readonly scenario: string; - readonly entries: ReadonlyArray; -}): CodexReplay.CodexAppServerReplayTranscript { - return { - provider: "codex", - protocol: "codex.app-server", - version: "0.144.0", - scenario: input.scenario, - entries: input.entries, - }; -} - -function withReplayRequestId( - entry: CodexReplay.CodexAppServerReplayEntry, - id: number, -): CodexReplay.CodexAppServerReplayEntry { - return entry.type !== "runtime_exit" && Predicate.isObject(entry.frame) - ? { ...entry, frame: { ...entry.frame, id } } - : entry; -} - -describe("CodexAdapterV2 session initialize", () => { - const openReplaySession = ( - transcript: CodexReplay.CodexAppServerReplayTranscript, - beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"], - ) => - Effect.gen(function* () { - const driver = yield* CodexReplay.makeReplayDriver( - transcript, - beforeEmitInbound === undefined ? {} : { beforeEmitInbound }, - ); - let initializeRequests = 0; - const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ - instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CODEX_SETTINGS, - environment: {}, - clientFactory: { - open: (openInput) => - Layer.build(CodexReplay.layerReplayWithDriver(driver)).pipe( - Effect.flatMap((context) => - Effect.service(CodexClient.CodexAppServerClient).pipe(Effect.provide(context)), - ), - Effect.map( - (client) => - ({ - ...client, - request: (method, params) => - Effect.sync(() => { - if (method === "initialize") initializeRequests++; - }).pipe(Effect.andThen(client.request(method, params))), - }) satisfies CodexClient.CodexAppServerClient["Service"], - ), - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterOpenSessionError({ - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - providerSessionId: openInput.providerSessionId, - cause, - }), - ), - ), - }, - crypto: yield* Crypto.Crypto, - fileSystem: yield* FileSystem.FileSystem, - idAllocator: yield* IdAllocator.IdAllocatorV2, - serverConfig: yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie), - }); - const runtime = yield* adapter.openSession({ - threadId: ThreadId.make(`thread-${transcript.scenario}`), - providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`), - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - return { - ensureThread: (threadId: string) => - runtime.ensureThread({ - threadId: ThreadId.make(threadId), - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }), - initializeRequests: () => initializeRequests, - }; - }); - - const replayPreamble = (nativeThreadId: string) => - codexReplayPreamble({ nativeThreadId, nativeTurnId: "unused", prompt: "unused" }); - - it.effect("sends one initialize when two threads start on a fresh session at once", () => - Effect.gen(function* () { - const initializeAwaitingResponse = yield* Deferred.make(); - const releaseInitialize = yield* Deferred.make(); - // The transcript allows exactly one handshake: a second `initialize` - // frame fails the replay, as Codex rejects it with "Already initialized". - const session = yield* openReplaySession( - makeCodexReplayTranscript({ - scenario: "concurrent-initialize", - entries: [ - ...replayPreamble("concurrent-first").slice(0, 5), - ...replayPreamble("concurrent-second") - .slice(3, 5) - .map((entry) => withReplayRequestId(entry, 3)), - ], - }), - (entry) => - entry.label === "initialize" - ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe( - Effect.andThen(Deferred.await(releaseInitialize)), - ) - : Effect.void, - ); - - const first = yield* session - .ensureThread("thread-concurrent-first") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(initializeAwaitingResponse); - const second = yield* session - .ensureThread("thread-concurrent-second") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.succeed(releaseInitialize, undefined); - - const providerThreads = [yield* Fiber.join(first), yield* Fiber.join(second)]; - assert.equal(session.initializeRequests(), 1); - assert.sameMembers( - providerThreads.map((providerThread) => providerThread.nativeThreadRef?.nativeId), - ["concurrent-first", "concurrent-second"], - ); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("retries initialize after a failed handshake", () => - Effect.gen(function* () { - const preamble = replayPreamble("initialize-retry"); - const entries: Array = [ - ...preamble.slice(0, 1), - { - type: "emit_inbound", - label: "initialize", - frame: { id: 1, error: { code: -32603, message: "Codex is not ready." } }, - }, - ...preamble.slice(0, 2).map((entry) => withReplayRequestId(entry, 2)), - ...preamble.slice(2, 3), - ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), - ]; - const session = yield* openReplaySession( - makeCodexReplayTranscript({ scenario: "initialize-retry", entries }), - ); - - const failure = yield* session.ensureThread("thread-initialize-retry").pipe(Effect.flip); - assert.equal(failure._tag, "ProviderAdapterEnsureThreadError"); - const providerThread = yield* session.ensureThread("thread-initialize-retry"); - assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-retry"); - assert.equal(session.initializeRequests(), 2); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("completes the handshake after a caller is interrupted mid-initialize", () => - Effect.gen(function* () { - const initializeAwaitingResponse = yield* Deferred.make(); - const releaseInitialize = yield* Deferred.make(); - const preamble = replayPreamble("initialize-interrupted"); - const session = yield* openReplaySession( - makeCodexReplayTranscript({ - scenario: "initialize-interrupted", - entries: [ - ...preamble.slice(0, 2), - ...preamble.slice(0, 1).map((entry) => withReplayRequestId(entry, 2)), - { - type: "emit_inbound", - label: "initialize-rejected", - frame: { id: 2, error: { code: -32600, message: "Already initialized" } }, - }, - ...preamble.slice(2, 3), - ...preamble.slice(3, 5).map((entry) => withReplayRequestId(entry, 3)), - ], - }), - (entry) => - entry.label === "initialize" - ? Deferred.succeed(initializeAwaitingResponse, undefined).pipe( - Effect.andThen(Deferred.await(releaseInitialize)), - ) - : Effect.void, - ); - - const interrupted = yield* session - .ensureThread("thread-initialize-interrupted") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(initializeAwaitingResponse); - yield* Fiber.interrupt(interrupted); - yield* Deferred.succeed(releaseInitialize, undefined); - - const providerThread = yield* session.ensureThread("thread-initialize-interrupted"); - assert.equal(providerThread.nativeThreadRef?.nativeId, "initialize-interrupted"); - assert.equal(session.initializeRequests(), 2); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); -}); - -describe("CodexAdapterV2 post-settle continuation", () => { - const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect => - Effect.gen(function* () { - for (let attempt = 0; attempt < 5000; attempt++) { - if (predicate()) { - return; - } - yield* Effect.yieldNow; - } - return yield* Effect.die(`Timed out waiting for ${label}.`); - }); - - const makeCodexReplayHarness = ( - transcript: CodexReplay.CodexAppServerReplayTranscript, - onEvent: (event: ProviderAdapter.ProviderAdapterV2Event) => Effect.Effect = () => - Effect.void, - onRequest: (method: string, params: unknown) => Effect.Effect = () => Effect.void, - readChildMetadata?: Parameters[2], - ) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const serverConfig = yield* makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie); - const continuationRequests: Array = - []; - const clientFactory: CodexAdapterV2.CodexAppServerClientFactoryShape = { - open: (openInput) => - Layer.build(CodexReplay.layerReplay(transcript)).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterOpenSessionError({ - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - providerSessionId: openInput.providerSessionId, - cause, - }), - ), - Effect.flatMap((context) => - Effect.service(CodexClient.CodexAppServerClient).pipe( - Effect.map((client) => - withCodexReplayChildMetadata(client, transcript, readChildMetadata), - ), - Effect.map( - (client) => - ({ - ...client, - request: (method, params) => - onRequest(method, params).pipe( - Effect.andThen(client.request(method, params)), - ), - }) satisfies CodexClient.CodexAppServerClient["Service"], - ), - Effect.provide(context), - ), - ), - ), - }; - const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ - instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, - settings: DEFAULT_CODEX_SETTINGS, - environment: {}, - clientFactory, - crypto: yield* Crypto.Crypto, - fileSystem, - idAllocator, - serverConfig, - continuationRequests: { - offer: (request) => - Effect.sync(() => { - continuationRequests.push(request); - }), - }, - }); - const threadId = ThreadId.make(`thread-${transcript.scenario}`); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`), - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - const providerThread = yield* runtime.ensureThread({ - threadId, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - const events: Array = []; - const firstTerminal = yield* Deferred.make(); - yield* runtime.events.pipe( - Stream.runForEach((event) => - Effect.sync(() => { - events.push(event); - }).pipe( - Effect.andThen( - event.type === "turn.terminal" - ? Deferred.succeed(firstTerminal, undefined) - : Effect.void, - ), - Effect.andThen(onEvent(event)), - ), - ), - Effect.forkScoped, - ); - if (runtime.hasPendingBackgroundWork === undefined) { - return yield* Effect.die("Codex adapter runtime must expose hasPendingBackgroundWork."); - } - const hasPendingBackgroundWork = runtime.hasPendingBackgroundWork; - const terminalEvents = () => - events.filter( - ( - event, - ): event is Extract => - event.type === "turn.terminal", - ); - const subagentUpdates = () => - events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "subagent.updated" } - > => event.type === "subagent.updated", - ); - return { - runtime, - providerThread, - threadId, - serverConfig, - events, - continuationRequests, - terminalEvents, - subagentUpdates, - hasPendingBackgroundWork, - firstTerminal: Deferred.await(firstTerminal), - }; - }); - - it.effect.each(["supported", "unsupported", "invalid"] as const)( - "delivers native history with %s app-server protocol", - (response) => - Effect.gen(function* () { - const nativeThreadId = `inject-${response}`; - const prompt = "Only the current request"; - const history: ProviderAdapter.ProviderAdapterV2HistoricalContext = { - context: "Historical conversation", - messages: (["user", "assistant"] as const).map((role) => ({ - role, - text: - role === "user" - ? "Original request\n" + "界".repeat(300) - : "Partial interrupted work", - threadId: ThreadId.make("source"), - runId: RunId.make("source-run"), - itemId: TurnItemId.make(`source-${role}`), - providerThreadId: null, - kind: `${role}_message`, - status: "interrupted", - })), - }; - const items = historyResponseItems(history.messages, history.context); - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "current-turn", - prompt, - }); - const transcript = makeCodexReplayTranscript({ - scenario: `inject-${response}`, - entries: [ - ...preamble.slice(0, -3), - { - type: "expect_outbound", - label: "inject", - frame: { - id: 3, - method: "thread/inject_items", - params: { threadId: nativeThreadId, items }, - }, - }, - { - type: "emit_inbound", - label: "inject-result", - frame: - response === "supported" - ? { id: 3, result: {} } - : { - id: 3, - error: { - code: response === "unsupported" ? -32601 : -32602, - message: "Injection rejected", - }, - }, - }, - ...(response === "invalid" - ? [] - : preamble - .slice(-3) - .map((entry) => - "frame" in entry && Predicate.isObject(entry.frame) && "id" in entry.frame - ? { ...entry, frame: { ...entry.frame, id: 4 } } - : entry, - )), - ], - }); - const requests: string[] = []; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method) => - Effect.sync(() => { - requests.push(method); - }), - ); - const injection = yield* harness.runtime.injectHistory!({ - providerThread: harness.providerThread, - ...history, - }).pipe(Effect.result); - if (response === "invalid") { - assert.equal(injection._tag, "Failure"); - if (injection._tag === "Failure") { - assert.equal(injection.failure._tag, "ProviderAdapterProtocolError"); - assert.propertyVal(injection.failure.cause, "code", -32602); - assert.notProperty(injection.failure, "payload"); - } - assert.notInclude(requests, "turn/start"); - return; - } - assert.equal(injection._tag, "Success"); - if (injection._tag === "Success") assert.equal(injection.success, response === "supported"); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("inject-attempt"), - text: prompt, - }), - ); - assert.equal(requests.filter((method) => method === "turn/start").length, 1); - assert.isBelow(requests.indexOf("thread/inject_items"), requests.indexOf("turn/start")); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("identifies sessions to Codex with the same client info as main", () => - Effect.gen(function* () { - const transcript = makeCodexReplayTranscript({ - scenario: "initialize-client-info", - entries: codexReplayPreamble({ - nativeThreadId: "client-info-thread", - nativeTurnId: "unused", - prompt: "unused", - }).slice(0, 5), - }); - const initializeParams: Array = []; - yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method, params) => - Effect.sync(() => { - if (method === "initialize") initializeParams.push(params); - }), - ); - assert.deepEqual(initializeParams, [ - { - clientInfo: { name: "T3 Code", title: "T3 Code", version: packageJson.version }, - capabilities: { - experimentalApi: true, - optOutNotificationMethods: ["turn/diff/updated"], - extensions: { - "io.modelcontextprotocol/ui": { mimeTypes: ["text/html;profile=mcp-app"] }, - }, - }, - }, - ]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("unsubscribes from the native thread when it is unloaded", () => - Effect.gen(function* () { - const nativeThreadId = "unload-thread"; - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "unused", - prompt: "unused", - }); - const transcript = makeCodexReplayTranscript({ - scenario: "unload-thread", - entries: [ - ...preamble.slice(0, 5), - { - type: "expect_outbound", - label: "thread/unsubscribe", - frame: { id: 3, method: "thread/unsubscribe", params: { threadId: nativeThreadId } }, - }, - { - type: "emit_inbound", - label: "thread/unsubscribe", - frame: { id: 3, result: { status: "unsubscribed" } }, - }, - ], - }); - const requests: Array = []; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method) => Effect.sync(() => requests.push(method)), - ); - assert.isDefined(harness.runtime.unloadThread); - yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); - assert.deepEqual(requests, ["initialize", "thread/start", "thread/unsubscribe"]); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("keeps the app-server failure as the cause when an unload is rejected", () => - Effect.gen(function* () { - const nativeThreadId = "unload-thread-rejected"; - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId: "unused", - prompt: "unused", - }); - const transcript = makeCodexReplayTranscript({ - scenario: "unload-thread-rejected", - entries: [ - ...preamble.slice(0, 5), - { - type: "expect_outbound", - label: "thread/unsubscribe", - frame: { id: 3, method: "thread/unsubscribe", params: { threadId: nativeThreadId } }, - }, - { - type: "emit_inbound", - label: "thread/unsubscribe", - frame: { id: 3, error: { code: -32600, message: "invalid thread id" } }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - const error = yield* harness.runtime.unloadThread!({ - providerThread: harness.providerThread, - }).pipe(Effect.flip); - assert.equal(error._tag, "ProviderAdapterProtocolError"); - const cause = error._tag === "ProviderAdapterProtocolError" ? error.cause : undefined; - assert.equal((cause as { _tag?: string } | undefined)?._tag, "CodexAppServerRequestError"); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("waits for native start before interrupting an acknowledged queued turn", () => - Effect.gen(function* () { - const nativeThreadId = "early-stop-thread"; - const nativeTurnId = "early-stop-turn"; - const prompt = "Run a command."; - const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }); - const transcript = makeCodexReplayTranscript({ - scenario: "early-stop-await-native-start", - entries: [ - ...preamble.slice(0, -2), - { - type: "emit_inbound", - label: "turn/start/queued", - frame: { - id: 3, - result: { - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), - startedAt: null, - }, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/started", - afterMs: 1000, - frame: { - method: "turn/started", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), - }, - }, - }, - { - 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" }), - }, - }, - }, - ], - }); - let interruptSent = false; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method) => - Effect.sync(() => { - if (method === "turn/interrupt") interruptSent = true; - }), - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("early-stop-attempt"), - text: prompt, - }), - ); - const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeTurnId, - }); - const interrupt = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("500 millis"); - assert.isFalse(interruptSent, "Stop must not reach Codex before native turn/started"); - yield* TestClock.adjust("500 millis"); - yield* Fiber.join(interrupt); - yield* harness.firstTerminal; - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("settles Stop when a queued native turn fails before starting", () => - Effect.gen(function* () { - const nativeThreadId = "early-stop-thread"; - const nativeTurnId = "early-stop-turn"; - const prompt = "Run a command."; - const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }); - const transcript = makeCodexReplayTranscript({ - scenario: "early-stop-failed-before-native-start", - entries: [ - ...preamble.slice(0, -2), - { - type: "emit_inbound", - label: "turn/start/queued", - frame: { - id: 3, - result: { - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), - startedAt: null, - }, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/failed", - afterMs: 1000, - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "failed" }), - startedAt: null, - error: { - message: "Failed before native start", - codexErrorInfo: null, - additionalDetails: null, - }, - }, - }, - }, - }, - ], - }); - let interruptSent = false; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method) => - Effect.sync(() => { - if (method === "turn/interrupt") interruptSent = true; - }), - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("early-stop-attempt"), - text: prompt, - }), - ); - const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeTurnId, - }); - const interrupt = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.forkScoped); - yield* TestClock.adjust("500 millis"); - assert.isFalse(interruptSent, "Stop must not reach Codex before native turn/started"); - yield* TestClock.adjust("500 millis"); - yield* Fiber.join(interrupt); - yield* harness.firstTerminal; - assert.equal(harness.terminalEvents()[0]?.status, "failed"); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse(interruptSent, "A terminal native turn must not receive turn/interrupt"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("bounds Stop when a queued native turn never starts", () => - Effect.gen(function* () { - const nativeThreadId = "early-stop-thread"; - const nativeTurnId = "early-stop-turn"; - const prompt = "Run a command."; - const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }); - const transcript = makeCodexReplayTranscript({ - scenario: "early-stop-never-starts", - entries: [ - ...preamble.slice(0, -2), - { - type: "emit_inbound", - label: "turn/start/queued", - frame: { - id: 3, - result: { - turn: { - ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), - startedAt: null, - }, - }, - }, - }, - ], - }); - let interruptSent = false; - const harness = yield* makeCodexReplayHarness( - transcript, - () => Effect.void, - (method) => - Effect.sync(() => { - if (method === "turn/interrupt") interruptSent = true; - }), - ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("early-stop-attempt"), - text: prompt, - }), - ); - const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeTurnId, - }); - const interrupt = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.exit, Effect.forkScoped); - yield* TestClock.adjust("10 seconds"); - assert.equal((yield* Fiber.join(interrupt))._tag, "Failure"); - yield* harness.firstTerminal; - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse(interruptSent, "An unstarted native turn must not receive turn/interrupt"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - it.effect("sends currency-sigil skill mentions to Codex as $ mentions", () => - Effect.gen(function* () { - const nativeThreadId = "skill-sigil-thread"; - const nativeTurnId = "skill-sigil-turn"; - const transcript = makeCodexReplayTranscript({ - scenario: "skill-sigil-canonicalized", - entries: [ - ...codexReplayPreamble({ - nativeThreadId, - nativeTurnId, - prompt: "€review do it", - sentPrompt: "$review do it", - }), - { - type: "expect_outbound", - label: "turn/steer", - frame: { - id: 4, - method: "turn/steer", - params: { - expectedTurnId: nativeTurnId, - input: [{ type: "text", text: "then $ship it" }], - threadId: nativeThreadId, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/steer", - frame: { id: 4, result: { turnId: nativeTurnId } }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - const turnInput = makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("skill-sigil-attempt"), - text: "€review do it", - }); - yield* harness.runtime.startTurn(turnInput); - yield* harness.runtime.steerTurn({ - threadId: harness.threadId, - runId: turnInput.runId, - providerThread: harness.providerThread, - providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ - driver: CodexAdapterV2.CODEX_DRIVER_KIND, - nativeTurnId, - }), - message: { - ...turnInput.message, - messageId: MessageId.make("message-skill-sigil-steer"), - text: "then £ship it", - }, - }); - }).pipe( - Effect.scoped, - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ); - - const assistantMessages = (events: ReadonlyArray) => - events.filter( - ( - event, - ): event is Extract => - event.type === "message.updated" && event.message.role === "assistant", - ); - const assistantTurnItems = (events: ReadonlyArray) => - events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "assistant_message" - ? [event.turnItem] - : [], - ); - - 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, - 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, - reasoningTokens: 1, - }); - } - assert.isEmpty(assistantMessages(harness.events)); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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 => [ - { - 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: "detailed", - }, - }, - }, - { - 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}` } : {}), - }, - }, - }, - { - 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", - }), - 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* awaitUntil(() => requests().length === count, `approval request ${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* awaitUntil(() => requests().length === 2, "file change request"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn 1"); - yield* runTurn(1); - yield* answer(2, "file-change", "acceptForSession"); - yield* awaitUntil(() => harness.terminalEvents().length === 2, "turn 2"); - yield* runTurn(2); - yield* answer(3, "command", "accept"); - yield* answer(4, "file-change", "accept"); - yield* awaitUntil(() => harness.terminalEvents().length === 3, "turn 3"); - assert.lengthOf(requests(), 4); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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"; - const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ - nativeThreadId, - codexInput: [{ type: "text", text: "work" }], - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - modelSelection: CODEX_TEST_MODEL_SELECTION, - hasT3Mcp: true, - }); - 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: "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: "restored", frame: { id: 4, result: {} } }, - { - type: "emit_inbound", - label: "done", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), - }, - }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - 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", - }), - ); - yield* harness.firstTerminal; - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("compacts Codex with the native RPC and completes the compaction turn", () => - Effect.scoped( - 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: "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) => ({ - 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" }), - }, - }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - assert.isDefined(harness.runtime.compactThread); - yield* harness.runtime.compactThread!( - makeCodexTestTurnInput({ - threadId: harness.threadId, - 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), - ), - ), - ), - ); - - 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, - }, - }, - }, - { - type: "emit_inbound", - label: "thread/resume", - frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - 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"); - assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect.each( - ( - [ - ["recovers archived-session errors", "session saved-thread is archived", 0, ""], - [ - "recovers unarchive hints", - "Run `codex unarchive saved-thread` to unarchive it first.", - 0, - "", - ], - ["preserves missing-thread errors", "thread not found", 3, "thread not found"], - ["preserves missing-rollout errors", "no rollout found", 3, "no rollout found"], - ["preserves authentication errors", "authentication failed", 3, "authentication failed"], - [ - "preserves archived-workspace errors", - "workspace is archived", - 3, - "workspace is archived", - ], - [ - "preserves unrelated archive-path errors", - "permission denied reading archived_sessions/saved-thread", - 3, - "permission denied reading archived_sessions/saved-thread", - ], - [ - "propagates unarchive missing-thread errors", - "session saved-thread is archived", - 4, - "thread not found", - ], - [ - "propagates unarchive archived errors", - "session saved-thread is archived", - 4, - "session saved-thread is archived", - ], - [ - "propagates retry missing-thread errors", - "session saved-thread is archived", - 5, - "thread not found", - ], - [ - "does not retry archived errors twice", - "session saved-thread is archived", - 5, - "session saved-thread is archived", - ], - ] 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), - { - 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: "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" }], - }, - }, - }, - }, - ); - } - 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), - ), - ), - ), - ); - - it.effect("continues an interrupted native thread with empty input and reasoning summaries", () => - Effect.scoped( - Effect.gen(function* () { - const scenario = "codex-restart-promptless"; - const nativeThreadId = "native-restart-promptless"; - const nativeTurnId = "turn-restart-promptless"; - const preamble = codexReplayPreamble({ - nativeThreadId, - nativeTurnId, - prompt: "unused", - }).slice(0, 5); - const transcript = makeCodexReplayTranscript({ - scenario, - entries: [ - ...preamble, - { - type: "expect_outbound", - label: "resume", - frame: { - id: 3, - method: "thread/resume", - params: { - threadId: nativeThreadId, - excludeTurns: true, - config: CodexAdapterV2.CODEX_THREAD_CONFIG, - }, - }, - }, - { - type: "emit_inbound", - label: "resume", - frame: { id: 3, result: { thread: { id: nativeThreadId, updatedAt: 1782622450 } } }, - }, - { - type: "expect_outbound", - label: "continue", - frame: { - id: 4, - method: "turn/start", - params: { - threadId: nativeThreadId, - input: [], - cwd: "/workspace", - model: "gpt-5.4", - approvalPolicy: "never", - approvalsReviewer: "user", - sandboxPolicy: { type: "dangerFullAccess" }, - summary: "detailed", - }, - }, - }, - { - type: "emit_inbound", - label: "continue", - frame: { - id: 4, - result: { turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }) }, - }, - }, - ], - }); - const harness = yield* makeCodexReplayHarness(transcript); - const resumed = yield* harness.runtime.resumeThread({ - providerThread: harness.providerThread, - modelSelection: CODEX_TEST_MODEL_SELECTION, - runtimePolicy: CODEX_TEST_RUNTIME_POLICY, - }); - yield* harness.runtime.startTurn({ - ...makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: resumed, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-restart-promptless"), - text: "Continue where you left off.", - }), - restartContinuationOfRunId: RunId.make("run-before-restart"), - }); - assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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 }, - }, - }, - }, - }, - }, - { - 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: "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* awaitUntil(() => harness.terminalEvents().length === 1, "Codex retry recovery"); - - const retryItems = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.retry !== undefined - ? [event.turnItem] - : [], - ); - assert.lengthOf(retryItems, 2); - 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.equal(retryItems[1]?.id, retryItems[0]?.id); - assert.equal(retryItems[1]?.status, "completed"); - assert.equal(retryItems[1]?.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), - ), - ), - ), - ); - - it.effect("stamps Codex items with their own start time, not the turn's", () => - Effect.scoped( - Effect.gen(function* () { - const scenario = "codex-item-start-times"; - const nativeThreadId = `native-${scenario}-thread`; - const nativeTurnId = `native-${scenario}-turn`; - const commandLifecycle = (id: string, startedAtMs: number) => - (["started", "completed"] as const).map((phase) => ({ - type: "emit_inbound" as const, - label: `item/${phase}/${id}`, - frame: { - method: `item/${phase}`, - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - ...(phase === "started" ? { startedAtMs } : { completedAtMs: startedAtMs + 10 }), - item: { - type: "commandExecution", - id, - command: "pwd", - cwd: "/workspace", - processId: "42", - source: "unifiedExecStartup", - status: phase === "started" ? "inProgress" : "completed", - commandActions: [{ type: "unknown", command: "pwd" }], - aggregatedOutput: phase === "started" ? null : "/workspace\n", - exitCode: phase === "started" ? null : 0, - durationMs: phase === "started" ? null : 10, - }, - }, - }, - })); - const transcript = makeCodexReplayTranscript({ - scenario, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Run two commands." }), - ...commandLifecycle("first-command", 1782622445000), - ...commandLifecycle("second-command", 1782622505000), - ...(["started", "completed"] as const).map((phase) => ({ - type: "emit_inbound" as const, - label: `item/${phase}/compaction`, - frame: { - method: `item/${phase}`, - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - ...(phase === "started" - ? { startedAtMs: 1782622565000 } - : { completedAtMs: 1782622575000 }), - item: { type: "contextCompaction", id: "compaction" }, - }, - }, - })), - { - type: "emit_inbound", - label: "turn/completed", - 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("attempt-codex-item-start-times"), - text: "Run two commands.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "Codex item start times"); - - const startedAtByItem = harness.events.flatMap((event) => - event.type === "turn_item.updated" && - (event.turnItem.type === "command_execution" || event.turnItem.type === "compaction") - ? [[event.turnItem.nativeItemRef?.nativeId, event.turnItem.startedAt] as const] - : [], - ); - assert.deepEqual( - startedAtByItem.map(([id, startedAt]) => [id, startedAt?.epochMilliseconds]), - [ - ["first-command", 1782622445000], - ["first-command", 1782622445000], - ["second-command", 1782622505000], - ["second-command", 1782622505000], - ["compaction", 1782622565000], - ["compaction", 1782622565000], - ], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - 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), - ), - ), - ), - ); - - it.effect("streams a proposed plan a few times a second instead of once per delta", () => - Effect.scoped( + it.effect.each(["supported", "unsupported", "invalid"] as const)( + "delivers native history with %s app-server protocol", + (response) => Effect.gen(function* () { - const scenario = "codex-plan-delta-coalescing"; - const nativeThreadId = `native-${scenario}-thread`; - const nativeTurnId = `native-${scenario}-turn`; - const prompt = "Plan the change."; - const deltas = Array.from({ length: 100 }, (_, index) => `step ${index}\n`); + const nativeThreadId = `inject-${response}`; + const prompt = "Only the current request"; + const history: ProviderAdapter.ProviderAdapterV2HistoricalContext = { + context: "Historical conversation", + messages: (["user", "assistant"] as const).map((role) => ({ + role, + text: + role === "user" + ? "Original request\n" + "界".repeat(300) + : "Partial interrupted work", + threadId: ThreadId.make("source"), + runId: RunId.make("source-run"), + itemId: TurnItemId.make(`source-${role}`), + providerThreadId: null, + kind: `${role}_message`, + status: "interrupted", + })), + }; + const items = historyResponseItems(history.messages, history.context); + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: "current-turn", + prompt, + }); const transcript = makeCodexReplayTranscript({ - scenario, + scenario: `inject-${response}`, entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), - ...deltas.map((delta, index): CodexReplay.CodexAppServerReplayEntry => ({ - type: "emit_inbound", - label: `item/plan/delta/${index}`, - afterMs: 20, - frame: { - method: "item/plan/delta", - params: { threadId: nativeThreadId, turnId: nativeTurnId, itemId: "plan", delta }, - }, - })), - { - type: "emit_inbound", - label: "item/completed/plan", - frame: { - method: "item/completed", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - item: { type: "plan", id: "plan", text: "" }, - }, - }, - }, + ...preamble.slice(0, -3), { - type: "emit_inbound", - label: "turn/completed", - 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(`attempt-${scenario}`), - text: prompt, - }), - ); - for (let step = 0; step < 200 && harness.terminalEvents().length === 0; step += 1) { - yield* Effect.yieldNow; - yield* TestClock.adjust("20 millis"); - } - yield* harness.firstTerminal; - - const plans = harness.events.flatMap((event) => - event.type === "plan.updated" && event.plan.kind === "proposed_plan" ? [event.plan] : [], - ); - const planItems = harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "proposed_plan" - ? [event.turnItem] - : [], - ); - assert.isAtLeast(plans.length, 2); - assert.isAtMost(plans.length, 7); - assert.equal(planItems.length, plans.length); - assert.equal(plans.at(-1)?.markdown, deltas.join("")); - assert.deepEqual( - planItems.map((item) => item.streaming), - [...Array.from({ length: planItems.length - 1 }, () => true), false], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - const finalAnswerTranscript = ( - scenario: string, - answers: ReadonlyArray<{ - readonly id: string; - readonly text: string; - readonly phase?: "commentary" | "final_answer" | null; - readonly omitPhase?: boolean; - readonly streamed?: boolean; - readonly completionDelayMs?: number; - }>, - ) => { - const nativeThreadId = `native-${scenario}-thread`; - const nativeTurnId = `native-${scenario}-turn`; - const prompt = "Reply with the requested recovery marker."; - return makeCodexReplayTranscript({ - scenario, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), - ...answers.flatMap( - (answer, index): ReadonlyArray => { - const phase = answer.omitPhase - ? {} - : { phase: answer.phase === undefined ? ("final_answer" as const) : answer.phase }; - const completed: CodexReplay.CodexAppServerReplayEntry = { - type: "emit_inbound", - label: `item/completed/${answer.id}`, - ...(answer.completionDelayMs === undefined - ? {} - : { afterMs: answer.completionDelayMs }), + type: "expect_outbound", + label: "inject", frame: { - method: "item/completed", - params: { - item: { - type: "agentMessage", - id: answer.id, - text: answer.text, - ...phase, - memoryCitation: null, - }, - threadId: nativeThreadId, - turnId: nativeTurnId, - completedAtMs: 1782622441000 + index, - }, - }, - }; - if (!answer.streamed) { - return [completed]; - } - return [ - { - type: "emit_inbound", - label: `item/started/${answer.id}`, - frame: { - method: "item/started", - params: { - item: { - type: "agentMessage", - id: answer.id, - text: "", - ...phase, - memoryCitation: null, - }, - threadId: nativeThreadId, - turnId: nativeTurnId, - startedAtMs: 1782622440500 + index, - }, - }, - }, - { - type: "emit_inbound", - label: `item/agentMessage/delta/${answer.id}`, - frame: { - method: "item/agentMessage/delta", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - itemId: answer.id, - delta: answer.text, - }, - }, + id: 3, + method: "thread/inject_items", + params: { threadId: nativeThreadId, items }, }, - completed, - ]; - }, - ), - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: nativeThreadId, - turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), }, - }, - }, - ], - }); - }; - - 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; - + { + type: "emit_inbound", + label: "inject-result", + frame: + response === "supported" + ? { id: 3, result: {} } + : { + id: 3, + error: { + code: response === "unsupported" ? -32601 : -32602, + message: "Injection rejected", + }, + }, + }, + ...(response === "invalid" + ? [] + : preamble + .slice(-3) + .map((entry) => + "frame" in entry && Predicate.isObject(entry.frame) && "id" in entry.frame + ? { ...entry, frame: { ...entry.frame, id: 4 } } + : entry, + )), + ], + }); + const requests: string[] = []; + const harness = yield* makeCodexReplayHarness( + transcript, + () => Effect.void, + (method) => + Effect.sync(() => { + requests.push(method); + }), + ); + const injection = yield* harness.runtime.injectHistory!({ + providerThread: harness.providerThread, + ...history, + }).pipe(Effect.result); + if (response === "invalid") { + assert.equal(injection._tag, "Failure"); + if (injection._tag === "Failure") { + assert.equal(injection.failure._tag, "ProviderAdapterProtocolError"); + assert.propertyVal(injection.failure.cause, "code", -32602); + assert.notProperty(injection.failure, "payload"); + } + assert.notInclude(requests, "turn/start"); + return; + } + assert.equal(injection._tag, "Success"); + if (injection._tag === "Success") assert.equal(injection.success, response === "supported"); 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.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("inject-attempt"), + text: prompt, }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["CODEX_RECOVERY_OK"], - ); + assert.equal(requests.filter((method) => method === "turn/start").length, 1); + assert.isBelow(requests.indexOf("thread/inject_items"), requests.indexOf("turn/start")); }).pipe( + Effect.scoped, Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), - ), ); - it.effect("streams text on the turn item and sends the message once, when it completes", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-streamed-message-once", [ - { id: "answer", text: "CODEX_RECOVERY_OK", streamed: true, completionDelayMs: 100 }, - ]); - const harness = yield* makeCodexReplayHarness(transcript); - const now = yield* DateTime.now; + it.effect("adds the session MCP server without replacing launch-argument servers", () => + Effect.gen(function* () { + const scenario = "launch-mcp-servers"; + yield* (yield* McpProviderSessions.McpProviderSessions).set({ + environmentId: EnvironmentId.make("environment-codex-mcp"), + threadId: ThreadId.make(`thread-${scenario}`), + providerSessionId: `provider-session-${scenario}`, + providerInstanceId: ProviderInstanceId.make("codex"), + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer secret-codex-token", + browserToolsAvailable: true, + }); + const requests: Array = []; + yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario, + entries: codexReplayPreamble({ + nativeThreadId: "launch-mcp-thread", + nativeTurnId: "unused", + prompt: "unused", + }).slice(0, 5), + }), + () => Effect.void, + (method, params) => + Effect.sync(() => { + if (method === "thread/start") requests.push(params); + }), + ); + assert.deepEqual(requests, [ + { + cwd: "/workspace", + model: "gpt-5.4", + config: { + "tools.update_plan.enabled": true, + mcp_optional_startup_grace_ms: 10_000, + "mcp_servers.t3-code": { + url: "http://127.0.0.1:43123/mcp", + tool_timeout_sec: 3_900, + http_headers: { Authorization: "Bearer secret-codex-token" }, + }, + }, + }, + ]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-streamed-message-once"), - text: "Reply with the requested recovery marker.", + // regression: #15839 launch-arg MCP servers survive the thread's t3-code server + it.effect("replays historical and dotted MCP config while enforcing other thread config", () => + Effect.gen(function* () { + const recordedServer = { + url: "http://127.0.0.1:41000/mcp", + http_headers: { Authorization: "Bearer recorded-token" }, + }; + const currentConfig = { + "tools.update_plan.enabled": true, + "mcp_servers.t3-code": { + url: "http://127.0.0.1:42000/mcp", + http_headers: { Authorization: "Bearer current-token" }, + }, + "mcp_servers.extra.command": "cat", + }; + for (const recordedMcp of [ + { mcp_servers: { "t3-code": recordedServer } }, + { "mcp_servers.t3-code": recordedServer, "mcp_servers.extra.command": "echo" }, + ]) { + const entries = codexReplayPreamble({ + nativeThreadId: "replayed-mcp-thread", + nativeTurnId: "unused", + prompt: "unused", + }) + .slice(3, 5) + .map((entry) => withReplayRequestId(entry, 1)); + entries[0] = { + type: "expect_outbound", + frame: { + id: 1, + method: "thread/start", + params: { config: { "tools.update_plan.enabled": true, ...recordedMcp } }, + }, + }; + entries.push({ + ...entries[0], + frame: { + id: 2, + method: "thread/start", + params: { config: { "tools.update_plan.enabled": true, ...recordedMcp } }, + }, + }); + const driver = yield* CodexReplay.makeReplayDriver( + makeCodexReplayTranscript({ + scenario: "mcp-config-normalization", + entries, }), ); - yield* Effect.yieldNow; - yield* TestClock.adjust("50 millis"); - yield* awaitUntil( - () => assistantTurnItems(harness.events).length === 1, - "streamed turn item", - ); - assert.deepEqual( - assistantTurnItems(harness.events).map(({ text, streaming }) => ({ text, streaming })), - [{ text: "CODEX_RECOVERY_OK", streaming: true }], - ); - assert.deepEqual(assistantMessages(harness.events), []); + yield* Effect.gen(function* () { + const client = yield* CodexClient.CodexAppServerClient; + const response = yield* client.request("thread/start", { config: currentConfig }); + assert.equal(response.thread.id, "replayed-mcp-thread"); + assert.isNull((yield* Ref.get(driver.state)).failure); + yield* client + .request("thread/start", { + config: { ...currentConfig, "tools.update_plan.enabled": false }, + }) + .pipe(Effect.flip); + assert.instanceOf( + (yield* Ref.get(driver.state)).failure, + CodexReplay.CodexAppServerReplayFrameMismatchError, + ); + }).pipe(Effect.provide(CodexReplay.layerReplayWithDriver(driver))); + } + }).pipe(Effect.scoped), + ); - yield* TestClock.adjust("50 millis"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - assert.deepEqual( - assistantMessages(harness.events).map(({ message }) => ({ - text: message.text, - streaming: message.streaming, - })), - [{ text: "CODEX_RECOVERY_OK", streaming: false }], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), + it.effect("waits for native start before interrupting an acknowledged queued turn", () => + Effect.gen(function* () { + const nativeThreadId = "early-stop-thread"; + const nativeTurnId = "early-stop-turn"; + const prompt = "Run a command."; + const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }); + const transcript = makeCodexReplayTranscript({ + scenario: "early-stop-await-native-start", + entries: [ + ...preamble.slice(0, -2), + { + type: "emit_inbound", + label: "turn/start/queued", + frame: { + id: 3, + result: { + turn: { + ...makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), + startedAt: null, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/started", + afterMs: 1000, + frame: { + method: "turn/started", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), + }, + }, + }, + { + 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" }), + }, + }, + }, + ], + }); + let interruptSent = false; + const harness = yield* makeCodexReplayHarness( + transcript, + () => Effect.void, + (method) => + Effect.sync(() => { + if (method === "turn/interrupt") interruptSent = true; + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("early-stop-attempt"), + text: prompt, + }), + ); + const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeTurnId, + }); + const interrupt = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* TestClock.adjust("500 millis"); + assert.isFalse(interruptSent, "Stop must not reach Codex before native turn/started"); + yield* TestClock.adjust("500 millis"); + yield* Fiber.join(interrupt); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); + assert.lengthOf(harness.terminalEvents(), 1); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), ), ); - it.effect("suppresses a later streamed duplicate final answer", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-streamed-duplicate-final", [ - { id: "answer-original", text: "CODEX_RECOVERY_OK" }, - { - id: "answer-duplicate", - text: "CODEX_RECOVERY_OK", - streamed: true, - completionDelayMs: 100, - }, - ]); - 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-streamed-duplicate-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* awaitUntil(() => assistantMessages(harness.events).length === 1, "original answer"); - yield* Effect.yieldNow; - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["CODEX_RECOVERY_OK"], - ); - - yield* TestClock.adjust("50 millis"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["CODEX_RECOVERY_OK"], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); + const assistantMessages = (events: ReadonlyArray) => + events.filter( + ( + event, + ): event is Extract => + event.type === "message.updated" && event.message.role === "assistant", + ); - it.effect("buffers an overlapping later final stream until duplicate detection", () => + it.effect("keeps an asynchronous Codex question actionable after the turn completes", () => Effect.scoped( Effect.gen(function* () { - const scenario = "codex-overlapping-duplicate-final"; - const nativeThreadId = `native-${scenario}-thread`; - const nativeTurnId = `native-${scenario}-turn`; - const answerItem = (id: string, text: string) => ({ - type: "agentMessage" as const, - id, - text, - phase: "final_answer" as const, - memoryCitation: null, - }); + 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, + scenario: "async-question-and-billed-usage", entries: [ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, - prompt: "Reply with the requested recovery marker.", + prompt: "Continue while I decide.", }), - ...["answer-overlap-original", "answer-overlap-duplicate"].flatMap( - (itemId, index): ReadonlyArray => [ - { - type: "emit_inbound", - label: `item/started/${itemId}`, - frame: { - method: "item/started", - params: { - item: answerItem(itemId, ""), - threadId: nativeThreadId, - turnId: nativeTurnId, - startedAtMs: 1782622440500 + index, - }, - }, - }, - { - type: "emit_inbound", - label: `item/agentMessage/delta/${itemId}`, - frame: { - method: "item/agentMessage/delta", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - itemId, - delta: "CODEX_RECOVERY_OK", - }, - }, - }, - ], - ), { type: "emit_inbound", - label: "item/completed/answer-overlap-original", - afterMs: 100, + label: "question", frame: { method: "item/completed", params: { - item: answerItem("answer-overlap-original", "CODEX_RECOVERY_OK"), threadId: nativeThreadId, turnId: nativeTurnId, - completedAtMs: 1782622441000, + item: { + type: "agentMessage", + id: "async-question-item", + text: "Which branch?", + delivery: "async", + questions: [{ title: "Which branch?", options: ["main", "dev"] }], + }, }, }, }, { type: "emit_inbound", - label: "item/completed/answer-overlap-duplicate", + label: "usage", frame: { - method: "item/completed", + method: "thread/tokenUsage/updated", params: { - item: answerItem("answer-overlap-duplicate", "CODEX_RECOVERY_OK"), threadId: nativeThreadId, turnId: nativeTurnId, - completedAtMs: 1782622441001, + tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, }, }, }, { type: "emit_inbound", - label: "turn/completed", + label: "complete", 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-overlapping-duplicate-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* Effect.yieldNow; - yield* TestClock.adjust("50 millis"); - yield* Effect.yieldNow; - - assert.equal(new Set(assistantTurnItems(harness.events).map((item) => item.id)).size, 1); - - yield* TestClock.adjust("50 millis"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - assert.equal( - new Set(assistantMessages(harness.events).map((event) => event.message.id)).size, - 1, - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("preserves a sole empty final answer", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-sole-empty-final", [ - { 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-sole-empty-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - [""], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("suppresses a second empty final answer", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-duplicate-empty-final", [ - { id: "answer-empty-original", text: "" }, - { id: "answer-empty-duplicate", 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-duplicate-empty-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - [""], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("preserves an empty final answer when only commentary preceded it", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-commentary-then-empty-final", [ - { id: "answer-commentary", text: "Working on it.", phase: "commentary" }, - { 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-commentary-then-empty-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["Working on it.", ""], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("suppresses an empty final answer after a non-empty unknown-phase answer", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-unknown-non-empty-then-empty-final", [ - { id: "answer-non-empty", text: "CODEX_RECOVERY_OK", phase: null }, - { 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-unknown-non-empty-then-empty-final"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["CODEX_RECOVERY_OK"], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("suppresses a trailing empty answer with an omitted phase", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-final-then-empty-unknown", [ - { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" }, - { id: "answer-empty", text: "", omitPhase: true }, - ]); - 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-final-then-empty-unknown"), - text: "Reply with the requested recovery marker.", - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["CODEX_RECOVERY_OK"], - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect("keeps a later non-empty final answer after an initial empty final answer", () => - Effect.scoped( - Effect.gen(function* () { - const transcript = finalAnswerTranscript("codex-empty-then-non-empty-final", [ - { id: "answer-empty", text: "" }, - { id: "answer-non-empty", text: "CODEX_RECOVERY_OK" }, - ]); + 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-empty-then-non-empty-final"), - text: "Reply with the requested recovery marker.", + now: yield* DateTime.now, + attemptId: RunAttemptId.make("async-question-attempt"), + text: "Continue while I decide.", }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - - assert.deepEqual( - assistantMessages(harness.events).map((event) => event.message.text), - ["", "CODEX_RECOVERY_OK"], + 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)); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -4515,675 +1512,572 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - const BG_SCENARIO = "codex-bg-exec-wake"; - const BG_NATIVE_THREAD = "native-codex-bg-thread"; - const BG_NATIVE_TURN = "native-codex-bg-turn"; - const BG_COMMAND_ITEM = "call-codex-bg-command"; - const BG_COMMAND = "sleep 20 && echo CODEX_BG_WAKE_DONE"; - const BG_PROMPT = "Start the sleep in the background and reply STARTED."; - - const backgroundCommandItem = (status: "inProgress" | "completed"): Record => ({ - type: "commandExecution", - id: BG_COMMAND_ITEM, - command: BG_COMMAND, - cwd: "/workspace", - processId: "4242", - source: "unifiedExecStartup", - status, - commandActions: [{ type: "unknown", command: BG_COMMAND }], - aggregatedOutput: status === "completed" ? "CODEX_BG_WAKE_DONE\n" : null, - exitCode: status === "completed" ? 0 : null, - durationMs: status === "completed" ? 25_000 : null, - }); - - const backgroundExecTranscript = makeCodexReplayTranscript({ - scenario: BG_SCENARIO, - entries: [ - ...codexReplayPreamble({ - nativeThreadId: BG_NATIVE_THREAD, - nativeTurnId: BG_NATIVE_TURN, - prompt: BG_PROMPT, - }), - { - type: "emit_inbound", - label: "item/started/command", - frame: { - method: "item/started", - params: { - item: backgroundCommandItem("inProgress"), - threadId: BG_NATIVE_THREAD, - turnId: BG_NATIVE_TURN, - startedAtMs: 1782622440500, + 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" }, }, - }, - }, - { - type: "emit_inbound", - label: "item/completed/root-answer", - frame: { - method: "item/completed", - params: { - item: { - type: "agentMessage", - id: "root-answer-bg", - text: "STARTED", - phase: "final_answer", - memoryCitation: null, + "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: "detailed", + collaborationMode: { mode: "default", settings: { model: "gpt-5.4" } }, + }, }, - threadId: BG_NATIVE_THREAD, - turnId: BG_NATIVE_TURN, - completedAtMs: 1782622441000, }, - }, - }, - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: BG_NATIVE_THREAD, - turn: makeCodexReplayTurn({ id: BG_NATIVE_TURN, status: "completed" }), + { + type: "emit_inbound", + label: `turn ${index + 1} turn/start`, + frame: { + id: 3 + index, + result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) }, + }, }, - }, - }, - { - type: "emit_inbound", - label: "item/completed/command-late", - afterMs: 30_000, - frame: { - method: "item/completed", - params: { - item: backgroundCommandItem("completed"), - threadId: BG_NATIVE_THREAD, - turnId: BG_NATIVE_TURN, - completedAtMs: 1782622465500, + 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}` } : {}), + }, + }, }, - }, - }, - ], - }); - - it.effect( - "projects a post-settle background command completion and requests a continuation", - () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(backgroundExecTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-bg-wake"), - text: BG_PROMPT, + { + 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* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - assert.isTrue( - yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread), - ); - assert.lengthOf(harness.continuationRequests, 0); - const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); + 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 }); + }); - yield* TestClock.adjust("30 seconds"); - yield* awaitUntil( - () => harness.continuationRequests.length === 1, - "continuation request", - ); - const request = harness.continuationRequests[0]; - assert.equal(request?.threadId, harness.threadId); - assert.equal(request?.providerThreadId, harness.providerThread.id); - assert.equal(request?.driver, CodexAdapterV2.CODEX_DRIVER_KIND); - assert.deepEqual(request?.notification, { - source: { kind: "command" }, - outcome: "completed", - summary: `Command "${BG_COMMAND}" finished (exit 0)`, - detail: BG_COMMAND, + 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]! }, + }); }); - assert.equal( - request?.detail, - `Background command completed (exit 0): ${BG_COMMAND}\n\n` + - "Output tail:\nCODEX_BG_WAKE_DONE", - ); - const lateCommandUpdateIndex = () => - harness.events.findIndex( - (event, index) => - index > terminalIndex && - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "completed" && - event.turnItem.output === "CODEX_BG_WAKE_DONE\n" && - event.turnItem.exitCode === 0, - ); - yield* awaitUntil( - () => lateCommandUpdateIndex() > terminalIndex, - "post-settle command projection", - ); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.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), ), ), + ), ); - const backgroundStopCases = [true, false, "still_running", "thread_unloaded"] as const; - const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => { - const stillRunning = terminated === "still_running"; - return makeCodexReplayTranscript({ - scenario: `codex-bg-stop-${terminated}`, - entries: [ - ...backgroundExecTranscript.entries.slice(0, -1), - { - type: "expect_outbound", - label: "terminate-background-command", - frame: { - id: 4, - method: "thread/backgroundTerminals/terminate", - params: { threadId: BG_NATIVE_THREAD, processId: "4242" }, - }, - }, - { - type: "emit_inbound", - label: "terminate-background-command", - frame: - terminated === "thread_unloaded" - ? { - id: 4, - error: { code: -32600, message: `thread not found: ${BG_NATIVE_THREAD}` }, - } - : { id: 4, result: { terminated: terminated === true } }, - }, - ...(terminated === false || stillRunning - ? [ - { - type: "expect_outbound" as const, - frame: { - id: 5, - method: "thread/backgroundTerminals/list", - params: { threadId: BG_NATIVE_THREAD }, - }, - }, - { - type: "emit_inbound" as const, - frame: { - id: 5, - result: { data: stillRunning ? [{ processId: "4242" }] : [], nextCursor: null }, - }, - }, - ] - : []), - ...(stillRunning - ? [ - { - type: "expect_outbound" as const, - frame: { - id: 6, - method: "thread/backgroundTerminals/terminate", - params: { threadId: BG_NATIVE_THREAD, processId: "4242" }, + 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"; + const params = yield* CodexAdapterV2.buildCodexTurnStartParams({ + nativeThreadId, + codexInput: [{ type: "text", text: "work" }], + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + modelSelection: CODEX_TEST_MODEL_SELECTION, + hasT3Mcp: true, + }); + 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" as const, - frame: { id: 6, result: { terminated: false } }, - }, - { - type: "expect_outbound" as const, - frame: { - id: 7, - method: "thread/backgroundTerminals/list", - params: { threadId: BG_NATIVE_THREAD }, + }, + { + 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" as const, - frame: { id: 7, result: { data: [{ processId: "4242" }], nextCursor: null } }, - }, - { - type: "expect_outbound" as const, - frame: { - id: 8, - method: "thread/backgroundTerminals/terminate", - params: { threadId: BG_NATIVE_THREAD, processId: "4242" }, + }, + { type: "emit_inbound", label: "restored", frame: { id: 4, result: {} } }, + { + type: "emit_inbound", + label: "done", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), }, }, - { - type: "emit_inbound" as const, - frame: { id: 8, result: { terminated: true } }, - }, - ] - : []), - backgroundExecTranscript.entries.at(-1)!, - ], - }); - }; - - it.effect.each(backgroundStopCases)( - "stops a command after root completion when termination returns %s", - (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, - 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, - providerTurnId: terminal.providerTurnId, - requestRuntimeRestart: true, - }) - .pipe(Effect.exit); - assert.equal(failed._tag, "Failure"); - assert.isTrue(yield* harness.hasPendingBackgroundWork); - } - yield* harness.runtime.interruptTurn({ + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + 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, - 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), - ), + now: yield* DateTime.now, + attemptId: RunAttemptId.make("context-attempt"), + text: "work", + }), + ); + yield* harness.firstTerminal; + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), - ); - }, + ), + ), ); - it.effect("interrupts a completed run's background command through orchestration", () => { - const transcript = makeBackgroundStopTranscript(true); - return Effect.scoped( + + it.effect("compacts Codex with the native RPC and completes the compaction turn", () => + 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), - ), + 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: "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) => ({ + 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" }), + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + assert.isDefined(harness.runtime.compactThread); + yield* harness.runtime.compactThread!( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("compact-attempt"), + text: "/compact", + }), ); - const replayDriver = yield* CodexReplay.makeReplayDriver(localTranscript); - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - assert.equal( - Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))), - 0, + yield* harness.firstTerminal; + const items = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "compaction" + ? [event.turnItem] + : [], ); - 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, + assert.deepEqual( + items.map((entry) => entry.status), + ["running", "completed"], ); - 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" }, + 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), + ), + ), + ), + ); + + 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, + }, + }, + }, + }, + ]), + ], }); - 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 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, ); - 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* 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.", + }), ); - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("stop-background-command"), - threadId, - runId: run.id, - }); - yield* worker.drain(); - yield* Fiber.join(stopped); - assert.equal( - (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)?.status, - "completed", + 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] + : [], ); - assert.deepEqual( - (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks, - [], + const completed = items.filter( + (item) => item.nativeItemRef?.nativeId === "completed-item", ); - }).pipe( - Effect.provide( - ProviderReplayHarness.layerWithRegistry( - { name: "codex-background-stop", runtimePolicyOverride: { cwd } }, - CodexAdapterV2Testkit.layer({ - transcript: localTranscript, - driver: replayDriver, - }), - { runEffectWorker: false }, - ), - ), - ); - }).pipe(Effect.provide(NodeServices.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" }, - ], - }); - 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 }), + const unfinished = items.filter( + (item) => item.nativeItemRef?.nativeId === "unfinished-item", ); - 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); + const status = outcome === "failed" ? "failed" : "interrupted"; assert.deepEqual( - before?.pendingBackgroundTasks?.map((task) => task.kind), - ["command"], - "the thread still shows the command the gone process never finished", + unfinished.map((item) => item.status), + ["running", status], ); - 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.equal(unfinished[0]?.id, unfinished[1]?.id); + assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000)); assert.deepEqual( - projection.turnItems.flatMap((item) => - item.type === "command_execution" ? [item.status] : [], - ), - ["interrupted"], + unfinished[1]?.completedAt, + DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000), ); - assert.equal(projection.runs.at(-1)?.status, "completed"); assert.deepEqual( - (yield* orchestrator.getThreadShell(threadId))?.pendingBackgroundTasks, - [], + 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( - ProviderReplayHarness.layerWithRegistry( - { name: "codex-background-stop-untracked", runtimePolicyOverride: { cwd } }, - CodexAdapterV2Testkit.layer({ transcript: localTranscript }), - { runEffectWorker: false }, - ), + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), ), - ); - }).pipe(Effect.provide(NodeServices.layer)), - ), + ), + ), ); - const PRE_SETTLE_SCENARIO = "codex-bg-exec-pre-settle"; - const PRE_SETTLE_NATIVE_THREAD = "native-codex-pre-settle-thread"; - const PRE_SETTLE_NATIVE_TURN = "native-codex-pre-settle-turn"; - - const preSettleTranscript = makeCodexReplayTranscript({ - scenario: PRE_SETTLE_SCENARIO, - entries: [ - ...codexReplayPreamble({ - nativeThreadId: PRE_SETTLE_NATIVE_THREAD, - nativeTurnId: PRE_SETTLE_NATIVE_TURN, - prompt: BG_PROMPT, - }), - { - type: "emit_inbound", - label: "item/started/command", - frame: { - method: "item/started", - params: { - item: backgroundCommandItem("inProgress"), - threadId: PRE_SETTLE_NATIVE_THREAD, - turnId: PRE_SETTLE_NATIVE_TURN, - startedAtMs: 1782622440500, - }, - }, - }, - { - type: "emit_inbound", - label: "item/completed/command-pre-settle", - frame: { - method: "item/completed", - params: { - item: backgroundCommandItem("completed"), - threadId: PRE_SETTLE_NATIVE_THREAD, - turnId: PRE_SETTLE_NATIVE_TURN, - completedAtMs: 1782622441000, - }, - }, - }, - { - type: "emit_inbound", - label: "item/completed/root-answer", - frame: { - method: "item/completed", - params: { - item: { - type: "agentMessage", - id: "root-answer-pre-settle", - text: "DONE", - phase: "final_answer", - memoryCitation: null, - }, - threadId: PRE_SETTLE_NATIVE_THREAD, - turnId: PRE_SETTLE_NATIVE_TURN, - completedAtMs: 1782622441500, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: PRE_SETTLE_NATIVE_THREAD, - turn: makeCodexReplayTurn({ id: PRE_SETTLE_NATIVE_TURN, status: "completed" }), - }, - }, - }, - ], - }); - - it.effect("does not request a continuation for a command that completes before settle", () => + it.effect("resumes a provider thread without requesting or decoding its history", () => Effect.scoped( Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(preSettleTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-bg-pre-settle"), - text: BG_PROMPT, - }), - ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "root turn terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "completed"); - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "completed" && - event.turnItem.exitCode === 0, - ), - "pre-settle command projection", - ); + 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 } } }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + const resumed = yield* harness.runtime.resumeThread({ + providerThread: harness.providerThread, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); - 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); + assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId); + assert.equal(resumed.status, "idle"); + assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -5192,289 +2086,278 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - const INTERRUPT_SCENARIO = "codex-interrupt-mid-command"; - const INTERRUPT_NATIVE_THREAD = "native-codex-interrupt-thread"; - const INTERRUPT_NATIVE_TURN = "native-codex-interrupt-turn"; - const INTERRUPT_COMMAND_ITEM = "exec-codex-interrupt-command"; - const INTERRUPT_COMMAND_ITEM_TWO = "exec-codex-interrupt-command-two"; - const INTERRUPT_CHILD_COMMAND_ITEM = "exec-codex-interrupt-child-command"; - const INTERRUPT_CHILD_TIMEOUT_BOUNDARY_ITEM = "exec-codex-interrupt-child-timeout-boundary"; - const INTERRUPT_CHILD_NATIVE_THREAD = "native-codex-interrupt-child-thread"; - const INTERRUPT_CHILD_NATIVE_TURN = "native-codex-interrupt-child-turn"; - const INTERRUPT_LATE_CHILD_NATIVE_TURN = "native-codex-interrupt-late-child-turn"; - const INTERRUPT_LATE_CHILD_2_NATIVE_TURN = "native-codex-interrupt-late-child-2-turn"; - const INTERRUPT_TIMEOUT_BOUNDARY_ITEM = "exec-codex-interrupt-timeout-boundary"; - const INTERRUPT_TIMEOUT_LATE_ITEM = "exec-codex-interrupt-timeout-late"; - const INTERRUPT_COMMAND = "bash -c 'sleep 30; echo SHOULD_NOT_FINISH_CMD_INTERRUPT_FIXTURE'"; - const INTERRUPT_COMMAND_TWO = "bash -c 'sleep 20; echo SECOND_COMMAND'"; - const INTERRUPT_PROMPT = "Run a long foreground command and wait until interrupted."; - - const interruptCommandItem = (status: "inProgress" | "completed"): Record => ({ - type: "commandExecution", - id: INTERRUPT_COMMAND_ITEM, - command: INTERRUPT_COMMAND, - cwd: "/workspace", - processId: "57680", - source: "unifiedExecStartup", - status, - commandActions: [{ type: "unknown", command: INTERRUPT_COMMAND }], - aggregatedOutput: status === "completed" ? "SHOULD_NOT_FINISH_CMD_INTERRUPT_FIXTURE\n" : null, - exitCode: status === "completed" ? 0 : null, - durationMs: status === "completed" ? 30_000 : null, - }); - - const interruptMidCommandTranscript = makeCodexReplayTranscript({ - scenario: INTERRUPT_SCENARIO, - entries: [ - ...codexReplayPreamble({ - nativeThreadId: INTERRUPT_NATIVE_THREAD, - nativeTurnId: INTERRUPT_NATIVE_TURN, - prompt: INTERRUPT_PROMPT, - }), - { - type: "emit_inbound", - label: "item/started/command", - frame: { - method: "item/started", - params: { - item: interruptCommandItem("inProgress"), - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - startedAtMs: 1782622440500, + // regression: #15389 archived native Codex sessions resume via thread/unarchive + it.effect.each( + ( + [ + ["recovers archived-session errors", "session saved-thread is archived", 0, ""], + ["preserves missing-thread errors", "thread not found", 3, "thread not found"], + [ + "propagates unarchive missing-thread errors", + "session saved-thread is archived", + 4, + "thread not found", + ], + [ + "does not retry archived errors twice", + "session saved-thread is archived", + 5, + "session saved-thread is archived", + ], + ] 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), + { + type: "expect_outbound", + label: "resume archived thread", + frame: { id: 3, method: "thread/resume", params }, }, - }, - }, - { - type: "expect_outbound", - label: "turn/interrupt", - frame: { - id: 4, - method: "turn/interrupt", - params: { - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, + { + type: "emit_inbound", + label: "resume error", + frame: { id: 3, error: { code: -32600, message: resumeError } }, }, - }, - }, - { - type: "emit_inbound", - label: "turn/interrupt", - frame: { id: 4, result: {} }, - }, - { - type: "emit_inbound", - label: "item/started/command-two-after-interrupt-response", - frame: { - method: "item/started", - params: { - item: { - ...interruptCommandItem("inProgress"), - id: INTERRUPT_COMMAND_ITEM_TWO, - command: INTERRUPT_COMMAND_TWO, - processId: "57681", - commandActions: [{ type: "unknown", command: INTERRUPT_COMMAND_TWO }], + ]; + if (failAt !== 3) { + entries.push( + { + type: "expect_outbound", + label: "unarchive same thread", + frame: { id: 4, method: "thread/unarchive", params: { threadId: nativeThreadId } }, }, - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - startedAtMs: 1782622440600, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: INTERRUPT_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: INTERRUPT_NATIVE_TURN, - status: "interrupted", - }), - }, - }, - }, - { - type: "expect_outbound", - label: "thread/backgroundTerminals/terminate/one", - frame: { - id: 5, - method: "thread/backgroundTerminals/terminate", - params: { threadId: INTERRUPT_NATIVE_THREAD, processId: "57680" }, - }, - }, - { - type: "emit_inbound", - label: "thread/backgroundTerminals/terminate/one", - frame: { id: 5, result: { terminated: false } }, - }, - { - type: "expect_outbound", - label: "thread/backgroundTerminals/list/after-false", - frame: { - id: 6, - method: "thread/backgroundTerminals/list", - params: { threadId: INTERRUPT_NATIVE_THREAD }, - }, - }, - { - type: "emit_inbound", - label: "thread/backgroundTerminals/list/after-false", - frame: { id: 6, result: { data: [], nextCursor: null } }, - }, - { - type: "expect_outbound", - label: "thread/backgroundTerminals/terminate/two", - frame: { - id: 7, - method: "thread/backgroundTerminals/terminate", - params: { threadId: INTERRUPT_NATIVE_THREAD, processId: "57681" }, - }, - }, - { - type: "emit_inbound", - label: "thread/backgroundTerminals/terminate/two", - frame: { id: 7, result: { terminated: true } }, - }, - { - type: "emit_inbound", - label: "item/completed/command-late", - afterMs: 30_000, - frame: { - method: "item/completed", - params: { - item: interruptCommandItem("completed"), - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - completedAtMs: 1782622465500, - }, - }, - }, - ], - }); + { + 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" }], + }, + }, + }, + }, + ); + } + 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), + ), + ), + ), + ); - it.effect("contains commands that start before and after the interrupt response", () => + it.effect("resolves retryable app-server errors on resumed provider activity", () => Effect.scoped( Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptMidCommandTranscript); + 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: "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: "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-interrupt-mid-command"), - text: INTERRUPT_PROMPT, + attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"), + text: "Open github.com.", }), ); + yield* harness.awaitTerminal(1); - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "running", - ), - "running command item", + const retryItems = harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "error" && + event.turnItem.retry !== undefined + ? [event.turnItem] + : [], ); - - 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, + assert.lengthOf(retryItems, 2); + 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.equal(retryItems[1]?.id, retryItems[0]?.id); + assert.equal(retryItems[1]?.status, "completed"); + assert.equal(retryItems[1]?.title, "Provider recovered"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - - 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; - } - } - 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 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); - - 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 && + const recoveredIndex = harness.events.findIndex( + (event) => event.type === "turn_item.updated" && - event.turnItem.type === "command_execution", - ); - assert.lengthOf( - postTerminalCommandUpdates, - 0, - "late item/completed after interrupt must not project", + event.turnItem.type === "error" && + event.turnItem.status === "completed", ); - - 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", + const resumedCommandIndex = harness.events.findIndex( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "command_execution" && + event.turnItem.input === "pwd", ); - assert.isAtLeast(commandUpdates.length, 2, "start + interrupt terminalization"); - assert.equal(commandUpdates[commandUpdates.length - 1]?.turnItem.status, "interrupted"); + 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), @@ -5483,176 +2366,282 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - const interruptSubagentCommandTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-subagent-command", - entries: [ - ...codexReplayPreamble({ - nativeThreadId: INTERRUPT_NATIVE_THREAD, - nativeTurnId: INTERRUPT_NATIVE_TURN, - prompt: INTERRUPT_PROMPT, - }), - { - type: "emit_inbound", - label: "item/completed/subAgentActivity-started", - frame: { - method: "item/completed", - params: { - item: { - type: "subAgentActivity", - id: "call-codex-interrupt-subagent", - kind: "started", - agentThreadId: INTERRUPT_CHILD_NATIVE_THREAD, - agentPath: "/root/stop_hold", - }, - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - completedAtMs: 1782622441000, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/started/child", - frame: { - method: "turn/started", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: INTERRUPT_CHILD_NATIVE_TURN, - status: "inProgress", + 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), + ), + ), + ), + ); + + const finalAnswerTranscript = ( + scenario: string, + answers: ReadonlyArray<{ + readonly id: string; + readonly text: string; + readonly phase?: "commentary" | "final_answer" | null; + readonly omitPhase?: boolean; + readonly streamed?: boolean; + readonly completionDelayMs?: number; + }>, + ) => { + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const prompt = "Reply with the requested recovery marker."; + return makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), + ...answers.flatMap( + (answer, index): ReadonlyArray => { + const phase = answer.omitPhase + ? {} + : { phase: answer.phase === undefined ? ("final_answer" as const) : answer.phase }; + const completed: CodexReplay.CodexAppServerReplayEntry = { + type: "emit_inbound", + label: `item/completed/${answer.id}`, + ...(answer.completionDelayMs === undefined + ? {} + : { afterMs: answer.completionDelayMs }), + frame: { + method: "item/completed", + params: { + item: { + type: "agentMessage", + id: answer.id, + text: answer.text, + ...phase, + memoryCitation: null, + }, + threadId: nativeThreadId, + turnId: nativeTurnId, + completedAtMs: 1782622441000 + index, + }, + }, + }; + if (!answer.streamed) { + return [completed]; + } + return [ + { + type: "emit_inbound", + label: `item/started/${answer.id}`, + frame: { + method: "item/started", + params: { + item: { + type: "agentMessage", + id: answer.id, + text: "", + ...phase, + memoryCitation: null, + }, + threadId: nativeThreadId, + turnId: nativeTurnId, + startedAtMs: 1782622440500 + index, + }, + }, + }, + { + type: "emit_inbound", + label: `item/agentMessage/delta/${answer.id}`, + frame: { + method: "item/agentMessage/delta", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + itemId: answer.id, + delta: answer.text, + }, + }, + }, + completed, + ]; }, - }, - }, - { - type: "emit_inbound", - label: "item/started/child-command", - frame: { - method: "item/started", - params: { - item: { - ...interruptCommandItem("inProgress"), - id: INTERRUPT_CHILD_COMMAND_ITEM, - processId: "57682", + ), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), }, - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turnId: INTERRUPT_CHILD_NATIVE_TURN, - startedAtMs: 1782622441500, - }, - }, - }, - { - type: "expect_outbound", - label: "turn/interrupt/root", - frame: { - id: 4, - method: "turn/interrupt", - params: { - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/interrupt/root", - frame: { id: 4, result: {} }, - }, - { - type: "expect_outbound", - label: "turn/interrupt/child", - frame: { - id: 5, - method: "turn/interrupt", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turnId: INTERRUPT_CHILD_NATIVE_TURN, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/interrupt/child", - frame: { id: 5, result: {} }, - }, - { - type: "expect_outbound", - label: "thread/backgroundTerminals/terminate/child", - frame: { - id: 6, - method: "thread/backgroundTerminals/terminate", - params: { threadId: INTERRUPT_CHILD_NATIVE_THREAD, processId: "57682" }, - }, - }, - { - type: "emit_inbound", - label: "thread/backgroundTerminals/terminate/child", - frame: { id: 6, result: { terminated: true } }, - }, - { - type: "emit_inbound", - label: "turn/completed/root", - frame: { - method: "turn/completed", - params: { - threadId: INTERRUPT_NATIVE_THREAD, - turn: makeCodexReplayTurn({ id: INTERRUPT_NATIVE_TURN, status: "interrupted" }), - }, - }, - }, - { - type: "emit_inbound", - label: "turn/completed/child-completed-race", - frame: { - method: "turn/completed", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: INTERRUPT_CHILD_NATIVE_TURN, - status: "completed", - }), }, }, - }, - { type: "runtime_exit", status: "success" }, - ], - }); - - const assertChildProviderTerminalBeforeRoot = ( - events: ReadonlyArray, - rootThreadId: ThreadId, - ) => { - const terminalIndex = events.findIndex((event) => event.type === "turn.terminal"); - const childProviderTurnIndex = events.findIndex( - (event) => - event.type === "provider_turn.updated" && - event.threadId !== rootThreadId && - event.providerTurn.status === "interrupted", - ); - const childProviderThreadIndex = events.findIndex( - (event) => - event.type === "provider_thread.updated" && - event.providerThread.appThreadId !== rootThreadId && - event.providerThread.status === "idle", - ); - assert.isAtLeast(childProviderTurnIndex, 0, "child provider turn must terminalize"); - assert.isAtLeast(childProviderThreadIndex, 0, "child provider thread must become idle"); - assert.isAbove( - terminalIndex, - childProviderTurnIndex, - "child provider turn must terminalize before the root run", - ); - assert.isAbove( - terminalIndex, - childProviderThreadIndex, - "child provider thread must become idle before the root run", - ); + ], + }); }; - it.effect("contains descendant commands and keeps Stop authoritative", () => + it.effect("suppresses a trailing empty final answer after a non-empty final answer", () => Effect.scoped( Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptSubagentCommandTranscript); + 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( @@ -5660,53 +2649,16 @@ describe("CodexAdapterV2 post-settle continuation", () => { threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-command"), - text: INTERRUPT_PROMPT, + attemptId: RunAttemptId.make("attempt-codex-redundant-empty-final"), + text: "Reply with the requested recovery marker.", }), ); - yield* awaitUntil( - () => - 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", - ), - "running child command item", - ); - 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); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal"); - 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.deepEqual( + assistantMessages(harness.events).map((event) => event.message.text), + ["CODEX_RECOVERY_OK"], ); - assert.equal(childCommandUpdates.at(-1)?.turnItem.status, "interrupted"); - assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "interrupted"); - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); - assert.isFalse(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -5715,473 +2667,653 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - const childInterruptResponseIndex = interruptSubagentCommandTranscript.entries.findIndex( - (entry) => entry.type === "emit_inbound" && entry.label === "turn/interrupt/child", - ); - const rootInterruptResponseIndex = interruptSubagentCommandTranscript.entries.findIndex( - (entry) => entry.type === "emit_inbound" && entry.label === "turn/interrupt/root", - ); - const interruptSubagentRequestFailureTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-subagent-request-failure", + const BG_SCENARIO = "codex-bg-exec-wake"; + const BG_NATIVE_THREAD = "native-codex-bg-thread"; + const BG_NATIVE_TURN = "native-codex-bg-turn"; + const BG_COMMAND_ITEM = "call-codex-bg-command"; + const BG_COMMAND = "sleep 20 && echo CODEX_BG_WAKE_DONE"; + const BG_PROMPT = "Start the sleep in the background and reply STARTED."; + + const backgroundCommandItem = (status: "inProgress" | "completed"): Record => ({ + type: "commandExecution", + id: BG_COMMAND_ITEM, + command: BG_COMMAND, + cwd: "/workspace", + processId: "4242", + source: "unifiedExecStartup", + status, + commandActions: [{ type: "unknown", command: BG_COMMAND }], + aggregatedOutput: status === "completed" ? "CODEX_BG_WAKE_DONE\n" : null, + exitCode: status === "completed" ? 0 : null, + durationMs: status === "completed" ? 25_000 : null, + }); + + const backgroundExecTranscript = makeCodexReplayTranscript({ + scenario: BG_SCENARIO, entries: [ - ...interruptSubagentCommandTranscript.entries.slice(0, rootInterruptResponseIndex + 1), + ...codexReplayPreamble({ + nativeThreadId: BG_NATIVE_THREAD, + nativeTurnId: BG_NATIVE_TURN, + prompt: BG_PROMPT, + }), + { + type: "emit_inbound", + label: "item/started/command", + frame: { + method: "item/started", + params: { + item: backgroundCommandItem("inProgress"), + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + startedAtMs: 1782622440500, + }, + }, + }, + { + type: "emit_inbound", + label: "item/completed/root-answer", + frame: { + method: "item/completed", + params: { + item: { + type: "agentMessage", + id: "root-answer-bg", + text: "STARTED", + phase: "final_answer", + memoryCitation: null, + }, + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + completedAtMs: 1782622441000, + }, + }, + }, { type: "emit_inbound", - label: "turn/completed/root-before-child-interrupt-failure", + label: "turn/completed", frame: { method: "turn/completed", params: { - threadId: INTERRUPT_NATIVE_THREAD, - turn: makeCodexReplayTurn({ id: INTERRUPT_NATIVE_TURN, status: "interrupted" }), + threadId: BG_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: BG_NATIVE_TURN, status: "completed" }), }, }, }, - ...interruptSubagentCommandTranscript.entries.slice( - rootInterruptResponseIndex + 1, - childInterruptResponseIndex, - ), { type: "emit_inbound", - label: "turn/interrupt/child", + label: "item/completed/command-late", + afterMs: 30_000, frame: { - id: 5, - error: { code: -32_000, message: "child interrupt request failed" }, + method: "item/completed", + params: { + item: backgroundCommandItem("completed"), + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + completedAtMs: 1782622465500, + }, }, }, - { type: "runtime_exit", status: "success" }, ], }); - it.effect("terminalizes descendants before the root when an interrupt request fails", () => - Effect.scoped( + it.effect.each([false, true])( + "keeps commands interrupted after native thread closure (persistent tool: %s)", + (retainContext) => Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptSubagentRequestFailureTranscript); - const now = yield* DateTime.now; - + const notification = (method: string, params: unknown) => ({ + type: "emit_inbound" as const, + label: method, + frame: { method, params }, + }); + const monitor = (status: "inProgress" | "completed") => + notification(status === "inProgress" ? "item/started" : "item/completed", { + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + item: { + type: "dynamicToolCall", + id: "persistent-monitor", + namespace: "grok", + tool: "monitor", + status, + arguments: { persistent: true, command: "tail -f" }, + }, + }); + // Replies fence notification handling on the same protocol reader. + const unsubscribe = (id: number, notifications: ReturnType[] = []) => [ + { + type: "expect_outbound" as const, + label: `unsubscribe-${id}`, + frame: { id, method: "thread/unsubscribe", params: { threadId: BG_NATIVE_THREAD } }, + }, + ...notifications, + { + type: "emit_inbound" as const, + label: `unsubscribe-result-${id}`, + frame: { id, result: { status: "notSubscribed" } }, + }, + ]; + const closed = notification("thread/closed", { threadId: BG_NATIVE_THREAD }); + const transcript = makeCodexReplayTranscript({ + scenario: `codex-background-thread-closed-${retainContext}`, + entries: [ + ...backgroundExecTranscript.entries.slice(0, -2), + ...(retainContext ? [monitor("inProgress")] : []), + backgroundExecTranscript.entries.at(-2)!, + ...unsubscribe(4), + ...unsubscribe(5, [notification("thread/closed", { threadId: "unrelated-thread" })]), + ...unsubscribe(6, [closed]), + ...unsubscribe(7, [ + closed, + notification("item/completed", { + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + item: backgroundCommandItem("completed"), + }), + ...(retainContext ? [monitor("completed")] : []), + ]), + ], + }); + const interrupted = yield* Deferred.make(); + const monitorCompleted = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness(transcript, (event) => { + if (event.type !== "turn_item.updated") return Effect.void; + if ( + event.turnItem.nativeItemRef?.nativeId === BG_COMMAND_ITEM && + event.turnItem.status === "interrupted" + ) { + return Deferred.succeed(interrupted, undefined); + } + return event.turnItem.nativeItemRef?.nativeId === "persistent-monitor" && + event.turnItem.status === "completed" + ? Deferred.succeed(monitorCompleted, undefined) + : Effect.void; + }); yield* harness.runtime.startTurn( makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-request-failure"), - text: INTERRUPT_PROMPT, - }), - ); - yield* awaitUntil( - () => - 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", - ), - "running child command item", - ); - 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 interruptExit = yield* harness.runtime - .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) - .pipe(Effect.exit); - - assert.equal(interruptExit._tag, "Failure"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal"); - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-codex-thread-closed"), + text: BG_PROMPT, + }), + ); + yield* harness.firstTerminal; + const unload = harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + yield* unload; + assert.isTrue(yield* harness.hasPendingBackgroundWork); + yield* unload; + assert.isTrue(yield* harness.hasPendingBackgroundWork); + yield* unload; + assert.equal(yield* harness.hasPendingBackgroundWork, retainContext); + yield* Deferred.await(interrupted); + yield* unload; + if (retainContext) yield* Deferred.await(monitorCompleted); + assert.deepEqual( + { + items: harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === BG_COMMAND_ITEM + ? [event.turnItem.status] + : [], + ), + nodes: harness.events.flatMap((event) => + event.type === "node.updated" && + event.node.nativeItemRef?.nativeId === BG_COMMAND_ITEM + ? [event.node.status] + : [], + ), + roots: harness.terminalEvents().map((event) => event.status), + continuations: harness.continuationRequests.length, + }, + { + items: ["running", "interrupted"], + nodes: ["running", "interrupted"], + roots: ["completed"], + continuations: 0, + }, + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + assert.isFalse( + yield* harness.runtime.hasPendingBackgroundWorkForThread!(harness.providerThread), + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + const backgroundStopCases = [true, false, "still_running", "thread_unloaded"] as const; + const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => { + const stillRunning = terminated === "still_running"; + return makeCodexReplayTranscript({ + scenario: `codex-bg-stop-${terminated}`, + entries: [ + ...backgroundExecTranscript.entries.slice(0, -1), + { + type: "expect_outbound", + label: "terminate-background-command", + frame: { + id: 4, + method: "thread/backgroundTerminals/terminate", + params: { threadId: BG_NATIVE_THREAD, processId: "4242" }, + }, + }, + { + type: "emit_inbound", + label: "terminate-background-command", + frame: + terminated === "thread_unloaded" + ? { + id: 4, + error: { code: -32600, message: `thread not found: ${BG_NATIVE_THREAD}` }, + } + : { id: 4, result: { terminated: terminated === true } }, + }, + ...(terminated === false || stillRunning + ? [ + { + type: "expect_outbound" as const, + frame: { + id: 5, + method: "thread/backgroundTerminals/list", + params: { threadId: BG_NATIVE_THREAD }, + }, + }, + { + type: "emit_inbound" as const, + frame: { + id: 5, + result: { data: stillRunning ? [{ processId: "4242" }] : [], nextCursor: null }, + }, + }, + ] + : []), + ...(stillRunning + ? [ + { + type: "expect_outbound" as const, + frame: { + id: 6, + method: "thread/backgroundTerminals/terminate", + params: { threadId: BG_NATIVE_THREAD, processId: "4242" }, + }, + }, + { + type: "emit_inbound" as const, + frame: { id: 6, result: { terminated: false } }, + }, + { + type: "expect_outbound" as const, + frame: { + id: 7, + method: "thread/backgroundTerminals/list", + params: { threadId: BG_NATIVE_THREAD }, + }, + }, + { + type: "emit_inbound" as const, + frame: { id: 7, result: { data: [{ processId: "4242" }], nextCursor: null } }, + }, + { + type: "expect_outbound" as const, + frame: { + id: 8, + method: "thread/backgroundTerminals/terminate", + params: { threadId: BG_NATIVE_THREAD, processId: "4242" }, + }, + }, + { + type: "emit_inbound" as const, + frame: { id: 8, result: { terminated: true } }, + }, + ] + : []), + backgroundExecTranscript.entries.at(-1)!, + ], + }); + }; + + it.effect.each(backgroundStopCases)( + "stops a command after root completion when termination returns %s", + (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, + 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, + 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), + ), ), - ), - ), - ); - - const childTerminationResponseIndex = interruptSubagentCommandTranscript.entries.findIndex( - (entry) => - entry.type === "emit_inbound" && entry.label === "thread/backgroundTerminals/terminate/child", + ); + }, ); - const interruptSubagentTimeoutTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-subagent-timeout", - entries: [ - ...interruptSubagentCommandTranscript.entries.slice(0, childTerminationResponseIndex + 1), - { - type: "emit_inbound", - label: "item/started/child-timeout-boundary", - frame: { - method: "item/started", - params: { - item: { - ...interruptCommandItem("inProgress"), - id: INTERRUPT_CHILD_TIMEOUT_BOUNDARY_ITEM, - processId: null, - }, - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turnId: INTERRUPT_CHILD_NATIVE_TURN, - startedAtMs: 1782622441600, - }, - }, - }, - ], - }); - - it.effect("terminalizes timed-out descendants before the root", () => - Effect.scoped( + 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 harness = yield* makeCodexReplayHarness(interruptSubagentTimeoutTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-timeout"), - text: INTERRUPT_PROMPT, - }), + 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), + ), ); - yield* awaitUntil( - () => - 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", - ), - "running child command item", + const replayDriver = yield* CodexReplay.makeReplayDriver(localTranscript); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + assert.equal( + Number(yield* spawner.exitCode(ChildProcess.make("git", ["init", "--quiet"], { cwd }))), + 0, ); - 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* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_TIMEOUT_BOUNDARY_ITEM && - event.turnItem.status === "running", + 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 }, + ), ), - "child timeout boundary item", - ); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); - - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal"); - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - const rootCompletionIndex = interruptSubagentCommandTranscript.entries.findIndex( - (entry) => entry.type === "emit_inbound" && entry.label === "turn/completed/root", - ); - const interruptLateSubagentTurnTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-late-subagent-turn", - entries: [ - ...interruptSubagentCommandTranscript.entries.slice(0, rootCompletionIndex), - { - type: "emit_inbound", - label: "turn/started/late-child", - frame: { - method: "turn/started", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: INTERRUPT_LATE_CHILD_NATIVE_TURN, - status: "inProgress", - }), - }, - }, - }, - ...interruptSubagentCommandTranscript.entries.slice(rootCompletionIndex, -1), - { - type: "expect_outbound", - label: "turn/interrupt/late-child", - frame: { - id: 7, - method: "turn/interrupt", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turnId: INTERRUPT_LATE_CHILD_NATIVE_TURN, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/interrupt/late-child", - frame: { id: 7, result: {} }, - }, - { type: "runtime_exit", status: "success" }, - ], - }); - - 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, - }), + ), + 0, ); - yield* awaitUntil( - () => - 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", + 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", ), - "running child command item", - ); - 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* awaitUntil( - () => - harness.events.some( + 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 === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, + event.type === "turn-item.updated" && + event.payload.type === "command_execution" && + event.payload.status === "interrupted", ), - "late child provider turn", - ); - yield* Fiber.join(interruptFiber); - - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal"); - 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, + 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 }, + ), + ), ); - 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), - ), - ), - ), - ); - - const interruptRescanLateSubagentTurnTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-rescan-late-subagent-turn", - entries: [ - ...interruptSubagentCommandTranscript.entries.slice(0, childTerminationResponseIndex + 1), - { - type: "emit_inbound", - label: "turn/started/late-child-1", - frame: { - method: "turn/started", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: INTERRUPT_LATE_CHILD_NATIVE_TURN, - status: "inProgress", - }), - }, - }, - }, - { - type: "expect_outbound", - label: "turn/interrupt/late-child-1", - frame: { - id: 7, - method: "turn/interrupt", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turnId: INTERRUPT_LATE_CHILD_NATIVE_TURN, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/started/late-child-2", - frame: { - method: "turn/started", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: INTERRUPT_LATE_CHILD_2_NATIVE_TURN, - status: "inProgress", - }), - }, - }, - }, - { - type: "emit_inbound", - label: "turn/interrupt/late-child-1", - frame: { id: 7, result: {} }, - }, - { - type: "expect_outbound", - label: "turn/interrupt/late-child-2", - frame: { - id: 8, - method: "turn/interrupt", - params: { - threadId: INTERRUPT_CHILD_NATIVE_THREAD, - turnId: INTERRUPT_LATE_CHILD_2_NATIVE_TURN, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/interrupt/late-child-2", - frame: { id: 8, result: {} }, - }, - { type: "runtime_exit", status: "success" }, - ], + }).pipe(Effect.provide(NodeServices.layer)), + ); }); - it.effect("interrupts descendants discovered only by the final interrupt rescan", () => + it.effect("Stop ends a background command no Codex process tracks any more", () => Effect.scoped( Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptRescanLateSubagentTurnTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-rescan-late-subagent-turn"), - text: INTERRUPT_PROMPT, - }), + 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), + ), ); - yield* awaitUntil( - () => - harness.events.some( + 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 === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.nativeItemRef?.nativeId === INTERRUPT_CHILD_COMMAND_ITEM && - event.turnItem.status === "running", + event.type === "run.updated" && + (event.payload.status === "waiting" || event.payload.status === "completed"), ), - "running child command item", - ); - 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* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN, + 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] : [], ), - "late child 1 provider turn", - ); - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); - - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted root terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - - const rootTerminalIndex = harness.events.findIndex( - (event) => event.type === "turn.terminal", - ); - const lateChild1InterruptedIndex = harness.events.findIndex( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_NATIVE_TURN && - event.providerTurn.status === "interrupted", - ); - const lateChild2InterruptedIndex = harness.events.findIndex( - (event) => - event.type === "provider_turn.updated" && - event.providerTurn.nativeTurnRef?.nativeId === INTERRUPT_LATE_CHILD_2_NATIVE_TURN && - event.providerTurn.status === "interrupted", - ); - assert.isAtLeast( - lateChild1InterruptedIndex, - 0, - "late child 1 must terminalize interrupted", - ); - assert.isAtLeast( - lateChild2InterruptedIndex, - 0, - "late child 2 must terminalize interrupted", - ); - assert.isAbove( - rootTerminalIndex, - lateChild1InterruptedIndex, - "late child 1 must terminalize before the root run", - ); - assert.isAbove( - rootTerminalIndex, - lateChild2InterruptedIndex, - "late child 2 must terminalize before the root run", + ["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: localTranscript }), + { runEffectWorker: false }, + ), + ), ); - assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), + }).pipe(Effect.provide(NodeServices.layer)), ), ); - const interruptTimeoutTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-timeout", + const INTERRUPT_SCENARIO = "codex-interrupt-mid-command"; + const INTERRUPT_NATIVE_THREAD = "native-codex-interrupt-thread"; + const INTERRUPT_NATIVE_TURN = "native-codex-interrupt-turn"; + const INTERRUPT_COMMAND_ITEM = "exec-codex-interrupt-command"; + const INTERRUPT_COMMAND_ITEM_TWO = "exec-codex-interrupt-command-two"; + const INTERRUPT_CHILD_COMMAND_ITEM = "exec-codex-interrupt-child-command"; + const INTERRUPT_CHILD_NATIVE_THREAD = "native-codex-interrupt-child-thread"; + const INTERRUPT_CHILD_NATIVE_TURN = "native-codex-interrupt-child-turn"; + const INTERRUPT_LATE_CHILD_NATIVE_TURN = "native-codex-interrupt-late-child-turn"; + const INTERRUPT_COMMAND = "bash -c 'sleep 30; echo SHOULD_NOT_FINISH_CMD_INTERRUPT_FIXTURE'"; + const INTERRUPT_COMMAND_TWO = "bash -c 'sleep 20; echo SECOND_COMMAND'"; + const INTERRUPT_PROMPT = "Run a long foreground command and wait until interrupted."; + + const interruptCommandItem = (status: "inProgress" | "completed"): Record => ({ + type: "commandExecution", + id: INTERRUPT_COMMAND_ITEM, + command: INTERRUPT_COMMAND, + cwd: "/workspace", + processId: "57680", + source: "unifiedExecStartup", + status, + commandActions: [{ type: "unknown", command: INTERRUPT_COMMAND }], + aggregatedOutput: status === "completed" ? "SHOULD_NOT_FINISH_CMD_INTERRUPT_FIXTURE\n" : null, + exitCode: status === "completed" ? 0 : null, + durationMs: status === "completed" ? 30_000 : null, + }); + + const interruptMidCommandTranscript = makeCodexReplayTranscript({ + scenario: INTERRUPT_SCENARIO, entries: [ ...codexReplayPreamble({ nativeThreadId: INTERRUPT_NATIVE_THREAD, @@ -6237,6 +3369,20 @@ describe("CodexAdapterV2 post-settle continuation", () => { }, }, }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: INTERRUPT_NATIVE_THREAD, + turn: makeCodexReplayTurn({ + id: INTERRUPT_NATIVE_TURN, + status: "interrupted", + }), + }, + }, + }, { type: "expect_outbound", label: "thread/backgroundTerminals/terminate/one", @@ -6249,33 +3395,27 @@ describe("CodexAdapterV2 post-settle continuation", () => { { type: "emit_inbound", label: "thread/backgroundTerminals/terminate/one", - frame: { id: 5, result: { terminated: true } }, + frame: { id: 5, result: { terminated: false } }, }, { - type: "emit_inbound", - label: "item/started/command-at-timeout-boundary", - afterMs: 9_999, + type: "expect_outbound", + label: "thread/backgroundTerminals/list/after-false", frame: { - method: "item/started", - params: { - item: { - ...interruptCommandItem("inProgress"), - id: INTERRUPT_TIMEOUT_BOUNDARY_ITEM, - command: "echo TIMEOUT_BOUNDARY", - processId: null, - commandActions: [{ type: "unknown", command: "echo TIMEOUT_BOUNDARY" }], - }, - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - startedAtMs: 1782622450500, - }, + id: 6, + method: "thread/backgroundTerminals/list", + params: { threadId: INTERRUPT_NATIVE_THREAD }, }, }, + { + type: "emit_inbound", + label: "thread/backgroundTerminals/list/after-false", + frame: { id: 6, result: { data: [], nextCursor: null } }, + }, { type: "expect_outbound", label: "thread/backgroundTerminals/terminate/two", frame: { - id: 6, + id: 7, method: "thread/backgroundTerminals/terminate", params: { threadId: INTERRUPT_NATIVE_THREAD, processId: "57681" }, }, @@ -6283,515 +3423,375 @@ describe("CodexAdapterV2 post-settle continuation", () => { { type: "emit_inbound", label: "thread/backgroundTerminals/terminate/two", - frame: { id: 6, result: { terminated: true } }, + frame: { id: 7, result: { terminated: true } }, }, { type: "emit_inbound", - label: "turn/completed/late", - afterMs: 20_000, + label: "item/completed/command-late", + afterMs: 30_000, frame: { - method: "turn/completed", + method: "item/completed", + params: { + item: interruptCommandItem("completed"), + threadId: INTERRUPT_NATIVE_THREAD, + turnId: INTERRUPT_NATIVE_TURN, + completedAtMs: 1782622465500, + }, + }, + }, + ], + }); + + 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; + + 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", + ), + ); + + 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.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); + + 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; + } + } + 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 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); + + 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 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), + ), + ), + ), + ); + + const interruptSubagentCommandTranscript = makeCodexReplayTranscript({ + scenario: "codex-interrupt-subagent-command", + entries: [ + ...codexReplayPreamble({ + nativeThreadId: INTERRUPT_NATIVE_THREAD, + nativeTurnId: INTERRUPT_NATIVE_TURN, + prompt: INTERRUPT_PROMPT, + }), + { + type: "emit_inbound", + label: "item/completed/subAgentActivity-started", + frame: { + method: "item/completed", + params: { + item: { + type: "subAgentActivity", + id: "call-codex-interrupt-subagent", + kind: "started", + agentThreadId: INTERRUPT_CHILD_NATIVE_THREAD, + agentPath: "/root/stop_hold", + }, + threadId: INTERRUPT_NATIVE_THREAD, + turnId: INTERRUPT_NATIVE_TURN, + completedAtMs: 1782622441000, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/started/child", + frame: { + method: "turn/started", params: { - threadId: INTERRUPT_NATIVE_THREAD, + threadId: INTERRUPT_CHILD_NATIVE_THREAD, turn: makeCodexReplayTurn({ - id: INTERRUPT_NATIVE_TURN, - status: "interrupted", + id: INTERRUPT_CHILD_NATIVE_TURN, + status: "inProgress", }), }, }, }, { type: "emit_inbound", - label: "item/started/command-after-timeout", + label: "item/started/child-command", frame: { method: "item/started", params: { item: { ...interruptCommandItem("inProgress"), - id: INTERRUPT_TIMEOUT_LATE_ITEM, - command: "echo LATE_AFTER_TIMEOUT", - processId: null, - commandActions: [{ type: "unknown", command: "echo LATE_AFTER_TIMEOUT" }], + id: INTERRUPT_CHILD_COMMAND_ITEM, + processId: "57682", }, + threadId: INTERRUPT_CHILD_NATIVE_THREAD, + turnId: INTERRUPT_CHILD_NATIVE_TURN, + startedAtMs: 1782622441500, + }, + }, + }, + { + type: "expect_outbound", + label: "turn/interrupt/root", + frame: { + id: 4, + method: "turn/interrupt", + params: { threadId: INTERRUPT_NATIVE_THREAD, turnId: INTERRUPT_NATIVE_TURN, - startedAtMs: 1782622470500, }, }, }, { type: "emit_inbound", - label: "item/completed/command-late", + label: "turn/interrupt/root", + frame: { id: 4, result: {} }, + }, + { + type: "expect_outbound", + label: "turn/interrupt/child", frame: { - method: "item/completed", + id: 5, + method: "turn/interrupt", params: { - item: interruptCommandItem("completed"), - threadId: INTERRUPT_NATIVE_THREAD, - turnId: INTERRUPT_NATIVE_TURN, - completedAtMs: 1782622465500, + threadId: INTERRUPT_CHILD_NATIVE_THREAD, + turnId: INTERRUPT_CHILD_NATIVE_TURN, }, }, }, - { type: "runtime_exit", status: "success" }, - ], - }); - - it.effect("bounds interrupt settlement and drops late completion events", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptTimeoutTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-timeout"), - text: INTERRUPT_PROMPT, - }), - ); - yield* awaitUntil( - () => - harness.events.filter( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "running", - ).length === 1, - "running command item", - ); - 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 interruptFiber = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId, - }) - .pipe(Effect.forkScoped); - yield* awaitUntil( - () => - harness.events.filter( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "running", - ).length === 2, - "post-interrupt running command item", - ); - - yield* TestClock.adjust("10 seconds"); - yield* Fiber.join(interruptFiber); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "timeout terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - const terminalProviderTurnsBeforeLateEvents = harness.events.filter( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "interrupted", - ); - assert.lengthOf(terminalProviderTurnsBeforeLateEvents, 1); - - const commandUpdatesBeforeLateEvents = harness.events.filter( - ( - event, - ): event is Extract< - ProviderAdapter.ProviderAdapterV2Event, - { type: "turn_item.updated" } - > => event.type === "turn_item.updated" && event.turnItem.type === "command_execution", - ); - const terminalCommands = commandUpdatesBeforeLateEvents.filter( - (event) => - event.turnItem.status === "interrupted" && - event.turnItem.nativeItemRef?.nativeId !== INTERRUPT_TIMEOUT_BOUNDARY_ITEM, - ); - assert.lengthOf(terminalCommands, 2); - const boundaryUpdates = commandUpdatesBeforeLateEvents.filter( - (event) => event.turnItem.nativeItemRef?.nativeId === INTERRUPT_TIMEOUT_BOUNDARY_ITEM, - ); - const lastBoundaryUpdate = boundaryUpdates.at(-1); - assert.isDefined(lastBoundaryUpdate); - assert.equal(lastBoundaryUpdate.turnItem.status, "interrupted"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - - yield* TestClock.adjust("20 seconds"); - for (let attempt = 0; attempt < 100; attempt++) { - yield* Effect.yieldNow; - } - assert.lengthOf(harness.terminalEvents(), 1); - assert.lengthOf( - harness.events.filter( - (event) => - event.type === "provider_turn.updated" && event.providerTurn.status === "interrupted", - ), - terminalProviderTurnsBeforeLateEvents.length, - "late completion must not duplicate provider-turn finalization", - ); - assert.lengthOf( - harness.events.filter( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "command_execution", - ), - commandUpdatesBeforeLateEvents.length, - "late starts and completions must not project after timeout", - ); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - const interruptTerminationFailureTranscript = makeCodexReplayTranscript({ - scenario: "codex-interrupt-termination-failure", - entries: [ - ...interruptMidCommandTranscript.entries - .filter( - (entry) => entry.type === "runtime_exit" || entry.label !== "item/completed/command-late", - ) - .map((entry) => - entry.type === "emit_inbound" && - entry.label === "thread/backgroundTerminals/list/after-false" - ? { - ...entry, - frame: { - id: 6, - result: { - data: [{ processId: "57680" }], - nextCursor: null, - }, - }, - } - : entry, - ), + { + type: "emit_inbound", + label: "turn/interrupt/child", + frame: { id: 5, result: {} }, + }, { type: "expect_outbound", - label: "thread/backgroundTerminals/terminate/one-retry", + label: "thread/backgroundTerminals/terminate/child", frame: { - id: 8, + id: 6, method: "thread/backgroundTerminals/terminate", - params: { threadId: INTERRUPT_NATIVE_THREAD, processId: "57680" }, + params: { threadId: INTERRUPT_CHILD_NATIVE_THREAD, processId: "57682" }, }, }, { type: "emit_inbound", - label: "thread/backgroundTerminals/terminate/one-retry", - frame: { id: 8, result: { terminated: false } }, + label: "thread/backgroundTerminals/terminate/child", + frame: { id: 6, result: { terminated: true } }, }, { - type: "expect_outbound", - label: "thread/backgroundTerminals/list/after-false-retry", + type: "emit_inbound", + label: "turn/completed/root", frame: { - id: 9, - method: "thread/backgroundTerminals/list", - params: { threadId: INTERRUPT_NATIVE_THREAD }, + method: "turn/completed", + params: { + threadId: INTERRUPT_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: INTERRUPT_NATIVE_TURN, status: "interrupted" }), + }, }, }, { type: "emit_inbound", - label: "thread/backgroundTerminals/list/after-false-retry", + label: "turn/completed/child-completed-race", frame: { - id: 9, - result: { data: [{ processId: "57680" }], nextCursor: null }, + method: "turn/completed", + params: { + threadId: INTERRUPT_CHILD_NATIVE_THREAD, + turn: makeCodexReplayTurn({ + id: INTERRUPT_CHILD_NATIVE_TURN, + status: "completed", + }), + }, }, }, { type: "runtime_exit", status: "success" }, ], }); - it.effect("attempts every terminal and cleans up tracking when termination fails", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(interruptTerminationFailureTranscript); - const now = yield* DateTime.now; - - yield* harness.runtime.startTurn( - makeCodexTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-codex-interrupt-termination-failure"), - text: INTERRUPT_PROMPT, - }), - ); - yield* awaitUntil( - () => - harness.events.some( - (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "command_execution" && - event.turnItem.status === "running", - ), - "running command item", - ); - 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 interruptExit = yield* harness.runtime - .interruptTurn({ - providerThread: harness.providerThread, - providerTurnId, - }) - .pipe(Effect.exit); - - assert.equal(interruptExit._tag, "Failure"); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "interrupted terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "interrupted"); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), - ), - ), - ); - - it.effect.each([ - { - name: "usage", - code: "usageLimitExceeded", - notification: false, - expectedClass: "usage_limit", - }, - { name: "rate", code: "rateLimitExceeded", notification: false, expectedClass: "usage_limit" }, - { - name: "ordinary", - code: "contextWindowExceeded", - notification: false, - expectedClass: "provider_error", - }, - { - name: "notification", - code: "usageLimitExceeded", - notification: true, - expectedClass: "usage_limit", - }, - { - name: "replacement", - code: "usageLimitExceeded", - notification: true, - expectedClass: "provider_error", - }, - { - name: "known-reset", - code: "usageLimitExceeded", - notification: false, - expectedClass: "usage_limit", - }, - { - name: "late-reset", - code: "usageLimitExceeded", - notification: false, - expectedClass: "usage_limit", - }, - { - name: "matching-details", - code: "usageLimitExceeded", - notification: true, - expectedClass: "usage_limit", - }, - { - name: "deferred-reset", - code: "usageLimitExceeded", - notification: false, - expectedClass: "usage_limit", - }, - { name: "retry", code: "usageLimitExceeded", notification: true, expectedClass: "usage_limit" }, - ] as const)("classifies Codex terminal failures from $name evidence", (scenario) => + const assertChildProviderTerminalBeforeRoot = ( + events: ReadonlyArray, + rootThreadId: ThreadId, + ) => { + const terminalIndex = events.findIndex((event) => event.type === "turn.terminal"); + const childProviderTurnIndex = events.findIndex( + (event) => + event.type === "provider_turn.updated" && + event.threadId !== rootThreadId && + event.providerTurn.status === "interrupted", + ); + const childProviderThreadIndex = events.findIndex( + (event) => + event.type === "provider_thread.updated" && + event.providerThread.appThreadId !== rootThreadId && + event.providerThread.status === "idle", + ); + assert.isAtLeast(childProviderTurnIndex, 0, "child provider turn must terminalize"); + assert.isAtLeast(childProviderThreadIndex, 0, "child provider thread must become idle"); + assert.isAbove( + terminalIndex, + childProviderTurnIndex, + "child provider turn must terminalize before the root run", + ); + assert.isAbove( + terminalIndex, + childProviderThreadIndex, + "child provider thread must become idle before the root run", + ); + }; + + it.effect("contains descendant commands and keeps Stop authoritative", () => Effect.scoped( Effect.gen(function* () { - const nativeThreadId = `native-limit-${scenario.name}`; - const nativeTurnId = `turn-limit-${scenario.name}`; - const message = "Provider stopped this request."; - 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 transcript = makeCodexReplayTranscript({ - scenario: `codex-limit-${scenario.name}`, - entries: [ - ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), - ...(scenario.name === "known-reset" || 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" as const, - label: "turn/started/child", - frame: { - method: "turn/started", - params: { - threadId: "native-limit-child", - turn: makeCodexReplayTurn({ - id: "limit-child-turn", - status: "inProgress", - }), - }, - }, - }, - ] - : []), - ...(scenario.notification - ? [ - { - type: "emit_inbound" as const, - label: "error", - frame: { - method: "error", - params: { - threadId: nativeThreadId, - turnId: nativeTurnId, - willRetry: scenario.name === "retry", - error: { - message, - codexErrorInfo: scenario.code, - additionalDetails: - scenario.name === "matching-details" - ? "Detailed provider allowance explanation." - : null, - }, - }, - }, - }, - ] - : []), - { - 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" - ? {} - : { codexErrorInfo: scenario.code }), - }, - }, - }, - }, - }, - ...(scenario.name === "late-reset" ? [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", - }), - }, - }, - }, - ] - : []), - ], - }); - const resetReceipt = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness(transcript, (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.failure.resetAt === resetAt - ? Deferred.succeed(resetReceipt, undefined) - : Effect.void, - ); + const harness = yield* makeCodexReplayHarness(interruptSubagentCommandTranscript); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( makeCodexTestTurnInput({ threadId: harness.threadId, providerThread: harness.providerThread, - now: yield* DateTime.now, - text: "Continue.", - attemptId: RunAttemptId.make(`attempt-limit-${scenario.name}`), + now, + attemptId: RunAttemptId.make("attempt-codex-interrupt-subagent-command"), + text: INTERRUPT_PROMPT, }), ); - 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"); - if (scenario.name === "known-reset" || scenario.name === "deferred-reset") - assert.equal(terminal.failure.resetAt, resetAt); - if (scenario.name === "matching-details") - assert.equal(terminal.failure.message, "Detailed provider allowance explanation."); - if (scenario.name === "late-reset") { - yield* Deferred.await(resetReceipt); - const item = harness.events.find( + yield* harness.until(() => + harness.events.some( (event) => event.type === "turn_item.updated" && - event.turnItem.type === "error" && - event.turnItem.failure.resetAt === resetAt, - ); - assert.isDefined(item); - } - if (scenario.name === "retry") assert.equal(terminal.retry?.attempt, 1); + 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"); + assertChildProviderTerminalBeforeRoot(harness.events, harness.threadId); + assert.isFalse(yield* harness.hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -6800,70 +3800,53 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - const FAILED_SCENARIO = "codex-failed-mid-command"; - const FAILED_NATIVE_THREAD = "native-codex-failed-thread"; - const FAILED_NATIVE_TURN = "native-codex-failed-turn"; - const FAILED_COMMAND_ITEM = "exec-codex-failed-command"; - const FAILED_COMMAND = "sleep 30"; - const FAILED_PROMPT = "Run a command that will be abandoned when the turn fails."; - - const failedMidCommandTranscript = makeCodexReplayTranscript({ - scenario: FAILED_SCENARIO, + const rootCompletionIndex = interruptSubagentCommandTranscript.entries.findIndex( + (entry) => entry.type === "emit_inbound" && entry.label === "turn/completed/root", + ); + const interruptLateSubagentTurnTranscript = makeCodexReplayTranscript({ + scenario: "codex-interrupt-late-subagent-turn", entries: [ - ...codexReplayPreamble({ - nativeThreadId: FAILED_NATIVE_THREAD, - nativeTurnId: FAILED_NATIVE_TURN, - prompt: FAILED_PROMPT, - }), + ...interruptSubagentCommandTranscript.entries.slice(0, rootCompletionIndex), { type: "emit_inbound", - label: "item/started/command", + label: "turn/started/late-child", frame: { - method: "item/started", + method: "turn/started", params: { - item: { - type: "commandExecution", - id: FAILED_COMMAND_ITEM, - command: FAILED_COMMAND, - cwd: "/workspace", - processId: "99", - source: "unifiedExecStartup", + threadId: INTERRUPT_CHILD_NATIVE_THREAD, + turn: makeCodexReplayTurn({ + id: INTERRUPT_LATE_CHILD_NATIVE_TURN, status: "inProgress", - commandActions: [{ type: "unknown", command: FAILED_COMMAND }], - aggregatedOutput: null, - exitCode: null, - durationMs: null, - }, - threadId: FAILED_NATIVE_THREAD, - turnId: FAILED_NATIVE_TURN, - startedAtMs: 1782622440500, + }), }, }, }, + ...interruptSubagentCommandTranscript.entries.slice(rootCompletionIndex, -1), { - type: "emit_inbound", - label: "turn/completed", + type: "expect_outbound", + label: "turn/interrupt/late-child", frame: { - method: "turn/completed", + id: 7, + method: "turn/interrupt", params: { - threadId: FAILED_NATIVE_THREAD, - turn: { - ...makeCodexReplayTurn({ - id: FAILED_NATIVE_TURN, - status: "failed", - }), - error: { message: "provider failed mid-command" }, - }, + threadId: INTERRUPT_CHILD_NATIVE_THREAD, + turnId: INTERRUPT_LATE_CHILD_NATIVE_TURN, }, }, }, + { + type: "emit_inbound", + label: "turn/interrupt/late-child", + frame: { id: 7, result: {} }, + }, + { type: "runtime_exit", status: "success" }, ], }); - it.effect("terminalizes running command items before turn.terminal on failed turns", () => + it.effect("interrupts descendants that start after the initial Stop snapshot", () => Effect.scoped( Effect.gen(function* () { - const harness = yield* makeCodexReplayHarness(failedMidCommandTranscript); + const harness = yield* makeCodexReplayHarness(interruptLateSubagentTurnTranscript); const now = yield* DateTime.now; yield* harness.runtime.startTurn( @@ -6871,29 +3854,55 @@ describe("CodexAdapterV2 post-settle continuation", () => { threadId: harness.threadId, providerThread: harness.providerThread, now, - attemptId: RunAttemptId.make("attempt-codex-failed-mid-command"), - text: FAILED_PROMPT, + attemptId: RunAttemptId.make("attempt-codex-interrupt-late-subagent-turn"), + text: INTERRUPT_PROMPT, }), ); - yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed terminal"); - assert.equal(harness.terminalEvents()[0]?.status, "failed"); + 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 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", + 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.isAtLeast(failedCommandIndex, 0); - assert.isAbove( - terminalIndex, - failedCommandIndex, - "failed-turn command terminalization must precede turn.terminal", + 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); - assert.lengthOf(harness.continuationRequests, 0); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), @@ -6902,161 +3911,246 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - const MCP_APP_SCENARIO = "codex-mcp-app-capture"; - const MCP_APP_NATIVE_THREAD = "native-codex-mcp-app-thread"; - const MCP_APP_NATIVE_TURN = "native-codex-mcp-app-turn"; - const MCP_APP_ITEM = "mcp-weather-call"; - const MCP_APP_PROMPT = "Show the weather in Oslo."; - const MCP_APP_RESOURCE = "ui://weather/dashboard"; - const MCP_APP_HTML = "

Weather

"; - const mcpAppToolItem = (status: "inProgress" | "completed") => ({ - type: "mcpToolCall", - id: MCP_APP_ITEM, - server: "weather", - tool: "get_weather", - status, - arguments: { city: "Oslo" }, - mcpAppResourceUri: MCP_APP_RESOURCE, - ...(status === "completed" - ? { result: { content: [{ type: "text", text: "Sunny" }], structuredContent: { temp: 21 } } } - : {}), - }); - - const mcpAppTranscript = makeCodexReplayTranscript({ - scenario: MCP_APP_SCENARIO, - entries: [ - ...codexReplayPreamble({ - nativeThreadId: MCP_APP_NATIVE_THREAD, - nativeTurnId: MCP_APP_NATIVE_TURN, - prompt: MCP_APP_PROMPT, - }), - { - type: "emit_inbound", - label: "item/started/app-tool", - frame: { - method: "item/started", - params: { - item: mcpAppToolItem("inProgress"), - threadId: MCP_APP_NATIVE_THREAD, - turnId: MCP_APP_NATIVE_TURN, - startedAtMs: 1782622440500, - }, - }, - }, - { - type: "emit_inbound", - label: "item/completed/app-tool", - frame: { - method: "item/completed", - params: { - item: mcpAppToolItem("completed"), - threadId: MCP_APP_NATIVE_THREAD, - turnId: MCP_APP_NATIVE_TURN, - completedAtMs: 1782622441500, - }, - }, - }, - { - type: "emit_inbound", - label: "turn/completed", - frame: { - method: "turn/completed", - params: { - threadId: MCP_APP_NATIVE_THREAD, - turn: makeCodexReplayTurn({ id: MCP_APP_NATIVE_TURN, status: "completed" }), + it.effect.each([ + { + name: "usage", + code: "usageLimitExceeded", + notification: false, + expectedClass: "usage_limit", + }, + { + name: "replacement", + code: "usageLimitExceeded", + notification: true, + expectedClass: "provider_error", + }, + { + name: "late-reset", + code: "usageLimitExceeded", + notification: false, + expectedClass: "usage_limit", + }, + { + name: "matching-details", + code: "usageLimitExceeded", + notification: true, + expectedClass: "usage_limit", + }, + { + name: "deferred-reset", + code: "usageLimitExceeded", + notification: false, + expectedClass: "usage_limit", + }, + { name: "retry", code: "usageLimitExceeded", notification: true, expectedClass: "usage_limit" }, + { + name: "exhausted-429", + code: "responseTooManyFailedAttempts", + errorInfo: { responseTooManyFailedAttempts: { httpStatusCode: 429 } }, + notification: false, + expectedClass: "usage_limit", + }, + { + name: "exhausted-500", + code: "responseTooManyFailedAttempts", + errorInfo: { responseTooManyFailedAttempts: { httpStatusCode: 500 } }, + notification: false, + expectedClass: "provider_error", + }, + { + name: "chatgpt-workspace-limit", + code: "other", + details: "subscription_sharing_workplace_individual_usage_limit_exceeded", + notification: true, + expectedClass: "provider_error", + }, + ] 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 = "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 }, + }, + }, }, - }, - }, - { - type: "expect_outbound", - label: "mcpServer/resource/read", - frame: { - id: 4, - method: "mcpServer/resource/read", - params: { threadId: MCP_APP_NATIVE_THREAD, server: "weather", uri: MCP_APP_RESOURCE }, - }, - }, - { - type: "emit_inbound", - label: "mcpServer/resource/read", - frame: { - id: 4, - result: { - contents: [ - { - uri: MCP_APP_RESOURCE, - mimeType: "text/html;profile=mcp-app", - text: MCP_APP_HTML, - _meta: { ui: { csp: { connectDomains: ["https://api.weather.test"] } } }, + }; + const transcript = makeCodexReplayTranscript({ + scenario: `codex-limit-${scenario.name}`, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + ...(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" as const, + label: "turn/started/child", + frame: { + method: "turn/started", + params: { + threadId: "native-limit-child", + turn: makeCodexReplayTurn({ + id: "limit-child-turn", + status: "inProgress", + }), + }, + }, + }, + ] + : []), + ...(scenario.notification + ? [ + { + type: "emit_inbound" as const, + label: "error", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: scenario.name === "retry", + error: { + message, + codexErrorInfo: errorInfo, + additionalDetails: + "details" in scenario + ? scenario.details + : scenario.name === "matching-details" + ? "Detailed provider allowance explanation." + : null, + }, + }, + }, + }, + ] + : []), + { + 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 }), + }, + }, + }, }, - ], - }, - }, - }, - ], - }); - - 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) => + }, + ...(scenario.name === "late-reset" ? [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", + }), + }, + }, + }, + ] + : []), + ], + }); + const resetReceipt = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness(transcript, (event) => event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.status === "completed" - ? Deferred.succeed(appCaptured, event.turnItem) + event.turnItem.type === "error" && + event.turnItem.failure.resetAt === resetAt + ? Deferred.succeed(resetReceipt, 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-mcp-app"), - text: MCP_APP_PROMPT, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-limit-${scenario.name}`), }), ); - 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); - - 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(""; + const mcpAppToolItem = (status: "inProgress" | "completed") => ({ + type: "mcpToolCall", + id: MCP_APP_ITEM, + server: "weather", + tool: "get_weather", + status, + arguments: { city: "Oslo" }, + mcpAppResourceUri: MCP_APP_RESOURCE, + ...(status === "completed" + ? { result: { content: [{ type: "text", text: "Sunny" }], structuredContent: { temp: 21 } } } + : {}), + }); - const orphanedDynamicToolTranscript = makeCodexReplayTranscript({ - scenario: ORPHAN_WAIT_SCENARIO, + const mcpAppTranscript = makeCodexReplayTranscript({ + scenario: MCP_APP_SCENARIO, entries: [ ...codexReplayPreamble({ - nativeThreadId: ORPHAN_WAIT_NATIVE_THREAD, - nativeTurnId: ORPHAN_WAIT_NATIVE_TURN, - prompt: ORPHAN_WAIT_PROMPT, + nativeThreadId: MCP_APP_NATIVE_THREAD, + nativeTurnId: MCP_APP_NATIVE_TURN, + prompt: MCP_APP_PROMPT, }), { type: "emit_inbound", - label: "item/started/completed-wait", + label: "item/started/app-tool", frame: { method: "item/started", params: { - item: { - type: "mcpToolCall", - id: COMPLETED_WAIT_ITEM, - server: "t3-code", - tool: "t3_thread_wait", - status: "inProgress", - arguments: { threadId: "thread:completed-wait", timeoutMs: 30000 }, - }, - threadId: ORPHAN_WAIT_NATIVE_THREAD, - turnId: ORPHAN_WAIT_NATIVE_TURN, + item: mcpAppToolItem("inProgress"), + threadId: MCP_APP_NATIVE_THREAD, + turnId: MCP_APP_NATIVE_TURN, startedAtMs: 1782622440500, }, }, }, { type: "emit_inbound", - label: "item/completed/completed-wait", + label: "item/completed/app-tool", frame: { method: "item/completed", params: { - item: { - type: "mcpToolCall", - id: COMPLETED_WAIT_ITEM, - server: "t3-code", - tool: "t3_thread_wait", - status: "completed", - arguments: { threadId: "thread:completed-wait", timeoutMs: 30000 }, - result: { content: [{ type: "text", text: "idle" }] }, - }, - threadId: ORPHAN_WAIT_NATIVE_THREAD, - turnId: ORPHAN_WAIT_NATIVE_TURN, + item: mcpAppToolItem("completed"), + threadId: MCP_APP_NATIVE_THREAD, + turnId: MCP_APP_NATIVE_TURN, completedAtMs: 1782622441500, }, }, }, { type: "emit_inbound", - label: "item/started/orphan-wait", - frame: { - method: "item/started", - params: { - item: { - type: "mcpToolCall", - id: ORPHAN_WAIT_ITEM, - server: "t3-code", - tool: "t3_thread_wait", - status: "inProgress", - arguments: { - threadId: - "thread:delegated-task:command%3Amcp%3Aaafffab1-e811-458a-ae83-558e542c61ff%3Adelegate-task%3Areview-mobile-reconnect-opus-20260815", - timeoutMs: 30000, - }, - }, - threadId: ORPHAN_WAIT_NATIVE_THREAD, - turnId: ORPHAN_WAIT_NATIVE_TURN, - startedAtMs: 1782622442500, - }, - }, - }, - { - type: "emit_inbound", - label: "item/started/persistent-monitor", + label: "turn/completed", frame: { - method: "item/started", + method: "turn/completed", params: { - item: { - type: "dynamicToolCall", - id: PERSISTENT_MONITOR_ITEM, - namespace: "grok", - tool: "monitor", - status: "inProgress", - arguments: { persistent: true, command: "tail -f" }, - }, - threadId: ORPHAN_WAIT_NATIVE_THREAD, - turnId: ORPHAN_WAIT_NATIVE_TURN, - startedAtMs: 1782622443500, + threadId: MCP_APP_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: MCP_APP_NATIVE_TURN, status: "completed" }), }, }, }, { - type: "emit_inbound", - label: "turn/completed", + type: "expect_outbound", + label: "mcpServer/resource/read", frame: { - method: "turn/completed", - params: { - threadId: ORPHAN_WAIT_NATIVE_THREAD, - turn: makeCodexReplayTurn({ - id: ORPHAN_WAIT_NATIVE_TURN, - status: "completed", - }), - }, + id: 4, + method: "mcpServer/resource/read", + params: { threadId: MCP_APP_NATIVE_THREAD, server: "weather", uri: MCP_APP_RESOURCE }, }, }, { type: "emit_inbound", - label: "item/completed/persistent-monitor", - afterMs: 30_000, + label: "mcpServer/resource/read", frame: { - method: "item/completed", - params: { - item: { - type: "dynamicToolCall", - id: PERSISTENT_MONITOR_ITEM, - namespace: "grok", - tool: "monitor", - status: "completed", - arguments: { persistent: true, command: "tail -f" }, - result: { content: [{ type: "text", text: "stopped" }] }, - }, - threadId: ORPHAN_WAIT_NATIVE_THREAD, - turnId: ORPHAN_WAIT_NATIVE_TURN, - completedAtMs: 1782622473500, + id: 4, + result: { + contents: [ + { + uri: MCP_APP_RESOURCE, + mimeType: "text/html;profile=mcp-app", + text: MCP_APP_HTML, + _meta: { ui: { csp: { connectDomains: ["https://api.weather.test"] } } }, + }, + ], }, }, }, ], }); - it.effect( - "terminalizes leftover nonpersistent dynamic tools when a completed turn never closes them", - () => - Effect.scoped( - Effect.gen(function* () { - const monitorCompleted = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness(orphanedDynamicToolTranscript, (event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === PERSISTENT_MONITOR_ITEM && - event.turnItem.status === "completed" - ? Deferred.succeed(monitorCompleted, 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-orphan-wait"), - text: ORPHAN_WAIT_PROMPT, - }), - ); - yield* harness.firstTerminal; - assert.equal(harness.terminalEvents()[0]?.status, "completed"); + 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; - const terminalIndex = harness.events.findIndex((event) => event.type === "turn.terminal"); - const cancelledWait = harness.events.find( - (event, index) => - index < terminalIndex && - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === ORPHAN_WAIT_ITEM && - event.turnItem.status === "cancelled", - ); - assert.isDefined(cancelledWait); - assert.isAbove( - terminalIndex, - harness.events.indexOf(cancelledWait!), - "orphaned wait terminalization must precede turn.terminal", - ); + 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 completedWaitStatuses = new Set( - harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === COMPLETED_WAIT_ITEM - ? [event.turnItem.status] - : [], - ), - ); - assert.isTrue( - completedWaitStatuses.has("completed"), - "the wait that received item/completed must stay completed", - ); - assert.isFalse( - completedWaitStatuses.has("cancelled"), - "a completed wait must not be rewritten as cancelled", - ); + 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 persistentMonitorStatuses = new Set( - harness.events.flatMap((event) => - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === PERSISTENT_MONITOR_ITEM - ? [event.turnItem.status] - : [], - ), - ); - assert.isTrue(persistentMonitorStatuses.has("running")); - assert.isFalse( - persistentMonitorStatuses.has("cancelled"), - "persistent monitors must remain running after the root turn completes", - ); - assert.isTrue( - yield* harness.hasPendingBackgroundWork, - "persistent dynamic tools must keep the session residency pin until they complete", - ); + 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 }, + }); - yield* TestClock.adjust("30 seconds"); - yield* Deferred.await(monitorCompleted); - const lateMonitorUpdateIndex = harness.events.findIndex( - (event, index) => - index > terminalIndex && - event.type === "turn_item.updated" && - event.turnItem.type === "dynamic_tool" && - event.turnItem.nativeItemRef?.nativeId === PERSISTENT_MONITOR_ITEM && - event.turnItem.status === "completed", - ); - assert.isAbove( - lateMonitorUpdateIndex, - terminalIndex, - "persistent tool completion must follow turn.terminal", - ); - assert.lengthOf(harness.terminalEvents(), 1); - assert.isFalse(yield* harness.hasPendingBackgroundWork); - }).pipe( - Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), - ), + 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("`); + const tree = String((await takeSnapshot()).accessibilityTree); + expect(tree.match(/\/url: data:text\/plain,…$/gm)).toHaveLength(8); + expect(tree).toContain("/url: data:,…"); + expect(tree).toContain("/url: https://example.com/data:report,2026"); + expect(tree).toMatch(/link "data:text\/plain,label" \[ref=t3-/); + expect(tree).not.toMatch(/PAYLOAD|tail|charset|\u2028/); + expect(tree).toContain('/url: "\\"data:text/plain,relative"'); + }); + + it("redacts a data: link whose scheme a password value would mask", async () => { + await page.setContent(` + +
Key`); + const tree = String((await takeSnapshot()).accessibilityTree); + expect(tree).toContain("/url: ••••••••:text/plain,…"); + expect(tree).not.toContain("PAYLOAD"); + }); + it("rejects refs from another tab", async () => { await page.setContent(""); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "same label"); @@ -186,16 +220,6 @@ describe("server browser element refs", () => { await expect(ServerBrowserPage.click(other, { locator })).rejects.toThrow(/another tab/); }); - it("revokes refs on takeover and issues usable refs in the next snapshot", async () => { - await page.setContent(""); - const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue"); - ServerBrowserPage.invalidateRefs(page); - await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/); - const fresh = buttonLocator((await takeSnapshot()).accessibilityTree, "continue"); - await ServerBrowserPage.click(page, { locator: fresh }); - expect(await page.locator("button").textContent()).toBe("clicked"); - }); - it("revokes refs after navigation even when labels are identical", async () => { await page.goto("data:text/html,"); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue"); @@ -203,13 +227,6 @@ describe("server browser element refs", () => { await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/); }); - it("only accepts refs from the most recent snapshot", async () => { - await page.setContent(""); - const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "continue"); - await takeSnapshot(); - await expect(ServerBrowserPage.click(page, { locator })).rejects.toThrow(/stale/); - }); - it.each(["aria-ref=e1", " aria-ref=e1", "css=body >> aria-ref=e1"])( "does not allow native refs to bypass generation validation (%s)", async (locator) => { @@ -219,14 +236,6 @@ describe("server browser element refs", () => { }, ); - it("preserves CSS selectors containing an aria-ref attribute", async () => { - await page.setContent( - '', - ); - await ServerBrowserPage.click(page, { selector: 'button[aria-ref="save"]' }); - expect(await page.locator("button").textContent()).toBe("saved"); - }); - it("preserves quoted attribute values containing ref engine text", async () => { await page.setContent( '', @@ -234,101 +243,6 @@ describe("server browser element refs", () => { await ServerBrowserPage.click(page, { selector: 'button[data-example=" >> aria-ref=e1"]' }); expect(await page.locator("button").textContent()).toBe("saved"); }); - - it("right-clicks, double-clicks, hovers, selects, and drags like a pointer user", async () => { - await page.setContent(` - - -
hover me
- -
card
lane
-

- `); - await ServerBrowserPage.click(page, { locator: "#target", button: "right" }); - await ServerBrowserPage.click(page, { locator: "#target", clickCount: 2 }); - await ServerBrowserPage.hover(page, { locator: "#hover" }); - expect(await page.isVisible("#menu")).toBe(true); - expect(await ServerBrowserPage.select(page, { locator: "#size", values: ["Large"] })).toEqual({ - selected: ["l"], - }); - await ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }); - expect(await page.textContent("#log")).toBe("context;dblclick;drop;"); - await expect( - ServerBrowserPage.select(page, { locator: "#target", values: ["s"] }), - ).rejects.toMatchObject({ tag: "PreviewAutomationTargetNotEditableError" }); - }); - - it("shows the agent's pointer at each target before the action reaches the page", async () => { - await page.setContent(` - -
tip
-
card
-
lane
- `); - const shown: Array = []; - const pointer: ServerBrowserPage.PointerReporter = async ({ x, y }, phase) => { - const seen = await page.evaluate("window.seen.length"); - shown.push(`${phase}@${Math.round(x)},${Math.round(y)} after ${seen}`); - }; - await ServerBrowserPage.click(page, { locator: "#go" }, pointer); - await ServerBrowserPage.hover(page, { locator: "#tip" }, pointer); - await ServerBrowserPage.drag(page, { source: "#card", target: "#lane" }, pointer); - expect(shown).toEqual([ - "click@140,50 after 0", - "move@330,50 after 1", - "move@40,140 after 2", - "move@270,140 after 2", - ]); - expect(await page.evaluate("window.seen")).toEqual(["click", "hover", "drop"]); - }); - - it("presents a headless page as Chrome, with client hints that agree", async () => { - await presentAsChrome(cdp, { platform: "linux", arch: "x64" }); - // userAgentData exists only in secure contexts; https comes from a route. - let secChUa: string | undefined; - await page.route("https://example.test/", (route) => { - secChUa = route.request().headers()["sec-ch-ua"]; - return route.fulfill({ contentType: "text/html", body: "

hi

" }); - }); - await page.goto("https://example.test/"); - const identity = (await page.evaluate(`(async () => ({ - userAgent: navigator.userAgent, - brands: navigator.userAgentData.brands.map((brand) => brand.brand), - full: (await navigator.userAgentData.getHighEntropyValues(["fullVersionList"])) - .fullVersionList.map((brand) => brand.brand), - }))()`)) as { userAgent: string; brands: string[]; full: string[] }; - expect(identity.userAgent).not.toContain("Headless"); - expect(identity.userAgent).toMatch(/ Chrome\/\d+\.0\.0\.0 /); - expect(identity.brands).toContain("Google Chrome"); - expect([...identity.brands, ...identity.full].join()).not.toContain("Headless"); - expect(secChUa).toContain('"Google Chrome"'); - expect(secChUa).not.toContain("Headless"); - }); - - it("stops an evaluation at its deadline so the page answers the next one", async () => { - await expect( - ServerBrowserPage.evaluate(cdp, { expression: "for (;;) {}" }, 200), - ).rejects.toMatchObject({ tag: "PreviewAutomationTimeoutError" }); - expect(await ServerBrowserPage.evaluate(cdp, { expression: "1 + 1" }, 2_000)).toBe(2); - }); }); describe("server browser drag", () => { @@ -357,8 +271,10 @@ describe("server browser drag", () => { ); void settled.then(() => (finished = true)); // Two macrotask turns: Node reports a rejection nobody observed after the first. - await new Promise((resolve) => setImmediate(resolve)); - await new Promise((resolve) => setImmediate(resolve)); + for (let turn = 0; turn < 2; turn++) { + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Node emits unhandledRejection only between macrotasks; no promise can mark that point. + await new Promise((resolve) => setImmediate(resolve)); + } expect(finished).toBe(false); targetBox.resolve(box); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index 908de1b6c48be..129eaa8a89bb5 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off globalDate:off globalTimers:off - Playwright callbacks run outside the Effect runtime. import { + type BrowserRecordingFrameRate, PROVIDER_SEND_TURN_MAX_FILE_BYTES, type PreviewAutomationClickInput, type PreviewAutomationConsoleEntry, @@ -18,7 +19,7 @@ import { type PreviewAutomationWaitForInput, } from "@t3tools/contracts"; import { constVoid } from "effect/Function"; -import type { CDPSession, Frame, Locator, Page } from "playwright-core"; +import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core"; import * as NodeCrypto from "node:crypto"; import { BrowserControlInterrupted } from "./SessionControl.ts"; @@ -39,7 +40,10 @@ export class ServerBrowserOperationError extends Error { } } -export const toOperationError = (cause: unknown): ServerBrowserOperationError => { +export const toOperationError = ( + cause: unknown, + timeoutMs?: number, +): ServerBrowserOperationError => { if (cause instanceof BrowserControlInterrupted) return new ServerBrowserOperationError( "PreviewAutomationControlInterruptedError", @@ -50,7 +54,11 @@ export const toOperationError = (cause: unknown): ServerBrowserOperationError => const message = cause instanceof Error ? cause.message : String(cause); const firstLine = message.split("\n")[0] ?? message; if (cause instanceof Error && cause.name === "TimeoutError") { - return new ServerBrowserOperationError("PreviewAutomationTimeoutError", firstLine); + return new ServerBrowserOperationError( + "PreviewAutomationTimeoutError", + firstLine, + timeoutMs === undefined ? undefined : { timeoutMs }, + ); } if ( /while parsing selector|Unknown engine|Unexpected token|strict mode violation/i.test(message) @@ -97,7 +105,6 @@ const targetLocator = ( ): Locator | null => { const selector = input.locator ?? input.selector; if (selector === undefined) return null; - // Ignore quoted/escaped CSS values when looking for a selector-engine boundary. const engines = selector.replace( /\\.|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`/g, " ", @@ -149,13 +156,59 @@ const SNAPSHOT_SCRIPT = `(() => { })()`; const MASKED_VALUE = "••••••••"; + +/** + * A `data:` URL carries its content, which can be a whole file, and URLs and diagnostics + * reach tool results and provider logs. Keeps only the media type: the payload can hold any + * character and parameters are page-chosen too. + */ +export const withoutDataPayload = (url: string) => { + // Read the scheme as a browser would: it ignores leading controls and spaces, and tabs and + // newlines anywhere. A snapshot's YAML value may be quoted and escaped; an escape that isn't a + // tab or newline still decodes to something that can't start a scheme. + const value = url + .replace(/^["']/, "") + .replace(/\\(x[\da-f]{2}|u[\da-f]{4}|.)/gi, (_escape, code: string) => + code.length > 1 + ? String.fromCharCode(Number.parseInt(code.slice(1), 16)) + : ({ t: "\t", n: "\n", r: "\r", '"': '"', "\\": "\\" }[code] ?? "\u0001"), + ) + .replace(/[\t\n\r]/g, "") + // eslint-disable-next-line no-control-regex -- URL parsing ignores these controls. + .replace(/^[\u0000-\u0020]+/, ""); + const parsed = /^data:([^,;]*)/i.exec(value); + if (!parsed) return url; + const type = parsed[1]!.trim(); + const mediaType = /^[\w.+-]{1,64}\/[\w.+-]{1,64}$/.test(type) ? type : ""; + return `data:${mediaType},…`; +}; + +/** + * Chromium's own console messages, which carry no arguments, quote `data:` URLs whole, as in a + * blocked navigation or a CSP violation. Everything after the first one goes, since Chromium + * accepts any type and a payload can hold any character. What a page logs itself is its own + * text, like anything else it shows, so it stays. + */ +export const consoleText = (message: ConsoleMessage) => + message.args().length > 0 + ? message.text() + : message.text().replace(/(? + tree + .split("\n") + .map((line) => { + const url = /^(\s*- \/url: )(.*)$/s.exec(line); + return url ? url[1] + withoutDataPayload(url[2]!) : line; + }) + .join("\n"); + // The broker waits 15s for the host; a snapshot, retry included, answers well before. const SNAPSHOT_TIMEOUT_MS = 10_000; -// How long a frame in another process gets to answer; one that crashed never does. const FRAME_ANSWER_MS = 1_000; -// Values the page draws as dots (password fields, and text fields whose CSS -// draws dots), normalized like accessible text. Open shadow roots included. +// Include password and CSS-masked text in open shadow roots, normalized like accessible text. const DOTTED_SCRIPT = `(() => { const values = []; const visit = (root) => { @@ -188,10 +241,10 @@ const tooBusy = () => const VALUE_TOO_LONG = "A password field holds a value too long to hide, so no snapshot was taken."; -/** A frame in another process keeps one CDP session, so none pile up across snapshots. */ +/** Reuse one CDP session per out-of-process frame across snapshots. */ const frameSessions = new WeakMap>(); -/** The value, or undefined when it fails or takes longer than a frame may. */ +/** Returns undefined on failure or frame timeout. */ const answered = (promise: Promise) => { let timer: ReturnType | undefined; const late = new Promise((resolve) => { @@ -200,14 +253,7 @@ const answered = (promise: Promise) => { return Promise.race([promise.catch(() => undefined), late]).finally(() => clearTimeout(timer)); }; -/** - * Reads dotted values in isolated worlds, where page script can't change what `value` - * returns, through the CDP session of the process each frame renders in. A frame in - * another process that can't be attached, as in desktop tabs where only the page can, - * is read in the page's own world, where its script can change `value`. `read` gives - * each reader's values, or undefined for one that didn't answer, and fails when the - * page's own frames don't or frames came or went. - */ +/** Isolated worlds prevent spoofing; desktop out-of-process frames use page worlds. Missing own-frame reads or changed frames fail; other missing reads return undefined. */ const openReaders = async (page: Page, cdp: CDPSession) => { const frames = page.frames(); const owners = new Map( @@ -220,8 +266,7 @@ const openReaders = async (page: Page, cdp: CDPSession) => { return [frame, await session] as const; } catch (cause) { frameSessions.delete(frame); - // CdpRelay refuses all but the page. Any other refusal reads the frame through its - // parent's session, which fails the read if the frame isn't there. + // CdpRelay supports only the page; other refusals fall back to the parent session, failing if the frame is absent. const desktop = String(cause).includes("Only this preview tab's page can be attached"); return [frame, desktop ? null : undefined] as const; } @@ -293,10 +338,8 @@ const openReaders = async (page: Page, cdp: CDPSession) => { ]; return { readers, - /** Readers that didn't answer `before` aren't asked again. */ read: async (before?: ReadonlyArray) => { const now = page.frames(); - // A frame added since the readers opened has none. if (now.length !== frames.length || now.some((frame, i) => frame !== frames[i])) { throw pageChanged(); } @@ -310,12 +353,7 @@ const openReaders = async (page: Page, cdp: CDPSession) => { }; }; -/** - * Matches each value as the snapshot prints it: raw, as a JSON name, as a - * quoted value, and with '' for each quote inside a quoted key. A value under - * four characters only matches between non-word characters; inside other words - * it would mask unrelated text. - */ +/** Short values need word boundaries to avoid masking unrelated text. */ const dottedPattern = (values: ReadonlyArray) => { const sources = values .flatMap((value) => { @@ -338,8 +376,7 @@ const dottedPattern = (values: ReadonlyArray) => { if (sources.length === 0) return undefined; const pattern = new RegExp(sources.join("|"), "gu"); try { - // Compiles it now, for one-byte and two-byte text: one too large fails only when it - // first runs on each, naming every value. + // Force regex compilation for one-byte and two-byte strings now; size errors name every value. pattern.test(""); pattern.test("\u2022"); } catch { @@ -348,16 +385,11 @@ const dottedPattern = (values: ReadonlyArray) => { return pattern; }; -// `- role "name" [attribute]...: value`, the key single-quoted when it holds ": ". A name -// that starts and ends with "/" prints unquoted. Only Playwright's own attributes count, so -// text around a value in a name can't pass for one. +// Playwright single-quotes keys containing ': ' and leaves /.../ names unquoted. Recognize only its attributes so name text cannot spoof them. const TREE_LINE = /^(\s*- '?[^\s"':]+)( "(?:[^"\\]|\\.)*"| \/(?:.*?\/)?)?((?: \[(?:active|checked(?:=mixed)?|disabled|expanded|level=\d+|pressed(?:=mixed)?|selected|ref=(?:f\d+)?e\d+|cursor=pointer|box=-?\d+,-?\d+,\d+,\d+)\])*'?)(:.*)?$/; -/** - * Masks each value on a line, except one that only matches inside the role or attributes, - * so refs keep working. A "/.../" name has no closing mark, so a value can seem to cross it. - */ +/** Preserve roles and attributes so refs work; unquoted /.../ names can make matches cross boundaries. */ const maskTree = (tree: string, dotted: RegExp) => tree .split("\n") @@ -373,19 +405,77 @@ const maskTree = (tree: string, dotted: RegExp) => }) .join("\n"); +/** Chromium sizes the capture, so the reported size is read from the PNG header. */ +const pngSize = (base64: string) => { + const header = Buffer.from(base64.slice(0, 32), "base64"); + return { width: header.readUInt32BE(16), height: header.readUInt32BE(20) }; +}; + +type Viewport = { readonly width: number; readonly height: number }; + +/** + * A page's display ratio and CSS viewport, read in an isolated world since page script can + * reassign `devicePixelRatio`, `innerWidth`, and `innerHeight` in its own, and its page zoom. + */ +const readPageMetrics = async (cdp: CDPSession) => { + const { frameTree } = await cdp.send("Page.getFrameTree"); + const { executionContextId } = await cdp.send("Page.createIsolatedWorld", { + frameId: frameTree.frame.id, + worldName: "t3-preview-metrics", + }); + let { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics"); + // Desktop zoom applies asynchronously; bracket the CSS metrics to reject a torn read. + for (let attempt = 0; attempt < 3; attempt += 1) { + const zoom = cssVisualViewport.zoom ?? 1; + const { result } = await cdp.send("Runtime.evaluate", { + expression: "({ ratio: devicePixelRatio, width: innerWidth, height: innerHeight })", + contextId: executionContextId, + returnByValue: true, + }); + ({ cssVisualViewport } = await cdp.send("Page.getLayoutMetrics")); + if ((cssVisualViewport.zoom ?? 1) === zoom) { + const { ratio, width, height } = result.value as { + readonly ratio: number; + readonly width: number; + readonly height: number; + }; + return { + ratio, + width, + height, + zoom, + offset: { x: cssVisualViewport.pageX * zoom, y: cssVisualViewport.pageY * zoom }, + }; + } + } + throw new Error( + "The page's zoom kept changing while the snapshot read its size. Try the snapshot again.", + ); +}; + // Scaled captures repaint live screencasts, so callers pause them. Clips use document offsets. export const captureViewport = async ( page: Page, cdp: CDPSession, - options: { readonly format: "png" | "jpeg"; readonly quality?: number; readonly scale: number }, + options: { + readonly format: "png" | "jpeg"; + readonly quality?: number; + readonly scale: number; + readonly viewport?: Viewport; + readonly offset?: { readonly x: number; readonly y: number } | undefined; + }, ) => { let clip; if (options.scale < 1) { - const viewport = page.viewportSize() ?? { width: 1280, height: 800 }; - const { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics"); + const viewport = options.viewport ?? page.viewportSize() ?? { width: 1280, height: 800 }; + let offset = options.offset; + if (!offset) { + const { cssVisualViewport } = await cdp.send("Page.getLayoutMetrics"); + const zoom = cssVisualViewport.zoom ?? 1; + offset = { x: cssVisualViewport.pageX * zoom, y: cssVisualViewport.pageY * zoom }; + } clip = { - x: cssVisualViewport.pageX, - y: cssVisualViewport.pageY, + ...offset, ...viewport, scale: options.scale, }; @@ -401,25 +491,45 @@ export const captureViewport = async ( type SnapshotInput = { readonly page: Page; readonly cdp: CDPSession; - readonly renderScale: number; + /** Headless pages render at the scale the server set; a desktop page at its display's. */ + readonly renderScale: number | "display"; readonly consoleEntries: ReadonlyArray; readonly networkEntries: ReadonlyArray; readonly actionTimeline: PreviewAutomationSnapshot["actionTimeline"]; }; +/** The scale a page renders at and its viewport in device-independent pixels, a clip's units. */ +const renderingOf = async (input: SnapshotInput) => { + if (input.renderScale !== "display") { + const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 }; + return { renderScale: input.renderScale, viewport, offset: undefined }; + } + // The display ratio a desktop page reports includes its page zoom, and its sizes are CSS pixels. + const page = await readPageMetrics(input.cdp); + return { + renderScale: page.ratio / page.zoom, + offset: page.offset, + viewport: { + width: Math.round(page.width * page.zoom), + height: Math.round(page.height * page.zoom), + }, + }; +}; + const capture = async ( input: SnapshotInput, deadline: number, ): Promise => { - const viewport = input.page.viewportSize() ?? { width: 1280, height: 800 }; - const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * input.renderScale)); + const { renderScale, viewport, offset } = await renderingOf(input); + // A late metrics reply must not begin a capture after viewers have resumed. + if (Date.now() >= deadline) throw tooBusy(); + const scale = Math.min(1, MAX_SCREENSHOT_WIDTH / (viewport.width * renderScale)); const state = refsFor(input.page); invalidateRefs(input.page); const generation = state.generation; const { readers, read } = await openReaders(input.page, input.cdp); const before = await read(); - // Taken between the reads, so a value that changes during either fails the comparison. - // Awaited after the tree: a capture that fails has finished its tree before a retry starts. + // Bracket the tree with value reads to detect changes; await tree completion before retrying failed captures. const pageAndScreenshot = Promise.all([ input.page.evaluate(SNAPSHOT_SCRIPT) as Promise< Pick< @@ -427,7 +537,7 @@ const capture = async ( "url" | "title" | "loading" | "visibleText" | "interactiveElements" > >, - captureViewport(input.page, input.cdp, { format: "png", scale }), + captureViewport(input.page, input.cdp, { format: "png", scale, viewport, offset }), ]); void pageAndScreenshot.catch(constVoid); // Leaves time for the second read; a frame that never loads holds the tree until then. @@ -441,8 +551,7 @@ const capture = async ( if (after.some((values, i) => values && JSON.stringify(values) !== JSON.stringify(before[i]))) throw pageChanged(); const dotted = dottedPattern(after.flatMap((values) => values ?? [])); - // A frame that didn't answer both times, such as one that crashed, can only hold values the - // tree shows if the tree shows its content. + // Unread frames can expose values only if their content appears in the tree. const unread = readers.flatMap((reader, i) => (after[i] ? [] : reader.frames)); const filled = /^\s*- iframe (?:\[active\] )?\[ref=(\S+?)\].*:$/gm; for (const [, ref] of unread.length ? tree.matchAll(filled) : []) { @@ -455,7 +564,10 @@ const capture = async ( const [page, data] = await pageAndScreenshot; if (state.generation !== generation) throw pageChanged(); const mask = (text: string) => (dotted ? text.replace(dotted, MASKED_VALUE) : text); - const accessibilityTree = (dotted ? maskTree(tree, dotted) : tree) + // Redacted before the cut, so a payload crossing it can't leave its start showing, and before + // masking, which could hide the `data:` scheme behind a password value's dots. + const redacted = withoutTreeDataPayloads(tree); + const accessibilityTree = (dotted ? maskTree(redacted, dotted) : redacted) .slice(0, MAX_VISIBLE_TEXT_LENGTH) .replace(/\[ref=((?:f\d+)?e\d+)\]/g, (_match, nativeRef: string) => { const ref = `t3-${generation}-${nativeRef}`; @@ -464,8 +576,7 @@ const capture = async ( }); return { ...page, - // Text that holds a value would otherwise show where the tree masked it. Masked before - // the cut, so a value crossing it can't leave its start showing. + // Mask text before truncating so a value crossing the cut cannot leak its prefix. visibleText: mask(page.visibleText).slice(0, MAX_VISIBLE_TEXT_LENGTH), accessibilityTree, consoleEntries: [...input.consoleEntries], @@ -474,8 +585,7 @@ const capture = async ( screenshot: { mimeType: "image/png", data, - width: Math.round(viewport.width * input.renderScale * scale), - height: Math.round(viewport.height * input.renderScale * scale), + ...pngSize(data), }, }; }; @@ -491,9 +601,7 @@ export const snapshot = async (input: SnapshotInput): Promise Date.now() < deadline && snapshotTurns.get(input.page) === turn && @@ -510,10 +618,7 @@ export const snapshot = async (input: SnapshotInput): Promise { (locator !== null || (await target.count()) > 0) && (await target.evaluate( (element) => { - // Like the desktop host: an enabled text control or contenteditable - // that actually takes focus. Anything else would swallow the text or - // send it to whichever field had focus before. + // Require an enabled, focused text target to avoid losing input or sending it to the previous field. const control = element as unknown as { readonly type?: string; readonly disabled?: boolean; @@ -662,8 +765,7 @@ export const drag = async ( const source = targetLocator(page, { locator: input.source })!; const target = targetLocator(page, { locator: input.target })!; await pointer(await targetPoint(page, source, {}, timeout), "move"); - // Observe the drag's outcome as it starts: a rejection nobody handles while the cursor - // moves exits the server. + // Observe drag rejection immediately; an unhandled rejection during cursor movement exits the server. const dragFailure = source.dragTo(target, { timeout }).then( () => null, (error: unknown) => ({ error }), @@ -696,11 +798,7 @@ export const scroll = async (page: Page, input: PreviewAutomationScrollInput) => await locator.evaluate((element, [x, y]) => element.scrollBy(x, y), delta); }; -/** - * Runs an agent's expression, bounded by its request's deadline. Past it, the - * page's script is terminated and the call fails, so the tab's control queue - * frees for the next request instead of waiting on the script. - */ +/** Terminate expired page scripts so a hung expression cannot block the tab's control queue. */ export const evaluate = async ( cdp: CDPSession, input: PreviewAutomationEvaluateInput, @@ -793,7 +891,7 @@ export const parseNetError = (errorText: string) => { return { description, code: NET_ERROR_CODES[description] ?? -2 }; }; -export const RECORDING_ENCODER_SCRIPT = `(() => { +export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => `(() => { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); const chunks = []; @@ -862,8 +960,8 @@ export const RECORDING_ENCODER_SCRIPT = `(() => { canvas.width = bitmap.width; canvas.height = bitmap.height; const mimeType = ["video/mp4;codecs=avc1.640033", "video/webm;codecs=vp9", "video/webm"].find((type) => MediaRecorder.isTypeSupported(type)); - const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * 30 * 0.05)); - recorder = new MediaRecorder(canvas.captureStream(30), { mimeType, videoBitsPerSecond: bitsPerSecond }); + const bitsPerSecond = Math.min(50e6, Math.max(2.5e6, bitmap.width * bitmap.height * ${frameRate} * 0.05)); + recorder = new MediaRecorder(canvas.captureStream(${frameRate}), { mimeType, videoBitsPerSecond: bitsPerSecond }); started = new Promise((resolve, reject) => { recorder.onstart = resolve; recorder.onerror = (event) => reject(event.error); diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts index 6b2d24802d247..d3f4781829a85 100644 --- a/apps/server/src/preview/ServerBrowserStream.test.ts +++ b/apps/server/src/preview/ServerBrowserStream.test.ts @@ -133,8 +133,7 @@ it.effect.each([ received.resolve(); }); yield* Effect.promise(() => received.promise); - // The ack follows every mutation on the socket, so this is also a barrier - // proving all preceding inputs were processed, without a timing sleep. + // The socket ack follows every mutation, providing a barrier without sleeps. yield* Effect.promise(() => acked.promise); expect(frames).toEqual([frame]); expect(viewports).toEqual([{ type: "viewport", width: 1280, height: 800 }]); @@ -215,7 +214,6 @@ 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"]); - // Frames 2 and 3 were superseded before they could be sent. expect(released).toEqual([2, 3]); next = Promise.withResolvers(); diff --git a/apps/server/src/preview/ServerBrowserStream.ts b/apps/server/src/preview/ServerBrowserStream.ts index 536d3f2c19205..ad42eaf5d729d 100644 --- a/apps/server/src/preview/ServerBrowserStream.ts +++ b/apps/server/src/preview/ServerBrowserStream.ts @@ -51,164 +51,164 @@ const parseMessage = (chunk: Uint8Array | string): unknown => { } }; -const makeHandler = (browser: ServerBrowser.ServerBrowser["Service"]) => - Effect.gen(function* () { - const request = yield* HttpServerRequest.HttpServerRequest; - const url = HttpServerRequest.toURL(request); - if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 }); - if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) { - return yield* serveDownload(browser, url.value.searchParams); - } - if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) { - return request.method === "POST" - ? yield* receiveUpload(browser, url.value.searchParams) - : HttpServerResponse.text("Method Not Allowed", { status: 405 }); - } - if ( - url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` || - request.headers.upgrade?.toLowerCase() !== "websocket" - ) { - return HttpServerResponse.text("Not Found", { status: 404 }); - } - const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope); - const params = url.value.searchParams; - const canOperate = - session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false"; - const threadId = params.get("threadId") ?? ""; - const tabId = params.get("tabId") ?? ""; - if (threadId.length === 0 || tabId.length === 0) { - return HttpServerResponse.text("Not Found", { status: 404 }); - } - return yield* Effect.scoped( - Effect.gen(function* () { - const attached = yield* browser - .attachViewer({ - threadId, - tabId, - canOperate, - maxWidth: intParam(params, "maxWidth", 1280, 7680), - maxHeight: intParam(params, "maxHeight", 800, 4320), - quality: intParam(params, "quality", DEFAULT_QUALITY, 100), - }) - .pipe( - Effect.map((viewer) => ({ _tag: "attached" as const, viewer })), - Effect.catchTags({ - ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }), - ServerBrowserLaunchError: (error) => { - const setup = hostSetup(error.cause); - return setup === undefined - ? Effect.fail(error) - : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) }); - }, - }), - ); - const incoming = NodeHttpServerRequest.toIncomingMessage(request); - // JPEGs are already compressed. Disabling deflate also keeps all - // pending writes in the socket buffer we bound below, not a zlib queue. - delete incoming.headers["sec-websocket-extensions"]; - const transport = incoming.socket; - const socket = yield* request.upgrade; - const reader = yield* socket.reader; - const writer = yield* socket.writer; - // A refused upgrade reads as an auth failure to ticket clients, so a - // missing tab is a close code they stop on. - const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed")); - if (attached._tag === "gone") { - yield* gone; - return HttpServerResponse.empty(); - } - if (attached._tag === "hostSetup") { - yield* writer.write( - new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason), - ); - return HttpServerResponse.empty(); - } - const viewer = attached.viewer; - // `write` returns once the frame is queued, so Chromium's ack for each - // frame waits for the viewer's `ack` message instead. Only one frame - // is on the wire and only the newest waits behind it, so replies never - // queue behind stale images on a slow link. - let inFlight: Effect.Effect | null = null; - let pending: Frame | null = null; - const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe( - Effect.andThen(Effect.interrupt), +// Request middleware owns tracing, including long-lived WebSocket sessions. +const makeHandler = Effect.fnUntraced(function* (browser: ServerBrowser.ServerBrowser["Service"]) { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) return HttpServerResponse.text("Bad Request", { status: 400 }); + if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/download`) { + return yield* serveDownload(browser, url.value.searchParams); + } + if (url.value.pathname === `${PREVIEW_STREAM_ROUTE_PREFIX}/upload`) { + return request.method === "POST" + ? yield* receiveUpload(browser, url.value.searchParams) + : HttpServerResponse.text("Method Not Allowed", { status: 405 }); + } + if ( + url.value.pathname !== `${PREVIEW_STREAM_ROUTE_PREFIX}/ws` || + request.headers.upgrade?.toLowerCase() !== "websocket" + ) { + return HttpServerResponse.text("Not Found", { status: 404 }); + } + const session = yield* authenticateMediaRequest(AuthOrchestrationReadScope); + const params = url.value.searchParams; + const canOperate = + session.scopes.includes(AuthPreviewOperateScope) && params.get("interactive") !== "false"; + const threadId = params.get("threadId") ?? ""; + const tabId = params.get("tabId") ?? ""; + if (threadId.length === 0 || tabId.length === 0) { + return HttpServerResponse.text("Not Found", { status: 404 }); + } + return yield* Effect.scoped( + Effect.gen(function* () { + const attached = yield* browser + .attachViewer({ + threadId, + tabId, + canOperate, + maxWidth: intParam(params, "maxWidth", 1280, 7680), + maxHeight: intParam(params, "maxHeight", 800, 4320), + quality: intParam(params, "quality", DEFAULT_QUALITY, 100), + }) + .pipe( + Effect.map((viewer) => ({ _tag: "attached" as const, viewer })), + Effect.catchTags({ + ServerBrowserTabNotFoundError: () => Effect.succeed({ _tag: "gone" as const }), + ServerBrowserLaunchError: (error) => { + const setup = hostSetup(error.cause); + return setup === undefined + ? Effect.fail(error) + : Effect.succeed({ _tag: "hostSetup" as const, reason: encodeHostSetup(setup) }); + }, + }), + ); + const incoming = NodeHttpServerRequest.toIncomingMessage(request); + // JPEGs are already compressed. Disabling deflate also keeps all + // pending writes in the socket buffer we bound below, not a zlib queue. + delete incoming.headers["sec-websocket-extensions"]; + const transport = incoming.socket; + const socket = yield* request.upgrade; + const reader = yield* socket.reader; + const writer = yield* socket.writer; + // A refused upgrade reads as an auth failure to ticket clients, so a + // missing tab is a close code they stop on. + const gone = writer.write(new Socket.CloseEvent(TAB_GONE_CODE, "tab closed")); + if (attached._tag === "gone") { + yield* gone; + return HttpServerResponse.empty(); + } + if (attached._tag === "hostSetup") { + yield* writer.write( + new Socket.CloseEvent(PREVIEW_STREAM_HOST_SETUP_CLOSE_CODE, attached.reason), ); - const write = (data: Uint8Array | string) => - Effect.suspend(() => { - const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength; - if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) { - return disconnectSlowViewer; + return HttpServerResponse.empty(); + } + const viewer = attached.viewer; + // `write` returns once the frame is queued, so Chromium's ack for each + // frame waits for the viewer's `ack` message instead. Only one frame + // is on the wire and only the newest waits behind it, so replies never + // queue behind stale images on a slow link. + let inFlight: Effect.Effect | null = null; + let pending: Frame | null = null; + const disconnectSlowViewer = Effect.sync(() => transport.destroy()).pipe( + Effect.andThen(Effect.interrupt), + ); + const write = (data: Uint8Array | string) => + Effect.suspend(() => { + const bytes = typeof data === "string" ? Buffer.byteLength(data) : data.byteLength; + if (transport.writableLength + bytes + 14 > MAX_SOCKET_BUFFER_BYTES) { + return disconnectSlowViewer; + } + return writer.write(data); + }); + const sendFrame = (frame: Frame) => { + inFlight = frame.ack; + return write(frame.data); + }; + const sendOutput = Queue.take(viewer.output).pipe( + Effect.flatMap((output) => { + switch (output._tag) { + case "frame": { + if (inFlight === null) return sendFrame(output); + const superseded = pending; + pending = output; + // Never sent, but Chromium still waits for its ack. + return superseded ? Effect.forkScoped(superseded.ack) : Effect.void; } - return writer.write(data); - }); - const sendFrame = (frame: Frame) => { - inFlight = frame.ack; - return write(frame.data); - }; - const sendOutput = Queue.take(viewer.output).pipe( - Effect.flatMap((output) => { - switch (output._tag) { - case "frame": { - if (inFlight === null) return sendFrame(output); - const superseded = pending; - pending = output; - // Never sent, but Chromium still waits for its ack. - return superseded ? Effect.forkScoped(superseded.ack) : Effect.void; - } - case "viewport": - case "control": - case "clipboard": - case "download": - case "fileChooser": - case "fileChooserClosed": - case "popup": - case "pointer": - case "probe": { - const { _tag: type, ...data } = output; - return write(JSON.stringify({ type, ...data })); - } - case "gone": - return gone.pipe(Effect.andThen(Effect.interrupt)); - case "reconnect": - return writer - .write(new Socket.CloseEvent(1012, "reconnect")) - .pipe(Effect.andThen(Effect.interrupt)); + case "viewport": + case "control": + case "clipboard": + case "download": + case "fileChooser": + case "fileChooserClosed": + case "popup": + case "pointer": + case "probe": { + const { _tag: type, ...data } = output; + return write(JSON.stringify({ type, ...data })); } - }), - ); - const receive = (chunk: Uint8Array | string) => { - const message = parseMessage(chunk); - // Ownership serializes actions in the service. Keep reading so dialog - // replies and takeover can unblock an action already waiting on the page. - if (!isAck(message)) - return canOperate - ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid) - : Effect.void; - const ack = inFlight; - const next = pending; - inFlight = null; - pending = null; - // Forked: Chromium acks are paced and must not hold up input. - return Effect.andThen( - ack ? Effect.forkScoped(ack) : Effect.void, - next ? sendFrame(next) : Effect.void, - ); - }; - const receiveInput = reader.pull.pipe( - Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })), + case "gone": + return gone.pipe(Effect.andThen(Effect.interrupt)); + case "reconnect": + return writer + .write(new Socket.CloseEvent(1012, "reconnect")) + .pipe(Effect.andThen(Effect.interrupt)); + } + }), + ); + const receive = (chunk: Uint8Array | string) => { + const message = parseMessage(chunk); + // Ownership serializes actions in the service. Keep reading so dialog + // replies and takeover can unblock an action already waiting on the page. + if (!isAck(message)) + return canOperate + ? viewer.input(message).pipe(Effect.forkScoped, Effect.asVoid) + : Effect.void; + const ack = inFlight; + const next = pending; + inFlight = null; + pending = null; + // Forked: Chromium acks are paced and must not hold up input. + return Effect.andThen( + ack ? Effect.forkScoped(ack) : Effect.void, + next ? sendFrame(next) : Effect.void, ); - return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput)); - }), - ).pipe( - Effect.catchTags({ - ServerBrowserLaunchError: (error) => - Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe( - Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })), - ), - }), - Effect.catch(() => Effect.succeed(HttpServerResponse.empty())), - ); - }); + }; + const receiveInput = reader.pull.pipe( + Effect.flatMap((chunks) => Effect.forEach(chunks, receive, { discard: true })), + ); + return yield* Effect.raceFirst(Effect.forever(sendOutput), Effect.forever(receiveInput)); + }), + ).pipe( + Effect.catchTags({ + ServerBrowserLaunchError: (error) => + Effect.logWarning("server preview browser failed to start", { cause: error.cause }).pipe( + Effect.as(HttpServerResponse.text("Service Unavailable", { status: 503 })), + ), + }), + Effect.catch(() => Effect.succeed(HttpServerResponse.empty())), + ); +}); const hostSetup = (cause: unknown): PreviewStreamHostSetup | undefined => isSandboxError(cause) @@ -220,28 +220,32 @@ const isSandboxError = Schema.is(PreviewBrowserHost.PreviewBrowserSandboxError); const isLibrariesError = Schema.is(PreviewBrowserHost.PreviewBrowserLibrariesError); const encodeHostSetup = Schema.encodeSync(Schema.fromJsonString(PreviewStreamHostSetup)); -const serveDownload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) => - Effect.gen(function* () { - yield* authenticateMediaRequest(AuthOrchestrationReadScope); - const download = yield* browser.openDownload({ - threadId: params.get("threadId") ?? "", - tabId: params.get("tabId") ?? "", - downloadId: params.get("id") ?? "", - }); - if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 }); - return yield* HttpServerResponse.file(download.value.path, { - headers: assetResponseHeaders(download.value.path, { - download: true, - fileName: download.value.fileName, - }), - }); +// The request span already covers this download route. +const serveDownload = Effect.fnUntraced(function* ( + browser: ServerBrowser.ServerBrowser["Service"], + params: URLSearchParams, +) { + yield* authenticateMediaRequest(AuthOrchestrationReadScope); + const download = yield* browser.openDownload({ + threadId: params.get("threadId") ?? "", + tabId: params.get("tabId") ?? "", + downloadId: params.get("id") ?? "", + }); + if (Option.isNone(download)) return HttpServerResponse.text("Not Found", { status: 404 }); + return yield* HttpServerResponse.file(download.value.path, { + headers: assetResponseHeaders(download.value.path, { + download: true, + fileName: download.value.fileName, + }), }); +}); const UPLOAD_MAX_FILE_BYTES = 100 * 1024 * 1024; const UPLOAD_MAX_FILES = 20; -const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) => - Effect.gen(function* () { +// The request span already covers this upload route. +const receiveUpload = Effect.fnUntraced( + function* (browser: ServerBrowser.ServerBrowser["Service"], params: URLSearchParams) { yield* authenticateMediaRequest(AuthPreviewOperateScope); const request = yield* HttpServerRequest.HttpServerRequest; const fs = yield* FileSystem.FileSystem; @@ -276,7 +280,9 @@ const receiveUpload = (browser: ServerBrowser.ServerBrowser["Service"], params: return answered ? HttpServerResponse.empty({ status: 204 }) : HttpServerResponse.text("The page's file picker is no longer open.", { status: 409 }); - }).pipe(Effect.scoped); + }, + (effect, _browser, _params) => effect.pipe(Effect.scoped), +); export const routeLayer = HttpRouter.use((router) => Effect.gen(function* () { diff --git a/apps/server/src/preview/SessionControl.test.ts b/apps/server/src/preview/SessionControl.test.ts index 42eabc212ac03..a5971f010a57e 100644 --- a/apps/server/src/preview/SessionControl.test.ts +++ b/apps/server/src/preview/SessionControl.test.ts @@ -157,16 +157,6 @@ describe("SessionControl", () => { expect(control.generation).toBe(1); }); - it("does not let a failed action poison the serial queue", async () => { - const control = new SessionControl("agent"); - await expect( - control.agent("agent", async () => { - throw new Error("navigation failed"); - }), - ).rejects.toThrow("navigation failed"); - await expect(control.agent("agent", async () => "recovered")).resolves.toBe("recovered"); - }); - it("lets any agent act on a tab no agent opened, but only while no human controls it", async () => { const control = new SessionControl(null); await expect(control.agent("agent-a", async () => "acted")).resolves.toBe("acted"); diff --git a/apps/server/src/preview/SessionControl.ts b/apps/server/src/preview/SessionControl.ts index 9e4396d697c43..de02f32a1f774 100644 --- a/apps/server/src/preview/SessionControl.ts +++ b/apps/server/src/preview/SessionControl.ts @@ -11,12 +11,19 @@ export class BrowserControlInterrupted extends Error { } } +const settle = (work: Promise) => + work.then( + () => undefined, + () => undefined, + ); + /** Reserves control immediately, but drains running work before the new owner can act. */ export class SessionControl { readonly agentId: string | null; private readonly onGenerationChange: () => void; private tail: Promise = Promise.resolve(); private pending: Promise = Promise.resolve(); + private readonly handoff = new Set>(); private owner: string | null = null; private epoch = 0; private closed = false; @@ -45,11 +52,15 @@ export class SessionControl { /** An action can respond before its navigation commits, while later actions still wait. */ track(work: Promise) { - const settled = work.then( - () => undefined, - () => undefined, - ); - this.pending = Promise.all([this.pending, settled]).then(() => undefined); + this.pending = Promise.all([this.pending, settle(work)]).then(() => undefined); + } + + /** Viewer input stays responsive, but control handoffs still drain its navigations. */ + trackUntilHandoff(work: Promise) { + const settled = settle(work).finally(() => { + this.handoff.delete(settled); + }); + this.handoff.add(settled); } private assertOpen() { @@ -62,13 +73,19 @@ export class SessionControl { this.onGenerationChange(); } - private async action(allowed: () => boolean, run: () => Promise) { + private async action(allowed: () => boolean, run: () => Promise, deadlineMs?: number) { this.assertOpen(); if (!allowed()) throw new BrowserControlInterrupted("You do not control this browser tab."); const epoch = this.epoch; return this.enqueue(async () => { this.assertOpen(); if (epoch !== this.epoch || !allowed()) throw new BrowserControlInterrupted(); + if (deadlineMs !== undefined && performance.now() >= deadlineMs) { + throw new DOMException( + "This browser request expired before it could start.", + "TimeoutError", + ); + } return run(); }); } @@ -77,7 +94,7 @@ export class SessionControl { return this.agentId === null || this.agentId === agentId; } - agent(agentId: string, run: () => Promise) { + agent(agentId: string, run: () => Promise, deadlineMs?: number) { if (!this.agentMayAct(agentId)) return Promise.reject( new BrowserControlInterrupted("This tab belongs to another agent.", "agentMismatch"), @@ -86,17 +103,14 @@ export class SessionControl { return Promise.reject( new BrowserControlInterrupted("A human controls this tab.", "humanControl"), ); - return this.action(() => this.agentMayAct(agentId) && this.owner === null, run); + return this.action(() => this.agentMayAct(agentId) && this.owner === null, run, deadlineMs); } agentCanActNow(agentId: string) { return this.agentMayAct(agentId) && this.owner === null; } - /** - * A read that needs no control and does not queue, so an agent can look at - * a page while a human drives it without holding up the human's input. - */ + /** Read without control or queueing so agents can observe without delaying human input. */ observe(run: () => Promise) { this.assertOpen(); return run(); @@ -131,7 +145,10 @@ export class SessionControl { ); } this.changeOwner(null); - await this.enqueue(afterDrain); + await this.enqueue(async () => { + await Promise.all(this.handoff); + await afterDrain(); + }); } async disconnect(viewerId: string, afterDrain?: () => Promise) { diff --git a/apps/server/src/preview/testing/DesktopPipeLifecycle.fixture.ts b/apps/server/src/preview/testing/DesktopPipeLifecycle.fixture.ts deleted file mode 100644 index b9fee70bf39fc..0000000000000 --- a/apps/server/src/preview/testing/DesktopPipeLifecycle.fixture.ts +++ /dev/null @@ -1,57 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - Entry point for the inherited-pipe shutdown regression test. -import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as Console from "effect/Console"; -import * as Context from "effect/Context"; -import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; -import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Stream from "effect/Stream"; - -import * as ServerSettings from "../../serverSettings.ts"; - -import * as ServerConfig from "../../config.ts"; -import * as DesktopTelemetryReceiver from "../../resourceTelemetry/DesktopTelemetryReceiver.ts"; -import * as DesktopBrowserChannel from "../DesktopBrowserChannel.ts"; - -const key = { threadId: "thread-1", tabId: "tab-1" }; - -Effect.gen(function* () { - const base = yield* ServerConfig.ServerConfig.pipe( - Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-pipe-lifecycle-" })), - ); - const context = yield* Layer.build( - Layer.merge(DesktopBrowserChannel.layer, DesktopTelemetryReceiver.layer).pipe( - Layer.provide(ServerSettings.layerTest()), - Layer.provide( - Layer.succeed(ServerConfig.ServerConfig, { - ...base, - desktopBrowserFd: 3, - desktopBrowserControlFd: 4, - desktopTelemetryFd: 5, - desktopTelemetryControlFd: 6, - }), - ), - ), - ); - const browser = Context.get(context, DesktopBrowserChannel.DesktopBrowserChannel); - const telemetry = Context.get(context, DesktopTelemetryReceiver.DesktopTelemetryReceiver); - const health = yield* telemetry.subscribeHealth; - const healthy = yield* health.changes.pipe( - Stream.filter((value) => value.status === "healthy"), - Stream.runHead, - Effect.forkScoped, - ); - const detached = yield* browser.detached.pipe(Stream.runHead, Effect.forkScoped); - yield* Console.log("ready"); - if (!(yield* browser.awaitAttached(key, "5 seconds"))) { - return yield* Effect.die("The browser attach message was not received."); - } - yield* Fiber.join(healthy); - yield* Console.log("attached"); - yield* Fiber.join(detached); - const endpoint = yield* Effect.exit(Effect.scoped(browser.endpoint(key))); - if (Exit.isSuccess(endpoint)) return yield* Effect.die("A detached tab received an endpoint."); - yield* Console.log("verified"); -}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain); diff --git a/apps/server/src/process/agentScope.test.ts b/apps/server/src/process/agentScope.test.ts index 396fc22987d43..44e9d6dbf4c2a 100644 --- a/apps/server/src/process/agentScope.test.ts +++ b/apps/server/src/process/agentScope.test.ts @@ -4,23 +4,19 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { describe, expect, it } from "@effect/vitest"; +import { assert, describe, expect, it } from "@effect/vitest"; +import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import { ChildProcessSpawner } from "effect/process"; +import * as Logger from "effect/Logger"; +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 { - agentSliceMemoryLimits, - classifyScope, - make, - ownedAgentSlice, - type ScopeState, -} from "./agentScope.ts"; - -const GiB = 1024 ** 3; +import { classifyScope, make, ownedAgentSlice, type ScopeState } from "./agentScope.ts"; const running: ScopeState = { loadState: "loaded", @@ -39,47 +35,40 @@ describe("classifyScope", () => { expect(classifyScope({ ...running, populated: false })).toBe("stopping"); expect(classifyScope({ ...running, activeState: "deactivating" })).toBe("stopping"); }); - - it("does not wait on a live agent or a scope that ended for another reason", () => { - expect(classifyScope(running)).toBe("running"); - expect(classifyScope({ ...running, activeState: "inactive", populated: undefined })).toBe( - "gone", - ); - expect(classifyScope({ ...running, loadState: "not-found", activeState: "inactive" })).toBe( - "gone", - ); - }); }); -describe("agentSliceMemoryLimits", () => { - it("leaves 6 GB before throttling and 4 GB before a kill on large machines", () => { - expect(agentSliceMemoryLimits(64 * GiB)).toEqual({ high: 58 * GiB, max: 60 * GiB }); - }); - - it("still gives agents most of a small machine", () => { - expect(agentSliceMemoryLimits(8 * GiB)).toEqual({ high: 4 * GiB, max: 6 * GiB }); - }); -}); +interface FakeUnit { + activeState: string; + result: string; + controlGroup?: string; +} const withFakeSystemd = ( body: (input: { readonly scope: Effect.Success; - readonly units: Map; + readonly units: Map; readonly calls: ReadonlyArray>; readonly stateDir: string; + readonly cgroupRoot: string; }) => Effect.Effect, + // A user manager older than systemd 253 rejects OOMPolicy on scopes. + { + oomPolicy = true, + stopFails = false, + }: { readonly oomPolicy?: boolean; readonly stopFails?: boolean } = {}, ) => Effect.gen(function* () { const bin = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-agent-scope-")); for (const name of ["systemd-run", "systemctl", "agent"]) { NodeFS.writeFileSync(NodePath.join(bin, name), "", { mode: 0o755 }); } - const units = new Map(); + const cgroupRoot = NodePath.join(bin, "cgroup"); + const units = new Map(); const calls: Array> = []; - const output = (stdout: string): ProcessRunner.ProcessRunOutput => ({ + const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({ stdout, stderr: "", - code: ChildProcessSpawner.ExitCode(0), + code: ChildProcessSpawner.ExitCode(code), timedOut: false, stdoutTruncated: false, stderrTruncated: false, @@ -90,24 +79,41 @@ const withFakeSystemd = ( run: ({ args }) => Effect.sync(() => { calls.push(args); + if (!oomPolicy && args.some((arg) => arg.startsWith("--property=OOMPolicy="))) { + return output("", 1); + } const [, verb, unit = ""] = args; + if (stopFails && verb === "stop") { + return { + ...output(""), + stderr: `Failed to stop ${args.at(-1)}: Unit not loaded.`, + code: ChildProcessSpawner.ExitCode(5), + }; + } if (verb === "reset-failed") units.delete(unit); if (verb !== "show") return output(""); const state = units.get(unit); return output( state === undefined ? "LoadState=not-found\nActiveState=inactive\nResult=success\n" - : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n`, + : `LoadState=loaded\nActiveState=${state.activeState}\nResult=${state.result}\n` + + `ControlGroup=${state.controlGroup ?? ""}\n`, ); }), }); + const fileSystem = yield* FileSystem.FileSystem; const scope = yield* make.pipe( Effect.provideService(ProcessRunner.ProcessRunner, runner), Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.Environment, { PATH: bin, XDG_RUNTIME_DIR: "/run/user/1" }), + Effect.provideService(FileSystem.FileSystem, { + ...fileSystem, + readFileString: (path, encoding) => + fileSystem.readFileString(path.replace("/sys/fs/cgroup", cgroupRoot), encoding), + }), ); const { stateDir } = yield* ServerConfig.ServerConfig; - return yield* body({ scope, units, calls, stateDir }).pipe( + return yield* body({ scope, units, calls, stateDir, cgroupRoot }).pipe( Effect.ensuring(Effect.sync(() => NodeFS.rmSync(bin, { recursive: true, force: true }))), ); }).pipe( @@ -125,6 +131,41 @@ const unitOf = (launch: { readonly args: ReadonlyArray }) => const sliceOf = (launch: { readonly args: ReadonlyArray }) => launch.args.find((arg) => arg.startsWith("--slice="))?.slice("--slice=".length) ?? ""; +/** An active scope as systemd and the kernel report it, with the agent itself gone. */ +const exitedAgent = ( + units: Map, + cgroupRoot: string, + unit: string, + { populated, oomKills }: { readonly populated: boolean; readonly oomKills: number | undefined }, +) => { + const controlGroup = `/${unit}`; + NodeFS.mkdirSync(NodePath.join(cgroupRoot, controlGroup), { recursive: true }); + NodeFS.writeFileSync( + NodePath.join(cgroupRoot, controlGroup, "cgroup.events"), + `populated ${populated ? 1 : 0}\nfrozen 0\n`, + ); + // An undefined count leaves memory.events unreadable. + if (oomKills !== undefined) { + NodeFS.writeFileSync( + NodePath.join(cgroupRoot, controlGroup, "memory.events"), + `low 0\nhigh 0\nmax 0\noom ${oomKills}\noom_kill ${oomKills}\noom_group_kill 0\n`, + ); + } + units.set(unit, { activeState: "active", result: "success", controlGroup }); +}; + +const stopsOf = (calls: ReadonlyArray>) => + calls.filter(([, verb]) => verb === "stop"); +const launchCodex = (scope: Effect.Success, threadId: string) => + makeCodexAppServerSpawnCommand({ command: "agent", args: ["app-server"], threadId }).pipe( + Effect.provideService(AgentScope, scope), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.map((command) => { + assert(ChildProcess.isStandardCommand(command)); + return command; + }), + ); + describe("AgentScope service", () => { it.effect("labels a thread from its newest scope until its next session clears it", () => withFakeSystemd(({ scope, units }) => @@ -146,6 +187,32 @@ describe("AgentScope service", () => { ), ); + it.effect( + "keeps shared Codex scopes running without attributing their OOM to the launch thread", + () => + withFakeSystemd(({ scope, units, calls }) => + Effect.gen(function* () { + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + expect(agent.args).toContain("--property=OOMPolicy=stop"); + units.set(unitOf(agent), { activeState: "failed", result: "oom-kill" }); + expect(yield* scope.oomKilled("a")).toBe(true); + + const codex = yield* launchCodex(scope, "a"); + expect(codex.args).toContain("--property=OOMPolicy=continue"); + expect(codex.args).not.toContain("--property=OOMPolicy=stop"); + expect(codex.args).toContain("--property=TimeoutStopSec=10s"); + expect(codex.args).toContain("--collect"); + units.set(unitOf(codex), { activeState: "active", result: "success" }); + expect(yield* scope.oomKilled("a")).toBe(false); + units.set(unitOf(codex), { activeState: "failed", result: "oom-kill" }); + expect(yield* scope.oomKilled("a")).toBe(false); + expect( + calls.filter(([, verb, unit]) => verb === "show" && unit === unitOf(codex)), + ).toEqual([]); + }), + ), + ); + it.effect("keeps a running scope while hundreds of other threads launch", () => withFakeSystemd(({ scope, units }) => Effect.gen(function* () { @@ -181,6 +248,83 @@ describe("AgentScope service", () => { ), ); + it.effect("stops leftover processes only in an active agent scope", () => + withFakeSystemd(({ scope, units, calls, cgroupRoot }) => + Effect.gen(function* () { + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + const unit = unitOf(agent); + expect(agent.unit).toBe(unit); + + yield* scope.stop("session-2.scope"); + expect(calls.some((args) => args.includes("session-2.scope"))).toBe(false); + yield* scope.stop(unit); + exitedAgent(units, cgroupRoot, unit, { populated: false, oomKills: 0 }); + yield* scope.stop(unit); + exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 0 }); + units.get(unit)!.activeState = "deactivating"; + yield* scope.stop(unit); + expect(stopsOf(calls)).toEqual([]); + + units.get(unit)!.activeState = "active"; + yield* scope.stop(unit); + expect(stopsOf(calls)).toEqual([["--user", "stop", "--no-block", unit]]); + expect(yield* scope.oomKilled("a")).toBe(false); + }), + ), + ); + + it.effect.each([true, false])( + "cleans up an OOM exit without losing its diagnosis (OOMPolicy=%s)", + (oomPolicy) => + withFakeSystemd( + ({ scope, units, calls, cgroupRoot }) => + Effect.gen(function* () { + const agent = yield* scope.wrap({ + command: "agent", + args: [], + name: "t", + threadId: "a", + }); + const unit = unitOf(agent); + exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: undefined }); + yield* scope.stop(unit); + expect(stopsOf(calls)).toEqual( + oomPolicy ? [] : [["--user", "stop", "--no-block", unit]], + ); + + // The kernel records the kill before systemd records the OOM result. + exitedAgent(units, cgroupRoot, unit, { populated: true, oomKills: 1 }); + yield* scope.stop(unit); + expect(stopsOf(calls)).toHaveLength(oomPolicy ? 0 : 2); + + if (oomPolicy) { + units.set(unit, { activeState: "failed", result: "oom-kill" }); + expect(yield* scope.oomKilled("a")).toBe(true); + units.delete(unit); + expect(yield* scope.oomKilled("a")).toBe(true); + } + }), + { oomPolicy }, + ), + ); + + it.effect("reports failed daemon cleanup without failing session teardown", () => { + const warnings: Array = []; + const logger = Logger.make(({ message }) => { + warnings.push(message); + }); + return withFakeSystemd( + ({ scope, units, cgroupRoot }) => + Effect.gen(function* () { + const agent = yield* scope.wrap({ command: "agent", args: [], name: "t", threadId: "a" }); + exitedAgent(units, cgroupRoot, unitOf(agent), { populated: true, oomKills: 0 }); + yield* scope.stop(unitOf(agent)); + expect(warnings.flat()).toContain("Could not stop an exited agent's scope"); + }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))), + { stopFails: true }, + ); + }); + it.effect("leaves a quiet slice alone", () => withFakeSystemd(({ scope, calls }) => Effect.gen(function* () { diff --git a/apps/server/src/process/agentScope.ts b/apps/server/src/process/agentScope.ts index ed69eb2ad753f..1e54691161ae4 100644 --- a/apps/server/src/process/agentScope.ts +++ b/apps/server/src/process/agentScope.ts @@ -33,7 +33,7 @@ const GiB = 1024 ** 3; * working. Small machines still give agents at least half of RAM before * throttling and three quarters before a kill. */ -export function agentSliceMemoryLimits(totalBytes: number) { +function agentSliceMemoryLimits(totalBytes: number) { return { high: Math.max(totalBytes - 6 * GiB, Math.floor(totalBytes / 2)), max: Math.max(totalBytes - 4 * GiB, Math.floor(totalBytes * 0.75)), @@ -44,15 +44,11 @@ export interface ScopeState { readonly loadState: string; readonly activeState: string; readonly result: string; - readonly oomKills: number; + readonly oomKills: number | undefined; readonly populated: boolean | undefined; } -/** - * Our pipe can close before systemd handles the kill, so a scope that is - * still stopping, is empty, or already counted an OOM kill is "stopping": - * systemd records `Result=oom-kill` for it in a moment. - */ +/** Pipes can close before systemd records oom-kill; stopping, empty or OOM-counted scopes remain pending. */ export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "running" | "stopping" { if (state.result === "oom-kill") return "oom-killed"; if ( @@ -62,7 +58,11 @@ export function classifyScope(state: ScopeState): "oom-killed" | "gone" | "runni ) { return "gone"; } - if (state.activeState === "deactivating" || state.oomKills > 0 || state.populated === false) { + if ( + state.activeState === "deactivating" || + (state.oomKills ?? 0) > 0 || + state.populated === false + ) { return "stopping"; } return "running"; @@ -82,8 +82,7 @@ function parseCgroupCounter(text: string, key: string): number | undefined { return match === null ? undefined : Number(match[1]); } -// A stop sends SIGTERM, then SIGKILL after this long. systemd's 90 s default -// would outlast the wait for a previous server's agents below. +// systemd's default 90 s stop timeout would outlast our leftover-agent wait. const STOP_TIMEOUT_OPTION = "--property=TimeoutStopSec=10s"; const STOPPING_POLL_INTERVAL = "100 millis"; const STOPPING_POLL_ATTEMPTS = 20; @@ -121,31 +120,32 @@ export const make = Effect.gen(function* () { // Old agents keep their scopes when the server is killed, and the restarted // server resumes their sessions. Stop them first, so two copies of one // session never work in the same worktree. - const stopLeftoverAgents = (systemctl: string) => - Effect.gen(function* () { - const shown = yield* run(systemctl, [ - "--user", - "show", - ownedSlice, - "--property=ActiveState,ControlGroup", - ]); - if (shown._tag === "None") return; - const values = parseKeyValues(shown.value.stdout); - if (values.get("ActiveState") !== "active") return; - const controlGroup = values.get("ControlGroup") ?? ""; - const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : ""; - if (parseCgroupCounter(events, "populated") === 0) return; - yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice }); - const stopped = yield* runner - .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" }) - .pipe(Effect.option); - if (stopped._tag === "None" || stopped.value.code !== 0) { - yield* Effect.logWarning("Could not stop agents left by a previous server", { - slice: ownedSlice, - stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined, - }); - } - }); + const stopLeftoverAgents = Effect.fn("agentScope.stopLeftoverAgents")(function* ( + systemctl: string, + ) { + const shown = yield* run(systemctl, [ + "--user", + "show", + ownedSlice, + "--property=ActiveState,ControlGroup", + ]); + if (shown._tag === "None") return; + const values = parseKeyValues(shown.value.stdout); + if (values.get("ActiveState") !== "active") return; + const controlGroup = values.get("ControlGroup") ?? ""; + const events = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : ""; + if (parseCgroupCounter(events, "populated") === 0) return; + yield* Effect.logWarning("Stopping agents left by a previous server", { slice: ownedSlice }); + const stopped = yield* runner + .run({ command: systemctl, args: ["--user", "stop", ownedSlice], timeout: "30 seconds" }) + .pipe(Effect.option); + if (stopped._tag === "None" || stopped.value.code !== 0) { + yield* Effect.logWarning("Could not stop agents left by a previous server", { + slice: ownedSlice, + stderr: stopped._tag === "Some" ? stopped.value.stderr.trim() : undefined, + }); + } + }); const systemd = yield* Effect.cached( Effect.gen(function* () { @@ -166,17 +166,9 @@ export const make = Effect.gen(function* () { "--", "true", ]).pipe(Effect.map((result) => result._tag === "Some" && result.value.code === 0)); - // Stop the whole scope when the kernel kills one of its processes, and - // record the result as oom-kill. Scopes take OOMPolicy from systemd 253; - // older user managers still get scopes, without the OOM label. - const stopOptions = [STOP_TIMEOUT_OPTION]; - const oomOptions = [...stopOptions, "--property=OOMPolicy=stop"]; - const scopeOptions = (yield* probe(oomOptions)) - ? oomOptions - : (yield* probe(stopOptions)) - ? stopOptions - : undefined; - if (scopeOptions === undefined) { + // Scopes take OOMPolicy from systemd 253; older managers still get scopes. + const supportsOomPolicy = yield* probe([STOP_TIMEOUT_OPTION, "--property=OOMPolicy=stop"]); + if (!supportsOomPolicy && !(yield* probe([STOP_TIMEOUT_OPTION]))) { yield* Effect.logInfo("Agent scopes are off: no systemd user manager"); return undefined; } @@ -197,86 +189,89 @@ export const make = Effect.gen(function* () { yield* Effect.logInfo("Agent scopes are on", { slice: AGENT_SLICE, ...limits, - oomPolicy: scopeOptions.length > 0, + oomPolicy: supportsOomPolicy, }); return { systemdRun, systemctl, runtimeDir, - scopeOptions, + supportsOomPolicy, }; }), ); const scopeByThread = new Map(); - const readScope = (systemctl: string, unit: string) => - Effect.gen(function* () { - const shown = yield* run(systemctl, [ - "--user", - "show", - unit, - "--property=LoadState,ActiveState,Result,ControlGroup", - ]); - if (shown._tag === "None" || shown.value.code !== 0) return undefined; - const values = parseKeyValues(shown.value.stdout); - const controlGroup = values.get("ControlGroup") ?? ""; - const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : ""; - const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : ""; - const populated = parseCgroupCounter(cgroupEvents, "populated"); - return { - loadState: values.get("LoadState") ?? "", - activeState: values.get("ActiveState") ?? "", - result: values.get("Result") ?? "", - oomKills: parseCgroupCounter(memoryEvents, "oom_kill") ?? 0, - populated: populated === undefined ? undefined : populated === 1, - } satisfies ScopeState; - }); + const readScope = Effect.fn("agentScope.readScope")(function* (systemctl: string, unit: string) { + const shown = yield* run(systemctl, [ + "--user", + "show", + unit, + "--property=LoadState,ActiveState,Result,ControlGroup", + ]); + if (shown._tag === "None" || shown.value.code !== 0) return undefined; + const values = parseKeyValues(shown.value.stdout); + const controlGroup = values.get("ControlGroup") ?? ""; + const memoryEvents = controlGroup ? yield* readCgroupFile(controlGroup, "memory.events") : ""; + const cgroupEvents = controlGroup ? yield* readCgroupFile(controlGroup, "cgroup.events") : ""; + const populated = parseCgroupCounter(cgroupEvents, "populated"); + return { + loadState: values.get("LoadState") ?? "", + activeState: values.get("ActiveState") ?? "", + result: values.get("Result") ?? "", + oomKills: parseCgroupCounter(memoryEvents, "oom_kill"), + populated: populated === undefined ? undefined : populated === 1, + } satisfies ScopeState; + }); - const clearFailed = (systemctl: string, unit: string) => - Effect.gen(function* () { - for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) { - const state = yield* readScope(systemctl, unit); - if (state === undefined) return; - if (state.activeState === "failed") { - yield* run(systemctl, ["--user", "reset-failed", unit]); - return; - } - if (state.activeState !== "deactivating") return; - yield* Effect.sleep(CLEAR_FAILED_INTERVAL); + const clearFailed = Effect.fn("agentScope.clearFailed")(function* ( + systemctl: string, + unit: string, + ) { + for (let attempt = 0; attempt < CLEAR_FAILED_ATTEMPTS; attempt++) { + const state = yield* readScope(systemctl, unit); + if (state === undefined) return; + if (state.activeState === "failed") { + yield* run(systemctl, ["--user", "reset-failed", unit]); + return; } - }); + if (state.activeState !== "deactivating") return; + yield* Effect.sleep(CLEAR_FAILED_INTERVAL); + } + }); const forget = (systemctl: string, unit: string) => clearFailed(systemctl, unit).pipe(Effect.forkIn(layerScope), Effect.asVoid); - const evictOldest = (systemctl: string) => - Effect.gen(function* () { - const oldest = scopeByThread.entries().next(); - if (oldest.done === true) return; - const [threadId, tracked] = oldest.value; - const state = yield* readScope(systemctl, tracked.unit); - if (scopeByThread.get(threadId) !== tracked) return; - scopeByThread.delete(threadId); - const status = state === undefined ? "running" : classifyScope(state); - if (status === "running" || status === "stopping") { - scopeByThread.set(threadId, tracked); - return; - } - yield* forget(systemctl, tracked.unit); - }); + const evictOldest = Effect.fn("agentScope.evictOldest")(function* (systemctl: string) { + const oldest = scopeByThread.entries().next(); + if (oldest.done === true) return; + const [threadId, tracked] = oldest.value; + const state = yield* readScope(systemctl, tracked.unit); + if (scopeByThread.get(threadId) !== tracked) return; + scopeByThread.delete(threadId); + const status = state === undefined ? "running" : classifyScope(state); + if (status === "running" || status === "stopping") { + scopeByThread.set(threadId, tracked); + return; + } + yield* forget(systemctl, tracked.unit); + }); - const track = (systemctl: string, threadId: string, unit: string | undefined) => - Effect.gen(function* () { - const previous = scopeByThread.get(threadId); - scopeByThread.delete(threadId); - if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false }); - if (previous !== undefined) yield* forget(systemctl, previous.unit); - if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl); - }); + const track = Effect.fn("agentScope.track")(function* ( + systemctl: string, + threadId: string, + unit: string | undefined, + ) { + const previous = scopeByThread.get(threadId); + scopeByThread.delete(threadId); + if (unit !== undefined) scopeByThread.set(threadId, { unit, oomKilled: false }); + if (previous !== undefined) yield* forget(systemctl, previous.unit); + if (scopeByThread.size > MAX_TRACKED_THREADS) yield* evictOldest(systemctl); + }); - const oomKilled: AgentScopeShape["oomKilled"] = (threadId) => - Effect.gen(function* () { + const oomKilled: AgentScopeShape["oomKilled"] = Effect.fn("agentScope.oomKilled")( + function* (threadId) { const tracked = scopeByThread.get(threadId); if (tracked === undefined) return false; if (tracked.oomKilled) return true; @@ -301,14 +296,40 @@ export const make = Effect.gen(function* () { return true; } return false; - }); + }, + ); - const clear: AgentScopeShape["clear"] = (threadId) => - Effect.gen(function* () { - if (!scopeByThread.has(threadId)) return; - const scope = yield* systemd; - if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined); - }); + const stop = Effect.fn("AgentScope.stop")(function* (unit: string) { + if (!unit.startsWith("t3code-") || !unit.endsWith(".scope")) return; + const scope = yield* systemd; + if (scope === undefined) return; + const state = yield* readScope(scope.systemctl, unit); + if ( + state === undefined || + state.loadState !== "loaded" || + state.activeState !== "active" || + state.result === "oom-kill" || + state.populated === false + ) + return; + // The kernel counts OOM kills before signaling the victim. Let OOMPolicy + // record the result before a manual stop can overwrite it; an unreadable + // counter cannot rule out that race. Older managers need us to stop it. + if (scope.supportsOomPolicy && (state.oomKills === undefined || state.oomKills > 0)) return; + const stopped = yield* run(scope.systemctl, ["--user", "stop", "--no-block", unit]); + if (stopped._tag === "None" || stopped.value.code !== 0) { + yield* Effect.logWarning("Could not stop an exited agent's scope", { + unit, + exitCode: stopped._tag === "Some" ? stopped.value.code : undefined, + }); + } + }); + + const clear: AgentScopeShape["clear"] = Effect.fn("agentScope.clear")(function* (threadId) { + if (!scopeByThread.has(threadId)) return; + const scope = yield* systemd; + if (scope !== undefined) yield* track(scope.systemctl, threadId, undefined); + }); return { wrap: Effect.fn("AgentScope.wrap")(function* ({ @@ -318,25 +339,37 @@ export const make = Effect.gen(function* () { threadId, env, survivesRestart, + shared, }) { const resolved = yield* resolve(command, env ?? hostEnvironment); if (resolved === null) return { command, args }; const scope = yield* systemd; if (scope === undefined) return agentScopeCommand({ command: resolved, args }); const unit = `t3code-${name}-${NodeCrypto.randomUUID().slice(0, 8)}.scope`; - if (threadId !== undefined) yield* track(scope.systemctl, threadId, unit); + // A continuing shared scope cannot attribute a tool's OOM to one thread. + // Clear the launch thread's previous scope instead. + const continuing = shared === true && scope.supportsOomPolicy; + const owned = threadId !== undefined && !continuing; + if (threadId !== undefined) yield* track(scope.systemctl, threadId, owned ? unit : undefined); const systemdScope: AgentSystemdScope = { systemdRun: scope.systemdRun, runtimeDir: scope.runtimeDir, slice: survivesRestart === true ? AGENT_SLICE : ownedSlice, unit, - // Without a thread nothing reads the result, so let systemd unload - // the unit even when it fails. - options: threadId === undefined ? [...scope.scopeOptions, "--collect"] : scope.scopeOptions, + // Without an owning thread nothing reads the result, so let systemd + // unload the unit even when it fails. + options: [ + STOP_TIMEOUT_OPTION, + ...(scope.supportsOomPolicy + ? [`--property=OOMPolicy=${continuing ? "continue" : "stop"}`] + : []), + ...(owned ? [] : ["--collect"]), + ], }; - return agentScopeCommand({ command: resolved, args, scope: systemdScope }); + return { ...agentScopeCommand({ command: resolved, args, scope: systemdScope }), unit }; }), oomKilled, + stop, clear, } satisfies AgentScopeShape; }); diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 21c7547374d71..29547d2a23ade 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -1,7 +1,4 @@ // @effect-diagnostics nodeBuiltinImport:off - the Windows launch smoke tests use filesystem notifications to observe real PowerShell launches. -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, it } from "@effect/vitest"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -13,22 +10,20 @@ 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 PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as ExternalLauncher from "./externalLauncher.ts"; -// Tests below write `#!/bin/sh` stubs into a real temp dir and hand that -// directory to a posix-mocked resolver as PATH. On a Windows host the temp -// path carries a drive letter, so the posix `:` split shatters it; there is -// no posix executable to find there anyway. +// Windows drive letters break mocked POSIX PATH splitting; these tests also require /bin/sh stubs. const windowsHost = HostProcess.Platform.defaultValue() === "win32"; interface MockSpawnResult { + readonly spawnError?: PlatformError.PlatformError; readonly exitCode?: number; readonly stdout?: string; readonly stall?: boolean; @@ -69,949 +64,251 @@ const layerTest = (input: { const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make((command) => - Effect.sync(() => { + Effect.gen(function* () { assert.equal(ChildProcess.isStandardCommand(command), true); if (!ChildProcess.isStandardCommand(command)) { throw new Error("Expected a standard command"); } input.onSpawn?.(command); + const result = input.spawnResult?.(command); + if (result?.spawnError) return yield* result.spawnError; return makeMockDetachedHandle({ ...(input.onUnref === undefined ? {} : { onUnref: input.onUnref }), - ...input.spawnResult?.(command), - }); - }), - ), - ); - - return Layer.mergeAll( - ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, layerSpawner))), - Layer.succeed(HostProcess.Platform, input.platform), - Layer.succeed( - SpawnExecutableResolution, - (command) => input.resolveExecutable?.(command) ?? command, - ), - ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })), - ); -}; - -it.effect("launches the default browser through the platform command", () => { - let spawned: ChildProcess.StandardCommand | undefined; - let didUnref = false; - return Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - - yield* launcher.launchBrowser("https://example.com/some path"); - - assert.ok(spawned); - assert.equal(spawned.command, "xdg-open"); - assert.deepEqual(spawned.args, ["https://example.com/some path"]); - assert.equal(spawned.options.detached, true); - assert.equal(didUnref, true); - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - onSpawn: (command) => { - spawned = command; - }, - onUnref: () => { - didUnref = true; - }, - }), - ), - ); -}); - -it.effect.each(["win32", "linux"] as const)( - "launches the browser through PowerShell on %s", - (platform) => { - let spawned: ChildProcess.StandardCommand | undefined; - return Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - - yield* launcher.launchBrowser("https://example.com/some path"); - - assert.ok(spawned); - assert.equal( - spawned.command, - platform === "win32" - ? "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" - : "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", - ); - assert.deepEqual(spawned.args.slice(0, -1), [ - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-EncodedCommand", - ]); - const encodedCommand = spawned.args[spawned.args.length - 1] ?? ""; - const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); - assert.equal( - decodedCommand, - "$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path'", - ); - assert.equal(spawned.options.detached, platform !== "win32"); - }).pipe( - Effect.provide( - layerTest({ - platform, - env: { SYSTEMROOT: "C:\\Windows", WSL_DISTRO_NAME: "Ubuntu" }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - }, -); - -it.effect("launches an installed editor with platform-safe arguments", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n"); - - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ - editor: "vscode", - cwd: "C:\\workspace with spaces\\src\\index.ts:12:4", - }); - }).pipe( - Effect.provide( - layerTest({ - platform: "win32", - env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" }, - resolveExecutable: (command) => - command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.ok(spawned); - assert.equal( - spawned.command, - [ - '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"', - '^"--goto^"', - '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"', - ].join(" "), - ); - assert.deepEqual(spawned.args, []); - assert.equal(spawned.options.shell, true); - assert.equal(spawned.options.detached, true); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -for (const platform of ["darwin", "linux"] as const) { - it.effect.skipIf(windowsHost)(`launches Cursor in classic IDE mode on ${platform}`, () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - const cursorPath = path.join(binDir, "cursor"); - yield* fileSystem.writeFileString(cursorPath, "#!/bin/sh\n"); - yield* fileSystem.chmod(cursorPath, 0o755); - - const spawned: ChildProcess.StandardCommand[] = []; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - for (const cwd of [ - "/workspace with spaces", - "/workspace with spaces/src/index.ts", - "/workspace with spaces/src/index.ts:12", - "/workspace with spaces/src/index.ts:12:4", - ]) { - yield* launcher.launchEditor({ editor: "cursor", cwd }); - } - }).pipe( - Effect.provide( - layerTest({ - platform, - env: { PATH: binDir }, - onSpawn: (command) => spawned.push(command), - }), - ), - ); - - assert.deepEqual( - spawned.map((command) => ({ command: command.command, args: command.args })), - [ - { command: "cursor", args: ["--classic", "/workspace with spaces"] }, - { command: "cursor", args: ["--classic", "/workspace with spaces/src/index.ts"] }, - { - command: "cursor", - args: ["--classic", "--goto", "/workspace with spaces/src/index.ts:12"], - }, - { - command: "cursor", - args: ["--classic", "--goto", "/workspace with spaces/src/index.ts:12:4"], - }, - ], - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); -} - -it.effect("launches Cursor in classic IDE mode through the Windows command shim", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fileSystem.writeFileString(path.join(binDir, "cursor.CMD"), "@echo off\r\n"); - - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ - editor: "cursor", - cwd: "C:\\workspace with spaces\\src\\index.ts:12:4", - }); - }).pipe( - Effect.provide( - layerTest({ - platform: "win32", - env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" }, - resolveExecutable: (command) => - command === "cursor" ? "C:\\Program Files\\Cursor\\bin\\cursor.CMD" : command, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.ok(spawned); - assert.equal( - spawned.command, - [ - '^"C:\\Program^ Files\\Cursor\\bin\\cursor.CMD^"', - '^"--classic^"', - '^"--goto^"', - '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"', - ].join(" "), - ); - assert.deepEqual(spawned.args, []); - assert.equal(spawned.options.shell, true); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect("opens a folder in File Explorer with Windows separators", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fileSystem.writeFileString(path.join(binDir, "explorer.EXE"), ""); - - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ editor: "file-manager", cwd: "C:/workspace/project" }); - }).pipe( - Effect.provide( - layerTest({ - platform: "win32", - env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.ok(spawned); - assert.deepEqual(spawned.args, ["C:\\workspace\\project"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)("reveals a file in Finder with open -R on macOS", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - const openPath = path.join(binDir, "open"); - yield* fileSystem.writeFileString(openPath, "#!/bin/sh\n"); - yield* fileSystem.chmod(openPath, 0o755); - - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/workspace/media/linux-mini-v2.mp4", - reveal: true, - }); - }).pipe( - Effect.provide( - layerTest({ - platform: "darwin", - env: { PATH: binDir }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.ok(spawned); - assert.equal(spawned.command, "open"); - assert.deepEqual(spawned.args, ["-R", "/workspace/media/linux-mini-v2.mp4"]); - assert.equal(spawned.options.detached, true); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect("reveals a file in File Explorer through PowerShell on Windows", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n"); - // resolvePowerShellPath builds `${SYSTEMROOT}\System32\...` with Windows - // separators, which on the posix test filesystem is one file name. - const systemRoot = path.join(binDir, "system-root"); - const powerShellPath = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; - yield* fileSystem.makeDirectory(path.dirname(powerShellPath), { recursive: true }); - yield* fileSystem.writeFileString(powerShellPath, ""); - - let spawned: ChildProcess.StandardCommand | undefined; - const kind = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "C:/workspace with spaces/media/author's clip.mp4", - reveal: true, - }); - return yield* launcher.resolveFileManagerRevealKind(); - }).pipe( - Effect.provide( - layerTest({ - platform: "win32", - env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD", SYSTEMROOT: systemRoot }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.equal(kind, "file-explorer"); - assert.ok(spawned); - assert.equal(spawned.command, powerShellPath); - assert.deepEqual(spawned.args.slice(0, -1), [ - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-EncodedCommand", - ]); - const encodedCommand = spawned.args[spawned.args.length - 1] ?? ""; - const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); - assert.equal( - decodedCommand, - "$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + 'C:\\workspace with spaces\\media\\author''s clip.mp4' + '\"')", - ); - assert.equal(spawned.options.shell, false); - assert.equal(spawned.options.detached, false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -for (const kind of ["browser", "reveal"] as const) { - it.live.skipIf(!windowsHost)( - `completes a ${kind} launch through real PowerShell after the launcher scope closes`, - () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-reveal-smoke-")); - const outputPath = NodePath.join(tempDir, "argv.txt"); - const watcher = NodeFS.watch(tempDir, { signal: AbortSignal.timeout(20_000) }); - try { - const recorderPath = NodePath.join(tempDir, "recorder.cmd"); - const stagingPath = NodePath.join(tempDir, "argv.tmp"); - NodeFS.writeFileSync( - recorderPath, - `@echo off\r\n>"${stagingPath}" echo(%*\r\nmove /y "${stagingPath}" "${outputPath}" >nul\r\n`, - ); - const recorded = new Promise((resolve, reject) => { - watcher.on("change", () => { - if (NodeFS.existsSync(outputPath)) { - resolve(NodeFS.readFileSync(outputPath, "utf8").trim()); - } - }); - watcher.on("error", reject); - watcher.on("close", () => - reject(new Error("PowerShell did not run the recording stub")), - ); - }); - - const target = "C:/workspace with spaces/media/author's clip.mp4"; - yield* Effect.all( - [ - Effect.gen(function* () { - const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const recordingSpawner = ChildProcessSpawner.make((command) => { - assert.ok(ChildProcess.isStandardCommand(command)); - const source = Buffer.from(command.args.at(-1) ?? "", "base64") - .toString("utf16le") - .replace("'explorer.exe'", `'${recorderPath.replaceAll("'", "''")}'`); - return realSpawner.spawn( - ChildProcess.make( - command.command, - [ - ...command.args.slice(0, -1), - Buffer.from(source, "utf16le").toString("base64"), - ], - command.options, - ), - ); - }); - const launcher = yield* ExternalLauncher.make.pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, recordingSpawner), - ); - if (kind === "browser") { - yield* launcher.launchBrowser(recorderPath); - } else { - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: target, - reveal: true, - }); - } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - Effect.promise(() => - recorded.then((value) => { - assert.equal( - value, - kind === "browser" ? "" : `/select,"${target.replaceAll("/", "\\")}"`, - ); - }), - ), - ], - { concurrency: "unbounded" }, - ); - } finally { - watcher.close(); - // The recording stub's cmd.exe can still hold the directory for a - // moment after it publishes its output, which Windows reports as EPERM. - NodeFS.rmSync(tempDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }); - } - }), - { timeout: 30_000 }, - ); -} - -it.effect("does not advertise reveal on Windows when PowerShell is missing", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n"); - - const result = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - return { - kind: yield* launcher.resolveFileManagerRevealKind(), - editors: yield* launcher.resolveAvailableEditors(), - }; - }).pipe( - Effect.provide( - layerTest({ - platform: "win32", - env: { - PATH: binDir, - PATHEXT: ".COM;.EXE;.BAT;.CMD", - SYSTEMROOT: path.join(binDir, "missing-system-root"), - }, - }), - ), - ); - - assert.equal(result.editors.includes("file-manager"), true); - assert.isUndefined(result.kind); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "reveals a WSL file in Windows File Explorer through its UNC path", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - let spawned: ChildProcess.StandardCommand | undefined; - const result = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - const kind = yield* launcher.resolveFileManagerRevealKind(); - const editors = yield* launcher.resolveAvailableEditors(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace/media/clip.mp4", - reveal: true, - }); - return { kind, editors }; - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { - PATH: binDir, - WSL_DISTRO_NAME: "Ubuntu-24.04", - WSL_INTEROP: "/run/WSL/1_interop", - }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.equal(result.kind, "file-explorer"); - assert.equal(result.editors.includes("file-manager"), true); - assert.ok(spawned); - assert.equal(spawned.command, "powershell.exe"); - assert.equal(spawned.options.detached, true); - const encodedCommand = spawned.args[spawned.args.length - 1] ?? ""; - const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); - assert.equal( - decodedCommand, - "$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace\\media\\clip.mp4' + '\"')", - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "does not advertise reveal from WSL when interop PowerShell is missing", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - const explorerPath = path.join(binDir, "explorer.exe"); - yield* fileSystem.writeFileString(explorerPath, ""); - yield* fileSystem.chmod(explorerPath, 0o755); - - const result = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - return { - kind: yield* launcher.resolveFileManagerRevealKind(), - editors: yield* launcher.resolveAvailableEditors(), - }; - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { - PATH: binDir, - WSL_DISTRO_NAME: "Ubuntu-24.04", - WSL_INTEROP: "/run/WSL/1_interop", - }, - }), - ), - ); - - assert.equal(result.editors.includes("file-manager"), true); - assert.isUndefined(result.kind); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "reveals through the Linux file manager when WSL lacks interop PowerShell", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["explorer.exe", "xdg-open", "xdg-mime"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - const spawnedCommands: ChildProcess.StandardCommand[] = []; - const kind = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - const revealKind = yield* launcher.resolveFileManagerRevealKind(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace/media/clip.mp4", - reveal: true, - }); - return revealKind; - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { - PATH: binDir, - WSL_DISTRO_NAME: "Ubuntu-24.04", - WSL_INTEROP: "/run/WSL/1_interop", - DISPLAY: ":0", - }, - onSpawn: (command) => { - spawnedCommands.push(command); - }, - spawnResult: (command) => - command.command === "xdg-mime" - ? { stdout: "org.gnome.Nautilus.desktop\n" } - : undefined, - }), - ), - ); - - assert.equal(kind, "files"); - const launch = spawnedCommands.find((command) => command.command === "xdg-open"); - assert.ok(launch); - assert.deepEqual(launch.args, ["/home/t3/workspace/media"]); - assert.isUndefined(spawnedCommands.find((command) => command.command === "explorer.exe")); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "falls back to the Linux file manager when WSL lacks the Explorer bridge", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["xdg-open", "xdg-mime"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - const spawnedCommands: ChildProcess.StandardCommand[] = []; - const result = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - const editors = yield* launcher.resolveAvailableEditors(); - const kind = yield* launcher.resolveFileManagerRevealKind(); - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/home/t3/workspace/media/clip.mp4", - reveal: true, - }); - return { editors, kind }; - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { - PATH: binDir, - WSL_DISTRO_NAME: "Ubuntu-24.04", - WSL_INTEROP: "/run/WSL/1_interop", - DISPLAY: ":0", - }, - onSpawn: (command) => { - spawnedCommands.push(command); - }, - spawnResult: (command) => - command.command === "xdg-mime" - ? { stdout: "org.gnome.Nautilus.desktop\n" } - : undefined, - }), - ), - ); - - assert.equal(result.editors.includes("file-manager"), true); - assert.equal(result.kind, "files"); - const launch = spawnedCommands.find((command) => command.command === "xdg-open"); - assert.ok(launch); - assert.deepEqual(launch.args, ["/home/t3/workspace/media"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "falls back to opening the containing directory for WSL paths Explorer cannot select", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["explorer.exe", "powershell.exe"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: '/home/t3/work "quoted"/clip.mp4', - reveal: true, - }); - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { - PATH: binDir, - WSL_DISTRO_NAME: "Ubuntu-24.04", - WSL_INTEROP: "/run/WSL/1_interop", - }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - - assert.ok(spawned); - assert.equal(spawned.command, "explorer.exe"); - assert.deepEqual(spawned.args, ['\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\work "quoted"']); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)("reveals by opening the containing directory on Linux", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["xdg-open", "xdg-mime"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - const spawnedCommands: ChildProcess.StandardCommand[] = []; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ - editor: "file-manager", - cwd: "/workspace/media/linux-mini-v2.mp4", - reveal: true, - }); - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { PATH: binDir, DISPLAY: ":0" }, - onSpawn: (command) => { - spawnedCommands.push(command); - }, - spawnResult: (command) => - command.command === "xdg-mime" ? { stdout: "org.gnome.Nautilus.desktop\n" } : undefined, - }), - ), - ); - - const spawned = spawnedCommands.find((command) => command.command === "xdg-open"); - assert.ok(spawned); - assert.deepEqual(spawned.args, ["/workspace/media"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "does not advertise a Linux file manager without a graphical session", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - const xdgOpenPath = path.join(binDir, "xdg-open"); - yield* fileSystem.writeFileString(xdgOpenPath, "#!/bin/sh\n"); - yield* fileSystem.chmod(xdgOpenPath, 0o755); - - const editors = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); - }).pipe(Effect.provide(layerTest({ platform: "linux", env: { PATH: binDir } }))); - - assert.equal(editors.includes("file-manager"), false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "advertises a Linux file manager when a directory handler is installed", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["xdg-open", "xdg-mime"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - let probe: ChildProcess.StandardCommand | undefined; - const editors = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { PATH: binDir, DISPLAY: ":0" }, - onSpawn: (command) => { - probe = command; - }, - spawnResult: (command) => - command.command === "xdg-mime" - ? { stdout: "org.gnome.Nautilus.desktop\n" } - : undefined, - }), - ), - ); + ...result, + }); + }), + ), + ); - assert.equal(editors.includes("file-manager"), true); - assert.ok(probe); - assert.equal(probe.command, "xdg-mime"); - assert.deepEqual(probe.args, ["query", "default", "inode/directory"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); + return Layer.mergeAll( + ExternalLauncher.layer.pipe(Layer.provide(Layer.merge(NodeServices.layer, layerSpawner))), + Layer.succeed(HostProcess.Platform, input.platform), + Layer.succeed( + SpawnExecutableResolution, + (command) => input.resolveExecutable?.(command) ?? command, + ), + ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })), + ); +}; it.effect.skipIf(windowsHost)( - "does not advertise a Linux file manager without a directory handler", + "launched browsers and editors do not inherit ELECTRON_RUN_AS_NODE", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["xdg-open", "xdg-mime"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } + const codePath = path.join(binDir, "code"); + yield* fileSystem.writeFileString(codePath, "#!/bin/sh\n"); + yield* fileSystem.chmod(codePath, 0o755); - const editors = yield* Effect.gen(function* () { + const spawned: ChildProcess.StandardCommand[] = []; + yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); + yield* launcher.launchBrowser("https://example.com"); + yield* launcher.launchEditor({ editor: "vscode", cwd: "/workspace" }); }).pipe( Effect.provide( layerTest({ platform: "linux", env: { PATH: binDir, DISPLAY: ":0" }, - spawnResult: (command) => (command.command === "xdg-mime" ? { stdout: "" } : undefined), + onSpawn: (command) => spawned.push(command), }), ), + Effect.provideService(HostProcess.Environment, { + PATH: binDir, + DISPLAY: ":0", + ELECTRON_RUN_AS_NODE: "1", + }), ); - assert.equal(editors.includes("file-manager"), false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect.skipIf(windowsHost)( - "does not advertise a Linux file manager when the handler query fails", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["xdg-open", "xdg-mime"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } - - const editors = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { PATH: binDir, DISPLAY: ":0" }, - spawnResult: (command) => - command.command === "xdg-mime" - ? { exitCode: 47, stdout: "org.gnome.Nautilus.desktop\n" } - : undefined, - }), - ), + assert.deepEqual( + spawned.map((command) => ({ + command: command.command, + env: command.options.env, + extendEnv: command.options.extendEnv, + })), + ["xdg-open", "code"].map((command) => ({ + command, + env: { PATH: binDir, DISPLAY: ":0" }, + extendEnv: false, + })), ); - - assert.equal(editors.includes("file-manager"), false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -// Runs on the live clock so the probe's real timeout fires. -it.live.skipIf(windowsHost)("a stalled handler probe drops only the file manager", () => +it.effect("launches an installed editor with platform-safe arguments", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - for (const name of ["xdg-open", "xdg-mime", "code"]) { - const filePath = path.join(binDir, name); - yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); - yield* fileSystem.chmod(filePath, 0o755); - } + yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n"); - const editors = yield* Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); + yield* launcher.launchEditor({ + editor: "vscode", + cwd: "C:\\workspace with spaces\\src\\index.ts:12:4", + }); }).pipe( Effect.provide( layerTest({ - platform: "linux", - env: { PATH: binDir, DISPLAY: ":0" }, - spawnResult: (command) => (command.command === "xdg-mime" ? { stall: true } : undefined), + platform: "win32", + env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" }, + resolveExecutable: (command) => + command === "code" ? "C:\\Program Files\\Microsoft VS Code\\bin\\code.CMD" : command, + onSpawn: (command) => { + spawned = command; + }, }), ), ); - assert.equal(editors.includes("vscode"), true); - assert.equal(editors.includes("file-manager"), false); + assert.ok(spawned); + assert.equal( + spawned.command, + [ + '^"C:\\Program^ Files\\Microsoft^ VS^ Code\\bin\\code.CMD^"', + '^"--goto^"', + '^"C:\\workspace^ with^ spaces\\src\\index.ts:12:4^"', + ].join(" "), + ); + assert.deepEqual(spawned.args, []); + assert.equal(spawned.options.shell, true); + assert.equal(spawned.options.detached, true); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +for (const {} of ["darwin", "linux"] as const) { +} + +for (const {} of [ + { kind: "browser", folderVerb: "none" }, + { kind: "reveal", folderVerb: "none" }, + { kind: "reveal", folderVerb: "" }, + { kind: "reveal", folderVerb: "open" }, +] as const) { +} + it.effect.skipIf(windowsHost)( - "does not advertise a Linux file manager when xdg-mime is missing", + "reveals a WSL file in Windows File Explorer through its UNC path", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - const xdgOpenPath = path.join(binDir, "xdg-open"); - yield* fileSystem.writeFileString(xdgOpenPath, "#!/bin/sh\n"); - yield* fileSystem.chmod(xdgOpenPath, 0o755); + for (const name of ["explorer.exe", "powershell.exe", "xdg-open"]) { + const filePath = path.join(binDir, name); + yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); + yield* fileSystem.chmod(filePath, 0o755); + } - const editors = yield* Effect.gen(function* () { + let spawned: ChildProcess.StandardCommand | undefined; + const result = yield* Effect.gen(function* () { const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); + const kind = yield* launcher.resolveFileManagerRevealKind(); + const editors = yield* launcher.resolveAvailableEditors(); + yield* launcher.launchEditor({ + editor: "file-manager", + cwd: "/home/t3/workspace [draft]/author's $media/clip|draft.mp4", + reveal: true, + }); + return { kind, editors }; }).pipe( - Effect.provide(layerTest({ platform: "linux", env: { PATH: binDir, DISPLAY: ":0" } })), + Effect.provide( + layerTest({ + platform: "linux", + env: { + PATH: binDir, + WSL_DISTRO_NAME: "Ubuntu-24.04", + WSL_INTEROP: "/run/WSL/1_interop", + }, + onSpawn: (command) => { + spawned = command; + }, + }), + ), ); - assert.equal(editors.includes("file-manager"), false); + assert.equal(result.kind, "file-explorer"); + assert.equal(result.editors.includes("file-manager"), true); + assert.ok(spawned); + assert.equal(spawned.command, "powershell.exe"); + assert.equal(spawned.options.detached, true); + const encodedCommand = spawned.args[spawned.args.length - 1] ?? ""; + const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); + assert.equal( + decodedCommand, + "$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media' } else { Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + '\\\\wsl.localhost\\Ubuntu-24.04\\home\\t3\\workspace [draft]\\author''s $media\\clip|draft.mp4' + '\"') }", + ); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect("discovers editors through the service API", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fileSystem.writeFileString(path.join(binDir, "code.CMD"), "@echo off\r\n"); - yield* fileSystem.writeFileString(path.join(binDir, "explorer.CMD"), "@echo off\r\n"); +for (const wsl of [false, true]) { + it.effect.skipIf(windowsHost)( + "selects a file over D-Bus on " + (wsl ? "WSLg without interop PowerShell" : "Linux"), + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); + for (const name of ["xdg-open", "xdg-mime", "gdbus", ...(wsl ? ["explorer.exe"] : [])]) { + const filePath = path.join(binDir, name); + yield* fileSystem.writeFileString(filePath, "#!/bin/sh\n"); + yield* fileSystem.chmod(filePath, 0o755); + } + const target = "/workspace/media/a 'quoted' \"clip\" #100% ? é\\name.mp4"; + const spawnedCommands: ChildProcess.StandardCommand[] = []; + yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + yield* launcher.launchEditor({ editor: "file-manager", cwd: target, reveal: true }); + }).pipe( + Effect.provide( + layerTest({ + platform: "linux", + env: { + PATH: binDir, + WAYLAND_DISPLAY: "wayland-1", + ...(wsl + ? { WSL_DISTRO_NAME: "Ubuntu-24.04", WSL_INTEROP: "/run/WSL/1_interop" } + : {}), + }, + onSpawn: (command) => spawnedCommands.push(command), + spawnResult: (command) => + command.command === "xdg-mime" + ? { stdout: "com.thisisgm.flea.desktop\n" } + : undefined, + }), + ), + ); - const editors = yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - return yield* launcher.resolveAvailableEditors(); - }).pipe( - Effect.provide( - layerTest({ - platform: "win32", - env: { PATH: binDir, PATHEXT: ".COM;.EXE;.BAT;.CMD" }, - }), - ), - ); + const reveal = spawnedCommands.find((command) => command.command === "gdbus"); + assert.ok(reveal); + assert.deepEqual(reveal.args, [ + "call", + "--session", + "--dest", + "org.freedesktop.FileManager1", + "--object-path", + "/org/freedesktop/FileManager1", + "--method", + "org.freedesktop.FileManager1.ShowItems", + "[\"file:///workspace/media/a%20'quoted'%20%22clip%22%20%23100%25%20%3F%20%C3%A9%5Cname.mp4\"]", + "", + ]); + assert.deepEqual( + spawnedCommands.filter((command) => command.command !== "xdg-mime"), + [reveal], + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +} - assert.equal(editors.includes("vscode"), true); - assert.equal(editors.includes("file-manager"), true); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); +for (const {} of ["rejected", "spawn-error", "stalled"] as const) { +} -for (const { platform, installPath, editor, args } of [ +for (const {} of [ { platform: "darwin", installPath: "Applications/Antigravity IDE.app/Contents/Resources/app/bin/antigravity-ide", @@ -1040,7 +337,7 @@ for (const { platform, installPath, editor, args } of [ platform: "darwin", installPath: "Applications/WebStorm.app/Contents/MacOS/webstorm", editor: "webstorm", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "darwin", @@ -1064,13 +361,13 @@ for (const { platform, installPath, editor, args } of [ platform: "win32", installPath: "Programs/JetBrains/WebStorm 2026.2/bin/webstorm64.exe", editor: "webstorm", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "win32", installPath: "Programs/WebStorm/bin/webstorm64.exe", editor: "webstorm", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "win32", @@ -1082,7 +379,7 @@ for (const { platform, installPath, editor, args } of [ platform: "linux", installPath: ".local/share/JetBrains/Toolbox/scripts/idea", editor: "idea", - args: ["--line", "12", "--column", "4", "/workspace with spaces/file.ts"], + args: ["--line", "12", "--column", "3", "/workspace with spaces/file.ts"], }, { platform: "linux", @@ -1091,43 +388,6 @@ for (const { platform, installPath, editor, args } of [ args: ["/workspace with spaces/file.ts:12:4"], }, ] as const) { - it.effect.skipIf(windowsHost && platform !== "win32")( - `discovers and launches ${editor} outside PATH on ${platform}`, - () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editor installs-" }); - const executable = path.join(home, installPath); - yield* fs.makeDirectory(path.dirname(executable), { recursive: true }); - yield* fs.writeFileString(executable, "#!/bin/sh\n"); - yield* fs.chmod(executable, 0o755); - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - assert.include(yield* launcher.resolveAvailableEditors(), editor); - yield* launcher.launchEditor({ editor, cwd: "/workspace with spaces/file.ts:12:4" }); - }).pipe( - Effect.provide( - layerTest({ - platform, - env: { HOME: home, LOCALAPPDATA: home, PATH: path.join(home, "empty") }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - assert.ok(spawned); - const shim = executable.endsWith(".cmd"); - assert.equal( - spawned.command, - shim ? [`^"${executable.replaceAll(" ", "^ ")}^"`, ...args].join(" ") : executable, - ); - assert.deepEqual(spawned.args, shim ? [] : args); - assert.equal(spawned.options.shell, shim); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); } for (const cwd of ["/workspace with spaces/", "/workspace with spaces/file.ts:12:4"]) { @@ -1209,7 +469,7 @@ it.effect.each([ "--line", "12", "--column", - "4", + "3", "/workspace with spaces/file.ts", ]); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), @@ -1374,63 +634,6 @@ it.effect.skipIf(windowsHost)("ignores unusable app bundles and keeps PATH launc }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect("memoizes editor discovery and refreshes after the cache window", () => { - let statCalls = 0; - const fileInfo = { type: "File" } as FileSystem.File.Info; - const layerLauncher = ExternalLauncher.layer.pipe( - Layer.provide( - Layer.mergeAll( - FileSystem.layerNoop({ - stat: () => - Effect.sync(() => { - statCalls += 1; - return fileInfo; - }), - }), - Path.layer, - Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())), - ), - ), - ), - ); - - return Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - - const first = yield* launcher.resolveAvailableEditors(); - assert.equal(first.includes("vscode"), true); - const statCallsAfterFirstScan = statCalls; - assert.isAbove(statCallsAfterFirstScan, 0); - - yield* TestClock.adjust("31 seconds"); - const second = yield* launcher.resolveAvailableEditors(); - assert.deepEqual([...second], [...first]); - assert.equal(statCalls, statCallsAfterFirstScan); - - yield* TestClock.adjust("30 seconds"); - yield* launcher.resolveAvailableEditors(); - assert.isAbove(statCalls, statCallsAfterFirstScan); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerLauncher, - Layer.succeed(HostProcess.Platform, "win32"), - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - PATH: "C:\\t3-editor-discovery-cache-test", - PATHEXT: ".COM;.EXE;.BAT;.CMD", - }, - }), - ), - TestClock.layer(), - ), - ), - ); -}); - it.effect("keeps scanning after the caller is interrupted and shares that scan", () => { const fileInfo = { type: "File" } as FileSystem.File.Info; const release = Deferred.makeUnsafe(); @@ -1549,43 +752,3 @@ it.effect("starts a Windows command shim for unicode paths with cmd metacharacte ); }), ); - -it.effect.skipIf(windowsHost)("passes line breaks through to editors started without a shell", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - const zed = path.join(binDir, "zed"); - yield* fileSystem.writeFileString(zed, "#!/bin/sh\n"); - yield* fileSystem.chmod(zed, 0o755); - let spawned: ChildProcess.StandardCommand | undefined; - yield* Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace/odd\nname.ts" }); - }).pipe( - Effect.provide( - layerTest({ - platform: "linux", - env: { PATH: binDir, HOME: binDir }, - onSpawn: (command) => { - spawned = command; - }, - }), - ), - ); - assert.ok(spawned); - assert.deepEqual(spawned.args, ["/workspace/odd\nname.ts"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect("rejects unknown editors through the service API", () => - Effect.gen(function* () { - const launcher = yield* ExternalLauncher.ExternalLauncher; - const error = yield* launcher - .launchEditor({ editor: "missing-editor" as never, cwd: "/tmp/workspace" }) - .pipe(Effect.flip); - assert.instanceOf(error, ExternalLauncher.ExternalLauncherUnknownEditorError); - assert.equal(error.editor, "missing-editor"); - assert.equal(error.message, "Unknown editor: missing-editor"); - }).pipe(Effect.provide(layerTest({ platform: "linux", env: { PATH: "" } }))), -); diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 13062253235c2..ff62b3ab5a113 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -1,3 +1,4 @@ +import * as NodePath from "@effect/platform-node/NodePath"; import { EDITORS, ExternalLauncherError, @@ -65,12 +66,7 @@ interface TargetPathAndPosition { readonly column: Option.Option; } -/** - * Windows command shims (`code.cmd`) forward arguments through `%*`, which - * cmd.exe parses a second time after the first escaping layer is gone: a - * line break ends the command there, and a double quote closes the quoting - * that keeps `&` or `|` literal. Neither can occur in a Windows path. - */ +// cmd shims reparse %* after escaping is gone; newlines and quotes can expose shell operators. // oxlint-disable-next-line no-control-regex const WINDOWS_SHIM_UNSAFE_ARG_PATTERN = /[\u0000-\u001f\u007f"]/; const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/; @@ -82,9 +78,7 @@ const POWERSHELL_ARGUMENTS_PREFIX = [ "-EncodedCommand", ] as const; -// Windows PowerShell started with DETACHED_PROCESS exits 0 without running its -// command, so native Windows launches through it stay attached. WSL interop -// PowerShell starts from a Linux process and keeps the detached launch. +// Detached Windows PowerShell exits 0 without executing; only WSL interop keeps detached launches. const WINDOWS_POWERSHELL_DETACHED = false; const DETACHED_IGNORE_STDIO_OPTIONS = { @@ -162,9 +156,10 @@ function resolveCommandEditorArgs( onSome: ({ path, line, column }) => [ "--line", line, + // JetBrains IDEs count `--column` from 0; targets count columns from 1. ...Option.match(column, { onNone: () => [], - onSome: (value) => ["--column", value], + onSome: (value) => ["--column", String(Math.max(0, Number(value) - 1))], }), path, ], @@ -194,10 +189,7 @@ function resolveWslPowerShellPath(): string { return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"; } -// File reveals from WSL resolve PowerShell through the interop PATH rather -// than the fixed /mnt/c mount: the automount root is configurable, and a -// PATH-resolved command keeps the advertised capability aligned with the -// availability check `launchEditor` performs before spawning. +// WSL automount roots vary; resolve PowerShell via PATH to match launchEditor's availability check. const WSL_POWERSHELL_COMMAND = "powershell.exe"; function shouldUseWindowsHostFromWsl( @@ -257,14 +249,8 @@ function fileManagerCommandForPlatform( } } -// A graphical session variable plus an executable `xdg-open` does not prove -// that opening a directory does anything: without an `inode/directory` MIME -// handler, `xdg-open` exits nonzero after the launcher has already detached, so -// the client would see a silent no-op. The probe carries its own timeout well -// inside the scan timeout `server.getConfig` applies to editor discovery: that -// outer timeout degrades to an empty editor list, so a hung `xdg-mime` (broken -// D-Bus or desktop session) must cost only the file manager, not every -// discovered editor. +// xdg-open needs an inode/directory handler or detached launches silently fail. +// Bound xdg-mime below discovery's timeout so a hung probe drops only the file manager. const LINUX_DIRECTORY_HANDLER_PROBE_TIMEOUT = "2 seconds"; const hasUsableLinuxDirectoryHandler = Effect.fn("externalLauncher.hasUsableLinuxDirectoryHandler")( @@ -317,10 +303,7 @@ const isUsableFileManagerCommand = Effect.fn("externalLauncher.isUsableFileManag }, ); -// WSL hosts prefer the Windows Explorer bridge, but interop can exist without -// `explorer.exe` on PATH (appendWindowsPath=false) or without a distro name -// while WSLg still provides a working Linux file manager, so they keep the -// `xdg-open` fallback instead of losing the editor entirely. +// WSL may lack Explorer on PATH or a distro name while WSLg still offers a Linux file manager. const resolveUsableFileManagerCommand = Effect.fn( "externalLauncher.resolveUsableFileManagerCommand", )(function* ( @@ -345,13 +328,8 @@ const resolveUsableFileManagerCommand = Effect.fn( return undefined; }); -// Reveal on Windows and WSL runs through PowerShell (see -// resolveFileManagerRevealLaunch), not the `explorer` command that gates the -// file-manager editor itself, so the capability must probe the executables the -// reveal actually spawns. Callers gate on file-manager availability first; -// the Linux "files" kind relies on that gate for the directory-handler probe, -// while the WSL fallback re-probes because its availability may have come -// from the Explorer bridge instead. +// Reveal uses PowerShell on Windows/WSL, so probe it separately from Explorer availability. +// Linux relies on the file-manager gate's handler probe; WSL re-probes because the gate may use Explorer. const fileManagerRevealKindForPlatform = Effect.fn( "externalLauncher.fileManagerRevealKindForPlatform", )(function* ( @@ -469,13 +447,7 @@ const resolveFileManagerRevealKind = Effect.fn("externalLauncher.resolveFileMana }, ); -// Callers apply a timeout (`resolveAvailableEditorsForConfig`) and disconnect -// mid-connect; neither may cancel a scan other connects are waiting on, or -// throw away work a slow host (a busy server at startup, a long PATH) needs -// more than one connect to finish. Expiry uses the monotonic clock -// (Clock.monotonicTimeNanos), matching the command-resolution cache in -// @t3tools/shared/shell, so a backward wall-clock adjustment cannot keep an -// expired entry alive. +// Shared scans must survive caller timeouts/disconnects; monotonic expiry prevents clock rollback extending stale entries. const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n; interface EditorDiscoveryCacheEntry { @@ -487,11 +459,7 @@ export class ExternalLauncher extends Context.Service< ExternalLauncher, { readonly resolveAvailableEditors: () => Effect.Effect>; - /** - * Only meaningful when `resolveAvailableEditors` includes "file-manager": - * on Linux that availability check also carries the directory-handler probe - * this capability relies on. - */ + /** Requires file-manager in resolveAvailableEditors; Linux relies on its directory-handler probe. */ readonly resolveFileManagerRevealKind: () => Effect.Effect; readonly launchBrowser: (target: string) => Effect.Effect; readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect; @@ -554,37 +522,30 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( command === "explorer.exe" && env.WSL_DISTRO_NAME !== undefined ? [resolveWslFileManagerPath(input.cwd, env.WSL_DISTRO_NAME)] : platform === "win32" - ? // Explorer reads `/` as a switch, so `C:/repo` silently opens - // a default folder instead of the target. + ? // Explorer interprets / as a switch and silently opens a fallback folder. [normalizeWindowsFileManagerPath(input.cwd)] : [input.cwd], }; }); -/** - * Explorer's contract is the single argument `/select,""` with only the - * path quoted; Node's default spawn quoting wraps the whole argument when the - * path has spaces and Explorer misparses it, silently opening a fallback - * folder. A single `-ArgumentList` string in Windows PowerShell 5.1 reaches the - * child's command line verbatim, preserving the raw switch. - */ -function buildFileExplorerRevealPowerShellSource(explorerCommand: string, target: string): string { - return `$ProgressPreference = 'SilentlyContinue'; Start-Process ${escapePowerShellStringLiteral(explorerCommand)} -ArgumentList ('/select,"' + ${escapePowerShellStringLiteral(target)} + '"')`; +// A replacement manager registers a default Directory shell verb; stock Windows +// uses "none". Explorer needs its /select argument passed verbatim through +// PowerShell because Node's argument quoting changes how Explorer parses it. +function buildFileManagerRevealPowerShellSource(target: string, parent: string): string { + const literal = escapePowerShellStringLiteral(target); + return `$ProgressPreference = 'SilentlyContinue'; $folderVerb = (Get-ItemProperty -LiteralPath 'Registry::HKEY_CLASSES_ROOT\\Directory\\shell' -ErrorAction SilentlyContinue).'(default)'; if ($folderVerb -and $folderVerb -ne 'none') { Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)} } else { Start-Process 'explorer.exe' -ArgumentList ('/select,"' + ${literal} + '"') }`; } -function fileExplorerRevealLaunch( +function powerShellFileManagerLaunch( target: string, - explorerTarget: string, + source: string, powershellCommand: string, ): EditorLaunch { return { editor: "file-manager", target, command: powershellCommand, - args: [ - ...POWERSHELL_ARGUMENTS_PREFIX, - encodeUtf16LeBase64(buildFileExplorerRevealPowerShellSource("explorer.exe", explorerTarget)), - ], + args: [...POWERSHELL_ARGUMENTS_PREFIX, encodeUtf16LeBase64(source)], }; } @@ -607,10 +568,12 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch } if (platform === "win32") { + const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32)); + const windowsTarget = normalizeWindowsFileManagerPath(target); return { - ...fileExplorerRevealLaunch( + ...powerShellFileManagerLaunch( target, - normalizeWindowsFileManagerPath(target), + buildFileManagerRevealPowerShellSource(windowsTarget, path.dirname(windowsTarget)), resolvePowerShellPath(env), ), detached: WINDOWS_POWERSHELL_DETACHED, @@ -624,20 +587,15 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch ) { const explorerTarget = resolveWslFileManagerPath(target, env.WSL_DISTRO_NAME); if (yield* isCommandAvailable(WSL_POWERSHELL_COMMAND, { env })) { - // Explorer's raw switch cannot express a double quote, and unlike - // Windows paths a WSL path may legally contain one: open the containing - // directory in File Explorer instead, matching the advertised - // "file-explorer" kind. - if (explorerTarget.includes('"')) { - const path = yield* Path.Path; - return { - editor: "file-manager", - target, - command: "explorer.exe", - args: [resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME)], - }; - } - return fileExplorerRevealLaunch(target, explorerTarget, WSL_POWERSHELL_COMMAND); + // WSL names may contain quotes that Explorer's /select cannot encode. + // Open the parent through the shell so replacement managers still apply. + const path = yield* Path.Path; + // .NET path parsing rejects characters that are legal in WSL filenames. + const parent = resolveWslFileManagerPath(path.dirname(target), env.WSL_DISTRO_NAME); + const source = explorerTarget.includes('"') + ? `Invoke-Item -LiteralPath ${escapePowerShellStringLiteral(parent)}` + : buildFileManagerRevealPowerShellSource(explorerTarget, parent); + return powerShellFileManagerLaunch(target, source, WSL_POWERSHELL_COMMAND); } if (hasGraphicalLinuxSession(env) && (yield* isUsableFileManagerCommand("xdg-open", env))) { const path = yield* Path.Path; @@ -652,18 +610,81 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch }; } - // Linux file managers have no portable "select this file" flag, so open - // the containing directory instead. const path = yield* Path.Path; return { editor: "file-manager", target, command, args: [path.dirname(target)] }; }); +const tryRevealLinuxItem = Effect.fn("externalLauncher.tryRevealLinuxItem")( + function* (target: string) { + const env = yield* readCommandLookupEnv; + if (!(yield* isCommandAvailable("gdbus", { env }))) return false; + + const path = yield* Path.Path; + const uri = yield* path.toFileUrl(target); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const exitCode = yield* spawner.exitCode( + ChildProcess.make( + "gdbus", + [ + "call", + "--session", + "--dest", + "org.freedesktop.FileManager1", + "--object-path", + "/org/freedesktop/FileManager1", + "--method", + "org.freedesktop.FileManager1.ShowItems", + // File URLs percent-encode the double quotes and backslashes GVariant would interpret. + `["${uri.href}"]`, + "", + ], + { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + // Timeout waits for scoped cleanup, even if the helper ignores SIGTERM. + forceKillAfter: "1 second", + }, + ), + ); + return exitCode === 0; + }, + Effect.timeout("2 seconds"), + Effect.catchTags({ + BadArgument: () => Effect.succeed(false), + PlatformError: () => Effect.succeed(false), + TimeoutError: () => Effect.succeed(false), + }), +); + +const launchEditor = Effect.fn("externalLauncher.launchEditor")(function* ( + input: LaunchEditorInput, +) { + const launch = yield* resolveEditorLaunch(input); + if ( + input.editor === "file-manager" && + input.reveal === true && + launch.command === "xdg-open" && + (yield* HostProcess.Platform) === "linux" && + (yield* tryRevealLinuxItem(launch.target)) + ) { + return; + } + yield* launchEditorProcess(launch); +}); + const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* ( launch: ProcessLaunch, onError: (cause: unknown) => ExternalLauncherError, ): Effect.fn.Return { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const command = ChildProcess.make(launch.command, launch.args, launch.options); + // Inherited ELECTRON_RUN_AS_NODE would make Electron apps opened by this launcher run as Node and exit. + const { ELECTRON_RUN_AS_NODE: _runAsNode, ...env } = yield* HostProcess.Environment; + const command = ChildProcess.make(launch.command, launch.args, { + ...launch.options, + env, + extendEnv: false, + }); yield* spawner.spawn(command).pipe( Effect.flatMap((handle) => handle.unref), @@ -731,7 +752,7 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu ); }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; @@ -769,8 +790,7 @@ export const make = Effect.gen(function* () { Effect.interruptible, Effect.forkIn(scope), ); - // Claiming the cache entry and starting its scan must not be split by an - // interrupt, or the entry would wait on a scan that never runs. + // Claim and start atomically; interruption between them would leave an entry waiting on no scan. const acquireEditorDiscovery = Effect.gen(function* () { const nowNanos = yield* Clock.monotonicTimeNanos; const [scan, isNewScan] = yield* Ref.modify( @@ -809,9 +829,9 @@ export const make = Effect.gen(function* () { Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ), launchEditor: (input) => - provideCommandResolutionServices( - Effect.flatMap(resolveEditorLaunch(input), launchEditorProcess), - ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)), + provideCommandResolutionServices(launchEditor(input)).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), }); }); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 13e811baedfd0..97c761811a91c 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -1,13 +1,10 @@ import { describe, expect, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { TestClock } from "effect/testing"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; @@ -79,50 +76,6 @@ const runWith = ); describe("runProcess", () => { - it.effect("collects stdout through an injected ChildProcessSpawner", () => - Effect.gen(function* () { - const spawner = makeSpawner((command) => - Effect.sync(() => { - expect(command.command).toBe("fake"); - expect(command.args).toEqual(["stdout-bytes", "32"]); - return makeHandle({ stdout: "x".repeat(32) }); - }), - ); - - const result = yield* runWith(spawner)({ - command: "fake", - args: ["stdout-bytes", "32"], - }); - - expect(result.code).toBe(0); - expect(result.stdout).toBe("x".repeat(32)); - expect(result.timedOut).toBe(false); - }), - ); - - it.effect("runs through the ProcessRunner service", () => { - const spawner = makeSpawner((command) => - Effect.sync(() => { - expect(command.command).toBe("fake"); - expect(command.args).toEqual(["--service"]); - return makeHandle({ stdout: "service ok" }); - }), - ); - const layer = ProcessRunner.layer.pipe( - Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)), - ); - - return Effect.gen(function* () { - const runner = yield* ProcessRunner.ProcessRunner; - const result = yield* runner.run({ - command: "fake", - args: ["--service"], - }); - - expect(result.stdout).toBe("service ok"); - }).pipe(Effect.provide(layer)); - }); - it.effect("resolves and escapes Windows command shims before spawning", () => { const spawner = makeSpawner((command) => Effect.sync(() => { @@ -164,49 +117,9 @@ describe("runProcess", () => { ); }); - it.effect("preserves resolved spawn context and cause", () => - Effect.gen(function* () { - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "ChildProcessSpawner", - method: "spawn", - pathOrDescriptor: "/actual/fake", - }); - const spawner = makeSpawner(() => Effect.fail(cause)); - - const error = yield* runWith(spawner)({ - command: "fake", - args: ["--flag", "secret-token-value"], - cwd: "/logical", - spawnCwd: "/actual", - }).pipe(Effect.flip); - - expect(error._tag).toBe("ProcessSpawnError"); - if (error._tag !== "ProcessSpawnError") { - return expect.fail("Expected ProcessSpawnError"); - } - expect(error).toMatchObject({ - command: "fake", - argumentCount: 2, - cwd: "/logical", - spawnCwd: "/actual", - resolvedCommand: "fake", - resolvedArgumentCount: 2, - shell: false, - }); - expect(error.cause).toBe(cause); - expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'"); - expect(error).not.toHaveProperty("args"); - expect(error).not.toHaveProperty("resolvedArgs"); - expect(error.message).not.toContain("secret-token-value"); - }), - ); - it.effect("types spawn failures that the platform spawner throws synchronously", () => Effect.gen(function* () { - // A non-directory entry on PATH makes node's spawn throw ENOTDIR - // synchronously. The platform spawner calls it inside `Effect.callback`, - // so the throw arrives as a defect rather than a typed error. + // File-valued PATH entries make spawn throw ENOTDIR synchronously, arriving through Effect.callback as a defect. const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" }); const spawner = makeSpawner(() => Effect.callback(() => { @@ -348,86 +261,8 @@ describe("runProcess", () => { }), ); - it.effect("returns output for non-zero exit codes", () => - Effect.gen(function* () { - const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 }))); - - const result = yield* runWith(spawner)({ - command: "fake", - args: ["stderr-exit", "boom", "2"], - }); - - expect(result.code).toBe(2); - expect(result.stderr).toBe("boom"); - }), - ); - - it.effect("fails on timeout", () => - Effect.gen(function* () { - const spawner = makeSpawner(() => - Effect.succeed( - makeHandle({ - exitCode: Effect.never, - }), - ), - ); - const errorFiber = yield* runWith(spawner)({ - command: "fake", - args: ["sleep"], - cwd: "/logical", - spawnCwd: "/actual", - timeout: "50 millis", - }).pipe(Effect.flip, Effect.forkScoped); - - yield* Effect.yieldNow; - yield* TestClock.adjust(Duration.millis(50)); - const error = yield* Fiber.join(errorFiber); - - expect(error._tag).toBe("ProcessTimeoutError"); - if (error._tag !== "ProcessTimeoutError") { - return expect.fail("Expected ProcessTimeoutError"); - } - expect(error).toMatchObject({ - command: "fake", - argumentCount: 1, - cwd: "/logical", - spawnCwd: "/actual", - timeoutMs: 50, - }); - expect(error.message).toBe("Process 'fake' in '/actual' timed out after 50ms"); - }), - ); - - it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () => - Effect.gen(function* () { - const spawner = makeSpawner(() => - Effect.succeed( - makeHandle({ - exitCode: Effect.never, - }), - ), - ); - const resultFiber = yield* runWith(spawner)({ - command: "fake", - args: ["sleep"], - timeout: "50 millis", - timeoutBehavior: "timedOutResult", - }).pipe(Effect.forkScoped); - - yield* Effect.yieldNow; - yield* TestClock.adjust(Duration.millis(50)); - const result = yield* Fiber.join(resultFiber); - - expect(result).toMatchObject({ - stdout: "", - stderr: "", - code: null, - timedOut: true, - stdoutTruncated: false, - stderrTruncated: false, - }); - }), - ); + for (const {} of ["timeout", "success"] as const) { + } }); describe("isWindowsCommandNotFound", () => { @@ -441,11 +276,3 @@ describe("isWindowsCommandNotFound", () => { }), ); }); - -describe("commandName", () => { - it("drops the directory from POSIX and Windows paths", () => { - expect(ProcessRunner.commandName("/Users/me/.local/bin/claude")).toBe("claude"); - expect(ProcessRunner.commandName("C:\\Program Files\\nodejs\\npx.cmd")).toBe("npx.cmd"); - expect(ProcessRunner.commandName("git")).toBe("git"); - }); -}); diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index 3ee8232688cba..c10c5cce032e1 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -29,10 +29,7 @@ export interface ProcessRunInput { readonly maxOutputBytes?: number | undefined; readonly outputMode?: "error" | "truncate" | undefined; readonly truncatedMarker?: string | undefined; - /** - * On timeout, return a synthetic timedOut result. - * Partial stdout/stderr are not preserved. - */ + /** Timed-out results discard partial stdout/stderr. */ readonly timeoutBehavior?: "error" | "timedOutResult" | undefined; } @@ -146,6 +143,8 @@ export class ProcessRunner extends Context.Service< >()("t3/processRunner") {} const DEFAULT_TIMEOUT = "60 seconds"; +// Keep SIGTERM-ignoring helpers from blocking timeouts or graceful shutdown. +const FORCE_KILL_AFTER = "1 second"; const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024; export { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe"; @@ -264,7 +263,7 @@ function finalizeRunProcess( ); } -export const commandName = (command: string) => command.replace(/^.*[\\/]/, ""); +const commandName = (command: string) => command.replace(/^.*[\\/]/, ""); const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* ( spawner: ChildProcessSpawner.ChildProcessSpawner["Service"], @@ -304,13 +303,12 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* ( } : {}), shell: spawnCommand.shell, + forceKillAfter: FORCE_KILL_AFTER, }), ) .pipe( Effect.mapError(toSpawnError), - // Node's spawn can also throw synchronously, e.g. ENOTDIR when a PATH - // entry is a file. That arrives as a defect, which `mapError` never sees, - // so callers that recover from spawn failures would be bypassed. + // Synchronous spawn throws arrive as defects; recover them too so callers see typed spawn failures. Effect.catchDefect((cause) => Effect.fail(toSpawnError(cause))), ); @@ -390,7 +388,7 @@ const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* ( } satisfies ProcessRunOutput; }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("ProcessRunner.make")(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 3a1ab5d0a7e6b..be7457da4335d 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -1,147 +1,390 @@ import { expect, it } from "@effect/vitest"; import { + EventId, ProjectId, + ProviderDriverKind, ProviderInstanceId, ThreadId, - type OrchestrationV2DomainEvent, + type ApplicationStoredEvent, + type OrchestrationV2AppThread, + type OrchestrationV2ProviderThread, } from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +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 Stream from "effect/Stream"; +import * as SqlClient from "effect/sql/SqlClient"; import * as EventSink from "../orchestration-v2/EventSink.ts"; -import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as EventStore from "../orchestration-v2/EventStore.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { + CLAUDE_MODEL_SELECTION, + CODEX_MODEL_SELECTION, +} from "../orchestration-v2/testkit/fixtures/shared.ts"; import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as AgentSessionImporter from "./AgentSessionImporter.ts"; import * as AgentSessionScanner from "./AgentSessionScanner.ts"; import * as ProjectService from "./ProjectService.ts"; const projectId = ProjectId.make("agent-session-import-project"); -const providerInstanceId = ProviderInstanceId.make("codex"); -const providerSessionId = "native-codex-thread"; -const threadId = ThreadId.make(`import:${providerInstanceId}:${providerSessionId}`); +const timestamp = "2026-09-01T10:00:00.000Z"; +const now = DateTime.makeUnsafe(timestamp); +const stores = Layer.mergeAll(EventStore.layer, ProjectionStore.layer).pipe( + Layer.provideMerge(SqlitePersistence.layerMemory), +); +const persistence = Layer.mergeAll( + stores, + EventSink.layer.pipe(Layer.provide(stores)), + ProviderSessionRuntime.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)), + IdAllocator.layer, +); + +function candidate( + modelSelection: typeof CODEX_MODEL_SELECTION, + providerSessionId: string, + provider: "codex" | "claudeAgent" = "codex", +) { + const providerInstanceId = modelSelection.instanceId; + return { + _tag: "Importable" as const, + source: { + provider, + providerInstanceId, + providerSessionId, + filePath: `/tmp/${providerInstanceId}/${providerSessionId}.jsonl`, + size: 100, + mtimeMs: 2, + device: 3, + inode: 4, + birthtimeMs: 1, + }, + thread: { + source: provider, + providerInstanceId, + providerSessionId, + title: "Imported thread", + model: modelSelection.model, + createdAt: timestamp, + updatedAt: timestamp, + messages: [ + { role: "user" as const, text: "Fix it", createdAt: timestamp }, + { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, + ], + }, + } satisfies AgentSessionScanner.AgentSessionRecentThread; +} + +function importId(source: ReturnType) { + return ThreadId.make( + `import:${source.source.providerInstanceId}:${source.source.providerSessionId}`, + ); +} + +const seedOwner = Effect.fn(function* ( + source: ReturnType, + lifecycle: "active" | "archived" | "deleted" = "active", +) { + const sink = yield* EventSink.EventSinkV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const { providerInstanceId, providerSessionId, provider } = source.source; + const threadId = ThreadId.make(`owner:${providerInstanceId}:${providerSessionId}`); + const driver = ProviderDriverKind.make(provider); + const providerThread: OrchestrationV2ProviderThread = { + id: ids.derive.providerThread({ + driver, + nativeThreadId: providerSessionId, + }), + driver, + providerInstanceId, + providerSessionId: null, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { driver, nativeId: providerSessionId, strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }; + const thread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: "Native thread", + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model: source.thread.model }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: lifecycle === "archived" ? now : null, + deletedAt: lifecycle === "deleted" ? now : null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + }; + yield* sink.write({ + events: [ + { + id: EventId.make(`${threadId}:created`), + type: "thread.created", + threadId, + occurredAt: now, + payload: thread, + }, + { + id: EventId.make(`${threadId}:provider`), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: providerThread, + }, + ], + }); + return threadId; +}); -it.effect("imports messages once and preserves the provider native resume binding", () => { - const writes: Array> = []; - const upserts: Array = []; - const recorded: Array = []; - let imported = false; - const scanner = AgentSessionScanner.AgentSessionScanner.of({ - scan: Effect.die("unused"), - recentThreads: () => - Stream.succeed({ - _tag: "Importable", - source: { - provider: "codex", - providerInstanceId, - providerSessionId, - filePath: "/tmp/native-codex-thread.jsonl", - size: 100, - mtimeMs: 2, - device: 3, - inode: 4, - birthtimeMs: 1, - }, - thread: { - source: "codex", - providerInstanceId, - providerSessionId, - title: "Imported thread", - model: "gpt-5.4", - createdAt: "2026-09-01T10:00:00.000Z", - updatedAt: "2026-09-01T10:01:00.000Z", - messages: [ - { role: "user", text: "Fix it", createdAt: "2026-09-01T10:00:00.000Z" }, - { role: "assistant", text: "Fixed", createdAt: "2026-09-01T10:01:00.000Z" }, - ], - }, - }), +const makeImporter = Effect.fn(function* ( + candidates: ReadonlyArray>, + beforeTransaction: Effect.Effect = Effect.void, +) { + const sql = yield* SqlClient.SqlClient; + const events = yield* EventStore.EventStoreV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const published: Array = []; + const withTransaction: typeof sql.withTransaction = (effect) => + beforeTransaction.pipe(Effect.andThen(sql.withTransaction(effect))); + const importSql = new Proxy(sql, { + get: (target, key, receiver) => + key === "withTransaction" ? withTransaction : Reflect.get(target, key, receiver), }); - const layerTest = AgentSessionImporter.layer.pipe( + const sinkLayer = Layer.fresh(EventSink.layer).pipe( Layer.provide( Layer.mergeAll( - Layer.succeed(AgentSessionScanner.AgentSessionScanner, scanner), - Layer.mock(ProjectService.ProjectService)({ - getById: () => - Effect.succeed( - Option.some({ id: projectId, workspaceRoot: "/workspace/project" } as never), + Layer.succeed(SqlClient.SqlClient, importSql), + Layer.succeed(ProjectionStore.ProjectionStoreV2, projections), + Layer.succeed(EventStore.EventStoreV2, { + ...events, + publishCommitted: (batch) => + events.publishCommitted(batch).pipe( + Effect.tap(() => + Effect.sync(() => { + published.push(...batch); + }), + ), ), }), - Layer.mock(Orchestrator.OrchestratorV2)({ - getThreadRecords: () => - imported - ? Effect.succeed({ - thread: { id: threadId, projectId, historyOrigin: "v1_import" }, - } as never) - : Effect.fail(new Orchestrator.OrchestratorProjectionError({ threadId })), - }), - Layer.mock(EventSink.EventSinkV2)({ - write: (input) => - Effect.sync(() => { - writes.push(input.events); - imported = true; - return []; - }), - }), - Layer.mock(ProviderSessionRuntime.ProviderSessionRuntimeRepository)({ - list: () => Effect.succeed([]), - upsert: (input) => Effect.sync(() => void upserts.push(input)), - recordImportedTranscript: (input) => Effect.sync(() => void recorded.push(input)), - }), - IdAllocator.layer, ), ), ); + const context = yield* Layer.build( + AgentSessionImporter.layer.pipe( + Layer.provide( + Layer.mergeAll( + sinkLayer, + Layer.succeed(IdAllocator.IdAllocatorV2, yield* IdAllocator.IdAllocatorV2), + Layer.succeed( + ProviderSessionRuntime.ProviderSessionRuntimeRepository, + yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository, + ), + Layer.mock(AgentSessionScanner.AgentSessionScanner)({ + recentThreads: () => Stream.fromIterable(candidates), + }), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeed( + Option.some({ + id: projectId, + title: "Project", + workspaceRoot: "/workspace/project", + defaultModelSelection: null, + scripts: [], + createdAt: timestamp, + updatedAt: timestamp, + deletedAt: null, + }), + ), + }), + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadRecords: (threadId, fields) => + projections + .getThreadRecords(threadId, fields) + .pipe( + Effect.mapError( + (cause) => new Orchestrator.OrchestratorProjectionError({ threadId, cause }), + ), + ), + }), + ), + ), + ), + ); + const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter); + return { run: importer.importRecentAgentThreads({ projectId }), published }; +}); - return Effect.gen(function* () { - const importer = yield* AgentSessionImporter.AgentSessionImporter; - expect(yield* importer.importRecentAgentThreads({ projectId })).toEqual({ - importedCount: 1, - skippedCount: 0, - }); - expect(yield* importer.importRecentAgentThreads({ projectId })).toEqual({ - importedCount: 1, - skippedCount: 0, - }); +it.effect( + "ignores owned sessions, including archived and deleted threads, but imports other instances and unowned sessions", + () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const events = yield* EventStore.EventStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const active = candidate(CODEX_MODEL_SELECTION, "active"); + const archived = candidate( + CLAUDE_MODEL_SELECTION, + "020e7f00-dce6-406b-8ec6-ed90498945d6", + "claudeAgent", + ); + const deleted = candidate(CODEX_MODEL_SELECTION, "deleted"); + const owners = [ + yield* seedOwner(active), + yield* seedOwner(archived, "archived"), + yield* seedOwner(deleted, "deleted"), + ]; + const before = yield* Effect.forEach(owners, (id) => + projections.getThreadRecords(id, ["providerThreads"]), + ); + const otherInstance = candidate( + { ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-other") }, + archived.source.providerSessionId, + "claudeAgent", + ); + const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); + const importer = yield* makeImporter([active, archived, deleted, otherInstance, unowned]); - expect(writes).toHaveLength(1); - expect(writes[0]?.map((event) => event.type)).toEqual([ - "thread.created", - "message.updated", - "turn-item.updated", - "message.updated", - "turn-item.updated", - "provider-thread.updated", - ]); - const created = writes[0]?.find((event) => event.type === "thread.created"); - const providerThread = writes[0]?.find((event) => event.type === "provider-thread.updated"); - expect(created?.payload).toMatchObject({ - id: threadId, - activeProviderThreadId: providerThread?.payload.id, - historyOrigin: "v1_import", - }); - expect(providerThread?.payload).toMatchObject({ - appThreadId: threadId, - nativeThreadRef: { - driver: "codex", - nativeId: providerSessionId, - strength: "strong", - }, - }); + expect(yield* importer.run).toEqual({ importedCount: 2, skippedCount: 0 }); + for (const source of [active, archived, deleted]) { + const threadId = importId(source); + expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); + expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); + expect(yield* runtimes.getByThreadId({ threadId })).toEqual(Option.none()); + } + expect( + yield* Effect.forEach(owners, (id) => + projections.getThreadRecords(id, ["providerThreads"]), + ), + ).toEqual(before); + expect( + new Set( + importer.published.flatMap((stored) => + "event" in stored ? [stored.event.threadId] : [], + ), + ), + ).toEqual(new Set([importId(otherInstance), importId(unowned)])); + for (const source of [otherInstance, unowned]) { + const threadId = importId(source); + const records = yield* projections.getThreadRecords(threadId, [ + "messages", + "providerThreads", + ]); + expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); + expect(records.thread.historyOrigin).toBe("v1_import"); + expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); + expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe( + source.source.providerSessionId, + ); + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ + providerInstanceId: source.source.providerInstanceId, + resumeCursor: + source.source.provider === "codex" + ? { threadId: source.source.providerSessionId } + : { threadId, resume: source.source.providerSessionId }, + runtimePayload: { importedTranscripts: [source.source] }, + }); + } + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect("rechecks ownership after the import reaches the commit transaction", () => + Effect.gen(function* () { + const enteringTransaction = yield* Deferred.make(); + const continueTransaction = yield* Deferred.make(); + const source = candidate(CODEX_MODEL_SELECTION, "claimed-during-import"); + const importer = yield* makeImporter( + [source], + Deferred.succeed(enteringTransaction, undefined).pipe( + Effect.andThen(Deferred.await(continueTransaction)), + ), + ); + const pending = yield* Effect.forkScoped(importer.run); + yield* Deferred.await(enteringTransaction); + // Commit ownership after all pre-transaction reads, before the import acquires SQLite. + const ownerId = yield* seedOwner(source); + yield* Deferred.succeed(continueTransaction, undefined); + expect(yield* Fiber.join(pending)).toEqual({ importedCount: 0, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 0 }); + const projections = yield* ProjectionStore.ProjectionStoreV2; + const events = yield* EventStore.EventStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + expect(yield* Effect.option(projections.getThread(importId(source)))).toEqual(Option.none()); + expect(yield* events.read({ threadId: importId(source) }).pipe(Stream.runCollect)).toEqual([]); + expect(yield* runtimes.list()).toEqual([]); + expect(importer.published).toEqual([]); expect( - writes[0] - ?.filter((event) => event.type === "message.updated") - .map((event) => event.payload.text), - ).toEqual(["Fix it", "Fixed"]); - expect(upserts).toEqual([ - expect.objectContaining({ - threadId, - providerInstanceId, - resumeCursor: { threadId: providerSessionId }, - }), - ]); - expect(recorded).toHaveLength(2); - }).pipe(Effect.provide(layerTest)); -}); + (yield* projections.getThreadRecords(ownerId, ["providerThreads"])).providerThreads[0] + ?.appThreadId, + ).toBe(ownerId); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect( + "retries failed commits and runtime persistence without replaying committed history", + () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const events = yield* EventStore.EventStoreV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const source = candidate(CODEX_MODEL_SELECTION, "retry"); + const threadId = importId(source); + const importer = yield* makeImporter([source]); + yield* sql`CREATE TEMP TRIGGER fail_import BEFORE INSERT ON orchestration_events WHEN NEW.event_type = 'message.updated' BEGIN SELECT RAISE(ABORT, 'test publication failure'); END`; + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); + expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual([]); + expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none()); + expect(yield* runtimes.list()).toEqual([]); + expect(importer.published).toEqual([]); + yield* sql`DROP TRIGGER fail_import`; + + yield* sql`CREATE TEMP TRIGGER fail_runtime BEFORE INSERT ON provider_session_runtime BEGIN SELECT RAISE(ABORT, 'test runtime failure'); END`; + expect(yield* importer.run).toEqual({ importedCount: 0, skippedCount: 1 }); + const committed = yield* events.read({ threadId }).pipe(Stream.runCollect); + expect(committed).toHaveLength(6); + expect(importer.published).toHaveLength(6); + expect(yield* runtimes.list()).toEqual([]); + yield* sql`DROP TRIGGER fail_runtime`; + + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 }); + expect(yield* events.read({ threadId }).pipe(Stream.runCollect)).toEqual(committed); + expect(importer.published).toHaveLength(6); + expect( + (yield* projections.getThreadRecords(threadId, ["messages"])).messages.map( + (message) => message.text, + ), + ).toEqual(["Fix it", "Fixed"]); + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ + providerInstanceId: source.source.providerInstanceId, + resumeCursor: { threadId: source.source.providerSessionId }, + runtimePayload: { 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 2c8d6a49d4c7d..11f168ff1d7be 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -249,6 +249,24 @@ const make = Effect.gen(function* () { providerSessionId: thread.providerSessionId, }); } + const driver = ProviderDriverKind.make(thread.source); + const persistRuntime = runtimes.upsert( + { + threadId, + providerName: driver, + providerInstanceId: thread.providerInstanceId, + adapterKey: driver, + runtimeMode: DEFAULT_RUNTIME_MODE, + status: "stopped", + lastSeenAt: thread.updatedAt, + resumeCursor: + thread.source === "codex" + ? { threadId: thread.providerSessionId } + : { threadId, resume: thread.providerSessionId }, + runtimePayload: { cwd: project.workspaceRoot }, + }, + { onConflict: "ignore" }, + ); const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); if (Option.isSome(existing)) { if (existing.value.thread.projectId !== input.projectId) { @@ -261,14 +279,15 @@ const make = Effect.gen(function* () { if (existing.value.thread.historyOrigin !== "v1_import") { return yield* new AgentSessionThreadModifiedError({ threadId }); } + yield* persistRuntime; yield* runtimes.recordImportedTranscript({ threadId, source }); return true; } - const driver = ProviderDriverKind.make(thread.source); const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL; const providerThreadId = idAllocator.derive.providerThread({ driver, + providerInstanceId: thread.providerInstanceId, nativeThreadId: thread.providerSessionId, }); const createdAt = dateTime(thread.createdAt); @@ -332,24 +351,8 @@ const make = Effect.gen(function* () { updatedAt, }; - yield* runtimes.upsert( - { - threadId, - providerName: driver, - providerInstanceId: thread.providerInstanceId, - adapterKey: driver, - runtimeMode: DEFAULT_RUNTIME_MODE, - status: "stopped", - lastSeenAt: thread.updatedAt, - resumeCursor: - thread.source === "codex" - ? { threadId: thread.providerSessionId } - : { threadId, resume: thread.providerSessionId }, - runtimePayload: { cwd: project.workspaceRoot }, - }, - { onConflict: "ignore" }, - ); - yield* eventSink.write({ + const committed = yield* eventSink.write({ + unlessNativeThreadOwned: providerThread, events: [ { id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`), @@ -373,6 +376,8 @@ const make = Effect.gen(function* () { }, ], }); + if (committed.length === 0) return null; + yield* persistRuntime; yield* runtimes.recordImportedTranscript({ threadId, source }); return true; }).pipe( @@ -384,10 +389,10 @@ const make = Effect.gen(function* () { }).pipe(Effect.as(false)), ), ); - if (imported) { + if (imported === true) { importedThreadIds.add(threadId); importedCount += 1; - } else { + } else if (imported === false) { skippedCount += 1; } }), diff --git a/apps/server/src/project/AgentSessionJson.ts b/apps/server/src/project/AgentSessionJson.ts index f9fe7e9754197..84b318f0642cc 100644 --- a/apps/server/src/project/AgentSessionJson.ts +++ b/apps/server/src/project/AgentSessionJson.ts @@ -47,9 +47,7 @@ export function createTranscriptJsonReader( selectPath: (path: JsonPath) => boolean, options?: { readonly maxDepth?: number }, ) { - // The synchronous tokenizer is exported at runtime in 3.6.0, but omitted - // from its bundled types. Unlike parser(), it does not wrap tokens in an - // async generator; the file reader already supplies backpressure and UTF-8. + // 3.6.0 omits the synchronous tokenizer from types; parser() adds an unnecessary async generator. const { jsonParser } = StreamJson as typeof StreamJson & { jsonParser: ( options: ParserOptions, @@ -88,9 +86,7 @@ export function createTranscriptJsonReader( assembler.consume(token); } }; - // Forward actual selected keys instead of reconstructing them from path - // changes: adjacent duplicate keys have the same path but JSON.parse keeps - // the last value. Reconstructing paths can silently retain the first value. + // Preserve actual keys; adjacent duplicates share a path, but JSON.parse keeps the last value. const stack: Array<{ path: JsonPath; key: string | number | null; selected: boolean }> = []; let selectedValue = false; const startValue = () => { diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 797fdf0292584..baf0f27f9edb3 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeOS from "node:os"; import { describe, expect, it } from "@effect/vitest"; import { + AgentSessionImportSource, type OrchestrationProjectShell, ProjectId, ProviderDriverKind, @@ -9,6 +10,7 @@ import { type ServerSettings as ContractServerSettings, } from "@t3tools/contracts"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -121,6 +123,8 @@ const claudeSessionLine = (cwd: string) => const codexRolloutLine = (cwd: string) => `${JSON.stringify({ timestamp: "2026-01-01T00:00:00.000Z", type: "session_meta", payload: { id: "r1", cwd } })}\n`; +const decodeImportSource = Schema.decodeUnknownSync(AgentSessionImportSource); + const encodeTranscriptRecord = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); function makeRecordLimitTranscript(cwd: string, overflow: boolean): string { @@ -148,6 +152,87 @@ function makeRecordLimitTranscript(cwd: string, overflow: boolean): string { : records; } +const makeFileIdentityFixture = Effect.fn("AgentSessionScanner.test.makeFileIdentityFixture")( + function* (originalInode = 10_000_000_000_000_001n, replacementInode = 10_000_000_000_000_000n) { + 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-large-id-claude-"); + const codexHomePath = yield* makeTempDir("t3code-large-id-codex-"); + const workspace = yield* makeTempDir("t3code-large-id-workspace-"); + const filePath = path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + "rollout-identity.jsonl", + ); + const replacementPath = `${filePath}.replacement`; + const savedPath = `${filePath}.saved`; + for (const [target, sessionId] of [ + [filePath, "original-session"], + [replacementPath, "replaced-session"], + ] as const) { + yield* writeTranscript({ + filePath: target, + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: sessionId, cwd: workspace }, + }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: "Imported prompt" }, + }), + ].join("\n"), + mtimeMs: nowMs, + }); + } + + // Adjacent NTFS IDs round to the same number; birthtimes can also collide. + const birthtime = Option.some(DateTime.toDateUtc(DateTime.makeUnsafe(nowMs))); + const ids = new Map(); + const effectIdentity = (target: string, info: FileSystem.File.Info) => { + if (target !== filePath) return info; + const realInode = Option.getOrThrow(info.ino); + const inode = ids.get(realInode) ?? (ids.size === 0 ? originalInode : replacementInode); + ids.set(realInode, inode); + return { ...info, ino: Option.some(inode), birthtime }; + }; + let opens = 0; + const simulatedFileSystem = FileSystem.FileSystem.of({ + ...fileSystem, + stat: (target) => + fileSystem.stat(target).pipe(Effect.map((info) => effectIdentity(target, info))), + open: (target, options) => { + if (target === filePath) opens += 1; + return fileSystem.open(target, options).pipe( + Effect.map((file) => ({ + ...file, + stat: file.stat.pipe(Effect.map((info) => effectIdentity(target, info))), + readAlloc: (size: number) => file.readAlloc(size), + })), + ); + }, + }); + const scanner = yield* AgentSessionScanner.AgentSessionScanner.pipe( + Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })), + Effect.provideService(FileSystem.FileSystem, simulatedFileSystem), + ); + return { + scanner, + workspace, + opens: () => opens, + replace: Effect.gen(function* () { + yield* fileSystem.rename(filePath, savedPath); + yield* fileSystem.rename(replacementPath, filePath); + }).pipe(Effect.orDie), + }; + }, +); + it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { describe("scan", () => { it.effect("reads Claude project cwds from transcripts, newest first", () => @@ -199,131 +284,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("groups Codex rollouts by cwd across date directories", () => - 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-"); - const otherWorkspace = yield* makeTempDir("t3code-workspace-other-"); - - const rollout = (year: string, month: string, day: string, name: string) => - path.join(codexHomePath, "sessions", year, month, day, name); - - yield* writeTranscript({ - filePath: rollout("2026", "01", "05", "rollout-2026-01-05T10-00-00-aaa.jsonl"), - contents: codexRolloutLine(workspace), - mtimeMs: Date.parse("2026-01-05T10:00:00.000Z"), - }); - yield* writeTranscript({ - filePath: rollout("2026", "02", "09", "rollout-2026-02-09T10-00-00-bbb.jsonl"), - contents: codexRolloutLine(workspace), - mtimeMs: Date.parse("2026-02-09T10:00:00.000Z"), - }); - yield* writeTranscript({ - filePath: rollout("2026", "02", "09", "rollout-2026-02-09T11-00-00-ccc.jsonl"), - contents: codexRolloutLine(otherWorkspace), - mtimeMs: Date.parse("2026-02-09T11:00:00.000Z"), - }); - - const result = yield* runScan({ claudeHomePath, codexHomePath }); - - expect(result.candidates).toEqual([ - { - path: otherWorkspace, - title: path.basename(otherWorkspace), - sources: ["codex"], - threadCount: 1, - lastActiveAt: "2026-02-09T11:00:00.000Z", - alreadyImported: false, - git: null, - }, - { - path: workspace, - title: path.basename(workspace), - sources: ["codex"], - threadCount: 2, - lastActiveAt: "2026-02-09T10:00:00.000Z", - alreadyImported: false, - git: null, - }, - ]); - }), - ); - - it.effect.each(["claudeAgent", "codex"] as const)( - "does not open a non-file %s transcript", - (source) => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); - const codexHomePath = yield* makeTempDir("t3code-codex-home-"); - const transcriptPath = - source === "claudeAgent" - ? path.join(claudeHomePath, "projects", "-slug", "session.jsonl") - : path.join(codexHomePath, "sessions", "2026", "08", "24", "rollout-session.jsonl"); - yield* fileSystem.makeDirectory(transcriptPath, { recursive: true }); - - let transcriptOpenCount = 0; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - open: (filePath, options) => { - if (filePath === transcriptPath) transcriptOpenCount += 1; - return fileSystem.open(filePath, options); - }, - }); - - const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe( - Effect.provideService(FileSystem.FileSystem, simulatedFileSystem), - ); - - expect(result.candidates).toEqual([]); - expect(transcriptOpenCount).toBe(0); - }), - ); - - it.effect.each(["claudeAgent", "codex"] as const)( - "stops %s directory reads at the discovery operation budget", - (source) => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); - const codexHomePath = yield* makeTempDir("t3code-codex-home-"); - const discoveryRoot = - source === "claudeAgent" - ? path.join(claudeHomePath, "projects") - : path.join(codexHomePath, "sessions"); - const emptyDirectories = Array.from( - { length: 20_001 }, - (_, index) => `empty-${index.toString().padStart(5, "0")}`, - ); - let directoryReadCount = 0; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - readDirectory: (directory, options) => { - if (directory === discoveryRoot) { - directoryReadCount += 1; - return Effect.succeed(emptyDirectories); - } - if (path.dirname(directory) === discoveryRoot) { - directoryReadCount += 1; - return Effect.succeed([]); - } - return fileSystem.readDirectory(directory, options); - }, - }); - - const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe( - Effect.provideService(FileSystem.FileSystem, simulatedFileSystem), - ); - - expect(result.candidates).toEqual([]); - expect(directoryReadCount).toBe(20_000); - }), - ); - it.effect("merges the same cwd seen by both agents and flags imported projects", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -402,38 +362,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("matches a persisted project alias to a transcript realpath", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); - const codexHomePath = yield* makeTempDir("t3code-codex-home-"); - const workspace = yield* makeTempDir("t3code-workspace-"); - const linkParent = yield* makeTempDir("t3code-scanner-links-"); - const workspaceAlias = path.join(linkParent, "workspace-alias"); - yield* fileSystem.symlink(workspace, workspaceAlias); - - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), - contents: claudeSessionLine(workspace), - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), - }); - - const result = yield* runScan({ - claudeHomePath, - codexHomePath, - importedWorkspaceRoots: [workspaceAlias], - }); - - expect(result.candidates[0]).toMatchObject({ - path: workspaceAlias, - projectId: ProjectId.make("project-1"), - alreadyImported: true, - git: null, - }); - }), - ); - it.effect("merges case aliases and preserves the persisted project path", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -680,34 +608,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("ignores invalid provider instances while scanning the remaining providers", () => - 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* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-actual", "session.jsonl"), - contents: claudeSessionLine(workspace), - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), - }); - - const result = yield* runScan({ - claudeHomePath, - codexHomePath, - providerInstances: { - [ProviderInstanceId.make("codex")]: { - driver: ProviderDriverKind.make("codex"), - config: { homePath: 123 }, - }, - }, - }); - - expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]); - }), - ); - it.effect("does not scan provider instances disabled by the envelope or config", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -749,25 +649,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("ignores relative working directories from malformed transcripts", () => - 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* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-relative", "session.jsonl"), - contents: claudeSessionLine(path.relative(path.resolve(), workspace)), - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), - }); - - const result = yield* runScan({ claudeHomePath, codexHomePath }); - - expect(result.candidates).toEqual([]); - }), - ); - it.effect("drops candidates whose directory no longer exists", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -834,48 +715,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("excludes Codex scratch directories and Downloads", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); - const codexHomePath = yield* makeTempDir("t3code-codex-home-"); - const home = NodeOS.homedir(); - const runId = path.basename(yield* makeTempDir("t3code-scanner-test-")); - const scratchRoot = path.join(home, "Documents", "Codex", runId); - const scratch = path.join(scratchRoot, "2026-09-01", "some-conversation"); - const downloads = path.join(home, "Downloads", runId); - const keep = yield* makeTempDir("t3code-workspace-keep-"); - yield* fileSystem.makeDirectory(scratch, { recursive: true }); - yield* fileSystem.makeDirectory(downloads, { recursive: true }); - yield* Effect.addFinalizer(() => - Effect.all([ - fileSystem.remove(scratchRoot, { recursive: true }).pipe(Effect.ignore), - fileSystem.remove(downloads, { recursive: true }).pipe(Effect.ignore), - ]), - ); - - for (const [index, cwd] of [scratch, downloads, keep].entries()) { - yield* writeTranscript({ - filePath: path.join( - codexHomePath, - "sessions", - "2026", - "09", - "01", - `rollout-${index}.jsonl`, - ), - contents: codexRolloutLine(cwd), - mtimeMs: Date.parse("2026-09-01T00:00:00.000Z"), - }); - } - - const result = yield* runScan({ claudeHomePath, codexHomePath }); - - expect(result.candidates.map((candidate) => candidate.path)).toEqual([keep]); - }), - ); - it.effect("skips linked git worktrees and reports the origin of real checkouts", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -893,9 +732,12 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { path.join(repo, ".git", "config"), '[core]\n\tbare = false\n[remote "origin"]\n\turl = git@github.com:pingdotgg/t3code.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n', ); + const worktreeGitDir = path.join(repo, ".git", "worktrees", "wt"); + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); yield* fileSystem.writeFileString( path.join(worktree, ".git"), - `gitdir: ${path.join(repo, ".git", "worktrees", "wt")}\n`, + `gitdir: ${worktreeGitDir}\n`, ); yield* fileSystem.makeDirectory(path.join(noRemote, ".git")); yield* fileSystem.writeFileString(path.join(noRemote, ".git", "config"), "[core]\n"); @@ -903,7 +745,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { yield* fileSystem.makeDirectory(submoduleGitDir, { recursive: true }); yield* fileSystem.writeFileString( path.join(submoduleGitDir, "config"), - '[remote "origin"]\n\turl = ssh://github.com/pingdotgg/vendor.git\n', + '[remote "origin"]\n\turl = ssh://gitlab.com/pingdotgg/libs/vendor.git\n', ); yield* fileSystem.writeFileString( path.join(submodule, ".git"), @@ -925,7 +767,10 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { ).toEqual([ { path: submodule, - git: { remoteKey: "github.com/pingdotgg/vendor", repository: "pingdotgg/vendor" }, + git: { + remoteKey: "gitlab.com/pingdotgg/libs/vendor", + repository: "pingdotgg/libs/vendor", + }, }, { path: noRemote, git: { remoteKey: null, repository: null } }, { path: plain, git: null }, @@ -937,6 +782,75 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect( + "offers bare-repository worktrees separately and imports only their own sessions", + () => + 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 configBaseDir = yield* makeTempDir("t3code-scanner-base-"); + const bare = yield* makeTempDir("t3code-workspace-bare-"); + const bareGitDir = path.join(bare, ".git"); + yield* fileSystem.makeDirectory(bareGitDir); + yield* fileSystem.writeFileString( + path.join(bareGitDir, "config"), + '[core] bare = "true" ; bare repository\n[remote "origin"]\nurl = git@github.com:pingdotgg/t3code.git\n', + ); + const dev = path.join(bare, "dev"); + const prod = path.join(bare, "prod"); + const managed = path.join(configBaseDir, "worktrees", "t3code", "sandbox"); + for (const [index, cwd] of [bare, dev, prod, managed].entries()) { + if (cwd !== bare) { + const gitDir = path.join(bareGitDir, "worktrees", path.basename(cwd)); + yield* fileSystem.makeDirectory(gitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n"); + yield* fileSystem.makeDirectory(cwd, { recursive: true }); + yield* fileSystem.writeFileString(path.join(cwd, ".git"), `gitdir: ${gitDir}\n`); + } + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + `rollout-${index}.jsonl`, + ), + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: `session-${index}`, cwd }, + }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: `Work in ${cwd}` }, + }), + ].join("\n"), + mtimeMs: nowMs - index * 1_000, + }); + } + + const input = { claudeHomePath, codexHomePath, configBaseDir }; + const result = yield* runScan(input); + const git = { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" }; + expect( + result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })), + ).toEqual([ + { path: bare, git }, + { path: dev, git }, + { path: prod, git }, + ]); + const threads = yield* runRecentThreads({ ...input, workspaceRoot: dev }); + expect(threads.map((thread) => thread.providerSessionId)).toEqual(["session-1"]); + const managedThreads = yield* runRecentThreads({ ...input, workspaceRoot: managed }); + expect(managedThreads).toEqual([]); + }), + ); + it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1028,356 +942,48 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("finds session metadata after a first record larger than one chunk", () => + it.effect("skips malformed transcripts without failing the scan", () => 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-"); - const history = `{"type":"file-history-snapshot","data":"${"x".repeat(32 * 1024)}"}\n`; yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-large", "session.jsonl"), - contents: `${history}${claudeSessionLine(workspace)}`, - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + filePath: path.join(claudeHomePath, "projects", "-broken", "a.jsonl"), + contents: "not json at all\n", + mtimeMs: Date.parse("2026-05-01T00:00:00.000Z"), + }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-no-cwd", "a.jsonl"), + contents: `{"type":"summary"}\n`, + mtimeMs: Date.parse("2026-05-02T00:00:00.000Z"), + }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-good", "a.jsonl"), + contents: claudeSessionLine(workspace), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), }); const result = yield* runScan({ claudeHomePath, codexHomePath }); - expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]); - }), - ); - - it.effect.each([64, 65])("shares metadata bytes across homes for %s one-MiB files", (count) => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-metadata-home-"); - const secondHome = yield* makeTempDir("t3code-metadata-second-"); - const codexHomePath = yield* makeTempDir("t3code-metadata-codex-"); - const firstWorkspace = yield* makeTempDir("t3code-metadata-first-project-"); - const secondWorkspace = yield* makeTempDir("t3code-metadata-second-project-"); - const directories = [ - path.join(claudeHomePath, "projects", "p"), - path.join(secondHome, "projects", "p"), - ]; - const templates = directories.map((directory) => path.join(directory, "template.jsonl")); - for (const [index, workspace] of [firstWorkspace, secondWorkspace].entries()) { - const record = encodeTranscriptRecord({ cwd: workspace }); - yield* writeTranscript({ - filePath: templates[index]!, - contents: - " ".repeat(1024 * 1024 - new TextEncoder().encode(record).byteLength) + record, - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z") - index * 1_000, - }); - } - const resolveFile = (filePath: string) => { - const index = directories.indexOf(path.dirname(filePath)); - return index === -1 ? filePath : templates[index]!; - }; - let reservedBytes = 0; - let opens = 0; - const requests: number[] = []; - const observedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - readDirectory: (directory, options) => { - const index = directories.indexOf(directory); - return index === -1 - ? fileSystem.readDirectory(directory, options) - : Effect.succeed( - Array.from( - { length: index === 0 ? 32 : count - 32 }, - (_, item) => `session-${item}.jsonl`, - ), - ); - }, - stat: (filePath) => fileSystem.stat(resolveFile(filePath)), - open: (filePath, options) => { - if (!directories.includes(path.dirname(filePath))) - return fileSystem.open(filePath, options); - opens += 1; - return fileSystem.open(resolveFile(filePath), options).pipe( - Effect.map((file) => ({ - ...file, - stat: file.stat, - readAlloc: (size: number) => { - reservedBytes += Number(size); - requests.push(Number(size)); - return file.readAlloc(size); - }, - })), - ); - }, - }); - const result = yield* runScan({ - claudeHomePath, - codexHomePath, - providerInstances: { - [ProviderInstanceId.make("claude-work")]: { - driver: ProviderDriverKind.make("claudeAgent"), - config: { homePath: secondHome }, - }, + expect(result.candidates).toEqual([ + { + path: workspace, + title: path.basename(workspace), + sources: ["claudeAgent"], + threadCount: 1, + lastActiveAt: "2026-05-03T00:00:00.000Z", + alreadyImported: false, + git: null, }, - }).pipe(Effect.provideService(FileSystem.FileSystem, observedFileSystem)); - expect(result.candidates.map((candidate) => candidate.path)).toEqual([ - firstWorkspace, - secondWorkspace, ]); - expect(result.candidates.map((candidate) => candidate.threadCount)).toEqual([32, 32]); - expect(result.truncated).toBe(count === 65 ? true : undefined); - expect(opens).toBe(64); - expect(reservedBytes).toBe(64 * 1024 * 1024); - expect(requests[0]).toBe(8 * 1024); - expect(Math.max(...requests)).toBe(8 * 1024); }), ); + }); - it.effect.each([50, 51])("bounds metadata open/read calls for %s short-read files", (count) => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-short-metadata-home-"); - const codexHomePath = yield* makeTempDir("t3code-short-metadata-codex-"); - const workspace = yield* makeTempDir("t3code-short-metadata-project-"); - const directory = path.join(claudeHomePath, "projects", "p"); - const template = path.join(directory, "template.jsonl"); - const record = encodeTranscriptRecord({ cwd: workspace }); - const contents = " ".repeat(399 - new TextEncoder().encode(record).byteLength) + record; - const bytes = new TextEncoder().encode(contents); - yield* writeTranscript({ - filePath: template, - contents, - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), - }); - let operations = 0; - const observedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - readDirectory: (target, options) => - target === directory - ? Effect.succeed( - Array.from({ length: count }, (_, index) => `session-${index}.jsonl`), - ) - : fileSystem.readDirectory(target, options), - stat: (filePath) => - fileSystem.stat(path.dirname(filePath) === directory ? template : filePath), - open: (filePath, options) => { - if (path.dirname(filePath) !== directory) return fileSystem.open(filePath, options); - operations += 1; - let offset = 0; - return fileSystem.open(template, options).pipe( - Effect.map((file) => ({ - ...file, - stat: file.stat, - readAlloc: () => - Effect.sync(() => { - operations += 1; - if (offset === bytes.length) return Option.none(); - return Option.some(bytes.subarray(offset, ++offset)); - }), - })), - ); - }, - }); - const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe( - Effect.provideService(FileSystem.FileSystem, observedFileSystem), - ); - expect(operations).toBe(20_000); - expect(result.candidates[0]?.threadCount).toBe(50); - expect(result.truncated).toBe(count === 51 ? true : undefined); - }), - ); - - it.effect("bounds malformed metadata records without excluding another account", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-record-metadata-home-"); - const secondHome = yield* makeTempDir("t3code-record-metadata-second-"); - const codexHomePath = yield* makeTempDir("t3code-record-metadata-codex-"); - const workspace = yield* makeTempDir("t3code-record-metadata-project-"); - const directory = path.join(claudeHomePath, "projects", "p"); - const template = path.join(directory, "template.jsonl"); - yield* writeTranscript({ - filePath: template, - contents: "x\n".repeat(1_001), - mtimeMs: Date.parse("2026-01-02T00:00:00.000Z"), - }); - yield* writeTranscript({ - filePath: path.join(secondHome, "projects", "p", "session.jsonl"), - contents: encodeTranscriptRecord({ cwd: workspace }), - mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), - }); - let malformedOpens = 0; - const observedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - readDirectory: (target, options) => - target === directory - ? Effect.succeed(Array.from({ length: 102 }, (_, index) => `session-${index}.jsonl`)) - : fileSystem.readDirectory(target, options), - stat: (filePath) => - fileSystem.stat(path.dirname(filePath) === directory ? template : filePath), - open: (filePath, options) => { - if (path.dirname(filePath) !== directory) return fileSystem.open(filePath, options); - malformedOpens += 1; - return fileSystem.open(template, options); - }, - }); - const result = yield* runScan({ - claudeHomePath, - codexHomePath, - providerInstances: { - [ProviderInstanceId.make("claude-work")]: { - driver: ProviderDriverKind.make("claudeAgent"), - config: { homePath: secondHome }, - }, - }, - }).pipe(Effect.provideService(FileSystem.FileSystem, observedFileSystem)); - expect(result.candidates.map((candidate) => candidate.path)).toEqual([workspace]); - expect(malformedOpens).toBe(100); - expect(result.truncated).toBe(true); - }), - ); - - it.effect.each([19_999, 20_000])( - "reports unfinished directory work for %s project directories", - (count) => - Effect.gen(function* () { - const path = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const claudeHomePath = yield* makeTempDir("t3code-directory-budget-home-"); - const codexHomePath = yield* makeTempDir("t3code-directory-budget-codex-"); - const projectsDir = path.join(claudeHomePath, "projects"); - let reads = 0; - const observedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - readDirectory: (directory, options) => { - if (directory === projectsDir) { - reads += 1; - return Effect.succeed( - Array.from({ length: count }, (_, index) => `project-${index}`), - ); - } - if (path.dirname(directory) === projectsDir) { - reads += 1; - return Effect.succeed([]); - } - return fileSystem.readDirectory(directory, options); - }, - }); - const result = yield* runScan({ claudeHomePath, codexHomePath }).pipe( - Effect.provideService(FileSystem.FileSystem, observedFileSystem), - ); - expect(reads).toBe(20_000); - expect(result.candidates).toEqual([]); - expect(result.truncated).toBe(count === 20_000 ? true : undefined); - }), - ); - - it.effect("skips malformed transcripts without failing the scan", () => - 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* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-broken", "a.jsonl"), - contents: "not json at all\n", - mtimeMs: Date.parse("2026-05-01T00:00:00.000Z"), - }); - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-no-cwd", "a.jsonl"), - contents: `{"type":"summary"}\n`, - mtimeMs: Date.parse("2026-05-02T00:00:00.000Z"), - }); - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-good", "a.jsonl"), - contents: claudeSessionLine(workspace), - mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), - }); - - const result = yield* runScan({ claudeHomePath, codexHomePath }); - - expect(result.candidates).toEqual([ - { - path: workspace, - title: path.basename(workspace), - sources: ["claudeAgent"], - threadCount: 1, - lastActiveAt: "2026-05-03T00:00:00.000Z", - alreadyImported: false, - git: null, - }, - ]); - }), - ); - - it.effect("returns an empty result when neither home directory exists", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const root = yield* makeTempDir("t3code-missing-homes-"); - - const result = yield* runScan({ - claudeHomePath: path.join(root, "no-claude"), - codexHomePath: path.join(root, "no-codex"), - }); - - expect(result.candidates).toEqual([]); - expect(result.scannedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); - }), - ); - }); - - describe("recentThreads", () => { - it.effect.each([false, true])( - "counts terminal newlines correctly with record overflow=%s", - (overflow) => - 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-record-limit-claude-"); - const codexHomePath = yield* makeTempDir("t3code-record-limit-codex-"); - const workspace = yield* makeTempDir("t3code-record-limit-project-"); - const directory = path.join(codexHomePath, "sessions", "2026", "08", "24"); - yield* writeTranscript({ - filePath: path.join(directory, "rollout-records.jsonl"), - contents: makeRecordLimitTranscript(workspace, overflow), - mtimeMs: nowMs, - }); - yield* writeTranscript({ - filePath: path.join(directory, "rollout-older.jsonl"), - contents: [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "older-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Older prompt" }, - }), - ].join("\n"), - mtimeMs: nowMs - 1_000, - }); - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }); - expect(outcomes.map((outcome) => outcome._tag)).toEqual( - overflow ? ["Skipped", "Importable"] : ["Importable", "Skipped"], - ); - expect( - outcomes.flatMap((outcome) => - outcome._tag === "Importable" - ? outcome.thread.messages.map((message) => message.text) - : [], - ), - ).toEqual([overflow ? "Older prompt" : "First prompt"]); - }), - ); - - it.effect("imports recent Claude and Codex sessions for the selected project only", () => + describe("recentThreads", () => { + it.effect("imports recent Claude and Codex sessions for the selected project only", () => Effect.gen(function* () { const path = yield* Path.Path; const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); @@ -1465,54 +1071,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("imports history recorded with a case alias", () => - 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 workspace = yield* makeTempDir("t3code-workspace-"); - const workspaceAlias = path.join( - path.dirname(workspace), - path.basename(workspace).toUpperCase(), - ); - - yield* writeTranscript({ - filePath: path.join(claudeHomePath, "projects", "-alias", "case-session.jsonl"), - contents: [ - encodeTranscriptRecord({ - type: "user", - cwd: workspaceAlias, - sessionId: "case-session", - timestamp: "2026-08-24T10:00:00.000Z", - message: { role: "user", content: "Import case alias history" }, - }), - encodeTranscriptRecord({ - type: "assistant", - sessionId: "case-session", - timestamp: "2026-08-24T10:01:00.000Z", - message: { role: "assistant", content: "Imported" }, - }), - ].join("\n"), - mtimeMs: nowMs, - }); - - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - stat: (filePath) => fileSystem.stat(filePath === workspaceAlias ? workspace : filePath), - }); - const threads = yield* runRecentThreads({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem)); - - expect(threads.map((thread) => thread.providerSessionId)).toEqual(["case-session"]); - }), - ); - it.effect("keeps the provider instance that owns a custom session home", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1554,6 +1112,67 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("excludes Codex subagents from discovery and the recent-thread budget", () => + 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-"); + const subagentSources = [ + { subagent: { thread_spawn: { parent_thread_id: "session-100", depth: 1 } } }, + { subagent: "review" }, + { subagent: { other: "guardian" } }, + { subAgent: "compact" }, + ]; + // Newer subagents would exhaust the 100-transcript import budget before any parent. + const sources = [ + ...Array.from({ length: 100 }, (_, index) => subagentSources[index % 4]), + "vscode", + undefined, + null, + { custom: "launcher" }, + ]; + for (const [index, source] of sources.entries()) { + yield* writeTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + `rollout-${index}.jsonl`, + ), + contents: [ + { type: "session_meta", payload: { id: `session-${index}`, cwd: workspace, source } }, + // A later cwd must not make an excluded rollout eligible again. + { type: "turn_context", payload: { cwd: workspace } }, + { + type: "event_msg", + payload: { type: "user_message", message: "Import this prompt" }, + }, + ] + .map((record) => encodeTranscriptRecord(record)) + .join("\n"), + mtimeMs: nowMs - index * 60_000, + }); + } + + yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const scan = yield* scanner.scan; + expect.soft(scan.candidates.map((candidate) => candidate.threadCount)).toEqual([4]); + const outcomes = yield* Stream.runCollect(scanner.recentThreads(workspace)); + expect( + outcomes.map((outcome) => + outcome._tag === "Importable" ? outcome.thread.providerSessionId : outcome._tag, + ), + ).toEqual(["session-100", "session-101", "session-102", "session-103"]); + }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + }), + ); + it.effect("suppresses duplicate session copies without reporting a skipped import", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1598,109 +1217,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); - it.effect("streams large transcripts across providers without hiding projects", () => - 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-budget-claude-"); - const codexHomePath = yield* makeTempDir("t3code-budget-codex-"); - const workspace = yield* makeTempDir("t3code-budget-workspace-"); - const transcriptPaths = new Set(); - for (const [index, source] of [ - "codex", - "claudeAgent", - "codex", - "claudeAgent", - "codex", - ].entries()) { - const sessionId = `budget-session-${index}`; - const filePath = - source === "codex" - ? path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - `rollout-${sessionId}.jsonl`, - ) - : path.join(claudeHomePath, "projects", "selected", `${sessionId}.jsonl`); - const contents = - source === "codex" - ? [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: sessionId, cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Imported prompt" }, - }), - ].join("\n") - : encodeTranscriptRecord({ - type: "user", - cwd: workspace, - sessionId, - message: { content: "Imported prompt" }, - }); - transcriptPaths.add(filePath); - yield* writeTranscript({ - filePath, - contents: `${contents}\n`.padEnd(16 * 1024 * 1024, " "), - mtimeMs: nowMs - index * 1_000, - }); - } - - const opens = new Map(); - let fullReadBytes = 0; - const trackedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - open: (filePath, options) => { - const count = (opens.get(filePath) ?? 0) + 1; - opens.set(filePath, count); - return fileSystem.open(filePath, options).pipe( - Effect.map((file) => - !transcriptPaths.has(filePath) || count === 1 - ? file - : { - ...file, - stat: file.stat, - readAlloc: (size: number) => - file.readAlloc(size).pipe( - Effect.tap((chunk) => - Effect.sync(() => { - if (chunk._tag === "Some") fullReadBytes += chunk.value.byteLength; - }), - ), - ), - }, - ), - ); - }, - }); - const outcomes = yield* Effect.gen(function* () { - const scanner = yield* AgentSessionScanner.AgentSessionScanner; - const scan = yield* scanner.scan; - expect(scan.candidates[0]?.threadCount).toBe(5); - return yield* scanner.recentThreads(workspace).pipe(Stream.runCollect); - }).pipe( - Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })), - Effect.provideService(FileSystem.FileSystem, trackedFileSystem), - ); - - expect(outcomes.map((outcome) => outcome._tag)).toEqual([ - "Importable", - "Importable", - "Importable", - "Importable", - "Importable", - ]); - expect(fullReadBytes).toBe(80 * 1024 * 1024); - }), - ); - it.effect("skips excessive records without blocking an older valid transcript", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1844,536 +1360,127 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { it.effect("checks file identity and provider before skipping completed history", () => 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-completed-claude-"); - const codexHomePath = yield* makeTempDir("t3code-completed-codex-"); - const workspace = yield* makeTempDir("t3code-completed-workspace-"); - const filePath = path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-replaced.jsonl", - ); - const contents = (sessionId: string) => - [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: sessionId, cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Imported prompt" }, - }), - ].join("\n"); - yield* writeTranscript({ - filePath, - contents: contents("original-session"), - mtimeMs: nowMs, + const fixture = yield* makeFileIdentityFixture(42n, 43n); + const { scanner, workspace } = fixture; + const initial = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect); + const imported = initial[0]; + expect(imported?._tag).toBe("Importable"); + if (imported?._tag !== "Importable") return; + const legacy = decodeImportSource({ ...imported.source, inode: 42 }); + const opensBeforeCompleted = fixture.opens(); + const completed = yield* scanner.recentThreads(workspace, [legacy]).pipe(Stream.runCollect); + expect(completed[0]?._tag).toBe("AlreadyImported"); + expect(fixture.opens()).toBe(opensBeforeCompleted); + const wrongProvider = yield* scanner + .recentThreads(workspace, [{ ...imported.source, provider: "claudeAgent" }]) + .pipe(Stream.runCollect); + expect(wrongProvider[0]?._tag).toBe("Importable"); + + yield* fixture.replace; + const replaced = yield* scanner + .recentThreads(workspace, [imported.source]) + .pipe(Stream.runCollect); + expect(replaced[0]).toMatchObject({ + _tag: "Importable", + thread: { providerSessionId: "replaced-session" }, + source: { size: imported.source.size, mtimeMs: imported.source.mtimeMs }, }); + }), + ); - yield* Effect.gen(function* () { - const scanner = yield* AgentSessionScanner.AgentSessionScanner; + it.effect( + "imports same-metadata replacements with exact large file IDs and backfills legacy IDs once", + () => + Effect.gen(function* () { + const fixture = yield* makeFileIdentityFixture(); + const { scanner, workspace } = fixture; const initial = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect); const imported = initial[0]; - expect(imported?._tag).toBe("Importable"); - if (imported?._tag !== "Importable") return; - const completed = yield* scanner - .recentThreads(workspace, [imported.source]) - .pipe(Stream.runCollect); - expect(completed[0]?._tag).toBe("AlreadyImported"); - const wrongProvider = yield* scanner - .recentThreads(workspace, [{ ...imported.source, provider: "claudeAgent" }]) - .pipe(Stream.runCollect); - expect(wrongProvider[0]?._tag).toBe("Importable"); - - yield* fileSystem.open(filePath); - yield* fileSystem.remove(filePath); - yield* writeTranscript({ - filePath, - contents: contents("replaced-session"), - mtimeMs: nowMs, - }); - const replaced = yield* scanner - .recentThreads(workspace, [imported.source]) - .pipe(Stream.runCollect); - expect(replaced[0]).toMatchObject({ - _tag: "Importable", - thread: { providerSessionId: "replaced-session" }, - source: { size: imported.source.size, mtimeMs: imported.source.mtimeMs }, - }); - }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); - }), - ); - - it.effect("imports visible history from a transcript with an oversized tool record", () => - 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-"); - const transcript = `${[ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "large-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Import this large session" }, - }), - ].join("\n")}\n${encodeTranscriptRecord({ type: "tool_result", data: "" }).padEnd( - 16 * 1024 * 1024 + 1, - " ", - )}`; - yield* writeTranscript({ - filePath: path.join(codexHomePath, "sessions", "2026", "08", "24", "rollout-large.jsonl"), - contents: transcript, - mtimeMs: nowMs, - }); - - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }); - - expect(outcomes).toMatchObject([ - { - _tag: "Importable", - thread: { - providerSessionId: "large-session", - messages: [{ role: "user", text: "Import this large session" }], - }, - }, - ]); - }), - ); - - it.effect("reports stat, read, and parse failures as skipped", () => - 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 workspace = yield* makeTempDir("t3code-workspace-"); - const missingPath = path.join(codexHomePath, "missing.jsonl"); - const transcriptPaths = { - stat: path.join(codexHomePath, "sessions", "2026", "08", "24", "rollout-stat.jsonl"), - read: path.join(codexHomePath, "sessions", "2026", "08", "24", "rollout-read.jsonl"), - parse: path.join(codexHomePath, "sessions", "2026", "08", "24", "rollout-parse.jsonl"), - }; - const transcriptContents = (sessionId: string) => - [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: sessionId, cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Import this session" }, - }), - ].join("\n"); - - yield* writeTranscript({ - filePath: transcriptPaths.stat, - contents: transcriptContents("stat-session"), - mtimeMs: nowMs, - }); - yield* writeTranscript({ - filePath: transcriptPaths.read, - contents: transcriptContents("read-session"), - mtimeMs: nowMs, - }); - yield* writeTranscript({ - filePath: transcriptPaths.parse, - contents: encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "parse-session", cwd: workspace }, - }), - mtimeMs: nowMs, - }); - - let statCount = 0; - let readOpenCount = 0; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - stat: (filePath) => { - if (filePath !== transcriptPaths.stat) return fileSystem.stat(filePath); - statCount += 1; - return fileSystem.stat(statCount === 1 ? filePath : missingPath); - }, - open: (filePath, options) => { - if (filePath !== transcriptPaths.read) return fileSystem.open(filePath, options); - readOpenCount += 1; - return fileSystem.open(readOpenCount === 1 ? filePath : missingPath, options); - }, - }); - - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem)); - - expect(outcomes).toEqual([{ _tag: "Skipped" }, { _tag: "Skipped" }, { _tag: "Skipped" }]); - }), - ); - - it.effect("does not reopen a transcript that becomes a non-file after discovery", () => - 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 workspace = yield* makeTempDir("t3code-workspace-"); - const nonFilePath = yield* makeTempDir("t3code-non-file-"); - const transcriptPath = path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-changed.jsonl", - ); - yield* writeTranscript({ - filePath: transcriptPath, - contents: [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "changed-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Do not import this session" }, - }), - ].join("\n"), - mtimeMs: nowMs, - }); - - let transcriptStatCount = 0; - let transcriptOpenCount = 0; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - stat: (filePath) => { - if (filePath !== transcriptPath) return fileSystem.stat(filePath); - transcriptStatCount += 1; - return fileSystem.stat(transcriptStatCount === 1 ? transcriptPath : nonFilePath); - }, - open: (filePath, options) => { - if (filePath === transcriptPath) transcriptOpenCount += 1; - return fileSystem.open(filePath, options); - }, - }); - - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem)); - - expect(transcriptStatCount).toBe(2); - expect(transcriptOpenCount).toBe(1); - expect(outcomes).toEqual([{ _tag: "Skipped" }]); - }), - ); - - it.effect("does not import a transcript dated after the current time", () => - 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* writeTranscript({ - filePath: path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-future.jsonl", - ), - contents: [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "future-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Future work" }, - }), - ].join("\n"), - // Node's BigInt stat (which the Effect file system now uses) floors - // sub-millisecond precision, so a one-millisecond offset can round - // back to `nowMs`; use a full second to stay clear of the clock. - mtimeMs: nowMs + 1_000, - }); - - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }); - - expect(outcomes).toEqual([]); - }), - ); - - it.effect("skips growth during reading without exceeding the reserved bytes", () => - 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 workspace = yield* makeTempDir("t3code-workspace-"); - const transcriptPath = path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-growing.jsonl", - ); - const contents = [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "growing-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Do not import a changing file" }, - }), - ].join("\n"); - yield* writeTranscript({ filePath: transcriptPath, contents, mtimeMs: nowMs }); - let transcriptOpenCount = 0; - let fullReadBytes = 0; - let grew = false; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - open: (filePath, options) => { - if (filePath !== transcriptPath) return fileSystem.open(filePath, options); - transcriptOpenCount += 1; - if (transcriptOpenCount === 1) return fileSystem.open(filePath, options); - return fileSystem.open(filePath, options).pipe( - Effect.map((file) => ({ - ...file, - stat: file.stat, - readAlloc: (size: number) => - file.readAlloc(size).pipe( - Effect.tap((chunk) => - Effect.gen(function* () { - if (chunk._tag === "None") return; - fullReadBytes += chunk.value.byteLength; - if (!grew) { - grew = true; - yield* fileSystem.writeFileString(filePath, `${contents}\nchanged`); - } - }), - ), - ), - })), - ); - }, - }); - - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem)); - - expect(transcriptOpenCount).toBe(2); - expect(fullReadBytes).toBe(new TextEncoder().encode(contents).byteLength); - expect(outcomes).toEqual([{ _tag: "Skipped" }]); - }), - ); - - it.effect("skips a transcript that shrinks after its size check", () => - 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 workspace = yield* makeTempDir("t3code-workspace-"); - const transcriptPath = path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-shrinking.jsonl", - ); - const shrunkPath = path.join(codexHomePath, "shrunk.jsonl"); - const contents = [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "shrinking-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Do not import a changing file" }, - }), - ].join("\n"); - yield* writeTranscript({ - filePath: transcriptPath, - contents: `${contents}\n${"padding".repeat(100)}`, - mtimeMs: nowMs, - }); - yield* writeTranscript({ filePath: shrunkPath, contents, mtimeMs: nowMs }); - - let transcriptOpenCount = 0; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - open: (filePath, options) => { - if (filePath !== transcriptPath) return fileSystem.open(filePath, options); - transcriptOpenCount += 1; - return fileSystem.open( - transcriptOpenCount === 1 ? transcriptPath : shrunkPath, - options, - ); - }, - }); - - const outcomes = yield* runRecentThreadOutcomes({ - claudeHomePath, - codexHomePath, - workspaceRoot: workspace, - }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem)); - - expect(transcriptOpenCount).toBe(2); - expect(outcomes).toEqual([{ _tag: "Skipped" }]); - }), - ); - - it.effect("does not read the second transcript when the consumer takes one thread", () => - 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 workspace = yield* makeTempDir("t3code-workspace-"); - const makeCodexTranscript = (sessionId: string, text: string) => - [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: sessionId, cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: text }, - }), - ].join("\n"); - const olderPath = path.join( - codexHomePath, - "sessions", - "2026", - "08", - "23", - "rollout-older.jsonl", - ); - const newerPath = path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-newer.jsonl", - ); - yield* writeTranscript({ - filePath: olderPath, - contents: makeCodexTranscript("older-session", "Older prompt"), - mtimeMs: nowMs - 1_000, - }); - yield* writeTranscript({ - filePath: newerPath, - contents: makeCodexTranscript("newer-session", "Newer prompt"), - mtimeMs: nowMs, - }); - - const openCounts = new Map(); - const contentReads: Array = []; - const trackedPaths = new Set([olderPath, newerPath]); - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - open: (filePath, options) => { - if (trackedPaths.has(filePath)) { - const count = (openCounts.get(filePath) ?? 0) + 1; - openCounts.set(filePath, count); - if (count === 2) contentReads.push(filePath); - } - return fileSystem.open(filePath, options); - }, - }); - - const threads = yield* Effect.gen(function* () { - const scanner = yield* AgentSessionScanner.AgentSessionScanner; - return yield* scanner.recentThreads(workspace).pipe( - Stream.take(1), - Stream.runCollect, - Effect.map((items) => Array.from(items)), - ); - }).pipe( - Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath })), - Effect.provideService(FileSystem.FileSystem, simulatedFileSystem), - ); + expect(imported?._tag).toBe("Importable"); + if (imported?._tag !== "Importable") return; - expect( - threads.flatMap((outcome) => - outcome._tag === "Importable" ? [outcome.thread.providerSessionId] : [], - ), - ).toEqual(["newer-session"]); - expect(contentReads).toEqual([newerPath]); - expect(openCounts.get(olderPath)).toBe(1); - }), + yield* fixture.replace; + const replaced = yield* scanner + .recentThreads(workspace, [imported.source]) + .pipe(Stream.runCollect); + expect(replaced[0]).toMatchObject({ + _tag: "Importable", + thread: { providerSessionId: "replaced-session" }, + source: { + ...imported.source, + providerSessionId: "replaced-session", + inode: "10000000000000000", + }, + }); + expect(imported.source.inode).toBe("10000000000000001"); + if (replaced[0]?._tag !== "Importable") return; + + const roundedInode = Number(imported.source.inode); + expect(Number.isSafeInteger(roundedInode)).toBe(false); + expect(String(roundedInode)).toBe(replaced[0].source.inode); + for (const inode of [null, roundedInode]) { + const legacy = decodeImportSource({ ...imported.source, inode }); + const opensBeforeBackfill = fixture.opens(); + const backfilled = yield* scanner + .recentThreads(workspace, [legacy]) + .pipe(Stream.runCollect); + expect(backfilled[0]).toMatchObject({ + _tag: "Importable", + thread: { providerSessionId: "replaced-session" }, + source: replaced[0].source, + }); + expect(fixture.opens()).toBe(opensBeforeBackfill + 1); + if (backfilled[0]?._tag !== "Importable") return; + const completed = yield* scanner + .recentThreads(workspace, [backfilled[0].source]) + .pipe(Stream.runCollect); + expect(completed[0]?._tag).toBe("AlreadyImported"); + expect(fixture.opens()).toBe(opensBeforeBackfill + 1); + } + }), ); - it.effect("does not import sessions from a T3-managed worktree", () => + it.effect("imports long Claude tool history with metadata from discarded records", () => 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 configBaseDir = yield* makeTempDir("t3code-scanner-base-"); - const workspace = path.join(configBaseDir, "worktrees", "t3code", "managed-worktree"); - yield* fileSystem.makeDirectory(workspace, { recursive: true }); - + const claudeHomePath = yield* makeTempDir("t3code-long-claude-"); + const codexHomePath = yield* makeTempDir("t3code-long-codex-"); + const workspace = yield* makeTempDir("t3code-long-workspace-"); + const record = (fields: Record) => + encodeTranscriptRecord({ sessionId: "first-session", ...fields }); + const toolResult = record({ + type: "user", + cwd: path.join(workspace, "later-cwd"), + message: { + role: "user", + content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }], + }, + }); yield* writeTranscript({ - filePath: path.join( - codexHomePath, - "sessions", - "2026", - "08", - "24", - "rollout-managed.jsonl", - ), + filePath: path.join(claudeHomePath, "projects", "-slug", "long-session.jsonl"), contents: [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "managed-session", cwd: workspace }, + record({ type: "attachment", cwd: workspace, aiTitle: "Old title" }), + record({ type: "user", message: { role: "user", content: "First prompt" } }), + record({ + type: "assistant", + message: { role: "assistant", model: "claude-opus-5-5", content: "First reply" }, }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Do not import this session" }, + // Small tool records exceed the real 32 MiB selected-history budget in aggregate. + ...Array.from({ length: 20_000 }, () => toolResult), + record({ type: "user", message: { role: "user", content: "Latest prompt" } }), + record({ + type: "assistant", + message: { + role: "assistant", + model: "claude-sonnet-5-5", + content: [{ type: "tool_use", id: "toolu_1", name: "Bash", input: {} }], + }, }), + record({ type: "custom-title", customTitle: "Renamed conversation" }), + record({ type: "ai-title", aiTitle: "Newest title" }), + record({ type: "attachment", sessionId: "latest-session" }), ].join("\n"), mtimeMs: nowMs, }); @@ -2381,60 +1488,92 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const threads = yield* runRecentThreads({ claudeHomePath, codexHomePath, - configBaseDir, workspaceRoot: workspace, }); - expect(threads).toEqual([]); + expect(threads).toMatchObject([ + { + providerSessionId: "latest-session", + title: "Renamed conversation", + model: "claude-sonnet-5-5", + messages: [ + { role: "user", text: "First prompt" }, + { role: "assistant", text: "First reply" }, + { role: "user", text: "Latest prompt" }, + ], + }, + ]); }), ); - it.effect("uses one deterministic provider instance for a shared session home", () => + it.effect("skips growth during reading without exceeding the reserved bytes", () => 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 sharedHome = yield* makeTempDir("t3code-codex-shared-"); const workspace = yield* makeTempDir("t3code-workspace-"); - - yield* writeTranscript({ - filePath: path.join(sharedHome, "sessions", "2026", "08", "24", "rollout-shared.jsonl"), - contents: [ - encodeTranscriptRecord({ - type: "session_meta", - payload: { id: "shared-session", cwd: workspace }, - }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: "Use the shared session" }, - }), - ].join("\n"), - mtimeMs: nowMs, + const transcriptPath = path.join( + codexHomePath, + "sessions", + "2026", + "08", + "24", + "rollout-growing.jsonl", + ); + const contents = [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: "growing-session", cwd: workspace }, + }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: "Do not import a changing file" }, + }), + ].join("\n"); + yield* writeTranscript({ filePath: transcriptPath, contents, mtimeMs: nowMs }); + let transcriptOpenCount = 0; + let fullReadBytes = 0; + let grew = false; + const simulatedFileSystem = FileSystem.FileSystem.of({ + ...fileSystem, + open: (filePath, options) => { + if (filePath !== transcriptPath) return fileSystem.open(filePath, options); + transcriptOpenCount += 1; + if (transcriptOpenCount === 1) return fileSystem.open(filePath, options); + return fileSystem.open(filePath, options).pipe( + Effect.map((file) => ({ + ...file, + stat: file.stat, + readAlloc: (size: number) => + file.readAlloc(size).pipe( + Effect.tap((chunk) => + Effect.gen(function* () { + if (chunk._tag === "None") return; + fullReadBytes += chunk.value.byteLength; + if (!grew) { + grew = true; + yield* fileSystem.writeFileString(filePath, `${contents}\nchanged`); + } + }), + ), + ), + })), + ); + }, }); - const threads = yield* runRecentThreads({ + const outcomes = yield* runRecentThreadOutcomes({ claudeHomePath, codexHomePath, workspaceRoot: workspace, - providerInstances: { - [ProviderInstanceId.make("codex")]: { - driver: ProviderDriverKind.make("codex"), - config: { homePath: sharedHome }, - }, - [ProviderInstanceId.make("codex-personal")]: { - driver: ProviderDriverKind.make("codex"), - config: { homePath: sharedHome }, - }, - [ProviderInstanceId.make("codex-work")]: { - driver: ProviderDriverKind.make("codex"), - config: { homePath: sharedHome }, - }, - }, - }); + }).pipe(Effect.provideService(FileSystem.FileSystem, simulatedFileSystem)); - expect(threads.map((thread) => thread.providerInstanceId)).toEqual(["codex"]); + expect(transcriptOpenCount).toBe(2); + expect(fullReadBytes).toBe(new TextEncoder().encode(contents).byteLength); + expect(outcomes).toEqual([{ _tag: "Skipped" }]); }), ); @@ -2482,88 +1621,6 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { expect(threads.map((thread) => thread.providerInstanceId)).toEqual(["codex-work"]); }), ); - - it.effect("keeps a second account when the first has 5000 newer files", () => - 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 oldWorkspace = yield* makeTempDir("t3code-workspace-old-"); - const recentWorkspace = yield* makeTempDir("t3code-workspace-recent-"); - const recentHome = yield* makeTempDir("t3code-claude-recent-home-"); - const oldDirectory = path.join(claudeHomePath, "projects", "-aaa-old"); - const oldTranscript = path.join(oldDirectory, "old.jsonl"); - const recentDirectory = path.join(recentHome, "projects", "-zzz-recent"); - - yield* writeTranscript({ - filePath: oldTranscript, - contents: encodeTranscriptRecord({ - type: "user", - cwd: oldWorkspace, - sessionId: "old-session", - message: { role: "user", content: "Old work" }, - }), - mtimeMs: nowMs, - }); - yield* writeTranscript({ - filePath: path.join(recentDirectory, "recent.jsonl"), - contents: encodeTranscriptRecord({ - type: "user", - cwd: recentWorkspace, - sessionId: "recent-session", - message: { role: "user", content: "Recent work" }, - }), - mtimeMs: nowMs - 1_000, - }); - - const simulatedOldTranscripts = Array.from( - { length: 5_000 }, - (_, index) => `old-${index}.jsonl`, - ); - const resolveTranscript = (filePath: string) => - path.dirname(filePath) === oldDirectory && path.basename(filePath).startsWith("old-") - ? oldTranscript - : filePath; - const simulatedFileSystem = FileSystem.FileSystem.of({ - ...fileSystem, - readDirectory: (directory, options) => - directory === oldDirectory - ? Effect.succeed(simulatedOldTranscripts) - : fileSystem.readDirectory(directory, options), - stat: (filePath) => fileSystem.stat(resolveTranscript(filePath)), - open: (filePath, options) => fileSystem.open(resolveTranscript(filePath), options), - }); - - const input = { - claudeHomePath, - codexHomePath, - providerInstances: { - [ProviderInstanceId.make("claude-work")]: { - driver: ProviderDriverKind.make("claudeAgent"), - config: { homePath: recentHome }, - }, - }, - }; - const threads = yield* Effect.gen(function* () { - const scanner = yield* AgentSessionScanner.AgentSessionScanner; - const scan = yield* scanner.scan; - expect(scan.truncated).toBe(true); - return yield* scanner.recentThreads(recentWorkspace).pipe(Stream.runCollect); - }).pipe( - Effect.provide(layerScannerTest(input)), - Effect.provideService(FileSystem.FileSystem, simulatedFileSystem), - ); - - expect( - threads.flatMap((outcome) => - outcome._tag === "Importable" ? [outcome.thread.providerSessionId] : [], - ), - ).toEqual(["recent-session"]); - }), - ); }); }); @@ -2648,6 +1705,40 @@ describe("parseAgentSessionTranscript", () => { }); }); + it.each([ + { customTitles: ["Refactor auth module"], expected: "Refactor auth module" }, + // Claude writes an empty customTitle when the user clears a rename. + { customTitles: ["Refactor auth module", ""], expected: "Generated title" }, + ])("uses Claude custom titles $customTitles over the AI title", ({ customTitles, expected }) => { + const aiTitle = JSON.stringify({ + type: "ai-title", + aiTitle: "Generated title", + sessionId: "claude-session", + }); + const thread = AgentSessionScanner.parseAgentSessionTranscript({ + contents: [ + JSON.stringify({ + type: "user", + sessionId: "claude-session", + timestamp: "2026-08-24T10:00:00.000Z", + message: { role: "user", content: "/effort" }, + }), + // Claude rewrites both records on every metadata flush with ai-title + // last, so a later ai-title must not override the user's rename. + ...customTitles.flatMap((customTitle) => [ + JSON.stringify({ type: "custom-title", customTitle, sessionId: "claude-session" }), + aiTitle, + ]), + ].join("\n"), + source: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + fallbackSessionId: "fallback", + lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), + }); + + expect(thread?.title).toBe(expected); + }); + it("drops injected Codex instructions while keeping the visible user event", () => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: [ @@ -3064,53 +2155,6 @@ describe("parseAgentSessionTranscript", () => { ]); }); - it("preserves a canonical Codex event that starts with context markup", () => { - const prompt = - "\n/tmp/project\n\n\nCreate a useful project."; - const thread = AgentSessionScanner.parseAgentSessionTranscript({ - contents: [ - encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { - type: "user_message", - message: prompt, - }, - }), - ].join("\n"), - source: "codex", - providerInstanceId: ProviderInstanceId.make("codex"), - fallbackSessionId: "fallback", - lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"), - }); - - expect(thread?.title).toBe("Create a useful project."); - expect(thread?.messages.map((message) => message.text)).toEqual([prompt]); - }); - - it("preserves a Codex request heading in a canonical event", () => { - const prompt = "\n ## My request for Codex:\n\nFix the visible bug"; - const thread = AgentSessionScanner.parseAgentSessionTranscript({ - contents: [ - encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { - type: "user_message", - message: prompt, - }, - }), - ].join("\n"), - source: "codex", - providerInstanceId: ProviderInstanceId.make("codex"), - fallbackSessionId: "fallback", - lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"), - }); - - expect(thread?.title).toBe("Fix the visible bug"); - expect(thread?.messages.map((message) => message.text)).toEqual([prompt]); - }); - it("titles a Codex event after the request that follows injected setup blocks", () => { const prompt = [ "\nGitHub\n", @@ -3136,26 +2180,6 @@ describe("parseAgentSessionTranscript", () => { expect(thread?.messages.map((message) => message.text)).toEqual([prompt]); }); - it("keeps context markup quoted inside visible Codex user text", () => { - const quoted = - "Do not remove this example:\n\n/tmp/example\n"; - const thread = AgentSessionScanner.parseAgentSessionTranscript({ - contents: [ - encodeTranscriptRecord({ type: "session_meta", payload: { id: "codex-session" } }), - encodeTranscriptRecord({ - type: "event_msg", - payload: { type: "user_message", message: quoted }, - }), - ].join("\n"), - source: "codex", - providerInstanceId: ProviderInstanceId.make("codex"), - fallbackSessionId: "fallback", - lastActiveAtMs: Date.parse("2026-08-25T08:00:00.000Z"), - }); - - expect(thread?.messages.map((message) => message.text)).toEqual([quoted]); - }); - it("skips sessions without a visible user message", () => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: JSON.stringify({ @@ -3170,32 +2194,4 @@ describe("parseAgentSessionTranscript", () => { expect(thread).toBeNull(); }); - - it("keeps the first prompt when later assistant output exceeds the message limit", () => { - const transcript = [ - encodeTranscriptRecord({ - type: "user", - sessionId: "claude-session", - message: { role: "user", content: "Keep this prompt" }, - }), - ...Array.from({ length: 250 }, (_, index) => - encodeTranscriptRecord({ - type: "assistant", - message: { role: "assistant", content: `Assistant update ${index}` }, - }), - ), - ].join("\n"); - - const thread = AgentSessionScanner.parseAgentSessionTranscript({ - contents: transcript, - source: "claudeAgent", - providerInstanceId: ProviderInstanceId.make("claudeAgent"), - fallbackSessionId: "fallback", - lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), - }); - - expect(thread?.messages).toHaveLength(200); - expect(thread?.messages[0]?.text).toBe("Keep this prompt"); - expect(thread?.messages.at(-1)?.text).toBe("Assistant update 249"); - }); }); diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 5b22f874b6eb3..9c26b187a55bf 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -24,19 +24,17 @@ import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; -import { - normalizeGitRemoteUrl, - parseGitHubRepositoryNameWithOwnerFromRemoteUrl, - parseOriginUrlFromGitConfig, -} from "@t3tools/shared/git"; +import { isBareGitConfig, parseOriginUrlFromGitConfig } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; +import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; import * as ServerConfig from "../config.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ServerSettings from "../serverSettings.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { createTranscriptJsonReader, createTranscriptJsonSelector, @@ -55,11 +53,7 @@ const MAX_METADATA_OPERATIONS_PER_SOURCE = MAX_TRANSCRIPTS_PER_SOURCE * 4; const MAX_METADATA_RECORDS_PER_SOURCE = 100_000; const MAX_METADATA_RECORDS_PER_TRANSCRIPT = 1_000; const RECENT_THREAD_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; -/** - * Large tool results (especially screenshots) can make an otherwise ordinary - * Codex transcript several GiB. Streaming field selection avoids allocating - * those payloads. - */ +// Screenshot-heavy transcripts can reach GiB; select fields while streaming to avoid allocating payloads. const MAX_IMPORTED_TRANSCRIPT_BYTES = 4 * 1024 * 1024 * 1024; const MAX_IMPORTED_MESSAGES = 200; const MAX_IMPORT_HISTORY_BYTES = 32 * 1024 * 1024; @@ -88,6 +82,7 @@ const TranscriptRecord = Schema.Struct({ cwd: Schema.optional(Schema.String), sessionId: Schema.optional(Schema.String), aiTitle: Schema.optional(Schema.String), + customTitle: Schema.optional(Schema.String), isSidechain: Schema.optional(Schema.Boolean), isMeta: Schema.optional(Schema.Boolean), isCompactSummary: Schema.optional(Schema.Boolean), @@ -214,16 +209,17 @@ function splitTranscriptRecords(contents: string, limit: number): string[] { return records.split("\n", limit); } +function isTextContentBlock(block: typeof TranscriptContentBlock.Type): boolean { + return block.type === "text" || block.type === "input_text" || block.type === "output_text"; +} + function extractText( content: string | ReadonlyArray | undefined, ): string { if (typeof content === "string") return content.trim(); if (content === undefined) return ""; return content - .filter( - (block) => - block.type === "text" || block.type === "input_text" || block.type === "output_text", - ) + .filter(isTextContentBlock) .map((block) => block.text?.trim() ?? "") .filter((text) => text.length > 0) .join("\n"); @@ -247,6 +243,40 @@ function codexTurnId(metadata: unknown): string | null { return decoded.value.turn_id; } +function isHiddenClaudeRecord(record: DecodedTranscriptRecord): boolean { + return record.isSidechain === true || record.isMeta === true || record.isCompactSummary === true; +} + +// Claude repeats session fields on records that need not be retained. +interface ClaudeFields { + readonly sessionId: string | undefined; + readonly title: string | undefined; + readonly customTitle: string | null; + readonly model: string | undefined; +} + +const emptyClaudeFields: ClaudeFields = { + sessionId: undefined, + title: undefined, + customTitle: null, + model: undefined, +}; + +function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord): ClaudeFields { + if (isHiddenClaudeRecord(record)) return fields; + const model = record.message?.model?.trim(); + return { + sessionId: record.sessionId?.trim() || fields.sessionId, + title: record.aiTitle?.trim() || fields.title, + // Claude flushes the AI title after the user's rename; an empty rename clears it. + customTitle: + record.customTitle === undefined ? fields.customTitle : record.customTitle.trim() || null, + // Claude uses this sentinel for local error responses. It is not a + // model ID that can be selected when the imported session resumes. + model: model && model !== "" ? model : fields.model, + }; +} + // Codex records setup context as user text ahead of the real request. Skip // these leading blocks when deriving a title; imported messages keep them. const CODEX_TITLE_PREAMBLE = @@ -265,20 +295,26 @@ export function parseAgentSessionTranscript( ): AgentSessionThread | null { if (lines.length > MAX_IMPORT_RECORDS) return null; const records = lines.flatMap((line) => Option.toArray(decodeTranscriptRecord(line))); - return parseAgentSessionRecords(input, records); + const claudeFields = + input.source === "claudeAgent" + ? records.reduce(foldClaudeFields, emptyClaudeFields) + : emptyClaudeFields; + return parseAgentSessionRecords(input, records, claudeFields); } function parseAgentSessionRecords( input: AgentSessionTranscriptMetadata, records: ReadonlyArray, + claudeFields: ClaudeFields, ): AgentSessionThread | null { const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs)); // Claude filenames are session IDs. Codex rollout filenames include extra // timestamp text, so only transcript metadata can provide a resumable ID. - let providerSessionId = input.source === "codex" ? "" : input.fallbackSessionId; - let title: string | null = null; + let providerSessionId = + input.source === "codex" ? "" : (claudeFields.sessionId ?? input.fallbackSessionId); + const title = claudeFields.title ?? null; + let model = claudeFields.model ?? null; let derivedTitle: string | undefined; - let model: string | null = null; let hasCodexSessionId = false; const messages: Array = []; let firstUserMessage: @@ -370,23 +406,8 @@ function parseAgentSessionRecords( for (const record of records) { recordIndex += 1; if (input.source === "claudeAgent") { - if ( - record.isSidechain === true || - record.isMeta === true || - record.isCompactSummary === true - ) { - continue; - } - if (record.sessionId?.trim()) providerSessionId = record.sessionId.trim(); - if (record.aiTitle?.trim()) title = record.aiTitle.trim(); - const messageModel = record.message?.model?.trim(); - // Claude uses this sentinel for local error responses. It is not a - // model ID that can be selected when the imported session resumes. - if (messageModel && messageModel !== "") model = messageModel; - if (record.type !== "user" && record.type !== "assistant") { - continue; - } - + if (isHiddenClaudeRecord(record)) continue; + if (record.type !== "user" && record.type !== "assistant") continue; const text = extractText(record.message?.content); if (text.length === 0) continue; retainMessage({ @@ -413,9 +434,7 @@ function parseAgentSessionRecords( if (record.type === "event_msg" && record.payload?.type === "user_message") { const text = record.payload.message ?? ""; if (text.trim().length === 0) continue; - // Codex can write the same prompt as both a response item and an event. - // Remove only the matching response copy so mixed-format logs keep every - // distinct user message. + // Codex can duplicate prompts across formats; remove only matching response copies. for (let index = messages.length - 1; index >= 0; index--) { const message = messages[index]; if (message?.role === "assistant") break; @@ -471,7 +490,7 @@ function parseAgentSessionRecords( source: input.source, providerInstanceId: input.providerInstanceId, providerSessionId, - title: title ?? derivedTitle ?? "Imported thread", + title: claudeFields.customTitle ?? title ?? derivedTitle ?? "Imported thread", model, createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp, updatedAt: fallbackTimestamp, @@ -488,16 +507,18 @@ function shouldRetainDecodedRecord( source: AgentSessionSource, record: DecodedTranscriptRecord, ): boolean { - if (extractDecodedCwd(record) !== null) return true; if (source === "claudeAgent") { - return ( - record.type === "user" || - record.type === "assistant" || - record.sessionId !== undefined || - record.aiTitle !== undefined || - record.message?.model !== undefined - ); + if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) { + return false; + } + const content = record.message?.content; + return typeof content === "string" + ? content.trim().length > 0 + : (content?.some( + (block) => isTextContentBlock(block) && (block.text?.trim().length ?? 0) > 0, + ) ?? false); } + if (extractDecodedCwd(record) !== null) return true; return ( record.type === "session_meta" || record.type === "turn_context" || @@ -525,7 +546,8 @@ function isT3ManagedWorktree( ); } -function extractCwd(line: string): string | null { +// false stops metadata scanning for an excluded rollout, even if later records contain a cwd. +function extractCwd(line: string, source: AgentSessionSource): string | null | false { let parsed: unknown; try { parsed = JSON.parse(line); @@ -540,6 +562,17 @@ function extractCwd(line: string): string | null { } const payload = record.payload; if (typeof payload === "object" && payload !== null) { + if (source === "codex" && record.type === "session_meta") { + const sessionSource = (payload as Record).source; + if ( + typeof sessionSource === "object" && + sessionSource !== null && + !Array.isArray(sessionSource) && + (Object.hasOwn(sessionSource, "subagent") || Object.hasOwn(sessionSource, "subAgent")) + ) { + return false; + } + } const nested = (payload as Record).cwd; if (typeof nested === "string" && nested.trim().length > 0) { return nested; @@ -554,7 +587,7 @@ function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) { size: Number(stats.size), mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }), device: Number(stats.dev), - inode: Option.match(stats.ino, { onNone: () => null, onSome: Number }), + inode: Option.match(stats.ino, { onNone: () => null, onSome: String }), birthtimeMs: Option.match(stats.birthtime, { onNone: () => null, onSome: (date) => date.getTime(), @@ -562,25 +595,35 @@ function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) { }; } -function sameTranscriptIdentity( - left: ReturnType, - right: ReturnType, -): boolean { +type TranscriptIdentity = Pick< + AgentSessionImportSource, + "filePath" | "size" | "mtimeMs" | "device" | "inode" | "birthtimeMs" +>; + +const fileIdKey = (inode: TranscriptIdentity["inode"]) => (inode === null ? null : String(inode)); + +function sameTranscriptIdentity(left: TranscriptIdentity, right: TranscriptIdentity): boolean { + // Unsafe legacy numbers may already have lost file ID precision. + if ( + (typeof left.inode === "number" && !Number.isSafeInteger(left.inode)) || + (typeof right.inode === "number" && !Number.isSafeInteger(right.inode)) + ) { + return false; + } return ( left.filePath === right.filePath && left.size === right.size && left.mtimeMs === right.mtimeMs && left.device === right.device && - left.inode === right.inode && + fileIdKey(left.inode) === fileIdKey(right.inode) && left.birthtimeMs === right.birthtimeMs ); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - // Different project imports can arrive concurrently from multiple clients. - // Only one transcript may hold its selected-history budget at a time. + // Concurrent client imports must not hold multiple selected-history budgets. const importReadLock = yield* Semaphore.make(1); const path = yield* Path.Path; const serverConfig = yield* ServerConfig.ServerConfig; @@ -635,11 +678,6 @@ export const make = Effect.gen(function* () { return `path:${normalizeProjectPathForComparison(realPath)}`; }); - /** - * When it points into a `worktrees/` directory the checkout is a linked worktree, which - * onboarding skips because its history belongs to the main checkout. Submodules use the same - * pointer shape but live under `modules/`, and are offered like any other repository. - */ const readGitIdentity = Effect.fn("AgentSessionScanner.readGitIdentity")(function* ( directory: string, ): Effect.fn.Return< @@ -658,22 +696,34 @@ export const make = Effect.gen(function* () { const target = /^gitdir:\s*(.+)$/m.exec(pointer)?.[1]?.trim(); if (target === undefined || target.length === 0) return { _tag: "NotGit" } as const; gitDir = path.resolve(directory, target); - if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) return { _tag: "Worktree" } as const; + } + const linkedWorktree = + gitStats.value.type !== "Directory" && /[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir); + if (linkedWorktree) { + const commonDir = yield* fileSystem + .readFileString(path.join(gitDir, "commondir")) + .pipe(Effect.orElseSucceed(() => "")); + if (commonDir.trim().length === 0) return { _tag: "Worktree" } as const; + gitDir = path.resolve(gitDir, commonDir.trim()); } const configText = yield* fileSystem .readFileString(path.join(gitDir, "config")) .pipe(Effect.orElseSucceed(() => "")); + // Bare repositories have no main checkout, so offer their linked worktrees independently. + if (linkedWorktree && !isBareGitConfig(configText)) return { _tag: "Worktree" } as const; const originUrl = parseOriginUrlFromGitConfig(configText); return { _tag: "Repository", git: { - remoteKey: originUrl === null ? null : normalizeGitRemoteUrl(originUrl), - repository: parseGitHubRepositoryNameWithOwnerFromRemoteUrl(originUrl), + remoteKey: + originUrl === null ? null : sourceControlDefinitions.repositoryKeyFromRemote(originUrl), + repository: repositoryPathFromRemoteUrl(originUrl), }, } as const; }); const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* ( + source: AgentSessionSource, transcript: TranscriptCandidate, budget: MetadataReadBudget, ) { @@ -710,7 +760,9 @@ export const make = Effect.gen(function* () { }; const readLastRecord = () => { const record = remaining + decoder.decode(); - return record.length === 0 || !reserveRecord() ? null : extractCwd(record.trim()); + return record.length === 0 || !reserveRecord() + ? null + : extractCwd(record.trim(), source); }; while (bytesRead < maxBytes) { @@ -737,7 +789,7 @@ export const make = Effect.gen(function* () { for (const line of lines) { if (!reserveRecord()) return null; - const cwd = extractCwd(line.trim()); + const cwd = extractCwd(line.trim(), source); if (cwd !== null) return cwd; } } @@ -769,6 +821,8 @@ export const make = Effect.gen(function* () { return null; } const records: Array = []; + let cwd = Option.none(); + let claudeFields = emptyClaudeFields; let historyBytes = 0; let recordBytes = 0; let recordCount = 0; @@ -790,9 +844,15 @@ export const make = Effect.gen(function* () { recordCount += 1; if (recordCount > recordLimit) return false; const decoded = decodeTranscriptValue(reader.finish()); - if (Option.isSome(decoded) && shouldRetainDecodedRecord(source, decoded.value)) { - records.push(decoded.value); - historyBytes += recordBytes; + if (Option.isSome(decoded)) { + if (Option.isNone(cwd)) cwd = Option.fromNullOr(extractDecodedCwd(decoded.value)); + if (source === "claudeAgent") { + claudeFields = foldClaudeFields(claudeFields, decoded.value); + } + if (shouldRetainDecodedRecord(source, decoded.value)) { + records.push(decoded.value); + historyBytes += recordBytes; + } } recordBytes = 0; reader = createTranscriptJsonReader(reserve, selectTranscriptPath); @@ -828,7 +888,7 @@ export const make = Effect.gen(function* () { if (recordStarted && !(yield* Effect.try(finishRecord))) return null; return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat)) - ? { records, recordCount } + ? { records, recordCount, cwd, claudeFields } : null; }), ), @@ -986,8 +1046,8 @@ export const make = Effect.gen(function* () { >(); for (const transcript of transcripts) { - const cwd = yield* readCwd(transcript, budget); - if (cwd === null) continue; + const cwd = yield* readCwd(source, transcript, budget); + if (cwd === null || cwd === false) continue; const key = `${transcript.providerInstanceId}\0${cwd}`; const existing = byOwnerAndCwd.get(key); if (existing) { @@ -1155,8 +1215,7 @@ export const make = Effect.gen(function* () { const realPath = yield* fileSystem .realPath(resolved) .pipe(Effect.orElseSucceed(() => resolved)); - // A symlink can point into the worktrees directory even when its own - // spelling doesn't; check again with links resolved. + // Symlinks can disguise excluded worktree paths; re-check their targets. if (isExcludedProjectPath(realPath)) { key = ""; } else { @@ -1193,8 +1252,7 @@ export const make = Effect.gen(function* () { : Math.max(existing.lastActiveAtMs, candidate.lastActiveAtMs); } - // Resolve persisted roots too. A project and a transcript can name - // different symlinks to the same directory. + // Resolve persisted roots too; transcripts may use different symlinks to the same directory. const importedProjects = yield* projectStore .listShells() .pipe( @@ -1349,15 +1407,10 @@ export const make = Effect.gen(function* () { } recordsRemaining -= snapshot.recordCount; - let snapshotCwd: string | null = null; - for (const record of snapshot.records) { - snapshotCwd = extractDecodedCwd(record); - if (snapshotCwd !== null) break; - } - if (snapshotCwd === null) { + if (Option.isNone(snapshot.cwd)) { return Option.some({ _tag: "Skipped" }); } - const expandedCwd = expandHomePath(snapshotCwd.trim(), homeDir); + const expandedCwd = expandHomePath(snapshot.cwd.value.trim(), homeDir); if ( !path.isAbsolute(expandedCwd) || (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity @@ -1373,6 +1426,7 @@ export const make = Effect.gen(function* () { lastActiveAtMs: transcript.mtimeMs, }, snapshot.records, + snapshot.claudeFields, ); if (parsedThread === null) { return Option.some({ _tag: "Skipped" }); diff --git a/apps/server/src/project/ManagedProjectFolders.test.ts b/apps/server/src/project/ManagedProjectFolders.test.ts index 453cf4431bdc7..86dbcc5beb618 100644 --- a/apps/server/src/project/ManagedProjectFolders.test.ts +++ b/apps/server/src/project/ManagedProjectFolders.test.ts @@ -1,12 +1,6 @@ import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { - CommandId, - GitCommandError, - ProjectId, - ThreadId, - VcsProcessSpawnError, -} from "@t3tools/contracts"; +import { CommandId, ProjectId, ThreadId, VcsProcessSpawnError } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -47,6 +41,7 @@ const layerEnrichment = ProjectEnrichmentService.layer.pipe( resolve: () => Effect.succeed(null), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: () => Effect.succeed(null), }), ), @@ -114,15 +109,6 @@ const requireRoot = Effect.gen(function* () { return Option.getOrThrow(yield* scratch.scratchRoot); }); -it.effect("offers a Scratch folder under the data dir when it is outside a checkout", () => - withScratch(({ baseDir }) => - Effect.gen(function* () { - const path = yield* Path.Path; - assert.equal(yield* requireRoot, path.resolve(baseDir, "scratch")); - }), - ), -); - it.effect("offers nothing when the data dir sits inside a Git checkout", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -134,6 +120,7 @@ it.effect("offers nothing when the data dir sits inside a Git checkout", () => yield* Effect.gen(function* () { const scratch = yield* ManagedProjectFolders.ManagedProjectFolders; assert.isTrue(Option.isNone(yield* scratch.scratchRoot)); + assert.isFalse(yield* scratch.isScratchProject(ProjectId.make("project:any"))); const failure = yield* Effect.flip(scratch.ensureScratchProject); assert.equal(failure._tag, "ScratchUnavailableError"); }).pipe(Effect.provide(layer(baseDir))); @@ -279,7 +266,7 @@ it.effect("leaves threads in other projects alone", () => const projects = yield* ProjectService.ProjectService; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - yield* scratch.ensureScratchProject; + const { projectId: scratchId } = yield* scratch.ensureScratchProject; const other = yield* projects.create({ commandId: CommandId.make("command:other"), projectId: ProjectId.make("project:other"), @@ -295,6 +282,8 @@ it.effect("leaves threads in other projects alone", () => }); assert.isTrue(Option.isNone(folder)); assert.deepEqual(yield* fileSystem.readDirectory(yield* requireRoot), []); + assert.isTrue(yield* scratch.isScratchProject(scratchId)); + assert.isFalse(yield* scratch.isScratchProject(other.id)); }), ), ); @@ -544,36 +533,3 @@ it.effect("removes the folder when the create is cancelled before the project ex ); }), ); - -it.effect("removes the folder when the repository cannot be made", () => - withScratch( - ({ baseDir }) => - Effect.gen(function* () { - const folders = yield* ManagedProjectFolders.ManagedProjectFolders; - const projects = yield* ProjectService.ProjectService; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - - const failure = yield* Effect.flip(folders.createNamedProject({ name: "Broken" })); - - assert.equal(failure._tag, "NamedProjectFolderError"); - assert.equal(failure.message, "Failed to create the project folder."); - assert.deepEqual(yield* fileSystem.readDirectory(path.resolve(baseDir, "projects")), []); - assert.deepEqual((yield* projects.snapshot).projects, []); - }), - { - git: Layer.mock(GitVcsDriver.GitVcsDriver)({ - readConfigValue: () => Effect.succeed(null), - execute: (input) => - Effect.fail( - new GitCommandError({ - operation: input.operation, - command: "git", - cwd: input.cwd, - detail: "git is broken", - }), - ), - }), - }, - ), -); diff --git a/apps/server/src/project/ManagedProjectFolders.ts b/apps/server/src/project/ManagedProjectFolders.ts index 406758cfab41d..1e1fab92562ee 100644 --- a/apps/server/src/project/ManagedProjectFolders.ts +++ b/apps/server/src/project/ManagedProjectFolders.ts @@ -91,16 +91,14 @@ export class ManagedProjectFolders extends Context.Service< { readonly scratchRoot: Effect.Effect>; readonly ensureScratchProject: Effect.Effect<{ readonly projectId: ProjectId }, ScratchError>; + readonly isScratchProject: (projectId: ProjectId) => Effect.Effect; readonly folderForThread: (input: { readonly projectId: ProjectId; readonly threadId: ThreadId; readonly text: string; }) => Effect.Effect, ScratchFolderError>; readonly namedProjectsRoot: string; - /** - * The folder is removed when the create fails or is cancelled before the - * project exists, never once another project owns it. - */ + /** Removes failed/cancelled creations' folders only while no project owns them. */ readonly createNamedProject: (input: { readonly name: string }) => Effect.Effect< { readonly projectId: ProjectId; @@ -150,10 +148,7 @@ function escapeXml(value: string): string { .replaceAll('"', """); } -/** - * It lives at `assets/icon.svg`, a path ProjectFaviconResolver already checks, - * so every machine that clones the project shows the same icon. - */ +// ProjectFaviconResolver finds assets/icon.svg on every clone. function namedProjectIconSvg(name: string): string { const words = name.split(/[^\p{L}\p{N}]+/u).filter(Boolean); const initials = @@ -200,7 +195,6 @@ function describeCommitFailure(stderr: string): string { const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError); -// Spawning a `git` that is not on PATH fails with NotFound, on Windows too. const isGitMissing = (error: GitManagerServiceError) => error._tag === "GitManagerError" && isVcsProcessSpawnError(error.cause) && @@ -216,10 +210,7 @@ const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const crypto = yield* Crypto.Crypto; - /** - * Each folder is created without `recursive`, so creating it is the claim: of - * two racers for one name, one gets AlreadyExists and moves on to the next. - */ + // Non-recursive mkdir atomically claims a name; racers move on after AlreadyExists. const claimFreeFolder = Effect.fnUntraced(function* ( folderFor: (attempt: number) => Effect.Effect, E>, onError: (folder: string, cause: PlatformError.PlatformError) => E, @@ -239,9 +230,7 @@ const make = Effect.gen(function* () { } }); - // Inside a checkout (a dev worktree's .t3, a dotfiles home) the folder would - // inherit the repo's git status and checkpoints, so Scratch is offered only - // when the data dir is outside any work tree. + // Scratch inside a checkout would inherit its git status and checkpoints; require a data dir outside work trees. const [probe, invalidate] = yield* Effect.cachedInvalidateWithTTL( gitWorkflow.isRepository(config.baseDir).pipe( Effect.catchIf(isGitMissing, () => Effect.succeed(false)), @@ -283,8 +272,7 @@ const make = Effect.gen(function* () { workspaceRoot, }) .pipe( - // bootstrap looks the root up before taking the workspace lock, so a - // racing create loses with a conflict that names the winner. + // bootstrap reads before locking; racing creates return the winner in a conflict. Effect.catchTags({ ProjectConflictError: (conflict) => Effect.succeed({ @@ -308,7 +296,7 @@ const make = Effect.gen(function* () { }, ); - const isScratchProject = (projectId: ProjectId, root: string) => + const isScratchRoot = (projectId: ProjectId, root: string) => projects.getById(projectId).pipe( Effect.map( Option.exists((project) => path.resolve(project.workspaceRoot) === path.resolve(root)), @@ -316,12 +304,22 @@ const make = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); + const isScratchProject: ManagedProjectFolders["Service"]["isScratchProject"] = (projectId) => + scratchRoot.pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(false), + onSome: (root) => isScratchRoot(projectId, root), + }), + ), + ); + const folderForThread: ManagedProjectFolders["Service"]["folderForThread"] = Effect.fn( "ManagedProjectFolders.folderForThread", )(function* (input) { const root = yield* scratchRoot; if (Option.isNone(root)) return Option.none(); - if (!(yield* isScratchProject(input.projectId, root.value))) return Option.none(); + if (!(yield* isScratchRoot(input.projectId, root.value))) return Option.none(); const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10); const words = folderWords(input.text); const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, ""); @@ -397,7 +395,7 @@ const make = Effect.gen(function* () { path.join(cwd, "assets", "icon.svg"), namedProjectIconSvg(name), ); - // Named and forced so a global ignore rule (say `*.svg`) cannot drop one. + // Force explicit filenames so global ignore rules cannot drop them. yield* git.execute({ operation: "ManagedProjectFolders.add", cwd, @@ -442,11 +440,7 @@ const make = Effect.gen(function* () { workspaceRoot, }) .pipe( - // A rejected create leaves the folder unused, so remove it. An - // interrupt can land after the create is committed, and a conflict - // means another project owns the folder, so it stays then; the owner - // is checked again first, since deleting another project's files is - // never acceptable. + // Re-check ownership before deleting rejected creations; interruption after commit or conflicts can leave an owner. Effect.tapError((error) => error._tag === "ProjectConflictError" ? Effect.void @@ -467,6 +461,7 @@ const make = Effect.gen(function* () { return ManagedProjectFolders.of({ scratchRoot, ensureScratchProject, + isScratchProject, folderForThread, namedProjectsRoot, createNamedProject, diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index 4dbbb01217527..6a13af9ef9449 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "@effect/vitest"; import { OrchestrationDispatchCommandError, ProjectId, + projectCloneProgressSummary, SourceControlRepositoryError, } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; @@ -105,6 +106,45 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("flags a clone stalled when git goes quiet and clears it when git speaks", () => { + const release = Deferred.makeUnsafe(); + const resumed = Deferred.makeUnsafe(); + const harness = makeHarness({ + clone: (input, options) => + Effect.gen(function* () { + const report = options?.onProgress ?? (() => Effect.void); + yield* report({ stage: "receiving", percent: 24, detail: "168.80 MiB | 20.69 MiB/s" }); + yield* Deferred.await(resumed); + yield* report({ stage: "receiving", percent: 25, detail: "170.00 MiB | 1.00 MiB/s" }); + yield* Deferred.await(release); + return { cwd: input.destinationPath, remoteUrl: input.remoteUrl ?? "", repository: null }; + }), + }); + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + yield* tracker.start(startInput, harness.hooks); + yield* Effect.yieldNow; + expect((yield* tracker.get(projectId))?.stalled).toBe(false); + + yield* TestClock.adjust("19 seconds"); + expect((yield* tracker.get(projectId))?.stalled).toBe(false); + yield* TestClock.adjust("1 second"); + const stalled = yield* tracker.get(projectId); + expect(stalled).toMatchObject({ stalled: true, percent: 24 }); + expect(projectCloneProgressSummary(stalled!)).toBe("Receiving objects · 24% · Stalled"); + + yield* Deferred.succeed(resumed, undefined); + yield* Effect.yieldNow; + expect(yield* tracker.get(projectId)).toMatchObject({ stalled: false, percent: 25 }); + + yield* TestClock.adjust("20 seconds"); + expect((yield* tracker.get(projectId))?.stalled).toBe(true); + yield* Deferred.succeed(release, undefined); + yield* Effect.yieldNow; + expect(yield* tracker.get(projectId)).toMatchObject({ phase: "done", stalled: false }); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("keeps a failed clone with git's own explanation and retries it", () => { let attempts = 0; const harness = makeHarness({ diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index e68ddf78b3fc8..8cad093efff60 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -20,6 +20,7 @@ import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; @@ -43,10 +44,7 @@ export class ProjectCloneTracker extends Context.Service< /** Interrupts a running clone and deletes the partial checkout. */ readonly cancel: (projectId: ProjectId) => Effect.Effect; readonly retry: (projectId: ProjectId) => Effect.Effect; - /** - * Stops tracking a project's clone, interrupting it if it still runs and - * removing an unfinished checkout. - */ + /** Stops tracking, interrupts any running clone and removes unfinished checkouts. */ readonly discard: (projectId: ProjectId) => Effect.Effect; readonly get: (projectId: ProjectId) => Effect.Effect; readonly stream: Stream.Stream>; @@ -67,6 +65,10 @@ export interface ProjectCloneHooks { } const DONE_RETENTION = "30 seconds"; +// Git prints nothing while a transfer waits on the network, and the kernel can +// take 15+ minutes to give up on a dead connection. Without this the banner +// keeps showing the last transfer speed as if data were still arriving. +const STALL_AFTER = "20 seconds"; function clampText(text: string, maxLength: number): string { return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}…`; @@ -86,7 +88,7 @@ interface TrackedClone { }; } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const repositories = yield* SourceControlRepositoryService.SourceControlRepositoryService; const clones = yield* Ref.make(new Map()); @@ -95,8 +97,7 @@ export const make = Effect.gen(function* () { let sequence = 0; const cloneScope = yield* Scope.make("parallel"); yield* Effect.addFinalizer(() => Scope.close(cloneScope, Exit.void)); - // start/cancel/retry/discard mutate the same entry and the same directory; - // one at a time keeps a double-clicked Retry from racing two clones into it. + // Serialize actions on the shared entry and directory so retries cannot race clones. const actionLock = yield* Semaphore.make(1); const locked = (effect: Effect.Effect) => actionLock.withPermits(1)(effect); @@ -133,20 +134,21 @@ export const make = Effect.gen(function* () { return next; }).pipe(Effect.andThen(publish)); - const scheduleRemoval = (projectId: ProjectId) => - Effect.gen(function* () { - yield* clearRetention(projectId); - const fiber = yield* remove(projectId).pipe( - Effect.delay(DONE_RETENTION), - Effect.ensuring( - Effect.sync(() => { - if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId); - }), - ), - Effect.forkDetach, - ); - retentionFibers.set(projectId, fiber); - }); + const scheduleRemoval = Effect.fn("ProjectCloneTracker.scheduleRemoval")(function* ( + projectId: ProjectId, + ) { + yield* clearRetention(projectId); + const fiber = yield* remove(projectId).pipe( + Effect.delay(DONE_RETENTION), + Effect.ensuring( + Effect.sync(() => { + if (retentionFibers.get(projectId) === fiber) retentionFibers.delete(projectId); + }), + ), + Effect.forkDetach, + ); + retentionFibers.set(projectId, fiber); + }); const progress = ( projectId: ProjectId, @@ -164,73 +166,99 @@ export const make = Effect.gen(function* () { percent: update.percent, detail: update.detail === null ? null : clampText(update.detail, PROJECT_CLONE_DETAIL_MAX_LENGTH), + stalled: false, }, })).pipe(Effect.asVoid); - const finish = ( + const markStalled = (projectId: ProjectId) => + modify(projectId, (tracked) => ({ + ...tracked, + snapshot: { ...tracked.snapshot, stalled: true }, + })).pipe(Effect.asVoid); + + /** Marks the clone stalled once, then waits for git to speak again. */ + const watchForStall = (projectId: ProjectId, pulses: Queue.Dequeue) => + Queue.take(pulses).pipe( + Effect.timeoutOption(STALL_AFTER), + Effect.flatMap((pulse) => + Option.isSome(pulse) + ? Effect.void + : markStalled(projectId).pipe(Effect.andThen(Queue.take(pulses))), + ), + Effect.forever, + ); + + const finish = Effect.fn("ProjectCloneTracker.finish")(function* ( projectId: ProjectId, phase: "done" | "failed" | "cancelled", error: string | null, - ) => - Effect.gen(function* () { - const endedAt = yield* nowIso; - yield* modify(projectId, (tracked) => ({ - ...tracked, - fiber: null, - snapshot: { - ...tracked.snapshot, - phase, - endedAt, - percent: phase === "done" ? 100 : tracked.snapshot.percent, - error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH), - }, - })); - if (phase === "done") yield* scheduleRemoval(projectId); - }); + ) { + const endedAt = yield* nowIso; + yield* modify(projectId, (tracked) => ({ + ...tracked, + fiber: null, + snapshot: { + ...tracked.snapshot, + phase, + endedAt, + percent: phase === "done" ? 100 : tracked.snapshot.percent, + stalled: false, + error: error === null ? null : clampText(error, PROJECT_CLONE_ERROR_MAX_LENGTH), + }, + })); + if (phase === "done") yield* scheduleRemoval(projectId); + }); + + const cloneWatchingForStall = Effect.fn("ProjectCloneTracker.cloneWatchingForStall")(function* ( + projectId: ProjectId, + tracked: TrackedClone, + ) { + const pulses = yield* Queue.sliding(1); + yield* watchForStall(projectId, pulses).pipe(Effect.forkScoped); + return yield* repositories.cloneRepository( + { remoteUrl: tracked.input.cloneUrl, destinationPath: tracked.input.destinationPath }, + { + onProgress: (update) => + Queue.offer(pulses, undefined).pipe(Effect.andThen(progress(projectId, update))), + timeoutMs: null, + }, + ); + }, Effect.scoped); /** - * Runs in its own fiber; the tracker records the outcome through `onExit`, - * which still runs when the fiber is interrupted (a `matchCause` handler - * would be skipped). Once git has finished the clone is marked done before - * the post-clone hook runs, so a late Cancel cannot tear down a complete - * checkout. + * `onExit` records outcomes even on interruption; `matchCause` would be skipped. + * Mark the clone done before the post-clone hook so a late Cancel cannot remove it. */ const runClone = (projectId: ProjectId, tracked: TrackedClone) => - repositories - .cloneRepository( - { remoteUrl: tracked.input.cloneUrl, destinationPath: tracked.input.destinationPath }, - { onProgress: (update) => progress(projectId, update), timeoutMs: null }, - ) - .pipe( - Effect.onExit((exit) => - Exit.isSuccess(exit) - ? finish(projectId, "done", null) - : Cause.hasInterruptsOnly(exit.cause) - ? finish(projectId, "cancelled", null) - : finish(projectId, "failed", describeCloneFailure(exit.cause)), - ), - Effect.flatMap(() => - tracked.hooks - .onCloned({ projectId, workspaceRoot: tracked.input.destinationPath }) - .pipe(Effect.ignoreCause({ log: true })), - ), - Effect.ignoreCause(), - ); + cloneWatchingForStall(projectId, tracked).pipe( + Effect.onExit((exit) => + Exit.isSuccess(exit) + ? finish(projectId, "done", null) + : Cause.hasInterruptsOnly(exit.cause) + ? finish(projectId, "cancelled", null) + : finish(projectId, "failed", describeCloneFailure(exit.cause)), + ), + Effect.flatMap(() => + tracked.hooks + .onCloned({ projectId, workspaceRoot: tracked.input.destinationPath }) + .pipe(Effect.ignoreCause({ log: true })), + ), + Effect.ignoreCause(), + ); - const launch = (projectId: ProjectId) => - Effect.gen(function* () { - const current = yield* Ref.get(clones); - const tracked = current.get(projectId); - if (!tracked) return; - const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope)); - yield* Ref.update(clones, (map) => { - const existing = map.get(projectId); - if (!existing) return map; - const next = new Map(map); - next.set(projectId, { ...existing, fiber }); - return next; - }); + const launch = Effect.fn("ProjectCloneTracker.launch")(function* (projectId: ProjectId) { + const current = yield* Ref.get(clones); + const tracked = current.get(projectId); + if (!tracked) return; + const fiber = yield* runClone(projectId, tracked).pipe(Effect.forkIn(cloneScope)); + yield* Ref.update(clones, (map) => { + const existing = map.get(projectId); + if (!existing) return map; + const next = new Map(map); + next.set(projectId, { ...existing, fiber }); + return next; }); + }); const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")( function* (input, hooks) { @@ -245,6 +273,7 @@ export const make = Effect.gen(function* () { stage: "connecting", percent: null, detail: null, + stalled: false, error: null, startedAt, endedAt: null, @@ -277,14 +306,11 @@ export const make = Effect.gen(function* () { detail: "A clone into this destination is already in progress.", }); } - // Everything after the claim runs to completion even if the requesting - // connection drops: a claimed entry with no fiber could neither be - // cancelled nor retried. Any failure in here releases the claim. + // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. yield* Effect.uninterruptible( Effect.gen(function* () { yield* clearRetention(input.projectId); - // The entry is registered before the project exists so a - // thread.create or project.delete racing this call already sees it. + // Register before creation so racing thread.create and project.delete see the clone. yield* hooks.createProject({ projectId: input.projectId, title: input.title, @@ -307,13 +333,12 @@ export const make = Effect.gen(function* () { const get: ProjectCloneTracker["Service"]["get"] = (projectId) => Ref.get(clones).pipe(Effect.map((current) => current.get(projectId)?.snapshot ?? null)); - const cancel: ProjectCloneTracker["Service"]["cancel"] = (projectId) => - Effect.gen(function* () { + const cancel: ProjectCloneTracker["Service"]["cancel"] = Effect.fn("ProjectCloneTracker.cancel")( + function* (projectId) { const current = yield* Ref.get(clones); const tracked = current.get(projectId); if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) return false; - // Uninterruptible past this point: a client that disconnects mid-cancel - // must not leave a dead fiber behind a "running" snapshot. + // Finish cancellation despite disconnects to avoid dead fibers behind running snapshots. yield* Effect.uninterruptible( Effect.gen(function* () { yield* Fiber.interrupt(tracked.fiber!); @@ -324,10 +349,11 @@ export const make = Effect.gen(function* () { }), ); return true; - }); + }, + ); - const retry: ProjectCloneTracker["Service"]["retry"] = (projectId) => - Effect.gen(function* () { + const retry: ProjectCloneTracker["Service"]["retry"] = Effect.fn("ProjectCloneTracker.retry")( + function* (projectId) { const current = yield* Ref.get(clones); const tracked = current.get(projectId); if ( @@ -346,6 +372,7 @@ export const make = Effect.gen(function* () { stage: "connecting", percent: null, detail: null, + stalled: false, error: null, startedAt, endedAt: null, @@ -353,23 +380,25 @@ export const make = Effect.gen(function* () { })); yield* launch(projectId); return true; - }); + }, + ); - const discard: ProjectCloneTracker["Service"]["discard"] = (projectId) => - Effect.gen(function* () { - const current = yield* Ref.get(clones); - const tracked = current.get(projectId); - if (!tracked) return; - if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber); - // Git may have finished while the interrupt was landing; the project - // is going away either way, but a complete checkout is the user's. - const after = yield* get(projectId); - if (after?.phase !== "done") { - yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore); - } - yield* clearRetention(projectId); - yield* remove(projectId); - }); + const discard: ProjectCloneTracker["Service"]["discard"] = Effect.fn( + "ProjectCloneTracker.discard", + )(function* (projectId) { + const current = yield* Ref.get(clones); + const tracked = current.get(projectId); + if (!tracked) return; + if (tracked.fiber) yield* Fiber.interrupt(tracked.fiber); + // Git may have finished while the interrupt was landing; the project + // is going away either way, but a complete checkout is the user's. + const after = yield* get(projectId); + if (after?.phase !== "done") { + yield* repositories.discardClone(tracked.input.destinationPath).pipe(Effect.ignore); + } + yield* clearRetention(projectId); + yield* remove(projectId); + }); const stream: ProjectCloneTracker["Service"]["stream"] = Stream.callback< ReadonlyArray @@ -405,11 +434,15 @@ const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError); * client can start a thread on an empty tree, and no attachment copies are made * for a command that is about to be refused. */ -export const rejectCommandsDuringClone = ( - tracker: ProjectCloneTracker["Service"], - command: { readonly type: string; readonly projectId?: ProjectId; readonly bootstrap?: unknown }, -): Effect.Effect => - Effect.gen(function* () { +export const rejectCommandsDuringClone = Effect.fn("ProjectCloneTracker.rejectCommandsDuringClone")( + function* ( + tracker: ProjectCloneTracker["Service"], + command: { + readonly type: string; + readonly projectId?: ProjectId; + readonly bootstrap?: unknown; + }, + ): Effect.fn.Return { const projectId = command.type === "thread.create" ? (command.projectId ?? null) @@ -425,7 +458,8 @@ export const rejectCommandsDuringClone = ( ? "The repository is still being cloned." : "The repository was not cloned. Retry the clone first.", }); - }); + }, +); function bootstrapProjectId(bootstrap: unknown): ProjectId | null { if (typeof bootstrap !== "object" || bootstrap === null) return null; diff --git a/apps/server/src/project/ProjectEnrichmentService.test.ts b/apps/server/src/project/ProjectEnrichmentService.test.ts index 7a0238159a747..492d1c43419ab 100644 --- a/apps/server/src/project/ProjectEnrichmentService.test.ts +++ b/apps/server/src/project/ProjectEnrichmentService.test.ts @@ -3,12 +3,8 @@ import type { RepositoryIdentity } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Logger from "effect/Logger"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; -import { TestClock } from "effect/testing"; - -import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as ProjectEnrichment from "./ProjectEnrichmentService.ts"; import * as ProjectFaviconResolver from "./ProjectFaviconResolver.ts"; @@ -48,108 +44,6 @@ const layer = ( Layer.provide(metadataLayer), ); -it.effect("preserves either enrichment field when the other resolver fails", () => - Effect.gen(function* () { - const layerMetadata = Layer.merge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (workspaceRoot) => - workspaceRoot === "/repo-fails" - ? Effect.die("repository resolver failed") - : Effect.succeed(identity(workspaceRoot)), - }), - Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { - resolvePath: (workspaceRoot) => - workspaceRoot === "/favicon-fails" - ? Effect.fail( - new ProjectFaviconResolver.ProjectFaviconResolutionError({ - operation: "stat-candidate", - workspaceRoot, - cause: "favicon resolver failed", - }), - ) - : Effect.succeed(`${workspaceRoot}/favicon.svg`), - }), - ); - - yield* Effect.gen(function* () { - const service = yield* ProjectEnrichment.ProjectEnrichmentService; - yield* service.request("/favicon-fails"); - yield* service.request("/repo-fails"); - - const faviconFailure = yield* waitForAvailable( - service, - "/favicon-fails", - (value) => value.repositoryIdentity !== null, - ); - assert.equal( - faviconFailure.repositoryIdentity?.canonicalKey, - "example.test/v1/favicon-fails", - ); - assert.isNull(faviconFailure.faviconPath); - - const repositoryFailure = yield* waitForAvailable( - service, - "/repo-fails", - (value) => value.faviconPath !== null, - ); - assert.isNull(repositoryFailure.repositoryIdentity); - assert.equal(repositoryFailure.faviconPath, "/repo-fails/favicon.svg"); - }).pipe(Effect.provide(layer(layerMetadata))); - }), -); - -it.effect("does not warn about favicons for workspace roots that no longer exist", () => - Effect.gen(function* () { - const warnings: Array = []; - const logger = Logger.make(({ message }) => { - warnings.push(message); - }); - const metadataLayer = Layer.merge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (workspaceRoot) => Effect.succeed(identity(workspaceRoot)), - }), - Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { - resolvePath: (workspaceRoot) => - Effect.fail( - workspaceRoot === "/missing" - ? new ProjectFaviconResolver.ProjectFaviconResolutionError({ - operation: "normalize-workspace", - workspaceRoot, - cause: new WorkspacePaths.WorkspaceRootNotExistsError({ - workspaceRoot, - normalizedWorkspaceRoot: workspaceRoot, - }), - }) - : new ProjectFaviconResolver.ProjectFaviconResolutionError({ - operation: "stat-candidate", - workspaceRoot, - cause: "favicon resolver failed", - }), - ), - }), - ); - - yield* Effect.gen(function* () { - const service = yield* ProjectEnrichment.ProjectEnrichmentService; - yield* service.request("/missing"); - yield* service.request("/broken"); - - for (let attempt = 0; attempt < 100 && warnings.length === 0; attempt += 1) { - yield* Effect.yieldNow; - } - - assert.lengthOf(warnings, 1); - assert.nestedPropertyVal(warnings[0], "[1].workspaceRoot", "/broken"); - }).pipe( - Effect.provide( - layer(metadataLayer, { concurrency: 1 }).pipe( - Layer.provide(Logger.layer([logger], { mergeWithExisting: false })), - ), - ), - ); - }), -); - it.effect("publishes repository completion while favicon enrichment is still pending", () => Effect.gen(function* () { const releaseFavicon = yield* Deferred.make(); @@ -158,6 +52,7 @@ it.effect("publishes repository completion while favicon enrichment is still pen resolve: (workspaceRoot) => Effect.succeed(identity(workspaceRoot)), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: (workspaceRoot) => Deferred.await(releaseFavicon).pipe(Effect.as(`${workspaceRoot}/favicon.svg`)), }), @@ -186,6 +81,7 @@ it.effect("keeps repository workers available when every favicon worker is hung" resolve: (workspaceRoot) => Effect.succeed(identity(workspaceRoot)), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: () => Effect.gen(function* () { const started = yield* Ref.updateAndGet(faviconStarts, (count) => count + 1); @@ -224,45 +120,6 @@ it.effect("keeps repository workers available when every favicon worker is hung" }), ); -it.effect("getAvailable returns immediately while repository identity is still unresolved", () => - Effect.gen(function* () { - const repositoryStarted = yield* Deferred.make(); - const releaseRepository = yield* Deferred.make(); - const layerMetadata = Layer.merge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (workspaceRoot) => - Deferred.succeed(repositoryStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseRepository)), - Effect.as(identity(workspaceRoot)), - ), - }), - Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { - resolvePath: (workspaceRoot) => Effect.succeed(`${workspaceRoot}/favicon.svg`), - }), - ); - - yield* Effect.gen(function* () { - const service = yield* ProjectEnrichment.ProjectEnrichmentService; - - const immediate = yield* service.getAvailable("/pending-identity"); - assert.isNull(immediate.repositoryIdentity); - assert.isNull(immediate.faviconPath); - assert.isFalse(immediate.repositoryIdentityResolved); - - yield* Deferred.await(repositoryStarted); - - yield* Deferred.succeed(releaseRepository, undefined); - const resolved = yield* waitForAvailable( - service, - "/pending-identity", - (value) => value.repositoryIdentity !== null, - ); - assert.equal(resolved.repositoryIdentity?.canonicalKey, "example.test/v1/pending-identity"); - assert.isTrue(resolved.repositoryIdentityResolved); - }).pipe(Effect.provide(layer(layerMetadata))); - }), -); - it.effect( "reports successful cached null as resolved while cold and failed lookups stay unresolved", () => @@ -285,6 +142,7 @@ it.effect( }, }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: () => Effect.succeed(null), }), ); @@ -344,6 +202,7 @@ it.effect("deduplicates requests, bounds pending work, and reloads invalidated r }), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: (workspaceRoot) => Effect.succeed(`${workspaceRoot}/favicon.svg`), }), ); @@ -394,88 +253,3 @@ it.effect("deduplicates requests, bounds pending work, and reloads invalidated r ); }), ); - -it.effect("rescans a favicon only after 15 minutes", () => - Effect.gen(function* () { - const faviconScans = yield* Ref.make(0); - const layerMetadata = Layer.merge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (workspaceRoot) => Effect.succeed(identity(workspaceRoot)), - }), - Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { - resolvePath: (workspaceRoot) => - Ref.updateAndGet(faviconScans, (count) => count + 1).pipe( - Effect.map((scan) => `${workspaceRoot}/favicon-${scan}.svg`), - ), - }), - ); - - yield* Effect.gen(function* () { - const service = yield* ProjectEnrichment.ProjectEnrichmentService; - yield* service.getAvailable("/repo"); - yield* waitForAvailable( - service, - "/repo", - (value) => value.faviconPath === "/repo/favicon-1.svg", - ); - - for (let minute = 1; minute < 15; minute += 1) { - yield* TestClock.adjust("1 minute"); - yield* service.getAvailable("/repo"); - } - assert.equal(yield* Ref.get(faviconScans), 1); - - yield* TestClock.adjust("1 minute"); - yield* service.getAvailable("/repo"); - yield* waitForAvailable( - service, - "/repo", - (value) => value.faviconPath === "/repo/favicon-2.svg", - ); - assert.equal(yield* Ref.get(faviconScans), 2); - }).pipe(Effect.provide(layer(layerMetadata))); - }), -); - -it.effect( - "follows repository identity changes within a minute without rescanning the favicon", - () => - Effect.gen(function* () { - const remoteVersion = yield* Ref.make(0); - const faviconScans = yield* Ref.make(0); - const layerMetadata = Layer.merge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (workspaceRoot) => - Ref.get(remoteVersion).pipe( - Effect.map((version) => (version === 0 ? null : identity(workspaceRoot, version))), - ), - }), - Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { - resolvePath: () => Ref.update(faviconScans, (count) => count + 1).pipe(Effect.as(null)), - }), - ); - - yield* Effect.gen(function* () { - const service = yield* ProjectEnrichment.ProjectEnrichmentService; - yield* service.getAvailable("/folder"); - yield* waitForAvailable(service, "/folder", (value) => value.repositoryIdentityResolved); - assert.equal((yield* service.peek("/folder")).repositoryIdentity, null); - - for (const version of [1, 2]) { - yield* Ref.set(remoteVersion, version); - yield* TestClock.adjust("1 minute"); - yield* service.getAvailable("/folder"); - const available = yield* waitForAvailable( - service, - "/folder", - (value) => value.repositoryIdentity?.canonicalKey === `example.test/v${version}/folder`, - ); - assert.equal( - available.repositoryIdentity?.canonicalKey, - `example.test/v${version}/folder`, - ); - } - assert.equal(yield* Ref.get(faviconScans), 1); - }).pipe(Effect.provide(layer(layerMetadata))); - }), -); diff --git a/apps/server/src/project/ProjectEnrichmentService.ts b/apps/server/src/project/ProjectEnrichmentService.ts index efb510e37ef2b..cbee7275b123f 100644 --- a/apps/server/src/project/ProjectEnrichmentService.ts +++ b/apps/server/src/project/ProjectEnrichmentService.ts @@ -19,9 +19,7 @@ const DEFAULT_CACHE_CAPACITY = 512; const DEFAULT_MAX_PENDING = 512; const DEFAULT_CONCURRENCY = 4; const DEFAULT_SUCCESS_TTL = Duration.minutes(1); -// A favicon scan checks about 20 files. Shell reads (and PR sync through them) ask for every -// linked project about once a minute, and icons rarely change, so a resolved favicon is kept -// longer than the identity, which is only a hit on RepositoryIdentityResolver's own cache. +// Frequent shell reads scan ~20 files per project; icons change rarely, so cache longer than identities. const DEFAULT_FAVICON_TTL = Duration.minutes(15); const DEFAULT_FAILURE_TTL = Duration.seconds(5); @@ -283,6 +281,8 @@ export const make = Effect.fn("ProjectEnrichmentService.make")(function* ( [ Cache.invalidate(repositoryIdentityCache, workspaceRoot), Cache.invalidate(faviconCache, workspaceRoot), + // The resolver keeps its own misses, which would outlive a clone filling the folder. + faviconResolver.invalidate(workspaceRoot), ], { concurrency: "unbounded", discard: true }, ), diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 1d5bf9441d0da..5877662f46bc7 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -1,11 +1,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, describe, expect } from "@effect/vitest"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; import { TestClock } from "effect/testing"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; @@ -51,27 +49,20 @@ const makeResolverWithFileSystem = (fileSystem: FileSystem.FileSystem) => it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { describe("resolvePath", () => { - it.effect("serves repeated resolves from cache instead of re-walking candidates", () => + it.effect("finds a favicon added after a cached miss once the workspace is invalidated", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; const path = yield* Path.Path; const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "public/favicon.svg", "public"); - const resolved = yield* resolver.resolvePath(cwd); - expect(resolved?.endsWith(path.join("public", "favicon.svg"))).toBe(true); - - yield* writeTextFile(cwd, "favicon.svg", "root"); - - for (const _attempt of [1, 2, 3]) { - expect(yield* resolver.resolvePath(cwd)).toBe(resolved); - } - - yield* TestClock.adjust(Duration.minutes(11)); + // A clone's project exists while its folder is still empty. + expect(yield* resolver.resolvePath(cwd)).toBeNull(); + yield* writeTextFile(cwd, "favicon.ico", "icon"); + expect(yield* resolver.resolvePath(cwd)).toBeNull(); - expect(yield* resolver.resolvePath(cwd)).toBe(path.join(cwd, "favicon.svg")); - expect(yield* resolver.resolvePath(cwd)).not.toBe(resolved); - }).pipe(Effect.provide(TestClock.layer())), + yield* resolver.invalidate(cwd); + expect(yield* resolver.resolvePath(cwd)).toBe(path.join(cwd, "favicon.ico")); + }), ); it.effect("falls back at once when a cached favicon is deleted", () => @@ -90,35 +81,6 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }).pipe(Effect.provide(TestClock.layer())), ); - it.effect("re-probes for a favicon added after a miss once the negative TTL expires", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - - expect(yield* resolver.resolvePath(cwd)).toBeNull(); - - yield* writeTextFile(cwd, "favicon.svg", "favicon"); - expect(yield* resolver.resolvePath(cwd)).toBeNull(); - - yield* TestClock.adjust(Duration.minutes(2)); - - expect(yield* resolver.resolvePath(cwd)).not.toBeNull(); - }).pipe(Effect.provide(TestClock.layer())), - ); - - it.effect("prefers well-known favicon files", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "favicon.svg", "favicon"); - - const resolved = yield* resolver.resolvePath(cwd); - - expect(resolved).not.toBeNull(); - expect(resolved).toContain("favicon.svg"); - }), - ); - it.effect("prefers a t3.json iconPath over well-known files", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; @@ -178,20 +140,6 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }), ); - it.effect("falls back to well-known files when the t3.json iconPath does not exist", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "t3.json", '{ "iconPath": "brand/missing.svg" }'); - yield* writeTextFile(cwd, "favicon.svg", "favicon"); - - const resolved = yield* resolver.resolvePath(cwd); - - expect(resolved).not.toBeNull(); - expect(resolved).toContain("favicon.svg"); - }), - ); - it.effect("ignores invalid t3.json files", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; @@ -259,42 +207,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }), ); - it.effect("resolves object-literal icon metadata when href precedes rel", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - yield* writeTextFile( - cwd, - "src/root.tsx", - `const links = [{ href: "/brand/logo.svg", rel: "shortcut icon" }];`, - ); - yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); - - const resolved = yield* resolver.resolvePath(cwd); - - expect(resolved).not.toBeNull(); - expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); - }), - ); - - it.effect("resolves object-literal icon metadata alongside nested objects", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - yield* writeTextFile( - cwd, - "src/root.tsx", - `const links = [{ attributes: {}, rel: "icon", href: "/brand/logo.svg" }];`, - ); - yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); - - const resolved = yield* resolver.resolvePath(cwd); - - expect(resolved).not.toBeNull(); - expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); - }), - ); - + // regression: #5538 favicon resolution pinned the event loop it.effect("skips icon metadata without an href and keeps scanning", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; @@ -313,110 +226,6 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }), ); - it.effect("scans large icon sources without an icon in reasonable time", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - const filler = `

${"pokopia companion guide ".repeat(24)}

\n`; - yield* writeTextFile( - cwd, - "index.html", - `guide\n${filler.repeat(1200)}`, - ); - - const startedAt = performance.now(); - const resolved = yield* resolver.resolvePath(cwd); - const elapsedMs = performance.now() - startedAt; - - expect(resolved).toBeNull(); - expect(elapsedMs).toBeLessThan(5_000); - }), - ); - - it.effect("returns null when no icon is present", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - - const resolved = yield* resolver.resolvePath(cwd); - - expect(resolved).toBeNull(); - }), - ); - - it.effect("preserves workspace normalization context", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - const missingCwd = `${cwd}/missing`; - - const error = yield* resolver.resolvePath(missingCwd).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "ProjectFaviconResolutionError", - operation: "normalize-workspace", - workspaceRoot: missingCwd, - }); - expect(error.cause).toBeInstanceOf(WorkspacePaths.WorkspaceRootNotExistsError); - }), - ); - - it.effect("preserves non-missing candidate stat failures", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* makeTempDir; - const faviconPath = path.join(cwd, "favicon.svg"); - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "stat", - pathOrDescriptor: faviconPath, - }); - const resolver = yield* makeResolverWithFileSystem( - FileSystem.FileSystem.of({ - ...fileSystem, - stat: (filePath) => - filePath === faviconPath ? Effect.fail(cause) : fileSystem.stat(filePath), - }), - ); - - const error = yield* resolver.resolvePath(cwd).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "ProjectFaviconResolutionError", - operation: "stat-candidate", - workspaceRoot: cwd, - relativePath: "favicon.svg", - absolutePath: faviconPath, - }); - expect(error.cause).toBe(cause); - }), - ); - - it.effect("probes well-known candidates concurrently", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* makeTempDir; - let inFlight = 0; - let peakInFlight = 0; - const resolver = yield* makeResolverWithFileSystem( - FileSystem.FileSystem.of({ - ...fileSystem, - stat: (filePath) => - Effect.suspend(() => { - inFlight += 1; - peakInFlight = Math.max(peakInFlight, inFlight); - return Effect.yieldNow.pipe(Effect.andThen(fileSystem.stat(filePath))); - }).pipe(Effect.ensuring(Effect.sync(() => (inFlight -= 1)))), - }), - ); - - expect(yield* resolver.resolvePath(cwd)).toBeNull(); - expect(peakInFlight).toBeGreaterThan(1); - }), - ); - it.effect("returns a found favicon without waiting for lower-ranked probes", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -435,70 +244,6 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { }), ); - it.effect("ignores a failing candidate that ranks below a found favicon", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "favicon.svg", "root"); - const failingPath = path.join(cwd, "favicon.ico"); - const resolver = yield* makeResolverWithFileSystem( - FileSystem.FileSystem.of({ - ...fileSystem, - stat: (filePath) => - filePath === failingPath - ? Effect.fail( - PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "stat", - pathOrDescriptor: failingPath, - }), - ) - : fileSystem.stat(filePath), - }), - ); - - expect(yield* resolver.resolvePath(cwd)).toBe(path.join(cwd, "favicon.svg")); - }), - ); - - it.effect("preserves icon source read failures", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* makeTempDir; - const sourcePath = path.join(cwd, "index.html"); - yield* writeTextFile(cwd, "index.html", ''); - const cause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFileString", - pathOrDescriptor: sourcePath, - }); - const resolver = yield* makeResolverWithFileSystem( - FileSystem.FileSystem.of({ - ...fileSystem, - readFileString: (filePath, options) => - filePath === sourcePath - ? Effect.fail(cause) - : fileSystem.readFileString(filePath, options), - }), - ); - - const error = yield* resolver.resolvePath(cwd).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "ProjectFaviconResolutionError", - operation: "read-source", - workspaceRoot: cwd, - relativePath: "index.html", - absolutePath: sourcePath, - }); - expect(error.cause).toBe(cause); - }), - ); - it.effect("skips icon metadata paths outside the workspace", () => Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; @@ -510,20 +255,5 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(resolved).toBeNull(); }), ); - - it.effect("continues to later sources after an outside-root icon href", () => - Effect.gen(function* () { - const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; - const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "index.html", ''); - yield* writeTextFile(cwd, "public/index.html", ''); - yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); - - const resolved = yield* resolver.resolvePath(cwd); - - expect(resolved).not.toBeNull(); - expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); - }), - ); }); }); diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 75dc4e661ef6b..dfae0d5fbe1b5 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -71,9 +71,7 @@ const ICON_SOURCE_FILES = [ "src/index.html", ] as const; -// The tag pattern is anchored on `]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; const ICON_REL_RE = /\brel\s*:\s*["'](?:icon|shortcut icon)["']/i; @@ -111,6 +109,8 @@ export class ProjectFaviconResolver extends Context.Service< cwd: string, faviconPath?: string, ) => Effect.Effect; + /** Forgets cached lookups for a workspace whose files changed, such as a finished clone. */ + readonly invalidate: (cwd: string) => Effect.Effect; } >()("t3/project/ProjectFaviconResolver") {} @@ -233,25 +233,21 @@ export const make = Effect.gen(function* () { return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace"); }); - // Starts every probe at once and returns the first hit in list order. A miss - // costs one round of filesystem latency instead of one per probe, which - // matters when the disk is slow. Fibers are joined in order, so a hit returns - // without waiting for lower-ranked probes (the scope interrupts them), and a - // failure surfaces only when no earlier probe found a file. - const firstInOrder =
( + // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit. + // A failure surfaces only if no earlier probe found a file; scope exit interrupts remaining probes. + const firstInOrder = Effect.fn("ProjectFaviconResolver.firstInOrder")(function* ( items: ReadonlyArray, probe: (item: A) => Effect.Effect, - ) => - Effect.gen(function* () { - const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item))); - for (const fiber of fibers) { - const found = yield* Fiber.join(fiber); - if (found) { - return found; - } + ) { + const fibers = yield* Effect.forEach(items, (item) => Effect.forkScoped(probe(item))); + for (const fiber of fibers) { + const found = yield* Fiber.join(fiber); + if (found) { + return found; } - return null; - }).pipe(Effect.scoped); + } + return null; + }, Effect.scoped); const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* ( cwd: string, @@ -341,7 +337,18 @@ export const make = Effect.gen(function* () { return yield* Cache.get(faviconCache, key); }); - return ProjectFaviconResolver.of({ resolvePath }); + const invalidate: ProjectFaviconResolver["Service"]["invalidate"] = (cwd) => + Cache.keys(faviconCache).pipe( + Effect.flatMap((keys) => + Effect.forEach( + Array.from(keys).filter((key) => parseFaviconCacheKey(key).cwd === cwd), + (key) => Cache.invalidate(faviconCache, key), + { discard: true }, + ), + ), + ); + + return ProjectFaviconResolver.of({ resolvePath, invalidate }); }); export const layer = Layer.effect(ProjectFaviconResolver, make); diff --git a/apps/server/src/project/ProjectMutation.test.ts b/apps/server/src/project/ProjectMutation.test.ts deleted file mode 100644 index c2f9ee1a89b1b..0000000000000 --- a/apps/server/src/project/ProjectMutation.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { assert, it } from "@effect/vitest"; -import { CommandId, ProjectId, type Project } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; -import * as Ref from "effect/Ref"; - -import { projectMutationOperation } from "./ProjectMutation.ts"; -import { type ProjectService } from "./ProjectService.ts"; - -const projectId = ProjectId.make("project:mutation-mapping"); -const project = { - id: projectId, - title: "Mapping", - workspaceRoot: "/work/mapping", - repositoryIdentity: null, - faviconPath: null, - projectIcon: null, - defaultModelSelection: null, - defaultThreadEnvMode: null, - autoPull: false, - scripts: [], - createdAt: "2026-09-05T00:00:00.000Z", - updatedAt: "2026-09-05T00:00:00.000Z", - deletedAt: null, -} satisfies Project; - -it.effect("preserves every project mutation field", () => - Effect.gen(function* () { - const calls = yield* Ref.make>([]); - const projects: Pick = { - create: (input) => - Ref.update(calls, (entries) => [...entries, input]).pipe(Effect.as(project)), - update: (input) => - Ref.update(calls, (entries) => [...entries, input]).pipe(Effect.as(project)), - delete: (input) => - Ref.update(calls, (entries) => [...entries, input]).pipe(Effect.as(project)), - }; - - yield* projectMutationOperation(projects, { - type: "project.create", - commandId: CommandId.make("command:create"), - projectId, - title: "Created", - workspaceRoot: "/work/created", - createWorkspaceRootIfMissing: true, - defaultModelSelection: null, - scripts: [], - }); - yield* projectMutationOperation(projects, { - type: "project.update", - commandId: CommandId.make("command:update"), - projectId, - title: "Updated", - workspaceRoot: "/work/updated", - defaultModelSelection: null, - autoPull: false, - projectIcon: null, - faviconPath: null, - defaultThreadEnvMode: null, - scripts: [], - }); - yield* projectMutationOperation(projects, { - type: "project.delete", - commandId: CommandId.make("command:delete"), - projectId, - force: true, - }); - - assert.deepEqual(yield* Ref.get(calls), [ - { - commandId: "command:create", - projectId, - title: "Created", - workspaceRoot: "/work/created", - createWorkspaceRootIfMissing: true, - defaultModelSelection: null, - scripts: [], - }, - { - commandId: "command:update", - projectId, - title: "Updated", - workspaceRoot: "/work/updated", - defaultModelSelection: null, - autoPull: false, - projectIcon: null, - faviconPath: null, - defaultThreadEnvMode: null, - scripts: [], - }, - { commandId: "command:delete", projectId, force: true }, - ]); - }), -); diff --git a/apps/server/src/project/ProjectService.deletion.test.ts b/apps/server/src/project/ProjectService.deletion.test.ts index a35e58224baa2..41804842d5205 100644 --- a/apps/server/src/project/ProjectService.deletion.test.ts +++ b/apps/server/src/project/ProjectService.deletion.test.ts @@ -58,6 +58,7 @@ const layerServices = Layer.mergeAll( resolve: () => Effect.succeed(null), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: () => Effect.succeed(null), }), ), @@ -203,6 +204,7 @@ it.effect("retries a partial project deletion without repeating child events or partialCleanup.map((effect) => [effect.thread_id, effect.effect_type]), [ [firstThreadId, "preview.cleanup"], + [firstThreadId, "scheduled-tasks.cleanup"], [firstThreadId, "terminal.cleanup"], ], ); @@ -226,7 +228,7 @@ it.effect("retries a partial project deletion without repeating child events or assert.deepEqual(finalEvents[0], partialEvents[0]); assert.equal(finalEvents[2]?.command_id, commandId); const finalCleanup = yield* readCleanup; - assert.lengthOf(finalCleanup, 4); + assert.lengthOf(finalCleanup, 6); assert.deepEqual( finalCleanup.filter((effect) => effect.thread_id === firstThreadId), partialCleanup, @@ -242,6 +244,12 @@ it.effect("retries a partial project deletion without repeating child events or command_id: expectedCommandId, effect_type: "preview.cleanup", }, + { + effect_id: `effect:${expectedCommandId}:scheduled-tasks.cleanup`, + thread_id: threadId, + command_id: expectedCommandId, + effect_type: "scheduled-tasks.cleanup", + }, { effect_id: `effect:${expectedCommandId}:terminal.cleanup`, thread_id: threadId, diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 67e76bfeafbc8..9347acef12c8f 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -46,6 +46,7 @@ const layerMetadata = Layer.merge( }), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: (workspaceRoot) => Effect.succeed(`${workspaceRoot}/favicon.svg`), }), ); @@ -202,28 +203,6 @@ it.layer(layerTest)("ProjectService", (it) => { }), ); - it.effect("rejects active workspace collisions", () => - Effect.gen(function* () { - const service = yield* ProjectService.ProjectService; - yield* TestClock.setTime(Date.parse("2026-06-20T10:00:00.000Z")); - yield* service.create({ - commandId: CommandId.make("command:collision:first"), - projectId: ProjectId.make("project:collision:first"), - title: "First", - workspaceRoot: "/work/shared", - }); - const error = yield* service - .create({ - commandId: CommandId.make("command:collision:second"), - projectId: ProjectId.make("project:collision:second"), - title: "Second", - workspaceRoot: "/work/shared", - }) - .pipe(Effect.flip); - assert.equal(error._tag, "ProjectConflictError"); - }), - ); - it.effect("auto-bootstraps a workspace exactly once", () => Effect.gen(function* () { const service = yield* ProjectService.ProjectService; @@ -485,111 +464,6 @@ it.layer(layerTest)("ProjectService", (it) => { ); }); -it.effect( - "returns project mutations before slow enrichment and shares the eventual result across reads", - () => - Effect.gen(function* () { - const repositoryStarted = yield* Deferred.make(); - const releaseRepository = yield* Deferred.make(); - const repositoryCalls = yield* Ref.make(0); - const faviconCalls = yield* Ref.make(0); - - const layerSlowMetadata = Layer.merge( - Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, { - resolve: (workspaceRoot) => - Effect.gen(function* () { - yield* Ref.update(repositoryCalls, (count) => count + 1); - yield* Deferred.succeed(repositoryStarted, undefined); - yield* Deferred.await(releaseRepository); - return { - canonicalKey: "github.com/t3tools/slow-project", - locator: { - source: "git-remote" as const, - remoteName: "origin", - remoteUrl: "git@github.com:t3tools/slow-project.git", - }, - rootPath: workspaceRoot, - }; - }), - }), - Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { - resolvePath: (workspaceRoot) => - Ref.updateAndGet(faviconCalls, (count) => count + 1).pipe( - Effect.as(`${workspaceRoot}/favicon.svg`), - ), - }), - ); - - yield* Effect.gen(function* () { - const service = yield* ProjectService.ProjectService; - const projectId = ProjectId.make("project:slow-enrichment"); - const createFiber = yield* service - .create({ - commandId: CommandId.make("command:slow-enrichment:create"), - projectId, - title: "Slow enrichment", - workspaceRoot: "/work/slow-enrichment", - }) - .pipe(Effect.forkChild({ startImmediately: true })); - - yield* Deferred.await(repositoryStarted); - yield* Effect.yieldNow; - assert.isDefined(createFiber.pollUnsafe()); - - const created = yield* Fiber.join(createFiber); - assert.isNull(created.repositoryIdentity); - assert.isNull(created.faviconPath); - - const updated = yield* service.update({ - commandId: CommandId.make("command:slow-enrichment:update"), - projectId, - title: "Updated before enrichment", - }); - assert.equal(updated.title, "Updated before enrichment"); - assert.isNull(updated.repositoryIdentity); - assert.equal(updated.faviconPath, "/work/slow-enrichment/favicon.svg"); - - const immediateReadFiber = yield* service - .getById(projectId) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Effect.yieldNow; - assert.isDefined(immediateReadFiber.pollUnsafe()); - const immediateRead = Option.getOrThrow(yield* Fiber.join(immediateReadFiber)); - assert.isNull(immediateRead.repositoryIdentity); - assert.equal(immediateRead.faviconPath, "/work/slow-enrichment/favicon.svg"); - - const snapshotFiber = yield* service.snapshot.pipe( - Effect.forkChild({ startImmediately: true }), - ); - yield* Effect.yieldNow; - assert.isDefined(snapshotFiber.pollUnsafe()); - const immediateSnapshot = yield* Fiber.join(snapshotFiber); - assert.isNull(immediateSnapshot.projects[0]?.repositoryIdentity ?? null); - - yield* Deferred.succeed(releaseRepository, undefined); - - const firstProject = yield* waitForProject( - service, - projectId, - (project) => project.repositoryIdentity !== null && project.faviconPath !== null, - ); - assert.isDefined(firstProject); - assert.equal( - firstProject.repositoryIdentity?.canonicalKey, - "github.com/t3tools/slow-project", - ); - assert.equal(firstProject.faviconPath, "/work/slow-enrichment/favicon.svg"); - - const byId = Option.getOrThrow(yield* service.getById(projectId)); - const secondSnapshot = yield* service.snapshot; - assert.equal(byId.repositoryIdentity?.canonicalKey, "github.com/t3tools/slow-project"); - assert.equal(secondSnapshot.projects[0]?.faviconPath, "/work/slow-enrichment/favicon.svg"); - assert.equal(yield* Ref.get(repositoryCalls), 1); - assert.equal(yield* Ref.get(faviconCalls), 1); - }).pipe(Effect.provide(layerTestFor(layerSlowMetadata))); - }), -); - it.effect("keeps project snapshots available when optional metadata enrichment fails", () => Effect.gen(function* () { const layerFailingMetadata = Layer.merge( @@ -597,6 +471,7 @@ it.effect("keeps project snapshots available when optional metadata enrichment f resolve: () => Effect.succeed(null), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: (workspaceRoot) => Effect.fail( new ProjectFaviconResolver.ProjectFaviconResolutionError({ @@ -647,6 +522,7 @@ it.effect("invalidates workspace-derived metadata when a project moves", () => ), }), Layer.succeed(ProjectFaviconResolver.ProjectFaviconResolver, { + invalidate: () => Effect.void, resolvePath: (workspaceRoot) => Ref.get(metadataVersion).pipe( Effect.map((version) => `${workspaceRoot}/favicon-v${version}.svg`), diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 1cfb2e093340b..b2c65dd17ae11 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -266,8 +266,7 @@ export const make = Effect.gen(function* () { `Command ${command.commandId} was already used by ${receipt.commandType} for ${receipt.projectId}.`, ); } - // A retried command re-plans against the state it already produced, so its - // first receipt, not the new plan, decides the outcome. + // Retries re-plan against their own effects; the first receipt determines the outcome. if (receipt.status === "accepted") return; const rejection = Option.getOrUndefined(decodeProjectCommandRejection(receipt.error)); switch (rejection?._tag) { @@ -474,11 +473,7 @@ export const make = Effect.gen(function* () { ); }); - // A machine-disabled provider instance that a deleted project's override - // once turned on must not stay probed and alive forever. Nothing else - // removes the entry, so deletion is where it goes; best-effort because a - // settings write failure should not block the deletion it is cleaning up - // after, and a server crash before a replay never revisits this project. + // Best-effort cleanup releases disabled instances kept alive by overrides; crashes have no replay to revisit deletion. const clearProjectSettingsOverrides = (projectId: ProjectId) => serverSettings.updateSettings({ projectSettingsOverrides: { [projectId]: null } }).pipe( Effect.asVoid, @@ -493,8 +488,7 @@ export const make = Effect.gen(function* () { const deleteProject: ProjectService["Service"]["delete"] = Effect.fn("ProjectService.delete")( function* (input) { const { projectId } = input; - // A deleted row still reaches commit, so a retried command id replays its - // receipt and any other command id is rejected as not found. + // Read deleted rows so retries replay receipts and other command ids fail as not found. const existing = yield* readRow(projectId, { includeDeleted: true }); if (Option.isNone(existing)) { return yield* new ProjectNotFoundError({ projectId }); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/ProjectSetupScriptRunner.test.ts index 8516c27941777..c295a06ac39ac 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.test.ts @@ -1,179 +1,168 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { assert, it, vi } from "@effect/vitest"; -import { ProjectId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import { ProjectId, type TerminalEvent, type TerminalSessionSnapshot } from "@t3tools/contracts"; +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 Queue from "effect/Queue"; +import { TestClock } from "effect/testing"; -import * as TerminalManager from "../terminal/Manager.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as TerminalManager from "../terminal/Manager.ts"; import * as ProjectService from "./ProjectService.ts"; import * as ProjectSetupScriptRunner from "./ProjectSetupScriptRunner.ts"; -it.effect("resolves setup scripts through the standalone project service", () => { - const open = vi.fn((input: Parameters[0]) => - Effect.succeed({ - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - worktreePath: input.worktreePath ?? null, - status: "running" as const, - pid: 123, - history: "", - exitCode: null, - exitSignal: null, - label: "Shell", - updatedAt: "2026-06-20T00:00:00.000Z", - }), - ); - const write = vi.fn( - (_input: Parameters[0]) => Effect.void, - ); - const closeIdle = vi.fn( - (_input: Parameters[0]) => Effect.void, - ); - const listeners: Array[0]> = - []; - const subscribe: TerminalManager.TerminalManager["Service"]["subscribe"] = (listener) => - Effect.sync(() => { - listeners.push(listener); - return () => undefined; - }); - const projectId = ProjectId.make("project:setup-runner-v2"); - const project = { - id: projectId, - title: "Project", - workspaceRoot: "/repo", - repositoryIdentity: null, - faviconPath: null, - defaultModelSelection: null, - scripts: [ - { - id: "setup", - name: "Setup", - command: "vp install", - icon: "configure" as const, - runOnWorktreeCreate: true, - }, - { - id: "clean", - name: "Clean", - command: "cargo clean", - icon: "build" as const, - runOnWorktreeCreate: false, - runOnSettle: true, - }, - ], - createdAt: "2026-06-20T00:00:00.000Z", - updatedAt: "2026-06-20T00:00:00.000Z", - deletedAt: null, - }; - const layer = ProjectSetupScriptRunner.layer.pipe( - Layer.provide( +const threadId = "thread-1"; +const terminalId = "setup-setup"; +const event = { threadId, terminalId, sequence: 1, createdAt: "2026-01-01T00:00:00.000Z" }; + +const openSnapshot = (history: string): TerminalSessionSnapshot => ({ + threadId, + terminalId, + cwd: "/repo/.t3/worktrees/feature", + worktreePath: null, + status: "running", + pid: 123, + history, + exitCode: null, + exitSignal: null, + label: "zsh", + updatedAt: "2026-01-01T00:00:00.000Z", +}); + +const makeHarness = Effect.fn(function* (options: { + readonly history?: string; + readonly opening?: Deferred.Deferred; +}) { + const listeners = new Set<(event: TerminalEvent) => Effect.Effect>(); + const writes = yield* Queue.unbounded(); + const outputLines = yield* Queue.unbounded(); + const terminals = Layer.mock(TerminalManager.TerminalManager)({ + open: () => + (options.opening + ? Deferred.succeed(options.opening, undefined).pipe(Effect.andThen(Effect.never)) + : Effect.void + ).pipe(Effect.as(openSnapshot(options.history ?? ""))), + subscribe: (listener) => + Effect.sync(() => { + listeners.add(listener); + return () => listeners.delete(listener); + }), + write: (input) => Queue.offer(writes, input.data).pipe(Effect.asVoid), + closeIdle: () => Effect.void, + }); + const runner = yield* ProjectSetupScriptRunner.make.pipe( + Effect.provide( Layer.mergeAll( - Layer.mock(ProjectService.ProjectService)({ - getById: () => Effect.succeed(Option.some(project)), - }), - Layer.mock(TerminalManager.TerminalManager)({ open, write, subscribe, closeIdle }), + terminals, + Layer.mock(ProjectService.ProjectService)({}), ServerSettings.layerTest(), NodeCrypto.layer, ), ), + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, { SHELL: "/bin/zsh" }), ); + const start = runner.runForThread({ + threadId, + worktreePath: "/repo/.t3/worktrees/feature", + observeCompletion: { onOutputLine: (line) => Queue.offer(outputLines, line) }, + project: { + id: ProjectId.make("project-1"), + workspaceRoot: "/repo", + scripts: [ + { + id: "setup", + name: "Setup", + command: "vp i", + icon: "configure", + runOnWorktreeCreate: true, + }, + ], + }, + }); + const emit = (terminalEvent: TerminalEvent) => + Effect.forEach([...listeners], (listener) => listener(terminalEvent), { discard: true }); + return { start, listeners, writes, outputLines, emit }; +}); + +const setup = Effect.fn(function* (options: { readonly history?: string } = {}) { + const harness = yield* makeHarness(options); + const result = yield* harness.start; + const completion = result.status === "started" ? result.completion : undefined; + if (!completion) return yield* Effect.die("setup did not start an observed run"); + return { ...harness, result, completion }; +}); - return Effect.gen(function* () { - const runner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner; - const result = yield* runner.runForThread({ - threadId: "thread-1", - projectId, - worktreePath: "/repo-worktree", - }); - assert.deepEqual(result, { - status: "started", - async: true, - scriptId: "setup", - scriptName: "Setup", - scriptCommand: "vp install", - terminalId: "setup-setup", - cwd: "/repo-worktree", - }); - assert.equal(open.mock.calls[0]?.[0].cwd, "/repo-worktree"); - assert.deepEqual(open.mock.calls[0]?.[0].env, { - T3CODE_PROJECT_ROOT: "/repo", - T3CODE_WORKTREE_PATH: "/repo-worktree", - COLORTERM: "", - NO_COLOR: "1", - FORCE_COLOR: "0", - }); - assert.equal(write.mock.calls[0]?.[0].data, "vp install\r"); - const lines: string[] = []; - const observed = yield* runner.runForThread({ - threadId: "thread-1", - projectId, - worktreePath: "/repo-worktree", - observeCompletion: { - onOutputLine: (line) => - Effect.sync(() => { - lines.push(line); - }), - }, - }); - assert.equal(observed.status, "started"); - const listener = listeners[0]!; - yield* listener({ - type: "output", - threadId: "thread-1", - terminalId: "setup-setup", - data: "Downloading 10%\rDownloading 20%\r\nDone\n", - }); - assert.deepEqual(lines, ["Downloading 10%", "Downloading 20%", "Done"]); - yield* listener({ type: "closed", threadId: "thread-1", terminalId: "setup-setup" }); +describe("ProjectSetupScriptRunner", () => { + it.effect("shows a startup prompt and types only once the line editor starts", () => + Effect.gen(function* () { + const { result, writes, outputLines, emit } = yield* setup(); + expect(result).toMatchObject({ status: "started", terminalId }); - const settle = yield* runner.runForThread({ - threadId: "thread-1", - projectId, - worktreePath: "/repo-worktree", - trigger: "settle", - }); - const settleTerminalId = settle.status === "started" ? settle.terminalId : ""; - assert.match(settleTerminalId, /^settle-clean-/); - assert.equal(write.mock.calls.at(-1)?.[0].data, "cargo clean\r"); + yield* emit({ ...event, type: "output", data: "Missing Node.\r\nInstall it? [y/N]: " }); + yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" }); + yield* TestClock.adjust("1 minute"); + expect(yield* Queue.size(writes)).toBe(0); + expect(yield* Queue.takeAll(outputLines)).toEqual(["Missing Node.", "Install it? [y/N]:"]); + + yield* emit({ ...event, type: "activity", hasRunningSubprocess: false, label: "zsh" }); + yield* emit({ ...event, type: "output", data: "\r\n% \x1b[?2004h" }); + expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/); + }), + ); - const observedSettle = yield* runner.runForThread({ - threadId: "thread-1", - projectId, - worktreePath: "/repo-worktree", - trigger: "settle", - observeCompletion: {}, - }); - const observedTerminalId = observedSettle.status === "started" ? observedSettle.terminalId : ""; - assert.notEqual(observedTerminalId, settleTerminalId); - const token = /__T3_SETUP_DONE___(\w+):/.exec(write.mock.calls.at(-1)?.[0].data ?? "")?.[1]; - const settleListener = listeners.at(-1)!; - const completion = yield* Effect.forkChild( - observedSettle.status === "started" && observedSettle.completion - ? observedSettle.completion - : Effect.die("no completion"), - ); - yield* settleListener({ - type: "output", - threadId: "thread-1", - terminalId: observedTerminalId, - data: `\r\n__T3_SETUP_DONE___${token}:0\r\n`, - }); - yield* Effect.yieldNow; - assert.equal(closeIdle.mock.calls.length, 0); - yield* settleListener({ - type: "output", - threadId: "thread-1", - terminalId: observedTerminalId, - data: "$ ", - }); - assert.deepEqual((yield* Fiber.join(completion)).exitCode, 0); - assert.deepEqual(closeIdle.mock.calls[0]?.[0], { - threadId: "thread-1", - terminalId: observedTerminalId, - }); - }).pipe(Effect.provide(layer)); + it.effect("types into a quiet shell that has no line editor", () => + Effect.gen(function* () { + const { writes } = yield* setup(); + yield* TestClock.adjust("3 seconds"); + expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/); + }), + ); + + it.effect("ignores line editor state restored from an earlier shell", () => + Effect.gen(function* () { + const { writes, emit } = yield* setup({ history: "old run\r\n% \x1b[?2004h" }); + yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" }); + yield* TestClock.adjust("1 minute"); + expect(yield* Queue.size(writes)).toBe(0); + }), + ); + + it.effect("forgets a busy startup child when the shell restarts", () => + Effect.gen(function* () { + const { writes, emit } = yield* setup(); + yield* emit({ ...event, type: "activity", hasRunningSubprocess: true, label: "fnm" }); + yield* TestClock.adjust("1 minute"); + expect(yield* Queue.size(writes)).toBe(0); + yield* emit({ ...event, type: "restarted", snapshot: openSnapshot("") }); + // The restart lands inside a quiet window, so the next full window decides. + yield* TestClock.adjust("6 seconds"); + expect(yield* Queue.take(writes)).toMatch(/^ \( vp i\r\);/); + }), + ); + + it.effect("drops its terminal listeners when cancelled while the terminal opens", () => + Effect.gen(function* () { + const opening = yield* Deferred.make(); + const { start, listeners } = yield* makeHarness({ opening }); + const fiber = yield* Effect.forkChild(start); + yield* Deferred.await(opening); + expect(listeners.size).toBe(2); + yield* Fiber.interrupt(fiber); + expect(listeners.size).toBe(0); + }), + ); + + it.effect("does not type into a shell that exits during startup", () => + Effect.gen(function* () { + const { completion, writes, emit } = yield* setup(); + yield* emit({ ...event, type: "exited", exitCode: 1, exitSignal: null }); + expect(yield* completion).toMatchObject({ exitCode: null }); + yield* TestClock.adjust("1 minute"); + expect(yield* Queue.size(writes)).toBe(0); + }), + ); }); diff --git a/apps/server/src/project/ProjectSetupScriptRunner.ts b/apps/server/src/project/ProjectSetupScriptRunner.ts index dfa850b2fdbcc..a2f8e0fc8e201 100644 --- a/apps/server/src/project/ProjectSetupScriptRunner.ts +++ b/apps/server/src/project/ProjectSetupScriptRunner.ts @@ -2,6 +2,7 @@ import { ProjectId, type ProjectScript } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { projectScriptRuntimeEnv, + projectScriptTerminalInput, resolveProjectScripts, settleProjectScript, setupProjectScript, @@ -32,9 +33,7 @@ export interface ProjectSetupScriptRunnerResultStarted { readonly terminalId: string; readonly cwd: string; readonly async: boolean; - /** - * The exit code is null when the terminal exited or was closed before the sentinel arrived. - */ + /** Null exit code means the terminal exited or closed before the sentinel. */ readonly completion?: Effect.Effect; } @@ -75,7 +74,7 @@ export class ProjectSetupScriptOperationError extends Schema.TaggedError()("t3/project/ProjectSetupScriptRunner") {} -/** @public Service construction is part of the canonical Effect module API. */ -/** - * Each run gets its own random token so script output cannot spoof completion, and the sentinel - * pattern is built per run from it. - */ +/** @public */ +// Random per-run tokens prevent script output from spoofing completion. const COMPLETION_SENTINEL_PREFIX = "__T3_SETUP_DONE__"; const OUTPUT_LINE_MAX_LENGTH = 400; const PARTIAL_LINE_MAX_LENGTH = 4_096; @@ -143,6 +139,18 @@ function stripTerminalControl(text: string): string { ); } +// Line editors (zsh, fish, bash 5.1+) enable bracketed paste when they start reading a command. +const BRACKETED_PASTE_ON = "\x1b[?2004h"; +const BRACKETED_PASTE_OFF = "\x1b[?2004l"; +// Longer than one subprocess poll plus its ps timeout, so a startup prompt is seen as busy first. +const SHELL_QUIET_FALLBACK = "3 seconds"; + +function lineEditorReading(text: string, previous: boolean): boolean { + const on = text.lastIndexOf(BRACKETED_PASTE_ON); + const off = text.lastIndexOf(BRACKETED_PASTE_OFF); + return on === off ? previous : on > off; +} + type CompletionShell = "posix" | "fish" | "powershell"; function resolveCompletionShell( @@ -157,12 +165,7 @@ function resolveCompletionShell( return "posix"; } -/** - * The command runs inside a block and the block closes on its own line, so a trailing `# comment` - * or a heredoc terminator in the command cannot swallow the sentinel. The shell reads the whole - * block before running any of it, so a script that reads stdin cannot consume the sentinel line - * either. - */ +// A block with its own closing line protects the sentinel from trailing comments, heredocs and scripts reading stdin. function wrapCommandForCompletion( command: string, shell: CompletionShell, @@ -179,31 +182,31 @@ function wrapCommandForCompletion( } } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const projects = yield* ProjectService.ProjectService; const terminalManager = yield* TerminalManager.TerminalManager; const serverSettings = yield* ServerSettings.ServerSettingsService; const crypto = yield* Crypto.Crypto; + const serviceScope = yield* Effect.scope; const completionShell = resolveCompletionShell( yield* HostProcess.Platform, yield* HostProcess.Environment, ); - const observeTerminalCompletion = (input: { - readonly threadId: string; - readonly terminalId: string; - readonly sentinel: string; - readonly sentinelPattern: RegExp; - /** The shell echoes typed input; lines ending with these are the wrapper, not output. */ - readonly echoedWrapperLines: ReadonlyArray; - readonly onOutputLine: ((line: string) => Effect.Effect) | undefined; - }) => - Effect.gen(function* () { + const observeTerminalCompletion = Effect.fn("ProjectSetupScriptRunner.observeTerminalCompletion")( + function* (input: { + readonly threadId: string; + readonly terminalId: string; + readonly sentinel: string; + readonly sentinelPattern: RegExp; + /** The shell echoes typed input; lines ending with these are the wrapper, not output. */ + readonly echoedWrapperLines: ReadonlyArray; + readonly onOutputLine: ((line: string) => Effect.Effect) | undefined; + }) { const startedAtMs = yield* Clock.currentTimeMillis; const done = yield* Deferred.make(); - // The shell redraws its prompt just after the sentinel. Closing before - // that would read the redraw as new activity and keep an idle shell. + // Wait for the prompt redraw; closing earlier mistakes it for activity and preserves an idle shell. const promptReturned = yield* Deferred.make(); let lineBuffer = ""; let settled = false; @@ -245,13 +248,10 @@ export const make = Effect.gen(function* () { } if (event.type === "output") { lineBuffer += event.data; - // A bare carriage return is how installers redraw a progress line in - // place; each redraw becomes a short line of its own instead of being - // glued into one long one. + // Bare CR redraws progress in place; split redraws instead of growing one line. const lines = lineBuffer.split(/\r\n|\r|\n/); lineBuffer = lines.pop() ?? ""; - // A script that never prints a newline must not grow this forever. - // The sentinel is always on its own line, so keeping the tail is safe. + // Bound newline-free output; the sentinel has its own line, so retaining the tail is safe. if (lineBuffer.length > PARTIAL_LINE_MAX_LENGTH) { lineBuffer = lineBuffer.slice(-PARTIAL_LINE_MAX_LENGTH); } @@ -276,8 +276,69 @@ export const make = Effect.gen(function* () { Effect.tap(() => Deferred.await(promptReturned).pipe(Effect.timeoutOption("1 second"))), Effect.ensuring(Effect.sync(() => unsubscribe())), ); - return { completion, unsubscribe }; - }); + // A startup prompt waits for input on a line that has no newline yet. + const flushPartialLine = Effect.suspend(() => { + const partial = lineBuffer; + lineBuffer = ""; + return handleLine(partial); + }); + const abandon = settle(null).pipe( + Effect.andThen(Deferred.succeed(promptReturned, undefined)), + ); + return { completion, unsubscribe, flushPartialLine, abandon }; + }, + ); + + // Input typed during shell startup can be read by an rc-file prompt (fnm, nvm) instead of the + // shell, which loses the command. Subscribe before the terminal opens so no activity is missed. + const watchShellReadiness = Effect.fn("ProjectSetupScriptRunner.watchShellReadiness")( + function* (input: { + readonly threadId: string; + readonly terminalId: string; + readonly onStartupPrompt: Effect.Effect; + }) { + const outcome = yield* Deferred.make<"ready" | "exited">(); + let reading = false; + let carry = ""; + let busy = false; + let activity = 0; + const unsubscribe = yield* terminalManager.subscribe((event) => { + if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) { + return Effect.void; + } + activity += 1; + // A new shell process starts idle; the manager resets its subprocess state without an event. + if (event.type === "started" || event.type === "restarted") { + busy = false; + reading = false; + carry = ""; + } + if (event.type === "activity") busy = event.hasRunningSubprocess; + if (event.type === "output") { + const text = carry + event.data; + carry = text.slice(-(BRACKETED_PASTE_ON.length - 1)); + reading = lineEditorReading(text, reading); + } + if (event.type === "exited" || event.type === "closed") { + return Deferred.succeed(outcome, "exited").pipe(Effect.asVoid); + } + return reading ? Deferred.succeed(outcome, "ready").pipe(Effect.asVoid) : Effect.void; + }); + // A startup prompt runs as a child process, so a busy shell keeps waiting for the user. + const quiet = Effect.gen(function* () { + while (true) { + const seen = activity; + yield* Effect.sleep(SHELL_QUIET_FALLBACK); + if (activity !== seen) continue; + if (!busy) return "ready" as const; + yield* input.onStartupPrompt; + } + }); + // Restored history can hold a previous shell's line editor state, so only live output counts. + const wait = Deferred.await(outcome).pipe(Effect.raceFirst(quiet)); + return { wait, unsubscribe }; + }, + ); const runForThread: ProjectSetupScriptRunner["Service"]["runForThread"] = Effect.fn( "ProjectSetupScriptRunner.runForThread", @@ -345,8 +406,7 @@ export const make = Effect.gen(function* () { } as const; } - // A thread settles again after it is resumed, and an earlier settle shell - // may still be busy; typing into it would feed its foreground program. + // Earlier settle shells may still run foreground programs; do not type resumed settles into them. const terminalId = input.preferredTerminalId ?? (trigger === "settle" @@ -358,8 +418,7 @@ export const make = Effect.gen(function* () { project: { cwd: project.workspaceRoot }, worktreePath: input.worktreePath, }), - // Setup can run before a client attaches. Truecolor probes in tools such - // as Vite+ wait for terminal replies that nobody can send at that point. + // Before client attachment, truecolor probes wait for terminal replies nobody can send. COLORTERM: "", }; const observe = input.observeCompletion; @@ -375,25 +434,7 @@ export const make = Effect.gen(function* () { ) : script.command; - yield* terminalManager - .open({ - threadId: input.threadId, - terminalId, - cwd, - worktreePath: input.worktreePath, - env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" }, - }) - .pipe( - Effect.mapError( - (cause) => - new ProjectSetupScriptOperationError({ - ...errorContext, - operation: "openTerminal", - cause, - }), - ), - ); - // Subscribe before writing so the sentinel cannot race past the listener. + // Subscribe before opening so neither startup activity nor the sentinel can race the listeners. const observed = observe && completionToken ? yield* observeTerminalCompletion({ @@ -405,25 +446,63 @@ export const make = Effect.gen(function* () { onOutputLine: observe.onOutputLine, }) : undefined; + // PowerShell has no line-editor signal; keep its immediate write. + const readiness = + completionShell === "powershell" + ? undefined + : yield* watchShellReadiness({ + threadId: input.threadId, + terminalId, + onStartupPrompt: observed?.flushPartialLine ?? Effect.void, + }); yield* terminalManager - .write({ + .open({ threadId: input.threadId, terminalId, - data: `${commandLine}\r`, + cwd, + worktreePath: input.worktreePath, + env: { ...env, NO_COLOR: "1", FORCE_COLOR: "0" }, }) .pipe( Effect.mapError( (cause) => new ProjectSetupScriptOperationError({ ...errorContext, - operation: "writeCommand", + operation: "openTerminal", cause, }), ), - Effect.tapError(() => Effect.sync(() => observed?.unsubscribe())), + Effect.onError(() => + Effect.sync(() => { + observed?.unsubscribe(); + readiness?.unsubscribe(); + }), + ), ); + // Return once the terminal exists so callers can show it while a startup prompt waits. + yield* (readiness?.wait ?? Effect.succeed("ready" as const)).pipe( + Effect.flatMap((shell) => + shell === "exited" + ? Effect.void + : terminalManager.write({ + threadId: input.threadId, + terminalId, + data: projectScriptTerminalInput(commandLine), + }), + ), + Effect.catchCause((cause) => + Effect.logWarning("project script command was not written", { + ...errorContext, + terminalId, + cause, + }).pipe(Effect.andThen(observed?.abandon ?? Effect.void)), + ), + Effect.ensuring(Effect.sync(() => readiness?.unsubscribe())), + Effect.forkIn(serviceScope), + ); + const completion = observed?.completion.pipe( Effect.tap(({ exitCode }) => exitCode === 0 diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 5f4e60f013026..7cd1cc82d6fec 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -1,16 +1,10 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; // @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not. import * as NodeFS from "node:fs"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { SourceControlProviderError } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; -import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; -import { TestClock } from "effect/testing"; import * as ProcessRunner from "../processRunner.ts"; import * as RepositoryIdentityResolver from "./RepositoryIdentityResolver.ts"; @@ -27,157 +21,11 @@ const git = (cwd: string, args: ReadonlyArray) => }); }).pipe(Effect.provide(ProcessRunner.layer)); -const layerRepositoryIdentityResolverTest = (options: { - readonly positiveCacheTtl?: Duration.Input; - readonly negativeCacheTtl?: Duration.Input; -}) => - Layer.effect( - RepositoryIdentityResolver.RepositoryIdentityResolver, - RepositoryIdentityResolver.make({ - cacheCapacity: 16, - ...options, - }), - ).pipe(Layer.provide(ProcessRunner.layer)); - it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { - it.effect("refreshes the Git root only when requested", () => { - const calls: Array> = []; - let rootPath = "/repo"; - let remoteUrl = "git@github.com:T3Tools/t3code.git"; - let refinements = 0; - let refinementFails = false; - const layerProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, { - run: (input) => - Effect.sync(() => { - calls.push(input.args); - return { - stdout: input.args.includes("rev-parse") - ? `${rootPath}\n` - : `origin\t${remoteUrl} (fetch)\n`, - stderr: "", - code: ChildProcessSpawner.ExitCode(0), - timedOut: false, - stdoutTruncated: false, - stderrTruncated: false, - stdoutInvalidUtf8: false, - stderrInvalidUtf8: false, - }; - }), - }); - const layerResolver = Layer.effect( - RepositoryIdentityResolver.RepositoryIdentityResolver, - RepositoryIdentityResolver.make({ - refine: (identity) => { - refinements++; - if (refinementFails) - return Effect.fail( - new SourceControlProviderError({ - provider: SourceControlProviderKind.make("forgejo"), - operation: "detectProvider", - cwd: rootPath, - detail: "account unavailable", - }), - ); - return Effect.succeed( - identity.canonicalKey.startsWith("ssh.forge.test/") - ? { - ...identity, - provider: "forgejo", - webUrl: "http://forge.test:3000/git/team/repo", - } - : identity, - ); - }, - }), - ).pipe(Layer.provide(layerProcessRunner)); - - return Effect.gen(function* () { - const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - const first = yield* resolver.resolve("/repo/packages/web"); - rootPath = "/repo/packages/web"; - // Longer than the one-minute cadence of the background sweeps. - yield* TestClock.adjust(Duration.minutes(10)); - const second = yield* resolver.resolve("/repo/packages/web"); - - expect(first?.canonicalKey).toBe("github.com/t3tools/t3code"); - expect(second).toEqual(first); - expect(refinements).toBe(1); - expect(calls).toEqual([ - ["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"], - ["-C", "/repo", "remote", "-v"], - ]); - - const refreshed = yield* resolver.resolve("/repo/packages/web", { refresh: true }); - expect(refreshed?.rootPath).toBe("/repo/packages/web"); - expect(yield* resolver.resolve("/repo/packages/web")).toEqual(refreshed); - expect(calls.slice(2)).toEqual([ - ["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"], - ["-C", "/repo/packages/web", "remote", "-v"], - ]); - remoteUrl = "git@ssh.forge.test:team/repo.git"; - const forgejo = yield* resolver.resolve(rootPath, { refresh: true }); - expect(forgejo?.webUrl).toBe("http://forge.test:3000/git/team/repo"); - expect(forgejo?.provider).toBe("forgejo"); - expect(forgejo?.canonicalKey).toBe("ssh.forge.test/team/repo"); - expect(forgejo?.locator.remoteUrl).toBe(remoteUrl); - expect(yield* resolver.resolve(rootPath)).toEqual(forgejo); - expect(refinements).toBe(3); - refinementFails = true; - const unavailable = yield* resolver.resolve(rootPath, { refresh: true }); - expect(unavailable?.webUrl).toBeUndefined(); - expect(unavailable?.canonicalKey).toBe("ssh.forge.test/team/repo"); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), layerResolver))); - }); - - it.effect("retries Git root discovery after the negative TTL", () => { - const calls: Array> = []; - let rootAttempts = 0; - const layerProcessRunner = Layer.succeed(ProcessRunner.ProcessRunner, { - run: (input) => - Effect.sync(() => { - calls.push(input.args); - const rootLookup = input.args.includes("rev-parse"); - const failed = rootLookup && rootAttempts++ === 0; - return { - stdout: rootLookup - ? failed - ? "" - : "/repo\n" - : "origin\tgit@github.com:T3Tools/t3code.git (fetch)\n", - stderr: failed ? "temporary Git failure" : "", - code: ChildProcessSpawner.ExitCode(failed ? 1 : 0), - timedOut: false, - stdoutTruncated: false, - stderrTruncated: false, - stdoutInvalidUtf8: false, - stderrInvalidUtf8: false, - }; - }), - }); - const layerResolver = Layer.effect( - RepositoryIdentityResolver.RepositoryIdentityResolver, - RepositoryIdentityResolver.make(), - ).pipe(Layer.provide(layerProcessRunner)); - - return Effect.gen(function* () { - const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - expect(yield* resolver.resolve("/repo/packages/web")).toBeNull(); - expect(yield* resolver.resolve("/repo/packages/web")).toBeNull(); - - yield* TestClock.adjust(Duration.minutes(1)); - const recovered = yield* resolver.resolve("/repo/packages/web"); - expect(recovered?.rootPath).toBe("/repo"); - expect(calls).toEqual([ - ["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"], - ["-C", "/repo/packages/web", "rev-parse", "--show-toplevel"], - ["-C", "/repo", "remote", "-v"], - ]); - }).pipe(Effect.provide(Layer.merge(TestClock.layer(), layerResolver))); - }); - it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-repository-identity-test-", }); @@ -187,8 +35,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; const identity = yield* resolver.resolve(cwd); - // Native realpath, since git reports the long form of a directory the - // temp dir may name by its 8.3 short form on Windows. + // Native realpath matches git's long paths when Windows temp dirs use 8.3 names. const resolvedIdentityRoot = identity?.rootPath === undefined ? "" : NodeFS.realpathSync.native(identity.rootPath); const resolvedCwd = NodeFS.realpathSync.native(cwd); @@ -200,6 +47,31 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { expect(identity?.provider).toBe("github"); expect(identity?.owner).toBe("T3Tools"); expect(identity?.name).toBe("t3code"); + expect(yield* resolver.resolve(path.join(cwd, ".git"))).toBeNull(); + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + + it.effect("resolves the fetch remote of a partial clone", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-partial-clone-test-", + }); + + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + yield* git(cwd, ["remote", "set-url", "--push", "origin", "git@github.com:T3Tools/push.git"]); + yield* git(cwd, ["config", "remote.origin.promisor", "true"]); + yield* git(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]); + + const remotes = yield* git(cwd, ["remote", "-v"]); + expect(remotes.stdout).toContain("(fetch) [blob:none]"); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const identity = yield* resolver.resolve(cwd); + expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code"); + expect(identity?.locator.remoteUrl).toBe("git@github.com:T3Tools/t3code.git"); + expect(identity?.locator.remoteName).toBe("origin"); }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); @@ -230,6 +102,60 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); + it.effect.each(["bare clone", "dot-bare"] as const)( + "resolves a %s to its Git directory and the same identity as a checkout", + (layout) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const checkout = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-checkout-", + }); + const root = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-bare-", + }); + const bareGitDir = layout === "dot-bare" ? path.join(root, ".bare") : root; + + yield* git(checkout, ["init"]); + yield* git(checkout, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); + yield* git(root, ["init", "--bare", bareGitDir]); + if (layout === "dot-bare") { + yield* fileSystem.writeFileString(path.join(root, ".git"), "gitdir: ./.bare\n"); + } + yield* git(root, [ + "--git-dir", + bareGitDir, + "remote", + "add", + "origin", + "https://github.com/T3Tools/t3code.git", + ]); + + const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const checkoutIdentity = yield* resolver.resolve(checkout); + expect(checkoutIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); + const resolvedBareGitDir = NodeFS.realpathSync.native(bareGitDir); + const projectRoots = layout === "dot-bare" ? [root, bareGitDir] : [root]; + + for (const projectRoot of projectRoots) { + const identity = yield* resolver.resolve(projectRoot); + const resolvedIdentityRoot = + identity?.rootPath === undefined ? "" : NodeFS.realpathSync.native(identity.rootPath); + + expect(identity).not.toBeNull(); + expect(identity?.canonicalKey).toBe(checkoutIdentity?.canonicalKey); + expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe( + normalizeResolvedPath(resolvedBareGitDir), + ); + } + + yield* git(root, ["--git-dir", bareGitDir, "remote", "remove", "origin"]); + for (const projectRoot of projectRoots) { + expect(yield* resolver.resolve(projectRoot, { refresh: true })).toBeNull(); + } + }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), + ); + it.effect("returns null for non-git folders and repos without remotes", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -334,6 +260,7 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { expect(identity?.displayName).toBe("T3Tools/t3code"); expect(identity?.origin).toEqual({ canonicalKey: "github.com/julius/t3code-fork", + remoteUrl: "git@github.com:julius/t3code-fork.git", displayName: "julius/t3code-fork", }); }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), @@ -359,86 +286,4 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => { expect(identity?.name).toBe("t3code"); }).pipe(Effect.provide(RepositoryIdentityResolver.layer)), ); - - it.effect( - "keeps null identities cached across repeated resolves until the negative TTL expires", - () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-repository-identity-late-remote-test-", - }); - - yield* git(cwd, ["init"]); - - const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - const initialIdentity = yield* resolver.resolve(cwd); - expect(initialIdentity).toBeNull(); - - yield* git(cwd, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); - - for (const _attempt of [1, 2, 3]) { - const cachedIdentity = yield* resolver.resolve(cwd); - expect(cachedIdentity).toBeNull(); - } - - yield* TestClock.adjust(Duration.millis(120)); - - const refreshedIdentity = yield* resolver.resolve(cwd); - expect(refreshedIdentity).not.toBeNull(); - expect(refreshedIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); - expect(refreshedIdentity?.name).toBe("t3code"); - }).pipe( - Effect.provide( - Layer.merge( - TestClock.layer(), - layerRepositoryIdentityResolverTest({ - negativeCacheTtl: Duration.millis(50), - positiveCacheTtl: Duration.seconds(1), - }), - ), - ), - ), - ); - - it.effect("refreshes cached identities after the positive TTL when a remote changes", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const cwd = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-repository-identity-remote-change-test-", - }); - - yield* git(cwd, ["init"]); - yield* git(cwd, ["remote", "add", "origin", "git@github.com:T3Tools/t3code.git"]); - - const resolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; - const initialIdentity = yield* resolver.resolve(cwd); - expect(initialIdentity).not.toBeNull(); - expect(initialIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); - - yield* git(cwd, ["remote", "set-url", "origin", "git@github.com:T3Tools/t3code-next.git"]); - - const cachedIdentity = yield* resolver.resolve(cwd); - expect(cachedIdentity).not.toBeNull(); - expect(cachedIdentity?.canonicalKey).toBe("github.com/t3tools/t3code"); - - yield* TestClock.adjust(Duration.millis(180)); - - const refreshedIdentity = yield* resolver.resolve(cwd); - expect(refreshedIdentity).not.toBeNull(); - expect(refreshedIdentity?.canonicalKey).toBe("github.com/t3tools/t3code-next"); - expect(refreshedIdentity?.displayName).toBe("T3Tools/t3code-next"); - expect(refreshedIdentity?.name).toBe("t3code-next"); - }).pipe( - Effect.provide( - Layer.merge( - TestClock.layer(), - layerRepositoryIdentityResolverTest({ - negativeCacheTtl: Duration.millis(50), - positiveCacheTtl: Duration.millis(100), - }), - ), - ), - ), - ); }); diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 80d5b39823abc..00254ee86781e 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -1,24 +1,20 @@ import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; -import { - detectSourceControlProviderFromGitRemoteUrl, - normalizeGitRemoteUrl, -} from "@t3tools/shared/git"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; +import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as ProcessRunner from "../processRunner.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import { explicitBareRepositoryEnv } from "../vcs/VcsProcess.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; const DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512; -// Background sweeps resolve every project each minute. A long TTL keeps them -// from spawning git each time. Clone, publish, and PR discovery (after a turn -// and before it saves links) resolve with `refresh: true`. +// Minute-by-minute sweeps need cached hits; clone, publish and PR discovery force refresh. const DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(15); const DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1); @@ -41,8 +37,7 @@ export class RepositoryIdentityResolver extends Context.Service< } >()("t3/project/RepositoryIdentityResolver") {} -// Local remotes (GitButler's `gb-local` is `.`) name a path on this machine, -// not a repository, so unrelated repos would share one identity. +// Local paths such as GitButler's gb-local=. would give unrelated repos the same identity. function isLocalRemoteUrl(url: string): boolean { if (/^file:/i.test(url)) return true; if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url)) return false; @@ -58,7 +53,8 @@ function parseRemoteFetchUrls(stdout: string): Map { for (const line of stdout.split("\n")) { const trimmed = line.trim(); if (trimmed.length === 0) continue; - const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed); + // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. + const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed); if (!match) continue; const [, remoteName = "", remoteUrl = "", direction = ""] = match; if ( @@ -100,10 +96,10 @@ function buildRepositoryOrigin( canonicalKey: string, ): RepositoryIdentity["origin"] { if (!originUrl) return undefined; - const originKey = normalizeGitRemoteUrl(originUrl); + const originKey = sourceControlDefinitions.repositoryKeyFromRemote(originUrl); if (originKey === canonicalKey) return undefined; const displayName = repositoryPathOf(originKey, originUrl); - return { canonicalKey: originKey, ...(displayName ? { displayName } : {}) }; + return { canonicalKey: originKey, remoteUrl: originUrl, ...(displayName ? { displayName } : {}) }; } function buildRepositoryIdentity(input: { @@ -112,8 +108,8 @@ function buildRepositoryIdentity(input: { readonly originUrl: string | undefined; readonly rootPath: string; }): RepositoryIdentity { - const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl); - const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl); + const canonicalKey = sourceControlDefinitions.repositoryKeyFromRemote(input.remoteUrl); + const sourceControlProvider = sourceControlDefinitions.recognizeRemote(input.remoteUrl); const repositoryPath = repositoryPathOf(canonicalKey, input.remoteUrl); const repositoryPathSegments = repositoryPath.split("/").filter((segment) => segment.length > 0); const [owner] = repositoryPathSegments; @@ -136,39 +132,77 @@ function buildRepositoryIdentity(input: { }; } +class RepositoryIdentityCacheKey extends Data.Class<{ + readonly rootPath: string; + readonly isBare: boolean; +}> {} + const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")( function* (cwd: string) { const processRunner = yield* ProcessRunner.ProcessRunner; + const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform); - // git is a real executable on every platform — no cmd.exe shell mode, which - // would split paths containing spaces during cmd's re-tokenization. + // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization. const topLevelResult = yield* processRunner .run({ command: "git", args: ["-C", cwd, "rev-parse", "--show-toplevel"], - env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform), + env, timeoutBehavior: "timedOutResult", }) .pipe(Effect.option); - if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) { + if (topLevelResult._tag === "None" || topLevelResult.value.timedOut) { return null; } + if (topLevelResult.value.code === 0) { + const rootPath = topLevelResult.value.stdout.trim(); + return rootPath.length > 0 + ? new RepositoryIdentityCacheKey({ rootPath, isBare: false }) + : null; + } + + // Explicit Git directories preserve safe.bareRepository=explicit for both layouts. + for (const gitDir of [".", ".git"]) { + const bareResult = yield* processRunner + .run({ + command: "git", + args: [ + "-C", + cwd, + `--git-dir=${gitDir}`, + "rev-parse", + "--is-bare-repository", + "--absolute-git-dir", + ], + env, + timeoutBehavior: "timedOutResult", + }) + .pipe(Effect.option); + if (bareResult._tag === "None" || bareResult.value.timedOut) return null; + if (bareResult.value.code !== 0) continue; - const candidate = topLevelResult.value.stdout.trim(); - return candidate.length > 0 ? candidate : null; + const [isBare, rootPath = ""] = bareResult.value.stdout + .split("\n") + .map((line) => line.trim()); + // A checkout's .git directory contains remotes but is not a project root. + return isBare === "true" && rootPath.length > 0 + ? new RepositoryIdentityCacheKey({ rootPath, isBare: true }) + : null; + } + return null; }, ); const resolveRepositoryIdentityFromCacheKey = Effect.fn( "RepositoryIdentityResolver.resolveFromCacheKey", )(function* ( - cacheKey: string, + cacheKey: RepositoryIdentityCacheKey, ): Effect.fn.Return { const processRunner = yield* ProcessRunner.ProcessRunner; const remoteResult = yield* processRunner .run({ command: "git", - args: ["-C", cacheKey, "remote", "-v"], + args: ["-C", cacheKey.rootPath, ...(cacheKey.isBare ? ["--git-dir=."] : []), "remote", "-v"], env: explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform), timeoutBehavior: "timedOutResult", }) @@ -180,7 +214,11 @@ const resolveRepositoryIdentityFromCacheKey = Effect.fn( const remotes = parseRemoteFetchUrls(remoteResult.value.stdout); const remote = pickPrimaryRemote(remotes); return remote - ? buildRepositoryIdentity({ ...remote, originUrl: remotes.get("origin"), rootPath: cacheKey }) + ? buildRepositoryIdentity({ + ...remote, + originUrl: remotes.get("origin"), + rootPath: cacheKey.rootPath, + }) : null; }); @@ -199,7 +237,7 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( onFailure: () => Duration.zero, }); - const repositoryRootCache = yield* Cache.makeWith( + const repositoryRootCache = yield* Cache.makeWith( (cwd) => resolveRepositoryIdentityCacheKey(cwd).pipe( Effect.provideService(ProcessRunner.ProcessRunner, processRunner), @@ -207,7 +245,10 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( { capacity: cacheCapacity, timeToLive }, ); - const repositoryIdentityCache = yield* Cache.makeWith( + const repositoryIdentityCache = yield* Cache.makeWith< + RepositoryIdentityCacheKey, + RepositoryIdentity | null + >( (cacheKey) => resolveRepositoryIdentityFromCacheKey(cacheKey).pipe( Effect.provideService(ProcessRunner.ProcessRunner, processRunner), diff --git a/apps/server/src/project/T3ProjectFileLoader.test.ts b/apps/server/src/project/T3ProjectFileLoader.test.ts index 5b42ea4cd2134..5abc78098869b 100644 --- a/apps/server/src/project/T3ProjectFileLoader.test.ts +++ b/apps/server/src/project/T3ProjectFileLoader.test.ts @@ -28,40 +28,6 @@ const writeProjectFile = Effect.fn("writeProjectFile")(function* (cwd: string, c it.layer(layerTest)("T3ProjectFileLoader", (it) => { describe("load", () => { - it.effect("loads and decodes a valid t3.json", () => - Effect.gen(function* () { - const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader; - const cwd = yield* makeTempDir; - yield* writeProjectFile( - cwd, - `{ - // JSONC is tolerated - "iconPath": "assets/logo.svg", - "scripts": [{ "name": "Dev", "command": "pnpm dev" }], - }`, - ); - - const loaded = yield* loader.load(cwd); - - expect(Option.isSome(loaded)).toBe(true); - if (Option.isSome(loaded)) { - expect(loaded.value.iconPath).toBe("assets/logo.svg"); - expect(loaded.value.scripts).toEqual([{ name: "Dev", command: "pnpm dev" }]); - } - }), - ); - - it.effect("returns none when t3.json is missing", () => - Effect.gen(function* () { - const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader; - const cwd = yield* makeTempDir; - - const loaded = yield* loader.load(cwd); - - expect(Option.isNone(loaded)).toBe(true); - }), - ); - it.effect("returns none for malformed JSON without failing", () => Effect.gen(function* () { const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader; @@ -73,17 +39,5 @@ it.layer(layerTest)("T3ProjectFileLoader", (it) => { expect(Option.isNone(loaded)).toBe(true); }), ); - - it.effect("returns none for schema-invalid files without failing", () => - Effect.gen(function* () { - const loader = yield* T3ProjectFileLoader.T3ProjectFileLoader; - const cwd = yield* makeTempDir; - yield* writeProjectFile(cwd, '{ "scripts": [{ "name": "Dev" }] }'); - - const loaded = yield* loader.load(cwd); - - expect(Option.isNone(loaded)).toBe(true); - }), - ); }); }); diff --git a/apps/server/src/project/T3ProjectFileLoader.ts b/apps/server/src/project/T3ProjectFileLoader.ts index b4335cb5660ce..1cc008d07cc83 100644 --- a/apps/server/src/project/T3ProjectFileLoader.ts +++ b/apps/server/src/project/T3ProjectFileLoader.ts @@ -28,10 +28,7 @@ export class T3ProjectFileLoadError extends Schema.TaggedError Effect.Effect>; } >()("t3/project/T3ProjectFileLoader") {} @@ -46,7 +43,7 @@ const logT3ProjectFileLoadError = (error: T3ProjectFileLoadError) => }), ); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; diff --git a/apps/server/src/project/WorktreeSetupTracker.test.ts b/apps/server/src/project/WorktreeSetupTracker.test.ts index e96a1815f1852..ed3fcc027c720 100644 --- a/apps/server/src/project/WorktreeSetupTracker.test.ts +++ b/apps/server/src/project/WorktreeSetupTracker.test.ts @@ -1,13 +1,10 @@ import { describe, expect, it } from "@effect/vitest"; -import { ThreadId, WorktreeSetupSnapshot } from "@t3tools/contracts"; +import { ThreadId } from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; -import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import * as WorktreeSetupTracker from "./WorktreeSetupTracker.ts"; @@ -76,34 +73,6 @@ describe("WorktreeSetupTracker", () => { }), ); - it.effect("stream never steps back behind the snapshot it started from", () => - Effect.gen(function* () { - const tracker = yield* WorktreeSetupTracker.make; - yield* tracker.begin({ - threadId, - branch: null, - baseRef: null, - stages: ["agent"], - fiber: null, - }); - yield* tracker.stageStatus(threadId, "agent", "running"); - yield* tracker.stageStatus(threadId, "agent", "done"); - - const collected = yield* tracker.stream(threadId).pipe( - Stream.takeUntil((snapshot) => snapshot?.phase === "done"), - Stream.runCollect, - Effect.forkChild, - ); - yield* Effect.yieldNow; - yield* tracker.finish(threadId, "done"); - - const snapshots = yield* Fiber.join(collected); - expect(snapshots.length).toBeGreaterThan(0); - expect(snapshots.every((snapshot) => (snapshot?.sequence ?? -1) >= 2)).toBe(true); - expect(snapshots.at(-1)?.phase).toBe("done"); - }), - ); - it.effect("a new setup on the same thread keeps sequences increasing", () => Effect.gen(function* () { const tracker = yield* WorktreeSetupTracker.make; @@ -138,24 +107,6 @@ describe("WorktreeSetupTracker", () => { }), ); - it.effect("finished setups are dropped after the retention window", () => - Effect.gen(function* () { - const tracker = yield* WorktreeSetupTracker.make; - yield* tracker.begin({ - threadId, - branch: null, - baseRef: null, - stages: ["agent"], - fiber: null, - }); - yield* tracker.finish(threadId, "done"); - expect((yield* tracker.get(threadId))?.phase).toBe("done"); - - yield* TestClock.adjust(Duration.seconds(31)); - expect(yield* tracker.get(threadId)).toBeNull(); - }), - ); - it.effect("cancel interrupts the bootstrap fiber and reports whether one was running", () => Effect.gen(function* () { const tracker = yield* WorktreeSetupTracker.make; @@ -189,30 +140,4 @@ describe("WorktreeSetupTracker", () => { yield* Fiber.interrupt(fiber); }), ); - - it.effect("clamps free text to the contract limits before publishing", () => - Effect.gen(function* () { - const tracker = yield* WorktreeSetupTracker.make; - yield* tracker.begin({ - threadId, - branch: null, - baseRef: null, - stages: ["checkout", "setup-script"], - fiber: null, - }); - const long = "x".repeat(2_000); - - yield* tracker.stageStatus(threadId, "checkout", "done", long); - yield* tracker.stage(threadId, "setup-script", { detail: long }); - yield* tracker.appendTail(threadId, "setup-script", long); - yield* tracker.finish(threadId, "failed", long); - - const snapshot = yield* tracker.get(threadId); - expect(snapshot?.stages[0]?.detail?.length).toBe(200); - expect(snapshot?.stages[1]?.detail?.length).toBe(200); - expect(snapshot?.stages[1]?.tail[0]?.length).toBe(400); - expect(snapshot?.error?.length).toBe(1000); - expect(Schema.is(WorktreeSetupSnapshot)(snapshot)).toBe(true); - }), - ); }); diff --git a/apps/server/src/project/WorktreeSetupTracker.ts b/apps/server/src/project/WorktreeSetupTracker.ts index 43639afe4515a..ff5580961d977 100644 --- a/apps/server/src/project/WorktreeSetupTracker.ts +++ b/apps/server/src/project/WorktreeSetupTracker.ts @@ -56,10 +56,7 @@ export class WorktreeSetupTracker extends Context.Service< phase: "done" | "failed" | "cancelled", error?: string | null, ) => Effect.Effect; - /** - * Called right before the turn is dispatched so a late cancel cannot roll - * back a thread whose agent has already started. - */ + /** Call just before dispatch so late cancellation cannot roll back a started agent's thread. */ readonly markUncancellable: (threadId: ThreadId) => Effect.Effect; readonly cancel: (threadId: ThreadId) => Effect.Effect; readonly get: (threadId: ThreadId) => Effect.Effect; @@ -103,8 +100,7 @@ export const make = Effect.gen(function* () { readonly snapshot: WorktreeSetupSnapshot | null; }>(); const retentionFibers = new Map>(); - // Sequences keep increasing across setups of the same thread so a stream - // opened during a previous setup still accepts the next one's first snapshot. + // Keep sequences increasing across setups so existing subscribers accept the next setup's first snapshot. const lastSequenceByThread = new Map(); const publish = (threadId: ThreadId, snapshot: WorktreeSetupSnapshot | null) => @@ -142,13 +138,12 @@ export const make = Effect.gen(function* () { return next; }).pipe( Effect.andThen(publish(threadId, null)), - // A subscriber that outlives retention sees `null` here and accepts any - // sequence after it, so the counter can start over for this thread. + // After retention, subscribers see null and accept any sequence; the counter can reset. Effect.tap(() => Effect.sync(() => lastSequenceByThread.delete(threadId))), ); - const begin: WorktreeSetupTracker["Service"]["begin"] = (input) => - Effect.gen(function* () { + const begin: WorktreeSetupTracker["Service"]["begin"] = Effect.fn("WorktreeSetupTracker.begin")( + function* (input) { yield* clearRetention(input.threadId); const startedAt = yield* nowIso; const ordered = WORKTREE_SETUP_STAGE_ORDER.filter((id) => input.stages.includes(id)); @@ -172,7 +167,8 @@ export const make = Effect.gen(function* () { return next; }); yield* publish(input.threadId, snapshot); - }); + }, + ); const update: WorktreeSetupTracker["Service"]["update"] = (threadId, mutate) => modify(threadId, (tracked) => ({ ...tracked, snapshot: mutate(tracked.snapshot) })).pipe( @@ -235,44 +231,45 @@ export const make = Effect.gen(function* () { ), })); - const finish: WorktreeSetupTracker["Service"]["finish"] = (threadId, phase, error) => - Effect.gen(function* () { - const endedAt = yield* nowIso; - const snapshot = yield* modify(threadId, (tracked) => ({ - fiber: null, - snapshot: { - ...tracked.snapshot, - phase, - endedAt, - error: - error === undefined || error === null - ? null - : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH), - stages: tracked.snapshot.stages.map((entry) => - entry.status === "running" - ? { - ...entry, - status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed", - endedAt, - } - : entry, - ), - }, - })); - if (!snapshot) return null; - yield* clearRetention(threadId); - const fiber = yield* remove(threadId).pipe( - Effect.delay(FINISHED_RETENTION), - Effect.ensuring( - Effect.sync(() => { - if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId); - }), + const finish: WorktreeSetupTracker["Service"]["finish"] = Effect.fn( + "WorktreeSetupTracker.finish", + )(function* (threadId, phase, error) { + const endedAt = yield* nowIso; + const snapshot = yield* modify(threadId, (tracked) => ({ + fiber: null, + snapshot: { + ...tracked.snapshot, + phase, + endedAt, + error: + error === undefined || error === null + ? null + : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH), + stages: tracked.snapshot.stages.map((entry) => + entry.status === "running" + ? { + ...entry, + status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed", + endedAt, + } + : entry, ), - Effect.forkDetach, - ); - retentionFibers.set(threadId, fiber); - return snapshot; - }); + }, + })); + if (!snapshot) return null; + yield* clearRetention(threadId); + const fiber = yield* remove(threadId).pipe( + Effect.delay(FINISHED_RETENTION), + Effect.ensuring( + Effect.sync(() => { + if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId); + }), + ), + Effect.forkDetach, + ); + retentionFibers.set(threadId, fiber); + return snapshot; + }); const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) => Ref.update(setups, (current) => { @@ -283,33 +280,29 @@ export const make = Effect.gen(function* () { return next; }); - const cancel: WorktreeSetupTracker["Service"]["cancel"] = (threadId) => - Effect.gen(function* () { - const current = yield* Ref.get(setups); - const tracked = current.get(threadId); - if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) { - return false; - } - yield* Fiber.interrupt(tracked.fiber); - return true; - }); + const cancel: WorktreeSetupTracker["Service"]["cancel"] = Effect.fn( + "WorktreeSetupTracker.cancel", + )(function* (threadId) { + const current = yield* Ref.get(setups); + const tracked = current.get(threadId); + if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) { + return false; + } + yield* Fiber.interrupt(tracked.fiber); + return true; + }); const get: WorktreeSetupTracker["Service"]["get"] = (threadId) => Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null)); - /** - * Each subscriber gets a one-slot sliding mailbox: a slow WebSocket only ever - * holds the newest snapshot, so a chatty setup script cannot grow the server - * heap. - */ + // One-slot sliding mailboxes bound slow WebSockets to the newest setup snapshot. const stream: WorktreeSetupTracker["Service"]["stream"] = (threadId) => Stream.callback( (mailbox) => Effect.gen(function* () { const subscription = yield* PubSub.subscribe(changes); const initial = yield* get(threadId); - // Changes published between subscribing and reading `initial` are - // already folded into it. Drop them so the client never steps back. + // The initial snapshot already includes queued changes; drop them to avoid stale replay. let lastSequence = initial?.sequence ?? -1; Queue.offerUnsafe(mailbox, initial); yield* Stream.fromSubscription(subscription).pipe( diff --git a/apps/server/src/project/gitCloneProgress.ts b/apps/server/src/project/gitCloneProgress.ts index 1a65c11d3cfe0..f1d75b532bc7a 100644 --- a/apps/server/src/project/gitCloneProgress.ts +++ b/apps/server/src/project/gitCloneProgress.ts @@ -18,10 +18,7 @@ const STAGE_PREFIXES: ReadonlyArray = [ const PERCENT = /:\s+(\d+)%\s+\((\d+)\/(\d+)\)(?:,\s*(.*?))?\s*(?:,\s*done\.)?\s*$/; -/** - * Git redraws each counter with a bare `\r`, so callers hand over each redraw - * as its own line. - */ +/** Pass each bare-CR progress redraw as a separate line. */ export function parseGitCloneProgressLine(line: string): GitCloneProgressLine | null { const trimmed = line.trim(); const stageEntry = STAGE_PREFIXES.find(([pattern]) => pattern.test(trimmed)); diff --git a/apps/server/src/project/http.test.ts b/apps/server/src/project/http.test.ts deleted file mode 100644 index ba20c5fbbc9f1..0000000000000 --- a/apps/server/src/project/http.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { assert, it } from "@effect/vitest"; -import { ProjectId } from "@t3tools/contracts"; -import * as Effect from "effect/Effect"; - -import { - ProjectConflictError, - ProjectNotEmptyError, - ProjectNotFoundError, - ProjectOperationError, -} from "./ProjectService.ts"; -import { ServerRuntimeStartupError } from "../serverRuntimeStartup.ts"; -import { failProjectMutation } from "./http.ts"; - -const projectId = ProjectId.make("project:http-mutation"); - -it.effect.each([ - new ProjectNotFoundError({ projectId }), - new ProjectNotEmptyError({ projectId }), - new ProjectConflictError({ - projectId, - workspaceRoot: "/workspace/project", - conflictingProjectId: ProjectId.make("project:http-mutation-conflict"), - }), -])("maps expected project mutation failures to invalid requests", (cause) => - Effect.gen(function* () { - const error = yield* failProjectMutation(cause).pipe(Effect.flip); - - assert.equal(error._tag, "EnvironmentRequestInvalidError"); - assert.equal(error.code, "invalid_request"); - assert.equal(error.reason, "invalid_command"); - }), -); - -it.effect.each([ - new ProjectOperationError({ - operation: "dispatch-project-command", - projectId, - cause: "database unavailable", - }), - new ServerRuntimeStartupError({ - mode: "web", - host: null, - port: 0, - cause: "startup unavailable", - }), -])("keeps operational and startup failures internal", (cause) => - Effect.gen(function* () { - const error = yield* failProjectMutation(cause).pipe(Effect.flip); - - assert.equal(error._tag, "EnvironmentInternalError"); - assert.equal(error.code, "internal_error"); - assert.equal(error.reason, "project_mutation_failed"); - }), -); diff --git a/apps/server/src/project/http.ts b/apps/server/src/project/http.ts index e1a04655d8353..825e6c1cc8f43 100644 --- a/apps/server/src/project/http.ts +++ b/apps/server/src/project/http.ts @@ -17,7 +17,7 @@ import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts"; import * as ProjectService from "./ProjectService.ts"; import { projectMutationOperation } from "./ProjectMutation.ts"; -export const failProjectMutation = Effect.fn("environment.projects.failMutation")(function* ( +const failProjectMutation = Effect.fn("environment.projects.failMutation")(function* ( cause: ProjectService.ProjectServiceError | ServerRuntimeStartup.ServerRuntimeStartupError, ) { if ( diff --git a/apps/server/src/project/threadWorkspaceRoot.ts b/apps/server/src/project/threadWorkspaceRoot.ts new file mode 100644 index 0000000000000..7ad8a3da99307 --- /dev/null +++ b/apps/server/src/project/threadWorkspaceRoot.ts @@ -0,0 +1,19 @@ +import type { ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProjectService from "./ProjectService.ts"; + +/** The directory a thread works in, or undefined when the thread or its project is gone. */ +export const threadWorkspaceRoot = Effect.fn("threadWorkspaceRoot")( + function* (threadId: ThreadId) { + const threads = yield* ThreadManagementService.ThreadManagementService; + const projects = yield* ProjectService.ProjectService; + const shell = yield* threads.getThreadShell(threadId); + if (shell === null) return undefined; + if (shell.worktreePath) return shell.worktreePath; + return Option.getOrUndefined(yield* projects.getById(shell.projectId))?.workspaceRoot; + }, + Effect.orElseSucceed(() => undefined), +); diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 7b69ca58baaaf..bc7c14d3b3c8a 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -6,11 +6,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { ProviderInstanceId } from "@t3tools/contracts"; import { AcpRegistrySettings } from "@t3tools/provider-acp-registry/settings"; import { describe, expect, it } from "@effect/vitest"; -import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; import * as Schema from "effect/Schema"; -import * as TestClock from "effect/testing/TestClock"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; @@ -21,7 +18,6 @@ import { logoutAcpRegistry, normalizeAcpRegistryAuthMethods, normalizeAcpRegistryCommands, - probeAcpRegistryConfiguration, } from "@t3tools/provider-acp-registry/testing"; import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; @@ -141,61 +137,6 @@ describe("ACP Registry probe", () => { expect(methods[0]).not.toHaveProperty("command"); }); - it("omits overlong opaque auth method and environment variable ids", () => { - const methods = normalizeAcpRegistryAuthMethods([ - { id: "x".repeat(129), name: "Invalid" }, - { - id: "api-key", - name: "API key", - type: "env_var", - vars: [ - { name: "y".repeat(129), label: "Invalid" }, - { name: "OPENAI_API_KEY", label: "OpenAI API key" }, - ], - }, - ]); - - expect(methods).toEqual([ - { - id: "api-key", - name: "API key", - description: null, - type: "env_var", - envVarNames: ["OPENAI_API_KEY"], - }, - ]); - }); - - it("falls back to model-category configuration options", () => { - const result = acpRegistryProbeResult(instanceId, { - sessionId: "probe-session", - initializeResult: { protocolVersion: 1 }, - sessionSetupResult: { - sessionId: "probe-session", - configOptions: [ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: "sonnet", - options: [ - { value: "sonnet", name: "Sonnet", description: "Balanced" }, - { value: "haiku", name: "Haiku" }, - ], - }, - ], - }, - modelConfigId: "model", - } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult); - - expect(result.models).toEqual([ - { id: "sonnet", name: "Sonnet", description: "Balanced" }, - { id: "haiku", name: "Haiku", description: null }, - ]); - expect(result.currentModelId).toBe("sonnet"); - }); - it("omits overlong opaque model ids instead of publishing mutated ids", () => { const result = acpRegistryProbeResult(instanceId, { sessionId: "probe-session", @@ -292,32 +233,42 @@ describe("ACP Registry probe", () => { ]); }); - it("omits a current model that falls outside the bounded model catalog", () => { - const result = acpRegistryProbeResult(instanceId, { - sessionId: "probe-session", - initializeResult: { protocolVersion: 1 }, - sessionSetupResult: { + it.each(["config option", "session model state"] as const)( + "retains the current model beyond the catalog cap from %s", + (source) => { + const models = Array.from({ length: 257 }, (_, index) => ({ + modelId: `model-${index}`, + name: `Model ${index}`, + })); + const result = acpRegistryProbeResult(instanceId, { sessionId: "probe-session", - configOptions: [ - { - id: "model", - name: "Model", - category: "model", - type: "select", - currentValue: "model-256", - options: Array.from({ length: 257 }, (_, index) => ({ - value: `model-${index}`, - name: `Model ${index}`, - })), - }, - ], - }, - modelConfigId: "model", - } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult); - - expect(result.models).toHaveLength(256); - expect(result.currentModelId).toBeNull(); - }); + initializeResult: { protocolVersion: 1 }, + sessionSetupResult: { + sessionId: "probe-session", + ...(source === "config option" + ? { + configOptions: [ + { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "model-256", + options: models.map(({ modelId, name }) => ({ value: modelId, name })), + }, + ], + } + : { models: { currentModelId: "model-256", availableModels: models } }), + }, + modelConfigId: source === "config option" ? "model" : undefined, + } satisfies AcpSessionRuntime.AcpSessionRuntimeStartResult); + + expect(result.models).toHaveLength(256); + expect(result.models[0]?.id).toBe("model-0"); + expect(result.models.at(-1)?.id).toBe("model-256"); + expect(result.currentModelId).toBe("model-256"); + }, + ); it("bounds and de-duplicates advertised commands", () => { const commands = normalizeAcpRegistryCommands([ @@ -367,97 +318,6 @@ describe("ACP Registry probe", () => { }); }); - it.effect("captures commands advertised just after session creation", () => - Effect.gen(function* () { - const result = yield* probeAcpRegistryConfiguration({ - instanceId, - settings: decodeSettings({ agentId: "mock-agent" }), - cwd: process.cwd(), - environment: process.env, - }); - - expect(result.slashCommands).toEqual([ - { - name: "review", - description: "Review the current changes", - input: { hint: "focus" }, - }, - ]); - expect(result.skills).toEqual([ - { - name: "workspace-skill", - description: "Run the workspace skill", - path: "acp://skill/workspace-skill", - scope: "agent", - enabled: true, - }, - ]); - }).pipe( - Effect.provideService( - AcpRegistrySupport.AcpRegistryCatalog, - AcpRegistrySupport.AcpRegistryCatalog.of({ - search: () => Effect.die("unused search"), - prepare: () => Effect.die("unused prepare"), - inspect: () => Effect.die("unused inspect"), - uninstallManagedBinary: () => Effect.die("unused uninstall"), - resolve: () => - Effect.succeed({ - agent: { - id: "mock-agent", - name: "Mock Agent", - version: "1.0.0", - description: "ACP probe test agent", - distribution: { npx: { package: "mock-agent@1.0.0" } }, - }, - distribution: "npx", - spawn: { - command: "node", - args: [mockAgentPath], - env: { - ...process.env, - T3_ACP_COMMAND_ADVERTISEMENT_DELAY_MS: "25", - }, - }, - }), - }), - ), - Effect.provide(NodeServices.layer), - Effect.scoped, - ), - ); - - it.effect("includes package resolution in the probe timeout", () => - Effect.gen(function* () { - const resolveStarted = yield* Deferred.make(); - const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ - search: () => Effect.die("unused search"), - prepare: () => Effect.die("unused prepare"), - inspect: () => Effect.die("unused inspect"), - uninstallManagedBinary: () => Effect.die("unused uninstall"), - resolve: () => - Deferred.succeed(resolveStarted, undefined).pipe(Effect.andThen(Effect.never)), - }); - const probe = yield* probeAcpRegistryConfiguration({ - instanceId, - settings: decodeSettings({ agentId: "slow-agent" }), - cwd: process.cwd(), - environment: process.env, - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), - Effect.flip, - Effect.forkChild({ startImmediately: true }), - ); - - yield* Deferred.await(resolveStarted); - yield* TestClock.adjust("60 seconds"); - - expect(yield* Fiber.join(probe)).toMatchObject({ - reason: "probe_failed", - message: expect.stringContaining("within 60 seconds"), - }); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), - ); - it.effect("lists native sessions and logs out through generic ACP lifecycle methods", () => { const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ search: () => Effect.die("unused search"), @@ -514,50 +374,6 @@ describe("ACP Registry probe", () => { ); }); - it.effect("preserves the ACP method error for unsupported session management", () => { - const catalog = AcpRegistrySupport.AcpRegistryCatalog.of({ - search: () => Effect.die("unused search"), - prepare: () => Effect.die("unused prepare"), - inspect: () => Effect.die("unused inspect"), - uninstallManagedBinary: () => Effect.die("unused uninstall"), - resolve: () => - Effect.succeed({ - agent: { - id: "mock-agent", - name: "Mock Agent", - version: "1.0.0", - description: "ACP unsupported management test agent", - distribution: { npx: { package: "mock-agent@1.0.0" } }, - }, - distribution: "npx" as const, - spawn: { - command: "node", - args: [mockAgentPath], - env: { ...process.env, T3_ACP_OMIT_SESSION_LIST_HANDLER: "1" }, - }, - }), - }); - - return Effect.gen(function* () { - const failure = yield* listAcpRegistrySessions({ - instanceId, - settings: decodeSettings({ agentId: "mock-agent" }), - cwd: process.cwd(), - environment: process.env, - }).pipe(Effect.flip); - - expect(failure).toMatchObject({ - reason: "session_list_unsupported", - message: "The ACP agent does not advertise session listing.", - cause: { _tag: "AcpRequestError", code: -32601 }, - }); - }).pipe( - Effect.provideService(AcpRegistrySupport.AcpRegistryCatalog, catalog), - Effect.provide(NodeServices.layer), - Effect.scoped, - ); - }); - it("distinguishes authentication failures from generic probe failures", () => { const advertised = normalizeAcpRegistryAuthMethods([ { id: "grok-login", name: "Log in with Grok" }, diff --git a/apps/server/src/provider/AntigravityAuth.test.ts b/apps/server/src/provider/AntigravityAuth.test.ts index 02e8b691a1334..af156a61663f4 100644 --- a/apps/server/src/provider/AntigravityAuth.test.ts +++ b/apps/server/src/provider/AntigravityAuth.test.ts @@ -63,6 +63,7 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( const authenticated = yield* Deferred.make(); const discovered = yield* Deferred.make(); const closed = yield* Deferred.make(); + const authenticateCalled = yield* Deferred.make(); const events: string[] = []; let receiveAuthorizationUrl: | ((url: string) => Effect.Effect) @@ -93,6 +94,7 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( start: () => Effect.gen(function* () { events.push("authenticate"); + yield* Deferred.succeed(authenticateCalled, undefined); if (options.interactive !== false && input.onAuthorizationUrl) { for (const url of options.authorizationUrls ?? [authorizationUrl]) { yield* input.onAuthorizationUrl(url); @@ -130,6 +132,7 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( authenticated, discovered, closed, + authenticateCalled, events, catalog: () => catalog, forwarded: () => forwarded, @@ -143,21 +146,6 @@ const makeHarness = Effect.fn("makeAuthTestHarness")(function* ( }); it.layer(NodeServices.layer)("AntigravityAuth", (it) => { - it.effect("accepts the same authorization URL from stderr and stdout", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ - authorizationUrls: [authorizationUrl, authorizationUrl], - }); - yield* harness.auth.controller.start(owner); - const waiting = yield* phase(harness.auth, "waiting"); - assert.equal(waiting.authorizationUrl, authorizationUrl); - - yield* Deferred.succeed(harness.authenticated, undefined); - yield* Deferred.succeed(harness.discovered, undefined); - yield* phase(harness.auth, "succeeded"); - }), - ); - it.effect("accepts a delayed duplicate after callback completion starts", () => Effect.gen(function* () { const harness = yield* makeHarness(); @@ -270,6 +258,38 @@ it.layer(NodeServices.layer)("AntigravityAuth", (it) => { }), ); + it.effect("tells the user when the agent cannot reach Google", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ interactive: false }); + yield* harness.auth.controller.start(owner); + yield* Deferred.await(harness.authenticateCalled); + + yield* TestClock.adjust("30 seconds"); + const stalled = yield* harness.auth.controller.subscribe(owner).pipe( + Stream.filter((state) => state.message?.includes("Broken IPv6") === true), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + assert.equal(stalled.phase, "starting"); + + yield* TestClock.adjust("270 seconds"); + const failed = yield* phase(harness.auth, "failed"); + assert.include(failed.message ?? "", "could not reach Google"); + }), + ); + + it.effect("keeps the expired message once the Google link was shown", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* harness.auth.controller.start(owner); + yield* phase(harness.auth, "waiting"); + + yield* TestClock.adjust("300 seconds"); + const failed = yield* phase(harness.auth, "failed"); + assert.equal(failed.message, "Google sign-in expired. Start sign-in again."); + }), + ); + it.effect("accepts direct local or cached completion without a callback RPC", () => Effect.gen(function* () { const harness = yield* makeHarness({ interactive: false }); @@ -352,24 +372,6 @@ it.layer(NodeServices.layer)("AntigravityAuth", (it) => { }), ); - it.effect("expires the flow at the official deadline and removes its URL", () => - Effect.gen(function* () { - const harness = yield* makeHarness(); - const state = yield* harness.auth.controller.start(owner); - yield* phase(harness.auth, "waiting"); - yield* TestClock.adjust("300 seconds"); - const failed = yield* phase(harness.auth, "failed"); - assert.include(failed.message ?? "", "expired"); - assert.isNull(failed.authorizationUrl); - yield* Deferred.await(harness.closed); - const late = yield* harness.auth.controller - .complete(owner, { flowId: state.flowId!, callbackUrl }) - .pipe(Effect.exit); - assert.isTrue(Exit.isFailure(late)); - assert.equal(harness.forwarded(), 0); - }), - ); - it.effect("survives subscriber disconnect and does not replace a competing client's flow", () => Effect.gen(function* () { const harness = yield* makeHarness(); @@ -422,45 +424,6 @@ it.layer(NodeServices.layer)("AntigravityAuth", (it) => { }), ); - it.effect("signs out after a slow packaged runtime starts", () => - Effect.gen(function* () { - const entered = yield* Deferred.make(); - const initialized = yield* Deferred.make(); - const harness = yield* makeHarness({ - beforeInitialize: Deferred.succeed(entered, undefined).pipe( - Effect.andThen(Deferred.await(initialized)), - ), - }); - const logout = yield* harness.auth.controller.logout(Effect.void).pipe(Effect.forkScoped); - yield* Deferred.await(entered); - yield* TestClock.adjust("47 seconds"); - yield* Deferred.succeed(initialized, undefined); - assert.equal((yield* Fiber.join(logout)).phase, "idle"); - assert.include(harness.events, "logout"); - assert.deepEqual(harness.catalog(), []); - yield* Deferred.await(harness.closed); - }), - ); - - it.effect("closes a stalled sign-out process without clearing its account catalog", () => - Effect.gen(function* () { - const entered = yield* Deferred.make(); - const harness = yield* makeHarness({ - beforeInitialize: Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never)), - }); - const logout = yield* harness.auth.controller - .logout(Effect.void) - .pipe(Effect.exit, Effect.forkScoped); - yield* Deferred.await(entered); - yield* TestClock.adjust("90 seconds"); - assert.isTrue(Exit.isFailure(yield* Fiber.join(logout))); - yield* Deferred.await(harness.closed); - assert.notInclude(harness.events, "logout"); - assert.deepEqual(harness.catalog(), ["previous-account-model"]); - yield* harness.auth.withProcess(Effect.void, Effect.void).pipe(Effect.scoped); - }), - ); - it.effect( "sign-out interrupts startup without interrupting its caller after startup returns", () => diff --git a/apps/server/src/provider/AntigravityAuth.ts b/apps/server/src/provider/AntigravityAuth.ts index ea1c8f7448cc2..a2026faa78d26 100644 --- a/apps/server/src/provider/AntigravityAuth.ts +++ b/apps/server/src/provider/AntigravityAuth.ts @@ -31,6 +31,13 @@ import { import type { ProviderAuthController } from "./ProviderAuthService.ts"; const AUTH_TIMEOUT_MS = 300_000; +// A healthy agent shows the Google link or finishes within seconds. Its bundled Python has no +// IPv4 fallback race, so a host with broken IPv6 waits about two minutes per Google request. +const NO_RESPONSE_HINT_MS = 30_000; +const NO_RESPONSE_MESSAGE = + "Antigravity has not reached Google after 30 seconds. Check this machine's network connection. Broken IPv6 is a common cause."; +const UNREACHABLE_MESSAGE = + "Antigravity could not reach Google. Check this machine's network connection, then start sign-in again."; const FORWARDING_FAILED_MESSAGE = "Could not deliver the sign-in response. Start sign-in again."; const isSetupError = Schema.is(ProviderSetupError); const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); @@ -261,9 +268,20 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < ), ); - const runSignIn = (flow: AuthFlow, stopSessions: Effect.Effect) => - Effect.gen(function* () { + const runSignIn = Effect.fn("AntigravityAuth.runSignIn")( + function* (flow: AuthFlow, stopSessions: Effect.Effect) { yield* stopSessions.pipe(Effect.ensuring(stopOwnedProcesses)); + yield* Effect.sleep(NO_RESPONSE_HINT_MS).pipe( + Effect.andThen( + lock.withPermits(1)( + Effect.gen(function* () { + if (activeFlow !== flow || flow.state.phase !== "starting") return; + yield* publishFlow(flow, { ...flow.state, message: NO_RESPONSE_MESSAGE }); + }), + ), + ), + Effect.forkScoped, + ); const runtime = yield* options.makeRuntime({ onAuthorizationUrl: (url) => receiveAuthorizationUrl(flow, url), }); @@ -281,16 +299,26 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < }), ); yield* options.onAuthenticated(started, runtime); - }).pipe( - Effect.scoped, - Effect.timeoutOrElse({ - duration: AUTH_TIMEOUT_MS, - orElse: () => - Effect.fail(setupError("start", "Google sign-in expired. Start sign-in again.")), - }), - Effect.exit, - Effect.flatMap((result) => finishFlow(flow, result)), - ); + }, + (effect, flow, stopSessions) => + effect.pipe( + Effect.scoped, + Effect.timeoutOrElse({ + duration: AUTH_TIMEOUT_MS, + orElse: () => + Effect.fail( + setupError( + "start", + flow.state.phase === "starting" + ? UNREACHABLE_MESSAGE + : "Google sign-in expired. Start sign-in again.", + ), + ), + }), + Effect.exit, + Effect.flatMap((result) => finishFlow(flow, result)), + ), + ); const stopFlow = (flow: AuthFlow, phase: "cancelled" | "failed", message: string) => Effect.uninterruptible( @@ -322,18 +350,21 @@ export const makeAntigravityAuth = Effect.fn("makeAntigravityAuth")(function* < }), ); - const requireFlow = (ownerSessionId: string, flowId: string, name: string) => - Effect.gen(function* () { - const flow = activeFlow; - if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) { - return yield* setupError(name, "This sign-in is no longer active in this client."); - } - const now = yield* Clock.currentTimeMillis; - if (now >= flow.expiresAtMillis) { - return yield* setupError(name, "Google sign-in expired. Start sign-in again."); - } - return flow; - }); + const requireFlow = Effect.fn("AntigravityAuth.requireFlow")(function* ( + ownerSessionId: string, + flowId: string, + name: string, + ) { + const flow = activeFlow; + if (!flow || flow.id !== flowId || flow.ownerSessionId !== ownerSessionId) { + return yield* setupError(name, "This sign-in is no longer active in this client."); + } + const now = yield* Clock.currentTimeMillis; + if (now >= flow.expiresAtMillis) { + return yield* setupError(name, "Google sign-in expired. Start sign-in again."); + } + return flow; + }); const controller: ProviderAuthController = { start: (ownerSessionId, stopSessions = Effect.void) => diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index 2817b21594291..363eb4b78858a 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -11,23 +11,14 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; -import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; -import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as AntigravityInstallation from "./AntigravityInstallation.ts"; -import { ANTIGRAVITY_AUTH_BROWSER_MARKER } from "./antigravityAuthSupport.ts"; -import { - resolveAntigravityReleaseAsset, - type AntigravityReleaseAsset, -} from "./antigravityRelease.ts"; - -import antigravityInitialize from "../../../../packages/effect-acp/test/fixtures/antigravity-initialize.json" with { type: "json" }; +import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; const serverContents = "antigravity runtime\n"; const harnessContents = "local harness\n"; @@ -52,10 +43,7 @@ const zipFixtures = { "UEsDBBQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAYWd5X2FjcF9zZXJ2ZXIuZXhlS8wryUwvSizLLKlUKCoFcnJTuQBQSwMEFAAAAAgAAAAiXV9yAykQAAAADgAAABkAAABsb2NhbGhhcm5lc3NfZXh0ZXJuYWwuZXhly8lPTsxRyEgsykstLuYCAFBLAQIUAxQAAAAIAAAAIl1zEy/oFAAAABQAAAASAAAAAAAAAAAAAADtgQAAAABhZ3lfYWNwX3NlcnZlci5leGVQSwECFAMUAAAACAAAACJdX3IDKRAAAAAOAAAAGQAAAAAAAAAAAAAA7YFEAAAAbG9jYWxoYXJuZXNzX2V4dGVybmFsLmV4ZVBLBQYAAAAAAgACAIcAAACLAAAAAAA=", }; -// The installation checks POSIX exec bits off the real filesystem unless the -// platform is win32, so a linux platform mock cannot pass on NTFS. Default to -// the host and let the fixture names follow; the suite is about install -// mechanics, which are the same on every platform. +// Linux platform mocks cannot enforce POSIX exec bits on NTFS; use the host platform. const hostPlatform: NodeJS.Platform = HostProcess.Platform.defaultValue() === "win32" ? "win32" : "linux"; const completeArchive = Buffer.from( @@ -307,256 +295,9 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { }), ); - it.effect.each( - [ - { - name: "the expected release with protocol 1", - protocolVersion: 1, - agentName: "antigravity-acp", - version: "fixture-new", - valid: true, - }, - { - name: "the expected release with protocol 2 and legacy fields", - protocolVersion: 2, - agentName: "antigravity-acp", - version: "fixture-new", - valid: true, - }, - { - name: "an unsupported protocol version", - protocolVersion: 3, - agentName: "antigravity-acp", - version: "fixture-new", - valid: false, - }, - { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false }, - { - name: "a different version", - agentName: "antigravity-acp", - version: "other-version", - valid: false, - }, - { - name: "the Windows ARM release with locked child processes", - platform: "win32" as const, - arch: "arm64" as const, - agentName: "antigravity-acp", - version: "fixture-new", - valid: true, - }, - { - name: "an invalid Windows ARM release with locked child processes", - platform: "win32" as const, - arch: "arm64" as const, - agentName: "antigravity-acp", - version: "other-version", - valid: false, - }, - { - name: "a cancelled Windows ARM verification with locked child processes", - platform: "win32" as const, - arch: "arm64" as const, - agentName: "antigravity-acp", - version: "fixture-new", - cancel: true, - valid: false, - }, - ].flatMap((testCase) => { - const cleanupErrorTags = - testCase.platform === "win32" - ? (["Unknown", "PermissionDenied", "Busy"] as const) - : (["Unknown"] as const); - return cleanupErrorTags.map((cleanupErrorTag) => ({ - ...testCase, - cleanupErrorTag, - name: `${cleanupErrorTag}: ${testCase.name}`, - })); - }), - )("validates $name with initialize only and removes the disposable profile", (testCase) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const platform = testCase.platform ?? hostPlatform; - const encoder = new TextEncoder(); - const decodeRequest = Schema.decodeUnknownEffect( - Schema.fromJsonString( - Schema.Struct({ - id: Schema.Union([Schema.String, Schema.Number]), - method: Schema.String, - }), - ), - ); - const methods: string[] = []; - const profiles = new Set(); - const cleanupRetryStarted = yield* Deferred.make(); - const initializationStarted = yield* Deferred.make(); - let childProcessesRunning = false; - let profileRemovalAttempts = 0; - let closedRuntimes = 0; - const spawner = ChildProcessSpawner.make( - Effect.fn("test.spawnAntigravityValidator")(function* (command) { - if (command._tag !== "StandardCommand") { - return yield* Effect.die("Expected one validation process."); - } - const profile = command.options.env?.GEMINI_HOME; - if (!profile) return yield* Effect.die("Expected a disposable validation profile."); - profiles.add(profile); - const helper = command.args[0] === "-e"; - if (!helper) childProcessesRunning = true; - if (!helper) { - if (platform === "win32") { - expect(command.options.env?.TEMP).toBe(profile); - expect(command.options.env?.TMP).toBe(profile); - } else { - expect(command.options.env?.TMPDIR).toBe(profile); - } - } - const output = yield* Queue.unbounded(); - const exited = yield* Deferred.make(); - const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe( - Effect.asVoid, - ); - yield* Effect.addFinalizer(() => - terminate.pipe( - Effect.andThen(Queue.shutdown(output)), - Effect.andThen( - Effect.sync(() => { - if (!helper) closedRuntimes += 1; - }), - ), - ), - ); - return ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(helper ? 1 : 2), - exitCode: helper - ? Effect.succeed(ChildProcessSpawner.ExitCode(0)) - : Deferred.await(exited), - isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)), - kill: () => - Effect.sync(() => { - if (!helper) childProcessesRunning = false; - }).pipe(Effect.andThen(terminate)), - unref: Effect.succeed(Effect.void), - stdin: Sink.forEach((bytes: Uint8Array) => - Effect.gen(function* () { - const request = yield* decodeRequest(new TextDecoder().decode(bytes)).pipe( - Effect.orDie, - ); - methods.push(request.method); - if (testCase.cancel) { - yield* Deferred.succeed(initializationStarted, undefined); - return; - } - yield* Queue.offer( - output, - encoder.encode( - `${encodeJsonString({ - jsonrpc: "2.0", - id: request.id, - ...(request.method === "initialize" - ? { - result: { - ...antigravityInitialize, - protocolVersion: testCase.protocolVersion ?? 2, - agentInfo: { name: testCase.agentName, version: testCase.version }, - }, - } - : { - error: { - code: -32601, - message: "Validation must not sign in or create sessions.", - }, - }), - })}\n`, - ), - ); - }), - ), - stdout: helper ? Stream.empty : Stream.fromQueue(output), - stderr: helper - ? Stream.make( - encoder.encode( - `${ANTIGRAVITY_AUTH_BROWSER_MARKER}${encodeJsonString(command.args.at(-1))}\n`, - ), - ) - : Stream.empty, - all: Stream.empty, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }); - }), - ); - const { installation, stagingReleased } = yield* makeHarness({ - previous: true, - useDefaultValidation: true, - platform, - ...(testCase.arch ? { arch: testCase.arch } : {}), - archive: - platform === "win32" ? Buffer.from(zipFixtures.windows, "base64") : completeArchive, - fileSystem: FileSystem.FileSystem.of({ - ...fs, - remove: (target, options) => - Effect.suspend(() => { - if (platform === "win32" && profiles.has(target)) { - profileRemovalAttempts += 1; - expect(childProcessesRunning).toBe(false); - // Even after the tree exits, Windows can briefly retain a DLL handle. - if (profileRemovalAttempts === 1) { - return Deferred.succeed(cleanupRetryStarted, undefined).pipe( - Effect.andThen( - Effect.fail( - PlatformError.systemError({ - _tag: testCase.cleanupErrorTag, - module: "FileSystem", - method: "remove", - description: "Unpacked DLL is in use", - }), - ), - ), - ); - } - } - return fs.remove(target, options); - }), - }), - }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); - const started = yield* installation.start; - const cancellation = testCase.cancel - ? yield* Deferred.await(initializationStarted).pipe( - Effect.andThen(installation.cancel(started.operationId!)), - Effect.forkChild, - ) - : undefined; - if (platform === "win32") { - yield* Effect.raceFirst( - Deferred.await(cleanupRetryStarted).pipe(Effect.andThen(TestClock.adjust("100 millis"))), - terminalState(installation), - ); - } - if (cancellation) yield* Fiber.join(cancellation); - expect((yield* terminalState(installation)).phase).toBe( - testCase.cancel ? "cancelled" : testCase.valid ? "succeeded" : "failed", - ); - yield* Deferred.await(stagingReleased); - expect(methods).toEqual(["initialize"]); - expect(closedRuntimes).toBe(1); - expect(profiles.size).toBe(1); - if (platform === "win32") expect(profileRemovalAttempts).toBe(2); - for (const profile of profiles) { - expect(yield* fs.exists(profile)).toBe(false); - } - if (testCase.valid) { - expect((yield* installation.resolve()).version).toBe("fixture-new"); - } else { - yield* expectPreviousRelease(installation); - } - }), - ); - it.effect("accepts an encoded Content-Length when the body is compressed", () => Effect.gen(function* () { - // dl.google.com gzips the archive and reports the encoded size. The decoded - // stream is still checked byte for byte and by hash. + // dl.google.com reports the gzip-encoded size; byte and hash checks use the decoded stream. const { installation, validations } = yield* makeHarness({ contentLength: completeArchive.byteLength - 1_000, contentEncoding: "gzip", @@ -828,8 +569,7 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { }), ); - // Real posix executables in a real temp dir, resolved by a linux-mocked - // PATH walk; a Windows temp path cannot be split on `:`. + // The mocked Linux PATH walk needs POSIX paths; Windows temp paths contain colons. it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "honors explicit paths and reports invalid overrides without falling back", () => @@ -1051,28 +791,4 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { expect(requests).toEqual([]); }), ); - - it("resolves all supported platform release assets including Intel Mac", () => { - const supportedPlatforms: Array<{ readonly platform: NodeJS.Platform; readonly arch: string }> = - [ - { platform: "darwin", arch: "arm64" }, - { platform: "darwin", arch: "x64" }, - { platform: "linux", arch: "x64" }, - { platform: "linux", arch: "arm64" }, - { platform: "win32", arch: "x64" }, - { platform: "win32", arch: "arm64" }, - ]; - - for (const { platform, arch } of supportedPlatforms) { - const asset = resolveAntigravityReleaseAsset(platform, arch); - expect(asset).not.toBeNull(); - expect(asset?.version).toBe("1.3.0"); - expect(asset?.url).toContain("1.3.0"); - expect(asset?.archiveBytes).toBeGreaterThan(0); - expect(asset?.executable.bytes).toBeGreaterThan(0); - expect(asset?.harness.bytes).toBeGreaterThan(0); - } - - expect(resolveAntigravityReleaseAsset("freebsd", "x64")).toBeNull(); - }); }); diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index b73d26a906530..3d590abda0bdb 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -24,6 +24,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as NodeCrypto from "node:crypto"; import * as NodeFSP from "node:fs/promises"; +import * as EffectAcpErrors from "effect-acp/errors"; import * as ServerConfig from "../config.ts"; import { openZipArchive } from "../zipArchive.ts"; @@ -69,6 +70,7 @@ export class AntigravityInstallationError extends Schema.TaggedError { + if (isInstallationError(cause)) return cause; + const detail = + isAcpProcessExitedError(cause) && + /\b(?:AF_INET6|enforce_kernel_ipv6_support)\b/.test(cause.stderr ?? "") + ? "Antigravity requires IPv6 socket support. Enable IPv6 in this environment. On WSL, remove ipv6.disable=1 from .wslconfig and run wsl --shutdown." + : "The downloaded Antigravity runtime could not start in this environment."; + return installationError("verify", detail, cause); + }), ); const install = Effect.fn("AntigravityInstallation.install")( @@ -459,7 +460,6 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma { flag: "wx", mode: 0o600 }, ); yield* fs.rename(pointerPath, activePath); - // The pointer commits the install. Later temp cleanup cannot undo it. yield* SubscriptionRef.update( state, (current) => @@ -526,9 +526,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const response = yield* http .execute(HttpClientRequest.get(asset.url)) .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); - // dl.google.com gzips the zip when the client accepts it, so - // `content-length` is the encoded size. The decoded stream is still - // checked against the pinned byte count and hash below. + // dl.google.com may gzip the zip: content-length is encoded, while byte/hash checks use decoded data. const contentLength = response.headers["content-length"]; const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase(); const identityBody = contentEncoding === undefined || contentEncoding === "identity"; diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts index be709add4f60f..ade033551f655 100644 --- a/apps/server/src/provider/AntigravityProvider.test.ts +++ b/apps/server/src/provider/AntigravityProvider.test.ts @@ -15,7 +15,6 @@ import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; @@ -179,23 +178,6 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* ( }); describe("Antigravity model catalog", () => { - it("keeps the captured personal catalog's IDs, labels, order, and selected default", () => { - const models = buildAntigravityModelsFromSession(sessionSetupResult); - expect(models.map((model) => [model.slug, model.name])).toEqual( - modelOptions.map((option) => [option.value, option.name]), - ); - expect(models.filter((model) => model.isDefault).map((model) => model.slug)).toEqual([ - "gemini-3.7-flash-high", - ]); - expect( - models - .filter((model) => model.aliases?.includes(ANTIGRAVITY_DEFAULT_MODEL)) - .map((model) => model.slug), - ).toEqual(["gemini-3.7-flash-high"]); - expect(models.every((model) => model.capabilities?.optionDescriptors?.length === 0)).toBe(true); - expect(models.every((model) => !model.isCustom)).toBe(true); - }); - it("uses legacy session models only when model config is absent", () => { const fromLegacy = buildAntigravityModelsFromSession({ models: sessionSetupResult.models, @@ -257,45 +239,6 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { ), ); - it.effect("ignores account updates while disabled", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness({ enabled: false }); - yield* harness.provider.onSessionStarted(started); - yield* harness.provider.onAvailableCommands(commands); - yield* harness.provider.onSignedOut; - const snapshot = yield* harness.provider.snapshot.refresh; - expect(snapshot).toMatchObject({ - enabled: false, - installed: false, - status: "disabled", - auth: { status: "unknown" }, - models: [], - slashCommands: [], - workspaceSnapshots: [], - }); - expect(yield* Ref.get(harness.probeCalls)).toBe(0); - }), - ), - ); - - it.effect("publishes the configured sign-in method before any account is checked", () => - Effect.scoped( - Effect.gen(function* () { - const provider = yield* makeAntigravityProvider(decodeSettings({ enabled: true }), { - stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }), - probe: Effect.succeed(initializeResult), - supportsTextGeneration: Effect.succeed(true), - auth: { type: "gemini-api-key", label: "Gemini API key" }, - }); - expect((yield* provider.snapshot.getSnapshot).auth).toEqual({ - status: "unknown", - type: "gemini-api-key", - }); - }), - ), - ); - it.effect("treats initialize as installation proof, not account or model discovery", () => Effect.scoped( Effect.gen(function* () { @@ -351,21 +294,6 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { ), ); - it.effect("does not retain a disposable sign-in workspace", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - yield* harness.provider.onSessionStarted(started); - yield* harness.provider.onAvailableCommands(commands); - const snapshot = yield* harness.provider.snapshot.getSnapshot; - expect(snapshot.models).toHaveLength(11); - expect(snapshot.slashCommands).toEqual(expectedCommands); - expect(snapshot.workspaceSnapshots).toEqual([]); - }), - ), - ); - it.effect("clears all account metadata on sign-out and authentication failure", () => Effect.scoped( Effect.gen(function* () { @@ -444,30 +372,6 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { ), ); - it.effect("accepts a known version from a later installation 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.3.0" }, - }, - }); - yield* Ref.set( - harness.probe, - Effect.succeed({ - ...initializeResult, - agentInfo: { ...initializeResult.agentInfo, version: "1.4.0" }, - }), - ); - expect((yield* harness.provider.snapshot.refresh).version).toBe("1.4.0"); - }), - ), - ); - it.effect("does not replace a handshake version with an unknown custom-launcher probe", () => Effect.scoped( Effect.gen(function* () { @@ -539,58 +443,6 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => { ), ); - it.effect("allows a slow packaged runtime health check to finish", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const entered = yield* Deferred.make(); - const initialized = yield* Deferred.make(); - yield* Ref.set( - harness.probe, - Deferred.succeed(entered, undefined).pipe(Effect.andThen(Deferred.await(initialized))), - ); - - const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); - yield* Deferred.await(entered); - yield* TestClock.adjust("47 seconds"); - yield* Deferred.succeed(initialized, initializeResult); - const snapshot = yield* Fiber.join(refresh); - - expect(snapshot).toMatchObject({ - installed: true, - status: "warning", - auth: { status: "unknown" }, - }); - }), - ), - ); - - it.effect("closes a stalled health probe at its deadline", () => - Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.initialize; - const entered = yield* Deferred.make(); - const closed = yield* Deferred.make(); - yield* Ref.set( - harness.probe, - Deferred.succeed(entered, undefined).pipe( - Effect.andThen(Effect.never), - Effect.ensuring(Deferred.succeed(closed, undefined)), - ), - ); - const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild); - yield* Deferred.await(entered); - yield* TestClock.adjust("90 seconds"); - const snapshot = yield* Fiber.join(refresh); - yield* Deferred.await(closed); - expect(snapshot.status).toBe("error"); - expect(snapshot.message).toContain("90 seconds"); - }), - ), - ); - it.effect("distinguishes missing executables from a failed installed executable", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts index 1c1f3d9a56d9c..c6809c3577132 100644 --- a/apps/server/src/provider/AntigravityProvider.ts +++ b/apps/server/src/provider/AntigravityProvider.ts @@ -160,9 +160,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func draft: initialDraft, authRevision: 0, }); - // Skills the driver discovered on disk per workspace. Session callbacks - // rewrite the workspace entry with native commands and must keep these, or - // the registry drops the suggestions and never re-reads the workspace. + // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them. const discoveredSkills = new Map(); const getSnapshot = SubscriptionRef.get(metadata).pipe( Effect.flatMap((state) => options.stampIdentity(state.draft)), @@ -211,8 +209,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func draft: { ...draft, installed: !missingInstallation, - // Custom launchers have no static version; their lightweight probe - // must not erase the version learned from a real ACP handshake. + // Lightweight custom-launcher probes lack versions; preserve the real handshake's version. version: version === "unknown" ? draft.version : version || draft.version, status: errorMessage ? "error" : authenticated ? "ready" : "warning", checkedAt: updatedAt, diff --git a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts index 54616bb3e8959..80740b0a21d49 100644 --- a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts +++ b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts @@ -1,65 +1,11 @@ // @effect-diagnostics nodeBuiltinImport:off - cleanup uses Node's retrying rm, which the FileSystem service does not expose. -import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; import { vi } from "vite-plus/test"; -import * as Deferred from "effect/Deferred"; -import * as Fiber from "effect/Fiber"; -import * as TestClock from "effect/testing/TestClock"; -import { - ClaudeSettings, - ProviderDriverKind, - ProviderInstanceId, - type ServerProvider, -} from "@t3tools/contracts"; -import * as NodeFSP from "node:fs/promises"; -import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; -import * as Schema from "effect/Schema"; -import { - buildClaudeCapabilitiesProbeQueryOptions, - CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES, - probeClaudeCapabilities, - probeClaudeWorkspaceSnapshot, -} from "./ClaudeProvider.ts"; -import { COMPACT_SLASH_COMMAND } from "@t3tools/provider-core/server/snapshotProbe"; +import { buildClaudeCapabilitiesProbeQueryOptions } from "./ClaudeProvider.ts"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); -const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings); - -it("isolates Claude capability probes without dropping workspace setting sources", () => { - const abortController = new AbortController(); - const options = buildClaudeCapabilitiesProbeQueryOptions({ - executablePath: "/usr/bin/claude", - abortController, - environment: { - HOME: "/home/user", - ENABLE_CLAUDEAI_MCP_SERVERS: "true", - FORCE_CODE_TERMINAL: "1", - }, - cwd: "/workspace/project", - managedMcpConfig: false, - }); - - assert.deepEqual(options.mcpServers, {}); - assert.equal(options.strictMcpConfig, true); - assert.equal(options.cwd, "/workspace/project"); - assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]); - assert.deepEqual(options.settings, { disableAllHooks: true }); - assert.deepEqual(options.allowedTools, []); - assert.equal(options.persistSession, false); - assert.equal(options.pathToClaudeCodeExecutable, "/usr/bin/claude"); - assert.equal(options.abortController, abortController); - assert.equal(options.env?.HOME, "/home/user"); - assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false"); - assert.equal(options.env?.FORCE_CODE_TERMINAL, undefined); - assert.equal(options.env?.CLAUDE_CODE_AUTO_CONNECT_IDE, "0"); - assert.equal(options.env?.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL, "1"); -}); - it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => { const options = buildClaudeCapabilitiesProbeQueryOptions({ executablePath: "/usr/bin/claude", @@ -74,317 +20,3 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp assert.deepEqual(options.mcpServers, {}); assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false"); }); - -it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => { - it.effect( - "discovers commands and skills separately for each cwd without replacing machine metadata", - () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-workspaces-" }); - const configDir = path.join(tempDir, "claude-home"); - const workspaces = [path.join(tempDir, "one"), path.join(tempDir, "two")]; - for (const cwd of workspaces) { - const skillDir = path.join(cwd, ".claude", "skills", "existing-skill"); - yield* fs.makeDirectory(skillDir, { recursive: true }); - yield* fs.writeFileString( - path.join(skillDir, "SKILL.md"), - "---\nname: existing-skill\ndescription: Existing project skill\n---\nUse this skill.", - ); - } - const machineSnapshot = { - instanceId: ProviderInstanceId.make("claude"), - driver: ProviderDriverKind.make("claudeAgent"), - enabled: true, - installed: true, - status: "ready", - auth: { status: "authenticated", email: "machine@example.com" }, - checkedAt: "2026-03-25T00:00:00.000Z", - version: "2.1.288", - models: [], - slashCommands: [{ name: "server-cwd-only" }], - skills: [], - } satisfies ServerProvider; - let usageCalls = 0; - const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => { - assert.equal(options?.env?.CLAUDE_CONFIG_DIR, configDir); - assert.equal(options?.env?.T3_WORKSPACE_PROBE, "owned-instance"); - return { - initializationResult: async () => ({ - account: { email: "workspace@example.com" }, - commands: [ - { - name: options?.cwd === workspaces[0] ? "start-session" : "other-project", - description: "Project command", - argumentHint: "[topic]", - }, - { name: "nested:review", description: "Review changes", argumentHint: "" }, - { name: "NESTED:review", description: "", argumentHint: "[path]" }, - { name: "compact", description: "Provider compact", argumentHint: "" }, - { name: "user-command", description: "Existing user command", argumentHint: "" }, - ], - }), - usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => { - usageCalls++; - return { rate_limits_available: false, rate_limits: null }; - }, - } as ReturnType; - }); - yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); - for (const [index, cwd] of workspaces.entries()) { - const scoped = yield* probeClaudeWorkspaceSnapshot( - decodeClaudeSettings({ homePath: configDir }), - machineSnapshot, - cwd, - { ...process.env, T3_WORKSPACE_PROBE: "owned-instance" }, - ); - assert.deepEqual(scoped, { - ...machineSnapshot, - slashCommandsPending: false, - slashCommands: [ - COMPACT_SLASH_COMMAND, - { - name: index === 0 ? "start-session" : "other-project", - description: "Project command", - input: { hint: "[topic]" }, - }, - { name: "nested:review", description: "Review changes", input: { hint: "[path]" } }, - { name: "user-command", description: "Existing user command" }, - ], - skills: [ - { - name: "existing-skill", - path: path.join(cwd, ".claude", "skills", "existing-skill", "SKILL.md"), - enabled: true, - scope: "project", - description: "Existing project skill", - }, - ], - }); - } - assert.deepEqual( - query.mock.calls.map(([input]) => input.options?.cwd), - workspaces, - ); - assert.equal(usageCalls, 0); - }).pipe(Effect.scoped), - ); - - it.effect("keeps readable skills during failed command discovery and recovers on retry", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-workspace-retry-" }); - const skillDir = path.join(cwd, ".claude", "skills", "existing-skill"); - yield* fs.makeDirectory(skillDir, { recursive: true }); - yield* fs.writeFileString( - path.join(skillDir, "SKILL.md"), - "---\nname: existing-skill\ndescription: Existing project skill\n---\nUse this skill.", - ); - const machineSnapshot = { - instanceId: ProviderInstanceId.make("claude"), - driver: ProviderDriverKind.make("claudeAgent"), - enabled: true, - installed: true, - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-03-25T00:00:00.000Z", - version: "2.1.288", - models: [], - slashCommands: [{ name: "server-cwd-only" }], - skills: [], - } satisfies ServerProvider; - const query = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: () => - Promise.reject( - new Error("Initialization failed"), - ), - usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({ - rate_limits_available: false, - rate_limits: null, - }), - }) as ReturnType, - ); - yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); - const settings = decodeClaudeSettings({ homePath: cwd }); - const failed = yield* probeClaudeWorkspaceSnapshot(settings, machineSnapshot, cwd); - assert.deepEqual(failed, { - ...machineSnapshot, - slashCommands: [COMPACT_SLASH_COMMAND], - slashCommandsPending: true, - skills: [ - { - name: "existing-skill", - path: path.join(skillDir, "SKILL.md"), - enabled: true, - scope: "project", - description: "Existing project skill", - }, - ], - }); - query.mockImplementation( - () => - ({ - initializationResult: async () => ({ - commands: [{ name: "recovered", description: "", argumentHint: "" }], - }), - usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({ - rate_limits_available: false, - rate_limits: null, - }), - }) as ReturnType, - ); - const recovered = yield* probeClaudeWorkspaceSnapshot(settings, machineSnapshot, cwd); - assert.deepEqual(recovered.slashCommands, [COMPACT_SLASH_COMMAND, { name: "recovered" }]); - assert.equal(recovered.status, "ready"); - assert.equal(recovered.slashCommandsPending, false); - assert.deepEqual(recovered.skills, failed.skills); - const disabled = yield* probeClaudeWorkspaceSnapshot( - { ...settings, enabled: false }, - machineSnapshot, - cwd, - ); - assert.equal(disabled, machineSnapshot); - assert.equal(query.mock.calls.length, 2); - }).pipe(Effect.scoped), - ); - - it.effect("serializes strict no-MCP options and still resolves account capabilities", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" }); - const executablePath = yield* path.fromFileUrl( - new URL("./testing/ClaudeCapabilitiesProbe.fixture.mjs", import.meta.url), - ); - const invocationPath = path.join(tempDir, "invocation.json"); - // The probe aborts the SDK without awaiting the child's exit, and on - // Windows a directory that is still some process's cwd cannot be - // removed. Keep the workspace outside the scoped directory and let it - // go with a retrying removal once the child has gone. - const workspaceCwd = yield* fs.makeTempDirectory({ prefix: "t3-claude-probe-cwd-" }); - // Node's own retry rather than an Effect schedule: it.effect runs on a - // TestClock, so a scheduled retry would wait for time nobody advances. - yield* Effect.addFinalizer(() => - Effect.promise(() => - NodeFSP.rm(workspaceCwd, { - recursive: true, - force: true, - maxRetries: 20, - retryDelay: 250, - }).catch(() => undefined), - ), - ); - - const capabilities = yield* probeClaudeCapabilities( - decodeClaudeSettings({ binaryPath: executablePath }), - { - ...process.env, - T3_PROBE_INVOCATION_PATH: invocationPath, - ENABLE_CLAUDEAI_MCP_SERVERS: "true", - }, - workspaceCwd, - ); - - assert.deepEqual(capabilities, { - email: "dev@example.com", - subscriptionType: "pro", - tokenSource: "oauth", - apiKeySource: undefined, - apiProvider: undefined, - slashCommands: [ - { - name: "review", - description: "Review changes", - input: { hint: "[path]" }, - }, - ], - usage: { - rate_limits_available: true, - rate_limits: { five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" } }, - }, - }); - - const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as { - readonly args: ReadonlyArray; - readonly cwd: string; - readonly connectorEnv: string; - readonly mcpConfig: unknown; - }; - assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd)); - assert.equal(invocation.connectorEnv, "false"); - assert.equal(invocation.args.includes("--strict-mcp-config"), true); - assert.equal(invocation.args.includes("--mcp-config"), false); - assert.equal(invocation.mcpConfig, undefined); - - assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true); - - const settingsFlagIndex = invocation.args.indexOf("--settings"); - assert.notEqual(settingsFlagIndex, -1); - const flagSettings = JSON.parse(invocation.args[settingsFlagIndex + 1] ?? "{}") as { - readonly disableAllHooks?: boolean; - }; - assert.equal(flagSettings.disableAllHooks, true); - }).pipe(Effect.scoped), - ); -}); - -it.effect("preserves initialized capabilities when optional usage times out", () => - Effect.gen(function* () { - const usageStarted = yield* Deferred.make(); - let abortSignal: AbortSignal | undefined; - const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(({ options }) => { - abortSignal = options?.abortController?.signal; - return { - initializationResult: async () => ({ - account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" }, - commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }], - }), - usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: () => { - Deferred.doneUnsafe(usageStarted, Effect.void); - return new Promise(() => {}); - }, - } as ReturnType; - }); - yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); - const probe = yield* probeClaudeCapabilities( - decodeClaudeSettings({ binaryPath: "claude" }), - ).pipe(Effect.forkChild); - yield* Deferred.await(usageStarted); - yield* TestClock.adjust("4 seconds"); - const capabilities = yield* Fiber.join(probe); - assert.equal(capabilities?.email, "dev@example.com"); - assert.equal(capabilities?.subscriptionType, "pro"); - assert.equal(capabilities?.tokenSource, "oauth"); - assert.deepEqual(capabilities?.slashCommands, [ - { name: "review", description: "Review changes", input: { hint: "[path]" } }, - ]); - assert.equal(capabilities?.usage, undefined); - assert.equal(abortSignal?.aborted, true); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -it.effect("asks for usage without the local transcript scan", () => - Effect.gen(function* () { - let usageOptions: unknown; - const query = vi.spyOn(ClaudeSdk, "query").mockImplementation( - () => - ({ - initializationResult: async () => ({ - account: { email: "dev@example.com", subscriptionType: "max", tokenSource: "oauth" }, - commands: [], - }), - usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async (options?: unknown) => { - usageOptions = options; - return { rate_limits_available: true, rate_limits: null }; - }, - }) as unknown as ReturnType, - ); - yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); - yield* probeClaudeCapabilities(decodeClaudeSettings({ binaryPath: "claude" })); - assert.deepEqual(usageOptions, { skipBehaviors: true }); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/provider/ClaudeModelCatalog.test.ts b/apps/server/src/provider/ClaudeModelCatalog.test.ts index da61038215d82..2092429f6d556 100644 --- a/apps/server/src/provider/ClaudeModelCatalog.test.ts +++ b/apps/server/src/provider/ClaudeModelCatalog.test.ts @@ -1,7 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; -import { hasValidClaudeManifestAdapters } from "./ClaudeModelManifest.ts"; import { resolveProviderCatalog, type ModelManifestData } from "./ModelManifest.ts"; import { formatClaudeVersionUpgradeMessage, @@ -171,37 +170,6 @@ describe("Claude model catalog", () => { ); }); - it("rejects malformed adapter mappings", () => { - const base = manifest(); - const malformed: ModelManifestData = { - ...base, - providers: { - ...base.providers, - claudeAgent: { - ...base.providers!.claudeAgent!, - profiles: { - ...base.providers!.claudeAgent!.profiles, - synthetic: { - ...base.providers!.claudeAgent!.profiles.synthetic!, - adapter: { claudeCode: { effortMap: { extreme: 123 } } }, - }, - }, - }, - }, - }; - assert.isFalse(hasValidClaudeManifestAdapters(malformed)); - }); - - it("preserves only SDK effort levels for uncatalogued models", () => { - const catalog = catalogFromManifest(manifest()); - for (const effort of ["low", "medium", "high", "xhigh", "max"]) { - assert.strictEqual(resolveClaudeCatalogEffort(catalog, "custom", ` ${effort} `), effort); - } - for (const effort of [undefined, null, "", " ", "brutal", "extreme", "HIGH", "ultrathink"]) { - assert.isUndefined(resolveClaudeCatalogEffort(catalog, "custom", effort)); - } - }); - it("appends custom models with their own descriptors and keeps bare slugs opaque", () => { const catalog = scopeClaudeModelCatalog(catalogFromManifest(manifest()), [ "synthetic", diff --git a/apps/server/src/provider/ClaudeModelCatalog.testFixtures.ts b/apps/server/src/provider/ClaudeModelCatalog.testFixtures.ts index 1a686b62c38c8..762f919dc39c1 100644 --- a/apps/server/src/provider/ClaudeModelCatalog.testFixtures.ts +++ b/apps/server/src/provider/ClaudeModelCatalog.testFixtures.ts @@ -3,7 +3,7 @@ import type { ClaudeModelCatalog } from "./ClaudeModelCatalog.ts"; export const SYNTHETIC_CLAUDE_CAPABLE_MODEL = "claude-synthetic-capable"; export const SYNTHETIC_CLAUDE_COLLIDING_ALIAS = "synthetic-collision"; export const SYNTHETIC_CLAUDE_STANDARD_MODEL = "claude-synthetic-standard"; -export const SYNTHETIC_CLAUDE_THINKING_MODEL = "claude-synthetic-thinking"; +const SYNTHETIC_CLAUDE_THINKING_MODEL = "claude-synthetic-thinking"; const effort = { id: "effort", @@ -71,7 +71,9 @@ export const SYNTHETIC_CLAUDE_MODEL_CATALOG: ClaudeModelCatalog = { name: "Claude Synthetic Thinking", isCustom: false, capabilities: { - optionDescriptors: [{ id: "thinking", label: "Thinking", type: "boolean" }], + optionDescriptors: [ + { id: "thinking", label: "Thinking", type: "boolean", currentValue: true }, + ], }, }, runtime: {}, diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 6b7907dd5c4fa..4c6a86dbc3815 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -5,6 +5,7 @@ import { type ServerProviderSlashCommand, type ServerProviderResetCredits, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -167,11 +168,7 @@ function apiProviderAuthMetadata( return apiProvider === "bedrock" ? { type: "bedrock", label: "Amazon Bedrock" } : undefined; } -/** - * The capability probe resolves for a logged-out CLI, so a completed probe only proves Claude - * Code started. `tokenSource: "none"` is the CLI reporting it found no token at all, and is the - * one shape that disproves authentication. - */ +/** Probe completion only proves Claude started. Only tokenSource: "none" disproves auth. */ function claudeAuthStatus( capabilities: Pick< ClaudeCapabilitiesProbe, @@ -182,19 +179,19 @@ function claudeAuthStatus( return "authenticated"; } if (capabilities.tokenSource !== "none") return "authenticated"; - // An `ANTHROPIC_API_KEY` install reports no token source but is authenticated - // all the same, so the key and account fields still get a say. + // API keys can authenticate with tokenSource: none; also check key and account fields. const hasApiKey = Boolean(capabilities.apiKeySource) && capabilities.apiKeySource !== "none"; return hasApiKey || capabilities.email || capabilities.subscriptionType ? "authenticated" : "unauthenticated"; } -// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the Bedrock -// backend and runs the `awsAuthRefresh` credential hook before returning account info. +// Bedrock initialization includes backend startup and awsAuthRefresh, taking longer than first-party auth. const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000; +// Native CLI startup on Windows can exceed the shared probe deadline. +const CLAUDE_VERSION_CHECK_TIMEOUT_MS = 20_000; -export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [ +const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [ "user", "project", "local", @@ -212,23 +209,17 @@ export function buildClaudeCapabilitiesProbeQueryOptions(input: { pathToClaudeCodeExecutable: input.executablePath, abortController: input.abortController, settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES], - // The probe keeps filesystem setting sources for slash-command discovery, - // but must not run the user's hooks: it fires every few minutes, so - // SessionStart hooks would run on every health check. + // Keep settings for slash-command discovery, but disable hooks so health checks do not run SessionStart repeatedly. settings: { disableAllHooks: true }, allowedTools: [], - // Ignore MCP definitions from every filesystem setting source above. The - // SDK combines this empty explicit map with --strict-mcp-config, which - // Claude refuses next to a managed-mcp.json that already excludes them. + // Exclude filesystem MCP servers; omit strict mode when managed-mcp.json already excludes them and forbids the flag. mcpServers: {}, ...(input.managedMcpConfig ? {} : { strictMcpConfig: true }), env: { ...input.environment, - // Connected claude.ai MCP servers are discovered outside filesystem - // config; disable them independently for this health check. + // Disable claude.ai MCP separately; it is discovered outside filesystem config. ENABLE_CLAUDEAI_MCP_SERVERS: "false", - // Skipping it also avoids Claude spawning a Windows `tasklist | findstr` process tree on - // every periodic refresh. + // Skipping this avoids a Windows tasklist | findstr process tree on every refresh. FORCE_CODE_TERMINAL: undefined, CLAUDE_CODE_AUTO_CONNECT_IDE: "0", CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL: "1", @@ -243,25 +234,18 @@ function nonEmptyProbeString(value: string): string | undefined { return candidate ? candidate : undefined; } -type ClaudeCapabilitiesProbe = { +export type ClaudeCapabilitiesProbe = { readonly email: string | undefined; readonly workspaceId?: string | undefined; readonly subscriptionType: string | undefined; readonly tokenSource: string | undefined; readonly apiKeySource: string | undefined; - /** - * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth - * login only applies when `"firstParty"`; for Amazon Bedrock (`"bedrock"`) - * the subscription/token fields are absent and auth is external AWS creds. - */ + /** OAuth applies only to firstParty; Bedrock uses external AWS credentials and omits subscription/token fields. */ readonly apiProvider: string | undefined; readonly slashCommands: ReadonlyArray; - /** - * Subscription windows from the SDK's `get_usage` control request, or - * `undefined` when the request itself failed. Absent windows on an - * otherwise successful response mean the account has none (API key). - */ + /** Undefined means get_usage failed; absent windows on success mean no subscription windows, as with API keys. */ readonly usage?: Pick; + readonly usageCheckedAt?: string; }; function parseClaudeInitializationCommands( @@ -336,12 +320,7 @@ function waitForAbortSignal(signal: AbortSignal): Promise { }); } -/** - * We pass a never-yielding AsyncIterable as the prompt so that no user message is ever written - * to the subprocess stdin. This means the Claude Code subprocess completes its local - * initialization IPC (returning account info and slash commands) but never starts an API - * request to Anthropic. - */ +/** A never-yielding prompt allows local initialization IPC without sending an Anthropic request. */ const probeClaudeCapabilities = ( claudeSettings: ClaudeSettings, environment?: NodeJS.ProcessEnv, @@ -358,9 +337,7 @@ const probeClaudeCapabilities = ( const managedMcpConfig = yield* hasClaudeManagedMcpConfig(); return yield* Effect.tryPromise(async () => { const q = claudeQuery({ - // Never yield — we only need initialization data, not a conversation. - // This prevents any prompt from reaching the Anthropic API. - // oxlint-disable-next-line require-yield + // oxlint-disable-next-line require-yield -- never yields, so no prompt reaches the API prompt: (async function* (): AsyncGenerator { await waitForAbortSignal(abort.signal); })(), @@ -382,6 +359,7 @@ const probeClaudeCapabilities = ( // Usage has its own deadline so a slow optional request cannot discard initialization. // Only the rate limits are read, so skip the local transcript scan that fills // `behaviors`: with a few GB of transcripts it outlasts the deadline. + const usageCheckedAt = DateTime.formatIso(yield* DateTime.now); const usageResult = includeUsage ? yield* Effect.tryPromise(() => q.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true }), @@ -410,7 +388,7 @@ const probeClaudeCapabilities = ( apiKeySource: account?.apiKeySource, apiProvider: account?.apiProvider, slashCommands: parseClaudeInitializationCommands(init.commands), - ...(usage ? { usage } : {}), + ...(usage ? { usage, usageCheckedAt } : {}), } satisfies ClaudeCapabilitiesProbe; }), ), @@ -419,11 +397,14 @@ const probeClaudeCapabilities = ( if (!abort.signal.aborted) abort.abort(); }), ), - Effect.result, - Effect.map((result) => (Result.isSuccess(result) ? result.success : undefined)), + Effect.tapError((error) => + Effect.logWarning("Claude capability probe failed.", { errorTag: error._tag }), + ), ); }; +type ClaudeCapabilitiesProbeError = Effect.Error>; + const runClaudeCommand = Effect.fn("runClaudeCommand")(function* ( claudeSettings: ClaudeSettings, args: ReadonlyArray, @@ -450,7 +431,10 @@ export const probeClaudeWorkspaceSnapshot = Effect.fn("probeClaudeWorkspaceSnaps ): Effect.fn.Return { if (!claudeSettings.enabled) return machineSnapshot; const skills = yield* discoverClaudeSkills(claudeSettings, cwd, environment); - const capabilities = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false); + const probeResult = yield* probeClaudeCapabilities(claudeSettings, environment, cwd, false).pipe( + Effect.result, + ); + const capabilities = Result.isSuccess(probeResult) ? probeResult.success : undefined; return { ...machineSnapshot, skills, @@ -466,7 +450,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( claudeSettings: ClaudeSettings, resolveCapabilities?: ( claudeSettings: ClaudeSettings, - ) => Effect.Effect, + ) => Effect.Effect, environment?: NodeJS.ProcessEnv, cwd?: string, modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG, @@ -507,7 +491,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( ["--version"], resolvedEnvironment, cwd, - ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result); + ).pipe(Effect.timeoutOption(CLAUDE_VERSION_CHECK_TIMEOUT_MS), Effect.result); if (Result.isFailure(versionProbe)) { const error = versionProbe.failure; @@ -579,9 +563,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const updateRequiredModels = resolveClaudeUpdateRequiredModels(modelCatalog, parsedVersion); const versionUpgradeMessage = formatClaudeVersionUpgradeMessage(modelCatalog, parsedVersion); - const capabilities = resolveCapabilities - ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined)) + const probeResult = resolveCapabilities + ? yield* resolveCapabilities(claudeSettings).pipe(Effect.result) : undefined; + const capabilities = + probeResult && Result.isSuccess(probeResult) ? probeResult.success : undefined; + const probeFailure = + probeResult && Result.isFailure(probeResult) ? probeResult.failure : undefined; const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment); const slashCommands = [COMPACT_SLASH_COMMAND, ...(capabilities?.slashCommands ?? [])]; const dedupedSlashCommands = dedupeSlashCommands(slashCommands); @@ -600,12 +588,23 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( version: parsedVersion, status: "warning", auth: { status: "unknown" }, - message: "Could not verify Claude authentication status from initialization result.", + message: probeFailure + ? Cause.isTimeoutError(probeFailure) + ? `Timed out after ${CAPABILITIES_PROBE_TIMEOUT_MS / 1_000}s while checking Claude account status.` + : "Claude Agent CLI failed while checking account status." + : "Could not verify Claude authentication status from initialization result.", }, }); } - if (claudeAuthStatus(capabilities) === "unauthenticated") { + // First-party account fields cannot verify custom endpoint credentials. + const endpoint = URL.parse(resolvedEnvironment.ANTHROPIC_BASE_URL?.trim() ?? ""); + const customApiEndpoint = + endpoint !== null && + (endpoint.protocol === "http:" || endpoint.protocol === "https:") && + endpoint.hostname !== "" && + endpoint.hostname !== "api.anthropic.com"; + if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") { return buildServerProvider({ presentation: CLAUDE_PRESENTATION, enabled: claudeSettings.enabled, @@ -627,15 +626,21 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( claudeAuthMetadata({ subscriptionType: capabilities.subscriptionType, authMethod: capabilities.tokenSource, - }) ?? apiProviderAuthMetadata(capabilities.apiProvider); + }) ?? + apiProviderAuthMetadata(capabilities.apiProvider) ?? + (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined); + const usageCheckedAt = capabilities.usageCheckedAt ?? checkedAt; const usageLimits = !capabilities.usage ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed" }) : scopedLimitNames ? yield* recordClaudeUsageResponse(scopedLimitNames, { response: capabilities.usage, - checkedAt, + checkedAt: usageCheckedAt, }) - : claudeUsageResponseToLimits({ response: capabilities.usage, checkedAt }).limits; + : claudeUsageResponseToLimits({ + response: capabilities.usage, + checkedAt: usageCheckedAt, + }).limits; const resetCredits = resolveResetCredits && capabilities.subscriptionType && @@ -669,11 +674,11 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const nowIso = Effect.map(DateTime.now, DateTime.formatIso); -export const makePendingClaudeProvider = ( - claudeSettings: ClaudeSettings, - modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG, -): Effect.Effect => - Effect.gen(function* () { +export const makePendingClaudeProvider = Effect.fn("ClaudeProvider.makePendingClaudeProvider")( + function* ( + claudeSettings: ClaudeSettings, + modelCatalog: ClaudeModelCatalog = BUNDLED_CLAUDE_MODEL_CATALOG, + ): Effect.fn.Return { const checkedAt = yield* nowIso; const models = providerModelsFromSettings( modelCatalog.models.map((entry) => entry.model), @@ -710,6 +715,7 @@ export const makePendingClaudeProvider = ( message: "Claude provider status has not been checked in this session yet.", }, }); - }); + }, +); export { probeClaudeCapabilities }; diff --git a/apps/server/src/provider/ClaudeTurnTokenUsage.ts b/apps/server/src/provider/ClaudeTurnTokenUsage.ts index 43b60d21fffa5..89cb3de6ed556 100644 --- a/apps/server/src/provider/ClaudeTurnTokenUsage.ts +++ b/apps/server/src/provider/ClaudeTurnTokenUsage.ts @@ -23,8 +23,7 @@ function addKnownCount(finalCount: unknown, earlierCounts: ReadonlyArray, earlierSegmentUsage: ReadonlyArray, diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 859537b25cb6d..3e521103d56cf 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -1,4 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Local mock OAuth server validates the browser callback boundary. +import * as NodeNet from "node:net"; +import * as Context from "effect/Context"; +import * as Scope from "effect/Scope"; +import * as ServerConfig from "../config.ts"; +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; import * as NodeHttp from "node:http"; import * as NodeCrypto from "node:crypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -10,14 +15,12 @@ import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; import * as Fiber from "effect/Fiber"; import * as Deferred from "effect/Deferred"; -import * as TestClock from "effect/testing/TestClock"; import { subscribeChatGptHandoff } from "./CodexChatGptHandoff.ts"; -import { FetchHttpClient } from "effect/http"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; import { exportJWK, generateKeyPair, SignJWT } from "jose"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; -import * as ServerSettings from "../serverSettings.ts"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; @@ -220,6 +223,7 @@ const makeHarnessFor = Effect.fnUntraced(function* ( analyticsEvents.push({ event, properties }); }), flush: Effect.void, + recordOwners: () => Effect.void, }); const auth = yield* makeCodexChatGptAuth({ instanceId, @@ -321,6 +325,16 @@ const makeHarnessFor = Effect.fnUntraced(function* ( ); return { auth: destination, bytes: destinationBytes }; }), + bindProfile: (expectedProfileKey: string) => + makeCodexChatGptAuth({ + instanceId, + expectedProfileKey, + discoveryUrl: `${origin}/discovery`, + resource: `${origin}/v1`, + }).pipe( + Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), + ), recreateAuth: makeCodexChatGptAuth({ instanceId, discoveryUrl: `${origin}/discovery`, @@ -454,33 +468,6 @@ it.effect.each(["identity", "sharing"] as const)( }), ), ); -it.effect("retains the callback host and path after controller recreation and token removal", () => - provision( - Effect.gen(function* () { - const bytes = new Map(); - const first = yield* makeHarnessFor(instanceId, bytes); - yield* first.signIn; - yield* first.phase("succeeded"); - const redirectUri = first.authorizationRequests[0]!.searchParams.get("redirect_uri"); - yield* first.auth.revoke; - const restarted = yield* makeHarnessFor(instanceId, bytes); - yield* restarted.signIn; - yield* restarted.phase("succeeded"); - assert.strictEqual( - restarted.authorizationRequests[0]!.searchParams.get("client_id"), - "oaiapp_test", - ); - assertSameCallback( - restarted.authorizationRequests[0]!.searchParams.get("redirect_uri"), - redirectUri, - ); - assert.strictEqual( - restarted.exchanges[0]!.get("redirect_uri"), - restarted.authorizationRequests[0]!.searchParams.get("redirect_uri"), - ); - }), - ), -); it.effect("reauthorizes on an available port when the original callback port is occupied", () => provision( Effect.gen(function* () { @@ -513,30 +500,6 @@ it.effect("reauthorizes on an available port when the original callback port is }), ), ); - -it.effect("registers a fresh client when the original registration is no longer stored", () => - provision( - Effect.gen(function* () { - const bytes = new Map(); - const h = yield* makeHarnessFor(instanceId, bytes); - yield* h.signIn; - yield* h.phase("succeeded"); - for (const [key, value] of bytes) { - const record = JSON.parse(new TextDecoder().decode(value)); - if (record.profiles) bytes.delete(key); - } - h.setCallbackClientId("oaiapp_replacement"); - yield* h.signIn; - yield* h.phase("succeeded"); - assert.strictEqual( - h.authorizationRequests[1]!.searchParams.get("client_id"), - "dynamic_agent_client", - ); - assert.strictEqual(h.exchanges[1]!.get("client_id"), "oaiapp_replacement"); - assert.strictEqual(Option.getOrThrow(yield* h.auth.read).clientId, "oaiapp_replacement"); - }), - ), -); it.effect("reauthorizes a registration without persisting its original port", () => provision( Effect.gen(function* () { @@ -715,20 +678,6 @@ it.effect( }), ), ); -it.effect("preserves the Welcome agents step and strips unrelated callback return parameters", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - h.setReturnUrl("http://localhost:7001/welcome?code=never-forward#agents:test-environment"); - yield* h.signIn; - assert.include( - h.callbackResponses[0]!.body, - 'content="1;url=http://localhost:7001/welcome#agents:test-environment"', - ); - assert.notInclude(h.callbackResponses[0]!.body, "never-forward"); - }), - ), -); it.effect( "does not redirect to an arbitrary return URL or claim success after verification fails", () => @@ -891,60 +840,6 @@ it.effect( }), ), ); -it.effect("revoked connection clears tokens but preserves registration for reconnect", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - yield* h.seedExpired; - h.setRevoked(); - yield* h.auth.access.pipe(Effect.result); - assert.isTrue(Option.isNone(yield* h.auth.read)); - assert.deepEqual(h.storedRecords(), [ - { - profiles: [ - { - clientId: "oaiapp_test", - connectionLabel: "Connection 1", - sharingEnabled: true, - redirectUri: h.authorizationRequests[0]!.searchParams.get("redirect_uri"), - subject: "user-test", - email: "hidden@example.test", - }, - ], - lastClientId: "oaiapp_test", - }, - ]); - yield* h.signIn; - yield* h.phase("succeeded"); - assert.strictEqual(h.authorizationRequests[1]?.searchParams.get("client_id"), "oaiapp_test"); - }), - ), -); - -it.effect("fresh sign-in ignores a registration left by the old disconnect behavior", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - yield* h.auth.revoke; - assert.isTrue(Option.isNone(yield* h.auth.read)); - assert.strictEqual(h.storedRecords().length, 1); - h.setCallbackClientId("oaiapp_new_workspace"); - h.setIdentity("new-workspace-user", "new@example.test"); - yield* h.changeAccount; - yield* h.phase("succeeded"); - assert.strictEqual( - h.authorizationRequests[1]!.searchParams.get("client_id"), - "dynamic_agent_client", - ); - assert.strictEqual(Option.getOrThrow(yield* h.auth.read).clientId, "oaiapp_new_workspace"); - assert.strictEqual(Option.getOrThrow(yield* h.auth.read).subject, "new-workspace-user"); - }), - ), -); it.effect("rejects mismatched callback state before any token exchange or credential write", () => provision( @@ -996,25 +891,6 @@ it.effect.each([ ), ); -it.effect("returns successful desktop sign-in to the original Welcome step", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - h.setReturnUrl("t3code-dev://app/welcome#agents:test-environment"); - yield* h.signIn; - yield* h.phase("succeeded"); - assert.include( - h.callbackResponses[0]!.body, - 'content="1;url=t3code-dev://app/welcome#agents:test-environment"', - ); - assert.include( - h.callbackResponses[0]!.body, - 'href="t3code-dev://app/welcome#agents:test-environment"', - ); - }), - ), -); - it.effect( "completes remote sign-in on the owning environment and reuses its exact callback for reauthorization", () => @@ -1206,44 +1082,6 @@ it.effect( ), ); -it.effect("fresh sign-in to the same identity preserves separate registration profiles", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - h.setIdentity("other-user", "other@example.test"); - h.setCallbackClientId("oaiapp_other_account"); - yield* h.changeAccount; - yield* h.phase("succeeded"); - h.setIdentity("user-test", "hidden@example.test"); - h.setCallbackClientId("oaiapp_replacement"); - yield* h.changeAccount; - const changed = yield* h.phase("succeeded"); - assert.deepEqual( - changed - .methods!.filter((method) => method.id.startsWith("chatgpt-profile:")) - .map((method) => method.id), - [ - "chatgpt-profile:oaiapp_replacement", - "chatgpt-profile:oaiapp_other_account", - "chatgpt-profile:oaiapp_test", - ], - ); - assert.strictEqual(Option.getOrThrow(yield* h.auth.read).clientId, "oaiapp_replacement"); - const redirectUri = h.authorizationRequests[2]!.searchParams.get("redirect_uri"); - yield* h.auth.controller.logout(Effect.void); - yield* h.reconnectProfile("oaiapp_replacement"); - yield* h.phase("succeeded"); - assert.strictEqual( - h.authorizationRequests[3]!.searchParams.get("client_id"), - "oaiapp_replacement", - ); - assertSameCallback(h.authorizationRequests[3]!.searchParams.get("redirect_uri"), redirectUri); - }), - ), -); - it.effect("preserves legacy profiles with the same email and subject", () => provision( Effect.gen(function* () { @@ -1386,38 +1224,6 @@ it.effect("declined sharing on an older profile does not replace the active acco ), ); -it.effect( - "Disconnect preserves a remote profile's callback URI for client-delivered reconnect", - () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - const first = yield* h.startRemote(); - yield* h.auth.controller.complete("owner", { - flowId: first.waiting.flowId!, - callbackUrl: first.callbackUrl, - }); - yield* h.phase("succeeded"); - yield* h.auth.controller.logout(Effect.void); - const second = yield* h.startRemote(); - assert.strictEqual( - new URL(second.waiting.authorizationUrl!).searchParams.get("client_id"), - "oaiapp_test", - ); - assertSameCallback( - new URL(second.waiting.authorizationUrl!).searchParams.get("redirect_uri"), - new URL(first.waiting.authorizationUrl!).searchParams.get("redirect_uri"), - ); - yield* h.auth.controller.complete("owner", { - flowId: second.waiting.flowId!, - callbackUrl: second.callbackUrl, - }); - yield* h.phase("succeeded"); - assert.strictEqual(Option.getOrThrow(yield* h.auth.read).subject, "user-test"); - }), - ), -); - it.effect.each([ "invalid_grant", "invalid_refresh_token", @@ -1481,23 +1287,6 @@ it.effect( ), ); -it.live("logout retries temporary revocation failures and reports local-only sign-out", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - h.setRevocationStatus(503); - const state = yield* h.auth.controller.logout(Effect.void); - assert.lengthOf(h.revocations, 3); - assert.strictEqual(state.phase, "idle"); - assert.include(state.message!, "Remote revocation could not be confirmed"); - assert.isTrue(Option.isNone(yield* h.auth.read)); - assert.isFalse(h.storedRecords().some((record) => record.idToken)); - }), - ), -); - it.effect( "reauth hints come from the selected profile, including after another profile logs out", () => @@ -1647,26 +1436,6 @@ it.effect( ), ); -it.effect("keeps the active connection first when another profile declines sharing", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - h.setCallbackClientId("oaiapp_identity_only"); - h.setIdentity("other-user", "other@example.test"); - h.declineSharing(); - yield* h.changeAccount; - const state = yield* h.phase("failed"); - assert.strictEqual(Option.getOrThrow(yield* h.auth.read).clientId, "oaiapp_test"); - const profiles = state.methods!.filter((method) => method.id.startsWith("chatgpt-profile:")); - assert.strictEqual(profiles[0]!.id, "chatgpt-profile:oaiapp_test"); - assert.include(profiles[0]!.name, "Connection 1"); - assert.include(profiles[1]!.name, "Connection 2"); - }), - ), -); - it.effect("primary completes OAuth and destination imports and owns the refresh session", () => provision( Effect.gen(function* () { @@ -1839,66 +1608,6 @@ it.effect( ), ); -it.effect("records one anonymous auth outcome per success, failure, or cancellation", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - h.setInvalidNonce(); - yield* h.signIn; - yield* h.phase("failed"); - const { waiting } = yield* h.startRemote(); - yield* h.auth.controller.cancel("owner", waiting.flowId!); - yield* h.phase("cancelled"); - const completed = h.analyticsEvents.filter(({ event }) => event === "chatgpt.auth.completed"); - assert.deepStrictEqual( - completed.map(({ properties }) => properties?.outcome), - ["succeeded", "failed", "cancelled"], - ); - assert.strictEqual( - h.analyticsEvents.filter(({ event }) => event === "chatgpt.auth.started").length, - 3, - ); - assert.strictEqual(completed[1]?.properties?.failureStage, "verify"); - for (const { properties } of completed) { - assert.isNumber(properties?.durationMs); - assert.strictEqual(properties?.flow, "direct"); - assert.deepStrictEqual( - Object.keys(properties!).sort(), - [ - ...(properties?.outcome === "succeeded" - ? [ - "accountCountScope", - "connectedAccountCount", - "connectedConnectionCount", - "savedConnectionCount", - "unidentifiedConnectedConnectionCount", - ] - : []), - "callbackMode", - "durationMs", - ...(properties?.failureStage ? ["failureStage"] : []), - "flow", - "intent", - "outcome", - ].sort(), - ); - } - const serialized = JSON.stringify(h.analyticsEvents); - for (const secret of [ - "hidden@example.test", - "oaiapp_test", - "user-test", - "access_token", - "refresh_token", - ]) { - assert.notInclude(serialized, secret); - } - }), - ), -); - it.effect("telemetry failures do not fail a verified ChatGPT sign-in", () => provision( Effect.gen(function* () { @@ -1910,142 +1619,205 @@ it.effect("telemetry failures do not fail a verified ChatGPT sign-in", () => }), ), ); - -it.effect("counts accounts separately from saved connections across additions and reconnects", () => +it.effect("a running session renews its bound profile but refuses a replacement sign-in", () => provision( Effect.gen(function* () { const h = yield* makeHarness; yield* h.signIn; yield* h.phase("succeeded"); - yield* h.signIn; - yield* h.phase("succeeded"); - h.setCallbackClientId("oaiapp_same_account"); - h.setIdentity("another-client-subject", "HIDDEN@example.test"); - yield* h.changeAccount; - yield* h.phase("succeeded"); - h.setCallbackClientId("oaiapp_other_account"); - h.setIdentity("other-user", "other@example.test"); - yield* h.changeAccount; - yield* h.phase("succeeded"); - yield* h.auth.controller.logout(Effect.void); - h.setCallbackClientId("oaiapp_test"); - h.setIdentity("user-test", "hidden@example.test"); + const profileKey = yield* h.auth.profileKey(Option.getOrThrow(yield* h.auth.read)); + const first = yield* h.bindProfile(profileKey); + const second = yield* h.bindProfile(profileKey); + yield* h.seedExpired; + const renewed = yield* Effect.all([first.access, second.access], { + concurrency: "unbounded", + }); + assert.equal(h.refreshes(), 1); + assert.equal(renewed[0].accessToken, "access-1"); + assert.deepEqual(renewed[0], renewed[1]); + assert.equal(yield* h.auth.profileKey(renewed[0]), profileKey); + + // Reconnecting the same account replaces its sign-in identity, too. yield* h.reconnectProfile("oaiapp_test"); yield* h.phase("succeeded"); - const completed = h.analyticsEvents.filter(({ event }) => event === "chatgpt.auth.completed"); - assert.deepStrictEqual( - completed.map(({ properties }) => [ - properties?.connectedAccountCount, - properties?.connectedConnectionCount, - properties?.savedConnectionCount, - ]), - [ - [1, 1, 1], - [1, 1, 1], - [1, 2, 2], - [2, 3, 3], - [1, 2, 3], - ], - ); - assert.isTrue( - completed.every(({ properties }) => properties?.unidentifiedConnectedConnectionCount === 0), - ); - assert.notInclude(JSON.stringify(h.analyticsEvents), "example.test"); + const replacement = Option.getOrThrow(yield* h.auth.read); + assert.equal(replacement.clientId, renewed[0].clientId); + assert.equal(replacement.subject, renewed[0].subject); + yield* h.seedExpired; + assert.equal((yield* first.access.pipe(Effect.flip)).operation, "access"); + assert.equal(h.refreshes(), 1); + yield* h.auth.revoke; + assert.equal((yield* second.access.pipe(Effect.flip)).operation, "access"); + assert.isTrue(Option.isNone(yield* h.auth.read)); }), ), ); -it.effect("includes accounts from other Codex instances in the environment", () => - provision( +const makeRenewalBroker = Effect.gen(function* () { + const oauthEntered = yield* Deferred.make(); + const oauthRelease = yield* Deferred.make(); + let pauseOAuth = false; + const refreshTokens: string[] = []; + const credentials = { + clientId: "oaiapp_broker", + subject: "broker-user", + idToken: "broker-sign-in", + email: null, + accessToken: "expired-access", + refreshToken: "single-use-refresh", + expiresAt: 0, + earliestRefreshAt: null, + scopes: ["chatgpt.tokens.use.direct"], + }; + const environmentId = EnvironmentId.make("00000000-0000-4000-8000-000000000001"); + const http = HttpClient.make((request) => Effect.gen(function* () { - const bytes = new Map(); - const personal = yield* makeHarnessFor(instanceId, bytes); - const work = yield* makeHarnessFor(ProviderInstanceId.make("managed-work"), bytes); - yield* personal.signIn; - yield* personal.phase("succeeded"); - work.setCallbackClientId("oaiapp_work"); - work.setIdentity("work-user", "work@example.test"); - yield* work.signIn; - yield* work.phase("succeeded"); - const completed = work.analyticsEvents.find( - ({ event }) => event === "chatgpt.auth.completed", - ); - assert.strictEqual(completed?.properties?.accountCountScope, "environment"); - assert.strictEqual(completed?.properties?.connectedAccountCount, 2); - assert.strictEqual(completed?.properties?.connectedConnectionCount, 2); - assert.strictEqual(completed?.properties?.savedConnectionCount, 2); - }).pipe( - Effect.provide( - ServerSettings.layerTest({ - providerInstances: { - [instanceId]: { driver: "codex", enabled: true }, - [ProviderInstanceId.make("managed-work")]: { driver: "codex", enabled: true }, - }, + if (request.url.endsWith("openid-configuration")) { + return HttpClientResponse.fromWeb( + request, + Response.json({ + issuer: "https://auth.openai.com", + authorization_endpoint: "https://auth.openai.com/authorize", + token_endpoint: "https://auth.openai.com/token", + jwks_uri: "https://auth.openai.com/jwks", + }), + ); + } + assert.equal(request.url, "https://auth.openai.com/token"); + assert.equal(request.body._tag, "Uint8Array"); + if (request.body._tag !== "Uint8Array") return yield* Effect.die("Missing refresh body"); + const body = new URLSearchParams(new TextDecoder().decode(request.body.body)); + refreshTokens.push(body.get("refresh_token")!); + yield* Deferred.succeed(oauthEntered, undefined); + if (pauseOAuth) yield* Deferred.await(oauthRelease); + return HttpClientResponse.fromWeb( + request, + Response.json({ + access_token: "renewed-access", + refresh_token: "rotated-refresh", + expires_in: 3600, + token_type: "Bearer", + scope: "chatgpt.tokens.use.direct", }), + ); + }), + ); + return yield* Effect.gen(function* () { + const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId); + yield* store.set(new TextEncoder().encode(JSON.stringify(credentials))); + const auth = yield* makeCodexChatGptAuth({ instanceId }); + const profileKey = yield* auth.profileKey(credentials); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer((exit) => Scope.close(scope, exit)); + const context = yield* Layer.buildWithScope(CodexManagedTokenBroker.layer, scope); + const broker = Context.get(context, CodexManagedTokenBroker.CodexManagedTokenBroker); + const endpoint = yield* broker.endpoint; + yield* Effect.addFinalizer(() => Deferred.succeed(oauthRelease, undefined)); + return { + auth, + store, + broker, + endpoint, + refreshTokens, + request: { version: 1, instanceId, environmentId, profileKey }, + oauthEntered, + oauthRelease, + pause: () => { + pauseOAuth = true; + }, + }; + }).pipe( + Effect.provide(ServerSecretStore.layer), + Effect.provideService(HttpClient.HttpClient, http), + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(environmentId), + }), + ); +}); + +const brokerClient = (endpoint: string, request: unknown) => + Effect.acquireRelease( + Effect.callback<{ socket: NodeNet.Socket; response: Promise }, Error>((resume) => { + const socket = NodeNet.createConnection(endpoint); + let text = ""; + socket.setEncoding("utf8"); + socket.on("data", (chunk) => { + text += chunk; + }); + const response = new Promise((resolve) => socket.once("close", () => resolve(text))); + socket.on("error", () => {}); + socket.once("error", (error) => resume(Effect.fail(error))); + socket.once("connect", () => { + socket.write(JSON.stringify(request) + "\n"); + resume(Effect.succeed({ socket, response })); + }); + return Effect.sync(() => { + if (socket.connecting) socket.destroy(); + }); + }), + ({ socket }) => Effect.sync(() => socket.destroy()), + ); +const provideBroker = (effect: Effect.Effect) => + effect.pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-renewal-test-" }).pipe( + Layer.provideMerge(NodeServices.layer), ), ), - ), -); - -it.effect("an unreadable unrelated profile omits counts without failing sign-in", () => - provision( - Effect.gen(function* () { - const h = yield* makeHarness; - const unrelated = yield* ProviderCredentialStore.make("codex-chatgpt", "codex").pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, h.secrets), - ); - h.bytes.set(unrelated.binding.key, new TextEncoder().encode("invalid")); - yield* h.signIn; - yield* h.phase("succeeded"); - const completed = h.analyticsEvents.find(({ event }) => event === "chatgpt.auth.completed"); - assert.strictEqual(completed?.properties?.outcome, "succeeded"); - assert.notProperty(completed?.properties ?? {}, "connectedAccountCount"); - }).pipe(Effect.provide(ServerSettings.layerTest())), - ), -); + ); -it.effect("reports connections without an email separately from identifiable accounts", () => - provision( +// regression: #16132 a renewal must outlive the Codex helper that asked for it, because the +// refresh token it spends is single-use. +it.effect("server-owned renewal persists rotated credentials after the helper disconnects", () => + provideBroker( Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.signIn; - yield* h.phase("succeeded"); - const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId).pipe( - Effect.provideService(ServerSecretStore.ServerSecretStore, h.secrets), - ); - yield* store.set( - new TextEncoder().encode( - JSON.stringify({ - activeClientId: "oaiapp_test", - sessions: [{ ...Option.getOrThrow(yield* h.auth.read), email: null }], - }), - ), - ); - h.setCallbackClientId("oaiapp_other_account"); - h.setIdentity("other-user", "other@example.test"); - yield* h.changeAccount; - yield* h.phase("succeeded"); - const completed = h.analyticsEvents.findLast( - ({ event }) => event === "chatgpt.auth.completed", - ); - assert.strictEqual(completed?.properties?.connectedAccountCount, 1); - assert.strictEqual(completed?.properties?.connectedConnectionCount, 2); - assert.strictEqual(completed?.properties?.unidentifiedConnectedConnectionCount, 1); + const h = yield* makeRenewalBroker; + h.pause(); + const client = yield* brokerClient(h.endpoint, h.request); + yield* Deferred.await(h.oauthEntered); + client.socket.destroy(); + yield* Effect.promise(() => client.response); + assert.equal(Option.getOrThrow(yield* h.auth.read).refreshToken, "single-use-refresh"); + yield* Deferred.succeed(h.oauthRelease, undefined); + yield* h.broker.awaitIdle; + const persisted = Option.getOrThrow(yield* h.auth.read); + assert.equal(persisted.refreshToken, "rotated-refresh"); + assert.equal((yield* h.auth.access).accessToken, "renewed-access"); + assert.deepEqual(h.refreshTokens, ["single-use-refresh"]); }), ), ); -it.effect("records an expired auth outcome when sign-in reaches its deadline", () => - provision( +it.live("the private broker refuses another environment, instance, or sign-in profile", () => + provideBroker( Effect.gen(function* () { - const h = yield* makeHarness; - yield* h.startRemote(); - yield* TestClock.adjust(300_001); - assert.include((yield* h.phase("failed")).message ?? "", "expired"); - const completed = h.analyticsEvents.filter(({ event }) => event === "chatgpt.auth.completed"); - assert.strictEqual(completed.length, 1); - assert.strictEqual(completed[0]?.properties?.outcome, "expired"); - assert.isAtLeast(completed[0]?.properties?.durationMs as number, 300_000); + const h = yield* makeRenewalBroker; + yield* Effect.forEach( + [ + { + ...h.request, + environmentId: EnvironmentId.make("00000000-0000-4000-8000-000000000002"), + }, + { ...h.request, instanceId: ProviderInstanceId.make("another-instance") }, + { ...h.request, profileKey: "0".repeat(64) }, + ], + (request) => + Effect.scoped( + Effect.gen(function* () { + const client = yield* brokerClient(h.endpoint, request); + assert.equal(yield* Effect.promise(() => client.response), ""); + }), + ), + ); + yield* h.broker.awaitIdle; + assert.deepEqual(h.refreshTokens, []); + const client = yield* brokerClient(h.endpoint, h.request); + assert.deepEqual(JSON.parse(yield* Effect.promise(() => client.response)), { + token: "renewed-access", + }); + yield* h.broker.awaitIdle; + assert.deepEqual(h.refreshTokens, ["single-use-refresh"]); }), ), ); diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.ts index 6a393ace4c605..1051f72814390 100644 --- a/apps/server/src/provider/CodexChatGptAuth.ts +++ b/apps/server/src/provider/CodexChatGptAuth.ts @@ -9,10 +9,13 @@ import { type ProviderInstanceId, } from "@t3tools/contracts"; import { codexCallbackUrl } from "@t3tools/shared/codexAuthHandoff"; +import { hashTelemetryId } from "@t3tools/shared/telemetryId"; import * as Clock from "effect/Clock"; import * as Cause from "effect/Cause"; import * as AnalyticsService from "../telemetry/AnalyticsService.ts"; +import { openAiUserId } from "../telemetry/Identify.ts"; import * as Crypto from "effect/Crypto"; +import * as Hex from "effect/encoding/Hex"; import * as Exit from "effect/Exit"; import { codexAuthCallbackPage, codexAuthReturnUrl } from "./CodexAuthCallbackPage.ts"; import * as Effect from "effect/Effect"; @@ -106,52 +109,52 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* readonly defaultReturnUrl?: string; readonly reconnectProfile?: ChatGptReconnectProfile | null; readonly telemetryFlow?: "direct" | "primary_handoff"; + readonly expectedProfileKey?: string; }) { const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService); const settings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService); - const track = ( + const track = Effect.fn("CodexChatGptAuth.track")(function* ( event: "auth" | "transfer", properties: Readonly>, task: Effect.Effect, expiresAt?: number, - ) => - Effect.gen(function* () { - if (Option.isNone(analytics)) return yield* task; - const record = (name: string, properties: Readonly>) => - analytics.value.record(name, properties).pipe(Effect.ignoreCause); - const startedAt = yield* Clock.currentTimeMillis; - yield* record(`chatgpt.${event}.started`, properties); - return yield* task.pipe( - Effect.onExit((result) => - Effect.gen(function* () { - const endedAt = yield* Clock.currentTimeMillis; - const error = Exit.isFailure(result) - ? Cause.findErrorOption(result.cause) - : Option.none(); - const counts = - Exit.isSuccess(result) && - (event === "transfer" || options.telemetryFlow !== "primary_handoff") - ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({}))) - : {}; - yield* record(`chatgpt.${event}.completed`, { - ...counts, - ...properties, - outcome: Exit.isSuccess(result) - ? "succeeded" - : Cause.hasInterruptsOnly(result.cause) - ? expiresAt !== undefined && endedAt >= expiresAt - ? "expired" - : "cancelled" - : "failed", - durationMs: Math.max(0, endedAt - startedAt), - ...(Option.isSome(error) && isSetupError(error.value) - ? { failureStage: error.value.operation } - : {}), - }); - }), - ), - ); - }); + ) { + if (Option.isNone(analytics)) return yield* task; + const record = (name: string, properties: Readonly>) => + analytics.value.record(name, properties).pipe(Effect.ignoreCause); + const startedAt = yield* Clock.currentTimeMillis; + yield* record(`chatgpt.${event}.started`, properties); + return yield* task.pipe( + Effect.onExit((result) => + Effect.gen(function* () { + const endedAt = yield* Clock.currentTimeMillis; + const error = Exit.isFailure(result) + ? Cause.findErrorOption(result.cause) + : Option.none(); + const counts = + Exit.isSuccess(result) && + (event === "transfer" || options.telemetryFlow !== "primary_handoff") + ? yield* accountCounts.pipe(Effect.catchCause(() => Effect.succeed({}))) + : {}; + yield* record(`chatgpt.${event}.completed`, { + ...counts, + ...properties, + outcome: Exit.isSuccess(result) + ? "succeeded" + : Cause.hasInterruptsOnly(result.cause) + ? expiresAt !== undefined && endedAt >= expiresAt + ? "expired" + : "cancelled" + : "failed", + durationMs: Math.max(0, endedAt - startedAt), + ...(Option.isSome(error) && isSetupError(error.value) + ? { failureStage: error.value.operation } + : {}), + }); + }), + ), + ); + }); const http = yield* HttpClient.HttpClient; const store = yield* ProviderCredentialStore.make("codex-chatgpt", options.instanceId); const registrationStore = yield* ProviderCredentialStore.make( @@ -222,6 +225,18 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* saved.sessions.find((session) => session.clientId === saved.activeClientId), ), ), + // The OpenAI account is the person, so it marks who owns this install. + Effect.tap((credentials) => { + const userId = Option.flatMap(credentials, (saved) => + Option.flatMap(Option.fromUndefinedOr(saved.idToken), openAiUserId), + ); + return Option.isSome(userId) && Option.isSome(analytics) + ? analytics.value.recordOwners( + [{ source: "openai", ownerId: hashTelemetryId(userId.value) }], + "server", + ) + : Effect.void; + }), ); const writeSessions = (saved: typeof Sessions.Type) => encodeSessions(saved).pipe( @@ -291,8 +306,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* for (const session of "sessions" in saved ? saved.sessions : [saved]) { if (!session.scopes.includes(REQUIRED_SCOPE) || connections.has(session.clientId)) continue; connections.add(session.clientId); - // Subjects are client-scoped. Use verified email only for counting locally, - // never export it or merge the underlying profiles. + // Client-scoped subjects need verified email for local counting only; never export email or merge profiles. const email = session.email?.trim().toLowerCase(); if (email) accounts.add(email); else unidentifiedConnectedConnectionCount++; @@ -445,8 +459,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* const savedRegistration = changingAccount ? undefined : registrations.profiles.find((profile) => profile.clientId === selectedClientId); - // Older development registrations used localhost, which cannot be changed on reauth. - // Register a 127.0.0.1 connection instead, preserving the verified account. + // Legacy localhost registrations cannot change on reauth; register 127.0.0.1 while preserving the verified account. const legacyCallback = savedRegistration?.redirectUri?.includes("//localhost:") === true; const registeredClientId = legacyCallback ? undefined : savedRegistration?.clientId; const selectedTokens = (yield* readSessions).sessions.find( @@ -625,8 +638,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* const expectedSubject = savedRegistration?.subject ?? (previous?.clientId === registeredClientId ? previous?.subject : undefined); - // Subjects are checked within the same registration. Legacy callback migration - // registers a new client, whose subject cannot be compared with the old client. + // Compare subjects only within a registration; legacy callback migration creates a new client. if (registeredClientId && expectedSubject && identity.subject !== expectedSubject) return yield* failure( "verify", @@ -713,6 +725,17 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* ), ); }); + // ID tokens survive renewal but change on sign-in. Bind active children to the + // launch profile without putting an identity token or subject in their argv. + const profileKey = (record: CodexChatGptCredentials) => + crypto + .digest( + "SHA-256", + new TextEncoder().encode( + JSON.stringify([record.clientId, record.subject, record.idToken ?? null]), + ), + ) + .pipe(Effect.map(Hex.encode), Effect.orDie); const access = lock.withPermit( withSessionLock( Effect.uninterruptible( @@ -721,6 +744,11 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* if (Option.isNone(saved)) return yield* failure("access", "Sign in with ChatGPT to use managed Codex."); let record = saved.value; + if ( + options.expectedProfileKey !== undefined && + (yield* profileKey(record)) !== options.expectedProfileKey + ) + return yield* failure("access", "The ChatGPT connection changed. Start a new session."); if (!record.scopes.includes(REQUIRED_SCOPE)) return yield* failure( "sharing", @@ -978,6 +1006,7 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* controller: { ...controller, reconnectProfile, importProfile }, read, access, + profileKey, exportProfile, revoke: lock.withPermit(withSessionLock(remove)), }; diff --git a/apps/server/src/provider/CodexDeveloperInstructions.test.ts b/apps/server/src/provider/CodexDeveloperInstructions.test.ts index 0808d89db9d6a..24e38d21b4a37 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.test.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.test.ts @@ -1,118 +1,36 @@ import * as NodeAssert from "node:assert/strict"; -import { - T3_CODE_ORCHESTRATION_INSTRUCTIONS, - T3_CODE_ORCHESTRATION_SECTIONS, -} from "@t3tools/provider-core/server/orchestrationInstructions"; import { describe, it } from "vite-plus/test"; import { buildCodexAdditionalContext, - buildCodexDeveloperInstructions, CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES, } from "./CodexDeveloperInstructions.ts"; describe("buildCodexAdditionalContext", () => { describe.each([ - { model: "gpt-5.3-codex", reasoningEffort: "high" }, { model: "custom-model", modelName: "Custom 🦊 Model", reasoningEffort: "xhigh" }, ])("with runtime $model", (runtime) => { - it.each([ - undefined, - false, - true, - { browser: false, device: false }, - { browser: true, device: false }, - { browser: false, device: true }, - { browser: true, device: true }, - ])("keeps every entry within Codex's per-entry cap with tools %j", (availability) => { - const context = buildCodexAdditionalContext(runtime, availability); - - for (const [key, entry] of Object.entries(context)) { - // Codex counts ceil(UTF-8 bytes / 4) tokens, excluding keys and wrappers. - const bytes = Buffer.byteLength(entry.value, "utf8"); - const limit = CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES; - NodeAssert.ok( - bytes <= limit, - `${key}: ${bytes} UTF-8 bytes exceeds Codex's ${limit}-byte per-entry cap by ${bytes - limit} bytes; split the instructions into separate entries to avoid silent truncation`, - ); - } - }); - }); - - it("delivers all orchestration sections in authored order when keys are sorted", () => { - const context = buildCodexAdditionalContext({ - model: "gpt-5.3-codex", - reasoningEffort: "high", - }); - const sections = Object.keys(context) - .filter((key) => key.startsWith("t3_code_orchestration_")) - .sort() - .map((key) => context[key]!); - - NodeAssert.deepEqual( - sections, - T3_CODE_ORCHESTRATION_SECTIONS.map((value) => ({ kind: "application", value })), - ); - NodeAssert.equal( - sections.map((entry) => entry.value).join("\n\n"), - T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim(), + it.each([undefined, { browser: true, device: true }])( + "keeps every entry within Codex's per-entry cap with tools %j", + (availability) => { + const context = buildCodexAdditionalContext(runtime, availability); + + for (const [key, entry] of Object.entries(context)) { + // Codex counts ceil(UTF-8 bytes / 4) tokens, excluding keys and wrappers. + const bytes = Buffer.byteLength(entry.value, "utf8"); + const limit = CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES; + NodeAssert.ok( + bytes <= limit, + `${key}: ${bytes} UTF-8 bytes exceeds Codex's ${limit}-byte per-entry cap by ${bytes - limit} bytes; split the instructions into separate entries to avoid silent truncation`, + ); + } + }, ); }); }); -describe("buildCodexDeveloperInstructions", () => { - it("appends runtime info after the mode instructions", () => { - const instructions = runtimeInstructions({ - model: "gpt-5.3-codex", - reasoningEffort: "high", - }); - - NodeAssert.match( - buildCodexDeveloperInstructions("default"), - /^# Collaboration Mode: Default/, - ); - NodeAssert.match(instructions, /T3 Code/); - NodeAssert.match(instructions, /Codex harness/); - NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/); - }); - - it("describes Markdown media support in the runtime context in both modes", () => { - { - const instructions = runtimeInstructions({ - model: "gpt-5.3-codex", - reasoningEffort: "high", - }); - NodeAssert.match( - instructions, - /.*embed images and videos.*Markdown.*<\/runtime_info>/, - ); - } - }); - - it("includes runtime info alongside plan mode instructions", () => { - const instructions = runtimeInstructions({ - model: "gpt-5.3-codex", - reasoningEffort: "medium", - }); - - NodeAssert.match(buildCodexDeveloperInstructions("plan"), /^# Plan Mode/); - NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/); - }); - - it("varies with the model and effort of each turn", () => { - const first = runtimeInstructions({ - model: "gpt-5.3-codex", - reasoningEffort: "medium", - }); - const second = runtimeInstructions({ - model: "gpt-5.4", - reasoningEffort: "high", - }); - - NodeAssert.notEqual(first, second); - }); - +describe("Codex runtime context", () => { it("flattens multiline metadata into single-line runtime info", () => { const instructions = runtimeInstructions({ model: "gpt\n5.3\ncodex", @@ -124,43 +42,27 @@ describe("buildCodexDeveloperInstructions", () => { }); }); -describe("T3 browser developer instructions", () => { - const runtime = { model: "gpt-5.3-codex", reasoningEffort: "high" }; - - it("prefers the product-native preview tools in both collaboration modes", () => { - { - const instructions = toolInstructions(runtime, true); - NodeAssert.match(instructions, /t3-code/); - NodeAssert.match(instructions, /preview_status/); - NodeAssert.match(instructions, /preview_open/); - NodeAssert.match(instructions, /Do not switch to global browser skills/); - } - }); - - it("omits the browser block entirely when the preview tools are not attached", () => { - for (const mode of ["default", "plan"] as const) { - const instructions = toolInstructions(runtime, false); - NodeAssert.doesNotMatch(instructions, /preview_status/); - NodeAssert.doesNotMatch(instructions, /preview_open/); - NodeAssert.doesNotMatch(instructions, /T3 Code collaborative browser/); - NodeAssert.doesNotMatch(instructions, /Do not switch to global browser skills/); - NodeAssert.match(buildCodexDeveloperInstructions(mode), //); - NodeAssert.match(buildCodexDeveloperInstructions(mode), /<\/collaboration_mode>/); - } - }); - - it("tracks the turn's MCP configuration rather than defaulting to on", () => { - NodeAssert.match(toolInstructions(runtime, true), /preview_open/); - NodeAssert.doesNotMatch(toolInstructions(runtime, false), /preview_open/); +describe("Codex orchestration context", () => { + it("routes same-child follow-ups to t3_thread_send and independent reviews to delegate_task", () => { + const orchestration = Object.entries(buildCodexAdditionalContext({ model: "gpt-6.1-sol" })) + .filter(([key]) => key.startsWith("t3_code_orchestration_")) + .map(([, entry]) => entry.value) + .join("\n"); + + NodeAssert.ok( + orchestration.includes( + "For independent T3 delegated review rounds, call `delegate_task` again.", + ), + ); + NodeAssert.ok( + orchestration.includes( + "For a follow-up that needs the same child's conversation, use `t3_thread_send` on its `childThreadId`.", + ), + ); + NodeAssert.ok(!orchestration.includes("Do not use `t3_thread_send`")); }); }); function runtimeInstructions(runtime: Parameters[0]) { return buildCodexAdditionalContext(runtime).t3_code_runtime!.value; } -function toolInstructions( - runtime: Parameters[0], - available: boolean, -) { - return buildCodexAdditionalContext(runtime, available).t3_code_tools?.value ?? ""; -} diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 7db4563cb4451..a42766e49aa27 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -1,4 +1,3 @@ -import type { ProviderInteractionMode } from "@t3tools/contracts"; import type { V2TurnStartParams__AdditionalContextEntry } from "effect-codex-app-server/schema"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; @@ -7,11 +6,7 @@ import { T3_CODE_ORCHESTRATION_SECTIONS, } from "@t3tools/provider-core/server/orchestrationInstructions"; -/** - * Codex cuts the middle out of any `additionalContext` value over 1,000 tokens, - * which it counts as UTF-8 bytes divided by four. It does this silently, so - * every value built here has to fit. - */ +/** Codex silently truncates additionalContext values over 1,000 tokens, counted as UTF-8 bytes / 4. */ export const CODEX_ADDITIONAL_CONTEXT_VALUE_MAX_BYTES = 4_000; const T3_CODE_DEVICE_TOOL_INSTRUCTIONS = `## T3 Code devices @@ -28,12 +23,7 @@ const normalizeAvailability = ( ): T3CodeToolAvailability => typeof availability === "boolean" ? { browser: availability, device: false } : availability; -/** - * Describing `preview_*` or `device_*` tools that aren't in the turn's tool list would be worse - * than saying nothing: the instructions actively steer the model away from Playwright, - * agent-browser, and raw simctl/adb, so leaving them in would talk it out of the only automation - * it still has. - */ +/** Instructions for unavailable tools would steer the model away from its remaining automation. */ const toolInstructions = (availability: boolean | T3CodeToolAvailability): string => { const tools = normalizeAvailability(availability); return [ @@ -44,173 +34,19 @@ const toolInstructions = (availability: boolean | T3CodeToolAvailability): strin .join("\n\n"); }; -const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) - -You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. - -## Mode rules (strict) - -You are in **Plan Mode** until a developer message explicitly ends it. - -Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it. - -## Plan Mode vs update_plan tool - -Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`\` block. - -Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error. - -## Execution vs. mutation in Plan Mode - -You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions. - -### Allowed (non-mutating, plan-improving) - -Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples: - -* Reading or searching files, configs, schemas, types, manifests, and docs -* Static analysis, inspection, and repo exploration -* Dry-run style commands when they do not edit repo-tracked files -* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files - -### Not allowed (mutating, plan-executing) - -Actions that implement the plan or change repo-tracked state. Examples: - -* Editing or writing files -* Running formatters or linters that rewrite files -* Applying patches, migrations, or codegen that updates repo-tracked files -* Side-effectful commands whose purpose is to carry out the plan rather than refine it - -When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it. - -## PHASE 1 - Ground in the environment (explore first, ask second) - -Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged. - -Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available. - -Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first. - -Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration. - -## PHASE 2 - Intent chat (what they actually want) - -* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs. -* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask. - -## PHASE 3 - Implementation chat (what/how we'll build) - -* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints. - -## Asking questions - -Critical rules: - -* Strongly prefer using the \`request_user_input\` tool to ask any questions. -* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant. -* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool. - -You SHOULD ask many questions, but each question must: - -* materially change the spec/plan, OR -* confirm/lock an assumption, OR -* choose between meaningful tradeoffs. -* not be answerable by non-mutating commands. - -Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration. - -## Two kinds of unknowns (treat differently) - -1. **Discoverable facts** (repo/system truth): explore first. - - * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants). - * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent. - * If asking, present concrete candidates (paths/service names) + recommend one. - * Never ask questions you can answer from your environment (e.g., "where is this struct"). - -2. **Preferences/tradeoffs** (not discoverable): ask early. - - * These are intent or implementation preferences that cannot be derived from exploration. - * Provide 2-4 mutually exclusive options + a recommended default. - * If unanswered, proceed with the recommended option and record it as an assumption in the final plan. - -## Finalization rule - -Only output the final plan when it is decision complete and leaves no decisions to the implementer. - -When you present the official plan, wrap it in a \`\` block so the client can render it specially: - -1) The opening tag must be on its own line. -2) Start the plan content on the next line (no text on the same line as the tag). -3) The closing tag must be on its own line. -4) Use Markdown inside the block. -5) Keep the tags exactly as \`\` and \`\` (do not translate or rename them), even if the plan content is in another language. - -Example: - - -plan content - - -plan content should be human and agent digestible. The final plan must be plan-only, concise by default, and include: - -* A clear title -* A brief summary section -* Important changes or additions to public APIs/interfaces/types -* Test cases and scenarios -* Explicit assumptions and defaults chosen where needed - -When possible, prefer a compact structure with 3-5 short sections, usually: Summary, Key Changes or Implementation Changes, Test Plan, and Assumptions. Do not include a separate Scope section unless scope boundaries are genuinely important to avoid mistakes. - -Prefer grouped implementation bullets by subsystem or behavior over file-by-file inventories. Mention files only when needed to disambiguate a non-obvious change, and avoid naming more than 3 paths unless extra specificity is necessary to prevent mistakes. Prefer behavior-level descriptions over symbol-by-symbol removal lists. For v1 feature-addition plans, do not invent detailed schema, validation, precedence, fallback, or wire-shape policy unless the request establishes it or it is needed to prevent a concrete implementation mistake; prefer the intended capability and minimum interface/behavior changes. - -Keep bullets short and avoid explanatory sub-bullets unless they are needed to prevent ambiguity. Prefer the minimum detail needed for implementation safety, not exhaustive coverage. Within each section, compress related changes into a few high-signal bullets and omit branch-by-branch logic, repeated invariants, and long lists of unaffected behavior unless they are necessary to prevent a likely implementation mistake. Avoid repeated repo facts and irrelevant edge-case or rollout detail. For straightforward refactors, keep the plan to a compact summary, key edits, tests, and assumptions. If the user asks for more detail, then expand. - -Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan. - -Only produce at most one \`\` block per turn, and only when you are presenting a complete spec. - -If the user stays in Plan mode and asks for revisions after a prior \`\`, any new \`\` must be a complete replacement. If the user indicates that the prior plan is not acceptable but does not provide enough information to produce a complete replacement, address the concern and continue planning without producing a \`\` block. If the follow-up neither requires changes nor calls the plan into question (e.g. clarifying question), answer it before the block, then reproduce the prior \`\` unchanged. -`; - -const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `# Collaboration Mode: Default - -You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active. - -Your active mode changes only when new developer instructions with a different \`...\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan. - -## request_user_input availability - -Use the \`request_user_input\` tool only when it is listed in the available tools for this turn. - -In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message. -`; - export interface CodexRuntimeInfo { readonly model: string; readonly modelName?: string | undefined; - readonly reasoningEffort: string; -} - -export function buildCodexDeveloperInstructions(interactionMode: ProviderInteractionMode): string { - return interactionMode === "plan" - ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS - : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS; + readonly reasoningEffort?: string | undefined; } -/** - * This must stay out of the collaboration mode: when the model catalog ships - * its own text for a mode, as newer models do, Codex uses that text and drops - * the client's `developer_instructions` entirely. - */ +/** Keep this outside collaboration mode; model-catalog mode text overrides client developer_instructions. */ export function buildCodexAdditionalContext( runtime: CodexRuntimeInfo, toolsAvailable: boolean | T3CodeToolAvailability = true, ): Record { const tools = toolInstructions(toolsAvailable); - // Separate keys keep each value under Codex's per-entry cap. Codex emits - // entries in key order, so the numbering preserves the authored order. + // Split values to fit per-entry caps; number keys because Codex emits them in key order. return { ...Object.fromEntries( T3_CODE_ORCHESTRATION_SECTIONS.map((section, index) => [ diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index 54cc2aeb41c1b..849b3c928af8b 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -2,23 +2,19 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as ModelManifest from "./ModelManifest.ts"; import { expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Clock from "effect/Clock"; import * as Crypto from "effect/Crypto"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; -import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Exit from "effect/Exit"; import * as Queue from "effect/Queue"; import * as Scope from "effect/Scope"; -import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import { HttpClient, HttpClientResponse } from "effect/http"; -import * as TestClock from "effect/testing/TestClock"; -import { ChildProcessSpawner } from "effect/process"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as CodexInstallation from "./CodexInstallation.ts"; const archive = Buffer.from( @@ -47,7 +43,7 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( const baseDir = input.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" })); const localDirectory = `${baseDir}/local`; - const localBinaryPath = `${localDirectory}/codex`; + const localBinaryPath = `${localDirectory}/codex${input.platform === "win32" ? ".exe" : ""}`; const probeLog = `${baseDir}/local-probes.txt`; if (input.local) { yield* fs.makeDirectory(localDirectory, { recursive: true }); @@ -190,17 +186,21 @@ it.effect.each([ expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect("falls back to a managed download when the reused local executable disappears", () => - Effect.gen(function* () { - const h = yield* makeHarness({ local: { version: "0.156.1" } }); - expect((yield* h.installation.resolve()).source).toBe("local"); - yield* h.fs.remove(h.localBinaryPath); - yield* h.installation.start; - expect((yield* terminalState(h.installation)).phase).toBe("succeeded"); - expect((yield* h.installation.resolve()).source).toBe("managed"); - expect(h.downloads()).toBe(1); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); + +const compileNative = Effect.fn("test.compileNative")(function* ( + executablePath: string, + source: string, +) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const compiler = yield* spawner.spawn( + ChildProcess.make("cc", ["-x", "c", "-", "-o", executablePath], { + stdin: Stream.make(new TextEncoder().encode(source)), + stdout: "inherit", + stderr: "inherit", + }), + ); + expect(yield* compiler.exitCode).toBe(0); +}, Effect.scoped); it.effect("rechecks compatibility after the local executable is replaced", () => Effect.gen(function* () { @@ -263,16 +263,38 @@ it.effect("uses bundled Codex compatibility when the remote manifest omits its p }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it.effect("preserves the invoked name of version-manager launcher symlinks", () => +it.effect.each([ + { kind: "script", name: "volta-shim" }, + { kind: "native", name: "volta-shim" }, + { kind: "native", name: "mise" }, + { kind: "native", name: "aqua-proxy" }, +])("preserves the invoked name of $kind $name launcher symlinks", ({ kind, name }) => Effect.gen(function* () { const h = yield* makeHarness({ local: { version: "0.156.1" } }); - const launcher = `${h.baseDir}/launcher`; - yield* h.fs.writeFileString( - launcher, - '#!/bin/sh\ncase "$0" in */codex) ;; *) exit 1;; esac\ncase "$1" in --version) printf "codex-cli 0.156.1\\n";; app-server) exit 0;; esac\n', - { mode: 0o755 }, - ); - yield* h.fs.remove(h.localBinaryPath); + const launcher = `${h.baseDir}/${name}`; + if (kind === "native") { + const payload = `${h.baseDir}/codex.js`; + yield* h.fs.rename(h.localBinaryPath, payload); + yield* compileNative( + launcher, + `#include +#include +int main(int argc, char **argv) { + const char *name = strrchr(argv[0], '/'); + if (strcmp(name ? name + 1 : argv[0], "codex") != 0) return 1; + execv(${JSON.stringify(payload)}, argv); + return 1; +} +`, + ); + } else { + yield* h.fs.writeFileString( + launcher, + '#!/bin/sh\ncase "$0" in */codex) ;; *) exit 1;; esac\ncase "$1" in --version) printf "codex-cli 0.156.1\\n";; app-server) exit 0;; esac\n', + { mode: 0o755 }, + ); + yield* h.fs.remove(h.localBinaryPath); + } yield* h.fs.symlink(launcher, h.localBinaryPath); expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" }); expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath); @@ -397,119 +419,4 @@ it.effect("keeps an activated runtime when a later update fails verification", ( }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -it("publishes complete packages for all supported platforms", () => { - for (const platform of ["darwin", "linux", "win32"] as const) - for (const arch of ["x64", "arm64"]) - expect(CodexInstallation.resolveCodexReleaseAsset(platform, arch)?.url).toContain( - "codex-package-", - ); - expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull(); -}); -// Live clock: staleness compares real filesystem mtimes. -it.live("startup removes only stale staging directories", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" }); - const managed = `${baseDir}/tools/codex`; - const stale = ((yield* Clock.currentTimeMillis) - 25 * 60 * 60_000) / 1000; - for (const name of [".install-stale", ".active-stale", ".install-live"]) { - yield* fs.makeDirectory(`${managed}/${name}`, { recursive: true }); - } - yield* fs.utimes(`${managed}/.install-stale`, stale, stale); - yield* fs.utimes(`${managed}/.active-stale`, stale, stale); - const h = yield* makeHarness({ baseDir }); - expect(yield* fs.readDirectory(managed)).toEqual([".install-live"]); - expect((yield* h.installation.state).canRemove).toBe(true); - - yield* fs.remove(`${managed}/.install-live`, { recursive: true }); - yield* fs.makeDirectory(`${managed}/.install-stale`); - yield* fs.utimes(`${managed}/.install-stale`, stale, stale); - const fresh = yield* makeHarness({ baseDir }); - expect(yield* fs.readDirectory(managed)).toEqual([]); - expect((yield* fresh.installation.state).canRemove).toBe(false); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); - -const processHandle = (stdout: string) => - ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(1), - exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), - isRunning: Effect.succeed(false), - kill: () => Effect.void, - unref: Effect.succeed(Effect.void), - stdin: Sink.drain, - stdout: Stream.make(new TextEncoder().encode(stdout)), - stderr: Stream.empty, - all: Stream.empty, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }); -const windowsPackage: Record = { - "bin/codex.exe": "codex", - "bin/codex-code-mode-host.exe": "host", - "codex-path/rg.exe": "rg", - "codex-package.json": JSON.stringify({ - layoutVersion: 1, - version: asset.version, - target: asset.target, - entrypoint: "bin/codex.exe", - }), -}; // Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout. -const makeWindowsTar = (fs: FileSystem.FileSystem, commands: Array) => - ChildProcessSpawner.make((command) => - Effect.gen(function* () { - const { command: executable, args } = command as unknown as { - readonly command: string; - readonly args: ReadonlyArray; - }; - commands.push(executable); - const names = Object.keys(windowsPackage); - if (args[0] === "-tzf") return processHandle(`${names.join("\r\n")}\r\n`); - if (args[0] === "-tvzf") - return processHandle(`${names.map((name) => `-rwxr-xr-x 0 0 ${name}`).join("\r\n")}\r\n`); - const runtime = args[3] ?? ""; - for (const [name, contents] of Object.entries(windowsPackage)) { - yield* fs.makeDirectory(`${runtime}/${name.split("/").slice(0, -1).join("/")}`, { - recursive: true, - }); - yield* fs.writeFileString(`${runtime}/${name}`, contents); - } - return processHandle(""); - }).pipe(Effect.orDie), - ); - -it.effect("installs on Windows via System32 tar with CRLF output and a locked runtime", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const commands: Array = []; - const h = yield* makeHarness({ - platform: "win32", - spawner: makeWindowsTar(fs, commands), - runtimeRenameFailures: 3, - }); - yield* h.installation.start; - // Each failed attempt has scheduled its retry before the test fiber resumes. - for (let attempt = 0; attempt < 3; attempt++) { - yield* Queue.take(h.failedRenames); - yield* TestClock.adjust("100 millis"); - } - expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded" }); - expect(commands).toEqual([ - "C:\\Windows\\System32\\tar.exe", - "C:\\Windows\\System32\\tar.exe", - "C:\\Windows\\System32\\tar.exe", - ]); - const path = yield* Path.Path; - expect((yield* h.installation.resolve()).executablePath).toBe( - path.join(h.baseDir, "tools", "codex", "0.156.1", "bin", "codex.exe"), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); -it.effect("does not retry a failed runtime rename outside Windows", () => - Effect.gen(function* () { - const h = yield* makeHarness({ runtimeRenameFailures: 1 }); - yield* h.installation.start; - expect((yield* terminalState(h.installation)).phase).toBe("failed"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 31b62f0e26b11..669cbc6c8e2f0 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -96,7 +96,7 @@ const RELEASES: Readonly> = { archiveBytes: 153839991, }, }; -export const resolveCodexReleaseAsset = (platform: NodeJS.Platform, arch: string) => +const resolveCodexReleaseAsset = (platform: NodeJS.Platform, arch: string) => RELEASES[`${platform}-${arch}`] ?? null; export class CodexInstallationError extends Schema.TaggedError()( "CodexInstallationError", @@ -329,6 +329,47 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ); return output; }, Effect.scoped); + // Native Codex needs its adjacent host; launchers resolve their own payloads. + const hasCodeModeHost = Effect.fn("CodexInstallation.hasCodeModeHost")( + function* (realExecutablePath: string) { + if (/^(?:volta-shim|mise|aqua-proxy)(?:\.exe)?$/iu.test(path.basename(realExecutablePath))) + return true; + if (platform === "win32") { + if (path.extname(realExecutablePath).toLowerCase() !== ".exe") return true; + for (const extension of [".bunx", ".shim"]) { + const marker = yield* fs + .stat(realExecutablePath.slice(0, -4) + extension) + .pipe(Effect.option); + if ( + Option.isSome(marker) && + marker.value.type === "File" && + Number(marker.value.size) > 0 + ) + return true; + } + } else { + const header = yield* fs.open(realExecutablePath, { flag: "r" }).pipe( + Effect.flatMap((file) => file.readAlloc(2)), + Effect.orElseSucceed(() => Option.none()), + ); + if (Option.isSome(header) && header.value[0] === 0x23 && header.value[1] === 0x21) + return true; + } + const info = yield* fs.stat( + path.join( + path.dirname(realExecutablePath), + `codex-code-mode-host${platform === "win32" ? ".exe" : ""}`, + ), + ); + return ( + info.type === "File" && + Number(info.size) > 0 && + (platform === "win32" || (info.mode & 0o111) !== 0) + ); + }, + Effect.scoped, + Effect.orElseSucceed(() => false), + ); const localCache = new Map(); const resolveLocal = Effect.fn("CodexInstallation.resolveLocal")( function* () { @@ -347,6 +388,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ) ) return null; + if (!(yield* hasCodeModeHost(realExecutablePath))) return null; const info = yield* fs.stat(executablePath); const fingerprint = `${realExecutablePath}:${info.size}:${Option.getOrUndefined(info.mtime)?.getTime()}:${Option.getOrUndefined(info.ino)}`; const cached = localCache.get(executablePath); @@ -555,8 +597,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }), { flag: "wx", mode: 0o600 }, ); - // On Windows, Defender and kernel process rundown can briefly hold the - // verified codex.exe handle open right after `--version` exits. + // Windows Defender or process rundown may retain codex.exe handles briefly after --version exits. const renameRuntime = fs.rename(runtime, destination); yield* platform === "win32" ? renameRuntime.pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("100 millis") })) @@ -699,9 +740,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ); yield* Effect.gen(function* () { - // Two servers can share a home, and writes below a staging directory do not - // refresh its mtime, so only directories far older than any real install - // (download is capped at 45 minutes) are treated as abandoned. + // Shared-home installs do not refresh parent mtimes; remove only staging directories far older than the 45-minute download cap. let canRemove = false; if (yield* fs.exists(managedDirectory)) { const entries = yield* fs @@ -720,8 +759,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function if (now - modifiedAt < STAGING_STALE_AFTER_MS) continue; yield* fs.remove(target, { recursive: true, force: true }).pipe(Effect.ignore); } - // The empty root itself stays: deleting it could race another server - // creating a staging directory inside. An unreadable root stays removable. + // Keep the empty root to avoid racing new staging directories; unreadable roots remain removable. const remaining = yield* fs.readDirectory(managedDirectory).pipe(Effect.option); canRemove = Option.isNone(remaining) || remaining.value.length > 0; } diff --git a/apps/server/src/provider/CodexManagedErrors.ts b/apps/server/src/provider/CodexManagedErrors.ts index 9c8fe26bbb6ec..f2ee114c74fd1 100644 --- a/apps/server/src/provider/CodexManagedErrors.ts +++ b/apps/server/src/provider/CodexManagedErrors.ts @@ -9,6 +9,11 @@ const legacyFailures = { "Your ChatGPT usage limit was reached. Check ChatGPT Usage settings for your available allowance.", revoke: false, }, + subscription_sharing_workplace_individual_usage_limit_exceeded: { + message: + "You reached your workspace's limit for using ChatGPT in other apps. Ask your workspace admin to increase it.", + revoke: false, + }, subscription_sharing_usage_unavailable: { message: "ChatGPT usage is temporarily unavailable. Try again shortly.", revoke: false, diff --git a/apps/server/src/provider/CodexManagedRuntime.test.ts b/apps/server/src/provider/CodexManagedRuntime.test.ts index 69d27f1377b6b..8f8408bdaee1f 100644 --- a/apps/server/src/provider/CodexManagedRuntime.test.ts +++ b/apps/server/src/provider/CodexManagedRuntime.test.ts @@ -1,5 +1,9 @@ // @effect-diagnostics nodeBuiltinImport:off - checks the host's default Codex directory without writing to it. -import * as NodeOS from "node:os"; +import * as NodeURL from "node:url"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { CodexSettings, EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; @@ -18,37 +22,13 @@ import * as CodexInstallation from "./CodexInstallation.ts"; import { makeCodexManagedRuntime } from "./CodexManagedRuntime.ts"; import * as ProviderCredentialStore from "./ProviderCredentialStore.ts"; import { codexAppServerArgs } from "./codexLaunchArgs.ts"; -import { resolveManagedCodexHomeLayout } from "./CodexManagedHome.ts"; const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const decodeSettings = Schema.decodeSync(CodexSettings); -it.effect("managed home defaults to the global Codex home and honors configured home paths", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const primary = yield* resolveManagedCodexHomeLayout( - "/t3-state", - ProviderInstanceId.make("codex"), - decodeSettings({}), - ); - assert.equal(primary.sharedHomePath, path.join(NodeOS.homedir(), ".codex")); - assert.equal(primary.mode, "direct"); - const additional = yield* resolveManagedCodexHomeLayout( - "/t3-state", - ProviderInstanceId.make("codex-work"), - decodeSettings({}), - ); - assert.equal(additional.sharedHomePath, primary.sharedHomePath); - assert.equal(additional.mode, "authOverlay"); - const configured = yield* resolveManagedCodexHomeLayout( - "/t3-state", - ProviderInstanceId.make("codex-work"), - decodeSettings({ homePath: "/custom/shared", shadowHomePath: "/custom/shadow" }), - ); - assert.equal(configured.sharedHomePath, "/custom/shared"); - assert.equal(configured.effectiveHomePath, "/custom/shadow"); - }).pipe(Effect.provide(NodeServices.layer)), +const decodeCommand = Schema.decodeUnknownSync( + Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.Array(Schema.String)])), ); -it.effect.each( +it.live.each( (["managed", "local"] as const).flatMap((source) => (["primary", "additional"] as const).map((account) => ({ source, account })), ), @@ -65,6 +45,7 @@ it.effect.each( yield* fs.writeFileString(path.join(sharedHome, "auth.json"), "native-auth-unchanged"); yield* fs.writeFileString(path.join(sharedHome, "config.toml"), "# shared config\n"); const data = new Map(); + let renewals = 0; const secrets = ServerSecretStore.ServerSecretStore.of({ get: (key) => Effect.sync(() => Option.fromUndefinedOr(data.get(key))), set: (key, value) => @@ -115,10 +96,13 @@ it.effect.each( yield* store.set(new TextEncoder().encode(json)); const ambient = { CODEX_HOME: "/user/.codex", + ACCESS_TOKEN: "ambient-bearer", + T3CODE_HOME: path.join(sharedHome, "wrong-server-home"), OPENAI_API_KEY: "dummy-global-key", OPENAI_BASE_URL: "https://user-proxy.test", T3CODE_CODEX_LAUNCH_ARGS: "--config model_provider=global-proxy", - PATH: "/usr/bin", + PATH: process.env.PATH, + SystemRoot: process.env.SystemRoot, }; const runtime = yield* makeCodexManagedRuntime({ instanceId, @@ -149,27 +133,78 @@ it.effect.each( ); assert.isFalse(yield* fs.exists(path.join(effective.config.homePath, "auth.json"))); } - assert.strictEqual(effective.environment.ACCESS_TOKEN, "dummy-owned-access"); + assert.isUndefined(effective.environment.ACCESS_TOKEN); assert.isUndefined(effective.environment.OPENAI_API_KEY); assert.isUndefined(effective.environment.OPENAI_BASE_URL); assert.isUndefined(effective.environment.T3CODE_CODEX_LAUNCH_ARGS); const args = codexAppServerArgs(effective.config.launchArgs); - assert.include( - args, - 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"', - ); - assert.include( - args, - 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"', - ); + assert.include(args, 'model_provider="openai_token_sharing"'); + const provider = args.find((arg) => + arg.startsWith("model_providers.openai_token_sharing="), + )!; + assert.include(provider, 'base_url="https://api.openai.com/v1"'); + assert.include(provider, 'model_catalog_url="https://api.openai.com/v1/models"'); + assert.notInclude(provider, "env_key"); + assert.include(provider, "refresh_interval_ms=0"); + // regression: #16132 Codex fetches each token through this helper, so a running + // session picks up renewals instead of keeping the token it launched with. + if (source === "managed" && account === "primary") { + const commandMatch = /auth=\{command=(.*),args=(\[.*\]),timeout_ms=/u.exec(provider); + assert.isNotNull(commandMatch); + const [command, helperArgs] = decodeCommand( + `[${commandMatch![1]},${commandMatch![2]}]`, + ); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const runHelper = Effect.gen(function* () { + const child = yield* spawner.spawn( + ChildProcess.make(command, helperArgs, { + extendEnv: false, + env: effective.environment, + }), + ); + const [stdout, stderr, code] = yield* Effect.all( + [ + child.stdout.pipe(Stream.decodeText(), Stream.mkString), + child.stderr.pipe(Stream.decodeText(), Stream.mkString), + child.exitCode, + ], + { concurrency: "unbounded" }, + ); + return { stdout, stderr, code: Number(code) }; + }).pipe(Effect.scoped); + assert.deepEqual(yield* runHelper, { + stdout: "dummy-owned-access", + stderr: "", + code: 0, + }); + const saved = Option.getOrThrow(yield* runtime.auth.read); + const expired = yield* encodeJson({ ...saved, expiresAt: 0 }); + yield* store.set(new TextEncoder().encode(expired)); + assert.deepEqual(yield* runHelper, { stdout: "renewed-access", stderr: "", code: 0 }); + assert.equal(renewals, 1); + assert.equal( + Option.getOrThrow(yield* runtime.auth.read).refreshToken, + "renewed-refresh", + ); + assert.equal((yield* runtime.resolve).revision, effective.revision); + const replaced = yield* encodeJson({ ...saved, subject: "replacement-user" }); + yield* store.set(new TextEncoder().encode(replaced)); + const refused = yield* runHelper; + assert.equal(refused.code, 1); + assert.equal(refused.stdout, ""); + assert.isFalse(yield* fs.exists(ambient.T3CODE_HOME)); + } assert.include(args, "features.api_key_model_discovery=true"); assert.include(args, "features.multi_agent=false"); assert.include(args, "features.multi_agent_v2=false"); assert.notInclude(effective.config.launchArgs, "model_catalog_json"); assert.notInclude(effective.config.launchArgs, "x-openai-chatpass-test"); - assert.include(args, "model_providers.openai_token_sharing.supports_websockets=false"); - assert.include(args, "model_providers.openai_token_sharing.requires_openai_auth=false"); - assert.notInclude(effective.config.launchArgs, "dummy-owned-access"); + assert.include(provider, "supports_websockets=false"); + assert.include(provider, "requires_openai_auth=false"); + for (const secret of ["dummy-owned-access", "dummy-refresh", "ambient-bearer"]) { + assert.notInclude(effective.config.launchArgs, secret); + assert.notInclude(JSON.stringify(effective.environment), secret); + } assert.strictEqual(ambient.CODEX_HOME, "/user/.codex"); }).pipe(Effect.scoped); assert.strictEqual(leases, 0); @@ -179,6 +214,11 @@ it.effect.each( "native-auth-unchanged", ); }).pipe( + Effect.provide(CodexManagedTokenBroker.layer), + Effect.provideService(HostProcess.Arguments, [ + process.execPath, + NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)), + ]), Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { getEnvironmentId: Effect.succeed( @@ -194,8 +234,22 @@ it.effect.each( [ "https://auth.openai.com/.well-known/openid-configuration", "https://auth.openai.com/revoke", + "https://auth.openai.com/api/accounts/oauth/token", ].includes(request.url), ); + if (request.url.endsWith("/token")) { + renewals++; + return HttpClientResponse.fromWeb( + request, + Response.json({ + access_token: "renewed-access", + refresh_token: "renewed-refresh", + token_type: "Bearer", + expires_in: 3600, + scope: "chatgpt.tokens.use.direct", + }), + ); + } return HttpClientResponse.fromWeb( request, request.url.endsWith("/revoke") diff --git a/apps/server/src/provider/CodexManagedRuntime.ts b/apps/server/src/provider/CodexManagedRuntime.ts index 826d777f1bd70..3704c919c2791 100644 --- a/apps/server/src/provider/CodexManagedRuntime.ts +++ b/apps/server/src/provider/CodexManagedRuntime.ts @@ -5,8 +5,12 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as ServerConfig from "../config.ts"; +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { resolveSelfInvocation, selfInvocationArgs } from "@t3tools/shared/nodeRuntime"; import * as CodexInstallation from "./CodexInstallation.ts"; import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; +import { COMMAND_TIMEOUT_MS } from "./CodexManagedTokenProtocol.ts"; import { materializeCodexShadowHome } from "./Drivers/CodexHomeLayout.ts"; export interface CodexEffectiveRuntime { @@ -15,21 +19,17 @@ export interface CodexEffectiveRuntime { readonly revision: string; } const decodeSettings = Schema.decodeSync(CodexSettings); -const managedCodexLaunchArgs = [ - 'model_provider="openai_token_sharing"', - 'model_providers.openai_token_sharing.name="OpenAI Token Sharing"', - 'model_providers.openai_token_sharing.base_url="https://api.openai.com/v1"', - 'model_providers.openai_token_sharing.model_catalog_url="https://api.openai.com/v1/models"', - "features.api_key_model_discovery=true", - "features.multi_agent=false", - "features.multi_agent_v2=false", - 'model_providers.openai_token_sharing.env_key="ACCESS_TOKEN"', - 'model_providers.openai_token_sharing.wire_api="responses"', - "model_providers.openai_token_sharing.requires_openai_auth=false", - "model_providers.openai_token_sharing.supports_websockets=false", -] - .map((value) => `-c '${value}'`) - .join(" "); +const managedCodexLaunchArgs = (command: string, args: ReadonlyArray) => + [ + 'model_provider="openai_token_sharing"', + // Codex persists this provider ID in rollouts and needs it unchanged to resume. + `model_providers.openai_token_sharing={name="OpenAI Token Sharing",base_url="https://api.openai.com/v1",model_catalog_url="https://api.openai.com/v1/models",wire_api="responses",requires_openai_auth=false,supports_websockets=false,auth={command=${JSON.stringify(command)},args=${JSON.stringify(args)},timeout_ms=${COMMAND_TIMEOUT_MS},refresh_interval_ms=0}}`, + "features.api_key_model_discovery=true", + "features.multi_agent=false", + "features.multi_agent_v2=false", + ] + .map((value) => `-c ${JSON.stringify(value)}`) + .join(" "); export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(function* (options: { readonly instanceId: ProviderInstanceId; @@ -41,6 +41,10 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func const config = yield* ServerConfig.ServerConfig; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const broker = yield* CodexManagedTokenBroker.CodexManagedTokenBroker; + const environmentIdentity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const environmentId = yield* environmentIdentity.getEnvironmentId; + const invocation = yield* resolveSelfInvocation(); const auth = yield* makeCodexChatGptAuth({ instanceId: options.instanceId, defaultReturnUrl: new URL( @@ -55,6 +59,19 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func ); const homePath = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath; const resolve = Effect.gen(function* () { + // Establish renewal availability before auth.access can consume a refresh token. + const endpoint = yield* broker.endpoint.pipe( + Effect.mapError( + (cause) => + new ProviderSetupError({ + instanceId: options.instanceId, + operation: "runtime", + detail: + "Could not prepare the private managed Codex token listener. Restart T3 and retry.", + cause, + }), + ), + ); const executable = yield* installation.acquire().pipe( Effect.mapError( () => @@ -66,6 +83,14 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func ), ); const credentials = yield* auth.access; + const profileKey = yield* auth.profileKey(credentials); + const authArgs = selfInvocationArgs(invocation, [ + "__managed-chatgpt-token", + endpoint, + options.instanceId, + environmentId, + profileKey, + ]); yield* materializeCodexShadowHome(homeLayout).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), @@ -91,9 +116,9 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func // Ambient CLI overrides cannot redirect a T3-owned token to a different provider. const environment: NodeJS.ProcessEnv = { ...options.environment, - ACCESS_TOKEN: credentials.accessToken, CODEX_HOME: homePath, }; + delete environment.ACCESS_TOKEN; delete environment.T3CODE_CODEX_LAUNCH_ARGS; delete environment.OPENAI_API_KEY; delete environment.OPENAI_BASE_URL; @@ -103,10 +128,10 @@ export const makeCodexManagedRuntime = Effect.fn("makeCodexManagedRuntime")(func setupMode: "managed", binaryPath: executable.executablePath, homePath, - launchArgs: managedCodexLaunchArgs, + launchArgs: managedCodexLaunchArgs(invocation.command, authArgs), }), environment, - revision: credentials.accessToken, + revision: profileKey, } satisfies CodexEffectiveRuntime; }); return { auth, resolve, installation, homePath, homeLayout }; diff --git a/apps/server/src/provider/CodexManagedTokenBroker.ts b/apps/server/src/provider/CodexManagedTokenBroker.ts new file mode 100644 index 0000000000000..4a1e861827142 --- /dev/null +++ b/apps/server/src/provider/CodexManagedTokenBroker.ts @@ -0,0 +1,225 @@ +// @effect-diagnostics nodeBuiltinImport:off - Server-owned private pipe/Unix socket, never a public listener. +import * as NodeFSP from "node:fs/promises"; +import * as NodeNet from "node:net"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeCrypto from "node:crypto"; +import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FiberSet from "effect/FiberSet"; +import * as Layer from "effect/Layer"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as Schema from "effect/Schema"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { makeCodexChatGptAuth } from "./CodexChatGptAuth.ts"; +import * as Protocol from "./CodexManagedTokenProtocol.ts"; + +const MAX_CONNECTIONS = 32; +const MAX_JOBS = 16; +// Stay below macOS's 104-byte and Linux's 108-byte sockaddr_un limits, including NUL. +const UNIX_SOCKET_PATH_BYTES = 100; +const encodeResponse = Schema.encodeSync(Schema.fromJsonString(Protocol.Response)); +class BrokerStartError extends Schema.TaggedError()( + "ManagedTokenBrokerStartError", + { + cause: Schema.Defect(), + }, +) { + override get message() { + return "Could not start the private managed token listener."; + } +} +export class CodexManagedTokenBroker extends Context.Service< + CodexManagedTokenBroker, + { + readonly endpoint: Effect.Effect; + readonly awaitIdle: Effect.Effect; + } +>()("t3/provider/CodexManagedTokenBroker") {} + +const io = (f: () => Promise) => + Effect.tryPromise({ try: f, catch: (cause) => new BrokerStartError({ cause }) }); +const acquireListener = Effect.gen(function* () { + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const environmentId = yield* identity.getEnvironmentId; + const platform = yield* HostProcess.Platform; + const uid = yield* HostProcess.UserId; + const owned = yield* Effect.acquireRelease( + io(async () => { + if (platform === "win32") + return { endpoint: `\\\\.\\pipe\\t3-token-${NodeCrypto.randomUUID()}` }; + if (uid === undefined) throw new Error("Missing IPC owner"); + const acquireDirectory = async (candidate: string) => { + const parent = await NodeFSP.realpath(candidate); + const stat = await NodeFSP.lstat(parent); + if ( + !stat.isDirectory() || + stat.isSymbolicLink() || + !( + (stat.uid === uid && (stat.mode & 0o022) === 0) || + (stat.uid === 0 && ((stat.mode & 0o022) === 0 || (stat.mode & 0o1000) !== 0)) + ) + ) + throw new Error("Untrusted IPC parent"); + const directory = await NodeFSP.mkdtemp(NodePath.join(parent, "t3-token-")); + try { + await NodeFSP.chmod(directory, 0o700); + const created = await NodeFSP.lstat(directory); + if ( + !created.isDirectory() || + created.isSymbolicLink() || + created.uid !== uid || + (created.mode & 0o777) !== 0o700 + ) + throw new Error("Unprotected IPC directory"); + const endpoint = NodePath.join(directory, "s"); + if (Buffer.byteLength(endpoint) > UNIX_SOCKET_PATH_BYTES) + throw new Error("IPC path too long"); + return { endpoint, directory, created }; + } catch (error) { + await NodeFSP.rmdir(directory); + throw error; + } + }; + return acquireDirectory(NodeOS.tmpdir()).catch(() => acquireDirectory("/tmp")); + }), + (owned) => + Effect.promise(async () => { + if (!("directory" in owned)) return; + // Never recursively remove a replaced directory or another process's files. + const current = await NodeFSP.lstat(owned.directory).catch(() => undefined); + if ( + current && + current.dev === owned.created.dev && + current.ino === owned.created.ino && + !current.isSymbolicLink() + ) + await NodeFSP.rmdir(owned.directory).catch(() => undefined); + }), + ); + const jobs = yield* FiberSet.make(); + const runJob = + yield* FiberSet.runtime(jobs)< + Exclude< + Effect.Services>, + import("effect/Scope").Scope + > + >(); + const connections = yield* FiberSet.make(); + const runConnection = yield* FiberSet.runtime(connections)(); + const sockets = new Set(); + let closing = false; + let admitted = 0; + // Keep branded validation here so the helper need not load the contracts graph. + const decode = Schema.decodeUnknownEffect( + Schema.fromJsonString( + Schema.Struct({ + ...Protocol.Request.fields, + instanceId: ProviderInstanceId, + environmentId: EnvironmentId, + }), + ), + { + onExcessProperty: "error", + }, + ); + const server = NodeNet.createServer((socket) => { + socket.on("error", () => {}); + if (closing || sockets.size >= MAX_CONNECTIONS) { + socket.destroy(); + return; + } + sockets.add(socket); + socket.once("close", () => sockets.delete(socket)); + let transferred = false; + runConnection( + Effect.gen(function* () { + // Windows pipes permit read-only peers by default; send no bytes until a complete request. + const request = yield* Protocol.readFrame( + socket, + Protocol.REQUEST_BYTES, + Protocol.SOCKET_IDLE_MS, + ).pipe(Effect.flatMap(decode)); + if (closing || admitted >= MAX_JOBS || request.environmentId !== environmentId) return; + admitted++; + transferred = true; + runJob( + Effect.scoped( + Effect.gen(function* () { + const auth = yield* makeCodexChatGptAuth({ + instanceId: request.instanceId, + expectedProfileKey: request.profileKey, + }); + // Retire abandoned permit waits; access saves a started rotation before honoring interruption. + const credentials = yield* auth.access.pipe( + Effect.timeout(Protocol.COMMAND_TIMEOUT_MS), + ); + yield* Protocol.writeFrame( + socket, + encodeResponse({ token: credentials.accessToken }), + Protocol.RESPONSE_BYTES, + ); + }), + ).pipe( + Effect.ignoreCause, + Effect.ensuring( + Effect.sync(() => { + admitted--; + socket.destroy(); + }), + ), + ), + ); + }).pipe( + Effect.ignoreCause, + Effect.ensuring( + Effect.sync(() => { + if (!transferred) socket.destroy(); + }), + ), + ), + ); + }); + server.on("error", () => {}); + // Drain accepted rotations before the FiberSet finalizers interrupt their fibers. + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + closing = true; + for (const socket of sockets) socket.destroy(); + yield* Effect.promise(() => new Promise((resolve) => server.close(() => resolve()))); + yield* FiberSet.awaitEmpty(connections); + yield* FiberSet.awaitEmpty(jobs); + }), + ); + yield* Effect.callback((resume) => { + const onError = (cause: Error) => resume(Effect.fail(new BrokerStartError({ cause }))); + server.once("error", onError); + try { + server.listen(owned.endpoint, () => resume(Effect.void)); + } catch (cause) { + resume(Effect.fail(new BrokerStartError({ cause }))); + } + return Effect.sync(() => server.off("error", onError)); + }); + if (platform !== "win32") yield* io(() => NodeFSP.chmod(owned.endpoint, 0o600)); + return { endpoint: owned.endpoint, awaitIdle: FiberSet.awaitEmpty(jobs) }; +}); +const make = Effect.gen(function* () { + const scope = yield* Scope.fork(yield* Effect.scope); + const acquired = yield* acquireListener.pipe(Scope.provide(scope), Effect.result); + if (acquired._tag === "Failure") { + yield* Scope.close(scope, Exit.fail(acquired.failure)); + return CodexManagedTokenBroker.of({ + endpoint: Effect.fail(acquired.failure), + awaitIdle: Effect.void, + }); + } + return CodexManagedTokenBroker.of({ + endpoint: Effect.succeed(acquired.success.endpoint), + awaitIdle: acquired.success.awaitIdle, + }); +}); +export const layer = Layer.effect(CodexManagedTokenBroker, make); diff --git a/apps/server/src/provider/CodexManagedTokenProtocol.ts b/apps/server/src/provider/CodexManagedTokenProtocol.ts new file mode 100644 index 0000000000000..d5f9e610d2188 --- /dev/null +++ b/apps/server/src/provider/CodexManagedTokenProtocol.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off - Private local IPC framing, shared by server and lean CLI. +import type * as NodeNet from "node:net"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +export const Request = Schema.Struct({ + version: Schema.Literal(1), + instanceId: Schema.NonEmptyString, + environmentId: Schema.NonEmptyString, + profileKey: Schema.String.check(Schema.isPattern(/^[a-f0-9]{64}$/u)), +}); +export const Response = Schema.Struct({ token: Schema.NonEmptyString }); +// Selectors are small; tokens can be larger JWTs. Never truncate either frame +// into something that could be accepted. +export const REQUEST_BYTES = 1024; +export const RESPONSE_BYTES = 64 * 1024; +// Idle/incomplete peers and blocked response consumers must not retain sockets. +export const SOCKET_IDLE_MS = 5_000; +// Existing lock retry (40s), OAuth (20s), plus startup/store headroom (20s). +export const COMMAND_TIMEOUT_MS = 80_000; +class ProtocolError extends Schema.TaggedError()("ManagedTokenProtocolError", {}) { + override get message(): string { + return "The managed token frame was invalid or incomplete."; + } +} + +export const readFrame = (socket: NodeNet.Socket, maxBytes: number, timeoutMs: number) => + Effect.callback((resume) => { + let bytes = Buffer.alloc(0); + const fail = () => resume(Effect.fail(new ProtocolError())); + const onData = (chunk: Buffer) => { + if (bytes.length + chunk.length > maxBytes) return fail(); + bytes = Buffer.concat([bytes, chunk]); + const end = bytes.indexOf(10); + if (end < 0) return; + if (end !== bytes.length - 1) return fail(); + resume(Effect.succeed(bytes.subarray(0, end).toString("utf8"))); + }; + socket.on("data", onData); + socket.once("error", fail); + socket.once("close", fail); + socket.once("end", fail); + return Effect.sync(() => { + socket.off("data", onData); + socket.off("error", fail); + socket.off("close", fail); + socket.off("end", fail); + }); + }).pipe( + Effect.timeoutOrElse({ duration: timeoutMs, orElse: () => Effect.fail(new ProtocolError()) }), + ); + +export const writeFrame = (socket: NodeNet.Socket, frame: string, maxBytes: number) => + Effect.callback((resume) => { + if (socket.destroyed || Buffer.byteLength(frame) + 1 > maxBytes) { + resume(Effect.fail(new ProtocolError())); + return; + } + const fail = () => resume(Effect.fail(new ProtocolError())); + socket.once("error", fail); + socket.once("close", fail); + socket.end(`${frame}\n`, () => resume(Effect.void)); + return Effect.sync(() => { + socket.off("error", fail); + socket.off("close", fail); + }); + }).pipe( + Effect.timeoutOrElse({ + duration: SOCKET_IDLE_MS, + orElse: () => Effect.fail(new ProtocolError()), + }), + ); diff --git a/apps/server/src/provider/CodexMcpElicitation.test.ts b/apps/server/src/provider/CodexMcpElicitation.test.ts index c0655faf0d67a..66dd7ddb6e7d0 100644 --- a/apps/server/src/provider/CodexMcpElicitation.test.ts +++ b/apps/server/src/provider/CodexMcpElicitation.test.ts @@ -45,12 +45,6 @@ describe("Codex MCP elicitation approvals", () => { }); }); - it("extracts the app name from a Computer Use request without metadata", () => { - const { _meta, ...requestWithoutMetadata } = request; - - NodeAssert.equal(describeMcpElicitation(requestWithoutMetadata).appName, "Safari"); - }); - it("returns the accepted form option to Codex", () => { NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "accept"), { action: "accept", @@ -66,6 +60,7 @@ describe("Codex MCP elicitation approvals", () => { }); }); + // regression: #8058 show Codex app access approval prompts it("returns persistent approval in the MCP response", () => { NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "acceptAlways"), { action: "accept", @@ -74,18 +69,6 @@ describe("Codex MCP elicitation approvals", () => { }); }); - it("returns rejection without form content", () => { - NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "decline"), { - action: "decline", - }); - }); - - it("returns cancellation without form content", () => { - NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "cancel"), { - action: "cancel", - }); - }); - it("supports boolean permanent-approval fields", () => { const booleanRequest = { ...request, diff --git a/apps/server/src/provider/CodexProvider.catalog.test.ts b/apps/server/src/provider/CodexProvider.catalog.test.ts deleted file mode 100644 index 9b76f4cb83635..0000000000000 --- a/apps/server/src/provider/CodexProvider.catalog.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, it } from "@effect/vitest"; -import { CodexSettings } from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; -import * as Schema from "effect/Schema"; - -import { checkCodexProviderStatus } from "./CodexProvider.ts"; - -/** - * Stand-in for Codex 0.162's app-server catalog behavior: - * - `model/list` answers from `CODEX_HOME/models_cache.json` while it is fresh. - * - A startup refresh runs before `initialize`, so it uses the originator set - * at spawn (the override env var, else the plain CLI's `codex_cli_rs`). - * - The backend grants Ultrafast only to entitled accounts on app originators. - */ -const FAKE_CODEX_APP_SERVER = String.raw`#!/usr/bin/env node -const fs = require("node:fs"); -const path = require("node:path"); -const readline = require("node:readline"); -const cachePath = path.join(process.env.CODEX_HOME, "models_cache.json"); -const originator = process.env.CODEX_INTERNAL_ORIGINATOR_OVERRIDE ?? "codex_cli_rs"; -const ultrafast = process.env.FAKE_ULTRAFAST_ENTITLED === "1" && originator !== "codex_cli_rs"; -const model = (tiers) => ({ - id: "gpt-6.1-sol", model: "gpt-6.1-sol", displayName: "GPT-6.1 Sol", description: "", - hidden: false, isDefault: true, defaultReasoningEffort: "high", - supportedReasoningEfforts: [{ reasoningEffort: "high", description: "" }], - serviceTiers: tiers.map((id) => ({ id, name: id, description: "" })), -}); -setTimeout(() => { - const tiers = ultrafast ? ["priority", "ultrafast"] : ["priority"]; - fs.writeFileSync(cachePath, JSON.stringify({ fetched_at: new Date().toISOString(), models: [model(tiers)] })); -}, 300); -const write = (message) => process.stdout.write(JSON.stringify(message) + "\n"); -readline.createInterface({ input: process.stdin }).on("line", (line) => { - const { id, method } = JSON.parse(line); - if (id === undefined) return; - if (method === "initialize") { - write({ id, result: { userAgent: "codex/0.162.0", codexHome: process.env.CODEX_HOME, platformFamily: "unix", platformOs: "macos" } }); - } else if (method === "account/read") { - write({ id, result: { account: { type: "chatgpt", email: "test@example.com", planType: "promax" }, requiresOpenaiAuth: false } }); - } else if (method === "skills/list") { - write({ id, result: { data: [] } }); - } else if (method === "model/list") { - write({ id, result: { data: JSON.parse(fs.readFileSync(cachePath, "utf8")).models, nextCursor: null } }); - } else { - write({ id, error: { code: -32601, message: "unsupported" } }); - } -}); -`; - -const decodeCodexSettings = Schema.decodeSync(CodexSettings); - -const solServiceTiers = Effect.fn("solServiceTiers")(function* (ultrafastEntitled: boolean) { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-catalog-" }); - const binaryPath = path.join(dir, "codex"); - yield* fs.writeFileString(binaryPath, FAKE_CODEX_APP_SERVER); - yield* fs.chmod(binaryPath, 0o755); - - yield* fs.writeFileString( - path.join(dir, "models_cache.json"), - JSON.stringify({ - fetched_at: DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { minutes: 1 })), - models: [ - { - id: "gpt-6.1-sol", - model: "gpt-6.1-sol", - displayName: "GPT-6.1 Sol", - description: "", - hidden: false, - isDefault: true, - defaultReasoningEffort: "high", - supportedReasoningEfforts: [{ reasoningEffort: "high", description: "" }], - serviceTiers: (ultrafastEntitled ? ["priority"] : ["priority", "ultrafast"]).map( - (id) => ({ id, name: id, description: "" }), - ), - }, - ], - }), - ); - - const { CODEX_INTERNAL_ORIGINATOR_OVERRIDE: _ambient, ...environment } = process.env; - const provider = yield* checkCodexProviderStatus( - decodeCodexSettings({ binaryPath, homePath: dir }), - undefined, - { ...environment, FAKE_ULTRAFAST_ENTITLED: ultrafastEntitled ? "1" : "0" }, - ); - const serviceTier = provider.models - .find((model) => model.slug === "gpt-6.1-sol") - ?.capabilities?.optionDescriptors?.find((descriptor) => descriptor.id === "serviceTier"); - return serviceTier?.type === "select" ? serviceTier.options.map((option) => option.id) : []; -}); - -it.layer(NodeServices.layer, { excludeTestServices: true })("Codex catalog discovery", (it) => { - it.effect("keeps Ultrafast when another Codex client wrote the shared catalog cache", () => - Effect.gen(function* () { - assert.deepStrictEqual(yield* solServiceTiers(true), ["default", "priority", "ultrafast"]); - }).pipe(Effect.scoped), - ); - - it.effect("drops Ultrafast once the account is no longer entitled to it", () => - Effect.gen(function* () { - assert.deepStrictEqual(yield* solServiceTiers(false), ["default", "priority"]); - }).pipe(Effect.scoped), - ); -}); diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.ts index 2c67b6f144dbb..30f63b21f318e 100644 --- a/apps/server/src/provider/CodexProvider.test.ts +++ b/apps/server/src/provider/CodexProvider.test.ts @@ -128,15 +128,6 @@ it("marks the most preferred available model as default", () => { ); }); -it("prefers sol over terra when both are available", () => { - const models = applyPreferredCodexDefaultModel([ - { slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null }, - { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null }, - ]); - - assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol"); -}); - it("ranks qualified Codex models while preserving their wire ids", () => { const models = applyPreferredCodexDefaultModel([ { @@ -154,15 +145,6 @@ it("ranks qualified Codex models while preserving their wire ids", () => { ); }); -it("keeps Codex's own default when no preferred model is available", () => { - const models = applyPreferredCodexDefaultModel([ - { slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null }, - { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null }, - ]); - - assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4"); -}); - it("ignores custom models that shadow a preferred slug", () => { const models = applyPreferredCodexDefaultModel([ { slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null }, diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index f4f123dc1a25f..25de2e9ffe093 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -67,14 +67,13 @@ type CodexRateLimitsProbe = | { readonly failure: string }; const CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = "2 seconds" as const; -const CODEX_CATALOG_REFRESH_TIMEOUT = "3 seconds" as const; +const CODEX_CATALOG_REFRESH_TIMEOUT_MS = 3_000; +const CODEX_CONFIG_PROBE_TIMEOUT_MS = 3_000; const CODEX_CATALOG_REFRESH_POLL = "100 millis" as const; const CODEX_CLIENT_NAME = "T3 Code"; -// Codex's probe does a full handshake plus account, models, and skills requests, which can -// legitimately run past the shared 10s AUTH_PROBE_TIMEOUT_MS on a loaded or slow machine -// (most often reported on Windows). Give Codex its own longer budget instead of raising the -// timeout for every provider. +// Handshake plus account/models/skills requests can exceed the shared 10s probe budget. const CODEX_AUTH_PROBE_TIMEOUT_MS = 20_000; +const CODEX_DISCOVERY_MARGIN_MS = 250; const CODEX_PRESENTATION = { displayName: "Codex", @@ -86,7 +85,8 @@ export interface CodexAppServerProviderSnapshot { readonly account: CodexSchema.V2GetAccountResponse; readonly rateLimits?: CodexRateLimitsProbe; readonly version: string | undefined; - readonly models: ReadonlyArray; + readonly models: ReadonlyArray | undefined; + readonly serviceTier?: string | undefined; readonly skills: ReadonlyArray; } @@ -128,14 +128,14 @@ export function codexPlanLabel(planType: string | null | undefined): string | un case "plus": return "ChatGPT Plus Subscription"; case "pro": - return "ChatGPT Pro 20x Subscription"; + return "ChatGPT Pro 200 Subscription"; case "prolite": - return "ChatGPT Pro 5x Subscription"; + return "ChatGPT Pro 100 Subscription"; case "promax": - return "ChatGPT Pro Max Subscription"; - case "team": - return "ChatGPT Team Subscription"; + return "ChatGPT Pro 500 Subscription"; case "self_serve_business_prolite": + return "ChatGPT Business Premium Subscription"; + case "team": case "self_serve_business_usage_based": case "business": return "ChatGPT Business Subscription"; @@ -160,12 +160,16 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"]) return account.email; } +export function codexDefaultReasoningEffortOverride(model: string): "medium" | undefined { + return codexModelFamily(model) === "gpt-6-astra" ? "medium" : undefined; +} + export function mapCodexModelCapabilities( model: CodexSchema.V2ModelListResponse__Model, ): ModelCapabilities { const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) => reasoningEffort === - (codexModelFamily(model.model) === "gpt-6-astra" ? "medium" : model.defaultReasoningEffort) + (codexDefaultReasoningEffortOverride(model.model) ?? model.defaultReasoningEffort) ? { id: reasoningEffort, label: reasoningEffortLabel(reasoningEffort), @@ -265,6 +269,37 @@ export function applyPreferredCodexDefaultModel( }); } +function applyConfiguredCodexServiceTier( + models: ReadonlyArray, + serviceTier: string | undefined, +): ReadonlyArray { + if (!serviceTier) return models; + return models.map((model) => { + if (!model.capabilities?.optionDescriptors) return model; + return { + ...model, + capabilities: { + ...model.capabilities, + optionDescriptors: model.capabilities.optionDescriptors.map((descriptor) => { + if (descriptor.id !== "serviceTier" || descriptor.type !== "select") return descriptor; + const value = descriptor.options.find( + (option) => + option.id === serviceTier || (serviceTier === "fast" && option.id === "priority"), + )?.id; + if (!value) return descriptor; + return { + ...descriptor, + currentValue: value, + options: descriptor.options.map(({ isDefault: _isDefault, ...option }) => + option.id === value ? { ...option, isDefault: true } : option, + ), + }; + }), + }, + }; + }); +} + /** * Codex has no static default capability set, so a bare custom slug borrows * the first built-in's descriptors; an entry with its own capabilities keeps @@ -350,6 +385,19 @@ const readCodexModelsCacheFetchedAt = Effect.fn("readCodexModelsCacheFetchedAt") ); }); +const withCodexDiscoveryDeadline = Effect.fnUntraced(function* ( + effect: Effect.Effect, + deadlineMs: number, + timeoutMs = Infinity, +) { + const remainingMs = Math.min(timeoutMs, deadlineMs - DateTime.toEpochMillis(yield* DateTime.now)); + if (remainingMs <= 0) return undefined; + return yield* effect.pipe( + Effect.timeoutOption(Duration.millis(remainingMs)), + Effect.map(Option.getOrUndefined), + ); +}); + /** * Every Codex client on the machine shares that file, and the backend tailors * the catalog to each client's originator: the plain CLI does not get Sol @@ -360,30 +408,36 @@ const requestCodexChatGptModels = Effect.fn("requestCodexChatGptModels")(functio readonly client: CodexClient.CodexAppServerClient["Service"]; readonly codexHome: string; readonly spawnedAtMs: number; + readonly deadlineMs: number; }) { - const models = yield* requestAllCodexModels(input.client); - const refreshed = yield* readCodexModelsCacheFetchedAt(input.codexHome).pipe( - Effect.repeat({ - schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL), - until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs, - }), - Effect.timeoutOption(CODEX_CATALOG_REFRESH_TIMEOUT), + const models = yield* withCodexDiscoveryDeadline( + requestAllCodexModels(input.client), + input.deadlineMs, + ); + if (models === undefined) return undefined; + const refreshed = yield* withCodexDiscoveryDeadline( + readCodexModelsCacheFetchedAt(input.codexHome).pipe( + Effect.repeat({ + schedule: Schedule.spaced(CODEX_CATALOG_REFRESH_POLL), + until: (fetchedAtMs) => fetchedAtMs >= input.spawnedAtMs, + }), + ), + input.deadlineMs, + CODEX_CATALOG_REFRESH_TIMEOUT_MS, ); - if (Option.isNone(refreshed)) { + if (refreshed === undefined) { yield* Effect.logWarning( "Codex did not refresh its model catalog in time; using the cached catalog.", ); return models; } - return yield* requestAllCodexModels(input.client); + return ( + (yield* withCodexDiscoveryDeadline(requestAllCodexModels(input.client), input.deadlineMs)) ?? + models + ); }); -/** - * App-server starts its catalog refresh before `initialize` names the client, - * so that first fetch goes out as the plain CLI, misses tiers like Sol - * Ultrafast, and overwrites the shared `models_cache.json`. Naming the - * originator at spawn closes that race. - */ +/** Set originator at spawn; the pre-initialize refresh otherwise overwrites shared cache with plain-CLI models. */ export const codexAppServerEnvironment = ( environment: NodeJS.ProcessEnv | undefined, ): NodeJS.ProcessEnv => ({ @@ -411,9 +465,7 @@ export const withCodexAppServerClient = Effect.fn("withCodexAppServerClient")(fu readonly cwd: string; readonly environment?: NodeJS.ProcessEnv | undefined; }) { - // `~` is not shell-expanded when env vars are set via `child_process.spawn`, - // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip - // "CODEX_HOME points to '~/.codex_work', but that path does not exist". + // Expand CODEX_HOME explicitly: spawn passes a literal ~ that Codex rejects. const resolvedHomePath = input.homePath ? expandHomePath(input.homePath, yield* HostProcess.HomeDirectory) : undefined; @@ -460,7 +512,6 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun readonly homePath?: string; readonly launchArgs?: string; readonly cwd: string; - readonly customModels?: ReadonlyArray; readonly environment?: NodeJS.ProcessEnv; readonly skipNativeUsage?: boolean; }) { @@ -475,33 +526,51 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun return { account: accountResponse, version, - models: appendCustomCodexModels([], input.customModels ?? []), + models: [], skills: [], } satisfies CodexAppServerProviderSnapshot; } - const [skillsResponse, models, rateLimits] = yield* Effect.all( + // Optional discovery must finish before the outer timeout can discard the account result. + const deadlineMs = spawnedAtMs + CODEX_AUTH_PROBE_TIMEOUT_MS - CODEX_DISCOVERY_MARGIN_MS; + const [skillsResponse, models, serviceTier, rateLimits] = yield* Effect.all( [ - client.request("skills/list", { - cwds: [input.cwd], - }), + withCodexDiscoveryDeadline(client.request("skills/list", { cwds: [input.cwd] }), deadlineMs), accountResponse.account?.type === "chatgpt" - ? requestCodexChatGptModels({ client, codexHome: initialize.codexHome, spawnedAtMs }) - : requestAllCodexModels(client), + ? requestCodexChatGptModels({ + client, + codexHome: initialize.codexHome, + spawnedAtMs, + deadlineMs, + }) + : withCodexDiscoveryDeadline(requestAllCodexModels(client), deadlineMs), + // The shared catalog must exclude config from the server's launch project. + withCodexDiscoveryDeadline( + client.request("config/read", { includeLayers: false }), + deadlineMs, + CODEX_CONFIG_PROBE_TIMEOUT_MS, + ).pipe( + Effect.map((response) => response?.config.service_tier ?? undefined), + Effect.catch(() => Effect.logDebug("Codex config read failed.").pipe(Effect.as(undefined))), + ), + // Usage is an enrichment: a failure or a slow answer degrades to "no + // usage this probe" rather than costing the account and models. input.skipNativeUsage ? Effect.succeed(undefined) - : client.request("account/rateLimits/read", null).pipe( - Effect.map((response): CodexRateLimitsProbe => ({ - snapshot: response.rateLimits, - rateLimitsByLimitId: response.rateLimitsByLimitId, - resetCredits: response.rateLimitResetCredits, - accountId: response.accountId, - })), - Effect.timeoutOption(Duration.millis(RATE_LIMITS_PROBE_TIMEOUT_MS)), - Effect.map( - Option.getOrElse((): CodexRateLimitsProbe => ({ - failure: "Codex did not answer the usage request.", - })), + : withCodexDiscoveryDeadline( + client.request("account/rateLimits/read", null), + deadlineMs, + RATE_LIMITS_PROBE_TIMEOUT_MS, + ).pipe( + Effect.map((response): CodexRateLimitsProbe => + response + ? { + snapshot: response.rateLimits, + rateLimitsByLimitId: response.rateLimitsByLimitId, + resetCredits: response.rateLimitResetCredits, + accountId: response.accountId, + } + : { failure: "Codex did not answer the usage request." }, ), Effect.catch((error) => Effect.logDebug("Codex rate-limit read failed.", { cause: error }).pipe( @@ -517,10 +586,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun account: accountResponse, ...(rateLimits ? { rateLimits } : {}), version, - models: applyPreferredCodexDefaultModel( - appendCustomCodexModels(models, input.customModels ?? []), - ), - skills: parseCodexSkillsListResponse(skillsResponse, input.cwd), + models, + serviceTier, + skills: skillsResponse ? parseCodexSkillsListResponse(skillsResponse, input.cwd) : [], } satisfies CodexAppServerProviderSnapshot; }); @@ -539,33 +607,16 @@ export const probeCodexSkillsForCwd = Effect.fn("probeCodexSkillsForCwd")(functi const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => appendCustomCodexModels([], codexSettings.customModels); -const makePendingCodexProvider = ( +const makePendingCodexProvider = Effect.fn("CodexProvider.makePendingCodexProvider")(function* ( codexSettings: CodexSettings, -): Effect.Effect => - Effect.gen(function* () { - const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso); - const models = emptyCodexModelsFromSettings(codexSettings); - - if (!codexSettings.enabled) { - return buildServerProvider({ - presentation: CODEX_PRESENTATION, - enabled: false, - checkedAt, - models, - skills: [], - probe: { - installed: false, - version: null, - status: "warning", - auth: { status: "unknown" }, - message: "Codex is disabled in T3 Code settings.", - }, - }); - } +): Effect.fn.Return { + const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso); + const models = emptyCodexModelsFromSettings(codexSettings); + if (!codexSettings.enabled) { return buildServerProvider({ presentation: CODEX_PRESENTATION, - enabled: true, + enabled: false, checkedAt, models, skills: [], @@ -574,10 +625,26 @@ const makePendingCodexProvider = ( version: null, status: "warning", auth: { status: "unknown" }, - message: "Codex provider status has not been checked in this session yet.", + message: "Codex is disabled in T3 Code settings.", }, }); + } + + return buildServerProvider({ + presentation: CODEX_PRESENTATION, + enabled: true, + checkedAt, + models, + skills: [], + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Codex provider status has not been checked in this session yet.", + }, }); +}); function accountProbeStatus({ account, rateLimits }: CodexAppServerProviderSnapshot): { readonly status: Exclude; @@ -618,7 +685,6 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu readonly homePath?: string; readonly launchArgs?: string; readonly cwd: string; - readonly customModels: ReadonlyArray; readonly environment?: NodeJS.ProcessEnv; readonly skipNativeUsage?: boolean; }) => Effect.Effect< @@ -659,12 +725,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu homePath: codexSettings.homePath, launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment), cwd: process.cwd(), - customModels: codexSettings.customModels, environment: resolvedEnvironment, ...(managedAuth ? { skipNativeUsage: true } : {}), }).pipe( - Effect.scoped, + // Process teardown can outlast the work budget without discarding a completed snapshot. Effect.timeoutOption(Duration.millis(CODEX_AUTH_PROBE_TIMEOUT_MS)), + Effect.scoped, Effect.result, ); @@ -720,6 +786,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu ? makeUnavailableUsageLimits({ checkedAt, reason: "probeFailed", + ...(accountStatus.message ? { message: accountStatus.message } : {}), ...(snapshot.rateLimits ? { message: snapshot.rateLimits.failure } : {}), }) : codexRateLimitsToLimits({ @@ -733,7 +800,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu presentation: CODEX_PRESENTATION, enabled: codexSettings.enabled, checkedAt, - models: snapshot.models, + models: applyConfiguredCodexServiceTier( + applyPreferredCodexDefaultModel( + appendCustomCodexModels(snapshot.models ?? [], codexSettings.customModels), + ), + snapshot.serviceTier, + ), skills: snapshot.skills, slashCommands: [ COMPACT_SLASH_COMMAND, @@ -751,9 +823,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu probe: { installed: true, version: snapshot.version ?? null, - status: accountStatus.status, + status: snapshot.models === undefined ? "warning" : accountStatus.status, auth: accountStatus.auth, - ...(accountStatus.message ? { message: accountStatus.message } : {}), + ...(accountStatus.message + ? { message: accountStatus.message } + : snapshot.models === undefined + ? { message: "Codex did not return its model catalog in time." } + : {}), ...(managedAuth ? {} : { usageLimits }), }, }); diff --git a/apps/server/src/provider/CodexTurnTokenUsage.ts b/apps/server/src/provider/CodexTurnTokenUsage.ts index 6f4959627eff9..7b0f20a123ffe 100644 --- a/apps/server/src/provider/CodexTurnTokenUsage.ts +++ b/apps/server/src/provider/CodexTurnTokenUsage.ts @@ -66,10 +66,7 @@ export function getCodexTurnAccumulator( return created; } -/** - * Codex reports a running `total` for the thread and `last`, the usage of the - * newest model response. - */ +/** total is thread-wide; last covers the newest model response. */ function codexTurnTokenUsageDelta( previous: CodexCumulativeTokenUsage | undefined, current: CodexCumulativeTokenUsage, @@ -104,8 +101,7 @@ export function accumulateCodexTurnTokenUsage( ): void { const current = codexTokenUsageBreakdown(usage.total); if (state.activeTurnId !== turnId) { - // The total is thread-wide, so every update moves the baseline. A late - // update for a finished turn is not counted toward the live turn. + // Every thread-wide total updates the baseline; late finished-turn updates do not count toward the live turn. state.baseline = current; return; } diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts index b27db9ca86b9b..74f4daa1323af 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts @@ -7,13 +7,10 @@ import { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; -import * as Deferred from "effect/Deferred"; -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 Schema from "effect/Schema"; -import * as TestClock from "effect/testing/TestClock"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { HttpClient } from "effect/http"; @@ -272,52 +269,6 @@ const layerTest = ProviderHostLive.layer.pipe( ); it.layer(layerTest)("AntigravityDriver", (it) => { - it.effect.skipIf(windowsHost)( - "preserves the Node install message when starting a standalone provider", - () => - Effect.gen(function* () { - const h = yield* makeHarness(); - const error = yield* h.refresh().pipe(Effect.flip); - expect(error.detail).toContain("Install Node.js"); - expect(h.launches).toEqual([]); - }).pipe( - Effect.scoped, - Effect.provideService(HostProcess.IsExecutable, true), - Effect.provideService(HostProcess.Environment, { PATH: "" }), - ), - ); - - it.effect.skipIf(windowsHost)("does not launch a process for a disabled instance", () => - Effect.gen(function* () { - const h = yield* makeHarness({ enabled: false }); - const snapshot = yield* h.instance.snapshot.refresh; - expect(snapshot.status).toBe("disabled"); - expect(h.acquisitions).toEqual([]); - expect(h.launches).toEqual([]); - expect(yield* h.fs.exists(h.profileDirectory)).toBe(false); - }).pipe(Effect.scoped), - ); - - it.effect.skipIf(windowsHost)("refreshes models after slow process startup", () => - Effect.gen(function* () { - const h = yield* makeHarness(); - const entered = yield* Deferred.make(); - const ready = yield* Deferred.make(); - h.controls.beforeAcquire = Deferred.succeed(entered, undefined).pipe( - Effect.andThen(Deferred.await(ready)), - ); - const refresh = yield* h.refresh().pipe(Effect.forkScoped); - yield* Deferred.await(entered); - yield* TestClock.adjust("70 seconds"); - yield* Deferred.succeed(ready, undefined); - yield* Fiber.join(refresh); - const snapshot = yield* h.instance.snapshot.getSnapshot; - expect(snapshot.auth.status).toBe("authenticated"); - expect(snapshot.models.length).toBeGreaterThan(0); - yield* h.assertClosed; - }).pipe(Effect.scoped), - ); - it.effect.skipIf(windowsHost)( "refreshes through the selected executable and personal Google ACP", () => @@ -382,42 +333,6 @@ it.layer(layerTest)("AntigravityDriver", (it) => { }).pipe(Effect.scoped), ); - it.effect.skipIf(windowsHost)( - "authenticates with the configured API key method and labels the account by method", - () => - Effect.gen(function* () { - const h = yield* makeHarness({ - config: { authMethod: "gemini-api-key", apiKey: "fixture-gemini-key" }, - }); - yield* h.refresh(); - const snapshot = yield* h.instance.snapshot.getSnapshot; - expect(snapshot.auth).toMatchObject({ - status: "authenticated", - type: "gemini-api-key", - label: "Gemini API key", - }); - expect(snapshot.models.length).toBeGreaterThan(0); - const nativeLaunches = h.launches.filter((launch) => launch.harnessPath !== undefined); - expect(nativeLaunches.map((launch) => launch.geminiApiKey)).toEqual(["fixture-gemini-key"]); - const requests = yield* h.readRequests; - expect( - requests - .filter((request) => request.method === "auth/login") - .map((request) => request.params?.methodId), - ).toEqual(["gemini-api-key"]); - yield* h.assertClosed; - }).pipe(Effect.scoped), - ); - - it.effect.skipIf(windowsHost)("reports the missing credential before launching a process", () => - Effect.gen(function* () { - const h = yield* makeHarness({ config: { authMethod: "gemini-api-key" } }); - const error = yield* h.refresh().pipe(Effect.flip); - expect(error.detail).toContain("API key"); - expect(h.launches.filter((launch) => launch.harnessPath !== undefined)).toEqual([]); - }).pipe(Effect.scoped), - ); - it.effect.skipIf(windowsHost)( "closes refresh processes and clears account metadata when Google sign-in is required", () => @@ -438,30 +353,6 @@ it.layer(layerTest)("AntigravityDriver", (it) => { }).pipe(Effect.scoped), ); - it.effect.skipIf(windowsHost)( - "clears account metadata when a text helper needs Google sign-in", - () => - Effect.gen(function* () { - const h = yield* makeHarness(); - yield* h.refresh(); - h.controls.selected = h.signedOut; - const error = yield* h.instance.textGeneration - .generateThreadTitle({ - cwd: h.profileDirectory, - message: "Repair Google login", - modelSelection: { instanceId: h.instance.instanceId, model: "gemini-test-low" }, - }) - .pipe(Effect.flip); - expect(error._tag).toBe("TextGenerationError"); - const snapshot = yield* h.instance.snapshot.getSnapshot; - expect(snapshot.auth.status).toBe("unauthenticated"); - expect(snapshot.models).toEqual([]); - expect(snapshot.supportsTextGeneration).toBe(false); - 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", () => Effect.gen(function* () { const h = yield* makeHarness(); @@ -479,26 +370,6 @@ it.layer(layerTest)("AntigravityDriver", (it) => { }).pipe(Effect.scoped), ); - it.effect.skipIf(windowsHost)( - "gives each process its own temp directory and removes it when the process closes", - () => - Effect.gen(function* () { - const h = yield* makeHarness(); - const tempRoot = h.directories.runtimeTemp; - yield* h.refresh(); - yield* h.refresh(); - const directories = h.launches.flatMap((launch) => - launch.tempDirectory === undefined ? [] : [launch.tempDirectory], - ); - expect(directories).toHaveLength(2); - for (const directory of directories) { - expect(h.path.dirname(directory)).toBe(tempRoot); - } - expect(new Set(directories).size).toBe(2); - yield* h.assertClosed; - }).pipe(Effect.scoped), - ); - it.effect.skipIf(windowsHost)( "removes runtime temp directories left by a previous server on create", () => @@ -536,15 +407,4 @@ it.layer(layerTest)("AntigravityDriver", (it) => { expect(yield* fs.exists(legacyRoot)).toBe(false); }).pipe(Effect.scoped), ); - - it.effect("probes through installation resolution without launching a process", () => - Effect.gen(function* () { - const h = yield* makeHarness({ enabled: true }); - const snapshot = yield* h.instance.snapshot.refresh; - expect(snapshot.installed).toBe(true); - expect(snapshot.version).toBe(h.first.version); - expect(h.launches).toEqual([]); - expect(h.acquisitions).toEqual([]); - }).pipe(Effect.scoped), - ); }); diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index 7a77aa6beb1ab..fe974dee763ff 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -93,435 +93,434 @@ export const AntigravityDriver: ProviderDriver< configSchema: AntigravitySettings, defaultConfig: () => decodeSettings({}), usage: AntigravityUsage.antigravityUsageReader, - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => - Effect.gen(function* () { - const crypto = yield* Crypto.Crypto; - const fileSystem = yield* FileSystem.FileSystem; - const httpClient = yield* HttpClient.HttpClient; - const path = yield* Path.Path; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const host = yield* ProviderHost.ProviderHost; - const selfInvocation = yield* resolveSelfInvocation(); - const installation = yield* AntigravityInstallation.AntigravityInstallation; - const loggers = yield* ProviderEventLoggers.ProviderEventLoggers; - const modelCatalog = yield* ModelCatalog.ModelCatalog; - const currentCatalog = modelCatalog.current(DRIVER); - const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; - const makeNativeLogger = yield* makeAcpNativeLoggerFactory(); - const settings = { ...config, enabled } satisfies AntigravitySettings; - const auth: AntigravityAuthConfig = { - authMethod: settings.authMethod, - apiKey: settings.apiKey, - gcpProject: settings.gcpProject, - gcpLocation: settings.gcpLocation, - }; - const authConfigIssue = antigravityAuthConfigIssue(auth); - const processEnvironment = yield* mergeProviderInstanceEnvironment(environment); - const userHome = resolveAntigravityUserHome( - yield* HostProcess.Platform, - processEnvironment, - yield* HostProcess.HomeDirectory, + create: Effect.fn("AntigravityDriver.create")(function* ({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }) { + const crypto = yield* Crypto.Crypto; + const fileSystem = yield* FileSystem.FileSystem; + const httpClient = yield* HttpClient.HttpClient; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const host = yield* ProviderHost.ProviderHost; + const selfInvocation = yield* resolveSelfInvocation(); + const installation = yield* AntigravityInstallation.AntigravityInstallation; + const loggers = yield* ProviderEventLoggers.ProviderEventLoggers; + const modelCatalog = yield* ModelCatalog.ModelCatalog; + const currentCatalog = modelCatalog.current(DRIVER); + const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + const makeNativeLogger = yield* makeAcpNativeLoggerFactory(); + const settings = { ...config, enabled } satisfies AntigravitySettings; + const auth: AntigravityAuthConfig = { + authMethod: settings.authMethod, + apiKey: settings.apiKey, + gcpProject: settings.gcpProject, + gcpLocation: settings.gcpLocation, + }; + const authConfigIssue = antigravityAuthConfigIssue(auth); + const processEnvironment = yield* mergeProviderInstanceEnvironment(environment); + const userHome = resolveAntigravityUserHome( + yield* HostProcess.Platform, + processEnvironment, + yield* HostProcess.HomeDirectory, + ); + const directories = yield* resolveAntigravityInstanceDirectories( + host.paths.stateDir, + instanceId, + ).pipe( + Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(Path.Path, path), + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER, + instanceId, + detail: "Could not resolve the Antigravity profile directory.", + cause, + }), + ), + ); + const profileDirectory = directories.profile; + for (const directory of [ + directories.runtimeTemp, + path.join(profileDirectory, "antigravity-acp", "tmp"), + ]) { + yield* removeAntigravityRuntimeTempDirs(directory).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), ); - const directories = yield* resolveAntigravityInstanceDirectories( - host.paths.stateDir, - instanceId, - ).pipe( - Effect.provideService(Crypto.Crypto, crypto), - Effect.provideService(Path.Path, path), + } + const continuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER, + instanceId, + }); + const stampIdentity = withInstanceIdentity({ + instanceId, + driverKind: DRIVER, + displayName, + accentColor, + continuationGroupKey: continuationIdentity.continuationKey, + }); + const classifyModels = (draft: ServerProviderDraft) => + currentCatalog.pipe( + Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))), + ); + + const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* ( + input: Omit, + ): Effect.fn.Return< + AcpSessionRuntime.AcpSessionRuntime["Service"], + AcpError | ProviderSetupError, + Scope.Scope + > { + if (authConfigIssue !== null) { + return yield* new ProviderSetupError({ + instanceId, + operation: "configure", + detail: authConfigIssue, + }); + } + const executable = yield* installation.acquire(settings.binaryPath, processEnvironment).pipe( Effect.mapError( (cause) => - new ProviderDriverError({ - driver: DRIVER, + new ProviderSetupError({ instanceId, - detail: "Could not resolve the Antigravity profile directory.", + operation: "resolve", + detail: cause.detail, cause, }), ), ); - const profileDirectory = directories.profile; - for (const directory of [ - directories.runtimeTemp, - path.join(profileDirectory, "antigravity-acp", "tmp"), - ]) { - yield* removeAntigravityRuntimeTempDirs(directory).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - ); - } - const continuationIdentity = defaultProviderContinuationIdentity({ - driverKind: DRIVER, - instanceId, - }); - const stampIdentity = withInstanceIdentity({ - instanceId, - driverKind: DRIVER, - displayName, - accentColor, - continuationGroupKey: continuationIdentity.continuationKey, - }); - const classifyModels = (draft: ServerProviderDraft) => - currentCatalog.pipe( - Effect.map((catalog) => stampIdentity(ModelCatalog.applyModelCatalog(draft, catalog))), - ); - - const makeRuntime = Effect.fn("AntigravityDriver.makeRuntime")(function* ( - input: Omit, - ): Effect.fn.Return< - AcpSessionRuntime.AcpSessionRuntime["Service"], - AcpError | ProviderSetupError, - Scope.Scope - > { - if (authConfigIssue !== null) { - return yield* new ProviderSetupError({ - instanceId, - operation: "configure", - detail: authConfigIssue, - }); - } - const executable = yield* installation - .acquire(settings.binaryPath, processEnvironment) - .pipe( - Effect.mapError( - (cause) => - new ProviderSetupError({ - instanceId, - operation: "resolve", - detail: cause.detail, - cause, - }), - ), - ); - const profile = yield* prepareAntigravityProfile({ - profileDirectory, - baseEnv: processEnvironment, - auth, - userHome, - tempDirectory: directories.runtimeTemp, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.mapError((cause) => - isNodeRuntimeUnavailableError(cause.cause) - ? new ProviderSetupError({ - instanceId, - operation: "start", - detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"), - cause, - }) - : cause, - ), - ); - // Each process unpacks into its own directory that dies with the - // runtime scope, after the child is killed. A shared directory would - // let one session's teardown delete files a sibling still reads. - // Removal is best effort: a handle can outlive the kill on Windows, - // and the sweep on the next driver start reclaims what is left. - const runtimeTempDirectory = yield* Effect.acquireRelease( - fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe( - Effect.mapError( - (cause) => - new ProviderSetupError({ - instanceId, - operation: "start", - detail: "Could not create an Antigravity runtime temp directory.", - cause, - }), - ), + const profile = yield* prepareAntigravityProfile({ + profileDirectory, + baseEnv: processEnvironment, + auth, + userHome, + tempDirectory: directories.runtimeTemp, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.mapError((cause) => + isNodeRuntimeUnavailableError(cause.cause) + ? new ProviderSetupError({ + instanceId, + operation: "start", + detail: nodeRuntimeUnavailableMessage("Antigravity sign-in"), + cause, + }) + : cause, + ), + ); + // Use one directory per process; shared cleanup could delete files another session still reads. + // Remove after the child dies, best-effort on Windows where handles may outlive the kill; + // the next driver start sweeps leftovers. + const runtimeTempDirectory = yield* Effect.acquireRelease( + fileSystem.makeTempDirectory({ directory: profile.tempDirectory, prefix: "run-" }).pipe( + Effect.mapError( + (cause) => + new ProviderSetupError({ + instanceId, + operation: "start", + detail: "Could not create an Antigravity runtime temp directory.", + cause, + }), ), - (directory) => - fileSystem - .remove(directory, { recursive: true, force: true }) - .pipe( - Effect.catch(() => - Effect.logWarning("Could not remove an Antigravity runtime temp directory."), - ), + ), + (directory) => + fileSystem + .remove(directory, { recursive: true, force: true }) + .pipe( + Effect.catch(() => + Effect.logWarning("Could not remove an Antigravity runtime temp directory."), ), - ); - const runtime = yield* makeAntigravityAcpRuntime({ - ...input, - authMethod: auth.authMethod, - childProcessSpawner: spawner, - spawn: buildAntigravityAcpSpawnInput({ - installation: executable, - profile, - cwd: input.cwd, - baseEnv: withAgentDeviceEnvironment(processEnvironment, input), - auth, - runtimeTempDirectory, - }), - }).pipe(Effect.provideService(Crypto.Crypto, crypto)); - return { - ...runtime, - start: () => - runtime - .start() - .pipe( - Effect.tapError((cause): Effect.Effect => - input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause) - ? provider.onAuthRequired - : Effect.void, - ), + ), + ); + const runtime = yield* makeAntigravityAcpRuntime({ + ...input, + authMethod: auth.authMethod, + childProcessSpawner: spawner, + spawn: buildAntigravityAcpSpawnInput({ + installation: executable, + profile, + cwd: input.cwd, + baseEnv: withAgentDeviceEnvironment(processEnvironment, input), + auth, + runtimeTempDirectory, + }), + }).pipe(Effect.provideService(Crypto.Crypto, crypto)); + return { + ...runtime, + start: () => + runtime + .start() + .pipe( + Effect.tapError((cause): Effect.Effect => + input.onAuthorizationUrl === undefined && isAntigravitySignInRequiredError(cause) + ? provider.onAuthRequired + : Effect.void, ), - }; - }); - - const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* ( - input: Pick, - ) { - const cwd = yield* fileSystem - .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" }) - .pipe( - Effect.mapError( - () => - new ProviderSetupError({ - instanceId, - operation: "start", - detail: "Could not create an Antigravity setup workspace.", - }), ), - ); - let sessionId: string | undefined; - yield* Effect.addFinalizer(() => - removeAntigravitySessionFiles({ - profileDirectory, - sessionId, - cwd, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), + }; + }); + + const makeDisposableRuntime = Effect.fn("AntigravityDriver.makeDisposableRuntime")(function* ( + input: Pick, + ) { + const cwd = yield* fileSystem + .makeTempDirectoryScoped({ prefix: "t3-antigravity-setup-" }) + .pipe( + Effect.mapError( + () => + new ProviderSetupError({ + instanceId, + operation: "start", + detail: "Could not create an Antigravity setup workspace.", + }), ), ); - const runtime = yield* makeRuntime({ + let sessionId: string | undefined; + yield* Effect.addFinalizer(() => + removeAntigravitySessionFiles({ + profileDirectory, + sessionId, cwd, - clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" }, - mcpServers: [], - ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}), - }); - return { - ...runtime, - start: () => - runtime.start().pipe( - Effect.tap((started) => - Effect.sync(() => { - sessionId = started.sessionId; - }), - ), - ), - }; - }); - - const publishCatalog = ( - started: AcpSessionRuntime.AcpSessionRuntimeStartResult, - runtime: Pick, - ): Effect.Effect => - Effect.gen(function* () { - yield* provider.onSessionStarted(started); - yield* Stream.runForEach(runtime.getEvents(), (event) => { - if (event._tag === "EventStreamBarrier") { - return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid); - } - if (event._tag === "ConfigOptionsUpdated") { - return provider.onConfigOptionsUpdated(event.configOptions); - } - return event._tag === "AvailableCommandsUpdated" - ? provider.onAvailableCommands(event.availableCommands) - : Effect.void; - }).pipe(Effect.forkScoped); - yield* runtime.drainEvents; - }).pipe(Effect.scoped); - - const authFlow: AntigravityAuth = yield* makeAntigravityAuth({ - instanceId, - makeRuntime: makeDisposableRuntime, - onAuthenticated: publishCatalog, - onSignedOut: Effect.suspend(() => provider.onSignedOut), - usesBrowser: antigravityAuthUsesBrowser(auth.authMethod), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + ); + const runtime = yield* makeRuntime({ + cwd, + clientInfo: { name: "t3-code-provider-setup", version: "0.0.0" }, + mcpServers: [], + ...(input.onAuthorizationUrl ? { onAuthorizationUrl: input.onAuthorizationUrl } : {}), }); + return { + ...runtime, + start: () => + runtime.start().pipe( + Effect.tap((started) => + Effect.sync(() => { + sessionId = started.sessionId; + }), + ), + ), + }; + }); - // The probe must not spawn. The agent is a PyInstaller one-file bundle - // that unpacks about 1 GB per launch, and the health check runs every - // minute. - const probe = Effect.gen(function* () { - yield* modelCatalog.refreshInBackground; - if (authConfigIssue !== null) { - return yield* new ProviderSetupError({ - instanceId, - operation: "configure", - detail: authConfigIssue, - }); + const publishCatalog = Effect.fn("AntigravityDriver.publishCatalog")(function* ( + started: AcpSessionRuntime.AcpSessionRuntimeStartResult, + runtime: Pick, + ) { + yield* provider.onSessionStarted(started); + yield* Stream.runForEach(runtime.getEvents(), (event) => { + if (event._tag === "EventStreamBarrier") { + return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid); } - const executable = yield* installation - .resolve(settings.binaryPath, processEnvironment) - .pipe( - Effect.mapError( - (cause) => - new ProviderSetupError({ - instanceId, - operation: "resolve", - detail: cause.detail, - cause, - }), - ), - ); - return { - protocolVersion: 1, - agentCapabilities: { - loadSession: true, - promptCapabilities: { image: true, audio: true, embeddedContext: true }, - sessionCapabilities: { list: {}, resume: {} }, - }, - authMethods: [{ id: "oauth-personal", name: "Log in with Google" }], - agentInfo: { - name: "antigravity-acp", - title: "Google Antigravity", - version: executable.version ?? "unknown", - }, - }; - }); + if (event._tag === "ConfigOptionsUpdated") { + return provider.onConfigOptionsUpdated(event.configOptions); + } + return event._tag === "AvailableCommandsUpdated" + ? provider.onAvailableCommands(event.availableCommands) + : Effect.void; + }).pipe(Effect.forkScoped); + yield* runtime.drainEvents; + }, Effect.scoped); - const usage = yield* makeAntigravityUsageProbe({ - profileDirectory, - authMethod: auth.authMethod, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.provideService(Crypto.Crypto, crypto), - Effect.provideService(HttpClient.HttpClient, httpClient), - ); - const provider = yield* makeAntigravityProvider(settings, { - stampIdentity: classifyModels, - probe, - probeUsage: usage.probe, - clearUsage: usage.clear, - auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, - supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.orElseSucceed(() => false), - ), - }).pipe( + const authFlow: AntigravityAuth = yield* makeAntigravityAuth({ + instanceId, + makeRuntime: makeDisposableRuntime, + onAuthenticated: publishCatalog, + onSignedOut: Effect.suspend(() => provider.onSignedOut), + usesBrowser: antigravityAuthUsesBrowser(auth.authMethod), + }); + + // The probe must not spawn. The agent is a PyInstaller one-file bundle + // that unpacks about 1 GB per launch, and the health check runs every + // minute. + const probe = Effect.gen(function* () { + yield* modelCatalog.refreshInBackground; + if (authConfigIssue !== null) { + return yield* new ProviderSetupError({ + instanceId, + operation: "configure", + detail: authConfigIssue, + }); + } + const executable = yield* installation.resolve(settings.binaryPath, processEnvironment).pipe( Effect.mapError( (cause) => - new ProviderDriverError({ - driver: DRIVER, + new ProviderSetupError({ instanceId, - detail: "Could not prepare the Antigravity provider status.", + operation: "resolve", + detail: cause.detail, cause, }), ), ); - const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel)); - const orchestrationAdapter = yield* makeAntigravityAdapterV2({ - instanceId, - selfInvocation, - makeRuntime, - withProcess: authFlow.withProcess, - defaultModel, - onSessionStarted: provider.onSessionStarted, - onSessionEvent: (event) => { - if (event._tag === "ConfigOptionsUpdated") { - return provider.onConfigOptionsUpdated(event.configOptions); - } - return event._tag === "AvailableCommandsUpdated" - ? provider.onAvailableCommands(event.availableCommands) - : Effect.void; + return { + protocolVersion: 1, + agentCapabilities: { + loadSession: true, + promptCapabilities: { image: true, audio: true, embeddedContext: true }, + sessionCapabilities: { list: {}, resume: {} }, }, - continuationRequests, - nativeLogging: (threadId) => - makeNativeLogger({ - nativeEventLogger: loggers.native, - provider: DRIVER, - threadId, - }), - }); - const textGeneration = yield* makeAntigravityTextGeneration({ - profileDirectory, - defaultModel, - withProcess: authFlow.withProcess, - makeRuntime: (cwd) => - makeRuntime({ - cwd, - clientInfo: { name: "t3-code-text", version: "0.0.0" }, - mcpServers: [], - }), - }); - - const refreshModels = Effect.fn("AntigravityDriver.refreshModels")( - function* () { - const processScope = yield* Scope.make(); - yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit)); - yield* authFlow - .withProcess( - Scope.close(processScope, Exit.void), - Effect.gen(function* () { - const runtime = yield* makeDisposableRuntime({}); - const started = yield* runtime.start(); - yield* publishCatalog(started, runtime); - }), - ) - .pipe(Effect.provideService(Scope.Scope, processScope)); + authMethods: [{ id: "oauth-personal", name: "Log in with Google" }], + agentInfo: { + name: "antigravity-acp", + title: "Google Antigravity", + version: executable.version ?? "unknown", }, - Effect.scoped, - Effect.timeoutOrElse({ - duration: "90 seconds", - orElse: () => - Effect.fail( - new ProviderDriverError({ - driver: DRIVER, - instanceId, - detail: "Antigravity model refresh timed out. Try again or check Google sign-in.", - }), - ), + }; + }); + + const usage = yield* makeAntigravityUsageProbe({ + profileDirectory, + authMethod: auth.authMethod, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(Crypto.Crypto, crypto), + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + const provider = yield* makeAntigravityProvider(settings, { + stampIdentity: classifyModels, + probe, + probeUsage: usage.probe, + clearUsage: usage.clear, + auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) }, + supportsTextGeneration: isAntigravityTextGenerationAvailable(profileDirectory).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.orElseSucceed(() => false), + ), + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER, + instanceId, + detail: "Could not prepare the Antigravity provider status.", + cause, + }), + ), + ); + const defaultModel = currentCatalog.pipe(Effect.map((catalog) => catalog?.defaultChatModel)); + const orchestrationAdapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation, + makeRuntime, + withProcess: authFlow.withProcess, + defaultModel, + onSessionStarted: provider.onSessionStarted, + onSessionEvent: (event) => { + if (event._tag === "ConfigOptionsUpdated") { + return provider.onConfigOptionsUpdated(event.configOptions); + } + return event._tag === "AvailableCommandsUpdated" + ? provider.onAvailableCommands(event.availableCommands) + : Effect.void; + }, + continuationRequests, + nativeLogging: (threadId) => + makeNativeLogger({ + nativeEventLogger: loggers.native, + provider: DRIVER, + threadId, }), - Effect.tapError((cause) => - isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void, - ), - Effect.mapError((cause) => - cause._tag === "ProviderDriverError" - ? cause - : new ProviderDriverError({ - driver: DRIVER, - instanceId, - detail: isAntigravitySignInRequiredError(cause) - ? "Sign in to Antigravity in provider settings before refreshing models." - : cause._tag === "ProviderSetupError" && - (cause.operation === "configure" || cause.operation === "start") - ? cause.detail - : "Could not refresh Antigravity models. The previous model list is unchanged.", - cause, - }), - ), - ); + }); + const textGeneration = yield* makeAntigravityTextGeneration({ + profileDirectory, + defaultModel, + withProcess: authFlow.withProcess, + makeRuntime: (cwd) => + makeRuntime({ + cwd, + clientInfo: { name: "t3-code-text", version: "0.0.0" }, + mcpServers: [], + }), + }); - return { - instanceId, - driverKind: DRIVER, - continuationIdentity, - displayName, - accentColor, - enabled, - snapshot: provider.snapshot, - snapshotForCwd: (cwd) => - !enabled - ? provider.snapshot.getSnapshot - : discoverAntigravitySkills({ cwd, userHome }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)), - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER, - instanceId, - detail: "Could not read Antigravity workspace skills.", - cause, - }), - ), + const refreshModels = Effect.fn("AntigravityDriver.refreshModels")( + function* () { + const processScope = yield* Scope.make(); + yield* Effect.addFinalizer((exit) => Scope.close(processScope, exit)); + yield* authFlow + .withProcess( + Scope.close(processScope, Exit.void), + Effect.gen(function* () { + const runtime = yield* makeDisposableRuntime({}); + const started = yield* runtime.start(); + yield* publishCatalog(started, runtime); + }), + ) + .pipe(Effect.provideService(Scope.Scope, processScope)); + }, + Effect.scoped, + Effect.timeoutOrElse({ + duration: "90 seconds", + orElse: () => + Effect.fail( + new ProviderDriverError({ + driver: DRIVER, + instanceId, + detail: "Antigravity model refresh timed out. Try again or check Google sign-in.", + }), + ), + }), + Effect.tapError((cause) => + isAntigravitySignInRequiredError(cause) ? provider.onAuthRequired : Effect.void, + ), + Effect.mapError((cause) => + cause._tag === "ProviderDriverError" + ? cause + : new ProviderDriverError({ + driver: DRIVER, + instanceId, + detail: isAntigravitySignInRequiredError(cause) + ? "Sign in to Antigravity in provider settings before refreshing models." + : cause._tag === "ProviderSetupError" && + (cause.operation === "configure" || cause.operation === "start") + ? cause.detail + : "Could not refresh Antigravity models. The previous model list is unchanged.", + cause, + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot: provider.snapshot, + snapshotForCwd: (cwd) => + !enabled + ? provider.snapshot.getSnapshot + : discoverAntigravitySkills({ cwd, userHome }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.flatMap((skills) => provider.snapshotForCwd(cwd, skills)), + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER, + instanceId, + detail: "Could not read Antigravity workspace skills.", + cause, + }), ), - orchestrationAdapter, - textGeneration, - auth: authFlow.controller, - refreshModels, - } satisfies ProviderInstance; - }), + ), + orchestrationAdapter, + textGeneration, + auth: authFlow.controller, + refreshModels, + } satisfies ProviderInstance; + }), }; diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 4293e800f56b1..5060d8a24e5ed 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -4,7 +4,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; -import { discoverAntigravitySkills, resolveAntigravityUserHome } from "./AntigravitySkills.ts"; +import { discoverAntigravitySkills } from "./AntigravitySkills.ts"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; const writeSkill = Effect.fn("writeSkill")(function* (directory: string, contents: string) { @@ -93,34 +93,6 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("returns no skills when the native roots are missing", () => - Effect.gen(function* () { - const input = yield* makeWorkspace(); - assert.deepEqual(yield* discoverAntigravitySkills(input), []); - }), - ); - - it.effect("discovers skills from the legacy workspace root", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const input = yield* makeWorkspace(); - const skillPath = yield* writeSkill( - path.join(input.cwd, ".agent", "skills", "review"), - "---\nname: review\ndescription: Review changes.\n---\n", - ); - - assert.deepEqual(yield* discoverAntigravitySkills(input), [ - { - name: "review", - description: "Review changes.", - path: skillPath, - scope: "project", - enabled: true, - }, - ]); - }), - ); - it.effect("uses native root order for duplicate names", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -340,38 +312,3 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); }); - -it("resolves the home the agent expands ~ against", () => { - assert.equal( - resolveAntigravityUserHome( - "linux", - { HOME: "/home/user", USERPROFILE: "C:\\Users\\user" }, - "/home/fallback", - ), - "/home/user", - ); - assert.equal( - resolveAntigravityUserHome( - "win32", - { HOME: "/home/user", USERPROFILE: "C:\\Users\\user" }, - "/home/fallback", - ), - "C:\\Users\\user", - ); - assert.equal( - resolveAntigravityUserHome( - "win32", - { HOMEDRIVE: "D:", HOMEPATH: "\\Users\\alice" }, - "/home/fallback", - ), - "D:\\Users\\alice", - ); - assert.equal( - resolveAntigravityUserHome("darwin", { HOME: "/Users/a b " }, "/home/fallback"), - "/Users/a b ", - ); - assert.equal( - resolveAntigravityUserHome("darwin", { HOME: "" }, "/home/fallback"), - "/home/fallback", - ); -}); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 7b25e24d90817..19e9d8d293f48 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -7,12 +7,7 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { parse as parseYamlDocument } from "yaml"; -/** - * The home directory the agent expands `~` against, matching Python's - * `os.path.expanduser` in the launch environment T3 hands the process: - * `USERPROFILE`, then `HOMEDRIVE` + `HOMEPATH`, on Windows and `HOME` - * elsewhere. - */ +/** Match Python os.path.expanduser: USERPROFILE, then HOMEDRIVE+HOMEPATH on Windows; HOME elsewhere. */ export function resolveAntigravityUserHome( platform: NodeJS.Platform, environment: NodeJS.ProcessEnv, @@ -28,12 +23,7 @@ export function resolveAntigravityUserHome( return environment.HOME || home; } -/** - * The agent resolves both under `GEMINI_HOME`, which T3 points at a private - * profile, so the profile links these back to the user's `~/.gemini`. - * `~/.agents/skills` is not read: the agent only treats `.agents/skills` as a - * project directory. - */ +/** Link private GEMINI_HOME skills to ~/.gemini; ~/.agents/skills is ignored because .agents/skills is project-only. */ export function antigravityUserSkillDirectories( path: Path.Path, geminiHome: string, @@ -147,9 +137,7 @@ const readSkill = Effect.fn("readAntigravitySkill")(function* ( return bytes.toString("utf8"); }); -/** - * Read failures remain typed so workspace snapshots do not cache partial results. - */ +/** Keep read errors typed so workspace snapshots cannot cache partial results. */ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(function* (input: { readonly cwd: string; readonly userHome: string; diff --git a/apps/server/src/provider/Drivers/AntigravityUsage.ts b/apps/server/src/provider/Drivers/AntigravityUsage.ts index faa2e4a0c8685..02168fdd83149 100644 --- a/apps/server/src/provider/Drivers/AntigravityUsage.ts +++ b/apps/server/src/provider/Drivers/AntigravityUsage.ts @@ -32,12 +32,13 @@ const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const host = yield* ProviderHost.ProviderHost; - const hostEnvironment = yield* HostProcess.Environment; const cache = makeAntigravityUsageCache(); - const dataRoots = Effect.gen(function* () { + const dataRoots = Effect.fn("AntigravityUsage.dataRoots")(function* ( + environment: NodeJS.ProcessEnv, + ) { const home = yield* HostProcess.HomeDirectory; - const configured = hostEnvironment["ANTIGRAVITY_DATA_DIR"] + const configured = environment["ANTIGRAVITY_DATA_DIR"] ?.split(",") .map((value) => value.trim()) .filter(Boolean); @@ -61,7 +62,8 @@ const make = Effect.gen(function* () { instances, windowStartMs, }) { - const roots = yield* dataRoots; + const roots: Array = []; + for (const instance of instances) roots.push(...(yield* dataRoots(instance.environment))); for (const { instanceId } of instances.filter((instance) => instance.configured)) { const directories = yield* resolveAntigravityInstanceDirectories( host.paths.stateDir, diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 67a217294294b..86832d53d3119 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -3,8 +3,10 @@ import * as Cache from "effect/Cache"; import * as Duration from "effect/Duration"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; @@ -29,6 +31,7 @@ import { makePendingClaudeProvider, probeClaudeCapabilities, probeClaudeWorkspaceSnapshot, + type ClaudeCapabilitiesProbe, } from "../ClaudeProvider.ts"; import { makeManagedServerProvider } from "@t3tools/provider-core/server/managedProvider"; import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog"; @@ -63,6 +66,12 @@ const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings); const DRIVER_KIND = ProviderDriverKind.make("claudeAgent"); const CAPABILITIES_PROBE_TTL = Duration.minutes(5); +const withoutUsage = (capabilities: ClaudeCapabilitiesProbe): ClaudeCapabilitiesProbe => { + const result = { ...capabilities }; + delete result.usage; + return result; +}; + function isClaudeNativeCommandPath(commandPath: string): boolean { const normalized = normalizeCommandPath(commandPath); return ( @@ -104,255 +113,300 @@ export const ClaudeDriver: ProviderDriver decodeClaudeSettings({}), usage: claudeUsageReader, - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => - Effect.gen(function* () { - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - // The server cwd is $HOME in packaged desktop builds, and `claude` - // wrappers that scope themselves to their cwd refuse to run there. - const { stateDir } = yield* ServerConfig.ServerConfig; - const httpClient = yield* HttpClient.HttpClient; - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; - const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator; - const catalogService = yield* ModelCatalog.ModelCatalog; - const modelCatalog = catalogService - .current(DRIVER_KIND) - .pipe(Effect.map(resolveClaudeModelCatalog)); - const processEnv = yield* mergeProviderInstanceEnvironment(environment); - const fallbackContinuationIdentity = defaultProviderContinuationIdentity({ - driverKind: DRIVER_KIND, - instanceId, - }); - const effectiveConfig = { - ...config, - enabled, - binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory), - } satisfies ClaudeSettings; - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( - resolveProviderMaintenanceCapabilitiesEffect(UPDATE, { - binaryPath: effectiveConfig.binaryPath, - env: processEnv, - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - ), - ); - const continuationGroupKey = yield* makeClaudeContinuationGroupKey( - effectiveConfig, - processEnv, - ); - const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv); - const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath( - effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim() - ? configDir - : undefined, - ); - const stampIdentity = withInstanceIdentity({ + create: Effect.fn("ClaudeDriver.create")(function* ({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + // The server cwd is $HOME in packaged desktop builds, and `claude` + // wrappers that scope themselves to their cwd refuse to run there. + const { stateDir } = yield* ServerConfig.ServerConfig; + const httpClient = yield* HttpClient.HttpClient; + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator; + const catalogService = yield* ModelCatalog.ModelCatalog; + const modelCatalog = catalogService + .current(DRIVER_KIND) + .pipe(Effect.map(resolveClaudeModelCatalog)); + const processEnv = yield* mergeProviderInstanceEnvironment(environment); + const fallbackContinuationIdentity = defaultProviderContinuationIdentity({ + driverKind: DRIVER_KIND, + instanceId, + }); + const effectiveConfig = { + ...config, + enabled, + binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory), + } satisfies ClaudeSettings; + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( + resolveProviderMaintenanceCapabilitiesEffect(UPDATE, { + binaryPath: effectiveConfig.binaryPath, + env: processEnv, + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + ); + const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig, processEnv); + const configDir = yield* resolveClaudeHomePath(effectiveConfig, processEnv); + const accountConfigPath = yield* ClaudeResetCredits.claudeAccountConfigPath( + effectiveConfig.homePath.trim() || processEnv.CLAUDE_CONFIG_DIR?.trim() + ? configDir + : undefined, + ); + const stampIdentity = withInstanceIdentity({ + instanceId, + driverKind: DRIVER_KIND, + displayName, + accentColor, + continuationGroupKey, + }); + + const scopedLimitNames = yield* makeClaudeScopedLimitNames; + const orchestrationAdapter = yield* createClaudeAdapterV2( + { instanceId, - driverKind: DRIVER_KIND, displayName, accentColor, - continuationGroupKey, - }); - - const scopedLimitNames = yield* makeClaudeScopedLimitNames; - const orchestrationAdapter = yield* createClaudeAdapterV2( - { - instanceId, - displayName, - accentColor, - environment, - enabled, - config, - }, - { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) }, - ).pipe( - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: "Failed to build Claude orchestration adapter.", - cause, - }), - ), - ); - const textGeneration = yield* makeClaudeTextGeneration( - effectiveConfig, - processEnv, - modelCatalog, - ); + environment, + enabled, + config, + }, + { scopedLimitNames, onUsageLimits: (update) => snapshot.applyUsageLimits(update) }, + ).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Claude orchestration adapter.", + cause, + }), + ), + ); + const textGeneration = yield* makeClaudeTextGeneration( + effectiveConfig, + processEnv, + modelCatalog, + ); - // Per-instance capabilities cache: keyed on binary + resolved HOME so - // account-specific probes never share auth metadata across instances. - const capabilitiesProbeCache = yield* Cache.make({ - capacity: 1, - timeToLive: CAPABILITIES_PROBE_TTL, - lookup: () => - Effect.all([ - probeClaudeCapabilities(effectiveConfig, processEnv, stateDir), - ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath), - ]).pipe( - Effect.map(([capabilities, workspaceId]) => - capabilities && workspaceId ? { ...capabilities, workspaceId } : capabilities, + // Per-instance capabilities cache: keyed on binary + resolved HOME so + // account-specific probes never share auth metadata across instances. + // A transient miss may reuse the last account once, but its usage windows keep their age. + const lastGoodCapabilities = yield* Ref.make(undefined); + const capabilitiesProbeCache = yield* Cache.makeWith( + () => + probeClaudeCapabilities(effectiveConfig, processEnv, stateDir).pipe( + Effect.flatMap((capabilities) => + ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe( + Effect.map((workspaceId) => ({ + _tag: "fresh" as const, + capabilities: + workspaceId === undefined ? capabilities : { ...capabilities, workspaceId }, + })), ), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), ), - }); - const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey( - effectiveConfig, - stateDir, - processEnv, - ); - - const checkProvider = catalogService.refreshInBackground.pipe( - Effect.andThen( - modelCatalog.pipe( - Effect.flatMap((catalog) => - checkClaudeProviderStatus( - effectiveConfig, - () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey), - processEnv, - stateDir, - catalog, - scopedLimitNames, - (version) => - ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe( - Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - ), + Effect.tap(({ capabilities }) => Ref.set(lastGoodCapabilities, capabilities)), + Effect.catch((error) => + Ref.getAndSet(lastGoodCapabilities, undefined).pipe( + Effect.flatMap((capabilities) => + capabilities === undefined + ? Effect.fail(error) + : ClaudeResetCredits.readClaudeOrganizationId(accountConfigPath).pipe( + Effect.flatMap((workspaceId) => + workspaceId === capabilities.workspaceId + ? Effect.succeed({ + _tag: "fallback" as const, + capabilities: withoutUsage(capabilities), + }) + : Effect.fail(error), + ), + ), ), ), - Effect.map(stampIdentity), ), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), ), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - ); + { + capacity: 1, + timeToLive: (exit) => + // Only fresh usage earns the TTL; failures, fallbacks and usage-less probes retry. + Exit.isSuccess(exit) && + exit.value._tag === "fresh" && + exit.value.capabilities.usage !== undefined + ? CAPABILITIES_PROBE_TTL + : Duration.zero, + }, + ); + const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey( + effectiveConfig, + stateDir, + processEnv, + ); + const resolveCapabilities = Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe( + Effect.map((result) => result.capabilities), + ); - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); - const snapshot = yield* makeManagedServerProvider>({ - resolveMaintenance, - getSettings: snapshotSettings.getSettings, - streamSettings: snapshotSettings.streamSettings, - haveSettingsChanged: haveProviderSnapshotSettingsChanged, - initialSnapshot: (settings) => - modelCatalog.pipe( - Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)), - Effect.map(stampIdentity), - ), - checkProvider, - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => - resolveMaintenance().pipe( - Effect.flatMap((maintenanceCapabilities) => - enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, { - enableProviderUpdateChecks: settings.enableProviderUpdateChecks, - }), + const checkProvider = catalogService.refreshInBackground.pipe( + Effect.andThen( + modelCatalog.pipe( + Effect.flatMap((catalog) => + checkClaudeProviderStatus( + effectiveConfig, + () => resolveCapabilities, + processEnv, + stateDir, + catalog, + scopedLimitNames, + (version) => + ClaudeResetCredits.readClaudeResetCredits(configDir, version).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), ), - Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), - Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)), ), - }).pipe( - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`, - cause, - }), + Effect.tap((provider) => + provider.auth.status === "unauthenticated" + ? Cache.invalidateAll(capabilitiesProbeCache) + : Effect.void, + ), + Effect.map(stampIdentity), ), - ); + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); - // Same rules as Codex: serialised on the config directory that holds the - // login, one request id kept until Claude answers (a cooldown or rate - // limit is an answer), then a re-probe. - const consumeResetCredit: NonNullable = () => - Effect.gen(function* () { - const current = yield* snapshot.getSnapshot; - const grantId = current.usageLimits?.resetCredits?.nextCreditId; - if (!grantId || !current.version) return "noCredit" as const; - const version = current.version; - return yield* resetCreditCoordinator.redeem( - configDir, - (requestId) => - ClaudeResetCredits.consumeClaudeResetCredit({ - configDir, - accountConfigPath, - version, - grantId, - requestId, - }), - ClaudeResetCredits.isSettledClaudeResetCreditFailure, - ); - }).pipe( - Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: - cause._tag === "ClaudeResetCreditError" - ? cause.message - : "Claude could not redeem the reset.", - cause, - }), - ), - Effect.tap((outcome) => - Effect.gen(function* () { - const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt; - yield* Cache.invalidateAll(capabilitiesProbeCache); - const refreshed = yield* snapshot.refresh; - const after = refreshed.usageLimits?.checkedAt; - if ( - outcome === "reset" && - (after === undefined || - after === before || - refreshed.usageLimits?.unavailable?.reason === "probeFailed") - ) { - return yield* new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: - "The reset was applied, but Claude could not confirm the new limits. Refresh to check.", - }); - } + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); + const snapshot = yield* makeManagedServerProvider>({ + resolveMaintenance, + getSettings: snapshotSettings.getSettings, + streamSettings: snapshotSettings.streamSettings, + haveSettingsChanged: haveProviderSnapshotSettingsChanged, + initialSnapshot: (settings) => + modelCatalog.pipe( + Effect.flatMap((catalog) => makePendingClaudeProvider(settings.provider, catalog)), + Effect.map(stampIdentity), + ), + checkProvider, + enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => + resolveMaintenance().pipe( + Effect.flatMap((maintenanceCapabilities) => + enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, { + enableProviderUpdateChecks: settings.enableProviderUpdateChecks, }), ), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), + Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)), + ), + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + + // Same rules as Codex: serialised on the config directory that holds the + // login, one request id kept until Claude answers (a cooldown or rate + // limit is an answer), then a re-probe. + const consumeResetCredit: NonNullable = Effect.fn( + "ClaudeDriver.consumeResetCredit", + )( + function* () { + const current = yield* snapshot.getSnapshot; + const grantId = current.usageLimits?.resetCredits?.nextCreditId; + if (!grantId || !current.version) return "noCredit" as const; + const version = current.version; + return yield* resetCreditCoordinator.redeem( + configDir, + (requestId) => + ClaudeResetCredits.consumeClaudeResetCredit({ + configDir, + accountConfigPath, + version, + grantId, + requestId, + }), + ClaudeResetCredits.isSettledClaudeResetCreditFailure, ); + }, + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: + cause._tag === "ClaudeResetCreditError" + ? cause.message + : "Claude could not redeem the reset.", + cause, + }), + ), + Effect.tap((outcome) => + Effect.gen(function* () { + const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt; + yield* Cache.invalidateAll(capabilitiesProbeCache); + const refreshed = yield* snapshot.refresh; + const after = refreshed.usageLimits?.checkedAt; + if ( + outcome === "reset" && + (after === undefined || + after === before || + refreshed.usageLimits?.unavailable?.reason === "probeFailed") + ) { + return yield* new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: + "The reset was applied, but Claude could not confirm the new limits. Refresh to check.", + }); + } + }), + ), + ); - return { - instanceId, - driverKind: DRIVER_KIND, - continuationIdentity: { - ...fallbackContinuationIdentity, - continuationKey: continuationGroupKey, - }, - displayName, - accentColor, - enabled, - snapshot, - invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache), - snapshotForCwd: (cwd: string) => - snapshot.getSnapshot.pipe( - Effect.flatMap((machineSnapshot) => - probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv), - ), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity: { + ...fallbackContinuationIdentity, + continuationKey: continuationGroupKey, + }, + displayName, + accentColor, + enabled, + snapshot, + invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache), + snapshotForCwd: (cwd: string) => + snapshot.getSnapshot.pipe( + Effect.flatMap((machineSnapshot) => + probeClaudeWorkspaceSnapshot(effectiveConfig, machineSnapshot, cwd, processEnv), ), - orchestrationAdapter, - textGeneration, - consumeResetCredit, - } satisfies ProviderInstance; - }), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + orchestrationAdapter, + textGeneration, + consumeResetCredit, + } satisfies ProviderInstance; + }), }; diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts index b03bd994a14bd..e1319caf69b16 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.test.ts @@ -24,30 +24,6 @@ function withWindowsResolution(input: { } describe("resolveClaudeSdkExecutablePath", () => { - it.effect("returns the configured path unchanged on non-Windows platforms", () => - Effect.gen(function* () { - expect( - yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( - Effect.provideService(HostProcess.Platform, "darwin"), - Effect.provideService(SpawnExecutableResolution, () => { - throw new Error("must not resolve on non-Windows platforms"); - }), - ), - ).toBe("claude"); - }), - ); - - it.effect("returns the resolved absolute path for native Windows executables", () => - Effect.gen(function* () { - const nativeBinary = "C:\\Users\\dev\\.local\\bin\\claude.exe"; - expect( - yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( - withWindowsResolution({ resolvedCommand: nativeBinary }), - ), - ).toBe(nativeBinary); - }), - ); - it.effect("follows an npm launcher shim to the packaged native binary", () => Effect.gen(function* () { expect( @@ -111,14 +87,4 @@ describe("resolveClaudeSdkExecutablePath", () => { ).toBe("claude"); }), ); - - it.effect("returns the configured path when command resolution finds nothing", () => - Effect.gen(function* () { - expect( - yield* resolveClaudeSdkExecutablePath("claude", {}).pipe( - withWindowsResolution({ resolvedCommand: undefined }), - ), - ).toBe("claude"); - }), - ); }); diff --git a/apps/server/src/provider/Drivers/ClaudeExecutable.ts b/apps/server/src/provider/Drivers/ClaudeExecutable.ts index e2bf2b99eefa1..5e4cbb4db6efe 100644 --- a/apps/server/src/provider/Drivers/ClaudeExecutable.ts +++ b/apps/server/src/provider/Drivers/ClaudeExecutable.ts @@ -7,20 +7,13 @@ import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; -/** - * Windows launcher-script extensions that Node cannot spawn without a shell - * (`spawn EINVAL` since Node 20.12) and that the Claude Agent SDK therefore - * cannot use as `pathToClaudeCodeExecutable`. - */ +/** Node 20.12+ cannot spawn Windows launcher scripts without a shell; the SDK cannot use these as executables. */ const WINDOWS_SHIM_EXTENSIONS: ReadonlySet = new Set([".cmd", ".bat", ".ps1"]); export const isWindowsClaudeLauncherShimPath = (filePath: string): boolean => WINDOWS_SHIM_EXTENSIONS.has(NodePath.win32.extname(filePath).toLowerCase()); -/** - * Newer package versions ship a native `bin/claude.exe`; older versions only ship `cli.js`, - * which the SDK runs with a JavaScript runtime. - */ +/** New packages provide bin/claude.exe; older packages need a JavaScript runtime for cli.js. */ const NPM_PACKAGE_ENTRY_CANDIDATES = [ ["node_modules", "@anthropic-ai", "claude-code", "bin", "claude.exe"], ["node_modules", "@anthropic-ai", "claude-code", "cli.js"], @@ -43,12 +36,7 @@ export const ClaudeExecutableFileCheck = Context.Reference( }, ); -/** - * The SDK spawns the given path without a shell and without Windows PATH / PATHEXT resolution, - * so a bare command name like `claude` fails with "native binary not found" and an npm - * `claude.cmd` shim fails with `spawn EINVAL`. CLI probes avoid this via `resolveSpawnCommand`, - * which can fall back to `shell: true`; the SDK offers no such escape hatch. - */ +/** On Windows the SDK skips shell and PATH/PATHEXT lookup: bare names and .cmd shims fail. */ export const resolveClaudeSdkExecutablePath = Effect.fn("resolveClaudeSdkExecutablePath")( function* (binaryPath: string, environment: NodeJS.ProcessEnv): Effect.fn.Return { const platform = yield* HostProcess.Platform; diff --git a/apps/server/src/provider/Drivers/ClaudeHome.test.ts b/apps/server/src/provider/Drivers/ClaudeHome.test.ts index fb1caf753f869..b9eb3b806ce0a 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.test.ts @@ -6,7 +6,6 @@ import * as Effect from "effect/Effect"; import * as Path from "effect/Path"; import { - claudeSignedOutMessage, makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey, makeClaudeEnvironment, @@ -15,23 +14,6 @@ import { it.layer(NodeServices.layer)("ClaudeHome", (it) => { describe("Claude home resolution", () => { - it.effect("treats empty, ~/.claude, and the expanded default as the same Claude home", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const resolved = path.resolve(path.join(NodeOS.homedir(), ".claude")); - - expect(yield* resolveClaudeHomePath({ homePath: "" })).toBe(resolved); - expect(yield* resolveClaudeHomePath({ homePath: "~/.claude" })).toBe(resolved); - expect(yield* resolveClaudeHomePath({ homePath: resolved })).toBe(resolved); - expect(yield* makeClaudeEnvironment({ homePath: "" })).toBe(process.env); - - const key = `claude:home:${resolved}`; - expect(yield* makeClaudeContinuationGroupKey({ homePath: "" })).toBe(key); - expect(yield* makeClaudeContinuationGroupKey({ homePath: "~/.claude" })).toBe(key); - expect(yield* makeClaudeContinuationGroupKey({ homePath: resolved })).toBe(key); - }), - ); - it.effect("resolves configured Claude HOME and stamps continuation/cache keys with it", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -65,17 +47,6 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => { }), ); - it("points the signed-out hint at the configured Claude home", () => { - expect(claudeSignedOutMessage({ configDir: undefined, cwd: "/synthetic" })).toContain( - "run `claude auth login`", - ); - const configDir = "/synthetic/Claude work's $literal"; - const message = claudeSignedOutMessage({ configDir, cwd: "/synthetic/project" }); - expect(message).toContain(`CLAUDE_CONFIG_DIR set to "${configDir}"`); - expect(message).not.toContain("CLAUDE_CONFIG_DIR="); - expect(message).toContain("then start a new thread"); - }); - it.effect("separates capability probes by cwd", () => Effect.gen(function* () { const config = { binaryPath: "claude", homePath: "" }; diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts index 0c7908b0264ca..bd81aa10bce7a 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -37,21 +37,12 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function const resolvedHomePath = yield* resolveClaudeHomePath(config); return { ...resolvedBaseEnv, - // Overriding HOME also relocates the macOS login keychain lookup - // ($HOME/Library/Keychains), so the spawned CLI can't find its stored - // OAuth credentials and reports "Not logged in". CLAUDE_CONFIG_DIR points - // Claude Code at its config dir directly while leaving HOME (and the - // keychain) intact. + // Changing HOME hides macOS Keychain credentials; use CLAUDE_CONFIG_DIR to keep login access. CLAUDE_CONFIG_DIR: resolvedHomePath, }; }); -/** - * While it exists Claude refuses `--strict-mcp-config` and exits before - * initializing, but it already ignores user, project and `--mcp-config` servers - * on its own, so callers that pass the flag for isolation can drop it. Paths - * match the ones Claude Code checks. - */ +/** managed-mcp.json excludes other MCP config and forbids --strict-mcp-config; omit the flag when present. */ export const hasClaudeManagedMcpConfig = Effect.fn("hasClaudeManagedMcpConfig")(function* () { const fileSystem = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; @@ -85,10 +76,7 @@ export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesC }, ); -/** - * Describe the spawned CLI's environment separately from the login command so - * paths remain literal on every shell, including relative inherited values. - */ +/** Separate spawn env from login commands to preserve literal paths, including relative inherited values. */ export const claudeSignedOutMessage = (input: { readonly configDir: string | undefined; readonly cwd: string; diff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts index abb80482a264f..975eb841b67a3 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts @@ -1,18 +1,24 @@ import { describe, expect, it } from "vite-plus/test"; -import { planClaudeSkillDispatch } from "./ClaudeSkillDispatch.ts"; +import { planClaudeSkillDispatch, type ClaudeSkillTarget } from "./ClaudeSkillDispatch.ts"; -const SKILLS = new Set(["2spec", "implement", "review", "re-release-version"]); +const skillPath = (name: string) => `/home/me/.claude/skills/${name}/SKILL.md`; + +const skillMap = (names: Iterable) => + new Map([...names].map((name) => [name, { path: skillPath(name) }])); + +const SKILLS = skillMap(["2spec", "implement", "review", "re-release-version"]); describe("planClaudeSkillDispatch", () => { + // regression: #9128 skills picked from the composer did not run it("leaves a prompt without a known skill untouched", () => { expect(planClaudeSkillDispatch("fix the build", SKILLS)).toBeUndefined(); expect(planClaudeSkillDispatch("echo $HOME then $unknown", SKILLS)).toBeUndefined(); }); - it("moves a mid-prompt mention into a trailing slash command", () => { + it("keeps the whole request ahead of a mid-prompt slash command", () => { expect(planClaudeSkillDispatch("ok, now $implement all the tickets", SKILLS)).toEqual({ - leadingText: "ok, now", + leadingText: "ok, now /implement all the tickets", commandText: "/implement all the tickets", skillName: "implement", }); @@ -26,17 +32,9 @@ describe("planClaudeSkillDispatch", () => { }); }); - it("dispatches a known skill whose name begins with a digit", () => { - expect(planClaudeSkillDispatch("use $2spec for this", SKILLS)).toEqual({ - leadingText: "use", - commandText: "/2spec for this", - skillName: "2spec", - }); - }); - it("dispatches the last mention and rewrites earlier ones inline", () => { expect(planClaudeSkillDispatch("$review the diff, then $implement the fixes", SKILLS)).toEqual({ - leadingText: "/review the diff, then", + leadingText: "/review the diff, then /implement the fixes", commandText: "/implement the fixes", skillName: "implement", }); @@ -50,7 +48,7 @@ describe("planClaudeSkillDispatch", () => { SKILLS, ), ).toEqual({ - leadingText: "/review the diff, then", + leadingText: "/review the diff, then /implement the fixes", commandText: "/implement the fixes", skillName: "implement", }); @@ -63,12 +61,8 @@ describe("planClaudeSkillDispatch", () => { } }); - it("ignores a dollar token glued to other text", () => { - expect(planClaudeSkillDispatch("cost is 5$implement", SKILLS)).toBeUndefined(); - }); - it("ignores currency amounts and compact monetary expressions", () => { - const skillsWithCurrency = new Set([...SKILLS, "20", "20k", "100M", "1e6"]); + const skillsWithCurrency = skillMap([...SKILLS.keys(), "20", "20k", "100M", "1e6"]); for (const symbol of ["$", "€", "£", "¥", "₹", "₩", "₿", "𑿝"]) { expect( planClaudeSkillDispatch( @@ -78,4 +72,21 @@ describe("planClaudeSkillDispatch", () => { ).toBeUndefined(); } }); + + it("bounds notes for repeated user-only skills and leaves the native dispatch unannotated", () => { + const skills = new Map([ + ["interrogate", { path: skillPath("interrogate"), userInvocationOnly: true }], + ["implement", { path: skillPath("implement"), userInvocationOnly: true }], + ]); + expect( + planClaudeSkillDispatch( + "$interrogate then $interrogate then $implement and $implement the fixes", + skills, + ), + ).toEqual({ + leadingText: `/interrogate [The user invoked this skill. Follow the instructions at: ${skillPath("interrogate")}] then /interrogate then /implement and /implement the fixes`, + commandText: "/implement the fixes", + skillName: "implement", + }); + }); }); diff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts index dac74b36c20bb..534308e9c2f4f 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts @@ -1,20 +1,19 @@ -/** - * Claude Code's only user-side invocation is a text block whose first character - * is `/`: the harness expands `/name args` into the SKILL.md body, and every - * character after the name (newlines included) arrives as `ARGUMENTS`. Only one - * skill expands per message; a second `/x` becomes argument text - * (anthropics/claude-code#87113). - */ +import type { ServerProviderSkill } from "@t3tools/contracts"; /** - * Same token shape the composer and timeline chips recognise - * (`packages/shared/src/composerInlineTokens.ts`), so a rendered chip and a - * dispatched skill are always the same set. + * Claude expands one skill per message only when `/name` starts the text block. + * Everything after the name, including newlines or a second `/x`, becomes `ARGUMENTS`. + * https://github.com/anthropics/claude-code/issues/87113 */ + +/** Match packages/shared/src/composerInlineTokens.ts so displayed chips and dispatched skills accept the same tokens. */ const SKILL_MENTION_PATTERN = /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu; +export type ClaudeSkillTarget = Pick; + export interface ClaudeSkillDispatch { + /** The whole prompt with mentions as `/name`, or `undefined` when the mention opens it. */ readonly leadingText: string | undefined; /** `/name` plus the trailing text, ready to be the message's last text block. */ readonly commandText: string; @@ -23,33 +22,39 @@ export interface ClaudeSkillDispatch { export function planClaudeSkillDispatch( prompt: string, - skillNames: ReadonlySet, + skills: ReadonlyMap, ): ClaudeSkillDispatch | undefined { const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => { const name = match[2] ?? ""; - if (!skillNames.has(name)) return []; + const skill = skills.get(name); + if (!skill) return []; const start = (match.index ?? 0) + (match[1]?.length ?? 0); - return [{ name, start, end: (match.index ?? 0) + match[0].length }]; + return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }]; }); const last = mentions.at(-1); if (!last) { return undefined; } - const leading = prompt.slice(0, last.start); - const trailing = prompt.slice(last.end); - const leadingWithInlineSlashes = mentions - .slice(0, -1) - .reduceRight( - (text, mention) => - `${text.slice(0, mention.start)}/${mention.name}${text.slice(mention.end)}`, - leading, - ) - .trimEnd(); + // Only the final skill gets native expansion. Earlier user-only skills need + // a fallback to their raw file because Claude's Skill tool refuses them. + const annotated = new Set([last.name]); + let promptWithInlineSlashes = ""; + let cursor = 0; + for (const mention of mentions) { + promptWithInlineSlashes += `${prompt.slice(cursor, mention.start)}/${mention.name}`; + if (mention.skill.userInvocationOnly === true && !annotated.has(mention.name)) { + promptWithInlineSlashes += ` [The user invoked this skill. Follow the instructions at: ${mention.skill.path}]`; + annotated.add(mention.name); + } + cursor = mention.end; + } + promptWithInlineSlashes = `${promptWithInlineSlashes}${prompt.slice(cursor)}`.trimEnd(); return { - leadingText: leadingWithInlineSlashes.length > 0 ? leadingWithInlineSlashes : undefined, - commandText: `/${last.name}${trailing}`.trimEnd(), + leadingText: + prompt.slice(0, last.start).trim().length > 0 ? promptWithInlineSlashes : undefined, + commandText: `/${last.name}${prompt.slice(last.end)}`.trimEnd(), skillName: last.name, }; } diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts index 4af478317c7f6..e331254c11718 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.test.ts @@ -1,11 +1,11 @@ -import * as NodePath from "@effect/platform-node/NodePath"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; -import { discoverClaudeSkills, skillOverrideSettingsPaths } from "./ClaudeSkills.ts"; +import { discoverClaudeSkills } from "./ClaudeSkills.ts"; +import { planClaudeSkillDispatch } from "./ClaudeSkillDispatch.ts"; const writeSkill = Effect.fn(function* ( skillsDir: string, @@ -20,6 +20,276 @@ const writeSkill = Effect.fn(function* ( }); it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { + it.effect("discovers enabled plugin skills with manifest names and ignores skill overrides", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(tempDir, "claude-home"); + const plugin = path.join(configDir, "plugins", "cache", "shop", "plugin", "1.0.0"); + const disabled = path.join(configDir, "plugins", "disabled"); + yield* writeSkill(path.join(disabled, "skills"), "hidden", "# Hidden"); + yield* writeSkill(path.join(plugin, "skills"), "plain", "# Plain"); + yield* writeSkill( + path.join(plugin, "engineering"), + "review", + "---\nname: review-alias\ndescription: Review changes.\ndisable-model-invocation: true\nuser-invocable: false\n---\n", + ); + yield* fs.makeDirectory(path.join(plugin, ".claude-plugin"), { recursive: true }); + yield* fs.writeFileString( + path.join(plugin, ".claude-plugin", "plugin.json"), + '{"name":"manifest-plugin","skills":["./engineering/review"]}', + ); + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ + plugins: { + "plugin@shop": [{ scope: "user", installPath: plugin }], + "disabled@shop": [{ scope: "user", installPath: disabled }], + "unconfigured@shop": [{ scope: "user", installPath: disabled }], + }, + }), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"plugin@shop":true,"disabled@shop":false,"uninstalled@shop":true,"other@shop":["^1.0.0"]},"skillOverrides":{"manifest-plugin:plain":"off"}}', + ); + + const skills = yield* discoverClaudeSkills({ homePath: configDir }); + assert.deepEqual(skills, [ + { + name: "manifest-plugin:plain", + path: path.join(plugin, "skills", "plain", "SKILL.md"), + enabled: true, + scope: "user", + }, + { + name: "manifest-plugin:review-alias", + path: path.join(plugin, "engineering", "review", "SKILL.md"), + enabled: true, + scope: "user", + description: "Review changes.", + userInvocationOnly: true, + userInvocable: false, + }, + ]); + }), + ); + + it.effect("merges plugin enablement and selects installs in native registry order", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(tempDir, "claude-home"); + const workspace = path.join(tempDir, "workspace"); + const nestedWorkspace = path.join(workspace, "packages", "app"); + const aliasedWorkspace = path.join(tempDir, "aliased-workspace"); + const userInstall = path.join(configDir, "plugins", "user"); + const projectInstall = path.join(configDir, "plugins", "project"); + const localInstall = path.join(configDir, "plugins", "local"); + const managedInstall = path.join(configDir, "plugins", "managed"); + yield* fs.makeDirectory(path.join(workspace, ".git"), { recursive: true }); + yield* fs.makeDirectory(nestedWorkspace, { recursive: true }); + yield* fs.symlink(workspace, aliasedWorkspace); + for (const install of [userInstall, projectInstall, localInstall, managedInstall]) { + yield* writeSkill(path.join(install, "skills"), "review", "# Review"); + } + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ + plugins: { + "plugin@shop": [ + { scope: "project", projectPath: aliasedWorkspace, installPath: localInstall }, + { scope: "project", projectPath: workspace, installPath: projectInstall }, + { scope: "user", installPath: userInstall }, + { scope: "managed", installPath: managedInstall }, + ], + "local@shop": [ + { scope: "local", projectPath: workspace, installPath: localInstall }, + { scope: "project", projectPath: workspace, installPath: projectInstall }, + { scope: "managed", installPath: path.join(configDir, "plugins", "missing") }, + { scope: "managed", installPath: managedInstall }, + { scope: "user", installPath: userInstall }, + ], + }, + }), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"plugin@shop":true,"local@shop":false}}', + ); + yield* fs.makeDirectory(path.join(workspace, ".claude"), { recursive: true }); + yield* fs.writeFileString( + path.join(workspace, ".claude", "settings.json"), + '{"enabledPlugins":{"plugin@shop":false,"local@shop":true,"other@shop":["^1.0.0"]}}', + ); + const projectSettings = yield* discoverClaudeSkills({ homePath: configDir }, workspace); + assert.deepEqual( + projectSettings.map((skill) => [skill.name, skill.scope, skill.path]), + [["local:review", "project", path.join(localInstall, "skills", "review", "SKILL.md")]], + ); + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, nestedWorkspace)).map((skill) => [ + skill.name, + skill.scope, + skill.path, + ]), + [["plugin:review", "project", path.join(projectInstall, "skills", "review", "SKILL.md")]], + ); + yield* fs.writeFileString( + path.join(workspace, ".claude", "settings.local.json"), + '{"enabledPlugins":{"plugin@shop":true,"local@shop":false},"skillOverrides":{"invalid":"bogus"}}', + ); + assert.deepEqual( + yield* discoverClaudeSkills({ homePath: configDir }, workspace), + projectSettings, + ); + yield* fs.writeFileString( + path.join(workspace, ".claude", "settings.local.json"), + '{"enabledPlugins":{"plugin@shop":true,"local@shop":true}}', + ); + const localSettings = yield* discoverClaudeSkills({ homePath: configDir }, workspace); + assert.deepEqual( + localSettings.map((skill) => [skill.name, skill.scope, skill.path]), + [ + ["local:review", "project", path.join(localInstall, "skills", "review", "SKILL.md")], + ["plugin:review", "project", path.join(projectInstall, "skills", "review", "SKILL.md")], + ], + ); + assert.deepEqual( + yield* discoverClaudeSkills({ homePath: configDir }, nestedWorkspace), + localSettings, + ); + assert.deepEqual( + yield* discoverClaudeSkills({ homePath: configDir }, aliasedWorkspace), + localSettings, + ); + yield* fs.writeFileString( + path.join(workspace, ".claude", "settings.local.json"), + '{"enabledPlugins":{"local@shop":["^1.0.0"]}}', + ); + assert.deepEqual(yield* discoverClaudeSkills({ homePath: configDir }, workspace), []); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"plugin@shop":true,"local@shop":true}}', + ); + const separateRepository = path.join(workspace, "separate"); + yield* fs.makeDirectory(path.join(separateRepository, ".git"), { recursive: true }); + for (const cwd of [undefined, path.join(tempDir, "elsewhere"), separateRepository]) { + const elsewhere = yield* discoverClaudeSkills({ homePath: configDir }, cwd); + assert.deepEqual( + elsewhere.map((skill) => [skill.name, skill.scope, skill.path]), + [ + ["local:review", "user", path.join(managedInstall, "skills", "review", "SKILL.md")], + ["plugin:review", "user", path.join(userInstall, "skills", "review", "SKILL.md")], + ], + ); + } + const worktree = path.join(tempDir, "worktree"); + const worktreeGitDirectory = path.join(workspace, ".git", "worktrees", "fixture"); + yield* fs.makeDirectory(worktree); + yield* fs.makeDirectory(worktreeGitDirectory, { recursive: true }); + yield* fs.writeFileString(path.join(worktree, ".git"), `gitdir: ${worktreeGitDirectory}\n`); + yield* fs.writeFileString(path.join(worktreeGitDirectory, "commondir"), "../..\n"); + yield* fs.writeFileString( + path.join(worktreeGitDirectory, "gitdir"), + path.join(worktree, ".git"), + ); + assert.deepEqual( + yield* discoverClaudeSkills({ homePath: configDir }, worktree), + localSettings, + ); + const linkedWorktree = path.join(tempDir, "linked-worktree"); + yield* fs.symlink(worktree, linkedWorktree); + assert.deepEqual( + yield* discoverClaudeSkills({ homePath: configDir }, linkedWorktree), + localSettings, + ); + }), + ); + + it.effect("publishes and dispatches canonical plugin folder names regardless of aliases", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const plugin = path.join(configDir, "plugins", "installed"); + yield* writeSkill(path.join(plugin, "skills"), "review", "---\nname: review-alias\n---\n"); + yield* writeSkill(path.join(plugin, "skills"), "alias", "---\nname: dot.alias\n---\n"); + yield* fs.writeFileString( + path.join(configDir, "plugins", "installed_plugins.json"), + JSON.stringify({ plugins: { "plugin@shop": [{ scope: "user", installPath: plugin }] } }), + ); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"plugin@shop":true}}', + ); + + const skills = yield* discoverClaudeSkills({ homePath: configDir }); + assert.deepEqual( + planClaudeSkillDispatch( + "$plugin:alias focus on auth", + new Map(skills.map((skill) => [skill.name, skill])), + ), + { + leadingText: undefined, + commandText: "/plugin:alias focus on auth", + skillName: "plugin:alias", + }, + ); + assert.deepEqual( + skills.map((skill) => skill.name), + ["plugin:alias", "plugin:review"], + ); + }), + ); + + it.effect("uses the native cache root, root-skill fallback and manifest path boundaries", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspace = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); + const configDir = path.join(workspace, "config"); + const pluginsDir = path.join(workspace, "plugin-cache"); + const plugin = path.join(pluginsDir, "installed"); + const outside = path.join(workspace, "outside"); + yield* writeSkill(pluginsDir, "installed", "---\nname: plugin:root.alias\n---\n"); + yield* fs.makeDirectory(configDir); + yield* fs.writeFileString( + path.join(configDir, "settings.json"), + '{"enabledPlugins":{"plugin@shop":true}}', + ); + yield* fs.writeFileString( + path.join(pluginsDir, "installed_plugins.json"), + JSON.stringify({ plugins: { "plugin@shop": [{ scope: "user", installPath: plugin }] } }), + ); + const environment = { CLAUDE_CODE_PLUGIN_CACHE_DIR: "plugin-cache" }; + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, workspace, environment)).map( + (skill) => skill.name, + ), + ["plugin:root-alias"], + ); + + yield* writeSkill(path.join(plugin, "skills"), "plain", "# Plain"); + yield* writeSkill(plugin, "custom", "---\nname: custom.review\n---\n"); + yield* writeSkill(outside, "escaped", "# Outside"); + yield* fs.symlink(outside, path.join(plugin, "escape")); + yield* fs.makeDirectory(path.join(plugin, ".claude-plugin")); + yield* fs.writeFileString( + path.join(plugin, ".claude-plugin", "plugin.json"), + '{"skills":["./custom","./escape","../../outside"]}', + ); + assert.deepEqual( + (yield* discoverClaudeSkills({ homePath: configDir }, workspace, environment)).map( + (skill) => skill.name, + ), + ["plugin:custom-review", "plugin:plain"], + ); + }), + ); + it.effect("discovers user and project skills with frontmatter metadata", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -67,25 +337,65 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); - it.effect("ignores .agents/skills, which Claude Code does not load", () => + it.effect("discovers skills from the instance's --add-dir launch args", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); const configDir = path.join(tempDir, "claude-home"); const workspace = path.join(tempDir, "workspace"); - - // Verified against the CLI: `/review` here is answered with - // `Unknown command`, so offering it would dispatch a dead command. + const extraDir = path.join(workspace, "extra skills"); + yield* fs.makeDirectory(workspace, { recursive: true }); yield* writeSkill( - path.join(workspace, ".agents", "skills"), - "review", - ["---", "name: review", "description: Review the changes.", "---"].join("\n"), + path.join(extraDir, ".claude", "skills"), + "demo", + ["---", "description: From an additional directory.", "---"].join("\n"), + ); + + assert.deepEqual(yield* discoverClaudeSkills({ homePath: configDir }, workspace), []); + for (const launchArgs of [ + `--add-dir "${extraDir}"`, + `--add-dir="${extraDir}"`, + '--add-dir "extra skills"', + '--add-dir="extra skills"', + `--add-dir missing --add-dir "${extraDir}"`, + ]) { + const settings = { homePath: configDir, launchArgs }; + const skills = yield* discoverClaudeSkills(settings, workspace); + assert.deepEqual(skills, [ + { + name: "demo", + path: path.join(extraDir, ".claude", "skills", "demo", "SKILL.md"), + enabled: true, + scope: "project", + description: "From an additional directory.", + }, + ]); + } + const settings = { homePath: configDir, launchArgs: `--add-dir "${extraDir}"` }; + const skills = yield* discoverClaudeSkills(settings, workspace); + assert.deepEqual( + planClaudeSkillDispatch( + "$demo", + new Map(skills.map((skill) => [skill.name, { path: skill.path }])), + ), + { + leadingText: undefined, + commandText: "/demo", + skillName: "demo", + }, ); - - const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace); - - assert.deepEqual(skills, []); + yield* writeSkill( + path.join(workspace, ".claude", "skills"), + "demo", + "---\ndescription: Project copy.\n---", + ); + const projectSkills = yield* discoverClaudeSkills(settings, workspace); + assert.equal(projectSkills[0]?.description, "Project copy."); + for (const launchArgs of ["--add-dir", '--add-dir=""', '--add-dir "extra skills"']) { + const settings = { homePath: configDir, launchArgs }; + assert.deepEqual(yield* discoverClaudeSkills(settings), []); + } }), ); @@ -127,33 +437,6 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); - it.effect("prefers user skills over project skills on name collisions", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); - const configDir = path.join(tempDir, "claude-home"); - const workspace = path.join(tempDir, "workspace"); - - yield* writeSkill( - path.join(configDir, "skills"), - "deploy", - ["---", "name: deploy", "description: User deploy.", "---"].join("\n"), - ); - yield* writeSkill( - path.join(workspace, ".claude", "skills"), - "deploy", - ["---", "name: deploy", "description: Project deploy.", "---"].join("\n"), - ); - - const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace); - - assert.equal(skills.length, 1); - assert.equal(skills[0]?.scope, "user"); - assert.equal(skills[0]?.description, "User deploy."); - }), - ); - it.effect("recovers colon-bearing descriptions with invocation metadata intact", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -221,9 +504,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { const skills = yield* discoverClaudeSkills({ homePath: configDir }, undefined); - // A skill with no frontmatter falls back to its directory name; a skill - // whose frontmatter fails to parse is skipped entirely (Claude Code - // won't load it either). + // Claude falls back to directory names without frontmatter, but skips malformed frontmatter. assert.deepEqual( skills.map((skill) => skill.name), ["no-frontmatter"], @@ -278,8 +559,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { const workspace = path.join(tempDir, "workspace"); yield* fs.makeDirectory(workspace, { recursive: true }); - // The spawned CLI resolves a relative CLAUDE_CONFIG_DIR against its own - // cwd (the workspace), so discovery must do the same. + // The CLI resolves relative CLAUDE_CONFIG_DIR against workspace cwd. yield* writeSkill( path.join(workspace, "relative-config", "skills"), "relative-skill", @@ -298,48 +578,6 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); - it.effect("marks skills that only the user can invoke", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); - const configDir = path.join(tempDir, "claude-home"); - const workspace = path.join(tempDir, "workspace"); - - yield* writeSkill( - path.join(workspace, ".claude", "skills"), - "re-release-version", - [ - "---", - "name: re-release-version", - "description: Move the current tag forward.", - "disable-model-invocation: true", - "---", - "", - "# Body", - ].join("\n"), - ); - yield* writeSkill( - path.join(workspace, ".claude", "skills"), - "release-version", - ["---", "name: release-version", "description: Cut a release.", "---", "", "# Body"].join( - "\n", - ), - ); - - const skills = yield* discoverClaudeSkills({ homePath: configDir }, workspace); - - assert.equal( - skills.find((skill) => skill.name === "re-release-version")?.userInvocationOnly, - true, - ); - assert.equal( - skills.find((skill) => skill.name === "release-version")?.userInvocationOnly, - undefined, - ); - }), - ); - it.effect("disables skills switched off by skillOverrides", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -443,8 +681,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { ["---", `name: ${name}`, "---", "", "# Body"].join("\n"), ); } - // Verified against the CLI: with an unknown string or a boolean in the - // map, the valid "off" sibling is ignored too and every skill runs. + // Claude ignores the entire override map when any value is an unknown string or boolean. yield* fs.writeFileString( path.join(configDir, "settings.json"), '{ "skillOverrides": { "unknown-mode": "some-future-mode", "boolean-false": false, "sibling-off": "off" } }', @@ -540,86 +777,6 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); - it.effect("lets the administrator's managed policy outrank every other settings file", () => - Effect.gen(function* () { - const path = yield* Path.Path.pipe(Effect.provide(NodePath.layerPosix)); - const win32Path = yield* Path.Path.pipe(Effect.provide(NodePath.layerWin32)); - - for (const [platform, expected] of [ - ["darwin", "/Library/Application Support/ClaudeCode/managed-settings.json"], - ["linux", "/etc/claude-code/managed-settings.json"], - ] as const) { - const paths = skillOverrideSettingsPaths(path, "/home/.claude", "/workspace", platform, {}); - assert.deepEqual(paths, [ - "/home/.claude/settings.json", - "/workspace/.claude/settings.json", - "/workspace/.claude/settings.local.json", - expected, - ]); - } - - assert.deepEqual( - skillOverrideSettingsPaths(win32Path, "C:\\Users\\me\\.claude", undefined, "win32", { - PROGRAMDATA: "C:\\ProgramData", - }).at(-1), - "C:\\ProgramData\\ClaudeCode\\managed-settings.json", - ); - assert.deepEqual( - skillOverrideSettingsPaths(win32Path, "C:\\Users\\me\\.claude", undefined, "win32", {}), - ["C:\\Users\\me\\.claude\\settings.json"], - ); - - assert.deepEqual( - skillOverrideSettingsPaths( - path, - "/home/.claude", - "/repo/packages/app", - "linux", - {}, - "/repo", - ), - [ - "/home/.claude/settings.json", - "/repo/packages/app/.claude/settings.json", - "/repo/packages/app/.claude/settings.local.json", - "/repo/.claude/settings.local.json", - "/etc/claude-code/managed-settings.json", - ], - ); - assert.deepEqual( - skillOverrideSettingsPaths(path, "/home/.claude", "/repo", "linux", {}, "/repo"), - [ - "/home/.claude/settings.json", - "/repo/.claude/settings.json", - "/repo/.claude/settings.local.json", - "/etc/claude-code/managed-settings.json", - ], - ); - }), - ); - - it.effect("records a skill Claude Code keeps out of its own slash commands", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); - const configDir = path.join(tempDir, "claude-home"); - - yield* writeSkill( - path.join(configDir, "skills"), - "agent-only", - ["---", "name: agent-only", "user-invocable: false", "---", "", "# Body"].join("\n"), - ); - - const skills = yield* discoverClaudeSkills({ homePath: configDir }); - - assert.deepEqual( - skills.map((skill) => [skill.name, skill.userInvocable]), - [["agent-only", false]], - ); - }), - ); - it.effect("identifies a skill by its directory, as Claude Code does", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -646,6 +803,7 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { }), ); + // regression: #9128 skills picked from the composer did not run it.effect("switches a skill off by its directory name", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -712,19 +870,4 @@ it.layer(NodeServices.layer)("discoverClaudeSkills", (it) => { ); }), ); - - it.effect("returns an empty list when no skill roots exist", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skills-" }); - - const skills = yield* discoverClaudeSkills( - { homePath: path.join(tempDir, "missing-home") }, - path.join(tempDir, "missing-workspace"), - ); - - assert.deepEqual(skills, []); - }), - ); }); diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index 8eaae6380b68b..56c2ff19bebdf 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -2,15 +2,24 @@ import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { parseCliArgs } from "@t3tools/shared/cliArgs"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; +import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { parse as parseYamlDocument } from "yaml"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; type ClaudeSkillScope = "user" | "project"; +type ClaudeSkillRoot = { + readonly directory: string; + readonly scope: ClaudeSkillScope; + readonly prefix?: string; +}; + const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/; type SkillFrontmatter = @@ -18,16 +27,13 @@ type SkillFrontmatter = | { readonly kind: "malformed" } | { readonly kind: "parsed"; + readonly name?: string; readonly description?: string; readonly userInvocationOnly?: boolean; readonly userInvocable?: boolean; }; -/** - * Claude Code accepts the YAML 1.1 boolean spellings (`yes`/`no`, `on`/`off`, - * `1`/`0`), which the 1.2 core schema this parser uses leaves as strings and - * numbers. - */ +/** Claude accepts YAML 1.1 booleans that this YAML 1.2 parser leaves as strings or numbers. */ function parseFrontmatterBoolean(value: unknown): boolean | undefined { if (typeof value === "boolean") return value; if (typeof value === "number") { @@ -61,8 +67,7 @@ function parseSkillFrontmatter(contents: string): SkillFrontmatter { try { parsed = parseYamlDocument(frontmatter); } catch { - // Claude Code accepts plain scalars containing `: `. Repair only those, - // leaving comments and YAML structure for the full-document parser. + // Repair Claude's accepted ': ' scalars without disturbing comments or YAML structure. const repaired = frontmatter.replace( /^([\w-]+:[ \t]*)([^\r\n]*)/gm, (line, prefix: string, value: string) => { @@ -84,9 +89,11 @@ function parseSkillFrontmatter(contents: string): SkillFrontmatter { } const record = parsed as Record; + const name = typeof record.name === "string" ? record.name.trim() : ""; const description = typeof record.description === "string" ? record.description.trim() : ""; return { kind: "parsed", + ...(name ? { name } : {}), ...(description ? { description } : {}), ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true ? { userInvocationOnly: true } @@ -112,7 +119,7 @@ function claudeManagedSettingsPath( return "/etc/claude-code/managed-settings.json"; } -export function skillOverrideSettingsPaths( +function skillOverrideSettingsPaths( path: Path.Path, configDirPath: string, cwd: string | undefined, @@ -156,6 +163,43 @@ const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* ( } }); +const findPluginRepositoryRoot = Effect.fn("findPluginRepositoryRoot")(function* (cwd: string) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* findRepositoryRoot(cwd); + if (root === undefined) return undefined; + const gitFile = yield* fileSystem + .readFileString(path.join(root, ".git")) + .pipe(Effect.orElseSucceed(() => "")); + if (!gitFile.trim().startsWith("gitdir:")) return root; + const gitDirectory = path.resolve(root, gitFile.trim().slice(7).trim()); + const commonFile = yield* fileSystem + .readFileString(path.join(gitDirectory, "commondir")) + .pipe(Effect.orElseSucceed(() => "")); + const worktreeFile = yield* fileSystem + .readFileString(path.join(gitDirectory, "gitdir")) + .pipe(Effect.orElseSucceed(() => "")); + if (!commonFile.trim() || !worktreeFile.trim()) return root; + const commonDirectory = path.resolve(gitDirectory, commonFile.trim()); + const backlinkPath = yield* fileSystem + .realPath(path.resolve(gitDirectory, worktreeFile.trim())) + .pipe(Effect.orElseSucceed(() => undefined)); + const worktreeGitPath = yield* fileSystem + .realPath(path.join(root, ".git")) + .pipe(Effect.orElseSucceed(() => undefined)); + if ( + path.dirname(gitDirectory) !== path.join(commonDirectory, "worktrees") || + backlinkPath === undefined || + backlinkPath !== worktreeGitPath + ) { + return root; + } + // Claude shares plugin install records across linked worktrees, using their common repository. + return path.basename(commonDirectory) === ".git" + ? path.dirname(commonDirectory) + : commonDirectory; +}); + /** * The CLI validates the whole map, not each entry: verified against it, one * entry with an unknown value (or a boolean) makes it drop every override in @@ -166,12 +210,13 @@ const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-o // Lenient because these settings files are hand-edited and Claude Code itself // tolerates comments and trailing commas in them. -const SkillOverrideSettings = fromLenientJson( +const SkillSettings = fromLenientJson( Schema.Struct({ skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)), + enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), }), ); -const decodeSkillOverrideSettings = Schema.decodeUnknownEffect(SkillOverrideSettings); +const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings); type SkillOverride = { readonly enabled: boolean; @@ -190,15 +235,16 @@ function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverrid } } -const readSkillOverrides = Effect.fn("readSkillOverrides")(function* ( +const readSkillSettings = Effect.fn("readSkillSettings")(function* ( configDirPath: string, cwd: string | undefined, environment: NodeJS.ProcessEnv, -): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { +) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const platform = yield* HostProcess.Platform; const overridesByName = new Map(); + const enabledPlugins = new Map(); const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd); for (const settingsPath of skillOverrideSettingsPaths( @@ -216,26 +262,150 @@ const readSkillOverrides = Effect.fn("readSkillOverrides")(function* ( continue; } - const parsed = yield* decodeSkillOverrideSettings(contents).pipe( + const parsed = yield* decodeSkillSettings(contents).pipe( Effect.tapError((cause) => - Effect.logDebug("claude settings file is unreadable; ignoring skillOverrides", { + Effect.logDebug("claude settings file is unreadable; ignoring skill settings", { path: settingsPath, cause, }), ), Effect.orElseSucceed(() => undefined), ); - const overrides = parsed?.skillOverrides; - if (!overrides) { - continue; - } - - for (const [name, value] of Object.entries(overrides)) { + for (const [name, value] of Object.entries(parsed?.skillOverrides ?? {})) { overridesByName.set(name, parseSkillOverride(value)); } + for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) { + if (typeof enabled === "boolean") { + enabledPlugins.set(key, enabled); + } else { + // Extended formats replace lower-precedence values without enabling the plugin here. + enabledPlugins.delete(key); + } + } } - return overridesByName; + return { skillOverrides: overridesByName, enabledPlugins }; +}); + +const InstalledPlugins = Schema.fromJsonString( + Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }), +); +const decodeInstalledPlugin = Schema.decodeUnknownOption( + Schema.Struct({ + scope: Schema.Literals(["user", "project", "local", "managed"]), + installPath: Schema.NonEmptyString, + projectPath: Schema.optional(Schema.NonEmptyString), + }), +); +const PluginManifest = Schema.fromJsonString( + Schema.Struct({ + name: Schema.optional(Schema.NonEmptyString), + skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])), + }), +); + +function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean { + const relative = path.relative(directory, candidate); + return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative); +} + +const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* ( + configDirPath: string, + cwd: string | undefined, + enabledPlugins: ReadonlyMap, + environment: NodeJS.ProcessEnv, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* HostProcess.HomeDirectory; + const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR; + const pluginsPath = pluginDirectory + ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home)) + : path.join(configDirPath, "plugins"); + const installed = yield* fileSystem + .readFileString(path.join(pluginsPath, "installed_plugins.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)), + Effect.orElseSucceed(() => undefined), + ); + if (installed === undefined) return []; + const roots: Array = []; + // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical. + const workspace = + cwd === undefined + ? undefined + : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd))); + const repositoryRoot = + workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace); + + for (const [key, entries] of Object.entries(installed.plugins).sort()) { + if (enabledPlugins.get(key) !== true) continue; + const applicable = yield* Effect.filter( + entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))), + (record) => + Effect.gen(function* () { + if (record.scope === "user" || record.scope === "managed") return true; + if (record.projectPath === undefined || workspace === undefined) return false; + if (path.resolve(record.projectPath) === workspace) return true; + return ( + repositoryRoot !== undefined && + (yield* findPluginRepositoryRoot(record.projectPath)) === repositoryRoot + ); + }), + ); + // The native loader keeps registry order, preferring the first install that exists. + const existing = yield* Effect.findFirst(applicable, (record) => + fileSystem + .exists(path.resolve(cwd ?? ".", record.installPath)) + .pipe(Effect.orElseSucceed(() => false)), + ); + const install = Option.getOrElse(existing, () => applicable[0]); + if (!install) continue; + const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project"; + const installPath = path.resolve(cwd ?? ".", install.installPath); + const manifest = yield* fileSystem + .readFileString(path.join(installPath, ".claude-plugin", "plugin.json")) + .pipe( + Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)), + Effect.orElseSucceed(() => undefined), + ); + const prefix = manifest?.name ?? key.split("@")[0]; + if (!prefix) continue; + + const defaultDirectory = path.join(installPath, "skills"); + const hasDefaultDirectory = yield* fileSystem + .exists(defaultDirectory) + .pipe(Effect.orElseSucceed(() => false)); + if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix }); + const declared = manifest?.skills; + if (declared === undefined && !hasDefaultDirectory) { + const hasRootSkill = yield* fileSystem + .exists(path.join(installPath, "SKILL.md")) + .pipe(Effect.orElseSucceed(() => false)); + if (hasRootSkill) roots.push({ directory: installPath, scope, prefix }); + } + + const canonicalInstallPath = yield* fileSystem + .realPath(installPath) + .pipe(Effect.orElseSucceed(() => undefined)); + for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) { + const directory = path.resolve(installPath, relative); + if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) { + continue; + } + const canonicalDirectory = yield* fileSystem + .realPath(directory) + .pipe(Effect.orElseSucceed(() => undefined)); + // The native loader rejects manifest roots that escape through a symlink, too. + if ( + canonicalDirectory !== undefined && + isInsideDirectory(path, canonicalInstallPath, canonicalDirectory) + ) { + roots.push({ directory, scope, prefix }); + } + } + } + return roots; }); const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* ( @@ -249,11 +419,7 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(funct if (homePath.length > 0) { return path.resolve(expandHomePath(homePath, home)); } - // No tilde expansion here: the spawned CLI receives this env var verbatim - // (env vars are never shell-expanded), so a literal `~` must stay literal - // for discovery to scan the same directory the runtime would. A relative - // value is resolved against the workspace cwd — the subprocess's own cwd — - // for the same reason. + // Match the spawned CLI: preserve a literal ~ and resolve relative config against workspace cwd. const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? ""; if (environmentConfigDir.length > 0) { return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir); @@ -261,34 +427,62 @@ const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(funct return path.join(home, ".claude"); }); -/** - * Roots are listed highest precedence first and the first hit for a name wins, - * matching Claude Code: verified against the CLI with the same skill name in - * both scopes, the user copy is the one that runs. - */ +/** First name wins, matching Claude Code's precedence of user skills over project skills. */ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* ( - config: Pick, + config: Pick & Partial>, cwd?: string, environment?: NodeJS.ProcessEnv, ): Effect.fn.Return, never, FileSystem.FileSystem | Path.Path> { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd); - const skillOverrides = yield* readSkillOverrides(configDirPath, cwd, environment ?? process.env); + const { skillOverrides, enabledPlugins } = yield* readSkillSettings( + configDirPath, + cwd, + environment ?? process.env, + ); - const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [ + const additionalDirectory = parseCliArgs(config.launchArgs ?? "").flags["add-dir"]; + const roots: ReadonlyArray = [ { directory: path.join(configDirPath, "skills"), scope: "user" }, ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []), + ...(additionalDirectory && (cwd || path.isAbsolute(additionalDirectory)) + ? [ + { + directory: path.join( + path.resolve(cwd ?? ".", additionalDirectory), + ".claude", + "skills", + ), + scope: "project" as const, + }, + ] + : []), + ...(yield* discoverPluginSkillRoots( + configDirPath, + cwd, + enabledPlugins, + environment ?? process.env, + )), ]; const skillsByName = new Map(); for (const root of roots) { - const entries = yield* fileSystem - .readDirectory(root.directory) - .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const singleSkill = + root.prefix !== undefined && + (yield* fileSystem + .exists(path.join(root.directory, "SKILL.md")) + .pipe(Effect.orElseSucceed(() => false))); + const entries = singleSkill + ? [path.basename(root.directory)] + : yield* fileSystem + .readDirectory(root.directory) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); for (const entry of [...entries].sort()) { - const skillPath = path.join(root.directory, entry, "SKILL.md"); + const skillPath = singleSkill + ? path.join(root.directory, "SKILL.md") + : path.join(root.directory, entry, "SKILL.md"); const contents = yield* fileSystem .readFileString(skillPath) .pipe(Effect.orElseSucceed(() => undefined)); @@ -301,22 +495,26 @@ export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* continue; } - // Claude Code identifies a skill by its directory, not by the - // frontmatter `name`: verified against the CLI, a skill in `probe-alias/` - // declaring `name: probe-alias-frontmatter` is published as - // `probe-alias`, and only `skillOverrides["probe-alias"]` switches it - // off. Keying off the frontmatter name would report a command that does - // not exist and miss the override that disables it. - const name = entry.trim(); - if (!name) { - continue; + const directoryName = entry.trim(); + if (!directoryName) continue; + let name = directoryName; + if (root.prefix) { + // Native folder skills use their folder; only a single SKILL.md uses its name field. + const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : ""; + const unprefixedName = declaredName?.startsWith(`${root.prefix}:`) + ? declaredName.slice(root.prefix.length + 1) + : declaredName; + name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`; + // Advertise only exact native names the shared composer grammar can invoke. + const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN); + if (mention?.[2] !== name) continue; } if (skillsByName.has(name)) { continue; } - const override = skillOverrides.get(name); + const override = root.prefix ? undefined : skillOverrides.get(name); const userInvocationOnly = (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) || override?.userInvocationOnly === true; diff --git a/apps/server/src/provider/Drivers/CodexDriver.test.ts b/apps/server/src/provider/Drivers/CodexDriver.test.ts index 51301ef43c50f..023942177a914 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.test.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.test.ts @@ -1,14 +1,15 @@ import * as CodexInstallation from "../CodexInstallation.ts"; +import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts"; import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; // @effect-diagnostics nodeBuiltinImport:off import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import { expect, it } from "@effect/vitest"; import { EnvironmentId, ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -58,6 +59,12 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), { }), ), Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})), + Layer.provideMerge( + Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({ + endpoint: Effect.succeed("unused-private-pipe"), + awaitIdle: Effect.void, + }), + ), Layer.provideMerge( Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")), @@ -96,10 +103,13 @@ const noSpawn = ChildProcessSpawner.make(() => const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); it.layer(layerTest)("CodexDriver", (it) => { - it.effect("disconnect refreshes a restored managed account while its auth flow is idle", () => + const checkManagedAccount = (replacementTiming: "unchanged" | "during-probe") => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("restored-managed-account"); const credentials = new Map(); + const catalogTokens: Array = []; + const probeEntered = yield* Deferred.make(); + const resumeProbe = yield* Deferred.make(); const secrets = ServerSecretStore.ServerSecretStore.of({ get: (key) => Effect.sync(() => Option.fromUndefinedOr(credentials.get(key))), set: (key, value) => @@ -126,6 +136,17 @@ it.layer(layerTest)("CodexDriver", (it) => { email: "account@example.test", }); yield* store.set(new TextEncoder().encode(json)); + const replacement = yield* encodeCredentials({ + clientId: "oaiapp_replacement", + subject: "replacement-user", + email: "replacement@example.test", + accessToken: "replacement-access", + refreshToken: "replacement-refresh", + expiresAt: Number.MAX_SAFE_INTEGER, + earliestRefreshAt: null, + scopes: ["chatgpt.tokens.use.direct"], + }); + const replaceAccount = store.set(new TextEncoder().encode(replacement)).pipe(Effect.orDie); const executable = { executablePath: "/user/bin/codex", managedVersionDirectory: null, @@ -140,9 +161,17 @@ it.layer(layerTest)("CodexDriver", (it) => { > = []; let interruptedChecks = 0; + let failAcquire = false; const startupChecksInterrupted = yield* Deferred.make(); const acquire = () => Effect.suspend(() => { + if (failAcquire) + return Effect.fail( + new CodexInstallation.CodexInstallationError({ + operation: "acquire", + detail: "The fixture runtime is unavailable", + }), + ); if (interruptedChecks === 2) return Effect.succeed(executable); interruptedChecks += 1; return ( @@ -179,13 +208,17 @@ it.layer(layerTest)("CodexDriver", (it) => { Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => - Effect.fail( - PlatformError.badArgument({ + Effect.gen(function* () { + if (replacementTiming === "during-probe") { + yield* Deferred.succeed(probeEntered, undefined); + yield* Deferred.await(resumeProbe); + } + return yield* PlatformError.badArgument({ module: "ChildProcessSpawner", method: "spawn", description: "The fixture app-server is unavailable", - }), - ), + }); + }), ), ), ); @@ -201,12 +234,34 @@ it.layer(layerTest)("CodexDriver", (it) => { Effect.forkScoped, ); yield* Deferred.await(startupChecksInterrupted); - const restored = yield* instance.snapshot.refresh; + const refresh = yield* instance.snapshot.refresh.pipe(Effect.forkChild); + if (replacementTiming === "during-probe") { + yield* Deferred.await(probeEntered); + yield* replaceAccount; + yield* Deferred.succeed(resumeProbe, undefined); + } + const restored = yield* Fiber.join(refresh); + if (replacementTiming === "during-probe") { + expect(catalogTokens).toEqual([]); + expect(restored.models).toEqual([]); + expect(restored.auth.email).toBe("replacement@example.test"); + expect(restored.auth.profileId).toBe("oaiapp_replacement"); + return; + } + expect(catalogTokens).toEqual(["Bearer dummy-owned-access"]); expect(restored.auth.email).toBe("account@example.test"); expect(restored.runtimePaths?.homePath).toBe(sharedHome); expect(restored.runtimePaths?.shadowHomePath).toContain( `providers/codex/${instanceId}/shadow`, ); + const scan = yield* instance.snapshotForCwd!(serverConfig.stateDir).pipe(Effect.exit); + expect(Exit.isFailure(scan)).toBe(true); + failAcquire = true; + const runtimeScan = yield* instance.snapshotForCwd!(serverConfig.stateDir).pipe( + Effect.exit, + ); + failAcquire = false; + expect(Exit.isFailure(runtimeScan)).toBe(true); yield* Deferred.await(observedAccount); const threadId = ThreadId.make("managed-account-thread"); @@ -226,7 +281,9 @@ it.layer(layerTest)("CodexDriver", (it) => { const launch = launches[0]!; expect(launch.settings.binaryPath).toBe(executable.executablePath); expect(launch.settings.launchArgs).toContain("openai_token_sharing"); - expect(launch.environment.ACCESS_TOKEN).toBe("dummy-owned-access"); + expect(launch.environment.ACCESS_TOKEN).toBeUndefined(); + expect(launch.settings.launchArgs).toContain("__managed-chatgpt-token"); + expect(launch.settings.launchArgs).not.toContain("dummy-owned-access"); expect(launch.environment.OPENAI_API_KEY).toBeUndefined(); expect(launch.environment.CODEX_HOME).toBe(launch.settings.homePath); const before = yield* instance.auth!.subscribe("test-owner").pipe(Stream.runHead); @@ -238,6 +295,8 @@ it.layer(layerTest)("CodexDriver", (it) => { expect(after.installed).toBe(true); expect(after.models).toEqual([]); expect(Option.isNone(yield* store.get)).toBe(true); + const signedOutScan = yield* instance.snapshotForCwd!(serverConfig.stateDir); + expect(signedOutScan.skills).toEqual([]); }).pipe( Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), Effect.provideService( @@ -249,8 +308,10 @@ it.layer(layerTest)("CodexDriver", (it) => { "https://auth.openai.com/revoke", "https://api.openai.com/v1/models", ]).toContain(request.url); - if (request.url.endsWith("/models")) + if (request.url.endsWith("/models")) { + catalogTokens.push(request.headers.authorization); return HttpClientResponse.fromWeb(request, Response.json({ models: [] })); + } return HttpClientResponse.fromWeb( request, request.url.endsWith("/revoke") @@ -267,7 +328,12 @@ it.layer(layerTest)("CodexDriver", (it) => { ), ), ); - }).pipe(Effect.scoped), + }).pipe(Effect.scoped); + // regression: a sign-in that replaces the account mid-probe must not label the old + // account's catalog with the new identity. + it.effect.each(["unchanged", "during-probe"] as const)( + "managed catalog keeps its account label and token together: %s", + checkManagedAccount, ); it.effect.skipIf(windowsHost)( @@ -311,22 +377,6 @@ it.layer(layerTest)("CodexDriver", (it) => { ), ); - it.effect("stays manual-only when the configured executable does not exist", () => - Effect.gen(function* () { - const instance = yield* CodexDriver.create({ - instanceId: ProviderInstanceId.make("codex-missing"), - displayName: "Codex test", - enabled: false, - environment: [], - config: { - ...CodexDriver.defaultConfig(), - binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-codex-missing", "codex"), - }, - }); - expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull(); - }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped), - ); - for (const fixture of [ { name: "leaves mise npm-backend installations manual-only", @@ -407,44 +457,7 @@ it.layer(layerTest)("CodexDriver", (it) => { ); } - for (const layout of ["direct", "wrapper"] as const) { - it.effect.skipIf(windowsHost)(`leaves a mise ${layout} installation manual-only`, () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const tempDir = yield* fs - .makeTempDirectoryScoped({ prefix: `t3-codex-mise-${layout}-` }) - .pipe(Effect.flatMap((directory) => fs.realPath(directory))); - const binaryPath = - layout === "direct" - ? NodePath.join(tempDir, "mise", "installs", "codex", "0.110.0", "codex") - : NodePath.join(tempDir, "omarchy", "bin", "codex"); - yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true }); - yield* fs.writeFileString( - binaryPath, - layout === "direct" - ? "#!/bin/sh\n" - : '#!/bin/sh\nmise use -g --quiet "codex" || exit 1\nexec mise x "codex" -- "codex" "$@"\n', - ); - yield* fs.chmod(binaryPath, 0o755); - - const instance = yield* CodexDriver.create({ - instanceId: ProviderInstanceId.make(`codex-mise-${layout}`), - displayName: "Codex mise test", - enabled: false, - environment: [], - config: { - ...CodexDriver.defaultConfig(), - binaryPath, - homePath: NodePath.join(tempDir, "codex-home"), - }, - }); - - expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull(); - }).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), - Effect.scoped, - ), - ); + for (const {} of ["direct", "wrapper"] as const) { } it.effect.each([ diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index 2388213eed301..2d078cf32594f 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -7,6 +7,7 @@ import * as Schema from "effect/Schema"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; +import type * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts"; import { makeCodexTextGeneration } from "../../textGeneration/CodexTextGeneration.ts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; @@ -52,6 +53,7 @@ import { import { makeManagedCodexProvider } from "./CodexManagedProvider.ts"; import { codexUsageReader } from "./codexUsage.ts"; import * as CodexInstallation from "../CodexInstallation.ts"; +import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts"; import * as ServerSecretStore from "../../auth/ServerSecretStore.ts"; import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -62,12 +64,7 @@ function isCodexStandaloneCommandPath(commandPath: string): boolean { return normalizeCommandPath(commandPath).includes("/packages/standalone/"); } -/** - * `codex update` replaces the standalone tree under `CODEX_HOME`. That tree - * lives in the shared home even when an auth-overlay shadow home is in use - * (the overlay only carries auth and a few local entries), so the updater - * runs against `sharedHomePath` rather than the instance's effective home. - */ +/** `codex update` owns the shared home's standalone tree; auth-overlay homes do not carry it. */ function makeCodexMaintenanceResolver(sharedHomePath: string) { return makePackageManagedProviderMaintenanceResolver({ provider: DRIVER_KIND, @@ -75,6 +72,7 @@ function makeCodexMaintenanceResolver(sharedHomePath: string) { nativeUpdate: { args: ["update"], isCommandPath: isCodexStandaloneCommandPath, + requiresCommandPath: true, env: { CODEX_HOME: sharedHomePath }, }, }); @@ -95,9 +93,14 @@ export type CodexDriverEnv = | ServerConfig.ServerConfig | ServerSecretStore.ServerSecretStore | ServerEnvironment.ServerEnvironmentIdentity - | CodexInstallation.CodexInstallation; + | CodexInstallation.CodexInstallation + | CodexManagedTokenBroker.CodexManagedTokenBroker; -export const CodexDriver: ProviderDriver = { +export const CodexDriver: ProviderDriver< + CodexSettings, + CodexDriverEnv, + Path.Path | CodexUsageHistory.CodexUsageHistory +> = { driverKind: DRIVER_KIND, metadata: { displayName: "Codex", @@ -106,246 +109,248 @@ export const CodexDriver: ProviderDriver decodeCodexSettings({}), usage: codexUsageReader, - create: ({ instanceId, displayName, accentColor, environment, enabled, config }) => - Effect.gen(function* () { - if (config.setupMode === "managed") - return yield* makeManagedCodexProvider({ - instanceId, - displayName, - accentColor, - environment, - enabled, - config, - }); - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator; - const fileSystem = yield* FileSystem.FileSystem; - const pathService = yield* Path.Path; - const httpClient = yield* HttpClient.HttpClient; - const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; - const modelCatalog = yield* ModelCatalog.ModelCatalog; - const currentCatalog = modelCatalog.current(DRIVER_KIND); - const processEnv = yield* mergeProviderInstanceEnvironment(environment); - const homeLayout = yield* resolveCodexHomeLayout(config); - const continuationIdentity = codexContinuationIdentity(homeLayout); - const stampIdentity = withInstanceIdentity({ + create: Effect.fn("CodexDriver.create")(function* ({ + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }) { + if (config.setupMode === "managed") + return yield* makeManagedCodexProvider({ instanceId, - driverKind: DRIVER_KIND, displayName, accentColor, - continuationGroupKey: continuationIdentity.continuationKey, - }); - yield* materializeCodexShadowHome(homeLayout).pipe( - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: cause.message, - cause, - }), - ), - ); - const effectiveConfig = { - ...config, + environment, enabled, - binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory), - homePath: homeLayout.effectiveHomePath ?? "", - } satisfies CodexSettings; - const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( - resolveProviderMaintenanceCapabilitiesEffect( - makeCodexMaintenanceResolver(homeLayout.sharedHomePath), - { - binaryPath: effectiveConfig.binaryPath, - env: processEnv, - }, - ).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, pathService), - ), - ); - - const orchestrationAdapter = yield* createCodexAdapterV2( + config, + }); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const resetCreditCoordinator = yield* ResetCreditCoordinator.ResetCreditCoordinator; + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const httpClient = yield* HttpClient.HttpClient; + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const modelCatalog = yield* ModelCatalog.ModelCatalog; + const currentCatalog = modelCatalog.current(DRIVER_KIND); + const processEnv = yield* mergeProviderInstanceEnvironment(environment); + const homeLayout = yield* resolveCodexHomeLayout(config); + const continuationIdentity = codexContinuationIdentity(homeLayout); + const stampIdentity = withInstanceIdentity({ + instanceId, + driverKind: DRIVER_KIND, + displayName, + accentColor, + continuationGroupKey: continuationIdentity.continuationKey, + }); + yield* materializeCodexShadowHome(homeLayout).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: cause.message, + cause, + }), + ), + ); + const effectiveConfig = { + ...config, + enabled, + binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory), + homePath: homeLayout.effectiveHomePath ?? "", + } satisfies CodexSettings; + const resolveMaintenance = yield* makeCachedProviderMaintenanceResolution( + resolveProviderMaintenanceCapabilitiesEffect( + makeCodexMaintenanceResolver(homeLayout.sharedHomePath), { - instanceId, - displayName, - accentColor, - environment, - enabled, - config, + binaryPath: effectiveConfig.binaryPath, + env: processEnv, }, - { onUsageLimits: (update) => snapshot.applyUsageLimits(update) }, ).pipe( - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: "Failed to build Codex orchestration adapter.", - cause, - }), - ), - ); - - // Kick the TTL-gated manifest refresh in the background and classify with the in-memory - // manifest, so a slow or hung fetch never delays the provider check. - const checkProvider = modelCatalog.refreshInBackground.pipe( - Effect.andThen( - Effect.zipWith( - checkCodexProviderStatus(effectiveConfig, undefined, processEnv), - currentCatalog, - (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)), - { concurrent: true }, - ), - ), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, pathService), - ); - const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); - const snapshot = yield* makeManagedServerProvider>({ - resolveMaintenance, - getSettings: snapshotSettings.getSettings, - streamSettings: snapshotSettings.streamSettings, - haveSettingsChanged: haveProviderSnapshotSettingsChanged, - initialSnapshot: (settings) => - Effect.zipWith( - makePendingCodexProvider(settings.provider), - currentCatalog, - (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)), - ), - checkProvider, - enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => - resolveMaintenance().pipe( - Effect.flatMap((maintenanceCapabilities) => - enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, { - enableProviderUpdateChecks: settings.enableProviderUpdateChecks, - }), - ), - Effect.provideService(HttpClient.HttpClient, httpClient), - Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), - Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)), - ), - }).pipe( - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`, - cause, + ), + ); + + const orchestrationAdapter = yield* createCodexAdapterV2( + { + instanceId, + displayName, + accentColor, + environment, + enabled, + config, + }, + { onUsageLimits: (update) => snapshot.applyUsageLimits(update) }, + ).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Failed to build Codex orchestration adapter.", + cause, + }), + ), + ); + + // Kick the TTL-gated manifest refresh in the background and classify with the in-memory + // manifest, so a slow or hung fetch never delays the provider check. + const checkProvider = modelCatalog.refreshInBackground.pipe( + Effect.andThen( + Effect.zipWith( + checkCodexProviderStatus(effectiveConfig, undefined, processEnv), + currentCatalog, + (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)), + { concurrent: true }, + ), + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, pathService), + ); + const snapshotSettings = yield* makeProviderSnapshotSettingsSource(effectiveConfig); + const snapshot = yield* makeManagedServerProvider>({ + resolveMaintenance, + getSettings: snapshotSettings.getSettings, + streamSettings: snapshotSettings.streamSettings, + haveSettingsChanged: haveProviderSnapshotSettingsChanged, + initialSnapshot: (settings) => + Effect.zipWith( + makePendingCodexProvider(settings.provider), + currentCatalog, + (draft, catalog) => stampIdentity(applyCodexModelCatalog(draft, catalog)), + ), + checkProvider, + enrichSnapshot: ({ settings, snapshot, publishSnapshot }) => + resolveMaintenance().pipe( + Effect.flatMap((maintenanceCapabilities) => + enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, { + enableProviderUpdateChecks: settings.enableProviderUpdateChecks, }), + ), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), + Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)), ), - ); - const textGeneration = yield* makeCodexTextGeneration( - effectiveConfig, - processEnv, - snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), - ); - const snapshotForCwd = (cwd: string) => - !effectiveConfig.enabled - ? snapshot.getSnapshot - : Effect.all([ - snapshot.getSnapshot, - probeCodexSkillsForCwd({ - binaryPath: effectiveConfig.binaryPath, - homePath: effectiveConfig.homePath, - launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), - cwd, - environment: processEnv, - }).pipe( - Effect.scoped, - Effect.timeout("20 seconds"), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ), - ]).pipe( - Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })), - Effect.mapError( - (cause) => - new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: `Failed to probe Codex skills for '${cwd}'`, - cause, - }), - ), - ); - - // Redemption spends something on the user's account. It serialises on - // the account (instances sharing a Codex home share the credit), keeps - // one idempotency key until Codex reports an outcome, and is bounded so - // a hung app-server cannot hold the account lock. - // Keyed on the directory holding auth.json: an auth-overlay instance has - // its own account under `effectiveHomePath`, while plain instances share - // the common home. The continuation key would conflate the two. - const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath; - const consumeResetCredit: NonNullable = () => - resetCreditCoordinator - .redeem(accountKey, (idempotencyKey) => - Effect.gen(function* () { - const { client } = yield* withCodexAppServerClient({ - binaryPath: effectiveConfig.binaryPath, - homePath: effectiveConfig.homePath, - launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), - cwd: process.cwd(), - environment: processEnv, - }); - const response = yield* client.request("account/rateLimitResetCredit/consume", { - idempotencyKey, - }); - return response.outcome; - }).pipe(Effect.scoped, Effect.timeout("20 seconds")), - ) - .pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + }).pipe( + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`, + cause, + }), + ), + ); + const textGeneration = yield* makeCodexTextGeneration( + effectiveConfig, + processEnv, + snapshot.getSnapshot.pipe(Effect.map((value) => value.models)), + ); + const snapshotForCwd = (cwd: string) => + !effectiveConfig.enabled + ? snapshot.getSnapshot + : Effect.all([ + snapshot.getSnapshot, + probeCodexSkillsForCwd({ + binaryPath: effectiveConfig.binaryPath, + homePath: effectiveConfig.homePath, + launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), + cwd, + environment: processEnv, + }).pipe( + Effect.scoped, + Effect.timeout("20 seconds"), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ]).pipe( + Effect.map(([machineSnapshot, skills]) => ({ ...machineSnapshot, skills })), Effect.mapError( (cause) => new ProviderDriverError({ driver: DRIVER_KIND, instanceId, - detail: "Codex could not redeem the reset credit.", + detail: `Failed to probe Codex skills for '${cwd}'`, cause, }), ), - // The windows just changed; re-probe so the snapshot says so. A - // failed probe republishes the pre-redemption limits rather than - // marking them failed, so "confirmed" means `checkedAt` moved past - // what was published before the redemption started. - Effect.tap((outcome) => - Effect.gen(function* () { - const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt; - const refreshed = yield* snapshot.refresh; - const after = refreshed.usageLimits?.checkedAt; - if ( - outcome === "reset" && - (after === undefined || - after === before || - refreshed.usageLimits?.unavailable?.reason === "probeFailed") - ) { - return yield* new ProviderDriverError({ - driver: DRIVER_KIND, - instanceId, - detail: - "The reset was applied, but Codex could not confirm the new limits. Refresh to check.", - }); - } - }), - ), ); - return { - instanceId, - driverKind: DRIVER_KIND, - continuationIdentity, - displayName, - accentColor, - enabled, - snapshot, - snapshotForCwd, - consumeResetCredit, - orchestrationAdapter, - textGeneration, - } satisfies ProviderInstance; - }), + // Redemption spends account credit; serialize by the auth.json directory, keep one idempotency key + // until the outcome, and bound the wait so a hung app-server cannot hold the account lock. + // Auth overlays use effectiveHomePath; the continuation key would conflate them with shared homes. + const accountKey = homeLayout.effectiveHomePath ?? homeLayout.sharedHomePath; + const consumeResetCredit: NonNullable = () => + resetCreditCoordinator + .redeem(accountKey, (idempotencyKey) => + Effect.gen(function* () { + const { client } = yield* withCodexAppServerClient({ + binaryPath: effectiveConfig.binaryPath, + homePath: effectiveConfig.homePath, + launchArgs: resolveCodexLaunchArgs(effectiveConfig.launchArgs, processEnv), + cwd: process.cwd(), + environment: processEnv, + }); + const response = yield* client.request("account/rateLimitResetCredit/consume", { + idempotencyKey, + }); + return response.outcome; + }).pipe(Effect.scoped, Effect.timeout("20 seconds")), + ) + .pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: "Codex could not redeem the reset credit.", + cause, + }), + ), + // The windows just changed; re-probe so the snapshot says so. A + // failed probe republishes the pre-redemption limits rather than + // marking them failed, so "confirmed" means `checkedAt` moved past + // what was published before the redemption started. + Effect.tap((outcome) => + Effect.gen(function* () { + const before = (yield* snapshot.getSnapshot).usageLimits?.checkedAt; + const refreshed = yield* snapshot.refresh; + const after = refreshed.usageLimits?.checkedAt; + if ( + outcome === "reset" && + (after === undefined || + after === before || + refreshed.usageLimits?.unavailable?.reason === "probeFailed") + ) { + return yield* new ProviderDriverError({ + driver: DRIVER_KIND, + instanceId, + detail: + "The reset was applied, but Codex could not confirm the new limits. Refresh to check.", + }); + } + }), + ), + ); + + return { + instanceId, + driverKind: DRIVER_KIND, + continuationIdentity, + displayName, + accentColor, + enabled, + snapshot, + snapshotForCwd, + consumeResetCredit, + orchestrationAdapter, + textGeneration, + } satisfies ProviderInstance; + }), }; diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts index 7434552471e3a..093777e67db5d 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts @@ -3,7 +3,6 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import { CodexSettings } from "@t3tools/contracts"; @@ -41,25 +40,6 @@ const writeTextFile = Effect.fn("CodexHomeLayout.test.writeTextFile")(function* it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { describe("resolveCodexHomeLayout", () => { - it.effect("uses direct CODEX_HOME when no shadow home is configured", () => - Effect.gen(function* () { - const homePath = yield* makeTempDir("t3code-codex-home-"); - - const layout = yield* resolveCodexHomeLayout( - decodeCodexSettings({ - homePath, - }), - ); - - expect(layout).toMatchObject({ - mode: "direct", - sharedHomePath: homePath, - effectiveHomePath: homePath, - continuationKey: `codex:home:${homePath}`, - }); - }), - ); - it.effect("uses the shared home for continuation and the shadow home for runtime", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -343,40 +323,5 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { ); }), ); - - it.effect("preserves filesystem operation, paths, and cause", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const sharedRoot = yield* makeTempDir("t3code-codex-shared-root-"); - const sharedHome = path.join(sharedRoot, "shared-home"); - const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); - const shadowHome = path.join(shadowRoot, "shadow"); - yield* writeTextFile(sharedHome, "not a directory\n"); - - const layout = yield* resolveCodexHomeLayout( - decodeCodexSettings({ - homePath: sharedHome, - shadowHomePath: shadowHome, - }), - ); - - const error = yield* materializeCodexShadowHome(layout).pipe(Effect.flip); - - expect(error._tag).toBe("CodexShadowHomeFileSystemError"); - if (error._tag !== "CodexShadowHomeFileSystemError") { - return expect.fail("Expected CodexShadowHomeFileSystemError"); - } - expect(error).toMatchObject({ - operation: "makeDirectory", - sharedHomePath: sharedHome, - effectiveHomePath: shadowHome, - }); - expect(error.path.startsWith(sharedHome)).toBe(true); - expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); - expect(error.message).toBe( - `Codex shadow home filesystem operation 'makeDirectory' failed for '${error.path}'.`, - ); - }), - ); }); }); diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.ts index b0bb7df4e2d46..f175a0fdd00a9 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.ts @@ -31,8 +31,7 @@ const KNOWN_SHARED_DIRECTORIES = [ const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]); // Finder maintains metadata separately for each directory, including shadow homes. const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp", ".DS_Store"]); -// Codex creates these runtime locks itself when it starts in a shadow home before the shared -// home has one. They guard shared state, so a local copy is replaced with the shared link. +// Shadow homes may create local runtime locks first; replace them with shared links because they guard shared state. const REPLACEABLE_SHARED_RUNTIME_ENTRIES = new Set(["mcp-oauth-locks", ".sqlite-maintenance.lock"]); function resolveHomePath(path: Path.Path, home: string, value: string | undefined): string { diff --git a/apps/server/src/provider/Drivers/CodexManagedProvider.ts b/apps/server/src/provider/Drivers/CodexManagedProvider.ts index eb44345840232..f9728f9a24973 100644 --- a/apps/server/src/provider/Drivers/CodexManagedProvider.ts +++ b/apps/server/src/provider/Drivers/CodexManagedProvider.ts @@ -1,4 +1,9 @@ -import { ProviderDriverKind, TextGenerationError, type CodexSettings } from "@t3tools/contracts"; +import { + ProviderDriverKind, + ProviderSetupError, + TextGenerationError, + type CodexSettings, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -55,7 +60,7 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu homePath: runtime.homeLayout.sharedHomePath, shadowHomePath: runtime.homeLayout.mode === "authOverlay" ? runtime.homePath : null, }; - const pending = makePendingCodexProvider({ ...config, customModels: [] }).pipe( + const pending = makePendingCodexProvider({ ...config, enabled, customModels: [] }).pipe( Effect.map((draft) => stamp({ ...draft, @@ -128,10 +133,21 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu effective.environment, managedAuth, ); - const models = yield* chatGptModels( - effective.environment.ACCESS_TOKEN!, - draft.models, - ).pipe(Effect.provideService(HttpClient.HttpClient, http)); + const credentials = yield* runtime.auth.access; + // Another server can replace the saved profile while the native probe runs. + // Never send that account's token with the launch profile's catalog labels. + if ( + (yield* runtime.auth.profileKey(credentials)) !== effective.revision || + (yield* runtime.auth.profileKey(saved.value)) !== effective.revision + ) + return yield* new ProviderSetupError({ + instanceId, + operation: "models", + detail: "The ChatGPT connection changed while checking Codex. Retry.", + }); + const models = yield* chatGptModels(credentials.accessToken, draft.models).pipe( + Effect.provideService(HttpClient.HttpClient, http), + ); return { ...draft, models }; }), ), @@ -219,13 +235,12 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu ); yield* runtime.auth.controller.subscribe("managed-codex-snapshot").pipe( Stream.filter((state) => ["idle", "succeeded", "failed", "cancelled"].includes(state.phase)), - // Sign-out closes the scope of an in-flight probe, which fails that refresh - // with an interrupt. Keep listening so the sign-out's own idle still refreshes. + // Sign-out interrupts in-flight probes; keep listening for its subsequent idle refresh. Stream.runForEach(() => snapshot.refresh.pipe(Effect.ignoreCause({ log: true }))), Effect.forkScoped, ); const resolveRuntime = runtime.auth.controller.withAccess!(runtime.resolve); - // Launch settings resolve per session from the signed-in token. The registry + // Launch settings bind the refresh command to the signed-in profile. The registry // already wraps openSession in withAccess, so resolve without re-entering it. const orchestrationAdapter = yield* createCodexAdapterV2(input, { onUsageLimits: (update) => snapshot.applyUsageLimits(update), @@ -284,21 +299,40 @@ export const makeManagedCodexProvider = Effect.fn("makeManagedCodexProvider")(fu snapshotForCwd: (cwd: string) => enabled ? resolveRuntime.pipe( - Effect.flatMap((effective) => - probeCodexSkillsForCwd({ - binaryPath: effective.config.binaryPath, - homePath: effective.config.homePath, - launchArgs: effective.config.launchArgs, - cwd, - environment: effective.environment, - }), - ), - Effect.flatMap((skills) => - snapshot.getSnapshot.pipe(Effect.map((draft) => ({ ...draft, skills }))), - ), + Effect.matchEffect({ + // Signed-out snapshots have an empty inventory; a signed-in runtime failure must fail the scan. + onFailure: (cause) => + snapshot.getSnapshot.pipe( + Effect.filterOrFail( + (machine) => machine.auth.status === "unauthenticated", + () => cause, + ), + ), + onSuccess: (effective) => + probeCodexSkillsForCwd({ + binaryPath: effective.config.binaryPath, + homePath: effective.config.homePath, + launchArgs: effective.config.launchArgs, + cwd, + environment: effective.environment, + }).pipe( + Effect.flatMap((skills) => + snapshot.getSnapshot.pipe(Effect.map((draft) => ({ ...draft, skills }))), + ), + ), + }), Effect.scoped, Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.catch(() => snapshot.getSnapshot), + // Fail instead of returning machine inventory, which the registry would publish as workspace inventory. + Effect.mapError( + (cause) => + new ProviderDriverError({ + driver: DRIVER, + instanceId, + detail: `Failed to probe Codex skills for '${cwd}'`, + cause, + }), + ), ) : snapshot.getSnapshot, } satisfies ProviderInstance; diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index e81a144210477..a08eac31746ff 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -1,9 +1,8 @@ // @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime or sub-millisecond mtime, which the cache tests compare. import * as NodeFSP from "node:fs/promises"; -import * as NodeSqlite from "node:sqlite"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, describe, it, vi } from "@effect/vitest"; +import { assert, describe, it } from "@effect/vitest"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -11,7 +10,6 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as SqlClient from "effect/sql/SqlClient"; -import * as Tracer from "effect/Tracer"; import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts"; @@ -164,6 +162,36 @@ describe("readAntigravityUsage", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("prices ACP effort variants at the base model rate", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const dir = yield* tempDir; + yield* seedDatabase(path.join(dir, "effort.db"), (db) => + Effect.gen(function* () { + yield* createTables(db); + for (const [idx, name] of ["gemini-4-argon-high", "gemini-4-argon"].entries()) { + yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ + idx, + new Uint8Array(protoBytes(1, protoText(19, name))), + ]); + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + idx, + new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))), + ]); + } + }), + ); + const result = yield* readAntigravityUsage(dir, 0); + assert.deepStrictEqual( + records(result).map(({ model, rateModel }) => [model, rateModel]), + [ + ["gemini-4-argon-high", "gemini-4-argon"], + ["gemini-4-argon", undefined], + ], + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("merges Antigravity aliases that bridge previously separate step records", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -311,65 +339,6 @@ describe("readAntigravityUsage", () => { ]), ); - it.effect("reuses an unchanged Antigravity database instead of decoding it again", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const dir = yield* tempDir; - const db = yield* openDatabase(path.join(dir, "session-1.db")); - yield* db.exec("CREATE TABLE gen_metadata (idx INTEGER, data BLOB)"); - yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [0, antigravityGeneration("r-1")]); - const cache = makeAntigravityUsageCache(); - assert.deepStrictEqual((yield* readAntigravityUsage(dir, 0, cache)).errors, []); - - yield* db.exec("BEGIN EXCLUSIVE"); - assert.strictEqual((yield* readAntigravityUsage(dir, 0)).errors.length, 1); - const cached = yield* readAntigravityUsage(dir, 0, cache); - assert.deepStrictEqual(cached.errors, []); - assert.deepStrictEqual( - records(cached).map((record) => record.dedupeKey), - ["antigravity:11:r-1"], - ); - yield* db.exec("ROLLBACK"); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("rereads an Antigravity database rewritten with its size and mtime restored", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const pathService = yield* Path.Path; - const dir = yield* tempDir; - const path = pathService.join(dir, "session-1.db"); - yield* seedDatabase(path, (db) => - Effect.gen(function* () { - yield* db.exec("CREATE TABLE gen_metadata (idx INTEGER, data BLOB)"); - yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ - 0, - antigravityGeneration("r-1"), - ]); - }), - ); - yield* fileSystem.utimes(path, 1780000000, 1780000000); - const cache = makeAntigravityUsageCache(); - assert.deepStrictEqual((yield* readAntigravityUsage(dir, 0, cache)).errors, []); - - // ctime has the kernel's timestamp granularity, which can be a few - // milliseconds, so repeat the forged rewrite until it lands on a later tick - // than the cached read, as any real rewrite does. - const stat = () => Effect.promise(() => NodeFSP.stat(path)); - const cached = yield* stat(); - do { - yield* fileSystem.writeFile(path, new Uint8Array(cached.size)); - yield* fileSystem.utimes(path, 1780000000, 1780000000); - } while ((yield* stat()).ctimeMs === cached.ctimeMs); - const restored = yield* stat(); - assert.strictEqual(restored.size, cached.size); - assert.strictEqual(restored.mtimeMs, cached.mtimeMs); - const next = yield* readAntigravityUsage(dir, 0, cache); - assert.deepStrictEqual(next.errors, [path]); - assert.deepStrictEqual(records(next), []); - }).pipe(Effect.provide(NodeServices.layer)), - ); - it.effect("rereads an Antigravity database when only its WAL changed", () => Effect.gen(function* () { const pathService = yield* Path.Path; @@ -444,104 +413,9 @@ describe("readAntigravityUsage", () => { }).pipe(Effect.provide(NodeServices.layer)), ); - const recordReads = Effect.gen(function* () { - const reads: Array<{ sql: string; rows: number }> = []; - const all = NodeSqlite.StatementSync.prototype.all; - yield* Effect.acquireRelease( - Effect.sync(() => - vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function ( - this: NodeSqlite.StatementSync, - ...params - ) { - const result = all.apply(this, params); - reads.push({ sql: this.sourceSQL, rows: result.length }); - return result; - }), - ), - (spy) => Effect.sync(() => spy.mockRestore()), - ); - return reads; - }); - const stepUsage = (responseId: string) => new Uint8Array(protoBytes(9, [...protoNumber(2, 10), ...protoText(11, responseId)])); - it.effect("reads one Antigravity generation or one page of steps per statement", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const dir = yield* tempDir; - yield* seedDatabase(path.join(dir, "session-1.db"), (db) => - Effect.gen(function* () { - yield* db.exec( - "CREATE TABLE `gen_metadata` (`idx` integer,`data` blob,`size` integer NOT NULL DEFAULT 0,PRIMARY KEY (`idx`))", - ); - yield* db.exec( - "CREATE TABLE `steps` (`idx` integer,`step_type` integer NOT NULL DEFAULT 0,`status` integer NOT NULL DEFAULT 0,`metadata` blob,PRIMARY KEY (`idx`))", - ); - yield* db.exec("CREATE INDEX `idx_steps_status` ON `steps`(`status`)"); - yield* db.exec("CREATE INDEX `idx_steps_step_type` ON `steps`(`step_type`)"); - yield* db.exec("BEGIN"); - for (let idx = 0; idx < 3; idx++) { - yield* db.run("INSERT INTO gen_metadata (idx, data) VALUES (?, ?)", [ - idx, - antigravityGeneration(`g-${idx}`), - ]); - } - for (let idx = 0; idx < 250; idx++) { - yield* db.run("INSERT INTO steps (idx, metadata) VALUES (?, ?)", [ - idx, - idx >= 75 && idx < 175 ? null : stepUsage(`s-${idx}`), - ]); - } - yield* db.exec("COMMIT"); - }), - ); - const reads = yield* recordReads; - const spans: Tracer.NativeSpan[] = []; - const tracer = Tracer.make({ - span: (options) => { - const span = new Tracer.NativeSpan(options); - spans.push(span); - return span; - }, - }); - const result = yield* readAntigravityUsage(dir, 0).pipe( - Effect.provideService(Tracer.Tracer, tracer), - ); - assert.deepStrictEqual(result.errors, []); - assert.deepStrictEqual( - records(result).map((record) => record.dedupeKey), - [ - ...Array.from({ length: 75 }, (_, idx) => `antigravity:11:s-${idx}`), - ...Array.from({ length: 75 }, (_, idx) => `antigravity:11:s-${idx + 175}`), - ...Array.from({ length: 3 }, (_, idx) => `antigravity:11:g-${idx}`), - ], - ); - assert.isTrue(spans.some((span) => span.name === "sqlite")); - assert.deepStrictEqual( - spans.flatMap((span) => { - const query = span.attributes.get("db.query.text"); - return typeof query === "string" && query.includes("rowid > ?") ? [query] : []; - }), - [], - ); - for (const [table, total, most] of [ - ["steps", 250, 64], - ["gen_metadata", 3, 1], - ] as const) { - const rows = reads - .filter((read) => read.sql.includes(`FROM ${table} `)) - .map((read) => read.rows); - assert.strictEqual( - rows.reduce((sum, count) => sum + count, 0), - total, - table, - ); - assert.isAtMost(Math.max(...rows), most, table); - } - }).pipe(Effect.provide(NodeServices.layer)), - ); - it.effect("returns Antigravity records in idx order however the rows are stored", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 1493c283c2adb..7d73f1221cb4b 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -101,6 +101,12 @@ const MODEL_IDS: Record = { 1047: "gemini-3-flash-preview", }; +// ACP slugs append the thinking level, which shares the base model's price. +function withRateModel(record: UsageRecord): UsageRecord { + const rateModel = record.model.replace(/-(?:low|medium|high)$/, ""); + return rateModel === record.model ? record : { ...record, rateModel }; +} + function modelName(name: string, id: number): string { if (name) { const normalized = name @@ -170,11 +176,7 @@ class AntigravityDatabaseDecodeError extends Schema.TaggedError(query, [after, pageRows]) .pipe(Effect.withTracerEnabled(false)); for (const row of rows) { - // Skipped here rather than in SQL, so a statement never scans past - // more than one page of steps that have no metadata. + // Filter outside SQL to bound scans to one page, including rows without metadata. if (step && row.data === null) continue; const idx = row.idx; if (typeof idx !== "number") { @@ -327,12 +326,7 @@ interface CachedDatabase { readonly candidates: readonly UsageCandidate[]; } -/** - * Parsed databases keyed by canonical path. An entry is reused only while both - * the database and its `-wal` sidecar keep the same size, mtime and ctime: new - * rows land in the WAL without touching the main file until a checkpoint, and - * ctime moves on any content write even when mtime is restored. - */ +/** Fingerprint canonical DB/WAL paths by size, mtime and ctime; WAL holds new rows, and ctime catches restored mtimes. */ export const makeAntigravityUsageCache = () => new Map(); export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* ( @@ -433,54 +427,56 @@ export const readAntigravityUsage = Effect.fn("readAntigravityUsage")(function* cache?.set(canonical, { fingerprint, candidates }); return candidates; }); - const walk = (directory: string, root: string): Effect.Effect => - Effect.gen(function* () { - const names = yield* fileSystem.readDirectory(directory).pipe( - Effect.catchTags({ - PlatformError: (cause) => { - if (cause.reason._tag !== "NotFound") errors.push(directory); - return Effect.succeed(null); - }, - }), - ); - if (names === null) return; - names.sort((a, b) => a.localeCompare(b)); - for (const name of names) { - const path = pathService.join(directory, name); - // Like a directory listing's entry types: symlinks are neither files nor directories. - const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path))); - const type = isLink - ? "SymbolicLink" - : yield* fileSystem.stat(path).pipe( - Effect.map((info) => info.type), - Effect.orElseSucceed(() => null), - ); - if (type === "Directory") { - yield* walk(path, root); - } else if ((type === "File" || type === null) && name.endsWith(".db")) { - const candidates = yield* readFile(path).pipe( - Effect.catch(() => { - errors.push(path); - return Effect.succeed(null); - }), + const walk = Effect.fn("antigravityUsageReader.walk")(function* ( + directory: string, + root: string, + ): Effect.fn.Return { + const names = yield* fileSystem.readDirectory(directory).pipe( + Effect.catchTags({ + PlatformError: (cause) => { + if (cause.reason._tag !== "NotFound") errors.push(directory); + return Effect.succeed(null); + }, + }), + ); + if (names === null) return; + names.sort((a, b) => a.localeCompare(b)); + for (const name of names) { + const path = pathService.join(directory, name); + // Like a directory listing's entry types: symlinks are neither files nor directories. + const isLink = Exit.isSuccess(yield* Effect.exit(fileSystem.readLink(path))); + const type = isLink + ? "SymbolicLink" + : yield* fileSystem.stat(path).pipe( + Effect.map((info) => info.type), + Effect.orElseSucceed(() => null), ); - if (candidates === null) continue; - const fileIndex = files.length; - files.push({ root, path, records: [] }); - for (const [index, candidate] of candidates.entries()) { - append(candidate, fileIndex); - if (index % 256 === 255) yield* Effect.yieldNow; - } + if (type === "Directory") { + yield* walk(path, root); + } else if ((type === "File" || type === null) && name.endsWith(".db")) { + const candidates = yield* readFile(path).pipe( + Effect.catch(() => { + errors.push(path); + return Effect.succeed(null); + }), + ); + if (candidates === null) continue; + const fileIndex = files.length; + files.push({ root, path, records: [] }); + for (const [index, candidate] of candidates.entries()) { + append(candidate, fileIndex); + if (index % 256 === 255) yield* Effect.yieldNow; } } - }); + } + }); for (const root of roots) yield* walk(root, root); if (cache !== undefined) { for (const key of cache.keys()) if (!visited.has(key)) cache.delete(key); } for (const [index, group] of groups.entries()) { if (group.parent === index && group.record.timestampMs >= sinceMs) { - files[group.fileIndex]!.records.push(group.record); + files[group.fileIndex]!.records.push(withRateModel(group.record)); } } return { files, errors }; diff --git a/apps/server/src/provider/Drivers/claudeUsage.test.ts b/apps/server/src/provider/Drivers/claudeUsage.test.ts index c65cb237d39ad..a9ebb05a2e1e7 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.test.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; -import { parseClaudeLine } from "./claudeUsage.ts"; +import { claudeUsageFormat, parseClaudeLine } from "./claudeUsage.ts"; function claudeLine(overrides: { messageId: string; @@ -48,17 +48,8 @@ describe("parseClaudeLine", () => { expect(record?.speed).toBe("standard"); }); - it("marks fast-mode requests", () => { - const line = (speed: string) => - parseClaudeLine(claudeLine({ messageId: "msg_1", contentType: "text", speed })); - - expect(line("fast")?.speed).toBe("fast"); - expect(line("standard")?.speed).toBe("standard"); - }); - it("gives every content block of one message the same dedupe key", () => { - // T3 Code writes one record per content block, each repeating the parent - // message's full usage. Summing them would overcount ~2.4x on real data. + // Content-block records repeat full parent usage; summing them overcounts. const text = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "text" })); const toolUse = parseClaudeLine(claudeLine({ messageId: "msg_2", contentType: "tool_use" })); @@ -66,8 +57,32 @@ describe("parseClaudeLine", () => { expect(text?.totals).toEqual(toolUse?.totals); }); - it("ignores records that are not assistant messages", () => { - expect(parseClaudeLine(JSON.stringify({ type: "user", message: {} }))).toBeNull(); - expect(parseClaudeLine("not json")).toBeNull(); + it("skips local placeholders in both reader paths but keeps real zero-token responses", () => { + const projected = { + type: "assistant", + timestamp: "2026-08-07T04:05:13.944Z", + message: { + model: "claude-fable-5", + usage: { input_tokens: 0, output_tokens: 0 }, + }, + }; + const expected = [ + expect.objectContaining({ + model: "claude-fable-5", + totals: { + uncachedInputTokens: 0, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 0, + reasoningTokens: 0, + }, + }), + ]; + expect(claudeUsageFormat.parseLine(JSON.stringify(projected), undefined)).toEqual(expected); + expect(claudeUsageFormat.parseProjected(projected, undefined)).toEqual(expected); + + const synthetic = { ...projected, message: { ...projected.message, model: "" } }; + expect(claudeUsageFormat.parseLine(JSON.stringify(synthetic), undefined)).toEqual([]); + expect(claudeUsageFormat.parseProjected(synthetic, undefined)).toEqual([]); }); }); diff --git a/apps/server/src/provider/Drivers/claudeUsage.ts b/apps/server/src/provider/Drivers/claudeUsage.ts index 86e352109cd30..c5ff71a5c839e 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.ts @@ -12,6 +12,9 @@ import { } from "@t3tools/provider-core/server/usage"; import * as HostProcess from "@t3tools/shared/HostProcess"; +// Claude Code uses this model for local placeholders that never reached the API. +export const CLAUDE_SYNTHETIC_MODEL = ""; + /** * T3 Code writes one record per assistant *content block*, and every one of those records repeats * the same complete `usage` object for the parent message. Summing them overcounts by roughly @@ -45,7 +48,7 @@ function parseClaudeRecord(parsed: unknown): UsageRecord | null { if (timestampMs === null) return null; const model = typeof messageRecord["model"] === "string" ? messageRecord["model"] : ""; - if (model.length === 0) return null; + if (model.length === 0 || model === CLAUDE_SYNTHETIC_MODEL) return null; const messageId = typeof messageRecord["id"] === "string" ? messageRecord["id"] : null; const requestId = typeof record["requestId"] === "string" ? record["requestId"] : null; diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index 4136aba3f3698..d9ee4f4a04ff5 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; -import { initialCodexScanState, parseCodexLine } from "./codexUsage.ts"; +import { codexUsageFormat, initialCodexScanState, parseCodexLine } from "./codexUsage.ts"; describe("parseCodexLine", () => { const sessionMeta = JSON.stringify({ @@ -30,6 +30,23 @@ describe("parseCodexLine", () => { }, }, }); + const counters = (input: number, output: number) => ({ + input_tokens: input, + cached_input_tokens: 0, + cache_write_input_tokens: 0, + output_tokens: output, + reasoning_output_tokens: 0, + total_tokens: input + output, + }); + const counted = (last: unknown, total?: unknown, extra = {}) => + JSON.stringify({ + type: "event_msg", + timestamp: "2026-08-01T05:17:49.919Z", + payload: { + type: "token_count", + info: { last_token_usage: last, total_token_usage: total, ...extra }, + }, + }); it("attributes usage to the model from the preceding turn context", () => { const state = initialCodexScanState(); @@ -55,41 +72,379 @@ describe("parseCodexLine", () => { expect(repeat).toBeNull(); }); - it("drops usage that arrives before any model is known", () => { + it("does not consume counters before the model and timestamp are valid", () => { const state = initialCodexScanState(); expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull(); + parseCodexLine(turnContext, state); + expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull(); + + const cumulativeState = initialCodexScanState(); + const line = counted(counters(100, 20), counters(100, 20)); + expect(parseCodexLine(line, cumulativeState)).toBeNull(); + parseCodexLine(turnContext, cumulativeState); + expect( + parseCodexLine(line.replace("2026-08-01T05:17:49.919Z", "invalid"), cumulativeState), + ).toBeNull(); + expect(parseCodexLine(line, cumulativeState)?.totals.outputTokens).toBe(20); + expect(codexUsageFormat.readMalformedRecords?.(cumulativeState)).toBe(0); }); - it("does not let a pre-model event poison the duplicate signature", () => { + it("ignores stale changed requests but counts equal requests when totals advance across contexts", () => { const state = initialCodexScanState(); - expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).toBeNull(); parseCodexLine(turnContext, state); - expect(parseCodexLine(tokenCount(100, 0, 10, 0), state)).not.toBeNull(); + const request = counters(100, 20); + expect(parseCodexLine(counted(request, request), state)?.totals.outputTokens).toBe(20); + expect(parseCodexLine(counted(counters(20, 5), request), state)).toBeNull(); + expect( + parseCodexLine( + counted({ ...counters(0, 0), total_tokens: 20330 }, request, { + model_context_window: 258400, + }), + state, + ), + ).toBeNull(); + expect(parseCodexLine(counted(request, counters(200, 40)), state)?.totals.outputTokens).toBe( + 20, + ); + + for (const [index, tier] of ["priority", "ultrafast"].entries()) { + parseCodexLine( + JSON.stringify({ type: "turn_context", payload: { model: "gpt-6-astra" } }), + state, + ); + parseCodexLine( + JSON.stringify({ + type: "event_msg", + payload: { type: "thread_settings_applied", thread_settings: { service_tier: tier } }, + }), + state, + ); + const record = parseCodexLine( + counted(request, counters(100 * (index + 3), 20 * (index + 3))), + state, + ); + expect(record).toMatchObject({ + model: "gpt-6-astra", + speed: tier === "priority" ? "fast" : "ultrafast", + totals: { uncachedInputTokens: 100, outputTokens: 20 }, + }); + } + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); }); - it("carries the service tier from the latest thread settings", () => { - const settings = (thread_settings: Record) => - JSON.stringify({ - type: "event_msg", - timestamp: "2026-08-01T05:17:42.000Z", - payload: { type: "thread_settings_applied", thread_settings }, + it.each([false, true])( + "does not rebill legacy requests or drop the next cumulative delta (initial cumulative=%s)", + (initialCumulative) => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + const first = counters(100, 20); + expect( + parseCodexLine(counted(first, initialCumulative ? first : undefined), state)?.totals + .outputTokens, + ).toBe(20); + expect(parseCodexLine(counted(first), state)).toBeNull(); + expect(parseCodexLine(counted(counters(20, 5)), state)?.totals.outputTokens).toBe(5); + expect(parseCodexLine(counted(counters(20, 5), counters(120, 25)), state)).toBeNull(); + expect( + parseCodexLine(counted(counters(10, 2), counters(130, 27)), state)?.totals.outputTokens, + ).toBe(2); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + }, + ); + + it("checks every cumulative component and recovers using an inconsistent pair's valid baseline", () => { + const request = { + ...counters(100, 20), + cached_input_tokens: 30, + cache_write_input_tokens: 10, + reasoning_output_tokens: 5, + }; + const fields = Object.keys(request) as (keyof typeof request)[]; + for (const field of fields) { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + expect(parseCodexLine(counted(request, request), state)?.totals).toEqual({ + uncachedInputTokens: 60, + cachedInputTokens: 30, + cacheCreationTokens: 10, + outputTokens: 20, + reasoningTokens: 5, }); + const total = { ...request }; + for (const key of fields) total[key] *= 2; + total[field] += 1; + if (field === "input_tokens" || field === "output_tokens") total.total_tokens += 1; + expect(parseCodexLine(counted(request, total), state), field).toBeNull(); + expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + for (const key of fields) total[key] += request[key]; + expect(parseCodexLine(counted(request, total), state)?.totals.outputTokens, field).toBe(20); + expect(codexUsageFormat.readMalformedRecords?.(state), field).toBe(1); + } + }); + + it.each(["continuation", "fork", "subagent"])( + "bills only the latest request when a %s has no initial counter baseline", + (source) => { + const state = initialCodexScanState(); + parseCodexLine( + JSON.stringify({ + type: "session_meta", + timestamp: "2026-08-01T05:17:41.000Z", + payload: { + id: "child", + model_provider: "openai", + ...(source === "fork" ? { forked_from_id: "parent" } : {}), + ...(source === "subagent" + ? { source: { subagent: { thread_spawn: { parent_thread_id: "parent" } } } } + : { source: "vscode" }), + }, + }), + state, + ); + parseCodexLine(turnContext, state); + const request = { + ...counters(100, 20), + cached_input_tokens: 30, + cache_write_input_tokens: 10, + reasoning_output_tokens: 5, + }; + const cumulative = { + ...counters(500, 60), + cached_input_tokens: 200, + cache_write_input_tokens: 20, + reasoning_output_tokens: 15, + }; + const first = counted(request, cumulative); + expect(parseCodexLine(first, state)).toMatchObject({ + sessionId: "child", + totals: { + uncachedInputTokens: 60, + cachedInputTokens: 30, + cacheCreationTokens: 10, + outputTokens: 20, + reasoningTokens: 5, + }, + }); + expect(parseCodexLine(first, state)).toBeNull(); + expect(parseCodexLine(counted(counters(10, 2), cumulative), state)).toBeNull(); + expect( + parseCodexLine( + counted(counters(10, 2), { + ...cumulative, + input_tokens: 510, + output_tokens: 62, + total_tokens: 572, + }), + state, + )?.totals.outputTokens, + ).toBe(2); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + }, + ); + + it.each([ + { + ...counters(90, 40), + cached_input_tokens: 60, + cache_write_input_tokens: 20, + reasoning_output_tokens: 10, + }, + { + ...counters(200, 10), + cached_input_tokens: 60, + cache_write_input_tokens: 20, + reasoning_output_tokens: 5, + }, + { + ...counters(200, 40), + cached_input_tokens: 20, + cache_write_input_tokens: 20, + reasoning_output_tokens: 10, + }, + { + ...counters(200, 40), + cached_input_tokens: 60, + cache_write_input_tokens: 5, + reasoning_output_tokens: 10, + }, + { + ...counters(200, 40), + cached_input_tokens: 60, + cache_write_input_tokens: 20, + reasoning_output_tokens: 3, + }, + { + ...counters(110, 40), + cached_input_tokens: 60, + cache_write_input_tokens: 20, + reasoning_output_tokens: 10, + }, + { + ...counters(200, 30), + cached_input_tokens: 60, + cache_write_input_tokens: 20, + reasoning_output_tokens: 20, + }, + ])("rejects an initial snapshot with an impossible inherited baseline: %j", (cumulative) => { const state = initialCodexScanState(); parseCodexLine(turnContext, state); - const speedAfter = (line: string, output: number) => { - parseCodexLine(line, state); - return parseCodexLine(tokenCount(100, 0, output, 0), state)?.speed; + const request = { + ...counters(100, 20), + cached_input_tokens: 30, + cache_write_input_tokens: 10, + reasoning_output_tokens: 5, }; + expect(parseCodexLine(counted(request, cumulative), state)).toBeNull(); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect(state.lastCumulativeUsage).toEqual(cumulative); + }); + + it.each(["request", "cumulative"])("skips malformed %s counters and recovers", (malformed) => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + const request = counters(100, 20); + parseCodexLine(counted(request, request), state); + expect( + parseCodexLine( + counted( + malformed === "request" ? { ...request, cached_input_tokens: -1 } : request, + malformed === "cumulative" + ? { ...counters(200, 40), output_tokens: "40" } + : counters(200, 40), + ), + state, + ), + ).toBeNull(); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + expect( + parseCodexLine( + counted(request, malformed === "request" ? counters(300, 60) : counters(200, 40)), + state, + )?.totals.outputTokens, + ).toBe(20); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(1); + }); + + it("does not bill a context-window estimate or lose the following real request", () => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + parseCodexLine(counted(counters(100, 20), counters(100, 20)), state); + const estimate = { ...counters(0, 0), total_tokens: 1000 }; + expect( + parseCodexLine( + counted({ ...estimate, total_tokens: 880 }, estimate, { model_context_window: 1000 }), + state, + ), + ).toBeNull(); + expect( + parseCodexLine(counted(counters(10, 2), { ...counters(10, 2), total_tokens: 1012 }), state) + ?.totals.outputTokens, + ).toBe(2); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + }); + + it.each([false, true])( + "accepts the post-compaction context marker without a malformed record (prior request: %s)", + (priorRequest) => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + if (priorRequest) parseCodexLine(counted(counters(100, 20), counters(100, 20)), state); + const marker = counted({ ...counters(0, 0), total_tokens: 26387 }, counters(0, 0), { + model_context_window: 475000, + }); + expect(parseCodexLine(marker, state)).toBeNull(); + expect( + parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens, + ).toBe(5); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + }, + ); + + it("bills the first request after a resume restarts the cumulative counters", () => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + parseCodexLine(counted(counters(100, 20), counters(100, 20)), state); + expect( + parseCodexLine(counted(counters(30, 5), counters(30, 5)), state)?.totals.outputTokens, + ).toBe(5); + expect( + parseCodexLine(counted(counters(10, 2), counters(40, 7)), state)?.totals.outputTokens, + ).toBe(2); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); + }); + + it("retains initial tier evidence only for the own OpenAI session and exact context until native settings arrive", () => { + const meta = (id: string, model_provider?: string) => + JSON.stringify({ type: "session_meta", payload: { id, model_provider } }); + const context = (turn_id?: string, model?: string) => + JSON.stringify({ type: "turn_context", payload: { turn_id, model } }); + for (const provider of ["openai", "t3", "custom", undefined]) { + const state = initialCodexScanState(); + parseCodexLine(meta("own-session", provider), state); + parseCodexLine(meta("ancestor", provider === "openai" ? "custom" : "openai"), state); + parseCodexLine(context("first-turn", "gpt-6-astra"), state); + const first = parseCodexLine(tokenCount(100, 0, 1, 0), state); + expect(first).toMatchObject({ + sessionId: "own-session", + model: "gpt-6-astra", + speed: "standard", + }); + if (provider === "openai") { + expect(first).toHaveProperty("unresolvedServiceTierTurnId", "first-turn"); + } else { + expect(first).not.toHaveProperty("unresolvedServiceTierTurnId"); + } + + parseCodexLine(context(undefined, "gpt-6-astra"), state); + expect(parseCodexLine(tokenCount(100, 0, 2, 0), state)).not.toHaveProperty( + "unresolvedServiceTierTurnId", + ); + parseCodexLine(context("missing-model"), state); + expect(parseCodexLine(tokenCount(100, 0, 3, 0), state)).not.toHaveProperty( + "unresolvedServiceTierTurnId", + ); + parseCodexLine(context("next-turn", "gpt-6-astra"), state); + const next = parseCodexLine(tokenCount(100, 0, 4, 0), state); + if (provider === "openai") { + expect(next).toHaveProperty("unresolvedServiceTierTurnId", "next-turn"); + } else { + expect(next).not.toHaveProperty("unresolvedServiceTierTurnId"); + } + } - expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)?.speed).toBe("standard"); - expect(speedAfter(settings({ service_tier: "ultrafast" }), 2)).toBe("ultrafast"); - expect(speedAfter(settings({ service_tier: "priority" }), 3)).toBe("fast"); - expect(speedAfter(settings({ model: "gpt-6-astra" }), 4)).toBe("standard"); + for (const service_tier of ["standard", "", undefined, "priority", "ultrafast"]) { + const state = initialCodexScanState(); + parseCodexLine(meta("own-session", "openai"), state); + parseCodexLine(context("first-turn", "gpt-6-astra"), state); + expect(parseCodexLine(tokenCount(100, 0, 1, 0), state)).toHaveProperty( + "unresolvedServiceTierTurnId", + "first-turn", + ); + parseCodexLine( + JSON.stringify({ + type: "event_msg", + payload: { type: "thread_settings_applied", thread_settings: { service_tier } }, + }), + state, + ); + for (const output of [2, 3]) { + parseCodexLine(context(`native-turn-${output}`, "gpt-6-astra"), state); + const record = parseCodexLine(tokenCount(100, 0, output, 0), state); + expect(record?.speed).toBe( + service_tier === "priority" + ? "fast" + : service_tier === "ultrafast" + ? "ultrafast" + : "standard", + ); + expect(record).not.toHaveProperty("unresolvedServiceTierTurnId"); + } + } }); // A forked/subagent rollout opens with the parent's history copied in and // every line re-stamped to the fork instant, then the ancestors' session - // metas. Counting those again multiplied usage ~1.85x on real data (#5758). + // metas. Counting those again multiplied usage ~1.85x on real data. describe("forked rollouts", () => { const meta = (overrides: { id: string; @@ -121,16 +476,6 @@ describe("parseCodexLine", () => { return JSON.stringify(parsed); }; - it("keeps the child session id over copied ancestor metas", () => { - const state = initialCodexScanState(); - parseCodexLine(meta({ id: "child", timestamp: "2026-08-01T05:00:00.000Z" }), state); - parseCodexLine(meta({ id: "parent", timestamp: "2026-08-01T05:00:00.000Z" }), state); - parseCodexLine(turnContext, state); - const record = parseCodexLine(tokenCount(100, 0, 10, 0), state); - - expect(record?.sessionId).toBe("child"); - }); - it("drops the re-stamped copied burst and keeps the first real event", () => { const state = initialCodexScanState(); const forkInstant = "2026-08-01T05:00:00.000Z"; @@ -139,24 +484,32 @@ describe("parseCodexLine", () => { parseCodexLine(stamped(forkInstant, turnContext), state); expect( - parseCodexLine(stamped("2026-08-01T05:00:00.001Z", tokenCount(100, 0, 10, 0)), state), + parseCodexLine( + stamped("2026-08-01T05:00:00.001Z", counted(counters(100, 10), counters(100, 10))), + state, + ), ).toBeNull(); expect( - parseCodexLine(stamped("2026-08-01T05:00:00.002Z", tokenCount(200, 0, 20, 0)), state), + parseCodexLine( + stamped("2026-08-01T05:00:00.002Z", counted(counters(200, 20), counters(300, 30))), + state, + ), ).toBeNull(); const real = parseCodexLine( - stamped("2026-08-01T05:00:06.000Z", tokenCount(300, 0, 30, 0)), + stamped("2026-08-01T05:00:06.000Z", counted(counters(200, 20), counters(500, 50))), state, ); expect(real).not.toBeNull(); - expect(real?.totals.outputTokens).toBe(30); + expect(real?.sessionId).toBe("child"); + expect(real?.totals.outputTokens).toBe(20); const next = parseCodexLine( - stamped("2026-08-01T05:00:06.100Z", tokenCount(400, 0, 40, 0)), + stamped("2026-08-01T05:00:06.100Z", counted(counters(400, 40), counters(900, 90))), state, ); expect(next).not.toBeNull(); + expect(codexUsageFormat.readMalformedRecords?.(state)).toBe(0); }); it("recognizes subagent spawns without forked_from_id", () => { diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index b737f19a6c884..38615eb2cb0cb 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -5,7 +5,6 @@ import * as Schema from "effect/Schema"; import { parseTimestampMs, - tokenCount, totalTokens, type ProviderUsageReader, type TranscriptUsageFormat, @@ -14,8 +13,54 @@ import { } from "@t3tools/provider-core/server/usage"; import type { UsageTokenTotals } from "@t3tools/contracts"; +import * as CodexUsageHistory from "../../usage/CodexUsageHistory.ts"; import { resolveCodexHomeLayout } from "./CodexHomeLayout.ts"; +const TokenCount = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); +const CodexTokenUsage = Schema.Struct({ + input_tokens: TokenCount, + cached_input_tokens: TokenCount, + cache_write_input_tokens: TokenCount, + output_tokens: TokenCount, + reasoning_output_tokens: TokenCount, + total_tokens: TokenCount, +}).check( + Schema.makeFilter( + (usage) => + usage.cached_input_tokens + usage.cache_write_input_tokens <= usage.input_tokens && + usage.reasoning_output_tokens <= usage.output_tokens && + usage.total_tokens >= usage.input_tokens + usage.output_tokens, + ), +); +type CodexTokenUsage = typeof CodexTokenUsage.Type; +const isCodexTokenUsage = Schema.is(CodexTokenUsage); +const CODEX_USAGE_FIELDS = Object.keys(CodexTokenUsage.fields) as (keyof CodexTokenUsage)[]; + +function readCodexTokenUsage(value: unknown): CodexTokenUsage | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) return null; + const raw = value as Record; + const input = raw["input_tokens"]; + const output = raw["output_tokens"]; + if (typeof input !== "number" || typeof output !== "number") return null; + const usage = { + input_tokens: input, + cached_input_tokens: raw["cached_input_tokens"] === undefined ? 0 : raw["cached_input_tokens"], + cache_write_input_tokens: + raw["cache_write_input_tokens"] === undefined ? 0 : raw["cache_write_input_tokens"], + output_tokens: output, + reasoning_output_tokens: + raw["reasoning_output_tokens"] === undefined ? 0 : raw["reasoning_output_tokens"], + total_tokens: raw["total_tokens"] === undefined ? input + output : raw["total_tokens"], + }; + return isCodexTokenUsage(usage) ? usage : null; +} + +function advanceCodexUsage(previous: CodexTokenUsage | null, last: CodexTokenUsage) { + return readCodexTokenUsage( + Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, (previous?.[key] ?? 0) + last[key]])), + ); +} + /** * Codex `token_count` events carry no model or service tier, so both are carried forward: the model * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`. @@ -25,7 +70,12 @@ export const CodexScanState = Schema.Struct({ speed: Schema.mutableKey(Schema.Literals(["standard", "fast", "ultrafast"])), sessionId: Schema.mutableKey(Schema.String), lastUsageSignature: Schema.mutableKey(Schema.NullOr(Schema.String)), + lastCumulativeUsage: Schema.mutableKey(Schema.NullOr(CodexTokenUsage)), + malformedRecords: Schema.mutableKey(TokenCount), sawSessionMeta: Schema.mutableKey(Schema.Boolean), + modelProvider: Schema.mutableKey(Schema.String), + turnId: Schema.mutableKey(Schema.String), + sawThreadSettings: Schema.mutableKey(Schema.Boolean), suppressingForkCopies: Schema.mutableKey(Schema.Boolean), forkCopyAnchorMs: Schema.mutableKey(Schema.Finite), }); @@ -37,18 +87,18 @@ export function initialCodexScanState(): CodexScanState { speed: "standard", sessionId: "", lastUsageSignature: null, + lastCumulativeUsage: null, + malformedRecords: 0, sawSessionMeta: false, + modelProvider: "", + turnId: "", + sawThreadSettings: false, suppressingForkCopies: false, forkCopyAnchorMs: 0, }; } -/** - * A forked or subagent rollout opens with the parent's full history copied in, - * every line re-stamped to the fork instant. Those copies are written in one - * synchronous burst (observed gaps 0-40ms), while the child's first genuine - * usage event only lands after a real model turn (observed 5s+). - */ +/** Forks copy and restamp parent history in a burst (0-40ms gaps); genuine child usage follows a model turn (5s+ observed). */ const FORK_COPY_MAX_GAP_MS = 1000; function isForkedSessionMeta(payload: Record): boolean { @@ -63,8 +113,8 @@ function isForkedSessionMeta(payload: Record): boolean { } /** - * Deltas come from `last_token_usage`. Summing those across a session reconciles with the session's - * final `total_token_usage`, provided consecutive duplicate events are dropped, which this does. + * Cumulative counters validate request deltas. Older events without cumulative counters use + * normalized consecutive-request deduplication. */ export function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null { let parsed: unknown; @@ -86,13 +136,14 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | const payloadType = payloadRecord["type"]; if (record["type"] === "session_meta") { - // Only the first meta describes this file's own session. A forked rollout - // repeats the ancestors' metas right after it; letting those through would - // reassign every subsequent record to an ancestor session. + // Only the first meta identifies this session; copied ancestor metas would misattribute later records. if (state.sawSessionMeta) return null; state.sawSessionMeta = true; const id = payloadRecord["id"] ?? payloadRecord["session_id"]; if (typeof id === "string") state.sessionId = id; + if (typeof payloadRecord["model_provider"] === "string") { + state.modelProvider = payloadRecord["model_provider"]; + } const metaTimestampMs = parseTimestampMs(record["timestamp"]); if (metaTimestampMs !== null && isForkedSessionMeta(payloadRecord)) { state.suppressingForkCopies = true; @@ -103,10 +154,18 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | if (record["type"] === "turn_context") { if (typeof payloadRecord["model"] === "string") state.model = payloadRecord["model"]; + // Model carry is useful for usage, but history recovery needs this context's own identity. + state.turnId = + typeof payloadRecord["turn_id"] === "string" && + typeof payloadRecord["model"] === "string" && + payloadRecord["model"].length > 0 + ? payloadRecord["turn_id"] + : ""; return null; } if (payloadType === "thread_settings_applied") { + state.sawThreadSettings = true; const settings = payloadRecord["thread_settings"]; if (typeof settings === "object" && settings !== null) { state.speed = codexSpeed((settings as Record)["service_tier"]); @@ -118,45 +177,102 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | const info = payloadRecord["info"]; if (typeof info !== "object" || info === null) return null; - const last = (info as Record)["last_token_usage"]; - if (typeof last !== "object" || last === null) return null; - const lastRecord = last as Record; - - // Only an event that is otherwise eligible may consume the duplicate - // signature. A token_count arriving before its turn_context (no model yet) - // must not poison it, or the re-emitted copy after the model is known would - // be skipped as a duplicate and those tokens never counted. + const infoRecord = info as Record; + + // Codex may re-emit these counters after the model or timestamp becomes available. const timestampMs = parseTimestampMs(record["timestamp"]); - if (timestampMs === null) return null; - if (state.model.length === 0) return null; + if (timestampMs === null || state.model.length === 0) return null; - // Codex re-emits an unchanged token_count on some stream boundaries. Summing - // those would double count, so identical consecutive payloads are skipped. - const signature = JSON.stringify(lastRecord); - if (signature === state.lastUsageSignature) return null; - state.lastUsageSignature = signature; + const last = readCodexTokenUsage(infoRecord["last_token_usage"]); + const rawCumulative = infoRecord["total_token_usage"]; + const hasCumulative = rawCumulative !== undefined && rawCumulative !== null; + const cumulative = hasCumulative ? readCodexTokenUsage(rawCumulative) : null; if (state.suppressingForkCopies) { if (timestampMs - state.forkCopyAnchorMs < FORK_COPY_MAX_GAP_MS) { state.forkCopyAnchorMs = timestampMs; + // Copied history is already billed in the parent, but establishes the child's baseline. + const signature = last === null ? null : JSON.stringify(last); + if (cumulative !== null) state.lastCumulativeUsage = cumulative; + else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) { + state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last); + } + state.lastUsageSignature = signature; return null; } state.suppressingForkCopies = false; + state.lastUsageSignature = null; + } + + const previous = state.lastCumulativeUsage; + // A valid snapshot remains the next baseline even when its paired request is malformed. + if (cumulative !== null) state.lastCumulativeUsage = cumulative; + if (last === null || (hasCumulative && cumulative === null)) { + state.malformedRecords += 1; + return null; + } + + // Zero-component counters report context size, not a request: fill_to_context_window, or the + // post-compaction marker whose total is the new context size (its cumulative may reset to zero). + if (last.input_tokens + last.output_tokens === 0) { + state.lastUsageSignature = null; + return null; + } + + if ( + cumulative !== null && + previous !== null && + CODEX_USAGE_FIELDS.every((key) => cumulative[key] === previous[key]) + ) { + return null; + } + + if (last.total_tokens !== last.input_tokens + last.output_tokens) { + state.malformedRecords += 1; + return null; + } + + const signature = JSON.stringify(last); + if (cumulative !== null) { + // A session resumed in a new Codex process restarts its cumulative counters at this request. + const restarted = CODEX_USAGE_FIELDS.every((key) => cumulative[key] === last[key]); + // Forks and paginated continuations can inherit totals without copying a counter snapshot. + // Only bill the latest request, and require the unseen prefix to be valid usage too. + const reconciled = + previous === null + ? readCodexTokenUsage( + Object.fromEntries(CODEX_USAGE_FIELDS.map((key) => [key, cumulative[key] - last[key]])), + ) !== null + : CODEX_USAGE_FIELDS.every((key) => cumulative[key] - previous[key] === last[key]); + if (!restarted && !reconciled) { + state.malformedRecords += 1; + return null; + } + } else { + if (signature === state.lastUsageSignature) return null; + // Advance expected totals for billed legacy requests so a cumulative re-emission is stale. + const advanced = advanceCodexUsage(previous, last); + if (advanced === null) { + state.malformedRecords += 1; + return null; + } + state.lastCumulativeUsage = advanced; } + state.lastUsageSignature = signature; - const inputTokens = tokenCount(lastRecord["input_tokens"]); - const cachedInputTokens = tokenCount(lastRecord["cached_input_tokens"]); - const cacheCreationTokens = tokenCount(lastRecord["cache_write_input_tokens"]); - const outputTokens = tokenCount(lastRecord["output_tokens"]); + const inputTokens = last.input_tokens; + const cachedInputTokens = last.cached_input_tokens; + const cacheCreationTokens = last.cache_write_input_tokens; + const outputTokens = last.output_tokens; const totals: UsageTokenTotals = { // Codex reports `input_tokens` inclusive of the cached portion. - uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens), + uncachedInputTokens: inputTokens - cachedInputTokens - cacheCreationTokens, cachedInputTokens, cacheCreationTokens, outputTokens, // Reported inside output_tokens, surfaced separately for the token mix. - reasoningTokens: Math.min(outputTokens, tokenCount(lastRecord["reasoning_output_tokens"])), + reasoningTokens: last.reasoning_output_tokens, }; if (totalTokens(totals) === 0) return null; @@ -169,14 +285,17 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): UsageRecord | totals, reportedCostUsd: null, speed: state.speed, + ...(!state.sawThreadSettings && + state.modelProvider === "openai" && + state.sessionId.length > 0 && + state.turnId.length > 0 + ? { unresolvedServiceTierTurnId: state.turnId } + : {}), dedupeKey: null, }; } -/** - * Codex omits the field when no tier was requested, which bills as standard, as - * do `default` and `standard`. `fast` is accepted as an alias of `priority`. - */ +/** Missing, default and standard tiers bill as standard; fast aliases priority. */ function codexSpeed(serviceTier: unknown): UsageSpeed { if (serviceTier === "priority" || serviceTier === "fast") return "fast"; if (serviceTier === "ultrafast") return "ultrafast"; @@ -194,27 +313,59 @@ export const codexUsageFormat: TranscriptUsageFormat = { type: true, id: true, session_id: true, + model_provider: true, + turn_id: true, model: true, thread_settings: { service_tier: true }, forked_from_id: true, source: { subagent: { thread_spawn: { parent_thread_id: true } } }, - info: { last_token_usage: true }, + info: { last_token_usage: true, total_token_usage: true }, }, }, - // `turn_context`, `thread_settings_applied` and `session_meta` lines hold no - // usage, but they carry the model, tier and session the reducer needs. + // Metadata lines carry model, tier and session even without usage. usageMarkers: ['"token_count"', '"turn_context"', '"thread_settings_applied"', '"session_meta"'], parseLine: (line, state) => orEmpty(parseCodexLine(line, state)), parseProjected: (projected, state) => orEmpty(parseCodexRecord(projected, state)), state: { initial: initialCodexScanState, schema: CodexScanState }, + readMalformedRecords: (state) => state.malformedRecords, // A rollout that moved after it was read leaves a copy in both places. sharedSessionsAcrossFiles: true, }; -export const codexUsageReader: ProviderUsageReader = { +export const codexUsageReader: ProviderUsageReader< + CodexSettings, + Path.Path | CodexUsageHistory.CodexUsageHistory +> = { kind: "transcripts", provider: "codex", format: codexUsageFormat, + resolveServiceTiers: Effect.fn("codexUsageReader.resolveServiceTiers")(function* (records) { + const history = yield* CodexUsageHistory.CodexUsageHistory; + const requests = new Map(); + for (const record of records) { + if (record.unresolvedServiceTierTurnId === undefined) continue; + requests.set( + { + sessionId: record.sessionId, + nativeTurnId: record.unresolvedServiceTierTurnId, + model: record.model, + }, + record, + ); + } + const resolved = yield* history.resolve([...requests.keys()]).pipe( + Effect.catchTags({ + CodexUsageHistoryReadError: () => + Effect.succeed(new Map()), + }), + ); + const speeds = new Map(); + for (const [request, speed] of resolved) { + const record = requests.get(request); + if (record !== undefined) speeds.set(record, speed); + } + return speeds; + }), directories: Effect.fn("codexUsageReader.directories")(function* ({ config, environment }) { if (config === undefined) return []; const path = yield* Path.Path; diff --git a/apps/server/src/provider/EventNdjsonLogger.test.ts b/apps/server/src/provider/EventNdjsonLogger.test.ts index e1af016095ee3..c932ac2fa5e5a 100644 --- a/apps/server/src/provider/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/EventNdjsonLogger.test.ts @@ -7,7 +7,6 @@ import { ThreadId } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { RotatingFileSinkError } from "@t3tools/shared/logging"; -import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as FileSystem from "effect/FileSystem"; @@ -16,7 +15,6 @@ import * as Logger from "effect/Logger"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; -import * as ResourceAttribution from "../resourceTelemetry/ResourceAttribution.ts"; import { makeEventNdjsonLogger, makeEventNdjsonLogStore, @@ -90,52 +88,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }).pipe(Effect.provide(Logger.layer([logCapture], { mergeWithExisting: false }))); }); - it.effect("writes effect-style lines to thread-scoped files", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "provider-native.ndjson"); - - try { - const logger = yield* makeEventNdjsonLogger(basePath, { stream: "native" }); - assert.notEqual(logger, undefined); - if (!logger) { - return; - } - - yield* logger.write( - { threadId: "provider-thread-1", id: "evt-1" }, - ThreadId.make("thread-1"), - ); - yield* logger.write( - { type: "turn.completed", threadId: "provider-thread-2", id: "evt-2" }, - ThreadId.make("thread-2"), - ); - yield* logger.close(); - - const threadOnePath = ownedLogPath(basePath, "thread-1"); - const threadTwoPath = ownedLogPath(basePath, "thread-2"); - assert.equal(NodeFS.existsSync(threadOnePath), true); - assert.equal(NodeFS.existsSync(threadTwoPath), true); - - const first = parseLogLine(NodeFS.readFileSync(threadOnePath, "utf8").trim()); - const second = parseLogLine(NodeFS.readFileSync(threadTwoPath, "utf8").trim()); - - assert.equal(Number.isNaN(Date.parse(first.observedAt)), false); - assert.equal(first.stream, "NTIVE"); - assert.equal(first.payload, '{"threadId":"provider-thread-1","id":"evt-1"}'); - - assert.equal(Number.isNaN(Date.parse(second.observedAt)), false); - assert.equal(second.stream, "NTIVE"); - assert.equal( - second.payload, - '{"type":"turn.completed","threadId":"provider-thread-2","id":"evt-2"}', - ); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - it.effect( "falls back to a global segment when orchestration thread id is missing or invalid", () => @@ -246,28 +198,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }), ); - it.effect("flushes an active batch without a permanent polling loop", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - const threadPath = ownedLogPath(basePath, "thread-batched"); - - try { - const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 1_000 }); - yield* store - .logger("native") - .write({ id: "batched-event" }, ThreadId.make("thread-batched")); - - assert.equal(NodeFS.existsSync(threadPath), false); - yield* TestClock.adjust(1_000); - yield* store.close(); - assert.equal(NodeFS.existsSync(threadPath), true); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - it.effect("does not strand a later batch after an interrupted write", () => Effect.gen(function* () { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); @@ -295,200 +225,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }), ); - it.effect("drops transient provider events before serialization", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - - try { - const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); - const canonical = store.logger("canonical"); - const native = store.logger("native"); - const threadId = ThreadId.make("thread-filtered"); - const circularDelta: Record = { type: "content.delta" }; - circularDelta["self"] = circularDelta; - - yield* canonical.write(circularDelta, threadId); - yield* canonical.write({ type: "item.completed", id: "final" }, threadId); - yield* native.write({ type: "content.delta", id: "native-delta" }, threadId); - yield* native.write( - { method: "item/agentMessage/delta", payload: circularDelta }, - threadId, - ); - yield* native.write( - { method: "thread/realtime/outputAudio/delta", payload: circularDelta }, - threadId, - ); - yield* native.write( - { method: "thread/realtime/transcript/delta", payload: circularDelta }, - threadId, - ); - yield* native.write({ method: "turn/diff/updated", payload: circularDelta }, threadId); - yield* native.write( - { - event: { - direction: "incoming", - stage: "decoded", - payload: { - method: "turn/diff/updated", - get params() { - throw new Error("unused diff snapshots must not be traversed"); - }, - }, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - method: "claude/stream_event/content_block_delta/text_delta", - payload: circularDelta, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - method: "session/update", - payload: { update: { sessionUpdate: "agent_message_chunk" } }, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - direction: "incoming", - stage: "decoded", - payload: { method: "item/commandExecution/outputDelta", params: circularDelta }, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - direction: "incoming", - stage: "decoded", - payload: { - type: "stream_event", - event: { type: "content_block_delta", delta: circularDelta }, - }, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - direction: "incoming", - stage: "raw", - get payload() { - throw new Error("raw frames must not be inspected"); - }, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - type: "message.part.updated", - payload: { properties: { part: { type: "text" } } }, - }, - }, - threadId, - ); - yield* native.write( - { - event: { - type: "message.part.updated", - payload: { - properties: { - part: { type: "tool", state: { status: "running", output: "progress" } }, - }, - }, - }, - }, - threadId, - ); - yield* native.write({ type: "turn.completed", id: "native-final" }, threadId); - yield* store.close(); - - const lines = NodeFS.readFileSync(ownedLogPath(basePath, "thread-filtered"), "utf8") - .trim() - .split("\n") - .map(parseLogLine); - - assert.deepEqual( - lines.map(({ stream, payload }) => ({ stream, payload })), - [ - { stream: "CANON", payload: '{"type":"item.completed","id":"final"}' }, - { stream: "NTIVE", payload: '{"type":"turn.completed","id":"native-final"}' }, - ], - ); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - - it.effect( - "drops Claude thinking-token counters while keeping system and terminal usage records", - () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - const threadId = ThreadId.make("claude-thinking-tokens"); - const counter = { - direction: "incoming", - stage: "decoded", - payload: { - type: "system", - subtype: "thinking_tokens", - estimated_tokens: 50, - estimated_tokens_delta: 50, - }, - }; - const retained = [ - { type: "system", subtype: "init", session_id: "claude-session" }, - { - type: "stream_event", - event: { type: "message_delta", usage: { output_tokens: 10 } }, - }, - { - type: "result", - subtype: "success", - usage: { output_tokens: 10, output_tokens_details: { thinking_tokens: 5 } }, - }, - ].map((payload) => ({ event: { direction: "incoming", stage: "decoded", payload } })); - - try { - const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); - const native = store.logger("native"); - yield* native.write(counter, threadId); - yield* native.write({ provider: "claudeAgent", event: counter }, threadId); - for (const event of retained) { - yield* native.write(event, threadId); - } - yield* store.close(); - - const records = NodeFS.readFileSync( - ownedLogPath(basePath, "claude-thinking-tokens"), - "utf8", - ) - .trim() - .split("\n") - .map((line) => decodeUnknownJson(parseLogLine(line).payload)); - assert.deepEqual(records, retained); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - it.effect("summarizes large histories without reading their items", () => Effect.gen(function* () { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); @@ -602,84 +338,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }), ); - it.effect("keeps OpenCode tool input, final output, and errors in native logs", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - const threadId = ThreadId.make("thread-tool-lifecycle"); - - try { - const store = yield* makeEventNdjsonLogStore(basePath, { batchWindowMs: 0 }); - const native = store.logger("native"); - const input = { command: "run-build" }; - const states = [ - { status: "pending", input }, - { status: "completed", input, output: "Build complete", time: { start: 1, end: 2 } }, - { status: "error", input, error: "Build failed", time: { start: 3, end: 4 } }, - { status: "unknown", input }, - null, - ]; - const events = states.map((state) => ({ - event: { - type: "message.part.updated", - payload: { properties: { part: { type: "tool", state } } }, - }, - })); - for (const event of events) { - yield* native.write(event, threadId); - } - yield* store.close(); - - const payloads = NodeFS.readFileSync( - ownedLogPath(basePath, "thread-tool-lifecycle"), - "utf8", - ) - .trim() - .split("\n") - .map((line) => parseLogLine(line).payload); - assert.deepEqual( - payloads, - events.map((event) => encodeUnknownJson(event)), - ); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - - it.effect("contains hostile event accessors inside guarded serialization", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - - try { - const logger = yield* makeEventNdjsonLogger(basePath, { - stream: "canonical", - batchWindowMs: 0, - }); - assert.exists(logger); - if (!logger) return; - const hostile = new Proxy( - { id: "hostile" }, - { - get(_target, property) { - if (property === "type") throw new Error("blocked"); - return undefined; - }, - }, - ); - - yield* logger.write(hostile, ThreadId.make("thread-hostile")); - yield* logger.close(); - - const contents = NodeFS.readFileSync(ownedLogPath(basePath, "thread-hostile"), "utf8"); - assert.notInclude(contents, "blocked"); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - it.effect("serializes concurrent first writes for the same segment", () => Effect.gen(function* () { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); @@ -773,79 +431,6 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { }), ); - it.effect("enforces aggregate age and byte retention on startup", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - const expiredPath = ownedLogPath(basePath, "expired"); - const oldPath = ownedLogPath(basePath, "old"); - const newPath = ownedLogPath(basePath, "new"); - const unrelatedLogPath = NodePath.join(tempDir, "unrelated.log"); - const legacyLogPath = NodePath.join(tempDir, "legacy-thread.log"); - const ignoredPath = NodePath.join(tempDir, "ignored.txt"); - - try { - yield* TestClock.setTime(1_800_000_000_000); - const now = yield* Clock.currentTimeMillis; - for (const filePath of [expiredPath, oldPath, newPath, unrelatedLogPath, ignoredPath]) { - NodeFS.writeFileSync(filePath, "x".repeat(40)); - } - NodeFS.writeFileSync( - legacyLogPath, - "[2026-01-01T00:00:00.000Z] CANON: legacy provider event\n", - ); - NodeFS.utimesSync(expiredPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000); - NodeFS.utimesSync(legacyLogPath, (now - 20_000) / 1_000, (now - 20_000) / 1_000); - NodeFS.utimesSync(oldPath, (now - 5_000) / 1_000, (now - 5_000) / 1_000); - NodeFS.utimesSync(newPath, now / 1_000, now / 1_000); - - const store = yield* makeEventNdjsonLogStore(basePath, { - maxAgeMs: 10_000, - maxTotalBytes: 60, - }); - yield* store.close(); - - assert.equal(NodeFS.existsSync(expiredPath), false); - assert.equal(NodeFS.existsSync(legacyLogPath), false); - assert.equal(NodeFS.existsSync(oldPath), false); - assert.equal(NodeFS.existsSync(newPath), true); - assert.equal(NodeFS.existsSync(unrelatedLogPath), true); - assert.equal(NodeFS.existsSync(ignoredPath), true); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - - it.effect("does not prune an active thread sink during an unrelated flush", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "events.log"); - const activePath = ownedLogPath(basePath, "active"); - - try { - yield* TestClock.setTime(1_800_000_000_000); - const store = yield* makeEventNdjsonLogStore(basePath, { - batchWindowMs: 0, - maxAgeMs: 1, - retentionCheckIntervalMs: 1, - }); - const logger = store.logger("native"); - - yield* logger.write({ id: "active-before-retention" }, ThreadId.make("active")); - assert.equal(NodeFS.existsSync(activePath), true); - - yield* TestClock.adjust("2 millis"); - yield* logger.write({ id: "retention-trigger" }, ThreadId.make("other")); - - assert.equal(NodeFS.existsSync(activePath), true); - yield* store.close(); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); - it.effect("attributes batches that were written before a later chunk fails", () => Effect.gen(function* () { const records: ReadonlyArray = [ @@ -939,36 +524,4 @@ it.layer(NodeServices.layer)("EventNdjsonLogger", (it) => { } }), ); - - it.effect("reports logical provider log writes to resource attribution", () => - Effect.gen(function* () { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-provider-log-")); - const basePath = NodePath.join(tempDir, "provider-native.ndjson"); - - try { - const attribution = yield* ResourceAttribution.make(); - const logger = yield* makeEventNdjsonLogger(basePath, { - stream: "native", - batchWindowMs: 0, - attribution, - }); - assert.notEqual(logger, undefined); - if (!logger) { - return; - } - - yield* logger.write({ id: "attributed-event" }, ThreadId.make("thread-attribution")); - yield* logger.close(); - - const snapshot = yield* attribution.snapshot; - assert.equal(snapshot.entries.length, 1); - assert.equal(snapshot.entries[0]?.component, "provider-event-log"); - assert.equal(snapshot.entries[0]?.operation, "native.append"); - assert.equal(snapshot.entries[0]?.count, 1); - assert.isAbove(snapshot.entries[0]?.logicalWriteBytes ?? 0, 0); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }), - ); }); diff --git a/apps/server/src/provider/EventNdjsonLogger.ts b/apps/server/src/provider/EventNdjsonLogger.ts index 6af7290b5f62d..93061b35913e3 100644 --- a/apps/server/src/provider/EventNdjsonLogger.ts +++ b/apps/server/src/provider/EventNdjsonLogger.ts @@ -1,8 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -/** - * Native and canonical views share batching, rotation, and retention state so - * they cannot race while appending to the same thread-scoped file. - */ +/** Native and canonical views share write state to avoid races on the same thread file. */ import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; @@ -203,8 +200,7 @@ export function shouldPersistProviderEvent(stream: EventNdjsonStream, event: unk const nested = Reflect.get(event, "event"); const envelope = typeof nested === "object" && nested !== null ? nested : event; - // Decoded frames carry the same information as raw frames without another - // copy of every token delta. + // Decoded frames preserve raw-frame information without duplicating every token delta. if (Reflect.get(envelope, "stage") === "raw") return false; const decodedPayload = Reflect.get(envelope, "payload"); const nativeEvent = diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index 6f532f00bbb54..a6945eb902a64 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -12,8 +12,6 @@ import { GrokSettings } from "@t3tools/provider-grok/settings"; import { buildGrokModelCapabilities, - buildGrokModelsFromSessionModelState, - buildInitialGrokProviderSnapshot, checkGrokProviderStatus, grokSlashCommandsFromInitialize, parseGrokModelsCliOutput, @@ -53,10 +51,6 @@ describe("parseGrokModelsCliOutput", () => { it("detects a logged-out CLI even though it exits 0", () => { expect(parseGrokModelsCliOutput(LOGGED_OUT_MODELS_OUTPUT).authenticated).toBe(false); }); - - it("returns unknown auth for unrecognized output", () => { - expect(parseGrokModelsCliOutput("grok 9.9.9\n").authenticated).toBeNull(); - }); }); describe("grokSlashCommandsFromInitialize", () => { @@ -110,101 +104,9 @@ describe("grokSlashCommandsFromInitialize", () => { expect(commands.map((command) => command.name)).toEqual(["compact", "session-info"]); expect(commands[1]?.description).toBe("Updated session details"); }); - - it("keeps compact available for older agents without command metadata", () => { - for (const _meta of [undefined, {}, { availableCommands: "invalid" }]) { - expect( - grokSlashCommandsFromInitialize({ protocolVersion: 1, ...(_meta ? { _meta } : {}) }).map( - (command) => command.name, - ), - ).toEqual(["compact"]); - } - }); -}); - -describe("buildGrokModelsFromSessionModelState", () => { - it("marks the agent's current model as default and keeps reasoning options", () => { - const models = buildGrokModelsFromSessionModelState({ - currentModelId: "grok-4.6", - availableModels: [ - { - modelId: "grok-4.6", - name: "Grok 4.6", - _meta: { - supportsReasoningEffort: true, - reasoningEffort: "high", - reasoningEfforts: [{ value: "high", label: "High", default: true }], - }, - }, - { modelId: "grok-4.5", name: "Grok 4.5" }, - ], - }); - expect(models.map((model) => [model.slug, model.isDefault ?? false])).toEqual([ - ["grok-4.6", true], - ["grok-4.5", false], - ]); - expect(models[0]?.capabilities?.optionDescriptors).toHaveLength(1); - }); }); describe("buildGrokModelCapabilities", () => { - it("preserves ACP-provided reasoning labels and the active default", () => { - const capabilities = buildGrokModelCapabilities({ - modelId: "grok-4.6", - name: "Grok 4.6", - _meta: { - supportsReasoningEffort: true, - reasoningEffort: "xhigh", - reasoningEfforts: [ - { value: "xhigh", label: "Extra High Effort", default: true }, - { value: "high", label: "High Effort", default: true }, - { value: "medium", label: "Medium Effort" }, - { value: "low", label: "Low Effort" }, - ], - }, - }); - - expect(capabilities.optionDescriptors).toEqual([ - { - id: "reasoningEffort", - label: "Reasoning", - type: "select", - currentValue: "xhigh", - options: [ - { id: "xhigh", label: "Extra High Effort", isDefault: true }, - { id: "high", label: "High Effort" }, - { id: "medium", label: "Medium Effort" }, - { id: "low", label: "Low Effort" }, - ], - }, - ]); - }); - - it("uses raw ACP values when option labels are omitted", () => { - const capabilities = buildGrokModelCapabilities({ - modelId: "grok-4.6", - name: "Grok 4.6", - _meta: { - supportsReasoningEffort: true, - reasoningEffort: "xhigh", - reasoningEfforts: [{ value: "xhigh" }, { value: "medium" }], - }, - }); - - expect(capabilities.optionDescriptors).toEqual([ - { - id: "reasoningEffort", - label: "Reasoning", - type: "select", - currentValue: "xhigh", - options: [ - { id: "xhigh", label: "xhigh" }, - { id: "medium", label: "medium" }, - ], - }, - ]); - }); - it("keeps ACP current effort separate from its collapsed advertised default", () => { const capabilities = buildGrokModelCapabilities({ modelId: "grok-4.6", @@ -273,19 +175,6 @@ describe("buildGrokModelCapabilities", () => { ]); }); - it("accepts an advertised ACP menu when the support flag is omitted", () => { - const capabilities = buildGrokModelCapabilities({ - modelId: "grok-4.6", - name: "Grok 4.6", - _meta: { - reasoningEffort: "high", - reasoningEfforts: [{ value: "high", label: "High Effort", default: true }], - }, - }); - - expect(capabilities.optionDescriptors).toHaveLength(1); - }); - it("honors an explicit ACP opt-out even when a menu is present", () => { const capabilities = buildGrokModelCapabilities({ modelId: "grok-4.6", @@ -298,77 +187,9 @@ describe("buildGrokModelCapabilities", () => { expect(capabilities.optionDescriptors).toEqual([]); }); - - it("does not synthesize a reasoning menu when ACP omits it", () => { - expect( - buildGrokModelCapabilities({ - modelId: "grok-4.6", - name: "Grok 4.6", - _meta: { supportsReasoningEffort: true, reasoningEffort: "xhigh" }, - }).optionDescriptors, - ).toEqual([]); - }); - - it("keeps non-reasoning Grok models free of reasoning controls", () => { - expect( - buildGrokModelCapabilities({ modelId: "grok-build", name: "Grok Build" }).optionDescriptors, - ).toEqual([]); - }); -}); - -describe("buildInitialGrokProviderSnapshot", () => { - it.effect("returns a disabled snapshot when settings.enabled is false", () => - Effect.gen(function* () { - const snapshot = yield* buildInitialGrokProviderSnapshot( - decodeGrokSettings({ enabled: false }), - ); - expect(snapshot.enabled).toBe(false); - expect(snapshot.status).toBe("disabled"); - expect(snapshot.installed).toBe(false); - expect(snapshot.message).toContain("disabled"); - }), - ); - - it.effect("returns a disabled snapshot by default — Grok is opt-in", () => - Effect.gen(function* () { - const snapshot = yield* buildInitialGrokProviderSnapshot(decodeGrokSettings({})); - expect(snapshot.enabled).toBe(false); - expect(snapshot.status).toBe("disabled"); - }), - ); - - it.effect("returns a pending snapshot when enabled", () => - Effect.gen(function* () { - const snapshot = yield* buildInitialGrokProviderSnapshot( - decodeGrokSettings({ enabled: true }), - ); - expect(snapshot.enabled).toBe(true); - expect(snapshot.installed).toBe(true); - expect(snapshot.status).toBe("warning"); - expect(snapshot.version).toBeNull(); - expect(snapshot.message).toContain("Checking Grok"); - expect(snapshot.requiresNewThreadForModelChange).toBeUndefined(); - expect(snapshot.supportsConversationRollback).toBe(false); - }), - ); }); it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => { - it.effect("reports the binary as missing when the binary path does not resolve", () => - Effect.gen(function* () { - const snapshot = yield* checkGrokProviderStatus( - decodeGrokSettings({ - enabled: true, - binaryPath: "/definitely/not/installed/grok-binary", - }), - ); - expect(snapshot.enabled).toBe(true); - expect(snapshot.installed).toBe(false); - expect(snapshot.status).toBe("error"); - expect(snapshot.message).toMatch(/not installed|not on PATH|Failed to execute/); - }), - ); - it.effect("reports an installed CLI as unhealthy when --version exits non-zero", () => Effect.gen(function* () { const secretStderr = "broken grok install: secret-token-value"; @@ -402,8 +223,9 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => { // A stand-in for the Grok CLI: `--version` and `models` print canned text, // and `agent stdio` execs the mock ACP agent so `initialize` returns model metadata. + // A list of `models` outputs is served in call order, repeating the last one. const writeFakeGrokCli = (input: { - readonly modelsOutput: string; + readonly modelsOutput: string | ReadonlyArray; readonly acp: boolean; readonly updateLogPath?: string; }) => @@ -428,7 +250,12 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => { " process.exit(0);", "}", 'if (process.argv[2] === "models") {', - ` process.stdout.write(${JSON.stringify(input.modelsOutput)});`, + ' const fs = await import("node:fs");', + ` const callsPath = ${JSON.stringify(NodePath.join(dir, "models-calls"))};`, + ' const calls = fs.existsSync(callsPath) ? fs.readFileSync(callsPath, "utf8").length : 0;', + ' fs.appendFileSync(callsPath, ".");', + ` const outputs = ${JSON.stringify([input.modelsOutput].flat())};`, + " process.stdout.write(outputs[Math.min(calls, outputs.length - 1)]);", " process.exit(0);", "}", 'if (process.argv[2] !== "agent") process.exit(1);', @@ -476,12 +303,14 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => { }), ); - it.effect("reports unauthenticated from `grok models` without starting a session", () => + // An expired access token prints the logged-out banner, then the CLI refreshes it in the + // same run, so the next `grok models` reports the login. + it.effect("reports authenticated when `grok models` logs in after refreshing a token", () => Effect.gen(function* () { const snapshot = yield* Effect.scoped( Effect.gen(function* () { const grokPath = yield* writeFakeGrokCli({ - modelsOutput: LOGGED_OUT_MODELS_OUTPUT, + modelsOutput: [LOGGED_OUT_MODELS_OUTPUT, LOGGED_IN_MODELS_OUTPUT], acp: true, }); return yield* checkGrokProviderStatus( @@ -491,10 +320,8 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => { }), ); - expect(snapshot.status).toBe("error"); - expect(snapshot.auth.status).toBe("unauthenticated"); - expect(snapshot.message).toContain("grok login"); - expect(snapshot.models.map((model) => model.slug)).toEqual(["grok-4.6", "grok-mock-alt"]); + expect(snapshot.status).toBe("ready"); + expect(snapshot.auth.status).toBe("authenticated"); }), ); @@ -552,29 +379,63 @@ it.layer(NodeServices.layer)("checkGrokProviderStatus", (it) => { describe("Grok usage limits", () => { const checkedAt = "2026-09-16T00:00:00.000Z"; - - it("uses the reported subscription percentage and weekly reset", () => { - const limits = grokUsageResponseToLimits( - { - config: { - creditUsagePercent: 100, - currentPeriod: { - type: "USAGE_PERIOD_TYPE_WEEKLY", - end: "2026-09-18T03:10:30.159171+00:00", - }, + const weeklyPeriod = { + type: "USAGE_PERIOD_TYPE_WEEKLY", + start: "2026-09-11T03:10:30.159171+00:00", + end: "2026-09-18T03:10:30.159171+00:00", + }; + + it("shows zero usage for complete weekly and monthly periods with no percentage", () => { + for (const [currentPeriod, kind, label, resetsAt] of [ + [weeklyPeriod, "weekly", "Weekly", "2026-09-18T03:10:30.159Z"], + [ + { + type: "USAGE_PERIOD_TYPE_MONTHLY", + start: "2026-09-01T00:00:00.000Z", + end: "2026-10-01T00:00:00.000Z", }, - }, - checkedAt, - ); - expect(limits.windows).toEqual([ - { - id: "subscription", - kind: "weekly", - label: "Weekly", - usedPercent: 100, - resetsAt: "2026-09-18T03:10:30.159Z", - }, - ]); + "monthly", + "Monthly", + "2026-10-01T00:00:00.000Z", + ], + ] as const) { + const response = { config: { currentPeriod } }; + expect + .soft(grokUsageResponseToLimits(response, checkedAt).windows) + .toEqual([{ id: "subscription", kind, label, usedPercent: 0, resetsAt }]); + } + }); + + it("keeps incomplete, invalid, unordered, and unknown periods unreported", () => { + for (const currentPeriod of [ + undefined, + { ...weeklyPeriod, type: undefined }, + { ...weeklyPeriod, type: "USAGE_PERIOD_TYPE_DAILY" }, + { ...weeklyPeriod, start: undefined }, + { ...weeklyPeriod, end: undefined }, + { ...weeklyPeriod, start: "invalid" }, + { ...weeklyPeriod, end: "invalid" }, + { ...weeklyPeriod, start: weeklyPeriod.end }, + { ...weeklyPeriod, start: weeklyPeriod.end, end: weeklyPeriod.start }, + ]) { + const response = { config: { currentPeriod } }; + expect + .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response)) + .toEqual([]); + } + }); + + // regression: #17061 show zero-use Grok billing periods + it("rejects impossible calendar dates at either period boundary", () => { + for (const [start, end] of [ + ["2026-02-30T00:00:00.000Z", "2026-03-09T00:00:00.000Z"], + ["2026-02-23T00:00:00.000Z", "2026-02-30T00:00:00.000Z"], + ]) { + const response = { config: { currentPeriod: { ...weeklyPeriod, start, end } } }; + expect + .soft(grokUsageResponseToLimits(response, checkedAt).windows, JSON.stringify(response)) + .toEqual([]); + } }); it("does not invent allowance or reset dates when billing omits them", () => { @@ -742,38 +603,6 @@ it.layer(NodeServices.layer)("readGrokAccount", (it) => { }).pipe(Effect.scoped), ); - it.effect( - "does not request subscription limits for custom account or endpoint configuration", - () => - Effect.gen(function* () { - for (const config of [ - '[auth]\nprovider_command = "custom-auth"', - '[grok_com_config]\nissuer = "https://custom.example"', - 'endpoints.proxy = "https://custom.example"', - ]) { - const { usageLimits: limits } = yield* readGrokAccount({ - GROK_AUTH: '{"https://accounts.x.ai/sign-in":{"key":"stored-token"}}', - }).pipe( - Effect.provideService( - FileSystem.FileSystem, - FileSystem.makeNoop({ - readFileString: (path) => { - expect(path.endsWith("config.toml")).toBe(true); - return Effect.succeed(config); - }, - }), - ), - Effect.provideService( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die("must not request another account's quota")), - ), - ); - expect(limits.windows).toEqual([]); - expect(limits.unavailable?.reason).toBe("unsupported"); - } - }), - ); - it.effect("sanitizes HTTP failures and malformed billing responses, keeping the account", () => Effect.gen(function* () { for (const response of [ diff --git a/apps/server/src/provider/ModelManifest.test.ts b/apps/server/src/provider/ModelManifest.test.ts index 635e5aa789113..560b702db3aa9 100644 --- a/apps/server/src/provider/ModelManifest.test.ts +++ b/apps/server/src/provider/ModelManifest.test.ts @@ -13,59 +13,6 @@ import * as ServerSettings from "../serverSettings.ts"; import * as ModelManifest from "./ModelManifest.ts"; describe("resolveProviderCatalog", () => { - it("resolves generic model presentation through a reusable profile", () => { - const manifest: ModelManifest.ModelManifestData = { - version: 1, - currentModels: {}, - providers: { - synthetic: { - defaults: { chat: "model-next" }, - profiles: { - standard: { - capabilities: { - optionDescriptors: [ - { - id: "mode", - label: "Mode", - type: "select", - options: [{ id: "fast", label: "Fast", isDefault: true }], - }, - ], - }, - adapter: { opaque: true }, - }, - }, - models: [ - { - slug: "model-next", - name: "Model Next", - aliases: ["next"], - status: "current", - badge: "new", - profile: "standard", - }, - ], - }, - }, - }; - - const catalog = ModelManifest.resolveProviderCatalog( - manifest, - ProviderDriverKind.make("synthetic"), - ); - assert.deepStrictEqual(catalog?.models[0], { - slug: "model-next", - name: "Model Next", - aliases: ["next"], - badge: "new", - status: "current", - capabilities: manifest.providers!.synthetic!.profiles.standard!.capabilities!, - adapter: undefined, - profileAdapter: { opaque: true }, - }); - assert.strictEqual(catalog?.defaultChatModel, "model-next"); - }); - it("rejects invalid catalog references", () => { const invalidCatalog = (input: { readonly models: NonNullable[string]["models"]; @@ -236,84 +183,6 @@ const layerService = (input: { ); describe("ModelManifest service", () => { - it.live("explicit refresh bypasses fresh memory and disk caches", () => { - let fetchCount = 0; - const updated: ModelManifest.ModelManifestData = { - ...REMOTE_MANIFEST, - currentModels: { codex: ["gpt-reloaded"] }, - }; - return Effect.gen(function* () { - const service = yield* ModelManifest.make; - assert.deepStrictEqual(yield* service.refresh, REMOTE_MANIFEST); - assert.deepStrictEqual(yield* service.refresh, REMOTE_MANIFEST); - assert.strictEqual(fetchCount, 1); - - const rebooted = yield* ModelManifest.make; - assert.deepStrictEqual(yield* rebooted.refresh, REMOTE_MANIFEST); - assert.strictEqual(fetchCount, 1); - assert.deepStrictEqual(yield* rebooted.forceRefresh, updated); - assert.strictEqual(fetchCount, 2); - assert.deepStrictEqual(yield* rebooted.current, updated); - assert.deepStrictEqual(yield* (yield* ModelManifest.make).current, updated); - }).pipe( - Effect.scoped, - Effect.provide( - layerService({ - prefix: "model-manifest-force-refresh-test", - response: () => Response.json(fetchCount++ === 0 ? REMOTE_MANIFEST : updated), - }), - ), - ); - }); - - it.live("explicit refresh retries immediately after failure and preserves last-good data", () => { - let fetchCount = 0; - return Effect.gen(function* () { - const service = yield* ModelManifest.make; - assert.deepStrictEqual(yield* service.refresh, REMOTE_MANIFEST); - assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); - assert.deepStrictEqual(yield* service.current, REMOTE_MANIFEST); - assert.deepStrictEqual(yield* (yield* ModelManifest.make).current, REMOTE_MANIFEST); - assert.strictEqual(fetchCount, 2); - assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); - assert.strictEqual(fetchCount, 3); - }).pipe( - Effect.scoped, - Effect.provide( - layerService({ - prefix: "model-manifest-force-retry-test", - response: () => - fetchCount++ === 1 - ? new Response(null, { status: 503 }) - : Response.json(REMOTE_MANIFEST), - }), - ), - ); - }); - - it.live("explicit refresh bypasses the retry delay after an initial failure", () => { - let fetchCount = 0; - return Effect.gen(function* () { - const service = yield* ModelManifest.make; - assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST); - assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST); - assert.strictEqual(fetchCount, 1); - assert.deepStrictEqual(yield* service.forceRefresh, REMOTE_MANIFEST); - assert.strictEqual(fetchCount, 2); - }).pipe( - Effect.scoped, - Effect.provide( - layerService({ - prefix: "model-manifest-force-initial-retry-test", - response: () => - fetchCount++ === 0 - ? new Response(null, { status: 503 }) - : Response.json(REMOTE_MANIFEST), - }), - ), - ); - }); - it.live("prefers a fetched manifest over the bundle and caches it to disk", () => Effect.gen(function* () { const service = yield* ModelManifest.make; @@ -357,21 +226,6 @@ describe("ModelManifest service", () => { ); }); - it.live("keeps the bundled manifest when the remote payload is malformed", () => - Effect.gen(function* () { - const service = yield* ModelManifest.make; - assert.deepStrictEqual(yield* service.refresh, ModelManifest.BUNDLED_MODEL_MANIFEST); - }).pipe( - Effect.scoped, - Effect.provide( - layerService({ - prefix: "model-manifest-malformed-test", - response: () => Response.json({ version: 999, nonsense: true }), - }), - ), - ), - ); - it.effect("preserves the last-good remote cache when later payloads are invalid", () => { let responseIndex = 0; const responses = [REMOTE_CLAUDE_MANIFEST, ...INVALID_REMOTE_MANIFESTS]; @@ -461,43 +315,3 @@ describe("ModelManifest service", () => { ), ); }); - -it.effect("caches valid compatibility policies and keeps them after a malformed refresh", () => { - const remote: ModelManifest.ModelManifestData = { - ...REMOTE_MANIFEST, - compatibility: [ - { - driver: "codex", - t3CodeRange: ">=0.0.42", - recommendedVersion: "2.0.0", - ranges: [{ range: "=2.0.0", status: "supported" }], - }, - ], - }; - let invalid = false; - return Effect.gen(function* () { - const service = yield* ModelManifest.make; - assert.deepStrictEqual((yield* service.refresh).compatibility, remote.compatibility); - invalid = true; - yield* TestClock.adjust("1 hour"); - assert.deepStrictEqual((yield* service.refresh).compatibility, remote.compatibility); - const rebooted = yield* ModelManifest.make; - assert.deepStrictEqual((yield* rebooted.current).compatibility, remote.compatibility); - }).pipe( - Effect.scoped, - Effect.provide( - layerService({ - prefix: "model-manifest-compatibility-test", - response: () => - Response.json( - invalid - ? { - ...remote, - compatibility: [{ ...remote.compatibility![0], recommendedVersion: "3.0.0" }], - } - : remote, - ), - }), - ), - ); -}); diff --git a/apps/server/src/provider/ModelManifest.ts b/apps/server/src/provider/ModelManifest.ts index 27cd700e1a20b..3cebfb22c7919 100644 --- a/apps/server/src/provider/ModelManifest.ts +++ b/apps/server/src/provider/ModelManifest.ts @@ -26,8 +26,7 @@ const MODEL_MANIFEST_URL = const MANIFEST_TTL_MS = 60 * 60 * 1000; -/** Minimum gap between fetch attempts after a failure, so an offline server - * does not pay a network timeout on every provider check. */ +/** Back off failed fetches so offline health checks do not each wait on the network. */ const MANIFEST_RETRY_MS = 5 * 60 * 1000; const FETCH_TIMEOUT_MS = 10_000; @@ -63,11 +62,7 @@ const ManifestProviderCatalog = Schema.Struct({ const ModelManifestEnvelopeSchema = Schema.Struct({ version: Schema.Literal(1), - /** - * A release bundles its manifest, and a disk cache of an older edit must not - * outrank it. Optional so older remote files still decode; they count as - * older than any dated bundle. - */ + /** Older disk caches must not override bundled manifests; absent dates rank below any dated bundle. */ updatedAt: Schema.optional(Schema.String), compatibility: Schema.optional(Schema.Array(ProviderCompatibilityPolicy)), currentModels: Schema.Record(Schema.String, Schema.Array(Schema.String)), @@ -169,9 +164,7 @@ export class ModelManifest extends Context.Service< readonly current: Effect.Effect; readonly refresh: Effect.Effect; readonly forceRefresh: Effect.Effect; - /** Drivers call this from - * provider checks: the fetch is process-shared state, so it must survive - * the teardown of whichever instance happened to trigger it. */ + /** Process-shared fetches must survive the triggering instance's teardown. */ readonly refreshInBackground: Effect.Effect; } >()("t3/provider/ModelManifest") {} @@ -199,9 +192,7 @@ export const make = Effect.gen(function* () { let lastAttemptMs: number | null = null; const refreshSemaphore = yield* Semaphore.make(1); - // `Effect.cached` makes concurrent first readers await the same disk load - // rather than racing a "loaded" flag. Only `refreshed` takes the fetch - // semaphore; `current` must never wait behind an in-flight network refresh. + // Only refresh takes the fetch semaphore; current must not wait on network I/O. const ensureDiskCacheLoaded = yield* Effect.cached( Effect.gen(function* () { const fromDisk = yield* fileSystem.readFileString(cachePath).pipe( @@ -209,8 +200,6 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); if (fromDisk === null) return; - // Comparing edit dates, not fetch time, keeps this independent of when - // the cache was written relative to the release. if (manifestUpdatedAtMs(BUNDLED_MODEL_MANIFEST) > manifestUpdatedAtMs(fromDisk.manifest)) { return; } @@ -222,9 +211,7 @@ export const make = Effect.gen(function* () { const refresh = Effect.fn("ModelManifest.refresh")(function* (force = false) { yield* ensureDiskCacheLoaded; const now = yield* Clock.currentTimeMillis; - // A timestamp in the future means the wall clock moved backwards (the - // disk cache crosses restarts, so monotonic time cannot cover it). Treat - // it as expired: the refetch rewrites both timestamps and self-heals. + // Expire future timestamps after clock rollback; disk caches cross restarts, ruling out monotonic time. const isWithin = (sinceMs: number | null, windowMs: number) => sinceMs !== null && now >= sinceMs && now - sinceMs < windowMs; if (!force && isWithin(fetchedAtMs, MANIFEST_TTL_MS)) return manifest; @@ -243,8 +230,7 @@ export const make = Effect.gen(function* () { Effect.timeout(FETCH_TIMEOUT_MS), Effect.catchCause(() => Effect.succeed(null)), ); - // A CDN can still serve an earlier edit after a release. Apply the same - // freshness rule as the disk cache so it cannot undo bundled version gates. + // Reject stale CDN edits just like stale disk caches to preserve bundled version gates. if (fetched === null || manifestUpdatedAtMs(fetched) < manifestUpdatedAtMs(manifest)) { return manifest; } diff --git a/apps/server/src/provider/OpenCode2Client.events.test.ts b/apps/server/src/provider/OpenCode2Client.events.test.ts index 5ca237f2a6691..ddc3bdbaa0c17 100644 --- a/apps/server/src/provider/OpenCode2Client.events.test.ts +++ b/apps/server/src/provider/OpenCode2Client.events.test.ts @@ -1,56 +1,15 @@ -import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; 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 Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import { TestClock } from "effect/testing"; import { HttpClient, HttpClientResponse } from "effect/http"; import { describe } from "vite-plus/test"; import * as OpenCode2Client from "@t3tools/provider-opencode/server/v2/OpenCode2Client"; -const RECORDING = new URL( - "../orchestration-v2/testkit/fixtures/opencode2_simple/opencode_transcript.ndjson", - import.meta.url, -); -const Entry = Schema.Struct({ type: Schema.String, frame: Schema.optional(Schema.Unknown) }); -const decodeEntry = Schema.decodeUnknownSync(Schema.fromJsonString(Entry)); const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); -const newerServerStream = Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const recorded = (yield* fs.readFileString(RECORDING.pathname)) - .split("\n") - .filter((line) => line.length > 0) - .map((line) => decodeEntry(line)) - .flatMap((entry) => { - const frame = entry.frame as { readonly type?: string; readonly event?: unknown } | undefined; - return frame?.type === "sdk.event" ? [frame.event as Record] : []; - }); - const executionStarted = recorded.findIndex( - (event) => event.type === "session.execution.started", - ); - const [first] = recorded; - return [ - ...recorded.slice(0, executionStarted), - { - id: "evt_0000000000newtype", - created: 1, - type: "session.hologram.projected", - data: { beams: 3 }, - }, - { - ...recorded[executionStarted], - data: { ...(recorded[executionStarted]!.data as object), lane: "fast" }, - }, - ...recorded.slice(executionStarted + 1), - first, - ]; -}); - const layerServing = (events: ReadonlyArray) => Layer.succeed( HttpClient.HttpClient, @@ -71,49 +30,7 @@ const connect = Effect.gen(function* () { return yield* opencode.connect({ baseUrl: "http://127.0.0.1:4096", password: "secret" }); }); -const layerServingThenSilent = (events: ReadonlyArray) => - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.succeed( - HttpClientResponse.fromWeb( - request, - new Response( - new ReadableStream({ - start(controller) { - for (const event of events) { - controller.enqueue(new TextEncoder().encode(`data: ${encodeJson(event)}\n\n`)); - } - }, - }), - { headers: { "content-type": "text/event-stream" } }, - ), - ), - ), - ), - ); - describe("OpenCode2Client events", () => { - it.effect("fails a stream that stops sending anything, even heartbeats", () => - Effect.gen(function* () { - const { events } = yield* connect.pipe( - Effect.provide( - OpenCode2Client.layer.pipe( - Layer.provide( - layerServingThenSilent([{ id: "evt_1", type: "server.connected", data: {} }]), - ), - ), - ), - ); - const drained = yield* (yield* events).pipe(Stream.runDrain, Effect.flip, Effect.forkChild); - // Let the first frame arrive and the timer start before the clock moves. - for (let i = 0; i < 20; i++) yield* Effect.yieldNow; - yield* TestClock.adjust("46 seconds"); - const failure = yield* Fiber.join(drained); - assert.strictEqual(failure._tag, "OpenCode2SilentStreamError"); - }).pipe(Effect.provide(TestClock.layer())), - ); - it.effect( "keeps an execution's end and start it cannot decode, and skips other unknown events", () => @@ -159,33 +76,4 @@ describe("OpenCode2Client events", () => { ]); }), ); - - it.effect("skips events a newer server adds and still sees the turn end", () => - Effect.gen(function* () { - const events = yield* newerServerStream; - const { events: subscribe } = yield* connect.pipe( - Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(layerServing(events)))), - ); - const types = yield* (yield* subscribe).pipe( - Stream.map((event) => event.type), - Stream.runCollect, - ); - - assert.notInclude(types, "session.hologram.projected"); - assert.include(types, "session.execution.started"); - assert.include(types, "session.execution.succeeded"); - assert.strictEqual(types.length, events.length - 1); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("the client's own subscription fails the whole stream on the same events", () => - Effect.gen(function* () { - const events = yield* newerServerStream; - const { client } = yield* connect.pipe( - Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(layerServing(events)))), - ); - const failure = yield* client.event.subscribe().pipe(Stream.runDrain, Effect.flip); - assert.strictEqual(failure._tag, "ClientError"); - }).pipe(Effect.provide(NodeServices.layer)), - ); }); diff --git a/apps/server/src/provider/ProjectSettingsOverrideSweep.test.ts b/apps/server/src/provider/ProjectSettingsOverrideSweep.test.ts deleted file mode 100644 index 01fd35c0c598d..0000000000000 --- a/apps/server/src/provider/ProjectSettingsOverrideSweep.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { DEFAULT_SERVER_SETTINGS, ProjectId, type ServerSettings } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { findOrphanedProjectIds } from "./ProjectSettingsOverrideSweep.ts"; - -const liveProjectId = ProjectId.make("project-live"); -const deletedProjectId = ProjectId.make("project-deleted"); - -function settingsWith(overrides: Partial): ServerSettings { - return { ...DEFAULT_SERVER_SETTINGS, ...overrides }; -} - -describe("findOrphanedProjectIds", () => { - it("reports a project override whose project is no longer live", () => { - const settings = settingsWith({ - projectSettingsOverrides: { - [liveProjectId]: { providerInstances: {} }, - [deletedProjectId]: { providerInstances: {} }, - }, - }); - - const orphaned = findOrphanedProjectIds(settings, new Set([liveProjectId])); - - expect(orphaned).toEqual([deletedProjectId]); - }); - - it("reports nothing when every override's project is still live", () => { - const settings = settingsWith({ - projectSettingsOverrides: { - [liveProjectId]: { providerInstances: {} }, - }, - }); - - const orphaned = findOrphanedProjectIds(settings, new Set([liveProjectId])); - - expect(orphaned).toEqual([]); - }); - - it("reports nothing when there are no overrides at all", () => { - const settings = settingsWith({ projectSettingsOverrides: {} }); - - const orphaned = findOrphanedProjectIds(settings, new Set([liveProjectId])); - - expect(orphaned).toEqual([]); - }); -}); diff --git a/apps/server/src/provider/ProjectSettingsOverrideSweep.ts b/apps/server/src/provider/ProjectSettingsOverrideSweep.ts index ae42e9b00c9ca..aa7d205271494 100644 --- a/apps/server/src/provider/ProjectSettingsOverrideSweep.ts +++ b/apps/server/src/provider/ProjectSettingsOverrideSweep.ts @@ -4,7 +4,7 @@ import * as Effect from "effect/Effect"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as Settings from "../serverSettings.ts"; -export const findOrphanedProjectIds = ( +const findOrphanedProjectIds = ( settings: Pick, liveProjectIds: ReadonlySet, ): ReadonlyArray => diff --git a/apps/server/src/provider/ProviderAuthService.test.ts b/apps/server/src/provider/ProviderAuthService.test.ts index 5f7dcd4410cf4..a5f8ff25aad56 100644 --- a/apps/server/src/provider/ProviderAuthService.test.ts +++ b/apps/server/src/provider/ProviderAuthService.test.ts @@ -451,27 +451,6 @@ describe("ProviderAuthService", () => { assert.include(error.detail, "does not accept"); }), ); - it.effect("stops routed sessions before sign-in, including for a disabled instance", () => - Effect.gen(function* () { - const { service, actions, released } = yield* makeHarness({ - enabled: false, - threads: [makeThread("active")], - sessions: new Map([[ThreadId.make("active"), [makeSession("active-session")]]]), - }); - const state = yield* service.start({ instanceId }, owner); - - assert.strictEqual(state.instanceId, instanceId); - assert.strictEqual(state.phase, "waiting"); - assert.deepStrictEqual(released, ["active-session"]); - assert.deepStrictEqual(actions, [ - "close-gate", - "list-threads", - "sessions:active", - "stop:active-session", - "start-sign-in", - ]); - }), - ); it.effect("keeps sign-in state private and accepts the owner's redirect URL", () => Effect.gen(function* () { @@ -689,42 +668,6 @@ describe("ProviderAuthService", () => { }), ); - it.effect.each([ - { text: "/logout", hasAttachments: false, handled: true }, - { text: " \n/logout\t", hasAttachments: false, handled: true }, - { text: "/logout", hasAttachments: true, handled: false }, - { text: "/logout please", hasAttachments: false, handled: false }, - { text: "Explain /logout", hasAttachments: false, handled: false }, - { text: "/Logout", hasAttachments: false, handled: false }, - ])("handles only a standalone logout command %#", ({ text, hasAttachments, handled }) => - Effect.gen(function* () { - const { service, actions } = yield* makeHarness(); - const result = yield* service.tryHandlePromptCommand({ instanceId, text, hasAttachments }); - - assert.strictEqual(result, handled); - assert.deepStrictEqual( - actions, - handled ? ["close-gate", "list-threads", "native-logout"] : [], - ); - }), - ); - - it.effect("does not intercept commands for providers without an auth controller", () => - Effect.gen(function* () { - const { service, actions } = yield* makeHarness(); - for (const id of [unsupportedInstanceId, ProviderInstanceId.make("missing")]) { - assert.isFalse( - yield* service.tryHandlePromptCommand({ - instanceId: id, - text: "/logout", - hasAttachments: false, - }), - ); - } - assert.deepStrictEqual(actions, []); - }), - ); - it.effect("does not log out when the thread shell cannot be read", () => Effect.gen(function* () { const { service, actions } = yield* makeHarness({ shellError: true }); @@ -761,22 +704,6 @@ describe("ProviderAuthService", () => { ]); }), ); - - it.effect("returns native logout failures to the command caller", () => - Effect.gen(function* () { - const logoutError = new ProviderSetupError({ - instanceId, - operation: "logout", - detail: "Native sign-out failed. Try again.", - }); - const { service } = yield* makeHarness({ logoutError }); - const error = yield* Effect.flip( - service.tryHandlePromptCommand({ instanceId, text: "/logout", hasAttachments: false }), - ); - - assert.strictEqual(error, logoutError); - }), - ); }); it.effect("queued logout prompts resolve the current controller after provider replacement", () => @@ -892,46 +819,6 @@ it.effect.each(["start", "logout", "prompt"] as const)( }).pipe(Effect.scoped), ); -it.effect.each([ - { owner: "provider" as const, key: "different-binding" }, - { owner: "t3" as const, key: "shared" }, -])( - "does not invalidate a peer that switches credential binding during session draining %#", - (binding) => - Effect.gen(function* () { - const draining = yield* Deferred.make(); - const continueDrain = yield* Deferred.make(); - const harness = yield* makeHarness({ - sharedCredentials: true, - ...sessionThreads([makeSession("shared-draining", "ready", otherInstanceId)]), - beforeStop: Deferred.succeed(draining, undefined).pipe( - Effect.andThen(Deferred.await(continueDrain)), - ), - }); - const logout = yield* harness.service.logout({ instanceId }).pipe(Effect.forkChild); - yield* Deferred.await(draining); - let replacementInvalidated = false; - harness.replaceInstance( - makeInstance({ - instanceId: otherInstanceId, - enabled: true, - auth: { - ...harness.auth, - credentialBinding: binding, - invalidate: Effect.sync(() => { - replacementInvalidated = true; - }), - }, - }), - ); - yield* Deferred.succeed(continueDrain, undefined); - yield* Fiber.join(logout); - assert.isFalse(replacementInvalidated); - assert.isFalse(harness.sessions.has(ThreadId.make("shared-draining"))); - assert.include(harness.actions, "native-logout"); - }).pipe(Effect.scoped), -); - it.effect.each(["selection", "drain"] as const)( "preserves replacement peer sessions when credentials change during session %s", (phase) => diff --git a/apps/server/src/provider/ProviderAuthService.ts b/apps/server/src/provider/ProviderAuthService.ts index 24f176dd70951..52c37e4d9ea55 100644 --- a/apps/server/src/provider/ProviderAuthService.ts +++ b/apps/server/src/provider/ProviderAuthService.ts @@ -10,6 +10,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; +import * as Function from "effect/Function"; import * as Layer from "effect/Layer"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -87,9 +88,7 @@ export const makeProviderAuthService = Effect.gen(function* () { return instance.auth; }); - // Native sessions may still belong to the previous provider after the - // selected model changes. Read session bindings, not the selected model, - // when invalidating credentials for sign-in or sign-out. + // Invalidate credentials using session bindings; model selection may already point to another provider. const stopSessions = Effect.fn("ProviderAuthService.stopSessions")(function* ( instanceId: ProviderInstanceId, binding: ProviderAuthController["credentialBinding"], @@ -267,8 +266,8 @@ export const makeProviderAuthService = Effect.gen(function* () { }), ); }), - subscribe: (input, ownerSessionId) => - Effect.gen(function* () { + subscribe: Function.flow( + Effect.fn("ProviderAuthService.subscribe")(function* (input, ownerSessionId) { const changes = yield* registry.subscribeChanges; const initial = yield* getController(input.instanceId, "subscribe"); return Stream.concat( @@ -280,7 +279,9 @@ export const makeProviderAuthService = Effect.gen(function* () { Stream.changesWith((previous, next) => previous === next), Stream.switchMap((auth) => auth.subscribe(ownerSessionId)), ); - }).pipe(Stream.unwrap), + }), + Stream.unwrap, + ), tryHandlePromptCommand: Effect.fn("ProviderAuthService.tryHandlePromptCommand")( function* (input) { const instance = yield* registry.getInstance(input.instanceId); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.test.ts b/apps/server/src/provider/ProviderInstanceRegistry.test.ts index 046ac7e9ec79b..0315cb8dfd83d 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.test.ts @@ -1,7 +1,10 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as CodexInstallation from "./CodexInstallation.ts"; +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk"; import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { EnvironmentId, @@ -13,8 +16,6 @@ import { } from "@t3tools/contracts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; -import type { GrokSettings } from "@t3tools/provider-grok/settings"; -import type { CursorSettings } from "@t3tools/provider-cursor/settings"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -22,27 +23,23 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; 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"; -import * as AntigravityInstallation from "./AntigravityInstallation.ts"; import * as ServerConfig from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; import { ClaudeDriver, type ClaudeDriverEnv } from "./Drivers/ClaudeDriver.ts"; import { CodexDriver, type CodexDriverEnv } from "./Drivers/CodexDriver.ts"; -import { CursorDriver, type CursorDriverEnv } from "@t3tools/provider-cursor/server"; -import { GrokDriver, type GrokDriverEnv } from "@t3tools/provider-grok/server"; -import { OpenCodeDriver, type OpenCodeDriverEnv } from "@t3tools/provider-opencode/server"; -import type { OpenCodeSettings } from "@t3tools/provider-opencode/settings"; import * as ModelManifest from "./ModelManifest.ts"; -import * as OpenCodeRuntime from "@t3tools/provider-opencode/server/OpenCodeRuntime"; -import * as OpenCodeServerLedger from "@t3tools/provider-opencode/server/OpenCodeServerLedger"; import * as ResetCreditCoordinator from "./resetCreditCoordinator.ts"; import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import { makeProviderInstanceRegistry } from "./ProviderInstanceRegistry.ts"; import * as ProviderOrchestrationAdapterInfrastructure from "./ProviderOrchestrationAdapterInfrastructure.ts"; import * as ProviderHostLive from "./ProviderHostLive.ts"; +vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); + const layerTestHttpClient = Layer.succeed( HttpClient.HttpClient, HttpClient.make((request) => @@ -101,28 +98,7 @@ const makeClaudeConfig = (overrides: Partial): ClaudeSettings => customModels: [], launchArgs: "", autoCompactWindow: "", - ...overrides, -}); - -const makeCursorConfig = (overrides: Partial): CursorSettings => ({ - enabled: false, - customModels: [], - ...overrides, -}); - -const makeGrokConfig = (overrides: Partial): GrokSettings => ({ - enabled: false, - binaryPath: "grok", - customModels: [], - ...overrides, -}); - -const makeOpenCodeConfig = (overrides: Partial): OpenCodeSettings => ({ - enabled: false, - binaryPath: "opencode", - serverUrl: "", - serverPassword: "", - customModels: [], + idleCompaction: "default", ...overrides, }); @@ -179,6 +155,11 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { const layerBaseDeps = ServerConfig.layerTest(process.cwd(), { prefix: "provider-instance-registry-test", }).pipe( + Layer.provideMerge( + Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({ + endpoint: Effect.succeed("unused-private-pipe"), + }), + ), Layer.provideMerge(NodeServices.layer), Layer.provideMerge( Layer.mock(CodexInstallation.CodexInstallation)({ @@ -213,79 +194,6 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { Layer.provideMerge(layerBase), ); - it.live("boots two independent codex instances from a ProviderInstanceConfigMap", () => - Effect.gen(function* () { - const personalId = ProviderInstanceId.make("codex_personal"); - const workId = ProviderInstanceId.make("codex_work"); - const codexDriverKind = ProviderDriverKind.make("codex"); - - const configMap: ProviderInstanceConfigMap = { - [personalId]: { - driver: codexDriverKind, - displayName: "Codex (personal)", - enabled: false, - config: makeCodexConfig({ - binaryPath: "/opt/codex-personal/bin/codex", - homePath: "/home/julius/.codex_personal", - customModels: ["personal-preview"], - }), - }, - [workId]: { - driver: codexDriverKind, - displayName: "Codex (work)", - enabled: false, - config: makeCodexConfig({ - binaryPath: "/opt/codex-work/bin/codex", - homePath: "/home/julius/.codex", - customModels: ["work-preview"], - }), - }, - }; - - const { registry } = yield* makeProviderInstanceRegistry({ - drivers: [CodexDriver], - configMap, - }); - - const instances = yield* registry.listInstances; - expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual( - [personalId, workId].toSorted(), - ); - expect(instances.every((instance) => instance.driverKind === codexDriverKind)).toBe(true); - expect(instances.map((instance) => instance.displayName).toSorted()).toEqual( - ["Codex (personal)", "Codex (work)"].toSorted(), - ); - - const personal = yield* registry.getInstance(personalId); - const work = yield* registry.getInstance(workId); - expect(personal).toBeDefined(); - expect(work).toBeDefined(); - expect(personal!.orchestrationAdapter).not.toBe(work!.orchestrationAdapter); - expect(personal!.textGeneration).not.toBe(work!.textGeneration); - expect(personal!.snapshot).not.toBe(work!.snapshot); - - const personalSnapshot = yield* personal!.snapshot.getSnapshot; - expect(personalSnapshot.instanceId).toBe(personalId); - expect(personalSnapshot.driver).toBe(codexDriverKind); - expect(personalSnapshot.enabled).toBe(false); - const path = yield* Path.Path; - expect(personalSnapshot.continuation?.groupKey).toBe( - `codex:home:${path.resolve("/home/julius/.codex_personal")}`, - ); - - const workSnapshot = yield* work!.snapshot.getSnapshot; - expect(workSnapshot.instanceId).toBe(workId); - expect(workSnapshot.driver).toBe(codexDriverKind); - expect(workSnapshot.enabled).toBe(false); - expect(workSnapshot.continuation?.groupKey).toBe( - `codex:home:${path.resolve("/home/julius/.codex")}`, - ); - - const unavailable = yield* registry.listUnavailable; - expect(unavailable).toEqual([]); - }).pipe(Effect.provide(layerTest)), - ); - it.live("treats an explicit in-config enabled:false as disabling despite the envelope", () => Effect.gen(function* () { const staleId = ProviderInstanceId.make("codex_stale"); @@ -310,42 +218,6 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); - it.live("reports Codex's answer when a redemption changed nothing", () => - Effect.gen(function* () { - if (yield* HostProcess.isWindows) return; - const fileSystem = yield* FileSystem.FileSystem; - const fixtures = yield* makeTildeProviderFixtures(); - yield* fileSystem.writeFileString( - fixtures.codexScriptPath, - JSON.stringify({ - rootThreadId: "probe-thread", - notifications: [], - account: { type: "chatgpt", email: "test@example.com", planType: "plus" }, - failRateLimitsRead: true, - resetCreditOutcome: "alreadyRedeemed", - }), - ); - const codexId = ProviderInstanceId.make("codex_reset"); - const { registry } = yield* makeProviderInstanceRegistry({ - drivers: [CodexDriver], - configMap: { - [codexId]: { - driver: ProviderDriverKind.make("codex"), - enabled: true, - environment: [ - { name: "T3_CODEX_COLLAB_SCRIPT", value: fixtures.codexScriptPath, sensitive: false }, - ], - config: makeCodexConfig({ enabled: true, binaryPath: fixtures.codexBinaryPath }), - }, - }, - }); - const codex = yield* registry.getInstance(codexId); - expect(codex).toBeDefined(); - yield* codex!.snapshot.refresh; - expect(yield* codex!.consumeResetCredit!()).toBe("alreadyRedeemed"); - }).pipe(Effect.provide(layerTest)), - ); - it.live("runs Codex and Claude readiness probes from configured tilde paths", () => Effect.gen(function* () { if (yield* HostProcess.isWindows) return; @@ -413,8 +285,7 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { [claudeId]: { driver: ProviderDriverKind.make("claudeAgent"), enabled: true, - // Packaged desktop builds start the server in $HOME, where some - // `claude` wrappers refuse to run. + // Packaged desktop starts in $HOME, where some claude wrappers refuse to run. environment: [{ name: "T3_CLAUDE_REQUIRED_CWD", value: stateDir, sensitive: false }], config: makeClaudeConfig({ enabled: true, @@ -434,6 +305,141 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("scopes Claude's one-probe fallback to the logged-in organization", () => + Effect.gen(function* () { + if (yield* HostProcess.isWindows) return; + + const fixtures = yield* makeTildeProviderFixtures(); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const accountConfigPath = path.join(fixtures.claudeHomePath, ".claude.json"); + yield* fs.writeFileString( + accountConfigPath, + JSON.stringify({ oauthAccount: { organizationUuid: "org-a" } }), + ); + const claudeId = ProviderInstanceId.make("claude_probe_recovery"); + let probeCount = 0; + let successfulProbeCount = 0; + let failProbe = false; + const query = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + initializationResult: () => { + probeCount++; + if (failProbe) return Promise.reject(new Error("initialization failed")); + successfulProbeCount++; + return Promise.resolve({ + commands: [ + { + name: successfulProbeCount === 1 ? "last-good" : "recovered", + description: "", + argumentHint: "", + }, + ], + account: { + email: + successfulProbeCount === 1 ? "account-a@example.com" : "account-b@example.com", + subscriptionType: "pro", + tokenSource: "oauth", + }, + }); + }, + usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({ + rate_limits_available: true, + rate_limits: { + five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" }, + }, + }), + }) as ReturnType, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore())); + + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [ClaudeDriver], + configMap: { + [claudeId]: { + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + config: makeClaudeConfig({ + enabled: true, + binaryPath: fixtures.claudeBinaryPath, + homePath: fixtures.claudeHomePath, + }), + }, + }, + }); + const claude = yield* registry.getInstance(claudeId); + expect(claude).toBeDefined(); + + const first = yield* claude!.snapshot.refresh; + expect(first).toMatchObject({ + status: "ready", + auth: { status: "authenticated", email: "account-a@example.com", workspaceId: "org-a" }, + slashCommands: expect.arrayContaining([expect.objectContaining({ name: "last-good" })]), + }); + expect(first.usageLimits?.unavailable).toBeUndefined(); + expect(probeCount).toBe(1); + + yield* TestClock.adjust("1 second"); + yield* fs.writeFileString( + accountConfigPath, + JSON.stringify({ oauthAccount: { organizationUuid: "org-b" } }), + ); + yield* claude!.invalidateCaches ?? Effect.void; + failProbe = true; + const accountChangedFailure = yield* claude!.snapshot.refresh; + + expect(accountChangedFailure).toMatchObject({ + status: "warning", + auth: { status: "unknown" }, + message: "Claude Agent CLI failed while checking account status.", + }); + expect(accountChangedFailure.checkedAt).not.toBe(first.checkedAt); + expect(accountChangedFailure.usageLimits).toBeUndefined(); + expect(accountChangedFailure.slashCommands).not.toEqual( + expect.arrayContaining([expect.objectContaining({ name: "last-good" })]), + ); + const failedProbeCount = probeCount; + expect(failedProbeCount).toBeGreaterThan(1); + + failProbe = false; + const recovered = yield* claude!.snapshot.refresh; + expect(recovered).toMatchObject({ + status: "ready", + auth: { status: "authenticated", email: "account-b@example.com", workspaceId: "org-b" }, + slashCommands: expect.arrayContaining([expect.objectContaining({ name: "recovered" })]), + }); + expect(recovered.usageLimits?.unavailable).toBeUndefined(); + const recoveredProbeCount = probeCount; + expect(recoveredProbeCount).toBeGreaterThan(failedProbeCount); + + yield* TestClock.adjust("1 second"); + yield* claude!.invalidateCaches ?? Effect.void; + failProbe = true; + const sameAccountFailure = yield* claude!.snapshot.refresh; + expect(sameAccountFailure).toMatchObject({ + status: "ready", + auth: { status: "authenticated", email: "account-b@example.com", workspaceId: "org-b" }, + slashCommands: expect.arrayContaining([expect.objectContaining({ name: "recovered" })]), + }); + expect(sameAccountFailure.usageLimits?.checkedAt).toBe(recovered.usageLimits?.checkedAt); + expect(sameAccountFailure.usageLimits?.windows).toEqual(recovered.usageLimits?.windows); + const sameAccountFailureProbeCount = probeCount; + expect(sameAccountFailureProbeCount).toBeGreaterThan(recoveredProbeCount); + + const repeatedFailure = yield* claude!.snapshot.refresh; + expect(repeatedFailure).toMatchObject({ + status: "warning", + auth: { status: "unknown" }, + message: "Claude Agent CLI failed while checking account status.", + }); + expect(repeatedFailure.slashCommands).not.toEqual( + expect.arrayContaining([expect.objectContaining({ name: "recovered" })]), + ); + expect(probeCount).toBeGreaterThan(sameAccountFailureProbeCount); + }).pipe(Effect.provide(layerTest)), + ); + const redeemClaudeReset = (claim: { result: string; usageFailsAfterClaim: boolean }) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -526,6 +532,79 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }), ); + const makeClaudeCacheFixture = Effect.fnUntraced(function* ( + state: "ready" | "signed-out" | "usage-failed", + ) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const fixtures = yield* makeTildeProviderFixtures(); + const recovered = path.join(fixtures.claudeHomePath, "recovered"); + const probeLog = path.join(fixtures.claudeHomePath, "probes.log"); + const instanceId = ProviderInstanceId.make("claude_cache"); + const { registry } = yield* makeProviderInstanceRegistry({ + drivers: [ClaudeDriver], + configMap: { + [instanceId]: { + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + environment: [ + { name: "T3_CLAUDE_PROBE_LOG", value: probeLog, sensitive: false }, + ...(state === "ready" + ? [] + : [ + { + name: + state === "signed-out" + ? "T3_CLAUDE_LOGIN_MARKER" + : "T3_CLAUDE_USAGE_FAILS_UNTIL", + value: recovered, + sensitive: false, + }, + ]), + ], + config: makeClaudeConfig({ + enabled: true, + binaryPath: fixtures.claudeBinaryPath, + homePath: fixtures.claudeHomePath, + }), + }, + }, + }); + const instance = yield* registry.getInstance(instanceId); + expect(instance).toBeDefined(); + return { + refresh: instance!.snapshot.refresh, + recover: fs.writeFileString(recovered, ""), + probeLog: fs.readFileString(probeLog), + }; + }); + + for (const state of ["signed-out", "usage-failed"] as const) { + it.effect.skipIf(windowsHost)( + state === "signed-out" + ? "shows Claude usage on the first refresh after signing back in" + : "retries Claude usage on the first refresh after a failed usage read", + () => + Effect.gen(function* () { + const fixture = yield* makeClaudeCacheFixture(state); + const before = yield* fixture.refresh; + if (state === "signed-out") { + expect(before.auth.status).toBe("unauthenticated"); + expect(before.usageLimits).toBeUndefined(); + } else { + expect(before.auth.status).toBe("authenticated"); + expect(before.usageLimits?.unavailable?.reason).toBe("probeFailed"); + } + + yield* fixture.recover; + const after = yield* fixture.refresh; + expect(after.auth.status).toBe("authenticated"); + expect(after.usageLimits?.unavailable).toBeUndefined(); + expect(after.usageLimits?.windows.map((window) => window.id)).toEqual(["five_hour"]); + }).pipe(Effect.provide(layerTest)), + ); + } + it.live( "shadows instances whose driver is not registered in this build without failing boot", () => @@ -566,196 +645,3 @@ describe("ProviderInstanceRegistry — multi-instance codex slice", () => { }).pipe(Effect.provide(layerTest)), ); }); - -describe("ProviderInstanceRegistry — all drivers slice", () => { - const layerInfra = OpenCodeRuntime.layer.pipe( - Layer.provide(OpenCodeServerLedger.layerTest), - Layer.provideMerge(NodeServices.layer), - Layer.provideMerge( - Layer.mock(CodexInstallation.CodexInstallation)({ - managedDirectory: "unused-managed-installation", - }), - ), - Layer.provideMerge( - Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { - getEnvironmentId: Effect.succeed( - EnvironmentId.make("00000000-0000-4000-8000-000000000001"), - ), - }), - ), - ); - const layerBaseDeps = AntigravityInstallation.AntigravityInstallation.layer.pipe( - Layer.provideMerge(ServerSecretStore.layer), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "provider-instance-registry-all-drivers-test", - }), - ), - Layer.provideMerge(layerInfra), - Layer.provideMerge(layerBackgroundPolicyAlwaysRun), - Layer.provideMerge(ServerSettings.layerTest()), - Layer.provideMerge(layerTestHttpClient), - Layer.provideMerge(ServerSettings.layerTest()), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(ProviderLatestVersions.layer), - Layer.provideMerge(McpProviderSessions.layer), - Layer.provideMerge(ModelManifest.layerTest), - Layer.provideMerge(ResetCreditCoordinator.layerTest), - ); - const layerBase = ProviderHostLive.layer.pipe(Layer.provideMerge(layerBaseDeps)); - const layerTest = ProviderOrchestrationAdapterInfrastructure.layer.pipe( - Layer.provideMerge(layerBase), - ); - - it.live("boots one instance of every shipped driver from a single config map", () => - Effect.gen(function* () { - const codexId = ProviderInstanceId.make("codex_default"); - const claudeId = ProviderInstanceId.make("claude_default"); - const cursorId = ProviderInstanceId.make("cursor_default"); - const grokId = ProviderInstanceId.make("grok_default"); - const openCodeId = ProviderInstanceId.make("opencode_default"); - - const codexDriverKind = ProviderDriverKind.make("codex"); - const claudeDriverKind = ProviderDriverKind.make("claudeAgent"); - const cursorDriverKind = ProviderDriverKind.make("cursor"); - const grokDriverKind = ProviderDriverKind.make("grok"); - const openCodeDriverKind = ProviderDriverKind.make("opencode"); - - const configMap: ProviderInstanceConfigMap = { - [codexId]: { - driver: codexDriverKind, - displayName: "Codex", - enabled: false, - config: makeCodexConfig({ homePath: "/home/julius/.codex" }), - }, - [claudeId]: { - driver: claudeDriverKind, - displayName: "Claude", - enabled: false, - config: makeClaudeConfig({ - homePath: "/home/julius/.claude-work", - launchArgs: "--verbose", - }), - }, - [cursorId]: { - driver: cursorDriverKind, - displayName: "Cursor", - enabled: false, - config: makeCursorConfig({}), - }, - [grokId]: { - driver: grokDriverKind, - displayName: "Grok", - enabled: false, - config: makeGrokConfig({}), - }, - [openCodeId]: { - driver: openCodeDriverKind, - displayName: "OpenCode", - enabled: false, - config: makeOpenCodeConfig({}), - }, - }; - - const { registry } = yield* makeProviderInstanceRegistry< - CodexDriverEnv | ClaudeDriverEnv | CursorDriverEnv | GrokDriverEnv | OpenCodeDriverEnv - >({ - drivers: [CodexDriver, ClaudeDriver, CursorDriver, GrokDriver, OpenCodeDriver], - configMap, - }); - - const unavailable = yield* registry.listUnavailable; - expect(unavailable).toEqual([]); - - const instances = yield* registry.listInstances; - expect(instances).toHaveLength(5); - expect(instances.map((instance) => instance.instanceId).toSorted()).toEqual( - [codexId, claudeId, cursorId, grokId, openCodeId].toSorted(), - ); - - const codex = yield* registry.getInstance(codexId); - const claude = yield* registry.getInstance(claudeId); - const cursor = yield* registry.getInstance(cursorId); - const grok = yield* registry.getInstance(grokId); - const openCode = yield* registry.getInstance(openCodeId); - expect(codex?.driverKind).toBe(codexDriverKind); - expect(claude?.driverKind).toBe(claudeDriverKind); - expect(cursor?.driverKind).toBe(cursorDriverKind); - expect(grok?.driverKind).toBe(grokDriverKind); - expect(openCode?.driverKind).toBe(openCodeDriverKind); - expect(codex?.displayName).toBe("Codex"); - expect(claude?.displayName).toBe("Claude"); - expect(cursor?.displayName).toBe("Cursor"); - expect(grok?.displayName).toBe("Grok"); - expect(openCode?.displayName).toBe("OpenCode"); - - const adapters = [ - codex!.orchestrationAdapter, - claude!.orchestrationAdapter, - cursor!.orchestrationAdapter, - grok!.orchestrationAdapter, - openCode!.orchestrationAdapter, - ]; - expect(new Set(adapters).size).toBe(adapters.length); - const textGenerations = [ - codex!.textGeneration, - claude!.textGeneration, - cursor!.textGeneration, - grok!.textGeneration, - openCode!.textGeneration, - ]; - expect(new Set(textGenerations).size).toBe(textGenerations.length); - const snapshots = [ - codex!.snapshot, - claude!.snapshot, - cursor!.snapshot, - grok!.snapshot, - openCode!.snapshot, - ]; - expect(new Set(snapshots).size).toBe(snapshots.length); - - const codexSnapshot = yield* codex!.snapshot.getSnapshot; - expect(codexSnapshot.instanceId).toBe(codexId); - expect(codexSnapshot.driver).toBe(codexDriverKind); - expect(codexSnapshot.enabled).toBe(false); - expect(codexSnapshot.continuation?.groupKey).toBe( - `codex:home:${(yield* Path.Path).resolve("/home/julius/.codex")}`, - ); - - const claudeSnapshot = yield* claude!.snapshot.getSnapshot; - expect(claudeSnapshot.instanceId).toBe(claudeId); - expect(claudeSnapshot.driver).toBe(claudeDriverKind); - expect(claudeSnapshot.enabled).toBe(false); - expect(claudeSnapshot.continuation?.groupKey).toBe( - `claude:home:${(yield* Path.Path).resolve("/home/julius/.claude-work")}`, - ); - - const cursorSnapshot = yield* cursor!.snapshot.getSnapshot; - expect(cursorSnapshot.instanceId).toBe(cursorId); - expect(cursorSnapshot.driver).toBe(cursorDriverKind); - expect(cursorSnapshot.enabled).toBe(false); - expect(cursorSnapshot.continuation?.groupKey).toBe( - `${cursorDriverKind}:instance:${cursorId}`, - ); - - const grokSnapshot = yield* grok!.snapshot.getSnapshot; - expect(grokSnapshot.instanceId).toBe(grokId); - expect(grokSnapshot.driver).toBe(grokDriverKind); - expect(grokSnapshot.enabled).toBe(false); - expect(grokSnapshot.continuation?.groupKey).toBe(`${grokDriverKind}:instance:${grokId}`); - - const openCodeSnapshot = yield* openCode!.snapshot.getSnapshot; - expect(openCodeSnapshot.instanceId).toBe(openCodeId); - expect(openCodeSnapshot.driver).toBe(openCodeDriverKind); - expect(openCodeSnapshot.enabled).toBe(false); - expect(openCodeSnapshot.continuation?.groupKey).toBe( - `${openCodeDriverKind}:instance:${openCodeId}`, - ); - }).pipe(Effect.provide(layerTest)), - ); -}); diff --git a/apps/server/src/provider/ProviderInstanceRegistry.ts b/apps/server/src/provider/ProviderInstanceRegistry.ts index e5bf808faa73b..3bbbe2900b9f2 100644 --- a/apps/server/src/provider/ProviderInstanceRegistry.ts +++ b/apps/server/src/provider/ProviderInstanceRegistry.ts @@ -29,14 +29,7 @@ export class ProviderInstanceRegistry extends Context.Service< ) => Effect.Effect; readonly listInstances: Effect.Effect>; readonly listUnavailable: Effect.Effect>; - /** - * NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the stream starts - * running, forking a consumer via `Stream.runForEach(...).pipe(Effect.forkScoped)` races - * the next publish — the forked fiber may not have subscribed yet when the publish lands. - * Hot-reload consumers that must not miss a publish should use `subscribeChanges` below - * instead, which acquires the subscription synchronously in the caller's fiber before the - * consumer loop is forked. - */ + /** streamChanges subscribes on consumption; use subscribeChanges before forking to avoid missing the next publish. */ readonly streamChanges: Stream.Stream; readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; } @@ -57,11 +50,7 @@ interface RegistryState { const entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean => Equal.equals(a, b); -/** - * An explicit false on either the envelope or the raw config blob wins (most - * restrictive) — old settings files can carry both flags with conflicting - * values, and a user's disable must never be silently undone. - */ +/** Conflicting saved flags must preserve any explicit disable. */ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown): boolean => { const rawConfigEnabled = providerInstanceConfigEnabledFlag(entry.config); if (entry.enabled === false || rawConfigEnabled === false) { @@ -70,98 +59,97 @@ const resolveEntryEnabled = (entry: ProviderInstanceConfig, typedConfig: unknown return entry.enabled ?? providerInstanceConfigEnabledFlag(typedConfig) ?? true; }; -const buildEntry = (input: { +const buildEntry = Effect.fn("ProviderInstanceRegistry.buildEntry")(function* (input: { readonly driversById: ReadonlyMap>; readonly parentScope: Scope.Scope; readonly instanceId: ProviderInstanceId; readonly rawInstanceId: string; readonly entry: ProviderInstanceConfig; -}): Effect.Effect< +}): Effect.fn.Return< | { readonly kind: "live"; readonly live: LiveEntry } | { readonly kind: "unavailable"; readonly snapshot: ServerProvider }, never, R -> => - Effect.gen(function* () { - const { driversById, parentScope, instanceId, rawInstanceId, entry } = input; - const driver = driversById.get(entry.driver); - if (!driver) { - return { - kind: "unavailable" as const, - snapshot: yield* buildUnavailableProviderSnapshot({ - driverKind: entry.driver, - instanceId, - displayName: entry.displayName, - accentColor: entry.accentColor, - reason: `Driver '${entry.driver}' is not registered in this build.`, - }), - }; - } - - const decoder = Schema.decodeUnknownEffect(driver.configSchema); - const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result); - if (decodeResult._tag === "Failure") { - const issue = decodeResult.failure; - const detail = issue.message ?? String(issue); - yield* Effect.logError("Failed to decode provider instance config", { - instanceId: rawInstanceId, - driver: entry.driver, - detail, - }); - return { - kind: "unavailable" as const, - snapshot: yield* buildUnavailableProviderSnapshot({ - driverKind: entry.driver, - instanceId, - displayName: entry.displayName, - accentColor: entry.accentColor, - reason: `Invalid config for instance '${rawInstanceId}': ${detail}`, - }), - }; - } - - const typedConfig = decodeResult.success; - const childScope = yield* Scope.make(); - yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore)); +> { + const { driversById, parentScope, instanceId, rawInstanceId, entry } = input; + const driver = driversById.get(entry.driver); + if (!driver) { + return { + kind: "unavailable" as const, + snapshot: yield* buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: `Driver '${entry.driver}' is not registered in this build.`, + }), + }; + } - const createResult = yield* driver - .create({ + const decoder = Schema.decodeUnknownEffect(driver.configSchema); + const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result); + if (decodeResult._tag === "Failure") { + const issue = decodeResult.failure; + const detail = issue.message ?? String(issue); + yield* Effect.logError("Failed to decode provider instance config", { + instanceId: rawInstanceId, + driver: entry.driver, + detail, + }); + return { + kind: "unavailable" as const, + snapshot: yield* buildUnavailableProviderSnapshot({ + driverKind: entry.driver, instanceId, displayName: entry.displayName, accentColor: entry.accentColor, - environment: entry.environment ?? [], - enabled: resolveEntryEnabled(entry, typedConfig), - config: typedConfig, - }) - .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result); - if (createResult._tag === "Failure") { - yield* Effect.logError("Failed to create provider instance", { - instanceId: rawInstanceId, - driver: entry.driver, - detail: createResult.failure.detail, - }); - yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore); - return { - kind: "unavailable" as const, - snapshot: yield* buildUnavailableProviderSnapshot({ - driverKind: entry.driver, - instanceId, - displayName: entry.displayName, - accentColor: entry.accentColor, - reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`, - }), - }; - } + reason: `Invalid config for instance '${rawInstanceId}': ${detail}`, + }), + }; + } + + const typedConfig = decodeResult.success; + const childScope = yield* Scope.make(); + yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore)); + const createResult = yield* driver + .create({ + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + environment: entry.environment ?? [], + enabled: resolveEntryEnabled(entry, typedConfig), + config: typedConfig, + }) + .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result); + if (createResult._tag === "Failure") { + yield* Effect.logError("Failed to create provider instance", { + instanceId: rawInstanceId, + driver: entry.driver, + detail: createResult.failure.detail, + }); + yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore); return { - kind: "live" as const, - live: { - instance: createResult.success, - scope: childScope, - entry, - }, + kind: "unavailable" as const, + snapshot: yield* buildUnavailableProviderSnapshot({ + driverKind: entry.driver, + instanceId, + displayName: entry.displayName, + accentColor: entry.accentColor, + reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`, + }), }; - }); + } + + return { + kind: "live" as const, + live: { + instance: createResult.success, + scope: childScope, + entry, + }, + }; +}); const makeReconcile = (input: { readonly state: RegistryState; @@ -178,9 +166,7 @@ const makeReconcile = (input: { nextRaw.map(([raw]) => ProviderInstanceId.make(raw)), ); - // 1. Close scopes for instances that disappeared or whose config - // changed. Do this BEFORE creating replacements so ids map 1-to-1 - // to live scopes at all times. + // Close changed/removed scopes before replacements to preserve one live scope per id. const removedIds: Array = []; const replacedIds = new Set(); for (const [instanceId, live] of previousEntries) { @@ -263,67 +249,68 @@ const makeReconcile = (input: { }); }; -export const makeProviderInstanceRegistry = (input: { +export const makeProviderInstanceRegistry = Effect.fn( + "ProviderInstanceRegistry.makeProviderInstanceRegistry", +)(function* (input: { readonly drivers: ReadonlyArray>; readonly configMap: ProviderInstanceConfigMap; -}): Effect.Effect< +}): Effect.fn.Return< { readonly registry: ProviderInstanceRegistry["Service"]; readonly mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape; }, never, R | Scope.Scope -> => - Effect.gen(function* () { - const driversById = new Map>( - input.drivers.map((driver) => [driver.driverKind, driver]), - ); +> { + const driversById = new Map>( + input.drivers.map((driver) => [driver.driverKind, driver]), + ); - // Capture the enclosing scope so per-instance child scopes can be - // attached to it at `reconcile` time. Without this, `reconcile` - // called later (e.g. from the hydration layer) would attach child - // scopes to the *caller's* scope instead of the registry's. - const parentScope = yield* Scope.Scope; + // Capture the enclosing scope so per-instance child scopes can be + // attached to it at `reconcile` time. Without this, `reconcile` + // called later (e.g. from the hydration layer) would attach child + // scopes to the *caller's* scope instead of the registry's. + const parentScope = yield* Scope.Scope; - const driverContext = yield* Effect.context(); + const driverContext = yield* Effect.context(); - const entries = yield* Ref.make>(new Map()); - const unavailable = yield* Ref.make>(new Map()); - const changes = yield* PubSub.unbounded(); - yield* Effect.addFinalizer(() => PubSub.shutdown(changes)); + const entries = yield* Ref.make>(new Map()); + const unavailable = yield* Ref.make>(new Map()); + const changes = yield* PubSub.unbounded(); + yield* Effect.addFinalizer(() => PubSub.shutdown(changes)); - const state: RegistryState = { entries, unavailable, changes }; - const reconcileWithR = makeReconcile({ state, driversById, parentScope }); - const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] = - (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext)); + const state: RegistryState = { entries, unavailable, changes }; + const reconcileWithR = makeReconcile({ state, driversById, parentScope }); + const reconcile: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape["reconcile"] = + (configMap) => reconcileWithR(configMap).pipe(Effect.provideContext(driverContext)); - yield* reconcile(input.configMap); + yield* reconcile(input.configMap); - const registry: ProviderInstanceRegistry["Service"] = { - getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)), - listInstances: Ref.get(entries).pipe( - Effect.map( - (map) => - Array.from(map.values(), (live) => live.instance) as ReadonlyArray, - ), + const registry: ProviderInstanceRegistry["Service"] = { + getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)), + listInstances: Ref.get(entries).pipe( + Effect.map( + (map) => + Array.from(map.values(), (live) => live.instance) as ReadonlyArray, ), - listUnavailable: Ref.get(unavailable).pipe( - Effect.map((map) => Array.from(map.values()) as ReadonlyArray), - ), - get streamChanges() { - return Stream.fromPubSub(changes); - }, - get subscribeChanges() { - return PubSub.subscribe(changes); - }, - }; + ), + listUnavailable: Ref.get(unavailable).pipe( + Effect.map((map) => Array.from(map.values()) as ReadonlyArray), + ), + get streamChanges() { + return Stream.fromPubSub(changes); + }, + get subscribeChanges() { + return PubSub.subscribe(changes); + }, + }; - const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = { - reconcile, - }; + const mutator: ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutatorShape = { + reconcile, + }; - return { registry, mutator }; - }); + return { registry, mutator }; +}); export const layer = (input: { readonly drivers: ReadonlyArray>; diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts index 16b3958f3613c..029904eac5b67 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.test.ts @@ -54,21 +54,6 @@ describe("deriveProviderInstanceConfigMap", () => { }); }); - it("leaves an already machine-enabled instance untouched", () => { - const settings = settingsWith({ - providerInstances: { - [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: true }, - }, - projectSettingsOverrides: { - [projectId]: { providerInstances: { [instanceId]: { enabled: true } } }, - }, - }); - - const merged = deriveProviderInstanceConfigMap(settings); - - expect(merged[instanceId]).toBe(settings.providerInstances[instanceId]); - }); - it("does not revive an instance a project override references but settings no longer configure", () => { const settings = settingsWith({ providerInstances: {}, @@ -96,27 +81,4 @@ describe("deriveProviderInstanceConfigMap", () => { expect(merged[instanceId]).toBe(settings.providerInstances[instanceId]); }); - - it("folds overrides from multiple projects", () => { - const otherInstanceId = ProviderInstanceId.make("claudeAgent_personal"); - const otherProjectId = ProjectId.make("project-b"); - const settings = settingsWith({ - providerInstances: { - [instanceId]: { driver: ProviderDriverKind.make("codex"), enabled: false }, - [otherInstanceId]: { driver: ProviderDriverKind.make("claudeAgent"), enabled: false }, - }, - projectSettingsOverrides: { - [projectId]: { providerInstances: { [instanceId]: { enabled: true } } }, - [otherProjectId]: { providerInstances: { [otherInstanceId]: { enabled: true } } }, - }, - }); - - const merged = deriveProviderInstanceConfigMap(settings); - - expect(merged[instanceId]).toEqual({ driver: ProviderDriverKind.make("codex"), enabled: true }); - expect(merged[otherInstanceId]).toEqual({ - driver: ProviderDriverKind.make("claudeAgent"), - enabled: true, - }); - }); }); diff --git a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts index 1dcb204256333..4ea8042d02ef1 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryHydration.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryHydration.ts @@ -45,9 +45,7 @@ export const deriveProviderInstanceConfigMap = ( merged[instanceId] = { driver: driver.driverKind }; } - // A project that turns an instance on needs it alive and probed even when the machine itself - // has it off, or a thread in that project would route to an instance nobody ever checked in - // on. + // Probe project-enabled instances even if disabled machine-wide; project threads can still route to them. for (const overrides of Object.values(settings.projectSettingsOverrides)) { for (const [rawInstanceId, projectOverride] of Object.entries( overrides?.providerInstances ?? {}, @@ -69,25 +67,28 @@ export const deriveProviderInstanceConfigMap = ( return merged as ProviderInstanceConfigMap; }; -const layerSettingsWatcher = Layer.effectDiscard( - Effect.gen(function* () { - const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator; - const serverSettings = yield* Settings.ServerSettingsService; - const settingsChanges = yield* serverSettings.subscribeChanges; - yield* settingsChanges.pipe( - Stream.runForEach((next) => - mutator - .reconcile(deriveProviderInstanceConfigMap(next)) - .pipe( +const layerSettingsWatcher = (settingsChanges: Stream.Stream) => + Layer.effectDiscard( + Effect.gen(function* () { + const mutator = yield* ProviderInstanceRegistryMutator.ProviderInstanceRegistryMutator; + const serverSettings = yield* Settings.ServerSettingsService; + yield* settingsChanges.pipe( + Stream.runForEach(() => + // The subscription predates the seed read, so a queued change can be + // older than the seed. A failed current read must leave the registry intact. + serverSettings.getSettings.pipe( + Effect.flatMap((current) => + mutator.reconcile(deriveProviderInstanceConfigMap(current)), + ), Effect.catchCause((cause) => Effect.logError("ProviderInstanceRegistry reconcile failed", cause), ), ), - ), - Effect.forkScoped, - ); - }), -); + ), + Effect.forkScoped, + ); + }), + ); export const layer: Layer.Layer< ProviderInstanceRegistry.ProviderInstanceRegistry, @@ -96,6 +97,8 @@ export const layer: Layer.Layer< > = Layer.unwrap( Effect.gen(function* () { const serverSettings = yield* Settings.ServerSettingsService; + // Subscribe before the seed read so saves during registry construction are queued. + const settingsChanges = yield* serverSettings.subscribeChanges; const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe( Effect.orElseSucceed(() => undefined), ); @@ -113,7 +116,7 @@ export const layer: Layer.Layer< Layer.provide(ProviderHostLive.layer), ); - return layerSettingsWatcher.pipe(Layer.provideMerge(layerMutable)); + return layerSettingsWatcher(settingsChanges).pipe(Layer.provideMerge(layerMutable)); }), ) as Layer.Layer< ProviderInstanceRegistry.ProviderInstanceRegistry, diff --git a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts index f7675ff33a38f..51322826230d8 100644 --- a/apps/server/src/provider/ProviderInstanceRegistryMutator.ts +++ b/apps/server/src/provider/ProviderInstanceRegistryMutator.ts @@ -1,9 +1,4 @@ -/** - * Closes the per-instance `Scope` of every removed or replaced entry (tearing - * down adapter processes, refresh fibres, temp files) BEFORE creating the - * replacement — `reconcile` guarantees "at most one live instance per id" at - * all times. - */ +/** Reconcile closes removed/replaced scopes before creating replacements: at most one live instance per id. */ import type { ProviderInstanceConfigMap } from "@t3tools/contracts"; import * as Context from "effect/Context"; import type * as Effect from "effect/Effect"; diff --git a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts index 266de2339137f..3245ee61294e4 100644 --- a/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts +++ b/apps/server/src/provider/ProviderOrchestrationAdapterInfrastructure.ts @@ -16,11 +16,7 @@ export type ProviderOrchestrationAdapterInfrastructure = | CursorKeychain.CursorKeychain | IdAllocator.IdAllocatorV2; -/** - * `providerContinuationRequestsLayer` must be the same layer reference the - * orchestration runtime provides to its continuation worker so Effect layer - * memoization yields one shared queue. - */ +/** Reuse the continuation worker's exact layer reference so memoization shares one queue. */ export const layer = Layer.mergeAll( ClaudeAdapterV2.layerQueryRunner, CodexAdapterV2.layerAppServerClientFactory, diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 725ddfe0c55be..f819fd64ca305 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -1,12 +1,13 @@ +import { vi } from "vite-plus/test"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as CodexInstallation from "./CodexInstallation.ts"; +import * as CodexManagedTokenBroker from "./CodexManagedTokenBroker.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, it, assert, expect } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Path from "effect/Path"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -17,7 +18,6 @@ import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import * as CodexErrors from "effect-codex-app-server/errors"; import { EnvironmentId, ClaudeSettings, @@ -27,11 +27,11 @@ import { ProviderDriverKind, ProviderInstanceId, ServerSettings, - type ServerProvider, + ServerSettingsError, + ServerProvider, type ServerProviderSlashCommand, type ServerSettings as ContractServerSettings, } from "@t3tools/contracts"; -import * as PlatformError from "effect/PlatformError"; import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import { deepMerge } from "@t3tools/shared/Struct"; @@ -65,7 +65,12 @@ import type { } from "@t3tools/provider-core/server/driver"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; +import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; +vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); + +const decodeServerProvider = Schema.decodeSync(ServerProvider); +const encodeServerProvider = Schema.encodeSync(ServerProvider); const decodeServerSettings = Schema.decodeSync(ServerSettings); const encodeServerSettings = Schema.encodeSync(ServerSettings); const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS); @@ -82,10 +87,6 @@ const disabledDefaultSlots = ( const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({}); const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({}); -const decodeCodexSettings = Schema.decodeSync(CodexSettings); -const disabledCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({ - enabled: false, -}); process.env.T3CODE_CURSOR_ENABLED = "1"; @@ -180,9 +181,6 @@ function claudeCapabilities(overrides: Partial = {}) { }); } -const noClaudeCapabilities = () => - Effect.sync(() => undefined as TestClaudeCapabilities | undefined); - function mockHandle(result: { stdout: string; stderr: string; code: number }) { return ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), @@ -215,92 +213,6 @@ function layerMockSpawner( ); } -function recordingMockSpawnerLayer( - handler: (args: ReadonlyArray) => { - stdout: string; - stderr: string; - code: number; - }, -) { - const commands: Array<{ - readonly args: ReadonlyArray; - readonly env: NodeJS.ProcessEnv | undefined; - }> = []; - const layer = Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make((command) => { - const cmd = command as unknown as { - args: ReadonlyArray; - options?: { - readonly env?: NodeJS.ProcessEnv; - }; - }; - commands.push({ args: cmd.args, env: cmd.options?.env }); - return Effect.succeed(mockHandle(handler(cmd.args))); - }), - ); - return { layer, commands }; -} - -function layerMockCommandSpawner( - handler: ( - command: string, - args: ReadonlyArray, - ) => { stdout: string; stderr: string; code: number }, -) { - return Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make((command) => { - const cmd = command as unknown as { - command: string; - args: ReadonlyArray; - }; - return Effect.succeed(mockHandle(handler(cmd.command, cmd.args))); - }), - ); -} - -function layerFailingSpawner(description: string) { - return Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.fail( - PlatformError.systemError({ - _tag: "NotFound", - module: "ChildProcess", - method: "spawn", - description, - }), - ), - ), - ); -} - -function layerHangingScopedSpawner(killCalls: Ref.Ref) { - return Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.gen(function* () { - const handle = ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(1), - exitCode: Effect.never, - isRunning: Effect.succeed(true), - kill: () => Ref.update(killCalls, (current) => current + 1), - unref: Effect.succeed(Effect.void), - stdin: Sink.drain, - stdout: Stream.never, - stderr: Stream.never, - all: Stream.never, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }); - yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore)); - return handle; - }), - ), - ); -} - const codexModelCapabilities = createModelCapabilities({ optionDescriptors: [ selectDescriptor("reasoningEffort", "Reasoning", [ @@ -394,7 +306,11 @@ const awaitPersistedProvider = ( ); const layerTestNodeServices = Layer.mergeAll( + ProviderLatestVersions.layer, NodeServices.layer, + Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({ + endpoint: Effect.succeed("unused-private-pipe"), + }), Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "unused-managed-installation", }), @@ -430,8 +346,9 @@ it.layer( assert.strictEqual(status.version, "1.0.0"); assert.strictEqual(status.auth.status, "authenticated"); assert.strictEqual(status.auth.type, "chatgpt"); - assert.strictEqual(status.auth.label, "ChatGPT Pro 20x Subscription"); + assert.strictEqual(status.auth.label, "ChatGPT Pro 200 Subscription"); assert.strictEqual(status.auth.email, "test@example.com"); + assert.deepStrictEqual(status.setup, { canAuthenticate: false, canInstall: false }); assert.deepStrictEqual(status.models, [ { slug: "gpt-live-codex", @@ -464,21 +381,6 @@ it.layer( }), ); - it.effect("passes configured launch args to the Codex provider probe", () => - Effect.gen(function* () { - let observedLaunchArgs: string | undefined; - const settings = decodeCodexSettings({ launchArgs: "--strict-config --enable foo" }); - - const status = yield* checkCodexProviderStatus(settings, (input) => { - observedLaunchArgs = input.launchArgs; - return Effect.succeed(makeCodexProbeSnapshot()); - }); - - assert.strictEqual(status.status, "ready"); - assert.strictEqual(observedLaunchArgs, "--strict-config --enable foo"); - }), - ); - it.effect("returns unauthenticated when app-server requires OpenAI auth", () => Effect.gen(function* () { const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => @@ -498,6 +400,10 @@ it.layer( status.message, "Codex CLI is not authenticated. Run `codex login` and try again.", ); + assert.deepStrictEqual(status.usageLimits?.unavailable, { + reason: "probeFailed", + message: "Codex CLI is not authenticated. Run `codex login` and try again.", + }); }), ); @@ -518,117 +424,10 @@ it.layer( assert.strictEqual(status.auth.status, "unknown"); }), ); - - it.effect("returns an api key label for codex api key auth", () => - Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => - Effect.succeed( - makeCodexProbeSnapshot({ - account: { - account: { type: "apiKey" }, - requiresOpenaiAuth: false, - }, - }), - ), - ); - - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "apiKey"); - assert.strictEqual(status.auth.label, "OpenAI API Key"); - }), - ); - - it.effect("returns an Amazon Bedrock label for codex Bedrock auth", () => - Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(defaultCodexSettings, () => - Effect.succeed( - makeCodexProbeSnapshot({ - account: { - account: { type: "amazonBedrock" }, - requiresOpenaiAuth: false, - }, - }), - ), - ); - - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "amazonBedrock"); - assert.strictEqual(status.auth.label, "Amazon Bedrock"); - }), - ); - - it.effect.each([ - "codex", - "/Applications/Custom App.app/Contents/Resources/codex", - "C:\\Tools\\codex.exe", - ])("explains how to configure a Codex executable that cannot start: %s", (binaryPath) => - Effect.gen(function* () { - const settings = { ...defaultCodexSettings, binaryPath }; - const status = yield* checkCodexProviderStatus(settings, (input) => { - assert.strictEqual(input.binaryPath, binaryPath); - return Effect.fail( - new CodexErrors.CodexAppServerSpawnError({ - command: `${binaryPath} app-server`, - cause: new Error("spawn ENOENT"), - }), - ); - }); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, false); - assert.strictEqual(status.auth.status, "unknown"); - assert.include(status.message, binaryPath); - assert.include(status.message, "Settings → Providers → Codex → Binary path on the server"); - assert.strictEqual( - status.message?.includes("Installing ChatGPT or Codex desktop"), - binaryPath === "codex", - ); - assert.strictEqual(settings.binaryPath, binaryPath); - }), - ); - - it.effect( - "does not time out a healthy probe slower than the shared 10s auth-probe timeout (#7513)", - () => - Effect.gen(function* () { - const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings, () => - Effect.sleep("15 seconds").pipe(Effect.as(makeCodexProbeSnapshot())), - ).pipe(Effect.forkChild); - - yield* Effect.yieldNow; - yield* TestClock.adjust("15 seconds"); - - const status = yield* Fiber.join(statusFiber); - assert.strictEqual(status.status, "ready"); - }), - ); - - it.effect("closes the app-server probe scope when provider status times out", () => - Effect.gen(function* () { - const killCalls = yield* Ref.make(0); - const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe( - Effect.provide(layerHangingScopedSpawner(killCalls)), - Effect.forkChild, - ); - - yield* Effect.yieldNow; - yield* TestClock.adjust("21 seconds"); - yield* Effect.yieldNow; - - const status = yield* Fiber.join(statusFiber); - assert.strictEqual(status.status, "error"); - assert.strictEqual( - status.message, - "Timed out while checking Codex app-server provider status.", - ); - assert.strictEqual(yield* Ref.get(killCalls), 1); - }), - ); }); describe("ProviderRegistry.layer", () => { - it("stores workspace skills and commands without changing machine metadata", () => { + it("stores workspace skills, commands and options without changing machine metadata", () => { const provider = { instanceId: ProviderInstanceId.make("codex"), driver: ProviderDriverKind.make("codex"), @@ -647,7 +446,15 @@ it.layer( checkedAt: "2026-03-25T00:01:00.000Z", slashCommands: [{ name: "project" }], skills: [{ name: "project", path: "/project/SKILL.md", enabled: true }], - } satisfies ServerProvider; + optionDescriptors: [ + { + id: "agent", + label: "Agent", + type: "select", + options: [{ id: "readonly", label: "Readonly" }], + }, + ], + } satisfies ProviderWorkspaceSnapshot; const result = ProviderRegistry.upsertProviderWorkspaceSnapshot( provider, @@ -657,12 +464,15 @@ it.layer( assert.deepStrictEqual(result.slashCommands, provider.slashCommands); assert.deepStrictEqual(result.skills, provider.skills); - assert.deepStrictEqual(result.workspaceSnapshots, [ + assert.strictEqual(result.models, provider.models); + const decoded = decodeServerProvider(encodeServerProvider(result)); + assert.deepStrictEqual(decoded.workspaceSnapshots, [ { cwd: "/project", checkedAt: scopedSnapshot.checkedAt, slashCommands: scopedSnapshot.slashCommands, skills: scopedSnapshot.skills, + optionDescriptors: scopedSnapshot.optionDescriptors, }, ]); @@ -695,6 +505,47 @@ it.layer( { name: "replacement" }, ]); assert.strictEqual(recovered.workspaceSnapshots?.[0]?.slashCommandsPending, undefined); + + const { optionDescriptors, ...failedSnapshot } = scopedSnapshot; + const firstFailure = ProviderRegistry.upsertProviderWorkspaceSnapshot( + provider, + "/project", + failedSnapshot, + ); + assert.strictEqual( + Object.hasOwn(firstFailure.workspaceSnapshots![0]!, "optionDescriptors"), + false, + ); + const failedOtherProject = ProviderRegistry.upsertProviderWorkspaceSnapshot( + recovered, + "/other-project", + failedSnapshot, + ); + assert.strictEqual( + Object.hasOwn(failedOtherProject.workspaceSnapshots![1]!, "optionDescriptors"), + false, + ); + + for (const clearedDescriptors of [[], [{ ...optionDescriptors[0]!, options: [] }]]) { + const cleared = ProviderRegistry.upsertProviderWorkspaceSnapshot(recovered, "/project", { + ...scopedSnapshot, + optionDescriptors: clearedDescriptors, + }); + assert.deepStrictEqual( + cleared.workspaceSnapshots?.[0]?.optionDescriptors, + clearedDescriptors, + ); + } + + const failedRefresh = ProviderRegistry.upsertProviderWorkspaceSnapshot( + failedOtherProject, + "/project", + failedSnapshot, + ); + assert.deepStrictEqual( + failedRefresh.workspaceSnapshots?.[1]?.optionDescriptors, + optionDescriptors, + ); }); it("preserves previously discovered provider models when a refresh returns none", () => { @@ -755,45 +606,6 @@ it.layer( ); }); - it("drops custom models the refreshed snapshot no longer carries", () => { - const previousProvider = { - instanceId: ProviderInstanceId.make("claudeAgent"), - driver: ProviderDriverKind.make("claudeAgent"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-14T00:00:00.000Z", - version: "2.1.0", - models: [ - { - slug: "claude-sonnet-4-6", - name: "Sonnet 4.6", - isCustom: false, - capabilities: null, - }, - { - slug: "removed-custom", - name: "removed-custom", - isCustom: true, - capabilities: null, - }, - ], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshedProvider = { - ...previousProvider, - checkedAt: "2026-04-14T00:01:00.000Z", - models: [previousProvider.models[0]], - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models, - [...refreshedProvider.models], - ); - }); - it("does not bring back models the installed CLI is too old to run", () => { const pendingProvider = { instanceId: ProviderInstanceId.make("claudeAgent"), @@ -827,41 +639,6 @@ it.layer( ); }); - it("drops stale ACP Registry models missing from a completed discovery probe", () => { - const previousProvider = { - instanceId: ProviderInstanceId.make("acpRegistry_codex"), - driver: ProviderDriverKind.make("acpRegistry"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-08-13T00:00:00.000Z", - version: "1.2.0", - models: [ - { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null }, - { - slug: "gpt-5.6-sol[low]", - name: "GPT-5.6-Sol (low)", - isCustom: false, - capabilities: null, - }, - { slug: "default", name: "Default", isCustom: false, capabilities: null }, - ], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshedProvider = { - ...previousProvider, - checkedAt: "2026-08-13T00:01:00.000Z", - models: [{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null }], - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models, - [...refreshedProvider.models], - ); - }); - it("retains ACP Registry models while discovery has not completed", () => { const previousProvider = { instanceId: ProviderInstanceId.make("acpRegistry_codex"), @@ -880,11 +657,17 @@ it.layer( ...previousProvider, checkedAt: "2026-08-13T00:01:00.000Z", auth: { status: "unknown" }, + message: "Checking ACP authentication, models, and commands in the background...", models: [{ slug: "default", name: "Default", isCustom: false, capabilities: null }], } satisfies ServerProvider; + const confirmedCheckingProvider = { + ...checkingProvider, + auth: { status: "authenticated" }, + } satisfies ServerProvider; const failedProbeProvider = { ...checkingProvider, status: "warning", + message: "ACP discovery failed.", } satisfies ServerProvider; assert.deepStrictEqual( @@ -895,60 +678,18 @@ it.layer( ], ); assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, failedProbeProvider).models, + ProviderRegistry.mergeProviderSnapshot(previousProvider, confirmedCheckingProvider).models, [ { slug: "default", name: "Default", isCustom: false, capabilities: null }, { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null }, ], ); - }); - - it("drops stale OpenCode models missing from a successful refresh", () => { - const previousProvider = { - instanceId: ProviderInstanceId.make("opencode"), - driver: ProviderDriverKind.make("opencode"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-07-17T00:00:00.000Z", - version: "1.0.0", - models: [ - { - slug: "github/gpt-5", - name: "GPT-5", - subProvider: "GitHub", - isCustom: false, - capabilities: null, - }, - { - slug: "removed-plugin/model", - name: "Removed Plugin Model", - subProvider: "Removed Plugin", - isCustom: false, - capabilities: null, - }, - ], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshedProvider = { - ...previousProvider, - checkedAt: "2026-07-17T00:01:00.000Z", - models: [ - { - slug: "github/gpt-5", - name: "GPT-5", - subProvider: "GitHub", - isCustom: false, - capabilities: null, - }, - ], - } satisfies ServerProvider; - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, refreshedProvider).models, - [...refreshedProvider.models], + ProviderRegistry.mergeProviderSnapshot(previousProvider, failedProbeProvider).models, + [ + { slug: "default", name: "Default", isCustom: false, capabilities: null }, + { slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null }, + ], ); }); @@ -1004,116 +745,6 @@ it.layer( ); }); - it("classifies pending, logout, uninstall, and reconnect OpenCode inventories", () => { - const previousProvider = { - instanceId: ProviderInstanceId.make("opencode"), - driver: ProviderDriverKind.make("opencode"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-07-17T00:00:00.000Z", - version: "1.0.0", - models: [ - { - slug: "github/gpt-5", - name: "GPT-5", - subProvider: "GitHub", - isCustom: false, - capabilities: null, - }, - { - slug: "removed-plugin/model", - name: "Removed Plugin Model", - subProvider: "Removed Plugin", - isCustom: false, - capabilities: null, - }, - ], - slashCommands: [{ name: "review", description: "Review changes" }], - skills: [ - { - name: "typescript", - description: "TypeScript help", - path: "/skills/typescript/SKILL.md", - enabled: true, - }, - ], - } as const satisfies ServerProvider; - const pendingProvider = { - ...previousProvider, - status: "warning", - installed: false, - auth: { status: "unknown" }, - checkedAt: "2026-07-17T00:01:00.000Z", - version: null, - models: [], - message: "OpenCode provider status has not been checked in this session yet.", - } satisfies ServerProvider; - const loggedOutProvider = { - ...previousProvider, - status: "warning", - auth: { status: "unknown" }, - checkedAt: "2026-07-17T00:02:00.000Z", - models: [], - slashCommands: [], - skills: [], - message: "OpenCode is available, but it did not report any connected upstream providers.", - } satisfies ServerProvider; - const missingProvider = { - ...previousProvider, - status: "error", - installed: false, - auth: { status: "unknown" }, - checkedAt: "2026-07-17T00:03:00.000Z", - version: null, - models: [], - message: "OpenCode CLI (`opencode`) is not installed or not on PATH.", - } satisfies ServerProvider; - const authoritativeProvider = { - ...previousProvider, - checkedAt: "2026-07-17T00:04:00.000Z", - models: [previousProvider.models[0]!], - } satisfies ServerProvider; - const failedProvider = { - ...authoritativeProvider, - status: "error", - auth: { status: "unknown" }, - checkedAt: "2026-07-17T00:05:00.000Z", - models: [], - message: "Failed to refresh OpenCode models.", - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, pendingProvider).models, - [...previousProvider.models], - ); - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, loggedOutProvider).models, - [], - ); - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, loggedOutProvider).slashCommands, - [], - ); - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, loggedOutProvider).skills, - [], - ); - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, missingProvider).models, - [], - ); - - const afterRemoval = ProviderRegistry.mergeProviderSnapshot( - previousProvider, - authoritativeProvider, - ); - const afterFailure = ProviderRegistry.mergeProviderSnapshot(afterRemoval, failedProvider); - - assert.deepStrictEqual(afterFailure.models, [authoritativeProvider.models[0]!]); - }); - describe("Pi model inventories", () => { const defaultModel = { slug: "default", @@ -1177,27 +808,6 @@ it.layer( message: "Pi is available, but T3 Code could not refresh its models and commands.", } satisfies ServerProvider; - it("drops disconnected Pi upstream models after successful discovery", () => { - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(cachedProvider, refreshedProvider).models, - refreshedProvider.models, - ); - }); - - it("clears discovered Pi models when successful discovery finds no usable models", () => { - const signedOutProvider = { - ...refreshedProvider, - status: "warning", - auth: { status: "unauthenticated", type: "pi" }, - models: [defaultModel, customModel], - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(cachedProvider, signedOutProvider).models, - signedOutProvider.models, - ); - }); - it("retains Pi inventories during incomplete probes without restoring removed custom models", () => { const incompleteProviders = [ pendingProvider, @@ -1357,51 +967,6 @@ it.layer( installed: true, } satisfies ServerProvider; - it("drops retired alpha models after discovery, including without OpenAI authentication", () => { - for (const authStatus of ["authenticated", "unknown"] as const) { - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(cachedProvider, { - ...refreshedProvider, - auth: { status: authStatus }, - }).models, - refreshedProvider.models, - ); - } - }); - - it("keeps discovered models during startup and failed probes without restoring removed custom models", () => { - for (const provider of [pendingProvider, failedProvider]) { - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot( - { - ...cachedProvider, - models: [...cachedProvider.models, { ...customModel, slug: "removed-custom" }], - }, - provider, - ).models, - [customModel, ...cachedProvider.models], - ); - } - }); - - it("clears discovered models after sign-out, disable, uninstall, or empty discovery", () => { - const emptyProvider = { ...refreshedProvider, models: [customModel] }; - const clearedProviders = [ - { ...emptyProvider, status: "error", auth: { status: "unauthenticated" } }, - { ...emptyProvider, status: "disabled", enabled: false }, - { ...emptyProvider, status: "error", installed: false, auth: { status: "unknown" } }, - emptyProvider, - { ...emptyProvider, models: [] }, - ] satisfies ReadonlyArray; - - for (const provider of clearedProviders) { - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(cachedProvider, provider).models, - provider.models, - ); - } - }); - it.effect("persists removals across failed refreshes and registry restarts", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -1516,65 +1081,6 @@ it.layer( skills: [], } as const satisfies ServerProvider; - it("removes unavailable models after a successful refresh", () => { - for (const status of ["ready", "warning"] as const) { - const refreshedProvider = { - ...previousProvider, - status, - checkedAt: "2026-09-02T00:01:00.000Z", - models: [previousProvider.models[1]], - } satisfies ServerProvider; - const afterRefresh = ProviderRegistry.mergeProviderSnapshot( - previousProvider, - refreshedProvider, - ); - - assert.deepStrictEqual(afterRefresh.models, refreshedProvider.models); - - const afterFailure = ProviderRegistry.mergeProviderSnapshot(afterRefresh, { - ...refreshedProvider, - status: "error", - auth: { status: "unknown" }, - models: [], - }); - assert.deepStrictEqual(afterFailure.models, refreshedProvider.models); - } - }); - - it("keeps cached models during health checks and temporary failures", () => { - for (const installed of [false, true]) { - const pendingProvider = { - ...previousProvider, - status: "warning", - installed, - auth: { status: "unknown" }, - checkedAt: "2026-09-02T00:01:00.000Z", - version: installed ? previousProvider.version : null, - models: [], - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, pendingProvider).models, - previousProvider.models, - ); - } - - for (const authStatus of ["unknown", "authenticated"] as const) { - const failedProvider = { - ...previousProvider, - status: "error", - auth: { status: authStatus }, - checkedAt: "2026-09-02T00:02:00.000Z", - models: [], - } satisfies ServerProvider; - - assert.deepStrictEqual( - ProviderRegistry.mergeProviderSnapshot(previousProvider, failedProvider).models, - previousProvider.models, - ); - } - }); - it("clears models after sign-out, disable, uninstall, or an empty successful refresh", () => { const emptyProvider = { ...previousProvider, @@ -1652,31 +1158,6 @@ it.layer( ); }); - it("carries the account through the boot probe and a failed probe without hiding them", () => { - const booting = { - ...restartProbe, - installed: false, - version: null, - message: "Checking Antigravity availability.", - } satisfies ServerProvider; - assert.deepStrictEqual(ProviderRegistry.mergeProviderSnapshot(signedIn, booting), { - ...booting, - auth: signedIn.auth, - models: signedIn.models, - }); - - const failed = { - ...restartProbe, - status: "error", - message: "Antigravity did not respond to its local health check within 90 seconds.", - } satisfies ServerProvider; - assert.deepStrictEqual(ProviderRegistry.mergeProviderSnapshot(signedIn, failed), { - ...failed, - auth: signedIn.auth, - models: signedIn.models, - }); - }); - it("does not invent an account after sign-out, disable, uninstall, or for other providers", () => { const untouched = [ { ...restartProbe, auth: { status: "unauthenticated" } }, @@ -1765,57 +1246,64 @@ it.layer( ); }); - it.effect("does not run provider probes during layer construction", () => + it.effect("publishes workspace skills while machine health is in error", () => Effect.gen(function* () { - const codexDriver = ProviderDriverKind.make("codex"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const initialProvider = { - instanceId: codexInstanceId, - driver: codexDriver, - status: "warning", + const driver = ProviderDriverKind.make("codex"); + const instanceId = ProviderInstanceId.make("codex"); + const healthyProvider = { + instanceId, + driver, + status: "ready", enabled: true, - installed: false, - auth: { status: "unknown" }, + installed: true, + auth: { status: "authenticated" }, checkedAt: "2026-06-10T00:00:00.000Z", - version: null, - message: "Checking Codex provider status.", + version: "1.0.0", models: [], - slashCommands: [], + slashCommands: [COMPACT_SLASH_COMMAND], skills: [], } as const satisfies ServerProvider; - const refreshCalls = yield* Ref.make(0); - const instance = { - instanceId: codexInstanceId, - driverKind: codexDriver, - continuationIdentity: { - driverKind: codexDriver, - continuationKey: "codex:instance:codex", - }, + const unhealthyProvider = { + ...healthyProvider, + status: "error", + auth: { status: "unknown" }, + message: "Codex app-server provider probe failed: unauthorized (401).", + slashCommands: [], + } as const satisfies ServerProvider; + const firstSkills = [{ name: "first", path: "/workspace/first/SKILL.md", enabled: true }]; + const laterSkills = [{ name: "later", path: "/workspace/later/SKILL.md", enabled: true }]; + const scanResult = yield* Ref.make({ + ...healthyProvider, + skills: firstSkills, + }); + const instance: ProviderInstance = { + instanceId, + driverKind: driver, + continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" }, displayName: undefined, enabled: true, snapshot: { resolveMaintenance: () => Effect.succeed( makeManualOnlyProviderMaintenanceCapabilities({ - provider: codexDriver, + provider: driver, packageName: null, }), ), - getSnapshot: Effect.succeed(initialProvider), - refresh: Ref.update(refreshCalls, (count) => count + 1).pipe( - Effect.andThen(Effect.never), - ), + getSnapshot: Effect.succeed(unhealthyProvider), + refresh: Effect.succeed(unhealthyProvider), streamChanges: Stream.empty, applyUsageLimits: () => Effect.void, }, + snapshotForCwd: () => Ref.get(scanResult), orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], textGeneration: {} as ProviderInstance["textGeneration"], - } satisfies ProviderInstance; + }; const layerInstanceRegistry = Layer.succeed( ProviderInstanceRegistry.ProviderInstanceRegistry, { - getInstance: (instanceId) => - Effect.succeed(instanceId === codexInstanceId ? instance : undefined), + getInstance: (requestedId) => + Effect.succeed(requestedId === instanceId ? instance : undefined), listInstances: Effect.succeed([instance]), listUnavailable: Effect.succeed([]), streamChanges: Stream.empty, @@ -1829,25 +1317,64 @@ it.layer( Layer.provideMerge(layerInstanceRegistry), Layer.provideMerge( ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-background-refresh-", + prefix: "t3-provider-registry-unhealthy-workspace-", }), ), Layer.provideMerge(NodeServices.layer), ), ).pipe(Scope.provide(scope)); + yield* Effect.gen(function* () { const registry = yield* ProviderRegistry.ProviderRegistry; - assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]); - assert.strictEqual(yield* Ref.get(refreshCalls), 0); + const workspaceOf = Effect.map( + registry.getProviders, + (providers) => providers[0]?.workspaceSnapshots?.[0], + ); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); + assert.deepStrictEqual((yield* workspaceOf)?.slashCommands, [COMPACT_SLASH_COMMAND]); + + yield* TestClock.adjust(PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS); + yield* Ref.set(scanResult, { ...unhealthyProvider, skills: laterSkills }); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); + const unhealthy = yield* workspaceOf; + assert.deepStrictEqual(unhealthy?.skills, laterSkills); + assert.deepStrictEqual(unhealthy?.slashCommands, [COMPACT_SLASH_COMMAND]); + assert.strictEqual(unhealthy?.slashCommandsPending, true); + const provider = (yield* registry.getProviders)[0]; + assert.strictEqual(provider?.status, "error"); + assert.strictEqual(provider?.message, unhealthyProvider.message); + + yield* Ref.set(scanResult, { ...unhealthyProvider, skills: [] }); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); + assert.deepStrictEqual((yield* workspaceOf)?.skills, []); + + const discoveredCommand = { name: "review", description: "Review changes" }; + yield* Ref.set(scanResult, { + ...unhealthyProvider, + slashCommands: [discoveredCommand], + slashCommandsPending: false, + }); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); + const discovered = yield* workspaceOf; + assert.deepStrictEqual(discovered?.slashCommands, [discoveredCommand]); + assert.strictEqual(discovered?.slashCommandsPending, undefined); + + yield* TestClock.adjust(PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS); + yield* Ref.set(scanResult, { ...healthyProvider, skills: laterSkills }); + yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); + const recovered = yield* workspaceOf; + assert.deepStrictEqual(recovered?.skills, laterSkills); + assert.deepStrictEqual(recovered?.slashCommands, [COMPACT_SLASH_COMMAND]); + assert.strictEqual(recovered?.slashCommandsPending, undefined); }).pipe(Effect.provide(runtimeServices)); }), ); - it.effect("deduplicates cwd probes and clears snapshots when an instance rebuilds", () => + it.effect("shares one in-flight pass between concurrent untargeted refreshes", () => Effect.gen(function* () { const driver = ProviderDriverKind.make("codex"); const instanceId = ProviderInstanceId.make("codex"); - const machineProvider = { + const provider = { instanceId, driver, status: "ready", @@ -1857,533 +1384,39 @@ it.layer( checkedAt: "2026-06-10T00:00:00.000Z", version: "1.0.0", models: [], - slashCommands: [{ name: "global" }], - skills: [{ name: "global", path: "/global/SKILL.md", enabled: true }], - } as const satisfies ServerProvider; - const scopedProvider = { - ...machineProvider, - checkedAt: "2026-06-10T00:01:00.000Z", - slashCommands: [{ name: "project" }], - skills: [{ name: "project", path: "/workspace/SKILL.md", enabled: true }], - } as const satisfies ServerProvider; - const pendingScopedProvider = { - ...scopedProvider, - status: "error", - installed: false, slashCommands: [], + skills: [], } as const satisfies ServerProvider; - const snapshotCalls = yield* Ref.make(0); - const scopedResult = yield* Ref.make({ - ...scopedProvider, - status: "error", - slashCommands: [COMPACT_SLASH_COMMAND], - slashCommandsPending: true, - }); - const cacheInvalidations = yield* Ref.make(0); - const scanGate = yield* Ref.make<{ - readonly started: Deferred.Deferred; - readonly release: Deferred.Deferred; - } | null>(null); - const returnPendingSnapshot = yield* Ref.make(true); + const refreshCalls = yield* Ref.make(0); const probeStarted = yield* Deferred.make(); const releaseProbe = yield* Deferred.make(); - const makeInstance = ( - provider: ServerProvider, - snapshotForCwd: NonNullable, - ): ProviderInstance => ({ - instanceId, - driverKind: driver, - continuationIdentity: { + const instances = [ + { + instanceId, driverKind: driver, - continuationKey: "codex:instance:codex", - }, - displayName: undefined, - enabled: true, - snapshot: { - resolveMaintenance: () => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ - provider: driver, - packageName: null, - }), - ), - getSnapshot: Effect.succeed(provider), - refresh: Effect.succeed(provider), - streamChanges: Stream.empty, - applyUsageLimits: () => Effect.void, - }, - snapshotForCwd, - invalidateCaches: Ref.update(cacheInvalidations, (count) => count + 1), - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - }); - const firstInstance = makeInstance(machineProvider, () => - Effect.gen(function* () { - yield* Ref.update(snapshotCalls, (count) => count + 1); - if (yield* Ref.get(returnPendingSnapshot)) return pendingScopedProvider; - yield* Deferred.succeed(probeStarted, undefined); - yield* Deferred.await(releaseProbe); - const result = yield* Ref.get(scopedResult); - const gate = yield* Ref.getAndSet(scanGate, null); - if (gate) { - yield* Deferred.succeed(gate.started, undefined); - yield* Deferred.await(gate.release); - } - return result; - }), - ); - const rebuiltProvider = { - ...machineProvider, - checkedAt: "2026-06-10T00:02:00.000Z", - status: "warning", - installed: false, - auth: { status: "unknown" }, - } satisfies ServerProvider; - const rebuiltInstance = makeInstance(rebuiltProvider, () => - Ref.update(snapshotCalls, (count) => count + 1).pipe(Effect.as(scopedProvider)), - ); - const registryChanges = yield* PubSub.unbounded(); - const instancesRef = yield* Ref.make>([firstInstance]); - const layerInstanceRegistry = Layer.succeed( - ProviderInstanceRegistry.ProviderInstanceRegistry, - { - getInstance: (requestedId) => - Ref.get(instancesRef).pipe( - Effect.map((instances) => - instances.find((instance) => instance.instanceId === requestedId), - ), - ), - listInstances: Ref.get(instancesRef), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.fromPubSub(registryChanges), - subscribeChanges: PubSub.subscribe(registryChanges), - }, - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const runtimeServices = yield* Layer.build( - ProviderRegistry.layer.pipe( - Layer.provideMerge(layerInstanceRegistry), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-workspace-snapshot-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); - assert.strictEqual((yield* registry.getProviders)[0]?.workspaceSnapshots, undefined); - yield* Ref.set(returnPendingSnapshot, false); - const workspaceUpdate = yield* registry.streamChanges.pipe( - Stream.runHead, - Effect.forkChild, - ); - yield* Effect.yieldNow; - const firstRefresh = yield* registry - .refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }) - .pipe(Effect.forkChild); - yield* Deferred.await(probeStarted); - const duplicateRefresh = yield* registry - .refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }) - .pipe(Effect.forkChild); - yield* Effect.yieldNow; - assert.strictEqual(yield* Ref.get(snapshotCalls), 2); - yield* Deferred.succeed(releaseProbe, undefined); - yield* Fiber.join(firstRefresh); - yield* Fiber.join(duplicateRefresh); - const published = yield* Fiber.join(workspaceUpdate); - assert.strictEqual(published._tag, "Some"); - const providers = yield* registry.getProviders; - assert.deepStrictEqual(providers[0]?.skills, machineProvider.skills); - assert.deepStrictEqual( - providers[0]?.workspaceSnapshots?.[0]?.skills, - scopedProvider.skills, - ); - assert.deepStrictEqual(providers[0]?.workspaceSnapshots?.[0]?.slashCommands, [ - COMPACT_SLASH_COMMAND, - ]); - assert.strictEqual(providers[0]?.workspaceSnapshots?.[0]?.slashCommandsPending, true); - yield* Ref.set(scopedResult, { - ...scopedProvider, - status: "error", - slashCommandsPending: false, - }); - yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); - assert.strictEqual(yield* Ref.get(snapshotCalls), 3); - assert.deepStrictEqual( - (yield* registry.getProviders)[0]?.workspaceSnapshots?.[0]?.slashCommands, - scopedProvider.slashCommands, - ); - assert.strictEqual( - (yield* registry.getProviders)[0]?.workspaceSnapshots?.[0]?.slashCommandsPending, - undefined, - ); - yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); - assert.strictEqual(yield* Ref.get(snapshotCalls), 3); - yield* TestClock.adjust(PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS - 1); - yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); - assert.strictEqual(yield* Ref.get(snapshotCalls), 3); - yield* TestClock.adjust(1); - yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace" }); - assert.strictEqual(yield* Ref.get(snapshotCalls), 4); - const newSkills = [ - ...scopedProvider.skills, - { name: "added", path: "/workspace/added/SKILL.md", enabled: true }, - ]; - yield* Ref.set(scopedResult, { ...scopedProvider, skills: newSkills }); - yield* registry.refreshWorkspaceSnapshot({ - instanceId, - cwd: "/workspace", - fresh: true, - }); - assert.strictEqual(yield* Ref.get(snapshotCalls), 5); - assert.strictEqual(yield* Ref.get(cacheInvalidations), 1); - assert.deepStrictEqual( - (yield* registry.getProviders)[0]?.workspaceSnapshots?.map((s) => s.skills), - [newSkills], - ); - - const slowStarted = yield* Deferred.make(); - const releaseSlow = yield* Deferred.make(); - yield* Ref.set(scanGate, { started: slowStarted, release: releaseSlow }); - yield* Ref.set(scopedResult, scopedProvider); - const slowScan = yield* registry - .refreshWorkspaceSnapshot({ instanceId, cwd: "/workspace", fresh: true }) - .pipe(Effect.forkChild); - yield* Deferred.await(slowStarted); - const latestSkills = [ - ...newSkills, - { name: "latest", path: "/workspace/latest/SKILL.md", enabled: true }, - ]; - yield* Ref.set(scopedResult, { ...scopedProvider, skills: latestSkills }); - yield* registry.refreshWorkspaceSnapshot({ - instanceId, - cwd: "/workspace", - fresh: true, - }); - yield* Deferred.succeed(releaseSlow, undefined); - yield* Fiber.join(slowScan); - assert.deepStrictEqual( - (yield* registry.getProviders)[0]?.workspaceSnapshots?.map((s) => s.skills), - [latestSkills], - ); - - yield* Ref.set(instancesRef, [rebuiltInstance]); - yield* PubSub.publish(registryChanges, undefined); - let rebuilt = yield* registry.getProviders; - for ( - let attempt = 0; - attempt < 50 && rebuilt[0]?.checkedAt !== rebuiltProvider.checkedAt; - attempt += 1 - ) { - yield* Effect.yieldNow; - rebuilt = yield* registry.getProviders; - } - assert.strictEqual(rebuilt[0]?.checkedAt, rebuiltProvider.checkedAt); - assert.strictEqual(rebuilt[0]?.workspaceSnapshots, undefined); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it.effect("refreshes OpenCode catalogs and preserves other providers", () => - Effect.gen(function* () { - const codexDriver = ProviderDriverKind.make("codex"); - const openCodeDriver = ProviderDriverKind.make("opencode"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const openCodeInstanceId = ProviderInstanceId.make("opencode"); - const codexRefreshCalls = yield* Ref.make(0); - const openCodeRefreshCalls = yield* Ref.make(0); - const codexProvider = { - instanceId: codexInstanceId, - driver: codexDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-06-10T00:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const failedOpenCodeProvider = { - instanceId: openCodeInstanceId, - driver: openCodeDriver, - status: "error", - enabled: true, - installed: true, - auth: { status: "unknown" }, - checkedAt: "2026-06-10T00:00:00.000Z", - version: "1.0.0", - message: "Failed to refresh OpenCode models.", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const recoveredOpenCodeProvider = { - ...failedOpenCodeProvider, - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-06-10T00:01:00.000Z", - message: "One upstream provider connected through OpenCode.", - models: [ - { - slug: "github/gpt-5", - name: "GPT-5", - subProvider: "GitHub", - isCustom: false, - capabilities: null, - }, - ], - } as const satisfies ServerProvider; - const changedCatalogProvider = { - ...recoveredOpenCodeProvider, - checkedAt: "2026-06-10T00:02:00.000Z", - models: [ - { - slug: "anthropic/claude-sonnet-4", - name: "Claude Sonnet 4", - subProvider: "Anthropic", - isCustom: false, - capabilities: null, - }, - ], - } as const satisfies ServerProvider; - const catalogSnapshot = yield* Ref.make(recoveredOpenCodeProvider); - const instances = [ - { - instanceId: codexInstanceId, - driverKind: codexDriver, - continuationIdentity: { - driverKind: codexDriver, - continuationKey: "codex:instance:codex", - }, - displayName: undefined, - enabled: true, - snapshot: { - resolveMaintenance: () => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ - provider: codexDriver, - packageName: null, - }), - ), - getSnapshot: Effect.succeed(codexProvider), - refresh: Ref.update(codexRefreshCalls, (count) => count + 1).pipe( - Effect.as(codexProvider), - ), - streamChanges: Stream.empty, - applyUsageLimits: () => Effect.void, - }, - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - }, - { - instanceId: openCodeInstanceId, - driverKind: openCodeDriver, - continuationIdentity: { - driverKind: openCodeDriver, - continuationKey: "opencode:instance:opencode", - }, - displayName: undefined, - enabled: true, - snapshot: { - resolveMaintenance: () => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ - provider: openCodeDriver, - packageName: null, - }), - ), - getSnapshot: Effect.succeed(failedOpenCodeProvider), - refresh: Ref.update(openCodeRefreshCalls, (count) => count + 1).pipe( - Effect.andThen(Ref.get(catalogSnapshot)), - ), - streamChanges: Stream.empty, - applyUsageLimits: () => Effect.void, - }, - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - }, - ] satisfies ReadonlyArray; - const layerInstanceRegistry = Layer.succeed( - ProviderInstanceRegistry.ProviderInstanceRegistry, - { - getInstance: (instanceId) => - Effect.succeed(instances.find((instance) => instance.instanceId === instanceId)), - listInstances: Effect.succeed(instances), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe), - }, - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const runtimeServices = yield* Layer.build( - ProviderRegistry.layer.pipe( - Layer.provideMerge(layerInstanceRegistry), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-reconnect-refresh-", - }), - ), - Layer.provideMerge(NodeServices.layer), - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - const initialProviders = yield* registry.getProviders; - assert.strictEqual( - initialProviders.find((provider) => provider.instanceId === openCodeInstanceId)?.status, - "error", - ); - - const recoveredProviders = yield* registry.refresh(); - assert.deepStrictEqual( - recoveredProviders.find((provider) => provider.instanceId === openCodeInstanceId) - ?.models, - recoveredOpenCodeProvider.models, - ); - assert.deepStrictEqual( - recoveredProviders.find((provider) => provider.instanceId === codexInstanceId), - withBundledCompatibility(codexProvider), - ); - - yield* Ref.set(catalogSnapshot, changedCatalogProvider); - const changedProviders = yield* registry.refresh(); - assert.deepStrictEqual( - changedProviders.find((provider) => provider.instanceId === openCodeInstanceId)?.models, - changedCatalogProvider.models, - ); - assert.deepStrictEqual( - changedProviders.find((provider) => provider.instanceId === codexInstanceId), - withBundledCompatibility(codexProvider), - ); - }).pipe(Effect.provide(runtimeServices)); - - assert.strictEqual(yield* Ref.get(codexRefreshCalls), 2); - assert.strictEqual(yield* Ref.get(openCodeRefreshCalls), 2); - }), - ); - - it("persists merged provider snapshots for the providers that were refreshed", () => { - const previousProviders = [ - { - instanceId: ProviderInstanceId.make("cursor"), - driver: ProviderDriverKind.make("cursor"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-14T00:00:00.000Z", - version: "2026.04.09-f2b0fcd", - models: [ - { - slug: "claude-opus-4-6", - name: "Opus 4.6", - isCustom: false, - capabilities: createModelCapabilities({ - optionDescriptors: [ - selectDescriptor("reasoning", "Reasoning", [ - { id: "high", label: "High", isDefault: true }, - ]), - booleanDescriptor("fastMode", "Fast Mode"), - booleanDescriptor("thinking", "Thinking"), - ], - }), - }, - ], - slashCommands: [], - skills: [], - }, - { - instanceId: ProviderInstanceId.make("codex"), - driver: ProviderDriverKind.make("codex"), - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-14T00:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - }, - ] as const satisfies ReadonlyArray; - const refreshedCursor = { - ...previousProviders[0], - checkedAt: "2026-04-14T00:01:00.000Z", - models: [], - } satisfies ServerProvider; - - const mergedProviders = ProviderRegistry.mergeProviderSnapshots(previousProviders, [ - refreshedCursor, - ]); - const persistedProviders = ProviderRegistry.selectProvidersByKind( - mergedProviders, - new Set([ProviderDriverKind.make("cursor")]), - ); - - assert.deepStrictEqual(persistedProviders, [ - { - ...refreshedCursor, - models: [...previousProviders[0].models], - }, - ]); - }); - - it.effect("shares one in-flight pass between concurrent untargeted refreshes", () => - Effect.gen(function* () { - const driver = ProviderDriverKind.make("codex"); - const instanceId = ProviderInstanceId.make("codex"); - const provider = { - instanceId, - driver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-06-10T00:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const refreshCalls = yield* Ref.make(0); - const probeStarted = yield* Deferred.make(); - const releaseProbe = yield* Deferred.make(); - const instances = [ - { - instanceId, - driverKind: driver, - continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" }, - displayName: undefined, - enabled: true, - snapshot: { - resolveMaintenance: () => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ - provider: driver, - packageName: null, - }), - ), - getSnapshot: Effect.succeed(provider), - refresh: Effect.gen(function* () { - yield* Ref.update(refreshCalls, (count) => count + 1); - yield* Deferred.succeed(probeStarted, undefined); - yield* Deferred.await(releaseProbe); - return provider; - }), - streamChanges: Stream.empty, - applyUsageLimits: () => Effect.void, - }, - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration: {} as ProviderInstance["textGeneration"], + continuationIdentity: { driverKind: driver, continuationKey: "codex:instance:codex" }, + displayName: undefined, + enabled: true, + snapshot: { + resolveMaintenance: () => + Effect.succeed( + makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver, + packageName: null, + }), + ), + getSnapshot: Effect.succeed(provider), + refresh: Effect.gen(function* () { + yield* Ref.update(refreshCalls, (count) => count + 1); + yield* Deferred.succeed(probeStarted, undefined); + yield* Deferred.await(releaseProbe); + return provider; + }), + streamChanges: Stream.empty, + applyUsageLimits: () => Effect.void, + }, + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], + textGeneration: {} as ProviderInstance["textGeneration"], }, ] satisfies ReadonlyArray; const instanceRegistryLayer = Layer.succeed( @@ -2765,226 +1798,6 @@ it.layer( }), ); - it.effect("keeps consuming registry changes after one sync fails", () => - Effect.gen(function* () { - const codexDriver = ProviderDriverKind.make("codex"); - const codexInstanceId = ProviderInstanceId.make("codex"); - const claudeDriver = ProviderDriverKind.make("claudeAgent"); - const claudeInstanceId = ProviderInstanceId.make("claudeAgent"); - const codexProvider = { - instanceId: codexInstanceId, - driver: codexDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-29T10:00:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const claudeProvider = { - instanceId: claudeInstanceId, - driver: claudeDriver, - status: "ready", - enabled: true, - installed: true, - auth: { status: "authenticated" }, - checkedAt: "2026-04-29T10:01:00.000Z", - version: "1.0.0", - models: [], - slashCommands: [], - skills: [], - } as const satisfies ServerProvider; - const makeInstance = (provider: ServerProvider): ProviderInstance => ({ - instanceId: provider.instanceId, - driverKind: provider.driver, - continuationIdentity: { - driverKind: provider.driver, - continuationKey: `${provider.driver}:instance:${provider.instanceId}`, - }, - displayName: undefined, - enabled: true, - snapshot: { - resolveMaintenance: () => - Effect.succeed( - makeManualOnlyProviderMaintenanceCapabilities({ - provider: provider.driver, - packageName: null, - }), - ), - getSnapshot: Effect.succeed(provider), - refresh: Effect.succeed(provider), - streamChanges: Stream.empty, - applyUsageLimits: () => Effect.void, - }, - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration: {} as ProviderInstance["textGeneration"], - }); - const codexInstance = makeInstance(codexProvider); - const claudeInstance = makeInstance(claudeProvider); - const changes = yield* PubSub.unbounded(); - const instancesRef = yield* Ref.make>([codexInstance]); - const failNextList = yield* Ref.make(false); - const wait = () => Effect.yieldNow; - const layerInstanceRegistry = Layer.succeed( - ProviderInstanceRegistry.ProviderInstanceRegistry, - { - getInstance: (instanceId) => - Ref.get(instancesRef).pipe( - Effect.map((instances) => - instances.find((instance) => instance.instanceId === instanceId), - ), - ), - listInstances: Effect.gen(function* () { - const shouldFail = yield* Ref.get(failNextList); - if (shouldFail) { - yield* Ref.set(failNextList, false); - return yield* Effect.die(new Error("simulated registry list failure")); - } - return yield* Ref.get(instancesRef); - }), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.fromPubSub(changes), - subscribeChanges: PubSub.subscribe(changes), - }, - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const runtimeServices = yield* Layer.build( - ProviderRegistry.layer.pipe( - Layer.provideMerge(layerInstanceRegistry), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-sync-failure-", - }), - ), - Layer.provideMerge(layerBackgroundPolicyAlwaysRun), - Layer.provideMerge(NodeServices.layer), - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - assert.deepStrictEqual(yield* registry.getProviders, [ - withBundledCompatibility(codexProvider), - ]); - - yield* Ref.set(failNextList, true); - yield* PubSub.publish(changes, undefined); - - yield* Ref.set(instancesRef, [codexInstance, claudeInstance]); - yield* PubSub.publish(changes, undefined); - - let providers = yield* registry.getProviders; - for ( - let attempt = 0; - attempt < 50 && !providers.some((provider) => provider.instanceId === claudeInstanceId); - attempt += 1 - ) { - yield* wait(); - providers = yield* registry.getProviders; - } - - assert.deepStrictEqual( - providers.map((provider) => provider.instanceId).toSorted(), - [codexInstanceId, claudeInstanceId].toSorted(), - ); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - - it.effect("propagates real Codex probe failures to the aggregator at boot", () => - Effect.gen(function* () { - const missingBinary = `t3code_codex_missing_`; - const serverSettings = yield* makeMutableServerSettingsService( - decodeServerSettings( - deepMerge(encodedDefaultServerSettings, { - providerInstances: { - ...disabledDefaultSlots("codex", "claudeAgent", "cursor", "grok", "opencode"), - codex_personal: { - driver: "codex", - displayName: "Codex Personal", - enabled: true, - config: { - binaryPath: missingBinary, - homePath: `/tmp/${missingBinary}_home`, - }, - }, - } as unknown as ContractServerSettings["providerInstances"], - }), - ), - ); - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const layerProviderRegistry = ProviderRegistry.layer.pipe( - Layer.provideMerge(ProviderInstanceRegistryHydration.layer), - Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer), - Layer.provideMerge( - Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), - ), - Layer.provideMerge(ServerSecretStore.layer), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge(layerTestHttpClient), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(ProviderLatestVersions.layer), - Layer.provideMerge(McpProviderSessions.layer), - Layer.provideMerge(ModelManifest.layerTest), - Layer.provideMerge(ResetCreditCoordinator.layerTest), - Layer.provideMerge( - OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)), - ), - Layer.provideMerge(layerBackgroundPolicyAlwaysRun), - ); - const runtimeServices = yield* Layer.build(layerProviderRegistry).pipe( - Scope.provide(scope), - ); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - let providers = yield* registry.getProviders; - for ( - let attempts = 0; - attempts < 50 && - providers.find((provider) => provider.instanceId === "codex_personal")?.status !== - "error"; - attempts += 1 - ) { - yield* Effect.yieldNow; - providers = yield* registry.getProviders; - } - const codexPersonal = providers.find( - (provider) => provider.instanceId === "codex_personal", - ); - assert.notStrictEqual( - codexPersonal, - undefined, - `Expected the aggregator to know about codex_personal; instead saw: ${providers - .map((provider) => provider.instanceId) - .join(", ")}`, - ); - assert.strictEqual( - codexPersonal?.status, - "error", - "Real Codex probe against a missing binary should surface as 'error' in the aggregator", - ); - assert.strictEqual(codexPersonal?.installed, false); - assert.include(codexPersonal?.message, missingBinary); - assert.include(codexPersonal?.message, "Settings → Providers → Codex → Binary path"); - }).pipe(Effect.provide(runtimeServices)); - }), - ); - it.effect("re-probes when settings change the codex binaryPath", () => Effect.gen(function* () { const firstMissing = `t3code_codex_first_`; @@ -3174,179 +1987,159 @@ it.layer( assert.notStrictEqual(ghost, undefined); assert.strictEqual(ghost?.driver, "ghostDriver"); assert.strictEqual(ghost?.availability, "unavailable"); + assert.strictEqual(Object.hasOwn(ghost ?? {}, "setup"), false); assert.match(ghost?.unavailableReason ?? "", /ghostDriver/); }).pipe(Effect.provide(runtimeServices)); }), ); - it.effect( - "keeps Cursor disabled and skips provider probing when settings use their defaults", - () => - Effect.gen(function* () { - const serverSettings = yield* makeMutableServerSettingsService( - decodeServerSettings( - deepMerge(encodedDefaultServerSettings, { - providerInstances: disabledDefaultSlots("codex", "grok"), - }), - ), - ); - let cursorSpawned = false; - const scope = yield* Scope.make(); - yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); - const layerProviderRegistry = ProviderRegistry.layer.pipe( - Layer.provideMerge(ProviderInstanceRegistryHydration.layer), - Layer.provideMerge(AntigravityInstallation.AntigravityInstallation.layer), - Layer.provideMerge( - Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), - ), - Layer.provideMerge(ServerSecretStore.layer), - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-provider-registry-", - }), - ), - Layer.provideMerge(layerTestHttpClient), - Layer.provideMerge( - Layer.succeed( - ProviderEventLoggers.ProviderEventLoggers, - ProviderEventLoggers.NoOpProviderEventLoggers, - ), - ), - Layer.provideMerge(ProviderLatestVersions.layer), - Layer.provideMerge(McpProviderSessions.layer), - Layer.provideMerge(ModelManifest.layerTest), - Layer.provideMerge(ResetCreditCoordinator.layerTest), - Layer.provideMerge( - OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)), - ), - Layer.provideMerge(layerBackgroundPolicyAlwaysRun), - Layer.provideMerge( - layerMockCommandSpawner((command, args) => { - if (command === "cursor-agent") { - cursorSpawned = true; - } - const joined = args.join(" "); - if (joined === "--version") { - return { - stdout: `${command} 1.0.0\n`, - stderr: "", - code: 0, - }; - } - if (joined === "auth status") { - return { - stdout: '{"authenticated":true}\n', - stderr: "", - code: 0, - }; - } - throw new Error(`Unexpected args: ${command} ${joined}`); - }), - ), - ); - const runtimeServices = yield* Layer.build( - Layer.mergeAll( - Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), - layerProviderRegistry, - ), - ).pipe(Scope.provide(scope)); - - yield* Effect.gen(function* () { - const registry = yield* ProviderRegistry.ProviderRegistry; - const providers = yield* registry.getProviders; - const cursorProvider = providers.find( - (provider) => provider.instanceId === ProviderInstanceId.make("cursor"), - ); + const startupSettings = (instanceId?: string) => + decodeServerSettings({ + ...encodedDefaultServerSettings, + providerInstances: { + ...disabledDefaultSlots( + "codex", + "claudeAgent", + "cursor", + "grok", + "opencode", + "antigravity", + "pi", + "muse", + ), + ...(instanceId ? { [instanceId]: { driver: "ghostDriver" } } : {}), + }, + }); - assert.deepStrictEqual(providers.map((provider) => provider.instanceId).toSorted(), [ - "antigravity", - "claudeAgent", - "codex", - "cursor", - "grok", - "muse", - "opencode", - "pi", - ]); - assert.strictEqual(cursorProvider?.enabled, false); - assert.strictEqual(cursorProvider?.status, "disabled"); - assert.strictEqual(cursorProvider?.message, "Cursor is disabled in T3 Code settings."); - const museProvider = providers.find((provider) => provider.driver === "muse"); - assert.strictEqual(museProvider?.enabled, false); - assert.strictEqual(museProvider?.status, "disabled"); - assert.strictEqual(cursorSpawned, false); - }).pipe(Effect.provide(runtimeServices)); + const hydrateDuringSettingsChange = Effect.fnUntraced(function* (input: { + seed: ContractServerSettings; + saved: ContractServerSettings; + current: ContractServerSettings; + failCurrentRead?: boolean; + }) { + const changes = yield* PubSub.unbounded(); + const consume = yield* Deferred.make(); + const drained: Array> = []; + let readSeed = true; + let failCurrentRead = false; + const settings = yield* makeMutableServerSettingsService(input.current); + const serverSettings = { + ...settings, + getSettings: Effect.suspend(() => { + if (!readSeed) { + readSeed = true; + return PubSub.publish(changes, input.saved).pipe(Effect.as(input.seed)); + } + return failCurrentRead + ? Effect.fail( + new ServerSettingsError({ + settingsPath: "", + operation: "read-secret", + cause: new Error("secret materialization failed"), + }), + ) + : settings.getSettings; }), - ); + streamChanges: Stream.empty, + subscribeChanges: Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(changes); + const done = yield* Deferred.make(); + drained.push(done); + // The terminal marker acknowledges preceding reconciles, including no-op/failed reads. + return Stream.fromEffectRepeat( + Deferred.await(consume).pipe(Effect.andThen(PubSub.take(subscription))), + ).pipe( + Stream.takeWhile((next): next is ContractServerSettings => next !== undefined), + Stream.ensuring(Deferred.succeed(done, undefined)), + ); + }), + } satisfies ServerSettingsModule.ServerSettingsService["Service"]; + const dependencies = yield* Layer.build( + Layer.mergeAll( + AntigravityInstallation.AntigravityInstallation.layer, + ServerSecretStore.layer, + OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layerTest)), + ).pipe( + Layer.provideMerge( + Layer.succeed(ServerSettingsModule.ServerSettingsService, serverSettings), + ), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-provider-registry-" }), + ), + Layer.provideMerge(layerTestHttpClient), + Layer.provideMerge( + Layer.succeed( + ProviderEventLoggers.ProviderEventLoggers, + ProviderEventLoggers.NoOpProviderEventLoggers, + ), + ), + Layer.provideMerge(ProviderLatestVersions.layer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provideMerge(ResetCreditCoordinator.layerTest), + Layer.provideMerge(layerBackgroundPolicyAlwaysRun), + ), + ); + readSeed = false; + const services = yield* Layer.build(ProviderInstanceRegistryHydration.layer).pipe( + Effect.provide(dependencies), + ); + failCurrentRead = input.failCurrentRead ?? false; + yield* PubSub.publish(changes, undefined); + yield* Deferred.succeed(consume, undefined); + yield* Effect.forEach(drained, Deferred.await); + const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry.pipe( + Effect.provide(services), + ); + return (yield* registry.listUnavailable).map( + (provider): string | undefined => provider.instanceId, + ); + }); - it.effect("skips codex probes entirely when the provider is disabled", () => + it.effect("applies a settings change saved while the provider registry starts", () => Effect.gen(function* () { - const status = yield* checkCodexProviderStatus(disabledCodexSettings).pipe( - Effect.provide(layerFailingSpawner("spawn codex ENOENT")), - ); - assert.strictEqual(status.enabled, false); - assert.strictEqual(status.status, "disabled"); - assert.strictEqual(status.installed, false); - assert.strictEqual(status.message, "Codex is disabled in T3 Code settings."); + const saved = startupSettings("ghost_late"); + const unavailable = yield* hydrateDuringSettingsChange({ + seed: startupSettings(), + saved, + current: saved, + }); + assert.include(unavailable, "ghost_late"); }), ); - }); - describe("checkClaudeProviderStatus", () => { - it.effect("returns ready when claude is installed and authenticated", () => + it.effect("does not apply a queued settings change older than the registry seed", () => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities(), - ); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "authenticated"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + const seed = startupSettings("ghost_current"); + const unavailable = yield* hydrateDuringSettingsChange({ + seed, + saved: startupSettings("ghost_stale"), + current: seed, + }); + assert.include(unavailable, "ghost_current"); + assert.notInclude(unavailable, "ghost_stale"); + }), ); - it.effect("returns ready and labels Bedrock-backed Claude as authenticated", () => - Effect.gen(function* () { - // Bedrock authenticates via external AWS credentials, so the SDK init - // reports only `apiProvider` with no subscription or token. - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities({ apiProvider: "bedrock" }), - ); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "bedrock"); - assert.strictEqual(status.auth.label, "Amazon Bedrock"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), + it.effect( + "retains the newer registry seed when a queued stale change cannot read current settings", + () => + Effect.gen(function* () { + const seed = startupSettings("ghost_current"); + const unavailable = yield* hydrateDuringSettingsChange({ + seed, + saved: startupSettings("ghost_stale"), + current: seed, + failCurrentRead: true, + }); + assert.include(unavailable, "ghost_current"); + assert.notInclude(unavailable, "ghost_stale"); + }), ); + }); + describe("checkClaudeProviderStatus", () => { it.effect("reports a logged-out CLI as unauthenticated", () => Effect.gen(function* () { - // The capability probe resolves for a logged-out CLI, so `tokenSource: - // "none"` is the only thing separating it from an authenticated one. const status = yield* checkClaudeProviderStatus( defaultClaudeSettings, claudeCapabilities({ @@ -3354,6 +2147,7 @@ it.layer( apiKeySource: "none", apiProvider: "firstParty", }), + { ANTHROPIC_BASE_URL: "" }, ); assert.strictEqual(status.status, "error"); assert.strictEqual(status.auth.status, "unauthenticated"); @@ -3368,20 +2162,33 @@ it.layer( ), ); - it.effect("keeps an API key install authenticated when it reports no token source", () => + it.effect.each([ + { source: "inherited HTTPS endpoint", baseUrl: "https://proxy.example/api", overrides: [] }, + { + source: "instance HTTP endpoint overriding Anthropic", + baseUrl: "https://api.anthropic.com", + overrides: [ + { name: "ANTHROPIC_BASE_URL", value: "http://localhost:8080", sensitive: false }, + ], + }, + ])("keeps Claude ready with an empty first-party account: $source", ({ baseUrl, overrides }) => Effect.gen(function* () { - // `ANTHROPIC_API_KEY` never populates `tokenSource`, so reading that - // field alone would log the install out. + const environment = yield* mergeProviderInstanceEnvironment(overrides, { + ANTHROPIC_BASE_URL: baseUrl, + }); const status = yield* checkClaudeProviderStatus( defaultClaudeSettings, claudeCapabilities({ tokenSource: "none", - apiKeySource: "ANTHROPIC_API_KEY", + apiKeySource: "none", apiProvider: "firstParty", }), + environment, ); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "customEndpoint"); + assert.strictEqual(status.auth.label, "Custom API endpoint"); }).pipe( Effect.provide( layerMockSpawner((args) => { @@ -3393,125 +2200,31 @@ it.layer( ), ); - it.effect("keeps a third-party backend authenticated without any token source", () => - Effect.gen(function* () { - // Bedrock and Vertex authenticate outside the CLI, so the account - // payload is empty by design rather than because nobody logged in. - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities({ tokenSource: "none", apiProvider: "bedrock" }), - ); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("keeps a CLI that says nothing about its account authenticated", () => - Effect.gen(function* () { - // Profile-authenticated installs report no token source at all, and a - // CLI too old to send an account payload reports nothing whatsoever. - // Only `tokenSource: "none"` disproves authentication; saying nothing - // is not the same as saying no. - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities(), - ); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns a display label for claude subscription types", () => + it.effect.each([ + "https://api.anthropic.com", + "https://api.anthropic.com:443", + "https://api.anthropic.com:8443", + "openrouter.ai/api", + "localhost:8080", + "ftp://proxy.example", + ])("keeps Claude logged out when the instance endpoint is %s", (baseUrl) => Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities({ subscriptionType: "maxplan" }), + const environment = yield* mergeProviderInstanceEnvironment( + [{ name: "ANTHROPIC_BASE_URL", value: baseUrl, sensitive: false }], + { ANTHROPIC_BASE_URL: "https://proxy.example/api" }, ); - assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "maxplan"); - assert.strictEqual(status.auth.label, "Claude Max Subscription"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("reads banked resets only for subscription logins", () => - Effect.gen(function* () { - const check = (overrides: Partial) => - checkClaudeProviderStatus( - defaultClaudeSettings, - () => - Effect.succeed({ - email: undefined, - subscriptionType: undefined, - tokenSource: undefined, - apiKeySource: undefined, - apiProvider: undefined, - slashCommands: [], - usage: { rate_limits_available: true, rate_limits: {} }, - ...overrides, - }), - undefined, - undefined, - undefined, - undefined, - () => Effect.succeed({ availableCount: 2 }), - ); - const subscription = yield* check({ subscriptionType: "max" }); - const bedrock = yield* check({ apiProvider: "bedrock" }); - assert.deepStrictEqual(subscription.usageLimits?.resetCredits, { availableCount: 2 }); - assert.strictEqual(bedrock.usageLimits?.resetCredits, undefined); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("does not duplicate Claude in full subscription labels", () => - Effect.gen(function* () { const status = yield* checkClaudeProviderStatus( defaultClaudeSettings, claudeCapabilities({ - subscriptionType: "Claude Max Subscription", + tokenSource: "none", + apiKeySource: "none", + apiProvider: "firstParty", }), + environment, ); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "Claude Max Subscription"); - assert.strictEqual(status.auth.label, "Claude Max Subscription"); + assert.strictEqual(status.status, "error"); + assert.strictEqual(status.auth.status, "unauthenticated"); + assert.strictEqual(status.auth.type, undefined); }).pipe( Effect.provide( layerMockSpawner((args) => { @@ -3523,17 +2236,18 @@ it.layer( ), ); - it.effect("does not duplicate Claude in provider-prefixed subscription names", () => + it.effect("keeps an API key install authenticated when it reports no token source", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus( defaultClaudeSettings, claudeCapabilities({ - subscriptionType: "Claude Max", + tokenSource: "none", + apiKeySource: "ANTHROPIC_API_KEY", + apiProvider: "firstParty", }), ); + assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "Claude Max"); - assert.strictEqual(status.auth.label, "Claude Max Subscription"); }).pipe( Effect.provide( layerMockSpawner((args) => { @@ -3545,237 +2259,19 @@ it.layer( ), ); - it.effect("returns claude auth email from initialization result", () => + it.effect("keeps a CLI that says nothing about its account authenticated", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus( defaultClaudeSettings, - claudeCapabilities({ email: "claude@example.com" }), - ); - assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.email, "claude@example.com"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: - '{"loggedIn":true,"authMethod":"claude.ai","account":{"email":"claude@example.com"}}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("runs Claude status probes with the configured CLAUDE_CONFIG_DIR", () => { - const claudeConfigDir = "/tmp/t3code-claude-home"; - const recorded = recordingMockSpawnerLayer((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }); - - return Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - { - ...defaultClaudeSettings, - homePath: claudeConfigDir, - }, claudeCapabilities(), ); assert.strictEqual(status.status, "ready"); - assert.deepStrictEqual( - recorded.commands.map((command) => command.env?.CLAUDE_CONFIG_DIR), - [(yield* Path.Path).resolve(claudeConfigDir)], - ); - }).pipe(Effect.provide(recorded.layer)); - }); - - it.effect("includes probed claude slash commands in the provider snapshot", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities({ - subscriptionType: "maxplan", - slashCommands: [ - { - name: "review", - description: "Review a pull request", - input: { hint: "pr-or-branch" }, - }, - ], - }), - ); - - assert.deepStrictEqual(status.slashCommands.slice(1), [ - { - name: "review", - description: "Review a pull request", - input: { hint: "pr-or-branch" }, - }, - ]); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("deduplicates probed claude slash commands by name", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities({ - subscriptionType: "maxplan", - slashCommands: [ - { - name: "ui", - description: "Explore and refine UI", - }, - { - name: "ui", - input: { hint: "component-or-screen" }, - }, - ], - }), - ); - - assert.deepStrictEqual(status.slashCommands, [ - COMPACT_SLASH_COMMAND, - { - name: "ui", - description: "Explore and refine UI", - input: { hint: "component-or-screen" }, - }, - ]); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns an api key label for claude api key auth", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities({ tokenSource: "ANTHROPIC_AUTH_TOKEN" }), - ); - assert.strictEqual(status.status, "ready"); assert.strictEqual(status.auth.status, "authenticated"); - assert.strictEqual(status.auth.type, "apiKey"); - assert.strictEqual(status.auth.label, "Claude API Key"); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":true,"authMethod":"api-key"}\n', - stderr: "", - code: 0, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ), - ); - - it.effect("returns unavailable when claude is missing", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities(), - ); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, false); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual(status.message, "Claude Agent CLI (`claude`) was not found on PATH."); - }).pipe(Effect.provide(layerFailingSpawner("spawn claude ENOENT"))), - ); - - it.effect("returns error when version check fails with non-zero exit code", () => { - const secretStderr = "Something went wrong: secret-token-value"; - return Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - claudeCapabilities(), - ); - assert.strictEqual(status.status, "error"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.message, "Claude Agent CLI is installed but failed to run."); - assert.ok(!(status.message ?? "").includes(secretStderr)); - }).pipe( - Effect.provide( - layerMockSpawner((args) => { - const joined = args.join(" "); - if (joined === "--version") - return { - stdout: "", - stderr: secretStderr, - code: 1, - }; - throw new Error(`Unexpected args: ${joined}`); - }), - ), - ); - }); - - it.effect("returns warning when the Claude initialization result is unavailable", () => - Effect.gen(function* () { - const status = yield* checkClaudeProviderStatus( - defaultClaudeSettings, - noClaudeCapabilities, - ); - assert.strictEqual(status.status, "warning"); - assert.strictEqual(status.installed, true); - assert.strictEqual(status.auth.status, "unknown"); - assert.strictEqual( - status.message, - "Could not verify Claude authentication status from initialization result.", - ); }).pipe( Effect.provide( layerMockSpawner((args) => { const joined = args.join(" "); if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; - if (joined === "auth status") - return { - stdout: '{"loggedIn":false}\n', - stderr: "", - code: 1, - }; throw new Error(`Unexpected args: ${joined}`); }), ), diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts index 2b884af557692..0096ca23c0370 100644 --- a/apps/server/src/provider/ProviderRegistry.ts +++ b/apps/server/src/provider/ProviderRegistry.ts @@ -21,6 +21,7 @@ import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import * as Semaphore from "effect/Semaphore"; +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as ModelManifest from "./ModelManifest.ts"; import { applyProviderCompatibility } from "./providerCompatibility.ts"; import * as ServerConfig from "../config.ts"; @@ -54,15 +55,17 @@ export class ProviderRegistry extends Context.Service< provider?: ProviderDriverKind, ) => Effect.Effect>; - /** - * When the instance id is unknown the call resolves with the currently - * cached list (no error) — matching the legacy `refresh` shim behaviour so - * transport layers don't have to special-case unknowns. - */ + /** Unknown instance ids return the cached list without error. */ readonly refreshInstance: ( instanceId: ProviderInstanceId, ) => Effect.Effect>; + /** Only refreshed instances can verify an update; the published list still includes every row. */ + readonly refreshAfterUpdate: ( + provider: ProviderDriverKind, + selectedInstanceId: ProviderInstanceId, + ) => Effect.Effect>; + readonly refreshWorkspaceSnapshot: (input: { readonly instanceId: ProviderInstanceId; readonly cwd: string; @@ -124,15 +127,17 @@ export function upsertProviderWorkspaceSnapshot( cwd: string, scopedSnapshot: ProviderWorkspaceSnapshot, ): ServerProvider { + const previousSnapshot = provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd); + const optionDescriptors = scopedSnapshot.optionDescriptors ?? previousSnapshot?.optionDescriptors; const workspaceSnapshot = { cwd, checkedAt: scopedSnapshot.checkedAt, slashCommands: scopedSnapshot.slashCommandsPending - ? (provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd)?.slashCommands ?? - scopedSnapshot.slashCommands) + ? (previousSnapshot?.slashCommands ?? scopedSnapshot.slashCommands) : scopedSnapshot.slashCommands, ...(scopedSnapshot.slashCommandsPending ? { slashCommandsPending: true } : {}), skills: scopedSnapshot.skills, + ...(optionDescriptors === undefined ? {} : { optionDescriptors }), } satisfies NonNullable[number]; return { ...provider, @@ -145,9 +150,7 @@ export function upsertProviderWorkspaceSnapshot( const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => { if (provider.driver === ProviderDriverKind.make("pi")) { - // Pi reports known auth only after RPC inventory discovery completes. - // An empty inventory is warning/unauthenticated; failed or interactive - // discovery stays ready/unknown and must keep the last known models. + // Pi auth becomes known only after inventory discovery: empty means unauthenticated; failed/interactive discovery preserves unknown auth and cached models. return !( provider.installed && (provider.status === "ready" || provider.status === "warning") && @@ -156,15 +159,11 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => } if (provider.driver === ProviderDriverKind.make("acpRegistry")) { - // ACP Registry discovery probes return the agent's complete inventory, so - // a completed probe (ready and authenticated) replaces the model list — - // otherwise agents that rename or collapse models leave stale entries - // pinned forever through the snapshot cache. Readiness-only and failed - // probe snapshots only know the "default" placeholder and stay partial. + // Only completed ACP discovery provides nativeSessions and inventory; placeholder probes cannot establish auth for agents without sign-in. return !( provider.installed && provider.status === "ready" && - provider.auth.status === "authenticated" + provider.nativeSessions !== undefined ); } @@ -186,10 +185,10 @@ const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => isAntigravity && provider.status === "warning" && provider.auth.status === "unknown"; const isPendingInitialProbe = provider.enabled && !provider.installed && provider.status === "warning"; - const didInstalledProviderProbeFail = provider.installed && provider.status === "error"; - return ( - isPendingAntigravityAuthentication || isPendingInitialProbe || didInstalledProviderProbeFail - ); + const isIncompleteInstalledProbe = + provider.installed && + (provider.status === "error" || (isCodex && provider.status === "warning")); + return isPendingAntigravityAuthentication || isPendingInitialProbe || isIncompleteInstalledProbe; }; const shouldRetainMissingOpenCodeMetadata = (provider: ServerProvider): boolean => @@ -228,11 +227,7 @@ const mergeProviderModels = ( : mergedModels; }; -/** - * Antigravity's health check only initializes the agent, so after a server - * restart it reports the account as unchecked. The saved Google login still - * works, and the previous snapshot proves it. - */ +/** Antigravity health checks only initialize; preserve previously verified Google auth across restarts. */ const carrySavedAntigravityAccount = ( previousProvider: ServerProvider, nextProvider: ServerProvider, @@ -285,30 +280,6 @@ export const mergeProviderSnapshot = ( }; }; -export const mergeProviderSnapshots = ( - previousProviders: ReadonlyArray, - nextProviders: ReadonlyArray, -): ReadonlyArray => { - const mergedProviders = new Map( - previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const), - ); - - for (const provider of nextProviders) { - mergedProviders.set( - snapshotInstanceKey(provider), - mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider), - ); - } - - return orderProviderSnapshots([...mergedProviders.values()]); -}; - -export const selectProvidersByKind = ( - providers: ReadonlyArray, - providerKinds: ReadonlySet, -): ReadonlyArray => - providers.filter((provider) => providerKinds.has(provider.driver)); - const haveProvidersChanged = ( previousProviders: ReadonlyArray, nextProviders: ReadonlyArray, @@ -339,9 +310,7 @@ const snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => { return provider.instanceId; }; -// Each call re-captures the instance's `snapshot` closures, so after -// `ProviderInstanceRegistry` rebuilds an instance (e.g. because its settings -// changed), a fresh source rides the new PubSub instead of a closed one. +// Rebuilt instances have new PubSubs; capture their fresh closures instead of a closed source. const buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, @@ -355,6 +324,7 @@ export const layer = Layer.effect( Effect.gen(function* () { const instanceRegistry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; const manifestService = yield* ModelManifest.ModelManifest; + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; const serviceScope = yield* Effect.scope; const config = yield* ServerConfig.ServerConfig; const fileSystem = yield* FileSystem.FileSystem; @@ -435,7 +405,7 @@ export const layer = Layer.effect( cachedProviders.map((provider) => classifyCompatibility(provider, initialManifest)), ); const workspaceRefreshesRef = yield* Ref.make< - ReadonlyMap> + ReadonlyMap> >(new Map()); const maintenanceActionStatesRef = yield* Ref.make< ReadonlyMap @@ -450,21 +420,22 @@ export const layer = Layer.effect( liveSubsRef, ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource))); - const persistProvider = (provider: ServerProvider) => - Effect.gen(function* () { - const key = snapshotInstanceKey(provider); - const filePath = yield* resolveProviderStatusCachePath({ - cacheDir: config.providerStatusCacheDir, - instanceId: key, - }).pipe(Effect.provideService(Path.Path, path)); - const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider; - yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.tapError(Effect.logError), - Effect.ignore, - ); - }); + const persistProvider = Effect.fn("ProviderRegistry.persistProvider")(function* ( + provider: ServerProvider, + ) { + const key = snapshotInstanceKey(provider); + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: key, + }).pipe(Effect.provideService(Path.Path, path)); + const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider; + yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.tapError(Effect.logError), + Effect.ignore, + ); + }); const applyProviderUpdateState = Effect.fn("applyProviderUpdateState")(function* ( provider: ServerProvider, @@ -551,8 +522,7 @@ export const layer = Layer.effect( }, ) { const providers = yield* upsertProviders([provider], options); - // Reclassify the current read model after fetching. Never republish the - // probe captured before the fetch: a newer health result may have landed. + // Reclassify the current model after fetch; republishing the old probe could overwrite newer health results. if (!(yield* Ref.getAndSet(compatibilityRefreshRunning, true))) { yield* manifestService.refresh.pipe( Effect.andThen(upsertProviders([], { persist: false })), @@ -636,8 +606,7 @@ export const layer = Layer.effect( }, ); if (claimed.owner) { - // Detached so an interrupted first caller cannot cancel the pass that - // other callers are already awaiting. + // Detach shared passes so the first caller's interruption cannot cancel other callers' work. yield* getLiveSources.pipe( Effect.flatMap((sources) => Effect.forEach(sources, (source) => refreshOneSource(source), { @@ -683,6 +652,70 @@ export const layer = Layer.effect( return yield* refreshOneSource(providerSource); }); + const refreshAfterUpdate = Effect.fn("refreshAfterUpdate")(function* ( + provider: ProviderDriverKind, + selectedInstanceId: ProviderInstanceId, + ) { + yield* manifestService.forceRefresh; + const instances = (yield* instanceRegistry.listInstances).filter( + (instance) => + instance.driverKind === provider && + (instance.enabled || instance.instanceId === selectedInstanceId), + ); + const failedInstances = new Set(); + const recoverInstanceFailure = Effect.fn("recoverPostUpdateRefreshFailure")(function* ( + instanceId: ProviderInstanceId, + cause: Cause.Cause, + ) { + if (Cause.hasInterruptsOnly(cause)) { + return yield* Effect.interrupt; + } + yield* Effect.logError("provider post-update refresh failed", { + instanceId, + cause: Cause.pretty(cause), + }); + failedInstances.add(instanceId); + // A cached ready snapshot cannot verify a successful update. + return yield* updateProviders((providers) => + providers.map((candidate) => + candidate.instanceId === instanceId + ? { ...candidate, status: "error", message: "Provider refresh failed after update." } + : candidate, + ), + ); + }); + // Accounts can share an installation, but discovery must use each + // instance's own executable, environment, and credentials. + yield* Effect.forEach( + instances, + (instance) => + Effect.gen(function* () { + yield* instance.invalidateCaches ?? Effect.void; + const maintenance = yield* instance.snapshot.resolveMaintenance({ fresh: true }); + if (maintenance.packageName) { + yield* latestVersions.invalidate(maintenance.packageName); + } + }).pipe(Effect.catchCause((cause) => recoverInstanceFailure(instance.instanceId, cause))), + { concurrency: "unbounded", discard: true }, + ); + yield* Effect.forEach( + instances.filter((instance) => !failedInstances.has(instance.instanceId)), + (instance) => + refreshOneSource(buildSnapshotSource(instance)).pipe( + Effect.catchCause((cause) => recoverInstanceFailure(instance.instanceId, cause)), + ), + { concurrency: "unbounded", discard: true }, + ); + const refreshedInstanceIds = new Set( + instances + .filter((instance) => !failedInstances.has(instance.instanceId)) + .map((instance) => instance.instanceId), + ); + return (yield* Ref.get(providersRef)).filter((candidate) => + refreshedInstanceIds.has(candidate.instanceId), + ); + }); + const getProviderMaintenanceCapabilitiesForInstance = Effect.fn( "getProviderMaintenanceCapabilitiesForInstance", )(function* ( @@ -690,9 +723,7 @@ export const layer = Layer.effect( provider: ProviderDriverKind, options?: { readonly fresh?: boolean }, ) { - // Read the instance registry, not `liveSubsRef`: the latter trails - // reconciliation, and an update must never run a retired instance's - // command against a freshly configured executable. + // liveSubsRef trails reconciliation and could run a retired instance's command; read the registry. const instance = yield* instanceRegistry.getInstance(instanceId); if (!instance || instance.driverKind !== provider) { return makeManualProviderMaintenanceCapabilities(provider); @@ -751,10 +782,7 @@ export const layer = Layer.effect( } } - // Fork long-lived subscriptions to each new/rebuilt instance's - // change stream before reading its current snapshot. If the - // driver's own initial probe finishes during this sync, either - // the current read or the active subscriber observes the result. + // Subscribe before reading so a probe completing mid-sync is observed by at least one path. for (const [, instance] of newlyAdded) { const source = buildSnapshotSource(instance); yield* Stream.runForEach(source.streamChanges, (provider) => @@ -890,19 +918,19 @@ export const layer = Layer.effect( ) { return providers; } - // Drivers spread their machine snapshot, whose `checkedAt` is the last - // health check. The TTL needs the time this scan started reading files. + // Use scan start for TTL, not checkedAt inherited from the machine health check. const scannedAt = DateTime.formatIso(now); const instance = yield* instanceRegistry.getInstance(input.instanceId); if (!instance?.snapshotForCwd) return providers; + const token = Symbol(); const claimed = yield* Ref.modify(workspaceRefreshesRef, (refreshes) => { const current = refreshes.get(instance); - if (current?.has(input.cwd)) return [false, refreshes] as const; + if (!input.fresh && current?.has(input.cwd)) return [false, refreshes] as const; const next = new Map(refreshes); - next.set(instance, new Set(current).add(input.cwd)); + next.set(instance, new Map(current).set(input.cwd, token)); return [true, next] as const; }); - if (!claimed && !input.fresh) return yield* Ref.get(providersRef); + if (!claimed) return yield* Ref.get(providersRef); const refreshMachineSnapshot = input.fresh ? (instance.invalidateCaches ?? Effect.void).pipe( Effect.andThen(refreshInstance(input.instanceId)), @@ -910,37 +938,43 @@ export const layer = Layer.effect( : Effect.void; return yield* refreshMachineSnapshot.pipe( Effect.andThen(instance.snapshotForCwd(input.cwd)), + // Scans fail on error; returned inventory remains valid even when provider health reports an error. Effect.flatMap((scopedSnapshot) => - scopedSnapshot.status === "error" && scopedSnapshot.slashCommandsPending === undefined - ? Ref.get(providersRef) - : instanceRegistry.getInstance(input.instanceId).pipe( - Effect.flatMap((currentInstance) => { - if (currentInstance !== instance) return Ref.get(providersRef); - return updateProviders((currentProviders) => - currentProviders.map((candidate) => - candidate.instanceId === input.instanceId && - Equal.equals(workspaceSnapshotOf(candidate), scannedFrom) - ? upsertProviderWorkspaceSnapshot(candidate, input.cwd, { - ...scopedSnapshot, - checkedAt: scannedAt, - }) - : candidate, - ), - ); - }), - ), + instanceRegistry.getInstance(input.instanceId).pipe( + Effect.flatMap((currentInstance) => { + if (currentInstance !== instance) return Ref.get(providersRef); + return updateProviders((currentProviders) => { + // Read ownership inside the update so a newer claim cannot race publication. + if (Ref.getUnsafe(workspaceRefreshesRef).get(instance)?.get(input.cwd) !== token) { + return currentProviders; + } + return currentProviders.map((candidate) => + candidate.instanceId === input.instanceId && + Equal.equals(workspaceSnapshotOf(candidate), scannedFrom) + ? upsertProviderWorkspaceSnapshot(candidate, input.cwd, { + ...scopedSnapshot, + checkedAt: scannedAt, + // Without driver command discovery, retain previous commands after failed health checks and retry. + slashCommandsPending: + scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error", + }) + : candidate, + ); + }); + }), + ), ), Effect.ensuring( - claimed - ? Ref.update(workspaceRefreshesRef, (refreshes) => { - const next = new Map(refreshes); - const current = new Set(next.get(instance)); - current.delete(input.cwd); - if (current.size) next.set(instance, current); - else next.delete(instance); - return next; - }) - : Effect.void, + Ref.update(workspaceRefreshesRef, (refreshes) => { + const current = refreshes.get(instance); + if (current?.get(input.cwd) !== token) return refreshes; + const next = new Map(refreshes); + const nextCwds = new Map(current); + nextCwds.delete(input.cwd); + if (nextCwds.size) next.set(instance, nextCwds); + else next.delete(instance); + return next; + }), ), ); }); @@ -953,6 +987,7 @@ export const layer = Layer.effect( refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)), refreshWorkspaceSnapshot: (input) => refreshWorkspaceSnapshot(input).pipe(Effect.catchCause(recoverRefreshFailure)), + refreshAfterUpdate, getProviderMaintenanceCapabilitiesForInstance, setProviderMaintenanceActionState, get streamChanges() { diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 4d1de51cc1b76..9e2da61be2af3 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -5,20 +5,20 @@ import * as NodeURL from "node:url"; import * as NodeFS from "node:fs"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { it } from "@effect/vitest"; +import { assert, 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 Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; -import * as Option from "effect/Option"; import * as Scope from "effect/Scope"; import * as Result from "effect/Result"; -import * as TestClock from "effect/testing/TestClock"; import * as Stream from "effect/Stream"; +import { ChildProcessSpawner } from "effect/process"; import { describe, expect } from "vite-plus/test"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; -import type * as EffectAcpProtocol from "effect-acp/protocol"; +import { AgentScope } from "@t3tools/shared/AgentScope"; import * as EffectAcpErrors from "effect-acp/errors"; const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)); @@ -108,42 +108,6 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("awaits native resume instead of using the load replay idle fallback", () => - Effect.gen(function* () { - const resumeStarted = yield* Deferred.make(); - const requestMethods: Array = []; - const runtime = yield* AcpSessionRuntime.make({ - ...mockRuntimeOptions, - spawn: { - ...mockRuntimeOptions.spawn, - env: { T3_ACP_WAIT_FOR_RESUME_RELEASE: "1", T3_ACP_SESSION_LIFECYCLE: "1" }, - }, - resumeSessionId: "mock-session-1", - resumeMethod: "resume", - sessionLoadReplayIdleGap: "1 second", - requestLogger: (event) => - Effect.sync(() => { - if (event.status === "started") requestMethods.push(event.method); - }), - }); - yield* runtime.handleSessionUpdate((notification) => - notification.update.sessionUpdate === "user_message_chunk" - ? Deferred.succeed(resumeStarted, undefined).pipe(Effect.asVoid) - : Effect.void, - ); - const startup = yield* runtime.start().pipe(Effect.forkChild); - yield* Deferred.await(resumeStarted); - yield* TestClock.adjust("3 seconds"); - expect(startup.pollUnsafe()).toBeUndefined(); - yield* runtime.request("_test/release-resume", {}); - const started = yield* Fiber.join(startup); - - expect(started.sessionSetupResult._meta).toEqual({ nativeResume: true }); - expect(requestMethods).toContain("session/resume"); - expect(requestMethods).not.toContain("session/load"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("waits for native cancellation and drains final updates before another prompt", () => Effect.gen(function* () { const toolStarted = yield* Deferred.make(); @@ -229,67 +193,40 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("retires a process when native cancellation times out", () => + it.effect("reports an idle child exit and rejects later prompts", () => Effect.gen(function* () { - const toolStarted = yield* Deferred.make(); - const cancelReceived = yield* Deferred.make(); - const runtime = yield* AcpSessionRuntime.make({ - ...mockRuntimeOptions, - spawn: { - ...mockRuntimeOptions.spawn, - env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" }, - }, - cancelBehavior: "wait-for-prompt", - cancelTimeout: "1 second", - }); - yield* runtime.getEvents().pipe( - Stream.runForEach((event) => { - if (event._tag === "EventStreamBarrier") { - return Deferred.succeed(event.acknowledge, undefined); - } - if (event._tag === "ToolCallUpdated") { - return Deferred.succeed(toolStarted, undefined); - } - if (event._tag === "ThoughtDelta") { - return Deferred.succeed(cancelReceived, undefined); - } - return Effect.void; + const stopped = yield* Deferred.make(); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions).pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + spawner.spawn(command).pipe( + Effect.map((child) => + ChildProcessSpawner.makeHandle({ + ...child, + // Model an inherited pipe held open until detached work is stopped. + stdout: Stream.concat( + child.stdout, + Stream.fromEffect(Deferred.await(stopped)).pipe(Stream.drain), + ), + }), + ), + ), + ), + ), + Effect.provideService(AgentScope, { + ...AgentScope.defaultValue(), + wrap: ({ command, args }) => + Effect.succeed({ command, args, unit: "t3code-acp-test.scope" }), + stop: (unit) => Deferred.succeed(stopped, unit).pipe(Effect.asVoid), }), - Effect.forkChild, ); yield* runtime.start(); - const prompt = yield* runtime - .prompt({ - prompt: [{ type: "text", text: "first" }], - }) - .pipe(Effect.forkChild); - yield* Deferred.await(toolStarted); - const cancellation = yield* runtime.cancel.pipe(Effect.forkChild); - yield* Deferred.await(cancelReceived); - yield* TestClock.adjust("2 seconds"); - - const error = yield* Fiber.join(cancellation).pipe(Effect.flip); - expect(error).toMatchObject({ - _tag: "AcpTransportError", - method: "session/cancel", - }); - expect(Exit.isFailure(yield* Fiber.await(prompt))).toBe(true); - expect( - yield* runtime - .prompt({ - prompt: [{ type: "text", text: "must not run" }], - }) - .pipe(Effect.flip), - ).toBe(error); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("reports an idle child exit and rejects later prompts", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.make(mockRuntimeOptions); - yield* runtime.start(); + expect(yield* Deferred.isDone(stopped)).toBe(false); yield* runtime.notify("_test/exit", {}); const events = yield* runtime.getEvents().pipe(Stream.take(1), Stream.runCollect); + expect(yield* Deferred.await(stopped)).toBe("t3code-acp-test.scope"); const event = events[0]; expect(event).toMatchObject({ _tag: "ConnectionTerminated", error: { code: 19 } }); if (event?._tag !== "ConnectionTerminated") return; @@ -376,7 +313,19 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("attaches child stderr when the ACP process exits before initialize", () => + it.effect.each([ + { name: "exit code", terminate: "process.exit(1)", code: 1, signal: undefined }, + ...(HostProcess.Platform.defaultValue() === "win32" + ? [] + : [ + { + name: "signal", + terminate: "process.kill(process.pid, 'SIGTERM')", + code: undefined, + signal: "SIGTERM", + }, + ]), + ])("retains the $name and sanitized stderr when ACP exits before initialize", (testCase) => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.make({ ...mockRuntimeOptions, @@ -384,15 +333,31 @@ describe("AcpSessionRuntime", () => { command: process.execPath, args: [ "-e", - "process.stderr.write(\"Invalid project config at /tmp/project/.cursor/cli.json: schema validation failed. Unrecognized key(s): 'approvalMode', 'sandbox'\\n\"); process.exit(1);", + `process.stderr.write("Invalid project config: Unrecognized key in cli.json\\nAuthorization: Bearer secret-token-value\\n", () => { ${testCase.terminate}; });`, ], }, }); const error = yield* runtime.start().pipe(Effect.flip); - expect(error._tag).toBe("AcpProcessExitedError"); - expect(error.message).toContain("cli.json"); - expect(error.message).toContain("Unrecognized key"); - expect(error.message).not.toContain("ACP process exited with code 1\nACP process exited"); + assert.instanceOf(error, EffectAcpErrors.AcpProcessExitedError); + expect(error.code).toBe(testCase.code); + expect(error.signal).toBe(testCase.signal); + expect(error).toMatchObject({ + pid: expect.any(Number), + stderr: + "Invalid project config: Unrecognized key in cli.json\nAuthorization: Bearer [redacted]", + }); + expect(error.message).toBe( + `${testCase.signal ? "ACP process exited after signal SIGTERM" : "ACP process exited with code 1"}\nInvalid project config: Unrecognized key in cli.json\nAuthorization: Bearer [redacted]`, + ); + if (testCase.signal) { + expect(error.cause).toMatchObject({ + reason: { + module: "ChildProcess", + method: "exitCode", + cause: new Error("Process interrupted due to receipt of signal: 'SIGTERM'"), + }, + }); + } }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -452,47 +417,6 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("bounds native cancellation when its event consumer is absent", () => - Effect.gen(function* () { - const toolStarted = yield* Deferred.make(); - const cancelReceived = yield* Deferred.make(); - const runtime = yield* AcpSessionRuntime.make({ - ...mockRuntimeOptions, - spawn: { - ...mockRuntimeOptions.spawn, - env: { T3_ACP_COMPLETE_FIRST_PROMPT_ON_CANCEL: "1" }, - }, - cancelBehavior: "wait-for-prompt", - cancelTimeout: "1 second", - }); - yield* runtime.handleSessionUpdate((notification) => { - if (notification.update.sessionUpdate === "tool_call_update") { - return Deferred.succeed(toolStarted, undefined).pipe(Effect.asVoid); - } - if (notification.update.sessionUpdate === "agent_thought_chunk") { - return Deferred.succeed(cancelReceived, undefined).pipe(Effect.asVoid); - } - return Effect.void; - }); - yield* runtime.start(); - const prompt = yield* runtime - .prompt({ - prompt: [{ type: "text", text: "first" }], - }) - .pipe(Effect.forkChild); - yield* Deferred.await(toolStarted); - const cancellation = yield* runtime.cancel.pipe(Effect.forkChild); - yield* Deferred.await(cancelReceived); - yield* runtime.request("_test/finish-cancel", {}); - expect(yield* Fiber.join(prompt)).toMatchObject({ stopReason: "cancelled" }); - yield* TestClock.adjust("2 seconds"); - expect(yield* Fiber.join(cancellation).pipe(Effect.flip)).toMatchObject({ - _tag: "AcpTransportError", - method: "session/cancel", - }); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("does not restore ambient variables to a sanitized child environment", () => Effect.gen(function* () { yield* Effect.acquireRelease( @@ -535,49 +459,6 @@ describe("AcpSessionRuntime", () => { expect(AcpSessionRuntime.selectAcpAgentAuthMethod(methods, "missing")).toBeUndefined(); }); - it.effect("merges custom initialize client capabilities into the ACP handshake", () => { - const requestEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - const initializeStarted = requestEvents.find( - (event) => event.method === "initialize" && event.status === "started", - ); - expect(initializeStarted?.payload).toMatchObject({ - protocolVersion: 2, - clientCapabilities: { - fs: { readTextFile: false, writeTextFile: false }, - terminal: false, - _meta: { parameterizedModelPicker: true }, - }, - }); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - }, - cwd: process.cwd(), - clientCapabilities: { - _meta: { - parameterizedModelPicker: true, - }, - }, - clientInfo: { name: "t3-test", version: "0.0.0" }, - authMethodId: "test", - requestLogger: (event) => - Effect.sync(() => { - requestEvents.push(event); - }), - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - it.effect("prefers MCP-over-ACP only when the agent advertises that transport", () => { const requestEvents: Array = []; return Effect.gen(function* () { @@ -614,41 +495,6 @@ describe("AcpSessionRuntime", () => { ); }); - it.effect("falls back to stdio MCP when the agent does not advertise MCP-over-ACP", () => { - const requestEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - const created = requestEvents.find( - (event) => event.method === "session/new" && event.status === "started", - ); - expect(created?.payload).toMatchObject({ - mcpServers: [{ type: "stdio", name: "t3-code", command: "/usr/bin/node", args: [] }], - }); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - authMethodId: "test", - mcpServers: [{ type: "stdio", name: "t3-code", command: "/usr/bin/node", args: [] }], - acpMcpServers: [{ type: "acp", name: "t3-code", serverId: "t3-code" }], - requestLogger: (event) => - Effect.sync(() => { - requestEvents.push(event); - }), - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - it.effect("supports v2 session deletion and secret-safe provider management", () => { const requestEvents: Array = []; return Effect.gen(function* () { @@ -701,37 +547,6 @@ describe("AcpSessionRuntime", () => { ); }); - it.effect("does not authenticate when an advertised method is not required", () => { - const requestEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - expect( - requestEvents.filter((event) => event.status === "started").map((event) => event.method), - ).toEqual(["initialize", "session/new"]); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - env: { T3_ACP_AUTH_METHOD_ID: "test" }, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - requestLogger: (event) => - Effect.sync(() => { - requestEvents.push(event); - }), - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - it.effect("authenticates explicitly typed v2 agent methods and retries session creation", () => { const requestEvents: Array = []; return Effect.gen(function* () { @@ -956,100 +771,6 @@ describe("AcpSessionRuntime", () => { ), ); - it.effect("supports successive standard ACP prompts", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - const firstPromptResult = yield* runtime.prompt({ - prompt: [{ type: "text", text: "first" }], - }); - const secondPromptResult = yield* runtime.prompt({ - prompt: [{ type: "text", text: "second" }], - }); - - expect(firstPromptResult).toMatchObject({ stopReason: "end_turn" }); - expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" }); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - authMethodId: "test", - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ), - ); - - it.effect("releases a fully silent prompt and forwards configured cancel metadata", () => { - const protocolEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - const promptFiber = yield* runtime - .prompt({ - prompt: [{ type: "text", text: "hang forever" }], - }) - .pipe(Effect.forkChild({ startImmediately: true })); - - yield* TestClock.adjust("500 millis"); - yield* runtime.cancel; - yield* Effect.yieldNow; - yield* Effect.yieldNow; - - expect( - protocolEvents.some( - (event) => - event.direction === "outgoing" && - event.stage === "raw" && - typeof event.payload === "string" && - event.payload.includes('"method":"session/cancel"') && - event.payload.includes('"cancelTrigger":"ctrl_c"'), - ), - ).toBe(true); - - const firstPromptResult = yield* Fiber.join(promptFiber); - expect(firstPromptResult).toMatchObject({ stopReason: "cancelled" }); - - const secondPromptResult = yield* runtime.prompt({ - prompt: [{ type: "text", text: "second" }], - }); - expect(secondPromptResult).toMatchObject({ stopReason: "end_turn" }); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - env: { - T3_ACP_HANG_FIRST_PROMPT_FOREVER: "1", - }, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - authMethodId: "test", - cancelMeta: { cancelTrigger: "ctrl_c" }, - protocolLogging: { - logOutgoing: true, - logger: (event) => - Effect.sync(() => { - protocolEvents.push(event); - }), - }, - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - it.effect("segments assistant text around ACP tool calls", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; @@ -1204,58 +925,6 @@ describe("AcpSessionRuntime", () => { ), ); - it.effect("logs ACP requests from the shared runtime", () => { - const requestEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - yield* runtime.setModel("composer-2"); - yield* runtime.prompt({ - prompt: [{ type: "text", text: "hi" }], - }); - - expect( - requestEvents.some( - (event) => event.method === "session/set_config_option" && event.status === "started", - ), - ).toBe(true); - expect( - requestEvents.some( - (event) => event.method === "session/set_config_option" && event.status === "succeeded", - ), - ).toBe(true); - expect( - requestEvents.some( - (event) => event.method === "session/prompt" && event.status === "started", - ), - ).toBe(true); - expect( - requestEvents.some( - (event) => event.method === "session/prompt" && event.status === "succeeded", - ), - ).toBe(true); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - requestLogger: (event) => - Effect.sync(() => { - requestEvents.push(event); - }), - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - it.effect("supports negotiated ACP session list, fork, resume, and close methods", () => { const requestEvents: Array = []; return Effect.gen(function* () { @@ -1321,37 +990,6 @@ describe("AcpSessionRuntime", () => { ); }); - it.effect("lists sessions without creating a disposable session", () => { - const requestEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - const listed = yield* runtime.listSessions(); - - expect(listed.sessions).toHaveLength(1); - expect( - requestEvents.filter((event) => event.status === "started").map((event) => event.method), - ).toEqual(["initialize", "session/list"]); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - env: { T3_ACP_SESSION_LIFECYCLE: "1" }, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - requestLogger: (event) => - Effect.sync(() => { - requestEvents.push(event); - }), - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - it.effect("rejects unauthenticated ACP session lifecycle requests", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; @@ -1401,88 +1039,7 @@ describe("AcpSessionRuntime", () => { ), ); - it.effect("skips no-op session config writes when the requested value is already active", () => { - const requestEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - yield* runtime.setConfigOption("model", "default"); - yield* runtime.setMode("ask"); - - expect( - requestEvents.some( - (event) => event.method === "session/set_config_option" && event.status === "started", - ), - ).toBe(false); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - requestLogger: (event) => - Effect.sync(() => { - requestEvents.push(event); - }), - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - - it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => { - const protocolEvents: Array = []; - return Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - - yield* runtime.prompt({ - prompt: [{ type: "text", text: "hi" }], - }); - - expect( - protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"), - ).toBe(true); - expect( - protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"), - ).toBe(true); - expect( - protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"), - ).toBe(true); - expect( - protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"), - ).toBe(true); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - }, - cwd: process.cwd(), - clientInfo: { name: "t3-test", version: "0.0.0" }, - protocolLogging: { - logIncoming: true, - logOutgoing: true, - logger: (event) => - Effect.sync(() => { - protocolEvents.push(event); - }), - }, - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - ); - }); - + // regression: #3156 harden ACP resume with replay-idle load readiness it.effect("fails session startup when session/load returns an error", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; @@ -1578,129 +1135,6 @@ describe("AcpSessionRuntime", () => { ), ); - it.effect("keeps active-session updates while loading a different session", () => - Effect.gen(function* () { - const loadStarted = yield* Deferred.make(); - const runtime = yield* AcpSessionRuntime.make({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - env: { - T3_ACP_DELAY_LOAD_SESSION_AFTER_REPLAY: "1", - T3_ACP_LOAD_SESSION_DELAY_MS: "250", - }, - }, - cwd: process.cwd(), - sessionLoadTimeout: "2 seconds", - clientInfo: { name: "t3-test", version: "0.0.0" }, - requestLogger: (event) => - event.method === "session/load" && event.status === "started" - ? Deferred.succeed(loadStarted, undefined).pipe(Effect.asVoid) - : Effect.void, - }); - yield* runtime.start(); - - const eventsFiber = yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)).pipe( - Effect.forkChild({ startImmediately: true }), - ); - const loadFiber = yield* runtime - .loadSession("mock-session-2") - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(loadStarted); - - yield* runtime.prompt({ - prompt: [{ type: "text", text: "active session prompt" }], - }); - const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("2 seconds"))); - expect(events.map((event) => event._tag)).toEqual([ - "PlanUpdated", - "AssistantItemStarted", - "ContentDelta", - "AssistantItemCompleted", - ]); - expect( - events.some((event) => event._tag === "ContentDelta" && event.text === "hello from mock"), - ).toBe(true); - - const loaded = yield* Fiber.join(loadFiber).pipe(Effect.timeout("2 seconds")); - expect(loaded.sessionId).toBe("mock-session-2"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), TestClock.withLive), - ); - - it.effect("completes session/load after replay becomes idle while its RPC stays pending", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - const started = yield* runtime.start().pipe(Effect.timeout("2 seconds")); - - expect(started.sessionId).toBe("mock-session-1"); - expect(started.sessionSetupResult._meta).toMatchObject({ - t3SessionLoadReady: "replay_idle", - }); - - const unexpectedReplayEvent = yield* Stream.runHead(runtime.getEvents()).pipe( - Effect.timeoutOption("100 millis"), - ); - expect(Option.isNone(unexpectedReplayEvent)).toBe(true); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - env: { - T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1", - T3_ACP_LOAD_SESSION_DELAY_MS: "10000", - }, - }, - cwd: process.cwd(), - resumeSessionId: "mock-session-1", - sessionLoadReplayIdleGap: "50 millis", - sessionLoadTimeout: "1 second", - clientInfo: { name: "t3-test", version: "0.0.0" }, - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - TestClock.withLive, - ), - ); - - it.effect("completes ad-hoc loadSession after replay becomes idle while RPC stays pending", () => - Effect.gen(function* () { - const runtime = yield* AcpSessionRuntime.AcpSessionRuntime; - yield* runtime.start(); - const loaded = yield* runtime.loadSession("mock-session-1").pipe(Effect.timeout("2 seconds")); - - expect(loaded.sessionId).toBe("mock-session-1"); - expect(loaded.sessionSetupResult._meta).toMatchObject({ - t3SessionLoadReady: "replay_idle", - }); - }).pipe( - Effect.provide( - AcpSessionRuntime.layer({ - authMethodId: "test", - spawn: { - command: mockAgentCommand, - args: mockAgentArgs, - env: { - T3_ACP_HANG_LOAD_SESSION_AFTER_REPLAY: "1", - T3_ACP_LOAD_SESSION_DELAY_MS: "10000", - }, - }, - cwd: process.cwd(), - sessionLoadReplayIdleGap: "50 millis", - sessionLoadTimeout: "1 second", - clientInfo: { name: "t3-test", version: "0.0.0" }, - }), - ), - Effect.scoped, - Effect.provide(NodeServices.layer), - TestClock.withLive, - ), - ); - it.effect("rejects invalid config option values before sending session/set_config_option", () => { const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "acp-runtime-")); const requestLogPath = NodePath.join(tempDir, "requests.ndjson"); diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts b/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts index cc911f2c60d0a..7ee010b6f76d5 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.processTree.test.ts @@ -2,21 +2,14 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; -import * as NodeURL from "node:url"; import { describe, expect, it, vi } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; -import * as Scope from "effect/Scope"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; -const threadSpawnHelperSource = NodeURL.fileURLToPath( - new URL("../../../scripts/acp-thread-spawn-helper.c", import.meta.url), -); - const identity = ( pid: number, ppid: number, @@ -63,15 +56,6 @@ function makeController(input: { const server = () => identity(process.pid, 1, process.pid, process.pid, "server"); -function processExists(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - describe("terminatePosixOwnedProcessTree", () => { it("parses unified cgroup paths and escaped cgroup2 mountinfo", () => { expect(AcpSessionRuntime.parseUnifiedCgroupPath("0::/user.slice/app.scope\n")).toBe( @@ -102,9 +86,7 @@ describe("terminatePosixOwnedProcessTree", () => { const scratchRoot = NodePath.join(process.cwd(), "tmp"); NodeFS.mkdirSync(scratchRoot, { recursive: true }); const parent = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-stale-siblings-")); - // Temp dirs are not cgroupfs: rmdir fails when control files exist, so the - // test injects populated/remove while still exercising the real selection - // and path-safety logic against a real parent directory tree. + // Unlike cgroupfs, temp directories cannot rmdir with control files; inject populated/remove. const populatedByPath = new Map(); const writeSibling = (name: string, populated: "0" | "1" | null) => { const path = NodePath.join(parent, name); @@ -178,8 +160,7 @@ describe("terminatePosixOwnedProcessTree", () => { expect(AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: "" })).toBe( bareGrok, ); - // Undefined PATH uses Node's default search path (/usr/bin:/bin), not cwd alone - // (bareGrok lives only in cwd / PATH=scratch). + // Undefined PATH searches /usr/bin:/bin; the bareGrok fixture lives only in cwd. expect( AcpSessionRuntime.resolveLinuxCgroupTargetCommand("grok", scratch, { PATH: undefined }), ).toBeUndefined(); @@ -306,8 +287,7 @@ describe("terminatePosixOwnedProcessTree", () => { }, ); expect(missingTargetResult.status, missingTargetResult.stderr).toBe(125); - // CI's /bin/sh is dash, which runs the EXIT trap after a failed exec. Bash does not, - // so run the same wrapper under bash too. + // dash runs EXIT traps after failed exec; bash does not, so exercise both. const missingTargetBash = NodeChildProcess.spawnSync("bash", missingTarget.args, { encoding: "utf8", }); @@ -321,171 +301,6 @@ describe("terminatePosixOwnedProcessTree", () => { } }); - it.live("kills a post-TERM detached double fork without touching an unrelated sentinel", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const controller = AcpSessionRuntime.makeLinuxCgroupController(); - const lease = controller.create(); - if (lease === undefined) return; - expect( - AcpSessionRuntime.parseUnifiedCgroupPath(NodeFS.readFileSync("/proc/self/cgroup", "utf8")), - ).not.toBe(lease.relativePath); - const scratchRoot = NodePath.join(process.cwd(), "tmp"); - NodeFS.mkdirSync(scratchRoot, { recursive: true }); - const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-cgroup-kill-")); - const readyPath = NodePath.join(scratch, "ready"); - const childPath = NodePath.join(scratch, "child"); - const childProgram = "setInterval(() => {}, 1000);"; - const launcherProgram = [ - 'const fs = require("node:fs");', - 'const cp = require("node:child_process");', - "const child = cp.spawn(process.execPath, ['-e', process.argv[2]], { detached: true, stdio: 'ignore' });", - "fs.writeFileSync(process.argv[1], String(child.pid));", - "child.unref();", - ].join("\n"); - const providerProgram = [ - 'const fs = require("node:fs");', - 'const cp = require("node:child_process");', - "fs.writeFileSync(process.argv[1], String(process.pid));", - "process.on('SIGTERM', () => {", - " const launcher = cp.spawn(process.execPath, ['-e', process.argv[3], process.argv[2], process.argv[4]], { detached: true, stdio: 'ignore' });", - " launcher.unref();", - " process.exit(0);", - "});", - "setInterval(() => {}, 1000);", - ].join("\n"); - const wrapped = AcpSessionRuntime.wrapCommandForLinuxCgroup(lease, process.execPath, [ - "-e", - providerProgram, - readyPath, - childPath, - launcherProgram, - childProgram, - ]); - const provider = NodeChildProcess.spawn(wrapped.command, wrapped.args, { - detached: true, - env: { ...process.env, ELECTRON_RUN_AS_NODE: "1", T3_ACP_CGROUP_WRAPPER: "1" }, - stdio: "ignore", - }); - provider.unref(); - const sentinel = NodeChildProcess.spawn(process.execPath, ["-e", childProgram], { - detached: true, - stdio: "ignore", - }); - sentinel.unref(); - let detachedChildPid: number | undefined; - try { - yield* Effect.gen(function* () { - while (!NodeFS.existsSync(readyPath)) yield* Effect.sleep("10 millis"); - }).pipe(Effect.timeout("2 seconds")); - process.kill(provider.pid!, "SIGTERM"); - detachedChildPid = yield* Effect.gen(function* () { - while (true) { - try { - const pid = Number(NodeFS.readFileSync(childPath, "utf8")); - if (Number.isSafeInteger(pid) && pid > 1) return pid; - } catch {} - yield* Effect.sleep("10 millis"); - } - }).pipe(Effect.timeout("2 seconds")); - expect(processExists(detachedChildPid)).toBe(true); - yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease); - expect(processExists(sentinel.pid!)).toBe(true); - yield* Effect.gen(function* () { - while (processExists(detachedChildPid!)) yield* Effect.sleep("10 millis"); - }).pipe(Effect.timeout("2 seconds")); - expect(NodeFS.existsSync(lease.path)).toBe(false); - - const replacement = controller.create(); - expect(replacement?.path).not.toBe(lease.path); - if (replacement !== undefined) { - NodeFS.mkdirSync(NodePath.join(replacement.path, "nested")); - yield* AcpSessionRuntime.terminateLinuxCgroupLease(replacement); - expect(NodeFS.existsSync(replacement.path)).toBe(false); - } - } finally { - yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease).pipe(Effect.ignore); - try { - process.kill(-provider.pid!, "SIGKILL"); - } catch {} - try { - process.kill(-sentinel.pid!, "SIGKILL"); - } catch {} - if (detachedChildPid !== undefined && processExists(detachedChildPid)) { - try { - process.kill(detachedChildPid, "SIGKILL"); - } catch {} - } - NodeFS.rmSync(scratch, { recursive: true, force: true }); - } - }), - ); - - it.live("re-kills repopulated cgroups and verifies root removal after retryable errors", () => - Effect.gen(function* () { - let exists = true; - let killCalls = 0; - let populated = false; - let removeCalls = 0; - const lease: AcpSessionRuntime.AcpLinuxCgroupLease = { - contains: () => false, - exists: () => exists, - path: "/test/t3-acp-repopulation", - relativePath: "/test/t3-acp-repopulation", - kill: () => { - killCalls += 1; - populated = false; - }, - populated: () => populated, - remove: () => { - removeCalls += 1; - if (removeCalls === 1) { - populated = true; - const error = new Error("repopulated") as NodeJS.ErrnoException; - error.code = "EBUSY"; - throw error; - } - if (removeCalls === 2) { - const error = new Error("nested path vanished") as NodeJS.ErrnoException; - error.code = "ENOENT"; - throw error; - } - exists = false; - }, - }; - - yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease); - expect(killCalls).toBeGreaterThanOrEqual(3); - expect(removeCalls).toBe(3); - expect(exists).toBe(false); - yield* AcpSessionRuntime.terminateLinuxCgroupLease(lease); - expect(removeCalls).toBe(3); - }), - ); - - it.live("reports persistent retryable removal failures as removal failures", () => - Effect.gen(function* () { - const removeError = Object.assign(new Error("cgroup remains busy"), { - code: "EBUSY", - }); - const lease: AcpSessionRuntime.AcpLinuxCgroupLease = { - contains: () => false, - exists: () => true, - path: "/test/t3-acp-busy", - relativePath: "/test/t3-acp-busy", - kill: () => undefined, - populated: () => false, - remove: () => { - throw removeError; - }, - }; - - const error = yield* Effect.flip(AcpSessionRuntime.terminateLinuxCgroupLease(lease)); - expect(error.detail).toBe("Failed to remove ACP cgroup /test/t3-acp-busy"); - expect(error.cause).toBe(removeError); - }), - ); - it("sends TERM only to the exact captured root while it remains in the child cgroup", () => { const fixture = makeController({ processes: [server(), identity(100, process.pid, 100, 100, "owned")], @@ -528,53 +343,6 @@ describe("terminatePosixOwnedProcessTree", () => { expect(migrated.signals).toEqual([]); }); - it.live("finds a child forked by a non-leader pthread", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) !== "linux") return; - const scratchRoot = NodePath.join(process.cwd(), "tmp"); - NodeFS.mkdirSync(scratchRoot, { recursive: true }); - const scratch = NodeFS.mkdtempSync(NodePath.join(scratchRoot, "acp-pthread-spawn-")); - const binary = NodePath.join(scratch, "helper"); - const pidPath = NodePath.join(scratch, "pids"); - expect(NodeFS.statSync(threadSpawnHelperSource).isFile()).toBe(true); - const compile = NodeChildProcess.spawnSync( - "cc", - ["-pthread", threadSpawnHelperSource, "-o", binary], - { - encoding: "utf8", - }, - ); - if ((compile.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") { - NodeFS.rmSync(scratch, { recursive: true, force: true }); - return; - } - expect(compile.status, compile.stderr).toBe(0); - const helper = NodeChildProcess.spawn(binary, [pidPath], { detached: true, stdio: "ignore" }); - helper.unref(); - try { - const published = yield* Effect.gen(function* () { - while (true) { - try { - const ids = NodeFS.readFileSync(pidPath, "utf8").trim().split(/\s+/).map(Number); - if (ids.length === 2 && ids.every(Number.isSafeInteger)) return ids; - } catch {} - yield* Effect.sleep("10 millis"); - } - }).pipe(Effect.timeout("2 seconds")); - const [workerTid, childPid] = published; - expect(workerTid).not.toBe(helper.pid); - expect( - AcpSessionRuntime.makePosixProcessTreeController("linux").childrenOf(helper.pid!), - ).toContainEqual(expect.objectContaining({ pid: childPid, ppid: helper.pid })); - } finally { - try { - process.kill(-helper.pid!, "SIGKILL"); - } catch {} - NodeFS.rmSync(scratch, { recursive: true, force: true }); - } - }), - ); - it.live("keeps ownership across a fork-before-exec executable transition", () => Effect.gen(function* () { const beforeExec = { ...identity(110, 100, 110, 110), executable: "/provider/fork" }; @@ -650,8 +418,7 @@ describe("terminatePosixOwnedProcessTree", () => { it.live("rotates more than 64 live parents without scanning retained tombstones", () => Effect.gen(function* () { - // The server fixture's process group is the runner's real pid, so a synthetic - // parent sharing it would be skipped as the server's own group. + // Use a different synthetic parent group; the fixture shares the runner's real group, which cleanup skips. const parentPidBase = process.pid < 500_000 ? 500_000 : 1_000; const parents = Array.from({ length: 130 }, (_, index) => identity(parentPidBase + index, 100, parentPidBase + index, parentPidBase + index), @@ -742,73 +509,6 @@ describe("terminatePosixOwnedProcessTree", () => { }), ); - it.live("polls only known descendants and stops with its scope", () => - Effect.gen(function* () { - let childrenCalls = 0; - let identityCalls = 0; - let snapshotCalls = 0; - const fixture = makeController({ - processes: [server(), identity(100, process.pid, 100, 100), identity(110, 100, 110, 110)], - }); - const controller: AcpSessionRuntime.AcpPosixProcessTreeController = { - ...fixture.controller, - childPidsOf: (pid) => { - childrenCalls += 1; - return fixture.controller.childPidsOf(pid); - }, - identity: (pid) => { - identityCalls += 1; - return fixture.controller.identity(pid); - }, - snapshot: () => { - snapshotCalls += 1; - return fixture.controller.snapshot(); - }, - }; - const scope = yield* Scope.make(); - const frontier = new Map(); - const childQueues = new Map>(); - let ledgerValuesCalls = 0; - const ledger = new (class extends Map { - override values(): MapIterator { - ledgerValuesCalls += 1; - return super.values(); - } - })(); - const root: AcpSessionRuntime.AcpPosixOwnershipRoot = { value: undefined }; - for (let index = 0; index < 5_000; index += 1) { - const tombstone = identity(10_000 + index, 1, 10_000 + index, 10_000 + index); - ledger.set(`${tombstone.pid}:${tombstone.startTime}`, { - ...tombstone, - parentExecutable: undefined, - parentStartTime: "", - }); - } - yield* AcpSessionRuntime.observePosixOwnershipLedgerContinuously({ - childQueues, - controller, - frontier, - ledger, - root, - rootPid: 100, - }).pipe(Effect.forkIn(scope)); - const timerStartedAt = yield* Clock.currentTimeMillis; - yield* Effect.sleep(0); - const timerDelay = (yield* Clock.currentTimeMillis) - timerStartedAt; - yield* Effect.sleep("80 millis"); - - expect(timerDelay).toBeLessThan(250); - expect(ledgerValuesCalls).toBe(0); - expect(snapshotCalls).toBe(0); - expect(childrenCalls).toBeGreaterThan(0); - expect(childrenCalls).toBeLessThanOrEqual(12); - const callsAtClose = identityCalls + childrenCalls; - yield* Scope.close(scope, Exit.void); - yield* Effect.sleep("60 millis"); - expect(identityCalls + childrenCalls).toBe(callsAtClose); - }), - ); - it.live("terminates nested owned groups bottom-up and catches a TERM fork race", () => Effect.gen(function* () { let forked = false; @@ -942,7 +642,6 @@ describe("terminatePosixOwnedProcessTree", () => { grace: 0, rootPid: 100, }); - // Zombies remain visible but must not fail residual teardown. expect(fixture.processes.get(100)?.state).toBe("Z"); expect(fixture.processes.get(110)?.state).toBe("Z"); }), @@ -988,36 +687,6 @@ describe("terminatePosixOwnedProcessTree", () => { expect(admitted?.startTime).toBe("live-child"); }); - it("admits a live child when a stale ledger entry still occupies the reused PID", () => { - const staleChild: AcpSessionRuntime.AcpOwnedPosixProcess = { - ...identity(200, 100, 200, 200, "stale-child"), - parentExecutable: `/proc/100/exe`, - parentStartTime: "100", - }; - const liveChild = identity(200, 100, 200, 200, "live-child"); - const root = identity(100, process.pid, 100, 100); - const ownedRoot: AcpSessionRuntime.AcpOwnedPosixProcess = { - ...root, - parentExecutable: `/proc/${process.pid}/exe`, - parentStartTime: "server", - }; - const ledger = new Map([ - [`100:${root.startTime}`, ownedRoot], - [`200:${staleChild.startTime}`, staleChild], - ]); - - AcpSessionRuntime.capturePosixOwnershipLedger({ - controller: makeController({ processes: [server(), root, liveChild] }).controller, - ledger, - rootPid: 100, - table: [root, liveChild], - }); - - expect([...ledger.values()].some((entry) => entry.startTime === "stale-child")).toBe(false); - const admitted = [...ledger.values()].find((entry) => entry.pid === 200); - expect(admitted?.startTime).toBe("live-child"); - }); - it.live("signals children forked under a still-live parent during the same pass", () => Effect.gen(function* () { let forked = false; diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index 8bb03d3469cb9..b36c4afe91596 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -4,7 +4,6 @@ import { ANTIGRAVITY_DEFAULT_MODEL, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, type ChatAttachment, - type RuntimeMode, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -14,7 +13,6 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { - antigravityPermissionMode, applyAntigravityAcpModelSelection, buildAntigravityPrompt, } from "./AntigravityAcpSupport.ts"; @@ -60,22 +58,6 @@ describe("applyAntigravityAcpModelSelection", () => { }), ); - it.effect("reapplies an explicit selection even when setup reports the same model", () => - Effect.gen(function* () { - const { runtime, selections } = makeModelRuntime([ - { ...modelConfig, currentValue: "gemini-saved" }, - ]); - const model = yield* applyAntigravityAcpModelSelection({ - runtime, - model: "gemini-saved", - mapError: (cause) => cause, - }); - - expect(model).toBe("gemini-saved"); - expect(selections).toEqual(["gemini-saved"]); - }), - ); - it.effect.each([undefined, null, ANTIGRAVITY_DEFAULT_MODEL])( "uses the native default for %s without sending an internal model ID", (requestedModel) => @@ -154,34 +136,6 @@ describe("applyAntigravityAcpModelSelection", () => { expect(selections).toEqual(["gemini-saved"]); }), ); - - it.effect("reports a native model-selection failure through the adapter error mapper", () => - Effect.gen(function* () { - const nativeError = EffectAcpErrors.AcpRequestError.invalidParams("Model access changed."); - const { runtime } = makeModelRuntime([modelConfig], nativeError); - const error = yield* applyAntigravityAcpModelSelection({ - runtime, - model: "gemini-saved", - mapError: (cause) => ({ operation: "select-model", cause }), - }).pipe(Effect.flip); - - expect(error).toEqual({ operation: "select-model", cause: nativeError }); - }), - ); -}); - -describe("antigravityPermissionMode", () => { - it.each([ - { runtimeMode: "approval-required", nativeMode: "default" }, - { runtimeMode: "auto", nativeMode: "default" }, - { runtimeMode: "auto-accept-edits", nativeMode: "auto_edit" }, - { runtimeMode: "full-access", nativeMode: "yolo" }, - ] satisfies ReadonlyArray<{ runtimeMode: RuntimeMode; nativeMode: string }>)( - "maps $runtimeMode to $nativeMode", - ({ runtimeMode, nativeMode }) => { - expect(antigravityPermissionMode(runtimeMode)).toBe(nativeMode); - }, - ); }); const imageAttachment = { @@ -298,30 +252,6 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }), ); - it.effect("rejects missing folded clipboard text", () => - Effect.gen(function* () { - const fixture = yield* makeAttachmentFixture(); - const pastedText = { - ...textAttachment, - name: "pasted-text.txt", - mimeType: "text/plain", - source: { _tag: "pasted-text" as const }, - } satisfies ChatAttachment; - - const error = yield* buildAntigravityPrompt({ - input: "Inspect the pasted text only as needed.", - attachments: [pastedText], - attachmentsDir: fixture.attachmentsDir, - }).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "AcpRequestError", - code: -32602, - errorMessage: "Could not read attachment 'pasted-text.txt'.", - }); - }), - ); - it.effect.each([ { name: "archive.zip", mimeType: "application/zip" }, { name: "clip.mp4", mimeType: "video/mp4" }, @@ -381,34 +311,6 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }), ); - it.effect("uses a PDF file resource link without copying or reading its bytes", () => - Effect.gen(function* () { - const fixture = yield* makeAttachmentFixture(); - const upload = yield* fixture.write(pdfAttachment, "%PDF-1.7\n"); - const forbidFileAccess = () => - Effect.die("PDF prompt construction must only inspect the file."); - const prompt = yield* buildAntigravityPrompt({ - input: undefined, - attachments: [pdfAttachment], - attachmentsDir: fixture.attachmentsDir, - }).pipe( - Effect.provideService(FileSystem.FileSystem, { - ...fixture.fs, - readFile: forbidFileAccess, - writeFile: forbidFileAccess, - writeFileString: forbidFileAccess, - copyFile: forbidFileAccess, - copy: forbidFileAccess, - rename: forbidFileAccess, - }), - ); - - expect(prompt).toEqual([ - { type: "resource_link", uri: upload.uri, name: "report.pdf", mimeType: "application/pdf" }, - ]); - }), - ); - it.effect.each([ { ...imageAttachment, name: "animation.gif", mimeType: "image/gif" }, ] satisfies ReadonlyArray)( @@ -583,21 +485,4 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => { }); }), ); - - it.effect("rejects an empty turn", () => - Effect.gen(function* () { - const fixture = yield* makeAttachmentFixture(); - const error = yield* buildAntigravityPrompt({ - input: " ", - attachments: [], - attachmentsDir: fixture.attachmentsDir, - }).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "AcpRequestError", - code: -32602, - errorMessage: "A turn requires text or supported attachments.", - }); - }), - ); }); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 9ba55af7cf2ca..0b3ef2603dcb3 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -248,9 +248,7 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi attachment.type === "file" && "source" in attachment && attachment.source?._tag === "pasted-text"; - // ProviderService has already put the file path in the text block. Keep a - // folded clipboard paste lazy so the agent can search or sample it rather - // than paying to embed the entire resource in context immediately. + // The text already carries the path; keep folded pastes lazy so agents can search without embedding the whole file. const mimeType = attachment.mimeType.toLowerCase().split(";", 1)[0] ?? ""; const image = attachment.type === "image" && IMAGE_MIME_TYPES.has(mimeType); const audio = attachment.type === "file" && AUDIO_MIME_TYPES.has(mimeType); diff --git a/apps/server/src/provider/acp/AntigravityClientFiles.ts b/apps/server/src/provider/acp/AntigravityClientFiles.ts index b31b66149c7c4..ebbc234e149b9 100644 --- a/apps/server/src/provider/acp/AntigravityClientFiles.ts +++ b/apps/server/src/provider/acp/AntigravityClientFiles.ts @@ -4,10 +4,7 @@ import type * as Path from "effect/Path"; import * as EffectAcpErrors from "effect-acp/errors"; import type * as EffectAcpSchema from "effect-acp/compat"; -/** - * The agent gates each write behind `session/request_permission`, so only - * path containment is checked here. - */ +/** The agent requests permission for every write; check only path containment here. */ const CLIENT_FILE_MAX_BYTES = 8 * 1024 * 1024; function isInsideRoot(path: Path.Path, root: string, candidate: string): boolean { @@ -15,10 +12,7 @@ function isInsideRoot(path: Path.Path, root: string, candidate: string): boolean return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); } -/** - * Symlinks resolve before the check, including the final component, so a link - * inside the workspace cannot read or write through to a file outside it. - */ +/** Resolve all symlinks, including the final component, before checking workspace containment. */ const resolveClientFilePath = Effect.fn("AntigravityClientFiles.resolveClientFilePath")( function* (input: { readonly fileSystem: FileSystem.FileSystem; @@ -34,8 +28,7 @@ const resolveClientFilePath = Effect.fn("AntigravityClientFiles.resolveClientFil const real = yield* input.fileSystem.realPath(resolved).pipe( Effect.catch(() => Effect.gen(function* () { - // Only a missing file (a new write) falls back to its parent; a - // dangling or unreadable link must not be followed on write. + // Fall back to the parent only for missing files, never dangling or unreadable links. const entryExists = yield* input.fileSystem.readLink(resolved).pipe( Effect.as(true), Effect.catch(() => input.fileSystem.exists(resolved)), diff --git a/apps/server/src/provider/acp/AntigravityProtocol.test.ts b/apps/server/src/provider/acp/AntigravityProtocol.test.ts index cfc7a6adfbe19..20d084c4bf81b 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.test.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.test.ts @@ -454,28 +454,6 @@ describe("Antigravity tool results", () => { expect(serialized).not.toContain("inline-data-url"); }); - it("keeps large assistant replies and startup command metadata unchanged", () => { - const notifications = [ - { - sessionId: "session-1", - update: { - sessionUpdate: "agent_message_chunk", - content: { type: "text", text: "a".repeat(20_000) }, - }, - }, - { - sessionId: "session-1", - update: { - sessionUpdate: "available_commands_update", - availableCommands: [{ name: "plan", description: "Make a plan" }], - }, - }, - ] satisfies ReadonlyArray; - for (const notification of notifications) { - expect(normalizeAntigravitySessionUpdate(notification)).toBe(notification); - } - }); - it("tracks only commands that have passed approval and are still running", () => { const running = normalizeAntigravityToolCall(parseToolUpdate(commandStarted).toolCall); expect(isAntigravityOpenCommand(running)).toBe(true); diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index 5c1ee06ee5f2e..d3940dfc3d8c0 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -69,10 +69,7 @@ const decodeSecurityWarning = Schema.decodeUnknownOption( }), ); -/** - * The agent marks "Allow Always" on shell and web tools with a prompt injection - * warning in `_meta`. Surface it as option text so both clients can show it. - */ +/** Expose shell/web Allow Always _meta warnings as option text for both clients. */ function antigravitySecurityWarning(option: EffectAcpSchema.PermissionOption): string | undefined { const meta = option._meta; if (!Predicate.isObject(meta)) return undefined; @@ -346,10 +343,7 @@ export function isAntigravityOpenCommand(toolCall: AcpToolCallState): boolean { return toolCall.kind === "execute" && toolCall.status === "inProgress"; } -/** - * ACP 1.1.1 exposes subagent invocations as ordinary tools, without child IDs - * or models. - */ +/** ACP 1.1.1 reports subagent calls as ordinary tools without child IDs or models. */ export function classifyAntigravitySubagentToolCall( toolCall: AcpToolCallState, rawPayload?: unknown, diff --git a/apps/server/src/provider/acp/AntigravitySessionFiles.ts b/apps/server/src/provider/acp/AntigravitySessionFiles.ts index be6174c33ffdb..7a25c8323174d 100644 --- a/apps/server/src/provider/acp/AntigravitySessionFiles.ts +++ b/apps/server/src/provider/acp/AntigravitySessionFiles.ts @@ -42,12 +42,7 @@ export const removeAntigravitySessionFiles = Effect.fn("removeAntigravitySession Effect.catch(() => Effect.logWarning("Could not remove temporary Antigravity session files.")), ); -/** - * Call once when the driver starts, before it launches any process, so a previous server that was - * killed mid-session cannot leave unpacked runtimes behind. The system temp directory belongs to - * other programs and Windows does not lock data files, so sweeping it could gut a live - * extraction. - */ +/** Sweep only private runtimes before launch; Windows does not protect live extracted data files from deletion. */ export const removeAntigravityRuntimeTempDirs = Effect.fn("removeAntigravityRuntimeTempDirs")( function* (tempDirectory: string) { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/provider/antigravityAuthSupport.test.ts b/apps/server/src/provider/antigravityAuthSupport.test.ts index dad00aa760344..9138a28dab5b3 100644 --- a/apps/server/src/provider/antigravityAuthSupport.test.ts +++ b/apps/server/src/provider/antigravityAuthSupport.test.ts @@ -1,6 +1,3 @@ -// @effect-diagnostics-next-line nodeBuiltinImport:off -import * as NodeChildProcess from "node:child_process"; - import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodePath from "@effect/platform-node/NodePath"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -15,20 +12,15 @@ import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as Ndjson from "effect/encoding/Ndjson"; -import * as ChildProcess from "effect/process/ChildProcess"; -import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as AcpErrors from "effect-acp/errors"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import { ANTIGRAVITY_AUTH_BROWSER_MARKER, ANTIGRAVITY_AUTH_STDOUT_PREFIX, - ANTIGRAVITY_PERSONAL_AUTH, ANTIGRAVITY_SIGN_IN_REQUIRED_MESSAGE, type AntigravityAuthConfig, - antigravityAuthConfigIssue, type AntigravityProfile, - antigravityProfileSettings, buildAntigravityAcpSpawnInput, isAntigravitySignInRequiredError, makeAntigravityStderrHandler, @@ -150,47 +142,6 @@ describe("Antigravity process environment", () => { expect(business.GOOGLE_API_KEY).toBeUndefined(); }); - it("writes the auth method and GCP block into the agent's settings.json", () => { - expect( - decodeJson( - antigravityProfileSettings({ - authMethod: "oauth-business", - apiKey: "never-written", - gcpProject: "proj", - gcpLocation: "us-central1", - }), - ), - ).toEqual({ - auth: { type: "oauth-business" }, - gcp: { project: "proj", location: "us-central1" }, - }); - expect(decodeJson(antigravityProfileSettings(ANTIGRAVITY_PERSONAL_AUTH))).toEqual({ - auth: { type: "oauth-personal" }, - }); - }); - - it("names the missing credential for each method", () => { - expect(antigravityAuthConfigIssue(ANTIGRAVITY_PERSONAL_AUTH)).toBeNull(); - expect( - antigravityAuthConfigIssue({ ...ANTIGRAVITY_PERSONAL_AUTH, authMethod: "gemini-api-key" }), - ).toContain("API key"); - expect( - antigravityAuthConfigIssue({ - ...ANTIGRAVITY_PERSONAL_AUTH, - authMethod: "oauth-business", - gcpProject: "proj", - }), - ).toContain("location"); - expect( - antigravityAuthConfigIssue({ - ...ANTIGRAVITY_PERSONAL_AUTH, - authMethod: "agent-platform", - gcpProject: "proj", - gcpLocation: "us-central1", - }), - ).toBeNull(); - }); - it("isolates TEMP and TMP to the profile directory on Windows", () => { const windowsProfile: AntigravityProfile = { platform: "win32", @@ -220,30 +171,6 @@ describe("Antigravity process environment", () => { expect(perRun.env?.TMP).toBe(`${windowsProfile.tempDirectory}\\run-1`); }); - it("isolates TMPDIR to the profile directory on POSIX hosts", () => { - const spawn = buildAntigravityAcpSpawnInput({ - installation: { executablePath: "/release/acp", harnessPath: "/release/harness" }, - profile, - cwd: "/project", - baseEnv: { TMPDIR: "/tmp" }, - runtimeTempDirectory: `${profile.tempDirectory}/run-1`, - }); - expect(spawn.env?.TMPDIR).toBe(`${profile.tempDirectory}/run-1`); - expect(spawn.env?.TEMP).toBeUndefined(); - }); - - it("uses the registry launch arguments for each supported host platform", () => { - for (const platform of ["linux", "darwin", "win32"] as const) { - const spawn = buildAntigravityAcpSpawnInput({ - installation: { executablePath: "/release/acp", harnessPath: "/release/harness" }, - profile: { ...profile, platform }, - cwd: "/project", - baseEnv: {}, - }); - expect(spawn.args).toEqual(platform === "linux" ? ["--uid="] : []); - } - }); - it.effect("keeps accounts separate even when instance IDs differ only by case", () => Effect.gen(function* () { const first = yield* resolveAntigravityInstanceDirectories( @@ -284,16 +211,6 @@ describe("Antigravity process environment", () => { }); describe("Antigravity authorization URL", () => { - it.effect("returns the official Google URL and its owned loopback target", () => - Effect.gen(function* () { - expect(yield* parseAntigravityAuthorizationUrl(authorizationUrl)).toEqual({ - authorizationUrl, - redirectUri: "http://127.0.0.1:46353/", - state: "test-opaque-state", - }); - }), - ); - it.effect( "rejects other origins, ambiguous state, and non-loopback redirects without retaining them", () => @@ -377,17 +294,6 @@ describe("Antigravity stdout compatibility", () => { }), ); - it.effect("handles an auth line without a final newline", () => - Effect.gen(function* () { - const urls: string[] = []; - const result = yield* makeAntigravityStdoutTransform({ - onAuthorizationUrl: (url) => Effect.sync(() => void urls.push(url)), - })(Stream.make(encode(authLine.slice(0, -1)))).pipe(Stream.runCollect); - expect(result).toEqual([]); - expect(urls).toEqual([authorizationUrl]); - }), - ); - it.effect("ends normal work with a safe sign-in error instead of waiting for OAuth", () => Effect.gen(function* () { const result = yield* makeAntigravityStdoutTransform()(Stream.make(encode(authLine))).pipe( @@ -484,22 +390,6 @@ describe("Antigravity stderr compatibility", () => { }), ); - it.effect("preserves failures from the sign-in flow owner", () => - Effect.gen(function* () { - const failure = new AcpErrors.AcpTransportError({ - detail: "The sign-in flow stopped.", - cause: undefined, - }); - const handleStderr = makeAntigravityStderrHandler({ - onAuthorizationUrl: () => Effect.fail(failure), - }); - const error = yield* handleStderr( - `${ANTIGRAVITY_AUTH_STDOUT_PREFIX}${authorizationUrl}\n`, - ).pipe(Effect.flip); - expect(error).toBe(failure); - }), - ); - it.effect("forwards an accepted browser-helper URL larger than 8 KiB", () => Effect.gen(function* () { const urls: string[] = []; @@ -556,6 +446,72 @@ describe("Antigravity stderr compatibility", () => { }); it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => { + const prepareSpawn = Effect.fn(function* ( + bundles: ReadonlyArray, + baseEnv: NodeJS.ProcessEnv = {}, + platform: NodeJS.Platform = "linux", + ) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped(); + const profile = yield* prepareAntigravityProfile({ + profileDirectory: path.join(directory, "profile"), + userHome: path.join(directory, "home"), + runtimeExecutablePath: process.execPath, + platform, + baseEnv, + }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + exists: (candidate) => Effect.succeed(bundles.includes(candidate)), + }), + ); + return buildAntigravityAcpSpawnInput({ + installation: { executablePath: "/release/acp", harnessPath: "/release/harness" }, + profile, + cwd: directory, + baseEnv, + }).env; + }); + + // A Windows Node path cannot preflight the browser helper as a POSIX host. + const caTest = it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32"); + + caTest( + "launches Linux agents with the first available CA bundle, preferring absolute Nix paths", + () => + Effect.gen(function* () { + const systemBundles = ["/etc/pki/tls/certs/ca-bundle.crt", "/etc/ssl/cert.pem"]; + const nixBundle = "/nix/store/nss-cacert/etc/ssl/certs/ca-bundle.crt"; + expect((yield* prepareSpawn(systemBundles))?.SSL_CERT_FILE).toBe(systemBundles[0]); + expect( + (yield* prepareSpawn([nixBundle, ...systemBundles], { NIX_SSL_CERT_FILE: nixBundle })) + ?.SSL_CERT_FILE, + ).toBe(nixBundle); + expect( + (yield* prepareSpawn(systemBundles, { NIX_SSL_CERT_FILE: nixBundle }))?.SSL_CERT_FILE, + ).toBe(systemBundles[0]); + expect( + (yield* prepareSpawn(["certs/local.pem", ...systemBundles], { + NIX_SSL_CERT_FILE: "certs/local.pem", + }))?.SSL_CERT_FILE, + ).toBe(systemBundles[0]); + expect((yield* prepareSpawn([]))?.SSL_CERT_FILE).toBeUndefined(); + }), + ); + + caTest("preserves explicit certificate files and directories in Linux launches", () => + Effect.gen(function* () { + const bundles = ["/etc/ssl/certs/ca-certificates.crt"]; + expect( + (yield* prepareSpawn(bundles, { SSL_CERT_FILE: "/custom/ca.pem" }))?.SSL_CERT_FILE, + ).toBe("/custom/ca.pem"); + const directoryEnv = yield* prepareSpawn(bundles, { SSL_CERT_DIR: "/custom/certs" }); + expect(directoryEnv?.SSL_CERT_DIR).toBe("/custom/certs"); + expect(directoryEnv?.SSL_CERT_FILE).toBeUndefined(); + }), + ); + it.effect("runs the browser helper with installed Node in standalone builds", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -683,61 +639,6 @@ it.layer(NodeServices.layer)("Antigravity profile preparation", (it) => { }), ); - it.effect("keeps the browser helper successful when cancellation closes stderr", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const temporaryDirectory = yield* fs.makeTempDirectoryScoped(); - let helperCommand: ChildProcess.StandardCommand | undefined; - yield* prepareAntigravityProfile({ profileDirectory: temporaryDirectory }).pipe( - Effect.provideService( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make((command) => { - if (ChildProcess.isStandardCommand(command)) helperCommand = command; - return spawner.spawn(command); - }), - ), - ); - expect(helperCommand).toBeDefined(); - if (!helperCommand) return; - const command = helperCommand; - const child = yield* Effect.acquireRelease( - Effect.sync(() => - NodeChildProcess.spawn(command.command, command.args, { - env: { ...command.options.env }, - stdio: ["ignore", "ignore", "pipe"], - }), - ), - (process) => Effect.sync(() => void process.kill()), - ); - child.stderr?.destroy(); - const exitCode = yield* Effect.promise( - () => - new Promise((resolve, reject) => { - child.once("error", reject); - child.once("exit", resolve); - }), - ); - expect(exitCode).toBe(0); - }), - ); - - it.effect("fails before creating a profile when the helper cannot start", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const temporaryDirectory = yield* fs.makeTempDirectoryScoped(); - const profileDirectory = path.join(temporaryDirectory, "unused-profile"); - const result = yield* prepareAntigravityProfile({ - profileDirectory, - runtimeExecutablePath: path.join(temporaryDirectory, "missing-runtime"), - }).pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - expect(yield* fs.exists(profileDirectory)).toBe(false); - }), - ); - it.effect("rejects Python BROWSER delimiter collisions before starting a helper", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/provider/antigravityAuthSupport.ts b/apps/server/src/provider/antigravityAuthSupport.ts index 216dbc7aa8585..5030b53005e89 100644 --- a/apps/server/src/provider/antigravityAuthSupport.ts +++ b/apps/server/src/provider/antigravityAuthSupport.ts @@ -51,9 +51,7 @@ const encodeProfileSettings = Schema.encodeSync(Schema.fromJsonString(ProfileSet const isAcpRequestError = Schema.is(AcpErrors.AcpRequestError); const isAcpTransportError = Schema.is(AcpErrors.AcpTransportError); -// Python splits BROWSER on the platform path separator before it parses quotes. -// EPIPE must still exit 0 so Python does not fall back to an OS browser after -// cancellation. +// Python splits BROWSER on path separators before parsing quotes. Exit 0 on EPIPE to prevent browser fallback after cancellation. const browserHelperSource = `process.stderr.on("error",()=>process.exit(0)).write(` + `"${ANTIGRAVITY_AUTH_BROWSER_MARKER}"+JSON.stringify(process.argv[1])+"\\n",` + @@ -87,6 +85,7 @@ export interface AntigravityProfile { readonly tokenPath: string; readonly tempDirectory: string; readonly browserCommand: string; + readonly caBundlePath?: string; } export interface AntigravityAuthConfig { @@ -96,7 +95,7 @@ export interface AntigravityAuthConfig { readonly gcpLocation: string; } -export const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = { +const ANTIGRAVITY_PERSONAL_AUTH: AntigravityAuthConfig = { authMethod: "oauth-personal", apiKey: "", gcpProject: "", @@ -141,7 +140,7 @@ export function antigravityAuthConfigIssue(auth: AntigravityAuthConfig): string * `auth.type` names the selected method so a native logout clears only that method's credentials * instead of every stored token. Never holds a credential. */ -export function antigravityProfileSettings(auth: AntigravityAuthConfig): string { +function antigravityProfileSettings(auth: AntigravityAuthConfig): string { const gcp = { ...(auth.gcpProject ? { project: auth.gcpProject } : {}), ...(auth.gcpLocation ? { location: auth.gcpLocation } : {}), @@ -171,10 +170,7 @@ export function isAntigravitySignInRequiredError(error: unknown): boolean { export interface AntigravityInstanceDirectories { readonly profile: string; - /** - * It sits beside the profile, not inside it: the agent unpacks members up to 120 characters deep, - * and the profile's longer name would push them past Windows' 260-character path limit. - */ + /** Keep beside the profile: 120-character archive members under its longer name would exceed Windows' 260-character limit. */ readonly runtimeTemp: string; } @@ -206,21 +202,23 @@ function antigravityEnvironment( // Windows treats environment keys as case-insensitive. Remove aliases too. if (!removedEnvironmentKeys.has(key.toUpperCase())) environment[key] = value; } - // The agent prefers GOOGLE_API_KEY over the GCP pair for Agent Platform, so the pair goes through - // settings.json instead of the environment. + // Put the GCP pair in settings.json because GOOGLE_API_KEY takes precedence in the environment. const credential = auth.authMethod === "gemini-api-key" && auth.apiKey ? { GEMINI_API_KEY: auth.apiKey } : auth.authMethod === "agent-platform" && auth.apiKey ? { GOOGLE_API_KEY: auth.apiKey } : {}; - // It unpacks about 1 GB into the system temp directory per launch and a force - // kill leaves that behind. Point it at a T3-owned directory so the driver can - // reclaim the space. + // Each launch unpacks about 1 GB; use T3-owned temp so the driver can reclaim files after force-kill. const tempDirectory = runtimeTempDirectory ?? profile.tempDirectory; return { ...environment, ...credential, + ...(profile.caBundlePath !== undefined && + baseEnv.SSL_CERT_FILE === undefined && + baseEnv.SSL_CERT_DIR === undefined + ? { SSL_CERT_FILE: profile.caBundlePath } + : {}), GEMINI_HOME: profile.geminiHome, AGY_ACP_FORCE_FILE_STORAGE: "1", BROWSER: profile.browserCommand, @@ -232,12 +230,7 @@ function antigravityEnvironment( }; } -/** - * The agent reads its user-global skills under `GEMINI_HOME`, which T3 points - * at the private profile. Link the two skill directories back to the user's - * real `~/.gemini` so global skills load, while MCP servers, hooks, and - * credentials stay isolated. - */ +/** Private GEMINI_HOME isolates credentials/hooks/MCP; link global skills from the real ~/.gemini. */ const linkAntigravityUserSkills = Effect.fn("linkAntigravityUserSkills")(function* (input: { readonly profileDirectory: string; readonly userHome: string; @@ -327,6 +320,27 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( const geminiHome = path.resolve(input.profileDirectory); const acpDirectory = path.join(geminiHome, "antigravity-acp"); const tempDirectory = input.tempDirectory ?? path.join(acpDirectory, "tmp"); + let caBundlePath: string | undefined; + if (platform === "linux") { + // Bundled Python may look for certificates at paths absent on this distribution. + // Relative paths would resolve differently when the agent runs in the project directory. + for (const candidate of [ + (input.baseEnv ?? process.env).NIX_SSL_CERT_FILE, + "/etc/ssl/certs/ca-bundle.crt", + "/etc/ssl/certs/ca-certificates.crt", + "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/cert.pem", + ]) { + if ( + candidate && + path.isAbsolute(candidate) && + (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) + ) { + caBundlePath = candidate; + break; + } + } + } const profile: AntigravityProfile = { platform, geminiHome, @@ -334,6 +348,7 @@ export const prepareAntigravityProfile = Effect.fn("prepareAntigravityProfile")( tokenPath: path.join(acpDirectory, "acp_token.json"), tempDirectory, browserCommand, + ...(caBundlePath === undefined ? {} : { caBundlePath }), }; const environment = antigravityEnvironment(profile, input.baseEnv ?? process.env, auth); yield* Effect.gen(function* () { diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index 6fa7f65f84316..7c0eeabb0a755 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -146,7 +146,6 @@ describe("Antigravity subscription limits", () => { expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56); yield* probe; expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1); - // Both quota endpoints are read on every probe. expect( requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")), ).toHaveLength(4); @@ -157,8 +156,7 @@ describe("Antigravity subscription limits", () => { Effect.gen(function* () { const { probe } = yield* fixture({ summaryByHost: { - // The daily endpoint has answered with only the Claude/GPT group; the - // other endpoint returns the full default summary. + // The daily endpoint can omit Gemini while the other endpoint returns all groups. "daily-cloudcode-pa.googleapis.com": { groups: [ { @@ -181,8 +179,6 @@ describe("Antigravity subscription limits", () => { ]); const byId = new Map(limits.windows.map((window) => [window.id, window])); expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly"); - // When endpoints disagree about a bucket, the most-used reading wins, - // whichever endpoint reported it. expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70); expect(byId.get("3p-weekly")?.usedPercent).toBe(100); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), @@ -284,21 +280,6 @@ describe("Antigravity subscription limits", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("preserves cached access token when quota endpoints return no usable windows", () => - Effect.gen(function* () { - const { probe, requests } = yield* fixture({ - summary: { groups: [] }, - models: { models: {} }, - }); - const first = yield* probe; - expect(first.unavailable?.reason).toBe("probeFailed"); - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1); - const second = yield* probe; - expect(second.unavailable?.reason).toBe("probeFailed"); - expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("returns a safe failure when OAuth refresh fails", () => Effect.gen(function* () { const { probe } = yield* fixture({ tokenStatus: 401 }); diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index 55ef3579942fb..75333ae8262e7 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -223,8 +223,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( ), ).pipe(Effect.flatMap(decodeTokenResponse)); accessToken = refreshed.access_token; - // Each machine's sign-in has its own refresh token, so the Google - // account id is what lets clients merge one account across environments. + // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. account = yield* request( HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), @@ -246,9 +245,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( accessToken = cached.accessToken; account = cached.account; } - // Endpoints can report different quota groups (the daily endpoint has - // returned the Claude/GPT group without Gemini), so merge every endpoint's - // windows. The most-used reading of a bucket wins, as in modelWindows. + // Merge endpoints because quota groups differ; keep each bucket's most-used reading. const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* ( operation: string, parse: (response: unknown) => Effect.Effect, diff --git a/apps/server/src/provider/builtInDrivers.ts b/apps/server/src/provider/builtInDrivers.ts index 065bce7271172..32b2347589c8c 100644 --- a/apps/server/src/provider/builtInDrivers.ts +++ b/apps/server/src/provider/builtInDrivers.ts @@ -45,12 +45,10 @@ export type BuiltInUsageReadersEnv = | ProviderUsageReaderEnv | ProviderUsageReaderEnv | ProviderUsageReaderEnv - | ProviderUsageReaderEnv; + | ProviderUsageReaderEnv + | ProviderUsageReaderEnv; -/** - * Aggregation keeps the first copy of a duplicate record, so the order is part - * of the result. - */ +/** Order matters: aggregation keeps the first duplicate record. */ export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray< AnyProviderDriver > = [ @@ -59,6 +57,7 @@ export const BUILT_IN_USAGE_DRIVERS: ReadonlyArray< GrokDriver, PiDriver, OpenCodeDriver, + MuseDriver, AntigravityDriver, CursorDriver, ]; diff --git a/apps/server/src/provider/claudeResetCredits.test.ts b/apps/server/src/provider/claudeResetCredits.test.ts index c946afb668320..8db751657454c 100644 --- a/apps/server/src/provider/claudeResetCredits.test.ts +++ b/apps/server/src/provider/claudeResetCredits.test.ts @@ -1,13 +1,10 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it as effectIt } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; -import * as Fiber from "effect/Fiber"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; -import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse, UrlParams } from "effect/http"; import { describe, expect, it } from "vite-plus/test"; @@ -209,41 +206,6 @@ effectIt.layer(NodeServices.layer)("consumeClaudeResetCredit", (it) => { }), ); - it.effect("times out a stalled claim body", () => - Effect.gen(function* () { - const login = yield* writeLogin; - const readingBody = yield* Deferred.make(); - const client = HttpClient.make((request) => { - const response = HttpClientResponse.fromWeb(request, Response.json({ result: "reset" })); - Object.defineProperty(response, "json", { - value: Deferred.succeed(readingBody, undefined).pipe(Effect.andThen(Effect.never)), - }); - return Effect.succeed(response); - }); - const claim = yield* ClaudeResetCredits.consumeClaudeResetCredit({ - ...login, - version: "2.1.0", - grantId: "grant_a", - requestId: "r-1", - }).pipe( - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(HttpClient.HttpClient, client), - Effect.result, - Effect.forkChild, - ); - yield* Deferred.await(readingBody); - yield* TestClock.adjust("26 seconds"); - expect(yield* Fiber.join(claim)).toMatchObject({ - _tag: "Failure", - failure: { - _tag: "ClaudeResetCreditError", - reason: "requestFailed", - cause: { _tag: "TimeoutError" }, - }, - }); - }).pipe(Effect.provide(TestClock.layer())), - ); - it.effect("refuses malformed ids without sending anything", () => Effect.gen(function* () { for (const ids of [ diff --git a/apps/server/src/provider/claudeResetCredits.ts b/apps/server/src/provider/claudeResetCredits.ts index 4736fbe497084..35973378edada 100644 --- a/apps/server/src/provider/claudeResetCredits.ts +++ b/apps/server/src/provider/claudeResetCredits.ts @@ -81,9 +81,7 @@ class ClaudeResetCreditError extends Schema.TaggedError( const isClaudeResetCreditError = Schema.is(ClaudeResetCreditError); -/** - * An unanswered or unconfirmed claim retries with the same request id. - */ +/** Retry unanswered or unconfirmed claims with the same request ID. */ export const isSettledClaudeResetCreditFailure = (error: unknown) => isClaudeResetCreditError(error) && error.reason !== "requestFailed" && @@ -122,25 +120,28 @@ export function claudeResetCreditsToContract( }; } -const readJson = (schema: S, file: string) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - return yield* fs.readFileString(file).pipe( - Effect.catchTags({ - PlatformError: (error) => - error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error), - }), - Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))), - ); - }); +const readJson = Effect.fn("claudeResetCredits.readJson")(function* ( + schema: S, + file: string, +) { + const fs = yield* FileSystem.FileSystem; + return yield* fs.readFileString(file).pipe( + Effect.catchTags({ + PlatformError: (error) => + error.reason._tag === "NotFound" ? Effect.succeed("{}") : Effect.fail(error), + }), + Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(schema))), + ); +}); -const readAccessToken = (configDir: string) => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) === "darwin") return undefined; - const path = yield* Path.Path; - const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json")); - return credentials.claudeAiOauth?.accessToken?.trim() || undefined; - }); +const readAccessToken = Effect.fn("claudeResetCredits.readAccessToken")(function* ( + configDir: string, +) { + if ((yield* HostProcess.Platform) === "darwin") return undefined; + const path = yield* Path.Path; + const credentials = yield* readJson(Credentials, path.join(configDir, ".credentials.json")); + return credentials.claudeAiOauth?.accessToken?.trim() || undefined; +}); const withClaudeHeaders = (token: string, version: string) => HttpClientRequest.setHeaders({ @@ -193,10 +194,7 @@ const CLAIM_OUTCOMES = { ineligible: "noCredit", } as const satisfies Record; -/** - * `requestId` is the idempotency key: a retry with the same id is the same - * claim. - */ +/** requestId is the claim's idempotency key. */ export const consumeClaudeResetCredit = Effect.fn("consumeClaudeResetCredit")(function* (input: { readonly configDir: string; readonly accountConfigPath: string; @@ -252,8 +250,7 @@ export const consumeClaudeResetCredit = Effect.fn("consumeClaudeResetCredit")(fu if (body.result === "cooldown") { return yield* new ClaudeResetCreditError({ reason: "coolingDown" }); } - // Claude could not say whether the claim landed, so, like the CLI, keep the - // request id and let the retry ask about the same claim. + // Unknown outcomes retain the request ID so retries address the same claim. if (body.result === "unavailable") { return yield* new ClaudeResetCreditError({ reason: "unconfirmed" }); } diff --git a/apps/server/src/provider/claudeUsageLimits.test.ts b/apps/server/src/provider/claudeUsageLimits.test.ts index a2da39b00d726..f20d8b0543636 100644 --- a/apps/server/src/provider/claudeUsageLimits.test.ts +++ b/apps/server/src/provider/claudeUsageLimits.test.ts @@ -16,8 +16,6 @@ describe("claudeUsageResponseToLimits", () => { five_hour: { utilization: 54, resets_at: "2026-07-18T14:39:00Z" }, seven_day: { utilization: 18.4, resets_at: "2026-07-24T08:59:00+00:00" }, seven_day_opus: { utilization: 3, resets_at: null }, - // Newer CLIs add this on top of the typed keys; the pinned SDK - // typings do not know it yet. ...({ model_scoped: [ { display_name: "Fable", utilization: 73, resets_at: "2026-07-24T08:59:00Z" }, @@ -86,15 +84,6 @@ describe("claudeUsageResponseToLimits", () => { ).toEqual({ overageIncluded: "Fable" }); }); - it("reports API key and Bedrock accounts as unsupported", () => { - expect( - claudeUsageResponseToLimits({ - checkedAt, - response: { rate_limits_available: false, rate_limits: null }, - }).limits, - ).toEqual({ checkedAt, windows: [], unavailable: { reason: "unsupported" } }); - }); - it("skips a window the endpoint reports without a utilization", () => { expect( claudeUsageResponseToLimits({ @@ -117,6 +106,121 @@ describe("claudeUsageResponseToLimits", () => { }, ]); }); + + const enterpriseResponse = { + rate_limits_available: true, + rate_limits: { + five_hour: null, + seven_day: null, + spend: { + enabled: true, + used: { amount_minor: 4_631, currency: "USD", exponent: 2 }, + limit: { amount_minor: 50_000, currency: "USD", exponent: 2 }, + percent: 9, + }, + extra_usage: { + is_enabled: true, + used_credits: 4_631, + monthly_limit: 50_000, + utilization: 9.261999999999999, + currency: "USD", + decimal_places: 2, + }, + }, + }; + const monthlyWindow = { + id: "monthly_spend", + kind: "monthly", + label: "Monthly spend", + usedPercent: expect.closeTo(9.262, 10), + }; + + it("maps the captured Enterprise budget precisely, preferring spend beside rolling windows", () => { + expect(claudeUsageResponseToLimits({ checkedAt, response: enterpriseResponse }).limits).toEqual( + { + checkedAt, + windows: [monthlyWindow], + }, + ); + const response = { + ...enterpriseResponse, + rate_limits: { + ...enterpriseResponse.rate_limits, + five_hour: { utilization: 12, resets_at: null }, + extra_usage: { + ...enterpriseResponse.rate_limits.extra_usage, + used_credits: 30_000, + utilization: 60, + }, + }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent: 12, + windowDurationMins: 300, + }, + monthlyWindow, + ]); + }); + + it("falls back to enabled extra usage amounts or utilization when spend is unusable", () => { + const response = { + ...enterpriseResponse, + rate_limits: { + ...enterpriseResponse.rate_limits, + spend: { + ...enterpriseResponse.rate_limits.spend, + enabled: false, + used: { amount_minor: 30_000, currency: "USD", exponent: 2 }, + }, + extra_usage: { ...enterpriseResponse.rate_limits.extra_usage, utilization: 9 }, + }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([ + monthlyWindow, + ]); + const utilizationOnly = { + ...response, + rate_limits: { + ...response.rate_limits, + spend: { enabled: true, used: null, limit: null, percent: 9 }, + extra_usage: { + ...enterpriseResponse.rate_limits.extra_usage, + used_credits: null, + monthly_limit: null, + }, + }, + }; + expect( + claudeUsageResponseToLimits({ checkedAt, response: utilizationOnly }).limits.windows, + ).toEqual([monthlyWindow]); + }); + + it("omits disabled budgets and refuses invalid money without an enabled fallback", () => { + const rateLimits = enterpriseResponse.rate_limits; + const response = { + ...enterpriseResponse, + rate_limits: { + ...rateLimits, + spend: { ...rateLimits.spend, enabled: false }, + extra_usage: { ...rateLimits.extra_usage, is_enabled: false }, + }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([]); + response.rate_limits.spend = { + ...rateLimits.spend, + limit: { ...rateLimits.spend.limit, currency: "EUR" }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([]); + response.rate_limits.spend = { + ...rateLimits.spend, + limit: { ...rateLimits.spend.limit, amount_minor: 0 }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits.windows).toEqual([]); + }); }); describe("claudeRateLimitEventToUpdate", () => { @@ -164,16 +268,4 @@ describe("claudeRateLimitEventToUpdate", () => { ], }); }); - - it("ignores windows the page does not render and events without a utilization", () => { - expect( - claudeRateLimitEventToUpdate( - { status: "allowed", rateLimitType: "seven_day_opus", utilization: 0.1 }, - noNames, - ), - ).toBeUndefined(); - expect( - claudeRateLimitEventToUpdate({ status: "rejected", rateLimitType: "five_hour" }, noNames), - ).toBeUndefined(); - }); }); diff --git a/apps/server/src/provider/claudeUsageLimits.ts b/apps/server/src/provider/claudeUsageLimits.ts index a4dd6d0152be8..d0acf43bb4968 100644 --- a/apps/server/src/provider/claudeUsageLimits.ts +++ b/apps/server/src/provider/claudeUsageLimits.ts @@ -8,6 +8,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import { clampPercent, @@ -25,15 +26,19 @@ const WINDOWS: Readonly< seven_day: { kind: "weekly", label: "Weekly", windowDurationMins: WEEK_MINS }, }; -/** - * The streamed event names the overage-included bucket by type - * (`seven_day_overage_included`), while `get_usage` names it by the model's - * `display_name`. Which model that is changes over time, so the probe records - * the name it saw and the event mapper reuses it; the mid-turn update then - * lands on the row the probe drew instead of opening a second one. - */ +/** Reuse probed display names for streamed bucket types so mid-turn updates target the same row. */ const OVERAGE_INCLUDED_EVENT_TYPE = "seven_day_overage_included"; +// The SDK does not yet type the spend budget returned by `get_usage`. +const SpendMoney = Schema.Struct({ + amount_minor: Schema.Natural, + currency: Schema.NonEmptyString, + exponent: Schema.Natural, +}); +const decodeSpendBudget = Schema.decodeUnknownOption( + Schema.Struct({ enabled: Schema.Boolean, used: SpendMoney, limit: SpendMoney }), +); + export interface ClaudeScopedLimitNames { readonly overageIncluded: string | undefined; } @@ -61,6 +66,44 @@ function scopedWindow( }; } +function percentFromAmounts(used: number | null | undefined, limit: number | null | undefined) { + if ( + typeof used !== "number" || + typeof limit !== "number" || + !Number.isFinite(used) || + !Number.isFinite(limit) || + used < 0 || + limit <= 0 + ) { + return undefined; + } + const percent = (used / limit) * 100; + return Number.isFinite(percent) ? clampPercent(percent) : undefined; +} + +function readSpendPercent(rateLimits: NonNullable) { + const spend = Option.getOrUndefined( + decodeSpendBudget((rateLimits as { readonly spend?: unknown }).spend), + ); + // Minor-unit ratios require matching currency and scale; spend.percent is rounded. + if ( + spend?.enabled && + spend.used.currency.trim().length > 0 && + spend.used.currency.trim() === spend.limit.currency.trim() && + spend.used.exponent === spend.limit.exponent + ) { + const percent = percentFromAmounts(spend.used.amount_minor, spend.limit.amount_minor); + if (percent !== undefined) return percent; + } + + const extra = rateLimits.extra_usage; + if (extra?.is_enabled !== true) return undefined; + const percent = percentFromAmounts(extra.used_credits, extra.monthly_limit) ?? extra.utilization; + return typeof percent === "number" && Number.isFinite(percent) && percent >= 0 + ? clampPercent(percent) + : undefined; +} + /** * `model_scoped` shipped in the CLI after the SDK typings we pin, so it is * read structurally until the `.d.ts` catches up. @@ -108,11 +151,7 @@ function makeWindow( }; } -/** - * Utilization is a 0–1 fraction on the streamed event. An overage-included - * event before any probe has named the bucket is dropped: guessing a name - * would draw a row the next probe cannot reconcile. - */ +/** Stream utilization is 0-1. Drop unnamed overage buckets until probed to avoid unreconcilable rows. */ export function claudeRateLimitEventToUpdate( info: SDKRateLimitInfo, names: ClaudeScopedLimitNames, @@ -132,9 +171,7 @@ export function claudeRateLimitEventToUpdate( return undefined; } -/** - * Percentages on the `get_usage` response are already 0–100. - */ +/** get_usage percentages are already 0-100. */ export function claudeUsageResponseToLimits(input: { readonly response: Pick; readonly checkedAt: string; @@ -142,7 +179,10 @@ export function claudeUsageResponseToLimits(input: { const { response, checkedAt } = input; if (!response.rate_limits_available || !response.rate_limits) { return { - limits: makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }), + limits: makeUnavailableUsageLimits({ + checkedAt, + reason: response.rate_limits_available ? "probeFailed" : "unsupported", + }), names: { overageIncluded: undefined }, }; } @@ -152,8 +192,7 @@ export function claudeUsageResponseToLimits(input: { if (!window || typeof window.utilization !== "number") continue; windows.push(makeWindow(id, window.utilization, isoFromString(window.resets_at))); } - // The CLI filters `model_scoped` to the overage-included allowlist, which - // today holds one model; the first entry is the one the event refers to. + // The CLI's overage allowlist currently has one model; events refer to its first entry. let overageIncluded: string | undefined; for (const entry of readModelScoped(response.rate_limits)) { if (typeof entry.utilization !== "number") continue; @@ -162,6 +201,15 @@ export function claudeUsageResponseToLimits(input: { ); overageIncluded ??= entry.display_name; } + const spendPercent = readSpendPercent(response.rate_limits); + if (spendPercent !== undefined) { + windows.push({ + id: "monthly_spend", + kind: "monthly", + label: "Monthly spend", + usedPercent: spendPercent, + }); + } return { limits: makeUsageLimits({ checkedAt, windows }), names: { overageIncluded }, diff --git a/apps/server/src/provider/codexLaunchArgs.test.ts b/apps/server/src/provider/codexLaunchArgs.test.ts index a7dfc81fae86b..ce18c8f3f1bd5 100644 --- a/apps/server/src/provider/codexLaunchArgs.test.ts +++ b/apps/server/src/provider/codexLaunchArgs.test.ts @@ -2,31 +2,7 @@ import * as NodeAssert from "node:assert/strict"; import { describe, it } from "vite-plus/test"; -import { - codexAppServerArgs, - codexExecLaunchArgs, - resolveCodexLaunchArgs, -} from "./codexLaunchArgs.ts"; - -describe("resolveCodexLaunchArgs", () => { - it("uses T3CODE_CODEX_LAUNCH_ARGS before configured settings", () => { - NodeAssert.equal( - resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: "--enable foo" }), - "--enable foo", - ); - }); - - it("uses configured settings when T3CODE_CODEX_LAUNCH_ARGS is empty", () => { - NodeAssert.equal( - resolveCodexLaunchArgs(" --strict-config ", { T3CODE_CODEX_LAUNCH_ARGS: " " }), - "--strict-config", - ); - }); - - it("ignores whitespace-only environment values", () => { - NodeAssert.equal(resolveCodexLaunchArgs("", { T3CODE_CODEX_LAUNCH_ARGS: " " }), ""); - }); -}); +import { codexAppServerArgs, codexExecLaunchArgs } from "./codexLaunchArgs.ts"; describe("codexAppServerArgs", () => { it("preserves escaped TOML quotes in config values", () => { @@ -35,29 +11,9 @@ describe("codexAppServerArgs", () => { ["app-server", "--config", 'model="gpt-6.1-sol"', "--strict-config"], ); }); - - it("returns the app-server command for empty launch args", () => { - NodeAssert.deepStrictEqual(codexAppServerArgs(""), ["app-server"]); - }); - - it("appends parsed launch args after app-server", () => { - NodeAssert.deepStrictEqual(codexAppServerArgs("--strict-config --enable foo"), [ - "app-server", - "--strict-config", - "--enable", - "foo", - ]); - }); }); describe("codexExecLaunchArgs", () => { - it("preserves escaped TOML quotes in config values", () => { - NodeAssert.deepStrictEqual( - codexExecLaunchArgs(String.raw`--config model=\"gpt-6.1-sol\" --strict-config`), - ["--config", 'model="gpt-6.1-sol"', "--strict-config"], - ); - }); - it("keeps shared codex flags and omits app-server-only flags", () => { NodeAssert.deepStrictEqual( codexExecLaunchArgs('--strict-config --enable foo --listen off --config model="gpt 5"'), diff --git a/apps/server/src/provider/codexModelCatalog.ts b/apps/server/src/provider/codexModelCatalog.ts index 037dad8b0d9bc..a459b1af81de0 100644 --- a/apps/server/src/provider/codexModelCatalog.ts +++ b/apps/server/src/provider/codexModelCatalog.ts @@ -14,10 +14,7 @@ const CodexModelAdapter = Schema.Struct({ }); const decodeCodexModelAdapter = Schema.decodeUnknownOption(CodexModelAdapter); -/** - * Codex lists only the models its own build knows, so a model released after - * the installed CLI never shows up. - */ +/** Codex catalogs omit models released after the installed CLI. */ function codexUpdateRequiredModels( catalog: ModelCatalog.ProviderCatalog | undefined, draft: ServerProviderDraft, diff --git a/apps/server/src/provider/codexUsageLimits.test.ts b/apps/server/src/provider/codexUsageLimits.test.ts index 8d310a9fff730..51970a3a54726 100644 --- a/apps/server/src/provider/codexUsageLimits.test.ts +++ b/apps/server/src/provider/codexUsageLimits.test.ts @@ -5,7 +5,6 @@ import { codexRateLimitsFailureMessage, codexRateLimitsToLimits, codexRateLimitsToUpdate, - codexResetCreditsToContract, codexUsageLimitMessage, mergeCodexRateLimits, } from "./codexUsageLimits.ts"; @@ -13,6 +12,34 @@ import { const checkedAt = "2026-07-18T10:00:00.000Z"; describe("codexRateLimitsToLimits", () => { + it("shows an Enterprise monthly credit allowance in reads and notifications without a duration", () => { + const snapshot = { + limitId: "codex", + planType: "enterprise_cbp_usage_based", + primary: null, + secondary: null, + individualLimit: { remainingPercent: 99, resetsAt: 1_784_500_000 }, + }; + const windows = [ + { + id: "individual", + kind: "monthly", + label: "Monthly credit limit", + usedPercent: 1, + resetsAt: "2026-07-19T22:26:40.000Z", + }, + ]; + + expect( + codexRateLimitsToLimits({ + checkedAt, + snapshot: { limitId: "spark" }, + rateLimitsByLimitId: { codex: snapshot }, + }), + ).toEqual({ checkedAt, windows }); + expect(codexRateLimitsToUpdate(snapshot)).toEqual({ windows }); + }); + it("maps primary and secondary onto the session and weekly windows", () => { expect( codexRateLimitsToLimits({ @@ -66,6 +93,7 @@ describe("codexRateLimitsToLimits", () => { it("selects the main Codex allowance and leaves Spark out", () => { const spark = { limitId: "codex_bengalfox", + individualLimit: { remainingPercent: 99, resetsAt: 1_784_500_000 }, primary: { usedPercent: 0, windowDurationMins: 300 }, secondary: { usedPercent: 90, windowDurationMins: 10080 }, }; @@ -98,18 +126,6 @@ describe("codexRateLimitsToLimits", () => { ); }, ); - - it("does not show a model-specific legacy snapshot as the main allowance", () => { - expect( - codexRateLimitsToLimits({ - checkedAt, - snapshot: { - limitId: "codex_bengalfox", - secondary: { usedPercent: 90 }, - }, - }).windows, - ).toEqual([]); - }); }); describe("codexRateLimitsToUpdate", () => { @@ -136,6 +152,7 @@ describe("codexRateLimitsToUpdate", () => { expect( codexRateLimitsToUpdate({ limitId: "codex_bengalfox", + individualLimit: { remainingPercent: 99, resetsAt: 1_784_500_000 }, primary: { usedPercent: 0, windowDurationMins: 300 }, secondary: { usedPercent: 90, windowDurationMins: 10080 }, }), @@ -169,39 +186,6 @@ describe("codexRateLimitsFailureMessage", () => { ), ).toBe("Codex could not read usage (JSON-RPC -32603)."); }); - - it("phrases a dead process differently from a bad answer", () => { - expect( - codexRateLimitsFailureMessage(new CodexErrors.CodexAppServerProcessExitedError({ code: 1 })), - ).toBe("Codex exited before it could report usage."); - }); -}); - -describe("codexResetCreditsToContract", () => { - it("counts available credits and reports the soonest expiry", () => { - expect( - codexResetCreditsToContract({ - availableCount: 2, - credits: [ - { status: "available", expiresAt: 1_784_500_000 }, - { status: "redeemed", expiresAt: 1_700_000_000 }, - { status: "available", expiresAt: 1_784_000_000 }, - ], - }), - ).toEqual({ availableCount: 2, nextExpiresAt: "2026-07-14T03:33:20.000Z" }); - expect(codexResetCreditsToContract({ availableCount: 0 })).toEqual({ availableCount: 0 }); - expect(codexResetCreditsToContract(null)).toBeUndefined(); - }); - - it("rides along on the probe's limits", () => { - expect( - codexRateLimitsToLimits({ - checkedAt, - snapshot: { primary: { usedPercent: 5, windowDurationMins: 300 } }, - resetCredits: { availableCount: 1 }, - }).resetCredits, - ).toEqual({ availableCount: 1 }); - }); }); describe("codexUsageLimitMessage", () => { @@ -246,42 +230,42 @@ describe("codexUsageLimitMessage", () => { "Codex usage limit reached. The session limit resets in 3h 20m. The workspace spend limit is reached: ask your workspace owner to raise it, or send the message again once the limit resets.", ); }); - - it("names no window when credits run out without one", () => { - expect( - codexUsageLimitMessage( - { limitId: "codex", rateLimitReachedType: "workspace_member_credits_depleted" }, - at, - ), - ).toBe( - "Codex usage limit reached. The workspace has no credits to continue sooner: ask your workspace owner to add credits, or send the message again once the limit resets.", - ); - }); - - it("says only what it knows without a snapshot", () => { - expect(codexUsageLimitMessage(undefined, at)).toBe( - "Codex usage limit reached. Send the message again once the limit resets.", - ); - }); }); describe("mergeCodexRateLimits", () => { - it("keeps windows an update does not carry", () => { - const merged = mergeCodexRateLimits( - { - limitId: "codex", - planType: "business", - primary: { usedPercent: 100, resetsAt: 1_800_000_000, windowDurationMins: 300 }, - }, - { rateLimitReachedType: "rate_limit_reached" }, - ); - - expect(merged).toEqual({ + it("updates monthly credit usage, retains it when omitted, and clears an explicit null", () => { + const snapshot = { limitId: "codex", - planType: "business", - rateLimitReachedType: "rate_limit_reached", - primary: { usedPercent: 100, resetsAt: 1_800_000_000, windowDurationMins: 300 }, + primary: { usedPercent: 12 }, + individualLimit: { remainingPercent: 99, resetsAt: 1_784_500_000 }, + }; + const individualLimit = { remainingPercent: 75, resetsAt: 1_787_000_000 }; + const changed = mergeCodexRateLimits(snapshot, { individualLimit }); + expect(changed).toEqual({ ...snapshot, individualLimit }); + expect(codexRateLimitsToUpdate(changed!)).toEqual({ + windows: [ + { + id: "primary", + kind: "session", + label: "Session", + usedPercent: 12, + windowDurationMins: 300, + }, + { + id: "individual", + kind: "monthly", + label: "Monthly credit limit", + usedPercent: 25, + resetsAt: "2026-08-17T20:53:20.000Z", + }, + ], }); + + const retained = mergeCodexRateLimits(changed, { primary: null }); + expect(retained).toEqual({ ...snapshot, primary: null, individualLimit }); + const cleared = mergeCodexRateLimits(retained, { individualLimit: null }); + expect(cleared).toEqual({ ...snapshot, primary: null, individualLimit: null }); + expect(codexRateLimitsToLimits({ checkedAt, snapshot: cleared! }).windows).toEqual([]); }); it("ignores a model-specific snapshot so it cannot replace the main allowance", () => { @@ -292,6 +276,7 @@ describe("mergeCodexRateLimits", () => { expect( mergeCodexRateLimits(main, { limitId: "spark", + individualLimit: { remainingPercent: 99, resetsAt: 1_784_500_000 }, primary: { usedPercent: 3, resetsAt: 1_800_000_000, windowDurationMins: 300 }, }), ).toBe(main); diff --git a/apps/server/src/provider/codexUsageLimits.ts b/apps/server/src/provider/codexUsageLimits.ts index 31d48535cf948..053700026b520 100644 --- a/apps/server/src/provider/codexUsageLimits.ts +++ b/apps/server/src/provider/codexUsageLimits.ts @@ -22,6 +22,10 @@ export interface CodexRateLimitSnapshot { readonly rateLimitReachedType?: string | null; readonly primary?: CodexRateLimitWindow | null; readonly secondary?: CodexRateLimitWindow | null; + readonly individualLimit?: { + readonly remainingPercent: number; + readonly resetsAt: number; + } | null; } export interface CodexResetCreditsSummary { @@ -52,16 +56,11 @@ function labelForKind(kind: ServerProviderUsageWindow["kind"]): string { return kind === "session" ? "Session" : kind === "weekly" ? "Weekly" : "Monthly"; } -/** - * `primary` / `secondary` are positions, not durations. Codex usually sends - * `windowDurationMins`; when it does not, paid plans expose the 5-hour and - * weekly pair and Free/Go expose one monthly allowance. - */ +/** primary/secondary are positions; without windowDurationMins, paid plans use 5-hour/weekly windows and Free/Go use monthly. */ function codexRateLimitsToWindows( snapshot: CodexRateLimitSnapshot, ): ReadonlyArray { - // Show the main allowance only. Model-specific notifications (such as Spark) - // must not replace its primary/secondary rows. Older CLIs omit the limit id. + // Keep model-specific limits out of main allowance rows; older CLIs omit limit IDs. if (snapshot.limitId && snapshot.limitId !== "codex") return []; const isMonthlyPlan = snapshot.planType === "free" || snapshot.planType === "go"; const positions = [ @@ -84,10 +83,21 @@ function codexRateLimitsToWindows( ...(resetsAt ? { resetsAt } : {}), }); } + const individualLimit = snapshot.individualLimit; + if (individualLimit && Number.isFinite(individualLimit.remainingPercent)) { + const resetsAt = isoFromEpochSeconds(individualLimit.resetsAt); + windows.push({ + id: "individual", + kind: "monthly", + label: "Monthly credit limit", + usedPercent: clampPercent(100 - individualLimit.remainingPercent), + ...(resetsAt ? { resetsAt } : {}), + }); + } return windows; } -export function codexResetCreditsToContract( +function codexResetCreditsToContract( summary: CodexResetCreditsSummary | null | undefined, ): ServerProviderResetCredits | undefined { if (!summary) return undefined; @@ -143,18 +153,12 @@ export function codexRateLimitsFailureMessage(error: CodexErrors.CodexAppServerE } } -/** - * Codex sends `account/rateLimits/updated` as a partial view of the snapshot: a - * field the update omits keeps the value observed earlier in the session, so a - * later notification that only names the limit it reached must not drop the - * windows an earlier one carried. - */ +/** Rate-limit notifications are partial: omitted fields preserve earlier session values. */ export function mergeCodexRateLimits( previous: CodexRateLimitSnapshot | undefined, update: CodexRateLimitSnapshot, ): CodexRateLimitSnapshot | undefined { - // Model-specific snapshots (such as Spark) describe a different allowance - // and must not overwrite the main one, the same rule the usage rows apply. + // Model-specific snapshots must not overwrite the main allowance. if (update.limitId && update.limitId !== "codex") return previous; if (!previous) return update; return { @@ -166,6 +170,7 @@ export function mergeCodexRateLimits( : {}), ...(update.primary !== undefined ? { primary: update.primary } : {}), ...(update.secondary !== undefined ? { secondary: update.secondary } : {}), + ...(update.individualLimit !== undefined ? { individualLimit: update.individualLimit } : {}), }; } diff --git a/apps/server/src/provider/model-manifest.json b/apps/server/src/provider/model-manifest.json index 6b950ed2d060e..e62f661fcfc2c 100644 --- a/apps/server/src/provider/model-manifest.json +++ b/apps/server/src/provider/model-manifest.json @@ -1,6 +1,6 @@ { "version": 1, - "updatedAt": "2026-10-09T23:31:10Z", + "updatedAt": "2026-10-21T06:20:00Z", "compatibility": [ { "driver": "codex", @@ -134,7 +134,9 @@ { "slug": "gpt-5.6-sol", "name": "GPT-5.6 Sol", "status": "legacy" }, { "slug": "gpt-5.6-terra", "name": "GPT-5.6 Terra", "status": "legacy" }, { "slug": "gpt-5.6-luna", "name": "GPT-5.6 Luna", "status": "legacy" }, - { "slug": "gpt-5.5", "name": "GPT-5.5", "status": "legacy" } + { "slug": "gpt-5.5", "name": "GPT-5.5", "status": "legacy" }, + { "slug": "gpt-5.4-mini", "name": "GPT-5.4 Mini", "status": "legacy" }, + { "slug": "gpt-5.3-codex-spark", "name": "GPT-5.3 Codex Spark", "status": "legacy" } ] }, "claudeAgent": { @@ -653,7 +655,8 @@ { "id": "thinking", "label": "Thinking", - "type": "boolean" + "type": "boolean", + "currentValue": true } ] }, diff --git a/apps/server/src/provider/providerCompatibility.test.ts b/apps/server/src/provider/providerCompatibility.test.ts index 0310c7998d907..e3d4f672016c0 100644 --- a/apps/server/src/provider/providerCompatibility.test.ts +++ b/apps/server/src/provider/providerCompatibility.test.ts @@ -11,10 +11,10 @@ import * as Stream from "effect/Stream"; import * as ServerConfig from "../config.ts"; import * as ModelManifest from "./ModelManifest.ts"; import * as ProviderRegistry from "./ProviderRegistry.ts"; +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import { makeManualOnlyProviderMaintenanceCapabilities } from "@t3tools/provider-core/server/maintenanceResolver"; -import { BUILT_IN_DRIVERS } from "./builtInDrivers.ts"; import * as Schema from "effect/Schema"; import { applyProviderCompatibility, @@ -50,27 +50,9 @@ const provider: ServerProvider = { slashCommands: [], }; -const V2_RELEASE = "0.0.46"; - describe("provider compatibility", () => { - it("bundles a compatibility policy for every built-in harness", () => { - for (const builtIn of BUILT_IN_DRIVERS) { - if (builtIn.driverKind === "acpRegistry") continue; - assert.isDefined( - resolveProviderCompatibility( - ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, - builtIn.driverKind, - null, - V2_RELEASE, - ), - `Missing bundled compatibility policy for ${builtIn.driverKind}`, - ); - } - }); - it("keeps releases before V2 on the OpenCode 1 policy they shipped with", () => { - // Every installed build fetches main's manifest, and 0.0.45 and older run the - // V1 orchestrator, which cannot drive OpenCode 2. + // Older builds fetch main's manifest; their V1 orchestrator cannot drive OpenCode 2. const opencode = ProviderDriverKind.make("opencode"); for (const [version, expected] of [ ["1.14.19", "supported"], @@ -96,44 +78,6 @@ describe("provider compatibility", () => { ); }); - it("supports OpenCode 2 and gives OpenCode 1.x limited support", () => { - const opencode = ProviderDriverKind.make("opencode"); - for (const [version, expected] of [ - ["2.0.18", "supported"], - ["2.1.0", "supported"], - ["2.0.17", "unsupported"], - ["2.0.0", "unsupported"], - ["1.99.0", "graceful"], - ["1.14.19", "graceful"], - ["1.14.18", "broken"], - ] as const) { - for (const t3CodeVersion of [V2_RELEASE, "0.0.46-preview.20261002.2598"]) { - const advisory = resolveProviderCompatibility( - ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, - opencode, - version, - t3CodeVersion, - ); - assert.strictEqual(advisory?.status, expected, `OpenCode ${version} on ${t3CodeVersion}`); - assert.strictEqual(advisory?.recommendedRange, ">=2.0.18"); - } - } - const ready = applyProviderCompatibility( - { ...provider, driver: opencode, version: "1.18.33", status: "ready", message: undefined }, - undefined, - ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, - ); - assert.strictEqual(ready.status, "ready"); - assert.strictEqual( - ready.compatibilityAdvisory?.status, - resolveProviderCompatibility( - ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, - opencode, - "1.18.33", - )?.status, - ); - }); - it("compares Cursor build dates without treating semver prereleases as stable", () => { const cursor = ProviderDriverKind.make("cursor"); const cursorPolicy: ProviderCompatibilityPolicy = { @@ -162,26 +106,6 @@ describe("provider compatibility", () => { ); }); - it("compares Muse versions by their release, ignoring the revision suffix", () => { - const muse = ProviderDriverKind.make("muse"); - for (const [version, expected] of [ - ["1.4.3-R5018.1", "supported"], - ["1.4.2-R4684", "supported"], - ["1.4.1-R4100.2", "unknown"], - ["1.4.3-beta.1", "unknown"], - ] as const) { - assert.strictEqual( - resolveProviderCompatibility( - ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, - muse, - version, - V2_RELEASE, - )?.status, - expected, - ); - } - }); - it("recognizes Antigravity semver release tags while keeping dated candidates unknown", () => { const antigravity = ProviderDriverKind.make("antigravity"); const taggedPolicy = { @@ -232,25 +156,6 @@ describe("provider compatibility", () => { } }); - it("supports every driver without inventing policies for uncovered adapters", () => { - for (const kind of [ - "codex", - "claudeAgent", - "cursor", - "grok", - "opencode", - "antigravity", - "customDriver", - ]) { - const adapter = ProviderDriverKind.make(kind); - assert.strictEqual( - resolveProviderCompatibility([{ ...policy, driver: adapter }], adapter, "2.0.0")?.status, - "supported", - ); - assert.isUndefined(resolveProviderCompatibility([], adapter, "2.0.0")); - } - }); - it("relaxes remote policy without losing probe errors, and falls back when a policy is omitted", () => { const broken = applyProviderCompatibility(provider, [], [policy]); assert.strictEqual(broken.compatibilityAdvisory?.status, "broken"); @@ -350,6 +255,7 @@ it.effect("a remote policy refresh preserves a newer health result on the regist ), ); const layerDependencies = Layer.mergeAll( + ProviderLatestVersions.layer, Layer.succeed(ModelManifest.ModelManifest, { current: Ref.get(manifest), refresh, @@ -391,32 +297,3 @@ it.effect("a remote policy refresh preserves a newer health result on the regist }).pipe(Effect.provide(ProviderRegistry.layer.pipe(Layer.provide(layerDependencies)))); }).pipe(Effect.scoped), ); - -it("recomputes latest-version compatibility without losing the underlying update advisory", () => { - const snapshot: ServerProvider = { - ...provider, - version: "2.0.0", - versionAdvisory: { - status: "behind_latest", - currentVersion: "2.0.0", - latestVersion: "4.0.0", - canUpdate: true, - updateCommand: "npm install -g fixture@latest", - checkedAt: provider.checkedAt, - message: null, - }, - }; - const blockedPolicy: ProviderCompatibilityPolicy = { - ...policy, - ranges: [...policy.ranges, { range: ">=3.0.0", status: "broken" }], - }; - const blocked = applyProviderCompatibility(snapshot, [blockedPolicy], []); - assert.strictEqual(blocked.compatibilityAdvisory?.latestVersionStatus, "broken"); - const relaxed = applyProviderCompatibility( - blocked, - [{ ...policy, ranges: [{ range: ">=2.0.0", status: "supported" }] }], - [], - ); - assert.strictEqual(relaxed.compatibilityAdvisory?.latestVersionStatus, "supported"); - assert.deepStrictEqual(relaxed.versionAdvisory, snapshot.versionAdvisory); -}); diff --git a/apps/server/src/provider/providerCompatibility.ts b/apps/server/src/provider/providerCompatibility.ts index a7a63324e7518..69322915f458a 100644 --- a/apps/server/src/provider/providerCompatibility.ts +++ b/apps/server/src/provider/providerCompatibility.ts @@ -65,9 +65,7 @@ export function resolveProviderCompatibility( ); if (!policy) return undefined; const unprefixed = version?.replace(/^v/, ""); - // Cursor appends a build hash to its date; Google's ACP runtime uses a release prefix; - // Muse appends a release revision. Strip only these driver-specific forms, keeping - // semver prereleases unknown. + // Strip Cursor build hashes, Google ACP release prefixes and Muse revisions; leave semver prereleases unknown. const stable = driver === "cursor" ? unprefixed?.replace(/^(\d{4}\.\d{2}\.\d{2})-[a-f0-9]+$/, "$1") @@ -115,11 +113,20 @@ export function applyProviderCompatibility( ? (resolveProviderCompatibility(policies, snapshot.driver, latestVersion) ?? resolveProviderCompatibility(fallback, snapshot.driver, latestVersion)) : undefined; + const updateCommand = snapshot.versionAdvisory?.updateCommand; + // The maintenance resolver emits this command only for confirmed Homebrew installs. + const needsHomebrewRefresh = + updateCommand?.startsWith("brew upgrade ") && + (advisory?.status === "unsupported" || advisory?.status === "broken") && + (latestAdvisory?.status === "unsupported" || latestAdvisory?.status === "broken"); return advisory ? { ...base, compatibilityAdvisory: { ...advisory, + message: needsHomebrewRefresh + ? `${advisory.message} Homebrew's local package metadata may be stale. Run brew update && ${updateCommand} on this environment's host, then refresh provider status.` + : advisory.message, ...(latestAdvisory ? { latestVersionStatus: latestAdvisory.status } : {}), }, } diff --git a/apps/server/src/provider/providerInstallation.test.ts b/apps/server/src/provider/providerInstallation.test.ts index af72c11a19f00..32d417a1d43d1 100644 --- a/apps/server/src/provider/providerInstallation.test.ts +++ b/apps/server/src/provider/providerInstallation.test.ts @@ -123,27 +123,6 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }); describe("provider installation routing", () => { - it.effect("allows explicit installation while the provider is disabled", () => - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* harness.router.start({ instanceId }); - assert.deepEqual(harness.calls, ["start"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("rejects another driver and unknown instances before installation", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ instance: instance(ProviderDriverKind.make("codex")) }); - const wrongDriver = yield* Effect.flip(harness.router.start({ instanceId })); - const missing = yield* Effect.flip( - harness.router.start({ instanceId: ProviderInstanceId.make("missing") }), - ); - assert.equal(wrongDriver._tag, "ProviderSetupError"); - assert.equal(missing._tag, "ProviderSetupError"); - assert.deepEqual(harness.calls, []); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("keeps external installs manual without hiding shared install status", () => Effect.gen(function* () { const harness = yield* makeHarness({ @@ -166,51 +145,6 @@ describe("provider installation routing", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("routes a managed Codex instance through its own installer and refreshes removal", () => - Effect.gen(function* () { - const codexId = ProviderInstanceId.make("codex"); - const harness = yield* makeHarness({ - instance: instance(ProviderDriverKind.make("codex"), codexId), - settings: { - providerInstances: { - [ProviderInstanceId.make("codex")]: { - driver: ProviderDriverKind.make("codex"), - config: { setupMode: "managed" }, - }, - }, - }, - }); - assert.equal((yield* harness.router.start({ instanceId: codexId })).driver, "codex"); - yield* harness.router.cancel({ instanceId: codexId, operationId: "operation" }); - const observed = yield* Stream.runCollect(harness.router.subscribe({ instanceId: codexId })); - assert.equal(Array.from(observed)[0]?.driver, "codex"); - yield* harness.router.remove({ instanceId: codexId }); - assert.deepEqual(harness.calls, ["codex-start", "codex-cancel", "codex-remove", "refresh"]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("keeps native Codex installation outside managed setup", () => - Effect.gen(function* () { - const codexId = ProviderInstanceId.make("codex"); - const harness = yield* makeHarness({ - instance: instance(ProviderDriverKind.make("codex"), codexId), - settings: { - providerInstances: { - [ProviderInstanceId.make("codex")]: { - driver: ProviderDriverKind.make("codex"), - config: { setupMode: "existing" }, - }, - }, - }, - }); - assert.include( - (yield* Effect.flip(harness.router.start({ instanceId: codexId }))).detail, - "Choose managed setup", - ); - assert.deepEqual(harness.calls, []); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect("protects another instance's binary found through its own PATH", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -238,25 +172,4 @@ describe("provider installation routing", () => { assert.deepEqual(harness.calls, ["remove", "refresh"]); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - - it.effect("keeps only the configured path when another instance's binary is missing", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-install-route-" }); - const binaryPath = path.join(directory, "missing"); - const harness = yield* makeHarness({ - settings: { - providerInstances: { - [ProviderInstanceId.make("antigravity-work")]: { - driver, - config: { binaryPath }, - }, - }, - }, - }); - yield* harness.router.remove({ instanceId }); - assert.deepEqual(harness.protectedPaths(), [binaryPath]); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); }); diff --git a/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts b/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts index f2fc03659be0c..c7db6bdf76aaf 100644 --- a/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts +++ b/apps/server/src/provider/providerMaintenanceCommandCoordinator.ts @@ -35,13 +35,13 @@ export const makeProviderMaintenanceCommandCoordinator = Effect.fn( return next; }); - const withCommandLock: ProviderMaintenanceCommandCoordinatorShape["withCommandLock"] = ({ - targetKey, - lockKey, - onQueued, - run, - }) => - Effect.gen(function* () { + const withCommandLock: ProviderMaintenanceCommandCoordinatorShape["withCommandLock"] = + Effect.fn("providerMaintenanceCommandCoordinator.withCommandLock")(function* ({ + targetKey, + lockKey, + onQueued, + run, + }) { const acquired = yield* acquireTarget(targetKey); if (!acquired) { return yield* Effect.fail(input.makeAlreadyRunningError(targetKey)); diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index fe0f6f9b0b31b..75c592b7811a1 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -7,8 +7,6 @@ import { } from "@t3tools/contracts"; import { ServerProviderUpdateError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -17,7 +15,6 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -28,6 +25,7 @@ import * as ModelManifest from "./ModelManifest.ts"; import * as ProviderMaintenanceRunner from "./providerMaintenanceRunner.ts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; import { + enrichProviderSnapshotWithVersionAdvisory, makeProviderMaintenanceCapabilities, type ProviderMaintenanceCapabilities, } from "@t3tools/provider-core/server/maintenanceResolver"; @@ -41,10 +39,7 @@ const NATIVE_CLI_INSTANCE_ID = ProviderInstanceId.make("nativeCli"); const OPENCODE_INSTANCE_ID = ProviderInstanceId.make("opencode"); const encoder = new TextEncoder(); -// Pin a non-win32 platform so `resolveSpawnCommand` is a no-op and the raw -// `{ command, args }` assertions below hold deterministically on any host -// (including Windows). Windows-specific resolution is covered by the dedicated -// win32 case at the end of this suite. +// Pin Linux so raw command/args assertions bypass Windows shim resolution. const layerNonWindowsPlatform = Layer.succeed(HostProcess.Platform, "linux"); function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabilities { @@ -197,6 +192,7 @@ function makeRegistry( getProviders: Ref.get(providersRef), refresh: () => Ref.get(providersRef), refreshInstance: () => Ref.get(providersRef), + refreshAfterUpdate: () => Ref.get(providersRef), refreshWorkspaceSnapshot: () => Ref.get(providersRef), getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => Effect.succeed(lifecycleFor(provider)), @@ -282,31 +278,6 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("reports unchanged when the updater exits 0 but the provider is gone", () => { - return Effect.gen(function* () { - const { registry, providersRef } = yield* makeRegistry(baseProvider); - const updater = yield* makeTestRunner({ - ...registry, - refreshInstance: () => - Ref.updateAndGet(providersRef, (providers) => - providers.map((provider) => ({ ...provider, installed: false, version: null })), - ), - }); - - const result = yield* updater.updateProvider(CODEX_DRIVER); - assert.strictEqual(result.providers[0]?.updateState?.status, "unchanged"); - assert.match(result.providers[0]?.updateState?.message ?? "", /could not verify/); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner(() => ({ stdout: "updated" })), - ), - ), - ); - }); - it.effect( "keeps a successful update when the binary is present but its version is unreadable", () => { @@ -314,7 +285,7 @@ describe("providerMaintenanceRunner", () => { const { registry, providersRef } = yield* makeRegistry(baseNativeCliProvider); const updater = yield* makeTestRunner({ ...registry, - refreshInstance: () => + refreshAfterUpdate: () => Ref.updateAndGet(providersRef, (providers) => providers.map((provider) => ({ ...provider, installed: true, version: null })), ), @@ -409,42 +380,6 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("reports the installer's latest output line while the update runs", () => { - const exited = Deferred.makeUnsafe(); - return Effect.gen(function* () { - const { registry, updateStatesRef } = yield* makeRegistry(baseNativeCliProvider); - const updater = yield* makeTestRunner(registry); - const runningMessages = Ref.get(updateStatesRef).pipe( - Effect.map((states) => - states.filter((state) => state.status === "running").map((state) => state.message), - ), - ); - - const fiber = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkChild); - yield* TestClock.adjust(Duration.seconds(1)); - assert.deepStrictEqual(yield* runningMessages, [ - "Checking for the latest version", - "Running native-agent update", - "80%", - ]); - - yield* Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)); - const result = yield* Fiber.join(fiber); - assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner(() => ({ - stdout: "Checking for updates\nDownloading 2.1.293\n\u001b[32m 40%\u001b[0m\r 80%", - exitCode: Deferred.await(exited), - })), - ), - ), - ); - }); - it("splits installer output into clean status lines", () => { assert.deepStrictEqual(ProviderMaintenanceRunner.splitOutputLines("Down", "loading\r\n 5"), { lines: ["Downloading"], @@ -507,177 +442,52 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("uses the resolved provider capabilities when choosing the update executable", () => { - const calls: Array<{ command: string; args: ReadonlyArray }> = []; - return Effect.gen(function* () { - const { registry } = yield* makeRegistry({ - ...baseProvider, - versionAdvisory: { - status: "behind_latest", - currentVersion: "2.0.14", - latestVersion: "2.1.123", - updateCommand: "bun i -g @anthropic-ai/claude-code@latest", - canUpdate: true, - checkedAt: "2026-04-30T12:00:00.000Z", - message: "Update available.", - }, - }); - const updater = yield* makeTestRunner({ - ...registry, - getProviderMaintenanceCapabilitiesForInstance: () => - Effect.succeed( - makeProviderMaintenanceCapabilities({ - provider: CODEX_DRIVER, - packageName: "@openai/codex", - updateExecutable: "bun", - updateArgs: ["i", "-g", "@openai/codex@latest"], - updateLockKey: "bun-global", - }), - ), - }); - - yield* updater.updateProvider(CODEX_DRIVER); - assert.deepStrictEqual(calls, [ - { - command: "bun", - args: ["i", "-g", "@openai/codex@latest"], - }, - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner((command, args) => { - calls.push({ command, args }); - return { stdout: "updated" }; - }), - ), - ), - ); - }); - - it.effect( - "runs update commands through Effect ChildProcess when no test runner is injected", - () => { - const calls: Array<{ command: string; args: ReadonlyArray }> = []; - return Effect.gen(function* () { - const { registry } = yield* makeRegistry(baseProvider); - const runner = yield* makeTestRunner(registry); + it.effect("records command failure output in provider update state", () => + Effect.gen(function* () { + const { registry } = yield* makeRegistry(); + const updater = yield* makeTestRunner(registry); - const result = yield* runner.updateProvider(CODEX_DRIVER); + const result = yield* updater.updateProvider(CODEX_DRIVER); + const updateState = result.providers[0]?.updateState; - assert.deepStrictEqual(calls, [ - { - command: "npm", - args: ["install", "-g", "@openai/codex@latest"], - }, - ]); - assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner((command, args) => { - calls.push({ command, args }); - return { stdout: "updated" }; - }), - ), - ), + assert.strictEqual(updateState?.status, "failed"); + assert.strictEqual( + updateState?.message, + "Update command exited with code 1: Error: Could not detect the Codex installation method.", ); - }, - ); - - it.effect("updates a single provider instance without touching sibling instances", () => { - const calls: Array<{ command: string; args: ReadonlyArray }> = []; - return Effect.gen(function* () { - const personalInstanceId = ProviderInstanceId.make("codex_personal"); - const workInstanceId = ProviderInstanceId.make("codex_work"); - const refreshedInstanceIds: Array = []; - const { registry } = yield* makeRegistry([ - { - ...baseProvider, - instanceId: personalInstanceId, - version: "0.124.0-alpha.3", - }, - { - ...baseProvider, - instanceId: workInstanceId, - version: "0.124.0-alpha.3", - }, - ]); - const updater = yield* makeTestRunner({ - ...registry, - getProviderMaintenanceCapabilitiesForInstance: (instanceId, provider) => - Effect.succeed( - makeProviderMaintenanceCapabilities({ - provider, - packageName: "@openai/codex-instance-test", - updateExecutable: "vp", - updateArgs: ["i", "-g", "@openai/codex"], - updateLockKey: "vite-plus-global", - }), - ).pipe( - Effect.tap(() => Effect.sync(() => assert.strictEqual(instanceId, personalInstanceId))), - ), - refreshInstance: (instanceId) => - registry.refreshInstance(instanceId).pipe( - Effect.tap(() => - Effect.sync(() => { - refreshedInstanceIds.push(instanceId); - }), - ), - ), - }); - - const result = yield* updater.updateProvider({ - provider: CODEX_DRIVER, - instanceId: personalInstanceId, - }); - - assert.deepStrictEqual(calls, [ - { - command: "vp", - args: ["i", "-g", "@openai/codex"], - }, - ]); - assert.deepStrictEqual(refreshedInstanceIds, [personalInstanceId]); - assert.strictEqual(result.providers[0]?.instanceId, personalInstanceId); - assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); - assert.strictEqual(result.providers[1]?.instanceId, workInstanceId); - assert.strictEqual(result.providers[1]?.updateState, undefined); + assert.include(updateState?.output ?? "", "checking install"); }).pipe( Effect.provide( Layer.mergeAll( layerNonWindowsPlatform, - layerLatestVersionHttpClient("0.124.0-alpha.3"), - layerMockSpawner((command, args) => { - calls.push({ command, args }); - return { stdout: "updated" }; - }), + layerLatestVersionHttpClient("0.0.0"), + layerMockSpawner(() => ({ + stdout: "checking install\n", + stderr: "Error: Could not detect the Codex installation method.\n\n", + code: 1, + })), ), ), - ); - }); + ), + ); - it.effect("records command failure output in provider update state", () => + it.effect("keeps the exit code message when a failed command prints nothing", () => Effect.gen(function* () { const { registry } = yield* makeRegistry(); const updater = yield* makeTestRunner(registry); const result = yield* updater.updateProvider(CODEX_DRIVER); - const updateState = result.providers[0]?.updateState; - assert.strictEqual(updateState?.status, "failed"); - assert.strictEqual(updateState?.message, "Update command exited with code 1."); - assert.include(updateState?.output ?? "", "permission denied"); + assert.strictEqual( + result.providers[0]?.updateState?.message, + "Update command exited with code 1.", + ); }).pipe( Effect.provide( Layer.mergeAll( layerNonWindowsPlatform, layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner(() => ({ stderr: "permission denied", code: 1 })), + layerMockSpawner(() => ({ code: 1 })), ), ), ), @@ -756,122 +566,6 @@ describe("providerMaintenanceRunner", () => { ); }); - it.effect("serializes different providers that share the same update lock key", () => { - const firstStartedLatch: { resolve: () => void } = { resolve: () => {} }; - const releaseFirstLatch: { resolve: () => void } = { resolve: () => {} }; - const firstStarted = new Promise((resolve) => { - firstStartedLatch.resolve = resolve; - }); - const releaseFirst = new Promise((resolve) => { - releaseFirstLatch.resolve = resolve; - }); - const calls: Array = []; - return Effect.gen(function* () { - const { registry } = yield* makeRegistry([baseProvider, baseOpenCodeProvider]); - const updater = yield* makeTestRunner({ - ...registry, - getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => - Effect.succeed( - makeProviderMaintenanceCapabilities({ - provider, - packageName: provider === OPENCODE_DRIVER ? "opencode-ai" : "@openai/codex", - updateExecutable: "npm", - updateArgs: - provider === OPENCODE_DRIVER - ? ["install", "-g", "opencode-ai@latest"] - : ["install", "-g", "@openai/codex@latest"], - updateLockKey: "npm-global", - }), - ), - }); - - const first = yield* updater.updateProvider(CODEX_DRIVER).pipe(Effect.forkScoped); - yield* Effect.promise(() => firstStarted); - - const second = yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped); - let providersWhileQueued: ReadonlyArray = []; - for (let attempt = 0; attempt < 20; attempt += 1) { - providersWhileQueued = yield* registry.getProviders; - const queuedStatus = providersWhileQueued.find( - (provider) => provider.instanceId === OPENCODE_INSTANCE_ID, - )?.updateState?.status; - if (queuedStatus === "queued") { - break; - } - yield* Effect.yieldNow; - } - assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]); - assert.strictEqual( - providersWhileQueued.find((provider) => provider.instanceId === OPENCODE_INSTANCE_ID) - ?.updateState?.status, - "queued", - ); - - releaseFirstLatch.resolve(); - yield* Fiber.join(first); - yield* Fiber.join(second); - assert.deepStrictEqual(calls, [ - "install -g @openai/codex@latest", - "install -g opencode-ai@latest", - ]); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("2.0.0"), - layerMockSpawner((_command, args) => { - calls.push(args.join(" ")); - if (calls.length === 1) { - firstStartedLatch.resolve(); - return { - stdout: "updated", - exitCode: Effect.promise(() => releaseFirst).pipe( - Effect.as(ChildProcessSpawner.ExitCode(0)), - ), - }; - } - return { stdout: "updated" }; - }), - ), - ), - ); - }); - - it.effect("accepts arbitrary driver-provided update lock keys", () => { - const calls: Array = []; - return Effect.gen(function* () { - const { registry } = yield* makeRegistry(baseProvider); - const updater = yield* makeTestRunner({ - ...registry, - getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => - Effect.succeed( - makeProviderMaintenanceCapabilities({ - provider, - packageName: "@openai/codex", - updateExecutable: "npm", - updateArgs: ["install", "-g", "@openai/codex@latest"], - updateLockKey: "unknown-lock-key", - }), - ), - }); - - const result = yield* updater.updateProvider(CODEX_DRIVER); - assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); - assert.deepStrictEqual(calls, ["install -g @openai/codex@latest"]); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerNonWindowsPlatform, - layerLatestVersionHttpClient("0.0.0"), - layerMockSpawner((_command, args) => { - calls.push(args.join(" ")); - return { stdout: "updated" }; - }), - ), - ), - ); - }); - it.effect( "releases the running-provider marker when interrupted after queuing but before the lock run starts", () => @@ -980,6 +674,180 @@ describe("providerMaintenanceRunner", () => { }); }); +it.effect.each([ + { + mode: "default", + version: "1.14.19", + installation: { installedVersion: "1.14.20" }, + status: "succeeded", + }, + { + mode: "targeted", + version: "1.14.19", + installation: { installedVersion: "1.14.20" }, + status: "succeeded", + }, + { + mode: "unknown", + version: "1.14.20", + installation: { installedVersion: null }, + status: "unchanged", + }, + { mode: "legacy", version: "1.14.20", installation: {}, status: "succeeded" }, +] as const)( + "verifies the $mode OpenCode update using the refreshed installation", + ({ mode, version, installation, status }) => { + const calls: string[] = []; + const capabilities = lifecycleFor(OPENCODE_DRIVER); + const pinnedCapabilities = { + ...capabilities, + update: { ...capabilities.update!, lockKey: "npm-global:/fixture" }, + }; + const manifest: ModelManifest.ModelManifestData = { + version: 1, + currentModels: {}, + compatibility: [ + { + driver: OPENCODE_DRIVER, + t3CodeRange: ">=0.0.42", + recommendedVersion: "1.14.20", + ranges: [{ range: "=1.14.20", status: "supported" }], + }, + ], + }; + return Effect.gen(function* () { + const { registry, providersRef } = yield* makeRegistry({ ...baseOpenCodeProvider, version }); + const httpClient = yield* HttpClient.HttpClient; + const latestVersions = yield* ProviderLatestVersions.ProviderLatestVersions; + const updater = yield* makeTestRunner( + { + ...registry, + getProviderMaintenanceCapabilitiesForInstance: () => Effect.succeed(pinnedCapabilities), + refreshAfterUpdate: () => + Effect.gen(function* () { + assert.strictEqual(calls.length, 1); + const refreshed = yield* enrichProviderSnapshotWithVersionAdvisory( + { ...baseOpenCodeProvider, version, ...installation }, + pinnedCapabilities, + ).pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.provideService( + ProviderLatestVersions.ProviderLatestVersions, + latestVersions, + ), + ); + return yield* Ref.updateAndGet(providersRef, (providers) => + providers.map((provider) => ({ ...provider, ...refreshed })), + ); + }), + }, + manifest, + ); + + const result = yield* updater.updateProvider({ + provider: OPENCODE_DRIVER, + ...(mode === "default" ? {} : { targetVersion: "1.14.20" }), + }); + + assert.deepStrictEqual(calls, [ + `npm install -g opencode-ai@${mode === "default" ? "latest" : "1.14.20"}`, + ]); + const provider = result.providers[0]; + assert.ok(provider); + assert.strictEqual(provider.updateState?.status, status); + assert.strictEqual(provider.version, version); + assert.strictEqual("installedVersion" in provider, mode !== "legacy"); + assert.strictEqual( + provider.versionAdvisory?.status, + mode === "unknown" ? "unknown" : "current", + ); + assert.strictEqual( + provider.versionAdvisory?.currentVersion, + mode === "unknown" ? null : "1.14.20", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + ProviderLatestVersions.layer, + layerLatestVersionHttpClient("1.14.20"), + layerMockSpawner((command, args) => { + calls.push([command, ...args].join(" ")); + return { stdout: "installed" }; + }), + ), + ), + ); + }, +); + +it.effect( + "uses fresh installer versions for post-update verification and compatibility checks", + () => { + const calls: string[] = []; + let latest = "1.0.0"; + const manifest: ModelManifest.ModelManifestData = { + version: 1, + currentModels: {}, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: "<=2.0.0", status: "supported" }, + { range: ">2.0.0", status: "broken" }, + ], + }, + ], + }; + return Effect.gen(function* () { + const { registry } = yield* makeRegistry({ ...baseProvider, version: "1.0.0" }); + const capabilities = makeProviderMaintenanceCapabilities({ + provider: CODEX_DRIVER, + packageName: "@openai/codex", + updateExecutable: "/opt/homebrew/bin/brew", + updateArgs: ["upgrade", "--cask", "codex"], + updateLockKey: "homebrew", + latestVersion: null, + lookupLatestVersion: Effect.sync(() => latest), + }); + const updater = yield* makeTestRunner( + { + ...registry, + getProviderMaintenanceCapabilitiesForInstance: () => Effect.succeed(capabilities), + }, + manifest, + ); + + const unchanged = yield* updater.updateProvider(CODEX_DRIVER); + assert.strictEqual(unchanged.providers[0]?.updateState?.status, "unchanged"); + assert.match(unchanged.providers[0]?.updateState?.message ?? "", /outdated provider version/); + assert.deepStrictEqual(calls, ["upgrade --cask codex"]); + + latest = "3.0.0"; + const refused = yield* updater.updateProvider(CODEX_DRIVER); + assert.strictEqual(refused.providers[0]?.updateState?.status, "failed"); + assert.match(refused.providers[0]?.updateState?.message ?? "", /incompatible/); + assert.deepStrictEqual(calls, ["upgrade --cask codex"]); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("Homebrew's latest should not come from npm")), + ), + layerMockSpawner((_command, args) => { + calls.push(args.join(" ")); + latest = "2.0.0"; + return { stdout: "upgraded" }; + }), + ), + ), + ); + }, +); + it.effect("refuses incompatible latest versions and unapproved or unpinnable targets", () => { const calls: string[] = []; const manifest: ModelManifest.ModelManifestData = { diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index 97b08c252bea9..9dddf23579d8a 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -30,7 +30,9 @@ import * as ProviderRegistry from "./ProviderRegistry.ts"; import { makeProviderMaintenanceCommandCoordinator } from "./providerMaintenanceCommandCoordinator.ts"; import { enrichProviderSnapshotWithVersionAdvisory, + invalidateLatestProviderVersion, makeTargetedProviderUpdateAction, + resolveLatestProviderUpdateAction, resolveLatestProviderVersion, type ProviderMaintenanceCommandAction, } from "@t3tools/provider-core/server/maintenanceResolver"; @@ -41,8 +43,7 @@ const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); const UPDATE_TIMEOUT_MS = 5 * 60_000; const UPDATE_OUTPUT_MAX_BYTES = 10_000; -// Every progress publish resends the provider list to each client, so the -// installer's output is sampled rather than forwarded line by line. +// Sample installer output because every progress update resends the provider list to all clients. const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1); const UPDATE_PROGRESS_MAX_LENGTH = 200; // An installer may write for minutes without a line ending; only its tail matters. @@ -96,9 +97,7 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR }) { const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")( function* () { - // On Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`), which a bare - // ChildProcess.spawn cannot launch (spawn npm ENOENT); resolveSpawnCommand finds the - // real `.cmd` and routes it through the shell. + // Windows batch shims require shell dispatch through resolveSpawnCommand. const resolved = yield* resolveSpawnCommand(input.command, input.args); const child = yield* input.spawner .spawn( @@ -240,14 +239,30 @@ function commandOutput(result: ProviderMaintenanceCommandResult): string | null return truncateText(output, UPDATE_OUTPUT_MAX_BYTES); } +// Updaters print their reason last, usually on stderr. +function lastOutputLine(result: ProviderMaintenanceCommandResult): string | null { + for (const output of [result.stderr, result.stdout]) { + const line = output + .split(/\r\n|\r|\n/) + .map(toProgressLine) + .findLast(Boolean); + if (line) { + return line; + } + } + return null; +} + function failureMessage(result: ProviderMaintenanceCommandResult): string { if (result.timedOut) { return "Update timed out."; } - if (result.exitCode !== null && result.exitCode !== 0) { - return `Update command exited with code ${result.exitCode}.`; - } - return "Update command failed."; + const summary = + result.exitCode !== null && result.exitCode !== 0 + ? `Update command exited with code ${result.exitCode}` + : "Update command failed"; + const reason = lastOutputLine(result); + return reason ? `${summary}: ${reason}` : `${summary}.`; } function isOutdatedProvider(provider: ServerProvider | undefined): boolean { @@ -274,7 +289,7 @@ function makeUpdateState(input: { }; } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const providerRegistry = yield* ProviderRegistry.ProviderRegistry; const manifestService = yield* ModelManifest.ModelManifest; @@ -305,28 +320,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { maintenanceCapabilities: ProviderMaintenanceCapabilities, instanceId: ProviderInstanceId, ): Effect.Effect => - providerRegistry.getProviders.pipe( - Effect.map((providers) => { - const instanceIds: Array = []; - for (const candidate of providers) { - if (candidate.driver === provider && candidate.instanceId === instanceId) { - instanceIds.push(candidate.instanceId); - } - } - return instanceIds; - }), - Effect.flatMap((instanceIds) => - instanceIds.length === 0 - ? providerRegistry.refreshInstance(instanceId) - : Effect.forEach( - instanceIds, - (instanceId) => providerRegistry.refreshInstance(instanceId), - { - concurrency: "unbounded", - discard: true, - }, - ).pipe(Effect.andThen(providerRegistry.getProviders)), - ), + providerRegistry.refreshAfterUpdate(provider, instanceId).pipe( Effect.flatMap((providers) => { const refreshedProviders = providers.filter( (candidate) => candidate.driver === provider && candidate.instanceId === instanceId, @@ -428,9 +422,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ).pipe(Effect.asVoid); yield* setRunningMessage("Checking for the latest version"); - // The cached capabilities chose the lock; re-derive ownership - // now so the command that runs matches the executable as it is - // at click time, not as it was at the last health refresh. + // Recheck ownership after acquiring the cached lock in case the executable changed. const fresh = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance( instanceId, provider, @@ -448,9 +440,11 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { } const manifest = yield* manifestService.current; + // Check compatibility against what an unpinned command would install now. const candidateVersion = targetVersion ?? - (yield* resolveLatestProviderVersion(fresh).pipe( + (yield* invalidateLatestProviderVersion(fresh).pipe( + Effect.andThen(resolveLatestProviderVersion(fresh)), Effect.provideService(HttpClient.HttpClient, httpClient), Effect.provideService( ProviderLatestVersions.ProviderLatestVersions, @@ -467,7 +461,7 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const command = targetVersion !== undefined ? makeTargetedProviderUpdateAction(fresh, targetVersion) - : fresh.update; + : resolveLatestProviderUpdateAction(fresh, candidateVersion); const rejected = targetVersion !== undefined ? !command || @@ -491,6 +485,13 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { const result = yield* runMaintenanceCommand(command, setRunningMessage); const finishedAt = yield* nowIso; if (result.timedOut || result.exitCode !== 0) { + yield* Effect.logWarning("Provider update command failed", { + provider, + command: describeCommand(command), + exitCode: result.exitCode, + timedOut: result.timedOut, + output: commandOutput(result), + }); return yield* finish( makeUpdateState({ status: "failed", @@ -503,27 +504,36 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { } yield* setRunningMessage("Verifying the installed version"); - // Homebrew's "latest" moves once the upgrade lands; read it again. const verified = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance( instanceId, provider, { fresh: true }, ); + yield* invalidateLatestProviderVersion(verified).pipe( + Effect.provideService(ProviderLatestVersions.ProviderLatestVersions, latestVersions), + ); const { verifiedProviders } = yield* verifyRefreshedProvider( provider, verified, instanceId, ); - // A missing version alone is not held against it, since Cursor's `about` probe can - // fail transiently on a healthy binary. + // Cursor about probes can fail transiently; missing versions alone do not imply failure. const couldNotVerify = verifiedProviders.length === 0 || - verifiedProviders.some( - (verifiedProvider) => + verifiedProviders.some((verifiedProvider) => { + const installedVersion = + verifiedProvider.installedVersion !== undefined + ? verifiedProvider.installedVersion + : verifiedProvider.version; + return ( !isStillInstalled(verifiedProvider) || + (verifiedProvider.status === "error" && + (verifiedProvider.auth.status !== "unauthenticated" || + !verifiedProvider.version)) || (targetVersion !== undefined && - verifiedProvider.version?.replace(/^v/, "") !== targetVersion), - ); + installedVersion?.replace(/^v/, "") !== targetVersion) + ); + }); const stillOutdated = targetVersion === undefined && verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider)); diff --git a/apps/server/src/provider/providerStatusCache.test.ts b/apps/server/src/provider/providerStatusCache.test.ts index cd7bfff273f86..79cb0bfbf5fdc 100644 --- a/apps/server/src/provider/providerStatusCache.test.ts +++ b/apps/server/src/provider/providerStatusCache.test.ts @@ -7,22 +7,11 @@ import { } from "@t3tools/contracts"; import { createModelCapabilities } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Logger from "effect/Logger"; -import { - hydrateCachedProvider, - isCachedProviderCorrelated, - readProviderStatusCache, - resolveProviderStatusCachePath, - writeProviderStatusCache, -} from "./providerStatusCache.ts"; +import { hydrateCachedProvider, isCachedProviderCorrelated } from "./providerStatusCache.ts"; const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] }); const CODEX_DRIVER = ProviderDriverKind.make("codex"); -const CLAUDE_AGENT_DRIVER = ProviderDriverKind.make("claudeAgent"); -const OPENCODE_DRIVER = ProviderDriverKind.make("opencode"); const makeProvider = ( provider: ProviderDriverKind, @@ -43,84 +32,6 @@ const makeProvider = ( }); it.layer(NodeServices.layer)("providerStatusCache", (it) => { - it.effect("logs structural diagnostics without retaining invalid cache contents", () => { - const messages: Array = []; - const logger = Logger.make((options) => { - if (Array.isArray(options.message)) { - messages.push(...options.message); - } else { - messages.push(options.message); - } - }); - - return Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-invalid-" }); - const cachePath = `${tempDir}/provider.json`; - const secretCacheValue = "secret-cache-value"; - yield* fs.writeFileString(cachePath, `{ "token": "${secretCacheValue}" }`); - - const result = yield* readProviderStatusCache(cachePath); - - assert.strictEqual(result, undefined); - const failure = messages.find( - (message): message is Record => - typeof message === "object" && message !== null && "path" in message, - ); - assert.exists(failure); - assert.strictEqual(failure.path, cachePath); - assert.strictEqual(typeof failure.errorTag, "string"); - assert.ok(!("cause" in failure)); - assert.ok(!("issues" in failure)); - assert.ok(!Object.values(failure).map(String).join("\n").includes(secretCacheValue)); - }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))); - }); - - it.effect("writes and reads provider status snapshots", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-provider-cache-" }); - const codexProvider = makeProvider(CODEX_DRIVER); - const claudeProvider = makeProvider(CLAUDE_AGENT_DRIVER, { - status: "warning", - auth: { status: "unknown" }, - }); - const openCodeProvider = makeProvider(OPENCODE_DRIVER, { - status: "warning", - auth: { status: "unknown", type: "opencode" }, - }); - const codexPath = yield* resolveProviderStatusCachePath({ - cacheDir: tempDir, - instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("codex")), - }); - const claudePath = yield* resolveProviderStatusCachePath({ - cacheDir: tempDir, - instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("claudeAgent")), - }); - const openCodePath = yield* resolveProviderStatusCachePath({ - cacheDir: tempDir, - instanceId: defaultInstanceIdForDriver(ProviderDriverKind.make("opencode")), - }); - - yield* writeProviderStatusCache({ - filePath: codexPath, - provider: codexProvider, - }); - yield* writeProviderStatusCache({ - filePath: claudePath, - provider: claudeProvider, - }); - yield* writeProviderStatusCache({ - filePath: openCodePath, - provider: openCodeProvider, - }); - - assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider); - assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider); - assert.deepStrictEqual(yield* readProviderStatusCache(openCodePath), openCodeProvider); - }), - ); - it("hydrates cached provider status while preserving current settings-derived models", () => { const cachedCodex = makeProvider(CODEX_DRIVER, { checkedAt: "2026-04-10T12:00:00.000Z", diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.ts index d2e5a70084dec..fd62e75cab077 100644 --- a/apps/server/src/provider/providerStatusCache.ts +++ b/apps/server/src/provider/providerStatusCache.ts @@ -20,9 +20,7 @@ const mergeProviderModels = ( cachedModels: ReadonlyArray, ): ReadonlyArray => { const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug)); - // The fallback snapshot is built from current settings and already carries - // every custom model, so cached custom rows that are not in it were removed - // while the cache was stale and must not come back. + // Settings already supply current custom models; cached rows could resurrect removed ones. return [ ...fallbackModels, ...cachedModels.filter((model) => !model.isCustom && !fallbackSlugs.has(model.slug)), @@ -94,10 +92,7 @@ export const hydrateCachedProvider = (input: { : hydratedProvider; }; -/** - * Cache contents must still carry matching `instanceId` + `driver` identity - * before hydration. The filename alone is not trusted as a routing key. - */ +/** Require matching instanceId and driver before hydration; filenames alone cannot authorize routing. */ export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCachePath")( function* (input: { readonly cacheDir: string; @@ -108,8 +103,8 @@ export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCa }, ); -export const readProviderStatusCache = (filePath: string) => - Effect.gen(function* () { +export const readProviderStatusCache = Effect.fn("providerStatusCache.readProviderStatusCache")( + function* (filePath: string) { const fs = yield* FileSystem.FileSystem; const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false)); if (!exists) { @@ -132,7 +127,8 @@ export const readProviderStatusCache = (filePath: string) => onSuccess: Effect.succeed, }), ); - }); + }, +); export const writeProviderStatusCache = (input: { readonly filePath: string; diff --git a/apps/server/src/provider/resetCreditCoordinator.ts b/apps/server/src/provider/resetCreditCoordinator.ts index 95e24cbdc656c..189c43b54f7f6 100644 --- a/apps/server/src/provider/resetCreditCoordinator.ts +++ b/apps/server/src/provider/resetCreditCoordinator.ts @@ -1,8 +1,4 @@ -/** - * Redeeming a reset credit is an account-level action: instances that share the - * directory holding a provider's login share the credit, so their redemptions - * must serialise on that directory, not the instance. - */ +/** Instances sharing a login directory share credits; serialize redemptions on that directory. */ import type { ProviderConsumeResetCreditOutcome } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; @@ -20,12 +16,7 @@ interface AccountRedemptionState { export class ResetCreditCoordinator extends Context.Service< ResetCreditCoordinator, { - /** - * The key is cleared when the provider reports an outcome, or when - * `isSettled` says a failure was a final answer (such as a cooldown). Any - * other failure (timeout included) keeps it so the next attempt is the same - * attempt. - */ + /** Reuse the idempotency key until an outcome or settled failure; timeouts keep it for retry. */ readonly redeem: ( accountKey: string, consume: (idempotencyKey: string) => Effect.Effect, @@ -35,13 +26,11 @@ export class ResetCreditCoordinator extends Context.Service< >()("t3/provider/resetCreditCoordinator") {} /** @public */ -/** @public Service construction is part of the canonical Effect module API. */ export const make = Effect.gen(function* () { const crypto = yield* Crypto.Crypto; const statesRef = yield* Ref.make>(new Map()); - // Get-or-create through one Ref.modify so two first redemptions for the - // same account cannot each install their own lock. + // Create account locks atomically so concurrent first redemptions cannot use separate locks. const stateFor = Effect.fn("ResetCreditCoordinator.stateFor")(function* (accountKey: string) { const existing = (yield* Ref.get(statesRef)).get(accountKey); if (existing) return existing; @@ -58,24 +47,25 @@ export const make = Effect.gen(function* () { }); }); - const redeem: ResetCreditCoordinator["Service"]["redeem"] = (accountKey, consume, isSettled) => - Effect.gen(function* () { - const state = yield* stateFor(accountKey); - return yield* state.lock.withPermits(1)( - Effect.gen(function* () { - const existing = yield* Ref.get(state.pendingKey); - const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4()); - yield* Ref.set(state.pendingKey, idempotencyKey); - const outcome = yield* consume(idempotencyKey).pipe( - Effect.tapError((error) => - isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void, - ), - ); - yield* Ref.set(state.pendingKey, null); - return outcome; - }), - ); - }); + const redeem: ResetCreditCoordinator["Service"]["redeem"] = Effect.fn( + "resetCreditCoordinator.redeem", + )(function* (accountKey, consume, isSettled) { + const state = yield* stateFor(accountKey); + return yield* state.lock.withPermits(1)( + Effect.gen(function* () { + const existing = yield* Ref.get(state.pendingKey); + const idempotencyKey = existing ?? (yield* crypto.randomUUIDv4()); + yield* Ref.set(state.pendingKey, idempotencyKey); + const outcome = yield* consume(idempotencyKey).pipe( + Effect.tapError((error) => + isSettled?.(error) ? Ref.set(state.pendingKey, null) : Effect.void, + ), + ); + yield* Ref.set(state.pendingKey, null); + return outcome; + }), + ); + }); return { redeem } satisfies ResetCreditCoordinator["Service"]; }); diff --git a/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjs b/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjs index 8e6284e3448dc..cae8ea2c9380d 100644 --- a/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjs +++ b/apps/server/src/provider/testFixtures/codexCollabMockPeer.mjs @@ -23,9 +23,7 @@ rl.on("line", (line) => { } const { id, method } = message; if (openServerRequests.has(id)) { - // Real codex identifies the resolved request by its item id — the key the - // runtime correlates on — so the receipt exercises the same path that - // closes the approval card in the UI. + // Match real Codex's resolved item ID so the runtime closes the corresponding approval card. const request = openServerRequests.get(id); openServerRequests.delete(id); NodeFS.appendFileSync( diff --git a/apps/server/src/provider/testUtils/providerRegistryMock.ts b/apps/server/src/provider/testUtils/providerRegistryMock.ts index 41b5c9b9ca353..358d49afe45c2 100644 --- a/apps/server/src/provider/testUtils/providerRegistryMock.ts +++ b/apps/server/src/provider/testUtils/providerRegistryMock.ts @@ -11,6 +11,7 @@ const makeProviderRegistryMock = ( getProviders: Effect.succeed(providers), refresh: () => Effect.succeed(providers), refreshInstance: () => Effect.succeed(providers), + refreshAfterUpdate: () => Effect.succeed(providers), refreshWorkspaceSnapshot: () => Effect.succeed(providers), getProviderMaintenanceCapabilitiesForInstance: (_instanceId, provider) => Effect.succeed(makeManualOnlyProviderMaintenanceCapabilities({ provider, packageName: null })), diff --git a/apps/server/src/provider/testing/ClaudeCapabilitiesProbe.fixture.mjs b/apps/server/src/provider/testing/ClaudeCapabilitiesProbe.fixture.mjs deleted file mode 100755 index f85dba5e6b5f2..0000000000000 --- a/apps/server/src/provider/testing/ClaudeCapabilitiesProbe.fixture.mjs +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env node -import * as NodeFS from "node:fs"; -import * as NodeReadline from "node:readline"; -const args = process.argv.slice(2); -const mcpConfigIndex = args.indexOf("--mcp-config"); -const rawMcpConfig = mcpConfigIndex >= 0 ? args[mcpConfigIndex + 1] : undefined; -let mcpConfig; -if (rawMcpConfig) { - const contents = NodeFS.existsSync(rawMcpConfig) - ? NodeFS.readFileSync(rawMcpConfig, "utf8") - : rawMcpConfig; - try { - mcpConfig = JSON.parse(contents); - } catch { - mcpConfig = contents; - } -} -NodeFS.writeFileSync( - process.env.T3_PROBE_INVOCATION_PATH, - JSON.stringify({ - args, - cwd: process.cwd(), - connectorEnv: process.env.ENABLE_CLAUDEAI_MCP_SERVERS, - mcpConfig, - }), -); -const lines = NodeReadline.createInterface({ input: process.stdin }); -lines.on("line", (line) => { - const message = JSON.parse(line); - if (message.type !== "control_request") return; - const reply = (response) => - process.stdout.write( - JSON.stringify({ - type: "control_response", - response: { subtype: "success", request_id: message.request_id, response }, - }) + "\n", - ); - if (message.request?.subtype === "initialize") { - reply({ - commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }], - agents: [], - output_style: "default", - available_output_styles: ["default"], - models: [], - account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" }, - }); - } - if (message.request?.subtype === "get_usage") { - reply({ - session: {}, - subscription_type: "pro", - rate_limits_available: true, - rate_limits: { five_hour: { utilization: 12, resets_at: "2026-07-18T14:39:00Z" } }, - behaviors: null, - }); - } -}); -// Stay alive for follow-up control requests, but never outlive the -// parent: the probe aborts the SDK without awaiting the child, so an -// unconditional interval would strand this process until reboot. -const keepAlive = setInterval(() => {}, 1_000); -lines.on("close", () => { - clearInterval(keepAlive); - process.exit(0); -}); diff --git a/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs b/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs index 3a864d524e800..5c4c84f2aa3e3 100755 --- a/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs +++ b/apps/server/src/provider/testing/ProviderInstanceRegistryLive.fixture.mjs @@ -10,13 +10,34 @@ if (process.argv.includes("--version")) { process.stdout.write("claude 2.1.219\n"); process.exit(0); } +const loginMarker = process.env.T3_CLAUDE_LOGIN_MARKER; +const signedOut = loginMarker !== undefined && !NodeFS.existsSync(loginMarker); +if (process.env.T3_CLAUDE_PROBE_LOG) + NodeFS.appendFileSync(process.env.T3_CLAUDE_PROBE_LOG, "probe\n"); const lines = NodeReadline.createInterface({ input: process.stdin }); lines.on("line", (line) => { const message = JSON.parse(line); if (message.type !== "control_request") return; + if (message.request?.subtype === "get_usage" && signedOut) { + process.stdout.write( + JSON.stringify({ + type: "control_response", + response: { + subtype: "success", + request_id: message.request_id, + response: { session: {}, rate_limits_available: false, rate_limits: null }, + }, + }) + "\n", + ); + return; + } if (message.request?.subtype === "get_usage") { const marker = process.env.T3_CLAUDE_RESET_MARKER; - if (process.env.T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM && marker && NodeFS.existsSync(marker)) { + const usageFailsUntil = process.env.T3_CLAUDE_USAGE_FAILS_UNTIL; + if ( + (usageFailsUntil && !NodeFS.existsSync(usageFailsUntil)) || + (process.env.T3_CLAUDE_USAGE_FAILS_AFTER_CLAIM && marker && NodeFS.existsSync(marker)) + ) { process.stdout.write( JSON.stringify({ type: "control_response", @@ -60,15 +81,15 @@ lines.on("line", (line) => { models: [], output_style: "default", available_output_styles: ["default"], - account: { email: "test@example.com", subscriptionType: "pro", tokenSource: "oauth" }, + account: signedOut + ? { tokenSource: "none", apiProvider: "firstParty" } + : { email: "test@example.com", subscriptionType: "pro", tokenSource: "oauth" }, }, }, }) + "\n", ); }); -// Stay alive for follow-up control requests, but never outlive the -// parent: the probe aborts the SDK without awaiting the child, so an -// unconditional interval would strand this process until reboot. +// Stay alive for control requests only while the parent lives; SDK abort does not await child exit. const keepAlive = setInterval(() => {}, 1_000); lines.on("close", () => { clearInterval(keepAlive); diff --git a/apps/server/src/provider/unavailableProviderSnapshot.ts b/apps/server/src/provider/unavailableProviderSnapshot.ts index 368c7e86d4606..8d34deab87b1c 100644 --- a/apps/server/src/provider/unavailableProviderSnapshot.ts +++ b/apps/server/src/provider/unavailableProviderSnapshot.ts @@ -19,38 +19,37 @@ export interface UnavailableProviderSnapshotInput { const nowIso = Effect.map(DateTime.now, DateTime.formatIso); -export function buildUnavailableProviderSnapshot( - input: UnavailableProviderSnapshotInput, -): Effect.Effect { - return Effect.gen(function* () { - const checkedAt = input.checkedAt ?? (yield* nowIso); - const displayName = input.displayName?.trim() || (input.driverKind as string); +export const buildUnavailableProviderSnapshot = Effect.fn( + "unavailableProviderSnapshot.buildUnavailableProviderSnapshot", +)(function* (input: UnavailableProviderSnapshotInput): Effect.fn.Return { + const checkedAt = input.checkedAt ?? (yield* nowIso); + const displayName = input.displayName?.trim() || (input.driverKind as string); - const base = buildServerProvider({ - presentation: { displayName }, - enabled: false, - checkedAt, - models: [], - skills: [], - probe: { - installed: false, - version: null, - status: "error", - auth: { status: "unknown" }, - message: input.reason, - }, - }); - - return { - ...base, - instanceId: input.instanceId, - ...(input.accentColor ? { accentColor: input.accentColor } : {}), - driver: - typeof input.driverKind === "string" - ? ProviderDriverKind.make(input.driverKind) - : input.driverKind, - availability: "unavailable", - unavailableReason: input.reason, - }; + // No driver ran, so its setup capabilities are still unknown. + const { setup: _setup, ...base } = buildServerProvider({ + presentation: { displayName }, + enabled: false, + checkedAt, + models: [], + skills: [], + probe: { + installed: false, + version: null, + status: "error", + auth: { status: "unknown" }, + message: input.reason, + }, }); -} + + return { + ...base, + instanceId: input.instanceId, + ...(input.accentColor ? { accentColor: input.accentColor } : {}), + driver: + typeof input.driverKind === "string" + ? ProviderDriverKind.make(input.driverKind) + : input.driverKind, + availability: "unavailable", + unavailableReason: input.reason, + }; +}); diff --git a/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts b/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts deleted file mode 100644 index 4b8f3c38ac13f..0000000000000 --- a/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; -import { assert, it } from "@effect/vitest"; - -import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; -import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy"; -import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; -import { azureDevOpsProviderFailure } from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestProvider"; -import { bitbucketProviderFailure } from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestProvider"; -import { gitHubProviderFailure } from "@t3tools/source-control-github/server/GitHubPullRequestProvider"; -import { gitLabProviderFailure } from "@t3tools/source-control-gitlab/server/GitLabPullRequestProvider"; - -const cause = new Error("redacted provider failure"); - -it("classifies rate limits from every pull-request provider", () => { - assert.deepStrictEqual( - gitHubProviderFailure( - new GitHubRequestPolicy.GitHubApiRateLimitError({ host: "github.com", operation: "execute" }), - ), - { reason: "rate-limited" }, - ); - assert.deepStrictEqual( - gitLabProviderFailure( - new GitLabCli.GitLabCliRateLimitError({ - operation: "execute", - command: "glab", - cwd: "/repo", - cause, - }), - ), - { reason: "rate-limited" }, - ); - assert.deepStrictEqual( - azureDevOpsProviderFailure( - new AzureDevOpsCli.AzureDevOpsCliRateLimitError({ - operation: "execute", - command: "az", - cwd: "/repo", - argumentCount: 1, - cause, - }), - ), - { reason: "rate-limited" }, - ); - assert.deepStrictEqual( - bitbucketProviderFailure( - new BitbucketApi.BitbucketResponseError({ - operation: "request", - status: 429, - responseBodyLength: 0, - retryAt: 120_000, - }), - ), - { reason: "rate-limited", retryAt: 120_000 }, - ); -}); - -it("keeps GitHub's exact retry time", () => { - assert.deepStrictEqual( - gitHubProviderFailure( - new SourceControlRateLimit.SourceControlRateLimitPausedError({ - provider: SourceControlProviderKind.make("github"), - host: "github.com", - retryAt: 1_786_802_400_000, - }), - ), - { reason: "rate-limited", retryAt: 1_786_802_400_000 }, - ); -}); diff --git a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts b/apps/server/src/pullRequest/PullRequestProviderRegistry.ts index 22a07e2a23171..63323b6122d20 100644 --- a/apps/server/src/pullRequest/PullRequestProviderRegistry.ts +++ b/apps/server/src/pullRequest/PullRequestProviderRegistry.ts @@ -24,16 +24,10 @@ export function fromProviders( }; } -/** - * @public Service construction is part of the canonical Effect module API. - */ +/** @public */ export const make = Effect.gen(function* () { - const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) => - driver.make.pipe(Effect.map((instance) => instance.pullRequests)), - ); - return fromProviders( - drivers.filter((provider): provider is PullRequestProviderApi => provider !== null), - ); + const drivers = yield* BuiltInDrivers.SourceControlDrivers; + return fromProviders(drivers.flatMap(({ instance }) => instance.pullRequests ?? [])); }); export const layer = Layer.effect(PullRequestProviderRegistry, make).pipe( diff --git a/apps/server/src/pullRequest/PullRequestReadCache.test.ts b/apps/server/src/pullRequest/PullRequestReadCache.test.ts index a4c0c8b178798..2d2fcfc1f05a8 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.test.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.test.ts @@ -1,123 +1,17 @@ import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { PullRequestOperationError } from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; -import * as Layer from "effect/Layer"; -import * as Path from "effect/Path"; -import * as Queue from "effect/Queue"; -import * as TestClock from "effect/testing/TestClock"; import * as KeyValueStore from "effect/persistence/KeyValueStore"; -import * as ServerConfig from "../config.ts"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; const cacheLayer = (directory: string) => PullRequestReadCache.make.pipe(Effect.provide(KeyValueStore.layerFileSystem(directory))); -const ageFiles = (directory: string, names: ReadonlyArray, age: Duration.Duration) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const mtime = DateTime.toDateUtc(DateTime.subtractDuration(yield* DateTime.now, age)); - for (const name of names) yield* fs.utimes(path.join(directory, name), mtime, mtime); - }); - it.layer(NodeServices.layer)("PR filesystem cache", (it) => { - it.effect("prunes entry files written before the max age and keeps fresh ones", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" }); - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-01T00:00:00Z"))); - const cache = yield* cacheLayer(directory); - yield* cache.get("old", Effect.succeed("old"), ["pr"]); - yield* cache.invalidate("pr"); - const [stale, revisions] = (yield* fs.readDirectory(directory)).toSorted(); - assert.strictEqual(revisions, "revisions"); - yield* cache.get("fresh", Effect.succeed("fresh")); - const fresh = (yield* fs.readDirectory(directory)).find( - (name) => name !== stale && name !== revisions, - ); - const unrelated = "unrelated.json"; - yield* fs.writeFileString(`${directory}/${unrelated}`, "{}"); - const prefixed = "pr-v2-backup.json"; - yield* fs.writeFileString(`${directory}/${prefixed}`, "{}"); - const justExpired = Duration.sum( - PullRequestReadCache.ENTRY_FILE_MAX_AGE, - Duration.seconds(1), - ); - yield* ageFiles(directory, [stale!, revisions!, unrelated, prefixed], justExpired); - yield* ageFiles(directory, [fresh!], PullRequestReadCache.ENTRY_FILE_MAX_AGE); - - yield* PullRequestReadCache.pruneExpiredEntryFiles(directory); - - assert.deepStrictEqual( - (yield* fs.readDirectory(directory)).toSorted(), - [fresh!, revisions!, unrelated, prefixed].toSorted(), - ); - }), - ); - - it.effect("sweeps the cache directory every hour once the layer is built", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const { providerStatusCacheDir } = yield* ServerConfig.ServerConfig; - const directory = `${providerStatusCacheDir}/pull-requests`; - yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-01T00:00:00Z"))); - yield* (yield* cacheLayer(directory)).get("summary", Effect.succeed("cached")); - const [entry] = yield* fs.readDirectory(directory); - yield* ageFiles( - directory, - [entry!], - Duration.subtract(PullRequestReadCache.ENTRY_FILE_MAX_AGE, Duration.minutes(90)), - ); - const operations = yield* Queue.unbounded(); - const observedFs = FileSystem.FileSystem.of({ - ...fs, - stat: (path) => fs.stat(path).pipe(Effect.tap(() => Queue.offer(operations, "stat"))), - remove: (path, options) => - fs.remove(path, options).pipe(Effect.tap(() => Queue.offer(operations, "remove"))), - }); - yield* Layer.build( - PullRequestReadCache.layer.pipe( - Layer.provide(Layer.succeed(FileSystem.FileSystem, observedFs)), - ), - ); - assert.strictEqual(yield* Queue.take(operations), "stat"); - yield* TestClock.adjust("1 hour"); - assert.strictEqual(yield* Queue.take(operations), "stat"); - assert.deepStrictEqual(yield* fs.readDirectory(directory), [entry]); - yield* TestClock.adjust("1 hour"); - assert.deepStrictEqual(yield* Queue.takeN(operations, 2), ["stat", "remove"]); - assert.deepStrictEqual(yield* fs.readDirectory(directory), []); - }).pipe( - Effect.scoped, - Effect.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-pr-cache-layer-" })), - ), - ); - - it.effect("reuses files after restart and respects the original expiry", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" }); - let reads = 0; - const lookup = Effect.sync(() => String(++reads)); - const first = yield* cacheLayer(directory); - const key = "long/repository/key".repeat(100); - assert.strictEqual(yield* first.get(key, lookup), "1"); - yield* TestClock.adjust("59 seconds"); - const restarted = yield* cacheLayer(directory); - assert.strictEqual(yield* restarted.get(key, lookup), "1"); - yield* TestClock.adjust("1 second"); - assert.strictEqual(yield* restarted.get(key, lookup), "2"); - assert.strictEqual(reads, 2); - assert.strictEqual((yield* fs.readDirectory(directory)).length, 1); - }), - ); - it.effect("clears in-flight reads before a new service can reuse them", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -212,29 +106,6 @@ it.layer(NodeServices.layer)("PR filesystem cache", (it) => { }).pipe(Effect.provide(KeyValueStore.layerMemory)), ); - it.effect("compacts expired scope records without discarding fresh PR data", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pr-cache-" }); - const cache = yield* cacheLayer(directory); - yield* cache.get("summary", Effect.succeed("old"), ["pr"]); - yield* cache.invalidate("pr"); - for (let index = 0; index < 100; index++) yield* cache.invalidate(`pr-${index}`); - assert.strictEqual((yield* fs.readDirectory(directory)).length, 2); - const before = (yield* fs.stat(`${directory}/revisions`)).size; - yield* TestClock.adjust("59 seconds"); - assert.strictEqual(yield* cache.get("summary", Effect.succeed("fresh"), ["pr"]), "fresh"); - yield* TestClock.adjust("1 second"); - yield* cache.invalidate("other-pr"); - assert.isTrue((yield* fs.stat(`${directory}/revisions`)).size < before); - const restarted = yield* cacheLayer(directory); - assert.strictEqual( - yield* restarted.get("summary", Effect.die("cache miss"), ["pr"]), - "fresh", - ); - }), - ); - it.effect("does not persist failed GitHub reads", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/pullRequest/PullRequestReadCache.ts b/apps/server/src/pullRequest/PullRequestReadCache.ts index 16860c78ee9a2..649a1cea80d3f 100644 --- a/apps/server/src/pullRequest/PullRequestReadCache.ts +++ b/apps/server/src/pullRequest/PullRequestReadCache.ts @@ -24,15 +24,14 @@ import * as ServerConfig from "../config.ts"; import { forkParked } from "../serverActivation.ts"; const CONCURRENT_READS = 512; -// Persistence prefixes every entry key with the store id, so each entry file -// name starts with it. The scope `revisions` file does not. +// Entry filenames have the store-id prefix; the scope revisions file does not. const STORE_ID = "pr-v2"; const ENTRY_FILE_NAME = new RegExp(`^${STORE_ID}[0-9a-f]{64}$`); /** * A file untouched for a day is long expired; the day only leaves slack for * clock changes. */ -export const ENTRY_FILE_MAX_AGE = Duration.days(1); +const ENTRY_FILE_MAX_AGE = Duration.days(1); type ReadError = PullRequestOperationError | PullRequestUnavailableError; const revisionCodec = Schema.fromJsonString( Schema.Record( @@ -153,8 +152,8 @@ export const make = Effect.gen(function* () { lock.withPermits(1), ); }), - invalidate: (scope) => - Effect.gen(function* () { + invalidate: Effect.fn("PullRequestReadCache.invalidate")( + function* (scope) { const now = clock.currentTimeMillisUnsafe(); const current = yield* Cache.get(revisions, undefined); const next = Object.fromEntries( @@ -164,14 +163,14 @@ export const make = Effect.gen(function* () { const encoded = yield* Schema.encodeEffect(revisionCodec)(next); yield* backing.set("revisions", encoded); yield* Cache.set(revisions, undefined, next); - }).pipe( - Effect.catch(() => { - enabled = false; - return Effect.logWarning("PR cache disabled after clearing failed"); - }), - Effect.uninterruptible, - lock.withPermits(CONCURRENT_READS), - ), + }, + Effect.catch(() => { + enabled = false; + return Effect.logWarning("PR cache disabled after clearing failed"); + }), + Effect.uninterruptible, + lock.withPermits(CONCURRENT_READS), + ), }); }); @@ -179,33 +178,33 @@ export const make = Effect.gen(function* () { * The persisted cache drops an expired entry only when it is read again, so * files for PRs nobody reopens would otherwise stay forever. */ -export const pruneExpiredEntryFiles = Effect.fn("PullRequestReadCache.pruneExpiredEntryFiles")( - function* (directory: string) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cutoff = (yield* Clock.currentTimeMillis) - Duration.toMillis(ENTRY_FILE_MAX_AGE); - const entries = (yield* fileSystem.readDirectory(directory)).filter((name) => - ENTRY_FILE_NAME.test(name), +const pruneExpiredEntryFiles = Effect.fn("PullRequestReadCache.pruneExpiredEntryFiles")(function* ( + directory: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cutoff = (yield* Clock.currentTimeMillis) - Duration.toMillis(ENTRY_FILE_MAX_AGE); + const entries = (yield* fileSystem.readDirectory(directory)).filter((name) => + ENTRY_FILE_NAME.test(name), + ); + const [, failures] = yield* Effect.partition(entries, (name) => { + const entryPath = path.join(directory, name); + return fileSystem.stat(entryPath).pipe( + Effect.flatMap((info) => + Option.exists(info.mtime, (mtime) => mtime.getTime() < cutoff) + ? fileSystem.remove(entryPath) + : Effect.void, + ), + Effect.catchReason("PlatformError", "NotFound", () => Effect.void), ); - const [, failures] = yield* Effect.partition(entries, (name) => { - const entryPath = path.join(directory, name); - return fileSystem.stat(entryPath).pipe( - Effect.flatMap((info) => - Option.exists(info.mtime, (mtime) => mtime.getTime() < cutoff) - ? fileSystem.remove(entryPath) - : Effect.void, - ), - Effect.catchReason("PlatformError", "NotFound", () => Effect.void), - ); + }); + if (failures.length > 0) { + yield* Effect.logWarning("Failed to prune some PR cache files", { + failed: failures.length, + cause: failures[0], }); - if (failures.length > 0) { - yield* Effect.logWarning("Failed to prune some PR cache files", { - failed: failures.length, - cause: failures[0], - }); - } - }, -); + } +}); export const layer = Layer.unwrap( Effect.gen(function* () { @@ -214,17 +213,18 @@ export const layer = Layer.unwrap( const directory = path.join(config.providerStatusCacheDir, "pull-requests"); return Layer.effect(PullRequestReadCache, make).pipe( Layer.provide( - KeyValueStore.layerFileSystem(directory).pipe( - Layer.tap(() => - forkParked( - pruneExpiredEntryFiles(directory).pipe( - Effect.catch((cause) => - Effect.logWarning("Failed to prune PR cache files", { cause }), - ), - Effect.repeat(Schedule.spaced(Duration.hours(1))), + // Memoize cleanup acquisition with the store; Layer.tap runs per consumer. + Layer.effectDiscard( + forkParked( + pruneExpiredEntryFiles(directory).pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to prune PR cache files", { cause }), ), + Effect.repeat(Schedule.spaced(Duration.hours(1))), ), ), + ).pipe( + Layer.provideMerge(KeyValueStore.layerFileSystem(directory)), Layer.catch(() => Layer.effectDiscard( Effect.logWarning("PR cache directory unavailable; using memory cache"), diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts index 403424cdc5970..b4dd965570a9f 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.test.ts @@ -3,10 +3,12 @@ import { assert, it } from "@effect/vitest"; import * as Context from "effect/Context"; 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 Ref from "effect/Ref"; -import * as Schedule from "effect/Schedule"; +import * as Queue from "effect/Queue"; +import * as Tracer from "effect/Tracer"; import { ProjectId, GitCommandError, @@ -15,7 +17,6 @@ import { type PullRequestStack, type PullRequestRef, } from "@t3tools/contracts"; -import type { ReviewGuideGenerationInput } from "@t3tools/provider-core/server/textGeneration"; import * as ServerConfig from "../config.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; @@ -88,11 +89,12 @@ const makeRepositories = Effect.gen(function* () { yield* git(remote, ["checkout", "--quiet", "main"]); yield* commit("unrelated.txt", "main moved on"); yield* git(root, ["clone", "--quiet", remote, workspace]); - return { root, workspace, headSha, lowerSha, upperSha }; + return { root, remote, workspace, headSha, lowerSha, upperSha }; }); const detail = (workspaceRoot: string, headSha: string): PullRequestDetail => ({ + provider: "github", number: 7, title: "Add the feature", body: "Adds the feature.", @@ -147,6 +149,7 @@ const stack = (repositories: { const makeLayer = (input: { readonly root: string; + readonly remote: string; readonly workspace: string; readonly headSha: string; readonly lowerSha: string; @@ -191,7 +194,10 @@ const makeLayer = (input: { Effect.succeedSome({ id: projectId, workspaceRoot: input.workspace, - repositoryIdentity: input.identity ?? ACME_APP, + repositoryIdentity: { + ...(input.identity ?? ACME_APP), + locator: { ...ACME_APP.locator, remoteUrl: input.remote }, + }, }), } as unknown as ProjectService.ProjectService["Service"]), ), @@ -219,18 +225,33 @@ const layerBase = Layer.mergeAll( type Repositories = Effect.Success; -const awaitRunFailure = ( - service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"], - input: PullRequestRef, -) => - service.get(input).pipe( - Effect.flatMap((result) => - result.run?._tag === "Failed" - ? Effect.succeed(result.run.detail) - : Effect.fail("still running" as const), - ), - Effect.retry(Schedule.spaced("20 millis")), - ); +// A run forks into the service's scope, so a test learns it settled when the run's `write` span +// ends; the run records its outcome synchronously right after. +const watchRuns = Effect.gen(function* () { + const ended = yield* Queue.unbounded(); + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + if (options.name !== "PullRequestReviewGuideService.write") return span; + const end = span.end.bind(span); + span.end = (endTime, exit) => { + end(endTime, exit); + Queue.offerUnsafe(ended, undefined); + }; + return span; + }, + }); + return { + generate: ( + service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"], + input: PullRequestRef, + ) => service.generate(input).pipe(Effect.withTracer(tracer)), + settled: ( + service: PullRequestReviewGuideService.PullRequestReviewGuideService["Service"], + input: PullRequestRef, + ) => Queue.take(ended).pipe(Effect.andThen(service.get(input))), + }; +}); const startSingleBranchRun = (input: { readonly repositoryName: string; @@ -326,7 +347,8 @@ const startSingleBranchRun = (input: { PullRequestReviewGuideService.PullRequestReviewGuideService, ); const guideReference = { ...reference, repository: `acme/${input.repositoryName}` }; - yield* service.generate(guideReference); + const runs = yield* watchRuns; + yield* runs.generate(service, guideReference); return { repositories, reportedHead, @@ -335,146 +357,11 @@ const startSingleBranchRun = (input: { stored, fetchedRefs, observed, + settled: runs.settled(service, guideReference), }; }); -// Runs drive real git, which the test clock does not advance, so waits use real time. it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideService", (it) => { - it.effect.each([ - { - name: "a short head already fetched", - shortHash: true, - prepare: "fetch-feature", - pushDuringFetch: false, - refuseCommitFetch: true, - expectedFetches: [], - }, - { - name: "a short head on its branch", - shortHash: true, - prepare: "none", - pushDuringFetch: false, - refuseCommitFetch: true, - expectedFetches: ["refs/heads/feature"], - }, - { - name: "a short head whose branch moves during the fetch", - shortHash: true, - prepare: "none", - pushDuringFetch: true, - refuseCommitFetch: true, - expectedFetches: ["refs/heads/feature"], - }, - { - name: "a full head served by commit", - shortHash: false, - prepare: "none", - pushDuringFetch: false, - refuseCommitFetch: false, - expectedFetches: [""], - }, - { - name: "a full head on its branch", - shortHash: false, - prepare: "none", - pushDuringFetch: false, - refuseCommitFetch: true, - expectedFetches: ["", "refs/heads/feature"], - }, - { - name: "a full head only on its pull ref", - shortHash: false, - prepare: "refs/pull/7/head", - pushDuringFetch: false, - refuseCommitFetch: true, - expectedFetches: ["", "refs/heads/feature", "refs/pull/7/head"], - }, - { - name: "a full head only on its merge request ref", - shortHash: false, - prepare: "refs/merge-requests/7/head", - pushDuringFetch: false, - refuseCommitFetch: true, - expectedFetches: [ - "", - "refs/heads/feature", - "refs/pull/7/head", - "refs/merge-requests/7/head", - ], - }, - ])( - "writes a guide for the reported commit: $name", - ({ shortHash, prepare, pushDuringFetch, refuseCommitFetch, expectedFetches }) => - Effect.scoped( - Effect.gen(function* () { - const run = yield* startSingleBranchRun({ - repositoryName: "fetched-head", - reportedHead: (repositories) => - shortHash ? repositories.headSha.slice(0, 12) : repositories.headSha, - refuseCommitFetch, - prepare: (repositories, workspace) => { - const remote = `${repositories.root}/remote`; - if (prepare === "fetch-feature") { - return git(workspace, ["fetch", "--quiet", "origin", "feature"]).pipe( - Effect.asVoid, - ); - } - if (prepare === "none") return Effect.void; - return git(remote, ["update-ref", prepare, repositories.headSha]).pipe( - Effect.andThen( - git(remote, ["update-ref", "refs/heads/feature", repositories.lowerSha]), - ), - Effect.asVoid, - ); - }, - onBranchFetch: pushDuringFetch - ? (repositories) => { - const remote = `${repositories.root}/remote`; - return git(remote, ["checkout", "--quiet", "feature"]).pipe( - Effect.andThen( - git(remote, [ - "commit", - "--quiet", - "--allow-empty", - "-m", - "push during fetch", - ]), - ), - Effect.asVoid, - ); - } - : undefined, - }); - yield* Effect.raceFirst( - Deferred.await(run.stored), - awaitRunFailure(run.service, run.reference).pipe( - Effect.flatMap((detail) => Effect.die(`run failed: ${detail}`)), - ), - ); - const { headSha } = run.repositories; - const result = yield* run.service.get(run.reference); - assert.strictEqual(result.guide?.headSha, run.reportedHead); - assert.deepStrictEqual(result.guide?.stops[0]?.files, [{ path: "feature.txt" }]); - assert.deepStrictEqual(run.observed, [ - { cwd: run.observed[0]?.cwd, head: headSha, changed: "feature.txt" }, - ]); - const headRefs = new Set([ - headSha, - run.reportedHead, - "refs/heads/feature", - "refs/pull/7/head", - "refs/merge-requests/7/head", - ]); - assert.deepStrictEqual( - run.fetchedRefs.filter((ref) => headRefs.has(ref)), - expectedFetches.map((ref) => (ref === "" ? headSha : ref)), - ); - const fs = yield* FileSystem.FileSystem; - assert.isFalse(yield* fs.exists(run.observed[0]?.cwd ?? "")); - }), - ), - ); - it.effect.each([ { name: "a branch named like the short head", @@ -499,13 +386,7 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic name: "a head no source has", reportedHead: () => "e".repeat(40), shadow: "none", - expected: [ - "local objects:", - "the commit:", - "branch feature:", - "refs/pull/7/head:", - "refs/merge-requests/7/head:", - ], + expected: ["local objects:", "the commit:", "branch feature:", "refs/pull/7/head:"], }, ])("refuses to write a guide for $name", ({ reportedHead, shadow, expected }) => Effect.scoped( @@ -524,11 +405,13 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic Effect.asVoid, ), }); - const detail = yield* Effect.raceFirst( - awaitRunFailure(run.service, run.reference), - Deferred.await(run.stored).pipe(Effect.andThen(Effect.die("a guide was written"))), - ); + 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; @@ -537,237 +420,102 @@ it.layer(layerBase, { excludeTestServices: true })("PullRequestReviewGuideServic ), ); - it.effect("briefs the change against its own base in a checkout it then removes", () => + 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 seen = yield* Deferred.make<{ - readonly input: ReviewGuideGenerationInput; - readonly changed: string; - readonly head: string; - readonly upper: string; - }>(); - const finish = yield* Deferred.make(); + 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 readCheckout = (cwd: string, args: ReadonlyArray) => - git(cwd, args).pipe( - Effect.provideService(GitVcsDriver.GitVcsDriver, driver), - Effect.orDie, - ); const stored = yield* Deferred.make(); - - // Built in this test's scope: runs are forked into the service's scope and must outlive - // the call that obtains the service. const context = yield* Layer.build( makeLayer({ ...repositories, stored, generate: (input) => - Effect.gen(function* () { - const changed = yield* readCheckout(input.cwd, [ - "diff", - "--name-only", - `${input.baseCommit}...HEAD`, - ]); - const head = yield* readCheckout(input.cwd, ["rev-parse", "HEAD"]); - const upper = yield* readCheckout(input.cwd, [ - "show", - `${repositories.upperSha}:upper.txt`, - ]); - yield* Deferred.succeed(seen, { input, changed, head, upper }); - yield* Deferred.await(finish); - return { - stops: [ - { - title: "The feature", - summary: "The change.", - attention: null, - excerpts: [ - { path: "feature.txt", side: "new", start: 4, end: 40, caption: "" }, - ], - files: [], - notes: [ - { path: "feature.txt", line: 5, title: "Kept", body: "Inside." }, - { path: "feature.txt", line: 30, title: "Dropped", body: "Outside." }, - ], - questions: [], - }, - ], - }; - }), + 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, ); - - const started = yield* service.generate(reference); - assert.strictEqual(started.run?._tag, "Running"); - assert.strictEqual(started.guide, null); - assert.isTrue(started.started); - - const failedRun = service.get(reference).pipe( - Effect.flatMap((result) => - result.run?._tag === "Failed" - ? Effect.die(`run failed: ${result.run.detail}`) - : Effect.fail("still running" as const), - ), - Effect.retry(Schedule.spaced("20 millis")), - ); - const observed = yield* Effect.raceFirst(Deferred.await(seen), failedRun); - assert.strictEqual(observed.head, repositories.headSha); - assert.strictEqual(observed.changed, "feature.txt"); - assert.strictEqual(observed.input.baseBranch, "stack-base"); - assert.deepStrictEqual(observed.input.stack, [ - { number: 6, title: "Lower", state: "open", headSha: repositories.lowerSha }, - { number: 7, title: "Add the feature", state: "open", headSha: repositories.headSha }, - { number: 8, title: "Upper", state: "open", headSha: repositories.upperSha }, - { number: 9, title: "Unpushed", state: "open", headSha: null }, - ]); - assert.strictEqual(observed.upper, "upper layer"); - - const joined = yield* service.generate(reference); - assert.strictEqual(joined.run, started.run); - assert.isFalse(joined.started); - - yield* Deferred.succeed(finish, undefined); + yield* service.generate(reference); + assert.strictEqual(yield* Deferred.await(changed), "feature.txt"); yield* Deferred.await(stored); - const finished = yield* service.get(reference); - assert.strictEqual(finished.guide?.headSha, repositories.headSha); - const guide = finished.guide; - assert.isNotNull(guide); - const [story] = guide.stops; - assert.deepStrictEqual(story?.excerpts, [ - { path: "feature.txt", side: "new", start: 4, end: 10, caption: "" }, - ]); - assert.deepStrictEqual( - story?.notes.map((note) => note.title), - ["Kept"], - ); - assert.strictEqual(guide.stops.length, 1); - - const fs = yield* FileSystem.FileSystem; - assert.isFalse(yield* fs.exists(observed.input.cwd)); - const worktrees = yield* git(repositories.workspace, ["worktree", "list", "--porcelain"]); - assert.notInclude(worktrees, observed.input.cwd); + 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("refuses to write a guide while the server has review guides off", () => + 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, - enabled: false, - generate: () => Effect.die("a guide must not be written while the beta is off"), - }), + 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 result = yield* Effect.flip(service.generate(reference)); - assert.include(result.message, "Review guides are off"); + 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( - "keeps a newer run's guide when an older run for the same pull request finishes late", - () => - Effect.scoped( - Effect.gen(function* () { - const repositories = yield* makeRepositories; - const stored = yield* Deferred.make(); - const currentHead = yield* Ref.make(repositories.headSha); - const releaseOld = yield* Deferred.make(); - const oldStarted = yield* Deferred.make(); - const answer = (title: string) => ({ - stops: [ - { - title, - summary: "", - attention: null, - excerpts: [], - files: [], - notes: [], - questions: [], - }, - ], - }); - const context = yield* Layer.build( - makeLayer({ - ...repositories, - stored, - currentHead, - generate: (input) => - input.cwd.length > 0 && input.baseCommit.length > 0 - ? Ref.get(currentHead).pipe( - Effect.flatMap((head) => - head === repositories.headSha - ? Deferred.succeed(oldStarted, undefined).pipe( - Effect.andThen(Deferred.await(releaseOld)), - Effect.as(answer("old head")), - ) - : Effect.succeed(answer("new head")), - ), - ) - : Effect.die("unreachable"), - }), - ); - const service = Context.get( - context, - PullRequestReviewGuideService.PullRequestReviewGuideService, - ); - - yield* service.generate(reference); - const firstFailed = service.get(reference).pipe( - Effect.flatMap((result) => - result.run?._tag === "Failed" - ? Effect.die(`first run failed: ${result.run.detail}`) - : Effect.fail("still running" as const), - ), - Effect.retry(Schedule.spaced("20 millis")), - ); - yield* Effect.raceFirst(Deferred.await(oldStarted), firstFailed); - yield* Ref.set(currentHead, repositories.upperSha); - const second = yield* service.generate(reference); - assert.strictEqual(second.run?._tag, "Running"); - assert.strictEqual(second.run?.headSha, repositories.upperSha); - const failedRun = service.get(reference).pipe( - Effect.flatMap((result) => - result.run?._tag === "Failed" - ? Effect.die(`run failed: ${result.run.detail}`) - : Effect.fail("still running" as const), - ), - Effect.retry(Schedule.spaced("20 millis")), - ); - yield* Effect.raceFirst(Deferred.await(stored), failedRun); - - yield* Deferred.succeed(releaseOld, undefined); - const settled = yield* service.get(reference).pipe( - Effect.filterOrFail( - (result) => result.run === null, - () => "still running" as const, - ), - Effect.retry({ schedule: Schedule.spaced("20 millis"), times: 250 }), - ); - assert.strictEqual(settled.guide?.headSha, repositories.upperSha); - yield* Effect.sleep("200 millis"); - const after = yield* service.get(reference); - assert.isNull(after.run); - assert.strictEqual(after.guide?.headSha, repositories.upperSha); - assert.strictEqual(after.guide?.stops[0]?.title, "new head"); - }), - ), - ); - it.effect("refuses a pull request from a repository the project is not a checkout of", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts index 8086541067fbe..e0dc7309289b6 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts @@ -24,7 +24,7 @@ import { } from "@t3tools/contracts"; import type { ReviewGuideStackLayer } from "@t3tools/provider-core/server/textGeneration"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; -import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import * as ServerConfig from "../config.ts"; import * as PullRequestReviewGuides from "../persistence/PullRequestReviewGuides.ts"; @@ -75,8 +75,7 @@ const make = Effect.gen(function* () { const serviceScope = yield* Effect.scope; const runs = yield* Ref.make>(new Map()); let runCounter = 0; - // Claiming a run and storing a finished guide take turns, so a run that still owns its pull - // request when it checks is the one whose guide is stored: a newer claim cannot land between. + // Serialize claims and guide writes so a newer claim cannot steal ownership between checking and storing. const ownership = yield* Semaphore.make(1); const keyFor = Effect.fn("PullRequestReviewGuideService.keyFor")(function* ( @@ -104,17 +103,23 @@ const make = Effect.gen(function* () { { projectId: ProjectId.make("own"), number: key.number, - repository: sourceControlRepositorySelector(identity) ?? "", + repository: sourceControlDefinitions.repositorySelector(identity) ?? "", }, identity, ); - if (own === null || own.host !== key.host || own.repository !== key.repository) { + if ( + identity == null || + own === null || + own.host !== key.host || + own.repository !== key.repository + ) { return yield* new PullRequestOperationError({ operation: "generateReviewGuide", detail: "Guides are written from this project's checkout, and this pull request is in another repository. Write it from a project that is a checkout of that repository.", }); } + return identity.locator; }, ); @@ -148,12 +153,40 @@ const make = Effect.gen(function* () { const checkoutHead = Effect.fn("PullRequestReviewGuideService.checkoutHead")(function* ( workspaceRoot: string, + locator: RepositoryIdentity["locator"], detail: PullRequestDetail, headSha: string, stack: PullRequestStack | null, runId: string, ) { - const remote = yield* git.resolvePrimaryRemoteName(workspaceRoot); + // Identity names can be stale; match effective fetch URLs, including insteadOf rewrites. + const names = yield* git + .execute({ + operation: "PullRequestReviewGuideService.listRemotes", + cwd: workspaceRoot, + args: ["remote"], + }) + .pipe(Effect.map((result) => result.stdout.split("\n").filter((name) => name.length > 0))); + const remote = yield* Effect.findFirst( + [locator.remoteName, ...names.filter((name) => name !== locator.remoteName)], + (name) => + git + .execute({ + operation: "PullRequestReviewGuideService.remoteUrl", + cwd: workspaceRoot, + args: ["remote", "get-url", "--", name], + }) + .pipe( + Effect.map((result) => result.stdout.trim() === locator.remoteUrl), + Effect.orElseSucceed(() => false), + ), + ).pipe(Effect.map(Option.getOrUndefined)); + if (remote === undefined) { + return yield* new PullRequestOperationError({ + operation: "generateReviewGuide", + detail: "This project's checkout no longer has a remote for the pull request's repository.", + }); + } const fetch = (args: ReadonlyArray) => git.execute({ operation: "PullRequestReviewGuideService.fetch", @@ -161,8 +194,7 @@ const make = Effect.gen(function* () { args: ["fetch", "--quiet", "--no-tags", "--", remote, ...args], timeoutMs: 5 * 60_000, }); - // The host names the base branch. A name git rejects, or one that would change the refspec - // (a leading `+`, a `:`), is refused before it reaches `git fetch`. + // Reject invalid branch names and refspec operators before fetching host-provided names. yield* git .execute({ operation: "PullRequestReviewGuideService.checkBaseBranch", @@ -179,8 +211,7 @@ const make = Effect.gen(function* () { }), ), ); - // Fetched into a ref of this run's own: FETCH_HEAD is shared by every fetch in the - // workspace, so a concurrent run could otherwise measure this change from its base. + // FETCH_HEAD is workspace-global; isolate this run's base from concurrent fetches. const baseRef = `refs/t3/review-guide/${runId}/base`; yield* fetch([`+refs/heads/${detail.baseBranch}:${baseRef}`]); yield* Effect.addFinalizer(() => @@ -205,7 +236,7 @@ const make = Effect.gen(function* () { detail: `The host reported a head for #${number} that is not a commit hash.`, }); } - // Not redundant: rev-parse prefers a branch or tag named like a short hash over the commit. + // rev-parse prefers same-named branches/tags over short hashes. const resolveHead = git.resolveCommit({ cwd: workspaceRoot, revision: sha }).pipe( Effect.filterOrFail( ({ commitSha }) => commitSha.startsWith(sha), @@ -217,6 +248,7 @@ const make = Effect.gen(function* () { ), ); const fetchAndResolve = (ref: string) => fetch([ref]).pipe(Effect.andThen(resolveHead)); + const headRef = sourceControlDefinitions.get(detail.provider).changeRequestHeadRef?.(number); const branchRef = `refs/heads/${branch}`; const checkBranch = git.execute({ operation: "PullRequestReviewGuideService.checkHeadBranch", @@ -232,11 +264,7 @@ const make = Effect.gen(function* () { source: `branch ${branch}`, head: checkBranch.pipe(Effect.andThen(fetchAndResolve(branchRef))), }, - { source: `refs/pull/${number}/head`, head: fetchAndResolve(`refs/pull/${number}/head`) }, - { - source: `refs/merge-requests/${number}/head`, - head: fetchAndResolve(`refs/merge-requests/${number}/head`), - }, + ...(headRef === undefined ? [] : [{ source: headRef, head: fetchAndResolve(headRef) }]), ]; const failures: Array = []; for (const { source, head } of sources) { @@ -302,8 +330,7 @@ const make = Effect.gen(function* () { .execute({ operation: "PullRequestReviewGuideService.readChange", cwd, - // Fixed prefixes: a user's diff.noPrefix or custom prefixes would hide the headers the - // parser reads. + // Override user diff prefixes so the parser can find headers. args: [ "-c", "core.quotePath=false", @@ -327,6 +354,7 @@ const make = Effect.gen(function* () { input: PullRequestRef, key: ThreadPullRequestKey, workspaceRoot: string, + locator: RepositoryIdentity["locator"], detail: PullRequestDetail, headSha: string, runId: string, @@ -349,6 +377,7 @@ const make = Effect.gen(function* () { ); const { generated, change } = yield* checkoutHead( workspaceRoot, + locator, detail, headSha, stack, @@ -412,7 +441,7 @@ const make = Effect.gen(function* () { }); } const { key, workspaceRoot, identity } = yield* keyFor(input); - yield* requireOwnRepository(key, identity); + const locator = yield* requireOwnRepository(key, identity); const runKey = keyString(key); yield* pullRequests.invalidate({ reference: input }); const [detail, stored] = yield* Effect.all([pullRequests.detail(input), readStored(key)], { @@ -430,9 +459,7 @@ const make = Effect.gen(function* () { headSha: currentHeadSha, startedAt: yield* nowIso, }; - // Claimed atomically, so two readers pressing Generate start one run between them. The head - // is read again under the claim: a press that read an older head before a push must not - // replace a run another press started for the new one, so it asks to be pressed again. + // Claim atomically and re-read the head so stale clicks cannot replace a newer head's run. const claimed = yield* ownership.withPermits(1)( pullRequests.detail(input).pipe( Effect.flatMap((latest) => @@ -465,7 +492,7 @@ const make = Effect.gen(function* () { return updated; }); const runId = `${runCounter++}`; - yield* write(input, key, workspaceRoot, detail, currentHeadSha, runId, owns).pipe( + yield* write(input, key, workspaceRoot, locator, detail, currentHeadSha, runId, owns).pipe( Effect.andThen(finish(null)), Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 21d947dcced8b..b3984ea105476 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -1,21 +1,15 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as NodeV8 from "node:v8"; -import * as NodeVM from "node:vm"; -import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as KeyValueStore from "effect/persistence/KeyValueStore"; -import { assert, it } from "@effect/vitest"; +import { assert, expect, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; -import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; -import * as Redacted from "effect/Redacted"; import * as Stream from "effect/Stream"; -import { HttpClient, HttpClientResponse } from "effect/http"; import * as TestClock from "effect/testing/TestClock"; import type { OrchestrationProjectShell, @@ -33,15 +27,10 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; +import type { SourceControlProvider } from "@t3tools/source-control-core/server/SourceControlProvider"; +import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli"; -import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider"; -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; -import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials"; -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; -import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider"; -import * as GitHubQuota from "@t3tools/source-control-github/server/GitHubQuota"; -import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import { fakePullRequestProvider } from "@t3tools/source-control-testing/fakeSourceControlDriver"; import { PullRequestProviderError, type ProviderChangeRequest, @@ -50,10 +39,6 @@ import { import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts"; import * as PullRequestService from "./PullRequestService.ts"; import * as PullRequestReadCache from "./PullRequestReadCache.ts"; -import { - FILE_REVISIONS_CACHE_CAPACITY, - MAX_FILE_REVISION_PATHS, -} from "./pullRequestViewedFiles.ts"; function project(input: { readonly id: string; @@ -78,7 +63,7 @@ function project(input: { remoteName: "origin", remoteUrl: input.remoteUrl ?? `https://${host}/${input.repository}.git`, }, - provider: input.provider ?? "github", + provider: SourceControlProviderKind.make(input.provider ?? "github"), displayName: input.repository, }, } @@ -131,237 +116,6 @@ function hostedChangeRequest(body: string, additions = 1) { }; } -it.effect("caches narrow previews and invalidates them after refresh or mutation", () => - Effect.gen(function* () { - let reads = 0; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: () => Effect.die("preview must not read the viewer"), - getChangeRequestPreview: () => - Effect.sync(() => { - reads += 1; - return changeRequest(1, "2026-07-02T00:00:00Z"); - }), - }), - ], - }); - const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const previews = yield* Effect.all([service.preview(ref), service.preview(ref)], { - concurrency: 2, - }); - assert.deepStrictEqual(previews[0], { - ...ref, - title: "Change request 1", - url: "https://host/pull/1", - author: { login: "octocat", name: null, avatarUrl: null }, - state: "open", - isDraft: false, - createdAt: "2026-07-01T00:00:00Z", - }); - assert.strictEqual(reads, 1); - yield* service.invalidate({ reference: ref }); - yield* service.preview(ref); - assert.strictEqual(reads, 2); - yield* service.runAction({ ...ref, action: "close" }); - yield* service.preview(ref); - assert.strictEqual(reads, 3); - yield* service.refreshAfterTurn(ref.projectId); - yield* service.preview(ref); - assert.strictEqual(reads, 4); - const error = yield* Effect.flip(service.preview({ ...ref, repository: "another/repo" })); - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.strictEqual(reads, 4); - }), -); - -it.effect("keeps cached previews available and pauses uncached previews until quota resets", () => - Effect.gen(function* () { - let reads = 0; - const retryAt = Date.parse("2099-08-13T14:00:00Z"); - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestPreview: ({ number }) => - Effect.gen(function* () { - reads++; - if (reads === 2) - return yield* new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getChangeRequestPreview", - reason: "rate-limited", - detail: "GitHub requests are paused until the rate limit resets.", - retryAt, - }); - return changeRequest(number, "2026-07-02T00:00:00Z"); - }), - }), - ], - }); - const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - yield* service.preview(ref); - const limited = yield* Effect.flip(service.preview({ ...ref, number: 2 })); - assert.instanceOf(limited, PullRequestOperationError); - if (limited._tag !== "PullRequestOperationError") return; - assert.include(limited.detail, "paused"); - assert.strictEqual((yield* service.preview(ref)).number, 1); - for (const number of [2, 3, 4]) { - const paused = yield* Effect.flip(service.preview({ ...ref, number })); - assert.instanceOf(paused, PullRequestOperationError); - if (paused._tag !== "PullRequestOperationError") return; - assert.include(paused.detail, "paused"); - } - assert.strictEqual(reads, 2); - yield* TestClock.setTime(retryAt); - assert.strictEqual((yield* service.preview({ ...ref, number: 2 })).number, 2); - assert.strictEqual(reads, 3); - }), -); - -it.effect("reuses only unexpired detail for previews", () => - Effect.gen(function* () { - let previewReads = 0; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => Effect.succeed(hostedChangeRequest("Description")), - getChangeRequestPreview: () => - Effect.sync(() => { - previewReads++; - return { - ...changeRequest(1, "2026-07-02T00:00:00Z"), - title: "Updated title", - state: "closed" as const, - }; - }), - }), - ], - }); - const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - yield* service.detail(ref); - assert.strictEqual((yield* service.preview(ref)).title, "Change request 1"); - assert.strictEqual(previewReads, 0); - yield* TestClock.adjust("61 seconds"); - const preview = yield* service.preview(ref); - assert.strictEqual(preview.title, "Updated title"); - assert.strictEqual(preview.state, "closed"); - assert.strictEqual(previewReads, 1); - }), -); - -it.effect("shares detail and activity for a minute, and for ten once merged", () => - Effect.gen(function* () { - const reads: Array = []; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: ({ number }) => - Effect.sync(() => { - reads.push(`detail #${number}`); - return { - ...hostedChangeRequest("Description"), - number, - state: - number === 1 - ? ("open" as const) - : number === 2 - ? ("merged" as const) - : ("closed" as const), - }; - }), - getChangeRequestActivity: ({ number }) => - Effect.sync(() => { - reads.push(`activity #${number}`); - return { - comments: [], - commentCount: 0, - commentsTruncated: false, - reviewThreads: [], - commits: [], - }; - }), - }), - ], - }); - const reread = Effect.forEach([1, 2, 3], (number) => { - const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number }; - return Effect.andThen(service.detail(ref), service.activity(ref)); - }).pipe( - Effect.andThen(Effect.yieldNow), - Effect.andThen(Effect.sync(() => reads.splice(0).toSorted())), - ); - - const everything = [ - "activity #1", - "activity #2", - "activity #3", - "detail #1", - "detail #2", - "detail #3", - ]; - assert.deepStrictEqual(yield* reread, everything); - yield* TestClock.adjust("59 seconds"); - assert.deepStrictEqual(yield* reread, []); - yield* TestClock.adjust("2 seconds"); - assert.deepStrictEqual(yield* reread, ["activity #1", "activity #3", "detail #1", "detail #3"]); - yield* TestClock.adjust("9 minutes"); - assert.deepStrictEqual(yield* reread, everything); - }), -); - -it.effect("re-reads an open pull request after a turn, but not a merged one", () => - Effect.gen(function* () { - const reads: Array = []; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: ({ number }) => - Effect.sync(() => { - reads.push(`detail #${number}`); - return { - ...hostedChangeRequest("Description"), - number, - state: number === 1 ? ("open" as const) : ("merged" as const), - }; - }), - getChangeRequestActivity: ({ number }) => - Effect.sync(() => { - reads.push(`activity #${number}`); - return { - comments: [], - commentCount: 0, - commentsTruncated: false, - reviewThreads: [], - commits: [], - }; - }), - }), - ], - }); - const merged = { projectId: "p1" as ProjectId, repository: "acme/web", number: 2 }; - const reread = Effect.forEach([1, 2], (number) => { - const ref = { ...merged, number }; - return Effect.andThen(service.detail(ref), service.activity(ref)); - }).pipe( - Effect.andThen(Effect.yieldNow), - Effect.andThen(Effect.sync(() => reads.splice(0).toSorted())), - ); - - assert.deepStrictEqual(yield* reread, ["activity #1", "activity #2", "detail #1", "detail #2"]); - for (let turn = 0; turn < 3; turn++) { - yield* service.refreshAfterTurn(merged.projectId); - assert.deepStrictEqual(yield* reread, ["activity #1", "detail #1"]); - } - yield* service.invalidate({ reference: merged }); - assert.deepStrictEqual(yield* reread, ["activity #2", "detail #2"]); - }), -); - it.effect("does not wait for an in-flight detail read to display a preview", () => Effect.gen(function* () { const detailStarted = yield* Deferred.make(); @@ -369,7 +123,7 @@ it.effect("does not wait for an in-flight detail read to display a preview", () const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequest: () => Deferred.succeed(detailStarted, undefined).pipe( Effect.andThen(Deferred.await(releaseDetail)), @@ -388,68 +142,6 @@ it.effect("does not wait for an in-flight detail read to display a preview", () }), ); -it.effect("keeps previews warm when another project finishes a turn", () => - Effect.gen(function* () { - const reads: string[] = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" }), - project({ id: "p2", title: "docs", workspaceRoot: "/d", repository: "acme/docs" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestPreview: (input) => - Effect.sync(() => { - reads.push(input.repository); - return changeRequest(1, "2026-07-02T00:00:00Z"); - }), - }), - ], - }); - const web = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const docs = { projectId: "p2" as ProjectId, repository: "acme/docs", number: 1 }; - yield* service.preview(web); - yield* service.preview(docs); - yield* service.preview({ ...web, host: "github.com" }); - assert.deepStrictEqual(reads, ["acme/web", "acme/docs"]); - yield* service.refreshAfterTurn(web.projectId); - yield* service.preview(web); - yield* service.preview(docs); - assert.deepStrictEqual(reads, ["acme/web", "acme/docs", "acme/web"]); - }), -); - -it.effect("uses full detail for hosts without a narrow preview", () => - Effect.gen(function* () { - let reads = 0; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "web", - workspaceRoot: "/w", - repository: "acme/web", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - getChangeRequest: () => - Effect.sync(() => { - reads += 1; - return hostedChangeRequest("Description"); - }), - }), - ], - }); - const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const preview = yield* service.preview(ref); - assert.strictEqual(preview.title, "Change request 1"); - assert.strictEqual(reads, 1); - assert.ok(!("body" in preview)); - }), -); - function unusable(provider: SourceControlProviderKind, reason: "missing-tool" | "unauthenticated") { return new PullRequestProviderError({ provider, @@ -475,53 +167,30 @@ const FULL_REVIEW: PullRequestReviewCapabilities = { const FULL_REVIEWERS: PullRequestReviewerCapabilities = { request: true, listCandidates: true }; -function fakeProvider( - kind: SourceControlProviderKind, - overrides: Partial = {}, -): PullRequestProviderApi { - return { - kind, - capabilities: { - diff: true, - comment: true, - actions: ["merge", "ready", "draft", "close", "reopen"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - edit: { changeRequest: true, comment: true }, - }, - getViewer: () => Effect.succeed("bilal"), - getViewerPermissions: () => - Effect.succeed({ - actions: ["merge", "ready", "draft", "close", "reopen"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }), - listChangeRequests: () => Effect.succeed({ items: [], truncated: false, continues: true }), - getChangeRequest: () => Effect.die("unused"), - getChangeRequestActivity: () => Effect.die("unused"), - getDiff: () => Effect.die("unused"), - runAction: () => Effect.void, - updateChangeRequest: () => Effect.void, - comment: () => Effect.void, - updateComment: () => Effect.void, - submitReview: () => Effect.void, - replyToThread: () => Effect.void, - setThreadResolution: () => Effect.void, - setReaction: () => Effect.void, - listReviewerCandidates: () => Effect.succeed({ candidates: [], truncated: false }), - setReviewerRequest: () => Effect.void, - ...(kind === "github" ? { mergeMessageRewrite: (message: string) => message } : {}), - ...(kind === "azure-devops" - ? { repositoryKey: ({ canonicalKey }: { readonly canonicalKey: string }) => canonicalKey } - : {}), - ...overrides, - }; -} +// Like Azure DevOps, whose repository names repeat across organizations and projects. +const keyedByCanonicalKey = { + repositoryKey: ({ canonicalKey }: { readonly canonicalKey: string }) => canonicalKey, +}; + +/** A host whose SSH remotes name an alias, so discovery says which server serves them. */ +const sshAliasHost = { + resolveRemoteWebHost: ({ cwd, context, resolveContext }) => + isSshRemoteUrl(context.remoteUrl) + ? resolveContext({ + cwd, + context: { + ...context, + provider: { kind: SourceControlProviderKind.make("unknown"), name: "", baseUrl: "" }, + }, + }).pipe( + Effect.map((resolved) => + resolved === null || resolved.provider.kind === "unknown" + ? null + : new URL(resolved.provider.baseUrl).host, + ), + ) + : Effect.succeed(null), +} as SourceControlProvider["Service"]; function makeService(input: { readonly settings?: ServerSettings; @@ -530,8 +199,7 @@ function makeService(input: { readonly resolveHandle?: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"]["resolveHandle"]; readonly resolveRepositoryIdentity?: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"]["resolve"]; }) { - // Built into the test's own scope rather than provided call by call: the marks store owns a - // database, and `Effect.provide` would close it the moment the service was handed back. + // Build in the test scope; per-call Effect.provide would close the marks database on service acquisition. return Effect.flatMap( Layer.build( Layer.mergeAll( @@ -546,6 +214,10 @@ function makeService(input: { resolveLink: () => undefined, resolveHandle: input.resolveHandle ?? (() => Effect.die("Unexpected provider refinement")), + get: (kind) => + Effect.succeed( + kind === "forgejo" ? sshAliasHost : ({} as SourceControlProvider["Service"]), + ), }), Layer.mock(ProjectService.ProjectService)({ listShells: (options) => @@ -584,7 +256,7 @@ it.effect("lists GitHub Enterprise PRs for a stored unknown repository after hos }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ host, repository }) => { assert.strictEqual(host, "code.example.test"); assert.strictEqual(repository, "team/project"); @@ -619,73 +291,6 @@ it.effect("lists GitHub Enterprise PRs for a stored unknown repository after hos }), ); -it.effect("reports each host's actions with its summary, so rows can offer them unread", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "web", - workspaceRoot: "/repo", - repository: "acme/web", - provider: SourceControlProviderKind.make("bitbucket"), - host: "bitbucket.org", - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("bitbucket"), { - capabilities: { - ...fakeProvider(SourceControlProviderKind.make("bitbucket")).capabilities, - actions: ["merge", "close"], - }, - }), - ], - }); - - const result = yield* service.list({ state: "open" }); - - assert.deepStrictEqual(result.providers[0]?.actions, ["merge", "close"]); - }), -); - -it.effect("refines unknown self-hosted GitLab projects before listing merge requests", () => - Effect.gen(function* () { - let refinementCalls = 0; - const selfHosted = project({ - id: "p1", - title: "self-hosted", - workspaceRoot: "/gitlab", - repository: "group/project", - provider: SourceControlProviderKind.make("unknown"), - host: "code.example.test", - }); - const service = yield* makeService({ - projects: [ - selfHosted, - { ...selfHosted, id: "p2" as ProjectId, workspaceRoot: "/gitlab-worktree" }, - ], - providers: [fakeProvider(SourceControlProviderKind.make("gitlab"))], - resolveHandle: ({ context }) => { - refinementCalls += 1; - assert.strictEqual(context?.remoteUrl, "https://code.example.test/group/project.git"); - return Effect.succeed({ - context: { - ...context!, - provider: { ...context!.provider, kind: SourceControlProviderKind.make("gitlab") }, - }, - provider: undefined as never, - }); - }, - }); - - const result = yield* service.list({ state: "open" }); - - assert.strictEqual(refinementCalls, 1); - assert.strictEqual(result.providers[0]?.host, "code.example.test"); - assert.strictEqual(result.providers[0]?.kind, "gitlab"); - }), -); - it.effect("derives a legacy repository host after refining its provider", () => Effect.gen(function* () { const current = project({ @@ -707,7 +312,7 @@ it.effect("derives a legacy repository host after refining its provider", () => } as unknown as OrchestrationProjectShell; const service = yield* makeService({ projects: [legacy], - providers: [fakeProvider(SourceControlProviderKind.make("gitlab"))], + providers: [fakePullRequestProvider(SourceControlProviderKind.make("gitlab"))], resolveHandle: ({ context }) => Effect.succeed({ context: { @@ -738,7 +343,7 @@ it.effect("tries another checkout when provider refinement remains unknown", () }); const service = yield* makeService({ projects: [selfHosted, { ...selfHosted, id: "p2" as ProjectId, workspaceRoot: "/healthy" }], - providers: [fakeProvider(SourceControlProviderKind.make("gitlab"))], + providers: [fakePullRequestProvider(SourceControlProviderKind.make("gitlab"))], resolveHandle: ({ cwd, context }) => { asked.push(cwd); return cwd === "/gone" @@ -780,7 +385,7 @@ it.effect("reads nothing from a host with no implementation, but reports it", () }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: (input) => { listed.push(input.repository); return Effect.succeed({ @@ -811,30 +416,6 @@ it.effect("reads nothing from a host with no implementation, but reports it", () }), ); -it.effect("asks for a whole page of a host, and for the reader's own size when given one", () => - Effect.gen(function* () { - const limits: number[] = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: (input) => { - limits.push(input.limit); - return Effect.succeed({ items: [], truncated: false, continues: true }); - }, - }), - ], - }); - - yield* service.list({ state: "open" }); - yield* service.list({ state: "open", limit: 10 }); - - assert.deepStrictEqual(limits, [99, 10]); - }), -); - it.effect("says where each repository carries on, and from nothing it has run out of", () => Effect.gen(function* () { const service = yield* makeService({ @@ -843,7 +424,7 @@ it.effect("says where each repository carries on, and from nothing it has run ou project({ id: "p2", title: "web", workspaceRoot: "/b", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ repository }) => Effect.succeed({ items: [changeRequest(1, "2026-07-02T00:00:00Z")], @@ -862,31 +443,6 @@ it.effect("says where each repository carries on, and from nothing it has run ou }), ); -it.effect("offers no continuation for a host that cannot be carried on from", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: true, - continues: false, - }), - }), - ], - }); - - const result = yield* service.list({ state: "open" }); - - assert.isTrue(result.truncated); - assert.deepStrictEqual(result.nextCursors, {}); - }), -); - it.effect("uses a provider's raw cursor advance when it consumed malformed rows", () => Effect.gen(function* () { const service = yield* makeService({ @@ -901,7 +457,8 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + ...keyedByCanonicalKey, listChangeRequests: () => Effect.succeed({ items: [changeRequest(7, "2026-07-02T00:00:00Z")], @@ -921,35 +478,63 @@ it.effect("uses a provider's raw cursor advance when it consumed malformed rows" }), ); -it.effect("reads only the repositories it was asked to carry on with", () => - Effect.gen(function* () { - const listed: string[] = []; - const cursors: Array = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - project({ id: "p2", title: "web", workspaceRoot: "/b", repository: "acme/web" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: (input) => { - listed.push(input.repository); - cursors.push(input.cursor); - return Effect.succeed({ items: [], truncated: false, continues: true }); - }, - }), - ], - }); - - const result = yield* service.list({ - state: "open", - cursors: { "github.com acme/web": "2026-07-02T00:00:00Z|99|7" }, - }); - - assert.deepStrictEqual(listed, ["acme/web"]); - assert.deepStrictEqual(cursors, [{ updatedBefore: "2026-07-02T00:00:00Z", delivered: 99 }]); - assert.strictEqual(result.providers.length, 1); - }), +it.effect( + "continues a timestamp-paged host's listings through tied timestamps and terminates", + () => + Effect.gen(function* () { + const boundary = "2026-10-12T00:00:00.000Z"; + const older = "2026-10-11T00:00:00.000Z"; + const rows = [1, 2, 3, 4, 5].map((number) => + changeRequest(number, number <= 3 ? boundary : older), + ); + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "web", + workspaceRoot: "/w", + repository: "acme/web", + provider: "bitbucket", + host: "bitbucket.org", + }), + ], + providers: [ + // Pages the way Bitbucket does: inclusively by update time, excluding rows already sent. + fakePullRequestProvider(SourceControlProviderKind.make("bitbucket"), { + listChangeRequests: ({ cursor, limit }) => + Effect.sync(() => { + const seen = new Set(cursor?.seenAt ?? []); + const matching = rows.filter( + (row) => + (cursor === undefined || row.updatedAt <= cursor.updatedBefore) && + !seen.has(row.number), + ); + return { + items: matching.slice(0, limit), + truncated: matching.length > limit, + continues: true, + }; + }), + }), + ], + }); + let page = yield* service.list({ state: "open", limit: 2 }); + assert.deepStrictEqual( + page.entries.map((entry) => entry.number), + [1, 2], + ); + for (const expected of [[3, 4], [5]]) { + assert.isTrue(page.truncated); + assert.isNotEmpty(page.nextCursors); + page = yield* service.list({ state: "open", limit: 2, cursors: page.nextCursors }); + assert.deepStrictEqual( + page.entries.map((entry) => entry.number), + expected, + ); + } + assert.isFalse(page.truncated); + assert.deepStrictEqual(page.nextCursors, {}); + }), ); it.effect("keeps a row already sent at the boundary instant from arriving twice", () => @@ -959,7 +544,7 @@ it.effect("keeps a row already sent at the boundary instant from arriving twice" project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: () => Effect.succeed({ items: [ @@ -996,7 +581,7 @@ it.effect("keeps the earlier exclusions when a slice ends on the instant it bega project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: () => Effect.succeed({ items: [ @@ -1025,31 +610,6 @@ it.effect("keeps the earlier exclusions when a slice ends on the instant it bega }), ); -it.effect("refuses a continuation it did not issue, before asking any host anything", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => Effect.die("should not be read"), - }), - ], - }); - - const error = yield* Effect.flip( - service.list({ state: "open", cursors: { "github.com pingdotgg/t3code": "yesterday" } }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.strictEqual( - error.message, - "Pull request operation list failed: The list could not be carried on from where it left off.", - ); - }), -); - it.effect("calls a transient viewer failure a failed operation, not a signed-out CLI", () => Effect.gen(function* () { const service = yield* makeService({ @@ -1057,7 +617,7 @@ it.effect("calls a transient viewer failure a failed operation, not a signed-out project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getViewer: () => Effect.fail( new PullRequestProviderError({ @@ -1091,7 +651,7 @@ it.effect("reports an unusable host over a merely failing one", () => }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getViewer: () => Effect.fail( new PullRequestProviderError({ @@ -1102,7 +662,11 @@ it.effect("reports an unusable host over a merely failing one", () => }), ), }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + unavailableRequirement: { + missing: "Install glab.", + unauthenticated: "Run glab auth login.", + }, getViewer: () => Effect.fail(unusable(SourceControlProviderKind.make("gitlab"), "missing-tool")), }), @@ -1112,91 +676,10 @@ it.effect("reports an unusable host over a merely failing one", () => const error = yield* Effect.flip(service.list({ state: "open" })); assert.strictEqual(error._tag, "PullRequestUnavailableError"); - assert.strictEqual(error.message.includes("glab"), true); - }), -); - -it.effect("lists every host that has an implementation", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - project({ - id: "p2", - title: "on gitlab", - workspaceRoot: "/b", - repository: "group/sub/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(1, "2026-07-01T00:00:00Z")], - truncated: false, - continues: true, - }), - }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { - listChangeRequests: (input) => - input.repository === "group/sub/project" - ? Effect.succeed({ - items: [changeRequest(2, "2026-07-05T00:00:00Z")], - truncated: false, - continues: true, - }) - : Effect.die("wrong repository identity"), - }), - ], - }); - - const result = yield* service.list({ state: "open" }); - - assert.deepStrictEqual( - result.entries.map((entry) => [entry.provider, entry.number]), - [ - ["gitlab", 2], - ["github", 1], - ], - ); - }), -); - -it.effect("narrows the listing to one host when asked", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - project({ - id: "p2", - title: "on gitlab", - workspaceRoot: "/b", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => Effect.die("should not be read"), - }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(2, "2026-07-05T00:00:00Z")], - truncated: false, - continues: true, - }), - }), - ], - }); - - const result = yield* service.list({ state: "open", host: "gitlab.com" }); - - assert.deepStrictEqual( - result.entries.map((entry) => entry.provider), - ["gitlab"], - ); + if (error._tag === "PullRequestUnavailableError") { + assert.strictEqual(error.requirement, "Install glab."); + } + assert.strictEqual(error.message, "Install glab."); }), ); @@ -1214,7 +697,7 @@ it.effect("tells two hosts of one kind apart in the switcher and the filter", () }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ host }) => Effect.succeed({ items: host === "ghe.example.com" ? [changeRequest(2, "2026-07-05T00:00:00Z")] : [], @@ -1242,137 +725,165 @@ it.effect("tells two hosts of one kind apart in the switcher and the filter", () }), ); -it.effect("keeps one host listed when another is not set up", () => +it.effect("reads a repository once when several worktrees share it", () => Effect.gen(function* () { + let calls = 0; const service = yield* makeService({ projects: [ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), project({ id: "p2", - title: "on gitlab", + title: "t3code worktree", workspaceRoot: "/b", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), + repository: "PingDotGG/T3Code", }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(1, "2026-07-01T00:00:00Z")], + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + listChangeRequests: () => { + calls += 1; + return Effect.succeed({ + items: [changeRequest(1, "2026-07-02T00:00:00Z")], truncated: false, continues: true, - }), - }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { - getViewer: () => - Effect.fail(unusable(SourceControlProviderKind.make("gitlab"), "missing-tool")), + }); + }, }), ], }); const result = yield* service.list({ state: "open" }); - assert.deepStrictEqual( - result.entries.map((entry) => entry.provider), - ["github"], - ); - assert.deepStrictEqual( - result.providers.map((summary) => [summary.kind, summary.configured]), - [ - ["github", true], - ["gitlab", false], - ], - ); + assert.strictEqual(calls, 1); + assert.strictEqual(result.entries.length, 1); }), ); -it.effect("fails as unavailable only when no host can be read", () => +it.effect("keeps healthy repositories when one of them cannot be read", () => Effect.gen(function* () { const service = yield* makeService({ projects: [ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), + project({ id: "p2", title: "broken", workspaceRoot: "/b", repository: "pingdotgg/broken" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: () => - Effect.fail(unusable(SourceControlProviderKind.make("github"), "missing-tool")), + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + listChangeRequests: (input) => + input.repository === "pingdotgg/broken" + ? Effect.fail(requestFailed) + : Effect.succeed({ + items: [changeRequest(1, "2026-07-02T00:00:00Z")], + truncated: false, + continues: true, + }), }), ], }); - const error = yield* service.list({ state: "open" }).pipe(Effect.flip); + const result = yield* service.list({ state: "open" }); - assert.strictEqual(error._tag, "PullRequestUnavailableError"); - assert.strictEqual( - error._tag === "PullRequestUnavailableError" ? error.reason : null, - "cli-missing", + assert.strictEqual(result.entries.length, 1); + assert.deepStrictEqual( + result.errors.map((error) => error.projectTitle), + ["broken"], ); }), ); -it.effect("reads a repository once when several worktrees share it", () => +it.effect("offers each label once across repositories, despite one that cannot be read", () => Effect.gen(function* () { - let calls = 0; + const reads: Array = []; const service = yield* makeService({ projects: [ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), project({ - id: "p2", + id: "p5", title: "t3code worktree", + workspaceRoot: "/e", + repository: "pingdotgg/t3code", + }), + project({ + id: "p2", + title: "uploadthing", workspaceRoot: "/b", - repository: "PingDotGG/T3Code", + repository: "pingdotgg/ut", + }), + project({ id: "p3", title: "broken", workspaceRoot: "/c", repository: "pingdotgg/broken" }), + project({ + id: "p4", + title: "elsewhere", + workspaceRoot: "/d", + repository: "group/app", + provider: "gitlab", }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => { - calls += 1; - return Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: false, - continues: true, - }); + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + listRepositoryLabels: (input) => { + reads.push(input.repository); + return input.repository === "pingdotgg/broken" + ? Effect.fail(requestFailed) + : Effect.succeed({ + items: + input.repository === "pingdotgg/t3code" + ? [ + { name: "size:XL", color: "d93f0b" }, + { name: "bug", color: "d73a4a" }, + ] + : [{ name: "Bug", color: "ee0701" }], + truncated: false, + }); }, }), + // A host with no repository labels is left out rather than failing the answer. + fakePullRequestProvider(SourceControlProviderKind.make("gitlab")), ], }); - const result = yield* service.list({ state: "open" }); + const result = yield* service.filterOptions({ kind: "labels" }); - assert.strictEqual(calls, 1); - assert.strictEqual(result.entries.length, 1); + assert.deepStrictEqual( + result.labels.map((label) => label.name), + ["bug", "size:XL"], + ); + assert.strictEqual(reads.filter((repository) => repository === "pingdotgg/t3code").length, 1); + assert.strictEqual(result.truncated, false); }), ); -it.effect("keeps healthy repositories when one of them cannot be read", () => +it.effect("puts the author a query names exactly ahead of those it only begins", () => Effect.gen(function* () { + const queries: Array = []; const service = yield* makeService({ projects: [ project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - project({ id: "p2", title: "broken", workspaceRoot: "/b", repository: "pingdotgg/broken" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: (input) => - input.repository === "pingdotgg/broken" - ? Effect.fail(requestFailed) - : Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: false, - continues: true, - }), + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + searchRepositoryAuthors: (input) => { + queries.push(input.query); + return Effect.succeed({ + items: [ + { login: "theo-browne", name: null, avatarUrl: null }, + { login: "octocat", name: "Theo", avatarUrl: null }, + { login: "julius", name: "Julius", avatarUrl: null }, + { login: "t3dotgg", name: "theo", avatarUrl: null }, + ], + truncated: true, + }); + }, }), ], }); - const result = yield* service.list({ state: "open" }); + const result = yield* service.filterOptions({ kind: "authors", query: "theo" }); - assert.strictEqual(result.entries.length, 1); + assert.deepStrictEqual(queries, ["theo"]); assert.deepStrictEqual( - result.errors.map((error) => error.projectTitle), - ["broken"], + result.authors.map((author) => author.login), + ["octocat", "t3dotgg", "theo-browne"], ); + assert.strictEqual(result.truncated, true); }), ); @@ -1384,7 +895,7 @@ it.effect("tries another workspace on the same host for the viewer", () => project({ id: "p2", title: "healthy", workspaceRoot: "/healthy", repository: "acme/two" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getViewer: (input) => input.cwd === "/healthy" ? Effect.succeed("bilal") @@ -1420,7 +931,7 @@ it.effect("routing verifies the current account on the requested host without ca }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getRoutingIdentity: (input) => { assert.deepStrictEqual(input, { cwd: "/a", host: "github.example.test" }); return Effect.succeed({ @@ -1457,7 +968,7 @@ it.effect("refuses an action the host never claimed it could run", () => const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { capabilities: { diff: true, comment: true, @@ -1490,6 +1001,41 @@ it.effect("refuses an action the host never claimed it could run", () => }), ); +it.effect( + "asks to remove agent credits on merge only from a host that rewrites merge messages", + () => + Effect.gen(function* () { + const asked: Array = []; + const runAction: PullRequestProviderApi["runAction"] = (input) => + Effect.sync(() => { + asked.push(input.removeAgentCreditsOnMerge); + }); + for (const rewrites of [true, false]) { + const service = yield* makeService({ + settings: { ...DEFAULT_SERVER_SETTINGS, removeAgentCreditsOnMerge: true }, + projects: [ + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + runAction, + getChangeRequestSummary: () => + Effect.succeed(changeRequest(1, "2026-09-03T00:00:00Z")), + ...(rewrites ? { mergeMessageRewrite: (message: string) => message } : {}), + }), + ], + }); + yield* service.runAction({ + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + action: "merge", + }); + } + assert.deepStrictEqual(asked, [true, undefined]); + }), +); + it.effect("publishes a merge for immediate settlement only after host confirmation", () => Effect.scoped( Effect.gen(function* () { @@ -1502,7 +1048,7 @@ it.effect("publishes a merge for immediate settlement only after host confirmati project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: () => confirmationFails ? Effect.fail( @@ -1559,7 +1105,7 @@ it.effect("refreshes every reader before a queued merge confirmation finishes", project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: () => Effect.gen(function* () { yield* Deferred.succeed(confirmationStarted, undefined); @@ -1600,7 +1146,7 @@ it.effect("runs branch deletion only when the host and viewer support it, never let actions = 0; let supported = false; let allowed = true; - const base = fakeProvider(SourceControlProviderKind.make("github")); + const base = fakePullRequestProvider(SourceControlProviderKind.make("github")); const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ @@ -1665,108 +1211,41 @@ it.effect("runs branch deletion only when the host and viewer support it, never }), ); -it.effect("keeps branch deletion on the credential that passed source repository permissions", () => +it.effect("checks and deletes a branch inside one verified credential", () => Effect.gen(function* () { - let activeToken = "account-a"; - const requests: Array<{ operation: string; authorization: string | undefined }> = []; - const credentials = Layer.succeed( - GitHubCredentials.GitHubCredentials, - GitHubCredentials.GitHubCredentials.of({ - get: (host) => - Effect.sync(() => ({ - host, - token: Redacted.make(activeToken), - source: "gh" as const, - fingerprint: `${host}:${activeToken}`, - })), - invalidate: () => Effect.void, - }), - ); - const http = Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => - Effect.sync(() => { - const operation = request.url.endsWith("/user") - ? "user" - : request.body._tag === "Uint8Array" - ? new TextDecoder().decode(request.body.body) - : ""; - requests.push({ operation, authorization: request.headers["authorization"] }); - let body; - if (operation === "user") { - body = { id: activeToken === "account-a" ? 101 : 202, login: activeToken }; - } else if (operation.includes("query PullRequestBranchToDelete")) { - body = { - data: { - repository: { - pullRequest: { - state: "MERGED", - headRefName: "feature", - baseRefName: "main", - headRefOid: "abc123", - headRepository: { id: "FORK_REPO" }, - }, - }, - }, - }; - } else if (operation.includes("query PullRequestSourceBranch")) { - body = { - data: { - node: { - __typename: "Repository", - defaultBranchRef: { name: "main" }, - ref: { target: { __typename: "Commit", oid: "abc123" } }, - }, - }, - }; - } else if (operation.includes("updateRefs(")) { - body = { data: { updateRefs: { clientMutationId: null } } }; - } else { - activeToken = "account-b"; - body = { - data: { - repository: { - mergeCommitAllowed: true, - squashMergeAllowed: true, - rebaseMergeAllowed: true, - viewerPermission: "READ", - pullRequest: { - viewerCanUpdate: false, - viewerDidAuthor: false, - headRepository: { viewerPermission: "WRITE" }, - }, - }, - }, - }; - } - return HttpClientResponse.fromWeb( - request, - new Response(JSON.stringify(body), { - headers: { "content-type": "application/json" }, - }), - ); - }), - ), - ); - const provider = yield* GitHubPullRequestProvider.make.pipe( - Effect.provide( - GitHubPullRequestApi.layer.pipe( - // GraphQL reads go over `http` too, through the same credential and quota as REST. - Layer.provide( - GitHubRest.layer.pipe( - Layer.provideMerge(Layer.mergeAll(credentials, http)), - Layer.provideMerge(GitHubQuota.layer), - Layer.provideMerge(SourceControlRateLimit.layer), - ), - ), - Layer.provide(TestSourceControlHost.layer()), - Layer.provide(NodeServices.layer), - ), - ), - ); + let pinned = false; + const calls: Array = []; const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [provider], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + capabilities: { + ...fakePullRequestProvider("github").capabilities, + actions: ["delete-branch"], + deleteBranch: true, + }, + withVerifiedCredential: (_, use) => + Effect.suspend(() => { + pinned = true; + return use({ accountId: "101", viewer: "bilal", credentialFingerprint: "a" }); + }).pipe(Effect.ensuring(Effect.sync(() => (pinned = false)))), + getViewerPermissions: () => + Effect.sync(() => { + calls.push(`permissions pinned=${pinned}`); + return { + actions: ["delete-branch"], + comment: true, + resolve: true, + verdicts: [], + requestReviewers: false, + }; + }), + runAction: (input) => + Effect.sync(() => { + calls.push(`${input.action} pinned=${pinned}`); + }), + }), + ], }); yield* service.runAction({ projectId: "p1" as ProjectId, @@ -1774,21 +1253,7 @@ it.effect("keeps branch deletion on the credential that passed source repository number: 1, action: "delete-branch", }); - assert.strictEqual(activeToken, "account-b"); - assert.strictEqual( - requests.filter(({ operation }) => operation.includes("updateRefs(")).length, - 1, - ); - assert.deepStrictEqual( - requests.map(({ authorization }) => authorization), - [ - "Bearer account-a", - "Bearer account-a", - "Bearer account-a", - "Bearer account-a", - "Bearer account-a", - ], - ); + assert.deepStrictEqual(calls, ["permissions pinned=true", "delete-branch pinned=true"]); }), ); @@ -1798,7 +1263,7 @@ it.effect("refuses an action this viewer may not take, and says what access it t const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getViewerPermissions: () => Effect.succeed({ actions: ["ready", "draft", "close", "reopen"], @@ -1832,7 +1297,7 @@ it.effect("gates arming a merge for later exactly as it gates merging now", () = const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { capabilities: { diff: true, comment: true, @@ -1867,7 +1332,7 @@ it.effect("gates arming a merge for later exactly as it gates merging now", () = service.runAction({ ...reference, action: "enable-auto-merge", mergeMethod: "squash" }), ); assert.strictEqual(refused._tag, "PullRequestOperationError"); - assert.include(refused.message, "merged for you once it is ready"); + assert.include(refused.message, "the repository has to allow it"); assert.strictEqual(ranWith, null); const wrongStrategy = yield* Effect.flip( @@ -1878,191 +1343,6 @@ it.effect("gates arming a merge for later exactly as it gates merging now", () = }), ); -it.effect("hands the host the strategy an armed merge was asked for", () => - Effect.gen(function* () { - let ranWith: { readonly action: string; readonly mergeMethod?: string } | null = null; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge", "enable-auto-merge", "disable-auto-merge"], - mergeMethods: ["merge", "squash"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getViewerPermissions: () => - Effect.succeed({ - actions: ["merge", "enable-auto-merge", "disable-auto-merge"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }), - runAction: (input) => { - ranWith = { - action: input.action, - ...(input.mergeMethod === undefined ? {} : { mergeMethod: input.mergeMethod }), - }; - return Effect.void; - }, - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - - yield* service.runAction({ ...reference, action: "enable-auto-merge", mergeMethod: "squash" }); - assert.deepStrictEqual(ranWith, { action: "enable-auto-merge", mergeMethod: "squash" }); - - yield* service.runAction({ ...reference, action: "disable-auto-merge" }); - assert.deepStrictEqual(ranWith, { action: "disable-auto-merge" }); - }), -); - -it.effect("refuses an auto-merge the host never claimed, without asking it", () => - Effect.gen(function* () { - let ran = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - runAction: () => { - ran = true; - return Effect.void; - }, - }), - ], - }); - - const error = yield* Effect.flip( - service.runAction({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - action: "enable-auto-merge", - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.isFalse(ran); - }), -); - -it.effect("refuses to resolve a conversation this viewer may not, without asking the host", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewerPermissions: () => - Effect.succeed({ - actions: ["merge", "ready", "draft", "close", "reopen"], - comment: true, - resolve: false, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }), - setThreadResolution: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.setThreadResolution({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - threadId: "t1", - resolved: true, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.include(error.message, "to resolve a review conversation."); - }), -); - -it.effect("asks nobody what the viewer may do when the host cannot do it at all", () => - Effect.gen(function* () { - let asked = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge", "close"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getViewerPermissions: () => { - asked = true; - return Effect.die("must not be called"); - }, - }), - ], - }); - - yield* Effect.flip( - service.runAction({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - action: "reopen", - }), - ); - - assert.isFalse(asked); - }), -); - -it.effect("refuses a comment on a host that cannot post one", () => - Effect.gen(function* () { - let posted = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: false, - comment: false, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - comment: () => { - posted = true; - return Effect.void; - }, - }), - ], - }); - - const error = yield* Effect.flip( - service.comment({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - body: "Looks good.", - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.isFalse(posted); - }), -); - it.effect("keeps two hosts of one provider kind as two accounts", () => Effect.gen(function* () { const viewerFor: Record = { "/cloud": "bilal", "/enterprise": "b.hassan" }; @@ -2078,7 +1358,7 @@ it.effect("keeps two hosts of one provider kind as two accounts", () => }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getViewer: (input) => Effect.succeed(viewerFor[input.cwd] ?? "unknown"), listChangeRequests: () => Effect.succeed({ @@ -2104,45 +1384,6 @@ it.effect("keeps two hosts of one provider kind as two accounts", () => }), ); -it.effect("reports repositories on a host that could not be read", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }), - project({ - id: "p2", - title: "enterprise", - workspaceRoot: "/enterprise", - repository: "acme/api", - host: "github.acme.dev", - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: (input) => - input.cwd === "/cloud" - ? Effect.succeed("bilal") - : Effect.fail(unusable(SourceControlProviderKind.make("github"), "unauthenticated")), - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: false, - continues: true, - }), - }), - ], - }); - - const result = yield* service.list({ state: "open" }); - - assert.strictEqual(result.entries.length, 1); - assert.deepStrictEqual( - result.errors.map((error) => error.projectId), - ["p2"], - ); - }), -); - it.effect("stops new reads after a rate limit while leaving manual actions available", () => Effect.gen(function* () { let listCalls = 0; @@ -2152,7 +1393,7 @@ it.effect("stops new reads after a rate limit while leaving manual actions avail project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: () => Effect.sync(() => { listCalls += 1; @@ -2192,272 +1433,33 @@ it.effect("stops new reads after a rate limit while leaving manual actions avail }), ); -for (const [providerName, host] of [ +for (const [] of [ ["github", "github.com"], ["gitlab", "gitlab.com"], ["forgejo", "code.example.test"], ["bitbucket", "bitbucket.org"], ["azure-devops", "dev.azure.com"], ] as const) { - const provider = SourceControlProviderKind.make(providerName); - it.effect.each(["detail", "checks"] as const)( - `shares fresh ${provider} %s reads and respects rate-limit resets`, - (read) => - Effect.gen(function* () { - let calls = 0; - let limited = false; - const repository = provider === "azure-devops" ? "web" : "acme/web"; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/repo", repository, provider, host }), - ], - providers: [ - fakeProvider(provider, { - [read === "detail" ? "getChangeRequest" : "getChangeRequestChecks"]: () => - Effect.gen(function* () { - calls += 1; - if (limited) { - return yield* new PullRequestProviderError({ - provider, - operation: "getChangeRequest", - reason: "rate-limited", - detail: "Retry after the reset.", - retryAt: (yield* Clock.currentTimeMillis) + 120_000, - }); - } - return hostedChangeRequest("current details"); - }), - }), - ], - }); - const reference = { - projectId: "p1" as ProjectId, - repository, - number: 1, - allowStale: false, - }; - const request: Effect.Effect = - service[read](reference); - yield* Effect.all([request, request], { concurrency: 2 }); - assert.strictEqual(calls, 1); - yield* TestClock.adjust("61 seconds"); - limited = true; - assert.strictEqual((yield* Effect.exit(request))._tag, "Failure"); - assert.strictEqual(calls, 2); - yield* TestClock.adjust("45 seconds"); - assert.strictEqual((yield* Effect.exit(request))._tag, "Failure"); - assert.strictEqual(calls, 2); - yield* TestClock.adjust("75 seconds"); - limited = false; - const recovered = yield* service[read](reference); - assert.strictEqual(recovered?.state, "open"); - assert.strictEqual(calls, 3); - yield* service.invalidate({ reference }); - yield* service[read](reference); - assert.strictEqual(calls, 4); - }), - ); } -it.effect("does not fall back to full detail when checks are unsupported", () => +it.effect("refuses a repository that does not belong to the requested project", () => Effect.gen(function* () { const service = yield* makeService({ projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/repo", repository: "acme/web" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => Effect.die("Unexpected full detail read"), - }), + project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), ], + providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"))], }); - assert.isNull( - yield* service.checks({ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }), - ); + + const error = yield* service + .diff({ projectId: "p1" as ProjectId, repository: "attacker/repo", number: 1 }) + .pipe(Effect.flip); + + assert.strictEqual(error._tag, "PullRequestOperationError"); }), ); -it.effect("uses a manual rate limit to pause later reads", () => - Effect.gen(function* () { - let listCalls = 0; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "cloud", workspaceRoot: "/cloud", repository: "acme/web" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => - Effect.sync(() => { - listCalls += 1; - return { items: [], truncated: false, continues: true }; - }), - runAction: () => - Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "runAction", - reason: "rate-limited", - detail: "GitHub API rate limit exceeded.", - }), - ), - }), - ], - }); - - yield* Effect.flip( - service.runAction({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - action: "close", - }), - ); - const error = yield* Effect.flip(service.list({ state: "open", involvement: "all" })); - - assert.strictEqual(listCalls, 0); - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("flags a review request for the viewer but not on their own change request", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => - Effect.succeed({ - items: [ - { ...changeRequest(1, "2026-07-02T00:00:00Z"), reviewRequestLogins: ["Bilal"] }, - { - ...changeRequest(2, "2026-07-02T00:00:00Z"), - author: { login: "bilal", name: null, avatarUrl: null }, - reviewRequestLogins: ["bilal"], - }, - ], - truncated: false, - continues: true, - }), - }), - ], - }); - - const result = yield* service.list({ state: "open" }); - - assert.deepStrictEqual( - result.entries.map((entry) => entry.viewerReviewRequested), - [true, false], - ); - }), -); - -it.effect("refuses a repository that does not belong to the requested project", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [fakeProvider(SourceControlProviderKind.make("github"))], - }); - - const error = yield* service - .diff({ projectId: "p1" as ProjectId, repository: "attacker/repo", number: 1 }) - .pipe(Effect.flip); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("caches stack membership separately from action details", () => - Effect.gen(function* () { - const reads: Array = []; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestStack: (input) => - Effect.sync(() => { - reads.push(input.includeDetails === true); - return { - id: "9", - number: 3, - url: "https://github.com/acme/web/stacks/3", - base: "main", - layers: [ - { - number: 7, - headBranch: "a", - state: "open" as const, - ...(input.includeDetails ? { title: "First layer", headSha: "abc" } : {}), - }, - ], - }; - }), - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 7 }; - yield* service.stack(reference, { includeDetails: false }); - yield* service.stack(reference, { includeDetails: false }); - const detail = yield* service.stack(reference); - yield* service.stack(reference); - assert.deepStrictEqual(reads, [false, true]); - assert.strictEqual(detail?.layers[0]?.headSha, "abc"); - yield* service.invalidate({ reference }); - yield* service.stack(reference, { includeDetails: false }); - yield* service.stack(reference); - assert.deepStrictEqual(reads, [false, true, false, true]); - }), -); - -it.effect("reads a host-native stack through the provider and null where it has none", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestStack: () => - Effect.succeed({ - id: "9", - number: 3, - url: "https://github.com/acme/web/stacks/3", - base: "main", - layers: [ - { number: 7, headBranch: "a", state: "open" as const }, - { number: 8, headBranch: "b", state: "open" as const }, - ], - }), - }), - ], - }); - - const stack = yield* service.stack({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 7, - }); - assert.deepStrictEqual( - stack?.layers.map((layer) => layer.number), - [7, 8], - ); - - const withoutStacks = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [fakeProvider(SourceControlProviderKind.make("github"))], - }); - assert.isNull( - yield* withoutStacks.stack({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 7, - }), - ); - }), -); - -it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after refinement", () => +it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after refinement", () => Effect.gen(function* () { for (const provider of ["forgejo", "unknown"] as const) { const seen: string[] = []; @@ -2475,7 +1477,7 @@ it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("forgejo"), { + fakePullRequestProvider(SourceControlProviderKind.make("forgejo"), { getViewer: (input) => { viewers.push(input.host); assert.strictEqual(input.host, "code.example:3000"); @@ -2549,6 +1551,52 @@ it.effect("routes explicit Forgejo HTTP authorities through SSH checkouts after }), ); +it.effect("names an SSH remote's web host from a later checkout when the first cannot", () => + Effect.gen(function* () { + const hosts: Array = []; + const service = yield* makeService({ + projects: ["/first", "/second"].map((workspaceRoot, index) => + project({ + id: `p${index}`, + title: `checkout ${index}`, + workspaceRoot, + repository: "team/repo", + provider: SourceControlProviderKind.make("forgejo"), + host: "ssh.code.example", + remoteUrl: "git@ssh.code.example:team/repo.git", + }), + ), + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("forgejo"), { + listChangeRequests: (input) => { + hosts.push(input.host); + return Effect.succeed({ items: [], truncated: false, continues: true }); + }, + }), + ], + resolveHandle: ({ cwd, context }) => + Effect.succeed({ + context: + cwd === "/first" + ? context! + : { + ...context!, + provider: { + kind: SourceControlProviderKind.make("forgejo"), + name: "Forgejo", + baseUrl: "http://code.example:3000", + }, + }, + provider: undefined as never, + }), + }); + + yield* service.list({ state: "open" }); + + assert.deepStrictEqual(hosts, ["code.example:3000"]); + }), +); + it.effect("rejects a different Forgejo HTTP port for an HTTP checkout", () => Effect.gen(function* () { const service = yield* makeService({ @@ -2563,7 +1611,7 @@ it.effect("rejects a different Forgejo HTTP port for an HTTP checkout", () => remoteUrl: "http://code.example:4000/team/repo.git", }), ], - providers: [fakeProvider(SourceControlProviderKind.make("forgejo"))], + providers: [fakePullRequestProvider(SourceControlProviderKind.make("forgejo"))], }); const failure = yield* service .summary( @@ -2591,7 +1639,7 @@ it.effect("resolves a project's repository identity when its shell has none cach const service = yield* makeService({ projects: [{ ...resolved, repositoryIdentity: null }], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: () => Effect.succeed(changeRequest(7, "2026-07-02T00:00:00Z")), }), ], @@ -2615,7 +1663,7 @@ it.effect("routes a hosted reference to another repository through a project on project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: (input) => Effect.sync(() => { seen.push({ cwd: input.cwd, repository: input.repository, host: input.host }); @@ -2650,7 +1698,8 @@ it.effect("routes Azure reads and writes through the requested organization's ch }), ), providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + ...keyedByCanonicalKey, getChangeRequestSummary: (input) => Effect.sync(() => { seen.push(`read ${input.cwd} ${input.repository}`); @@ -2716,7 +1765,8 @@ it.effect.each([ target, ], providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + ...keyedByCanonicalKey, getChangeRequestSummary: (input) => Effect.sync(() => { seen.push(`read ${input.cwd} ${input.repository}`); @@ -2755,7 +1805,8 @@ it.effect("refuses Azure cross-organization reads and writes without its checkou }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + ...keyedByCanonicalKey, getChangeRequestSummary: () => Effect.die("must not read the wrong organization"), runAction: () => Effect.die("must not modify the wrong organization"), }), @@ -2776,49 +1827,6 @@ it.effect("refuses Azure cross-organization reads and writes without its checkou }), ); -it.effect.each([ - ["github.com", "github"], - ["bitbucket.org", "bitbucket"], - ["codeberg.org", "forgejo"], -] as const)("reads linked PR summaries and stacks on %s without a checkout", ([host, kind]) => - Effect.gen(function* () { - const seen: Array<{ cwd: string; repository: string; host: string }> = []; - const service = yield* makeService({ - projects: [project({ id: "inbox", title: "Inbox", workspaceRoot: "/home/alex" })], - providers: [ - fakeProvider(SourceControlProviderKind.make(kind), { - getChangeRequestSummary: (input) => - Effect.sync(() => { - seen.push({ cwd: input.cwd, repository: input.repository, host: input.host }); - return changeRequest(7, "2026-07-02T00:00:00Z"); - }), - getChangeRequestStack: (input) => - Effect.sync(() => { - seen.push({ cwd: input.cwd, repository: input.repository, host: input.host }); - return null; - }), - }), - ], - }); - const reference = { - projectId: "inbox" as ProjectId, - host, - repository: "acme/api", - number: 7, - }; - const summary = yield* service.summary(reference, { recoverTransientFailure: false }); - const stack = yield* service.stack(reference, { includeDetails: false }); - assert.strictEqual(summary.title, "Change request 7"); - assert.strictEqual(summary.state, "open"); - assert.strictEqual(summary.projectId, reference.projectId); - assert.strictEqual(stack, null); - assert.deepStrictEqual(seen, [ - { cwd: "/home/alex", repository: "acme/api", host }, - { cwd: "/home/alex", repository: "acme/api", host }, - ]); - }), -); - it.effect("prefers a matching checkout over a non-repository project's directory", () => Effect.gen(function* () { const seen: string[] = []; @@ -2828,7 +1836,7 @@ it.effect("prefers a matching checkout over a non-repository project's directory project({ id: "repo", title: "API", workspaceRoot: "/api", repository: "acme/api" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: (input) => Effect.sync(() => { seen.push(input.cwd); @@ -2850,11 +1858,12 @@ it.effect("prefers a matching checkout over a non-repository project's directory }), ); +// regression: #17167 refresh linked PRs without a checkout it.effect("requires an explicit host for a non-repository project's linked PR", () => Effect.gen(function* () { const service = yield* makeService({ projects: [project({ id: "inbox", title: "Inbox", workspaceRoot: "/home/alex" })], - providers: [fakeProvider(SourceControlProviderKind.make("github"))], + providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"))], }); const error = yield* service .summary( @@ -2870,1002 +1879,42 @@ it.effect("requires an explicit host for a non-repository project's linked PR", }), ); -it.effect("refuses a public host reference without a selected project directory", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [], - providers: [fakeProvider(SourceControlProviderKind.make("github"))], - }); - const error = yield* service - .summary( - { - projectId: "missing" as ProjectId, - host: "github.com", - repository: "acme/api", - number: 7, - }, - { recoverTransientFailure: false }, - ) - .pipe(Effect.flip); - assert.strictEqual(error._tag, "PullRequestUnavailableError"); - }), -); - -it.effect( - "requires a checkout for GitLab because its adapter does not explicitly target the host", - () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "inbox", title: "Inbox", workspaceRoot: "/home/alex" })], - providers: [fakeProvider(SourceControlProviderKind.make("gitlab"))], - }); - const error = yield* service - .summary( - { - projectId: "inbox" as ProjectId, - host: "gitlab.com", - repository: "acme/api", - number: 7, - }, - { recoverTransientFailure: false }, - ) - .pipe(Effect.flip); - assert.strictEqual(error._tag, "PullRequestUnavailableError"); - }), -); - -it.effect("refuses a hosted reference when its provider is unavailable", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }), - ], - providers: [fakeProvider(SourceControlProviderKind.make("github"))], - }); - - const error = yield* service - .summary( - { - projectId: "frontend" as ProjectId, - host: "gitlab.com", - repository: "acme/api", - number: 7, - }, - { recoverTransientFailure: false }, - ) - .pipe(Effect.flip); - - assert.strictEqual(error._tag, "PullRequestUnavailableError"); - }), -); - -it.effect("refuses a diff on a host that cannot produce one", () => +it.effect("refuses a review request this viewer may not make, and says what access it takes", () => Effect.gen(function* () { + let sent = false; const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on azure", - workspaceRoot: "/a", - repository: "org/project", - provider: SourceControlProviderKind.make("azure-devops"), - }), - ], + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { - capabilities: { - diff: false, - comment: true, - actions: ["merge", "close"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getViewerPermissions: () => + Effect.succeed({ + actions: ["ready", "draft", "close", "reopen"], + comment: true, + resolve: true, + verdicts: ["comment", "approve", "request-changes"], + requestReviewers: false, + }), + setReviewerRequest: () => { + sent = true; + return Effect.void; }, - getDiff: () => Effect.die("must not be called"), }), ], }); - const error = yield* service - .diff({ projectId: "p1" as ProjectId, repository: "org/project", number: 1 }) - .pipe(Effect.flip); + const error = yield* Effect.flip( + service.requestReviewers({ + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + reviewers: [{ id: "octocat", kind: "user" }], + requested: true, + }), + ); assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("rejects an empty comment before reaching the host", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - comment: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* service - .comment({ - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - body: " ", - }) - .pipe(Effect.flip); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("refuses a verdict the host never claimed, without asking the provider", () => - Effect.gen(function* () { - let submitted = false; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: { - inlineComment: true, - reply: true, - resolve: true, - verdicts: ["comment", "approve"], - }, - reviewers: FULL_REVIEWERS, - }, - submitReview: () => { - submitted = true; - return Effect.void; - }, - }), - ], - }); - - const error = yield* Effect.flip( - service.submitReview({ - projectId: "p1" as ProjectId, - repository: "group/project", - number: 1, - verdict: "request-changes", - body: "no", - comments: [], - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.isFalse(submitted); - }), -); - -it.effect("refuses line comments on a host that takes only a summary", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: { inlineComment: false, reply: false, resolve: false, verdicts: ["comment"] }, - reviewers: FULL_REVIEWERS, - }, - submitReview: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.submitReview({ - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - verdict: "comment", - body: "", - comments: [{ path: "src/a.ts", position: { kind: "added", newLine: 1 }, body: "nit" }], - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect( - "refuses a review with neither a summary nor a comment, but lets an approval through", - () => - Effect.gen(function* () { - let approved = false; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "t3code", - workspaceRoot: "/a", - repository: "pingdotgg/t3code", - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - submitReview: () => { - approved = true; - return Effect.void; - }, - }), - ], - }); - const reference = { - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - }; - - const error = yield* Effect.flip( - service.submitReview({ ...reference, verdict: "comment", body: " ", comments: [] }), - ); - assert.strictEqual(error._tag, "PullRequestOperationError"); - - yield* service.submitReview({ ...reference, verdict: "approve", body: "", comments: [] }); - assert.isTrue(approved); - }), -); - -it.effect("refuses to resolve a conversation on a host that cannot", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: { inlineComment: true, reply: false, resolve: false, verdicts: ["comment"] }, - reviewers: FULL_REVIEWERS, - }, - setThreadResolution: () => Effect.die("must not be called"), - replyToThread: () => Effect.die("must not be called"), - }), - ], - }); - const reference = { - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - }; - - const resolveError = yield* Effect.flip( - service.setThreadResolution({ ...reference, threadId: "t1", resolved: true }), - ); - const replyError = yield* Effect.flip( - service.replyToThread({ ...reference, threadId: "t1", body: "hi" }), - ); - - assert.strictEqual(resolveError._tag, "PullRequestOperationError"); - assert.strictEqual(replyError._tag, "PullRequestOperationError"); - }), -); - -it.effect("refuses to react on a host with no reactions", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: false, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - setReaction: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.setReaction({ - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - content: "heart", - reacted: true, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("refuses to react on a host whose capabilities omit reactions entirely", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - setReaction: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.setReaction({ - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - content: "heart", - reacted: true, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("passes a reaction through with its subject id on a host that has them", () => - Effect.gen(function* () { - let received: { - readonly subjectId: string | undefined; - readonly content: string; - readonly reacted: boolean; - } | null = null; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - setReaction: (input) => { - received = { - subjectId: input.subjectId, - content: input.content, - reacted: input.reacted, - }; - return Effect.void; - }, - }), - ], - }); - - yield* service.setReaction({ - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - subjectId: "IC_1", - content: "heart", - reacted: true, - }); - - assert.deepStrictEqual(received, { subjectId: "IC_1", content: "heart", reacted: true }); - }), -); - -it.effect("invalidates the cached activity after reacting, like the other mutations", () => - Effect.gen(function* () { - let activityCalls = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestActivity: () => { - activityCalls += 1; - return Effect.succeed({ - comments: [], - commentCount: 0, - commentsTruncated: false, - reviewThreads: [], - commits: [], - }); - }, - }), - ], - }); - - yield* service.refreshAfterTurn(reference.projectId); - const previousRefresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); - yield* service.activity(reference); - assert.strictEqual(activityCalls, 1); - - yield* service.setReaction({ ...reference, content: "heart", reacted: true }); - assert.isAbove( - Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)), - previousRefresh, - ); - yield* service.activity(reference); - - assert.strictEqual(activityCalls, 2); - }), -); - -it.effect("refuses an empty reply before it reaches the host", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - replyToThread: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.replyToThread({ - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - threadId: "t1", - body: " ", - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - }), -); - -it.effect("refuses a merge strategy the host does not offer", () => - Effect.gen(function* () { - let ranWith: string | null = null; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge", "squash"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-07-02T00:00:00Z")), - runAction: (input) => { - ranWith = input.mergeMethod ?? "merge"; - return Effect.void; - }, - }), - ], - }); - const reference = { - projectId: "p1" as ProjectId, - repository: "pingdotgg/t3code", - number: 1, - }; - - const error = yield* Effect.flip( - service.runAction({ ...reference, action: "merge", mergeMethod: "rebase" }), - ); - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.strictEqual(ranWith, null); - - yield* service.runAction({ ...reference, action: "merge", mergeMethod: "squash" }); - assert.strictEqual(ranWith, "squash"); - }), -); - -it.effect("hands the provider the host its repository lives on", () => - Effect.gen(function* () { - const hosts: string[] = []; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "enterprise", - workspaceRoot: "/a", - repository: "acme/web", - host: "github.acme.dev", - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: (input) => { - hosts.push(input.host); - return Effect.succeed({ items: [], truncated: false, continues: true }); - }, - }), - ], - }); - - yield* service.list({ state: "open" }); - - assert.deepStrictEqual(hosts, ["github.acme.dev"]); - }), -); - -it.effect("asks every host the reader's search, rather than filtering what came back", () => - Effect.gen(function* () { - const asked: Array = []; - const listing = (input: { readonly query?: string | undefined }) => { - asked.push(input.query); - return Effect.succeed({ items: [], truncated: false, continues: true }); - }; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - project({ - id: "p2", - title: "on gitlab", - workspaceRoot: "/b", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { listChangeRequests: listing }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { listChangeRequests: listing }), - ], - }); - - yield* service.list({ state: "open", query: "pull requests page" }); - - assert.deepStrictEqual(asked, ["pull requests page", "pull requests page"]); - }), -); - -it.effect("asks for no search when the reader has typed nothing", () => - Effect.gen(function* () { - const asked: Array = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: (input) => { - asked.push(input.query); - return Effect.succeed({ items: [], truncated: false, continues: true }); - }, - }), - ], - }); - - yield* service.list({ state: "open" }); - - assert.deepStrictEqual(asked, [undefined]); - }), -); - -it.effect("asks another checkout who is signed in when the first one cannot answer", () => - Effect.gen(function* () { - const asked: string[] = []; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "t3code (stale worktree)", - workspaceRoot: "/gone", - repository: "pingdotgg/t3code", - }), - project({ - id: "p2", - title: "t3code", - workspaceRoot: "/healthy", - repository: "pingdotgg/t3code", - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: (input) => { - asked.push(input.cwd); - return input.cwd === "/gone" - ? Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getViewer", - reason: "failed", - detail: "not a git repository", - }), - ) - : Effect.succeed("bilal"); - }, - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: false, - continues: true, - }), - }), - ], - }); - - const result = yield* service.list({ state: "open" }); - - assert.deepStrictEqual(asked, ["/gone", "/healthy"]); - assert.strictEqual(result.entries.length, 1); - assert.strictEqual(result.providers[0]?.configured, true); - }), -); - -it.effect("refuses to ask for a review on a host that cannot, before any call is made", () => - Effect.gen(function* () { - let asked = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: { request: false, listCandidates: false }, - }, - getViewerPermissions: () => { - asked = true; - return Effect.die("must not be called"); - }, - setReviewerRequest: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.requestReviewers({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - reviewers: [{ id: "octocat", kind: "user" }], - requested: true, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.include(error.message, "cannot ask somebody for a review."); - assert.isFalse(asked); - }), -); - -it.effect("refuses the candidate list on a host that has no such list to give", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: false, - comment: false, - actions: ["merge"], - mergeMethods: ["merge"], - search: false, - reactions: true, - review: FULL_REVIEW, - reviewers: { request: true, listCandidates: false }, - }, - listReviewerCandidates: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.reviewerCandidates({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.include(error.message, "cannot say who may review a change request."); - }), -); - -it.effect("refuses a review request this viewer may not make, and says what access it takes", () => - Effect.gen(function* () { - let sent = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewerPermissions: () => - Effect.succeed({ - actions: ["ready", "draft", "close", "reopen"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: false, - }), - setReviewerRequest: () => { - sent = true; - return Effect.void; - }, - }), - ], - }); - - const error = yield* Effect.flip( - service.requestReviewers({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - reviewers: [{ id: "octocat", kind: "user" }], - requested: true, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.include(error.message, "You need write access on this repository to ask for a review."); - assert.isFalse(sent); - }), -); - -it.effect("keeps the menu from a viewer who may not ask, which is all it is for", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewerPermissions: () => - Effect.succeed({ - actions: [], - comment: true, - resolve: false, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: false, - }), - listReviewerCandidates: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.reviewerCandidates({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - }), - ); - - assert.include(error.message, "You need write access on this repository to ask for a review."); - }), -); - -it.effect("hands the host's own candidate list back, and asks for it with the change request", () => - Effect.gen(function* () { - let askedFor: number | null = null; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listReviewerCandidates: (input) => { - askedFor = input.number; - return Effect.succeed({ - candidates: [ - { - id: "octocat", - kind: "user", - login: "octocat", - name: null, - avatarUrl: null, - isRequested: true, - }, - ], - truncated: false, - continues: true, - }); - }, - }), - ], - }); - - const list = yield* service.reviewerCandidates({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 4, - }); - - assert.strictEqual(askedFor, 4); - assert.deepStrictEqual( - list.candidates.map((candidate) => candidate.login), - ["octocat"], - ); - }), -); - -it.effect("refuses a label change on a host that has not said it takes one", () => - Effect.gen(function* () { - let changed = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - setLabels: () => { - changed = true; - return Effect.void; - }, - }), - ], - }); - - const error = yield* Effect.flip( - service.setLabels({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - labels: ["bug"], - applied: true, - }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.include(error.message, "cannot change the labels"); - assert.isFalse(changed); - }), -); - -it.effect("refuses a label change this viewer may not make, and says what access it takes", () => - Effect.gen(function* () { - let changed = false; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities, - labels: true, - }, - getViewerPermissions: () => - Effect.succeed({ - actions: [], - comment: true, - resolve: false, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: false, - labels: false, - }), - listLabelCandidates: () => Effect.die("must not be called"), - setLabels: () => { - changed = true; - return Effect.void; - }, - }), - ], - }); - - const listError = yield* Effect.flip( - service.labelCandidates({ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }), - ); - assert.include(listError.message, "You need triage access on this repository"); - - const error = yield* Effect.flip( - service.setLabels({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - labels: ["bug"], - applied: true, - }), - ); - assert.include(error.message, "You need triage access on this repository"); - assert.isFalse(changed); - }), -); - -it.effect("hands a label change to the host, and reads the labels back for the menu", () => - Effect.gen(function* () { - let received: { labels: ReadonlyArray; applied: boolean } | null = null; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities, - labels: true, - }, - listLabelCandidates: () => - Effect.succeed({ - candidates: [{ name: "bug", color: null, description: null, isApplied: false }], - truncated: false, - }), - setLabels: (input) => { - received = { labels: input.labels, applied: input.applied }; - return Effect.void; - }, - }), - ], - }); - - const list = yield* service.labelCandidates({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 4, - }); - assert.deepStrictEqual( - list.candidates.map((label) => label.name), - ["bug"], - ); - - yield* service.setLabels({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 4, - labels: ["bug"], - applied: false, - }); - assert.deepStrictEqual(received, { labels: ["bug"], applied: false }); - }), -); - -it.effect("answers a repeated listing from cache, and concurrent readers share one request", () => - Effect.gen(function* () { - let hostCalls = 0; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => { - hostCalls += 1; - return Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: false, - continues: false, - }); - }, - }), - ], - }); - - yield* Effect.all([service.list({ state: "open" }), service.list({ state: "open" })], { - concurrency: "unbounded", - }); - yield* service.list({ state: "open" }); - assert.strictEqual(hostCalls, 1); - - yield* service.list({ state: "all" }); - assert.strictEqual(hostCalls, 2); + assert.include(error.message, "You need write access on this repository to ask for a review."); + assert.isFalse(sent); }), ); @@ -3893,7 +1942,7 @@ it.effect.each(["list", "listStats"] as const)( project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: () => lookup.pipe( Effect.as({ @@ -3941,131 +1990,32 @@ it.effect("shares one cold viewer lookup across distinct concurrent lists", () = const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getViewer: () => Effect.sync(() => { viewerCalls += 1; }).pipe(Effect.andThen(Effect.yieldNow), Effect.as("bilal")), listChangeRequests: () => - Effect.sync(() => { - listCalls += 1; - return { items: [], truncated: false, continues: true }; - }), - }), - ], - }); - - yield* Effect.forEach( - ["all", "authored", "reviewing"], - (involvement) => - service.list({ - state: "open", - involvement: involvement as "all" | "authored" | "reviewing", - }), - { concurrency: "unbounded" }, - ); - - assert.strictEqual(viewerCalls, 1); - assert.strictEqual(listCalls, 3); - }), -); - -it.effect("uses five host reads for the normal indexed-repository page workflow", () => - Effect.gen(function* () { - let viewerCalls = 0; - let searchCalls = 0; - let fallbackCalls = 0; - let statsCalls = 0; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: () => - Effect.sync(() => { - viewerCalls += 1; - return "bilal"; - }), - listChangeRequestsAcross: (input) => - Effect.sync(() => { - searchCalls += 1; - return { - items: - input.involvement === "all" - ? [batchedChangeRequest(1, "acme/web", "2026-07-02T00:00:00Z")] - : [], - truncated: false, - }; - }), - listChangeRequests: () => - Effect.sync(() => { - fallbackCalls += 1; - return { items: [], truncated: false, continues: true }; - }), - listChangeRequestStats: () => - Effect.sync(() => { - statsCalls += 1; - return [{ repository: "acme/web", number: 1, additions: 3, deletions: 1 }]; - }), - }), - ], - }); - - const baseline = yield* service.list({ state: "open", involvement: "all" }); - yield* Effect.all( - [ - service.list({ state: "open", involvement: "authored" }), - service.list({ state: "open", involvement: "reviewing" }), - ], - { concurrency: "unbounded" }, - ); - yield* service.listStats({ - refs: baseline.entries.map(({ projectId, repository, number }) => ({ - projectId, - repository, - number, - })), - }); - - assert.deepStrictEqual( - { viewerCalls, searchCalls, fallbackCalls, statsCalls }, - { viewerCalls: 1, searchCalls: 3, fallbackCalls: 0, statsCalls: 1 }, - ); - }), -); - -it.effect("returns the refreshed listing on the first read after its cache expires", () => - Effect.gen(function* () { - let hostCalls = 0; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => { - hostCalls += 1; - return Effect.succeed({ - items: [changeRequest(hostCalls, "2026-07-02T00:00:00Z")], - truncated: false, - continues: false, - }); - }, + Effect.sync(() => { + listCalls += 1; + return { items: [], truncated: false, continues: true }; + }), }), ], }); - const first = yield* service.list({ state: "open" }); - assert.deepStrictEqual( - first.entries.map((entry) => entry.number), - [1], + yield* Effect.forEach( + ["all", "authored", "reviewing"], + (involvement) => + service.list({ + state: "open", + involvement: involvement as "all" | "authored" | "reviewing", + }), + { concurrency: "unbounded" }, ); - yield* TestClock.adjust("31 seconds"); - const refreshed = yield* service.list({ state: "open" }); - - assert.strictEqual(hostCalls, 2); - assert.deepStrictEqual( - refreshed.entries.map((entry) => entry.number), - [2], - ); + assert.strictEqual(viewerCalls, 1); + assert.strictEqual(listCalls, 3); }), ); @@ -4078,7 +2028,7 @@ it.effect("a listing narrowed to some projects is its own cache entry", () => project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequestsAcross: (input) => { asked.push(input.repositories); return Effect.succeed({ @@ -4119,7 +2069,7 @@ it.effect( project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ filters }) => Effect.gen(function* () { reads += 1; @@ -4167,92 +2117,13 @@ it.effect( }), ); -it.effect("keeps unrelated PRs warm after a mutation, explicit refresh, and project turn", () => - Effect.gen(function* () { - const calls: string[] = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: (input) => - Effect.sync(() => { - calls.push(`${input.repository}/${input.number}`); - return { ...hostedChangeRequest("body"), number: input.number }; - }), - }), - ], - }); - const refs = [ - { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }, - { projectId: "p1" as ProjectId, repository: "acme/web", number: 2 }, - { projectId: "p2" as ProjectId, repository: "acme/docs", number: 3 }, - ]; - const readAll = Effect.forEach(refs, (ref) => service.summary({ ...ref, allowStale: false })); - yield* readAll; - yield* service.invalidate({ reference: { ...refs[0]!, host: "github.com" } }); - yield* readAll; - assert.deepStrictEqual(calls, ["acme/web/1", "acme/web/2", "acme/docs/3", "acme/web/1"]); - yield* service.comment({ ...refs[0]!, body: "hello" }); - yield* readAll; - assert.deepStrictEqual(calls.slice(4), ["acme/web/1"]); - yield* service.refreshAfterTurn("p1" as ProjectId); - yield* readAll; - assert.deepStrictEqual(calls.slice(5), ["acme/web/1", "acme/web/2"]); - }), -); - -it.effect( - "keeps matching PR numbers on different hosts separate and refreshes the serving project", - () => - Effect.gen(function* () { - const hosts: string[] = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "public", workspaceRoot: "/a", repository: "acme/web" }), - project({ - id: "p2", - title: "enterprise", - workspaceRoot: "/b", - repository: "acme/web", - host: "enterprise.test", - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: (input) => - Effect.sync(() => { - hosts.push(input.host); - return hostedChangeRequest("body"); - }), - }), - ], - }); - const own = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const other = { ...own, host: "enterprise.test" }; - const readBoth = Effect.all([service.summary(own), service.summary(other)]); - yield* readBoth; - yield* service.invalidate({ reference: { ...own, host: "github.com" } }); - yield* readBoth; - assert.deepStrictEqual(hosts, ["github.com", "enterprise.test", "github.com"]); - yield* service.invalidate({ reference: own }); - yield* readBoth; - assert.deepStrictEqual(hosts.slice(3), ["github.com"]); - yield* service.refreshAfterTurn("p2" as ProjectId); - yield* readBoth; - assert.deepStrictEqual(hosts.slice(4), ["enterprise.test"]); - }), -); - it.effect("does not revive old summaries when project epochs are evicted", () => Effect.gen(function* () { let title = "old"; const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("body"), title }), }), ], @@ -4268,44 +2139,6 @@ it.effect("does not revive old summaries when project epochs are evicted", () => }), ); -it.effect("explicit and turn invalidations make the next listing ask the host again", () => - Effect.gen(function* () { - let hostCalls = 0; - let viewerCalls = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: () => { - viewerCalls += 1; - return Effect.succeed("bilal"); - }, - listChangeRequests: () => { - hostCalls += 1; - return Effect.succeed({ items: [], truncated: false, continues: false }); - }, - }), - ], - }); - - yield* service.list({ state: "open" }); - yield* service.invalidate({}); - yield* service.list({ state: "open" }); - assert.strictEqual(hostCalls, 2); - assert.strictEqual(viewerCalls, 2); - - yield* service.invalidate({ reference }); - yield* service.list({ state: "open" }); - assert.strictEqual(hostCalls, 2); - yield* service.refreshAfterTurn("p1" as ProjectId); - const refresh = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); - yield* service.list({ state: "open" }); - assert.isAbove(refresh, 0); - assert.strictEqual(hostCalls, 3); - }), -); - it.effect("close and reopen notify subscribed readers after invalidating their cached state", () => Effect.scoped( Effect.gen(function* () { @@ -4317,7 +2150,7 @@ it.effect("close and reopen notify subscribed readers after invalidating their c project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: () => Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }), runAction: (input) => @@ -4359,77 +2192,6 @@ it.effect("close and reopen notify subscribed readers after invalidating their c ), ); -it.effect("explicit invalidation refreshes origin readers after a routed host mutation", () => - Effect.scoped( - Effect.gen(function* () { - 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.succeed({ ...changeRequest(1, "2026-09-16T00:00:00.000Z"), state }), - }), - ], - }); - yield* service.refreshAfterTurn(reference.projectId); - let revision = Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)); - yield* service.invalidate({ reference }); - assert.strictEqual( - Option.getOrThrow(yield* Stream.runHead(service.subscribeRefreshes)), - revision, - ); - assert.strictEqual((yield* service.summary(reference)).state, "open"); - - for (const nextState of ["closed", "open"] as const) { - const refreshed = yield* service.subscribeRefreshes.pipe( - Stream.drop(1), - Stream.take(1), - Stream.mapEffect((nextRevision) => - service - .summary(reference) - .pipe(Effect.map((summary) => ({ revision: nextRevision, state: summary.state }))), - ), - Stream.runHead, - Effect.forkChild({ startImmediately: true }), - ); - state = nextState; - yield* service.invalidate({ reference }, { notifyReaders: true }); - const result = Option.getOrThrow(yield* Fiber.join(refreshed)); - assert.strictEqual(result.state, nextState); - assert.isAbove(result.revision, revision); - revision = result.revision; - } - }), - ), -); - -it.effect("does not cache a failed listing", () => - Effect.gen(function* () { - let hostCalls = 0; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getViewer: () => { - hostCalls += 1; - return hostCalls === 1 ? Effect.fail(requestFailed) : Effect.succeed("bilal"); - }, - }), - ], - }); - - const error = yield* Effect.flip(service.list({ state: "open" })); - assert.strictEqual(error._tag, "PullRequestOperationError"); - const second = yield* service.list({ state: "open" }); - assert.strictEqual(hostCalls, 2); - assert.strictEqual(second.providers[0]?.configured, true); - }), -); - it.effect("reads a host's repositories in one search, and files the rows back under each", () => Effect.gen(function* () { const asked: Array> = []; @@ -4447,7 +2209,7 @@ it.effect("reads a host's repositories in one search, and files the rows back un }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ repository }) => { separately.push(repository); return Effect.succeed({ items: [], truncated: false, continues: true }); @@ -4463,7 +2225,7 @@ it.effect("reads a host's repositories in one search, and files the rows back un }); }, }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { listChangeRequests: ({ repository }) => { separately.push(repository); return Effect.succeed({ @@ -4499,7 +2261,7 @@ it.effect("carries every repository of a slice on from the oldest row in it", () project({ id: "p3", title: "docs", workspaceRoot: "/c", repository: "acme/docs" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequestsAcross: () => Effect.succeed({ items: [ @@ -4508,6 +2270,7 @@ it.effect("carries every repository of a slice on from the oldest row in it", () batchedChangeRequest(3, "acme/web", "2026-07-02T00:00:00Z"), ], truncated: true, + unresolved: ["acme/docs"], }), }), ], @@ -4528,7 +2291,7 @@ it.effect("carries a slice on without sending the rows it already sent", () => const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequestsAcross: (input) => { cursors.push(input.cursor); return Effect.succeed({ @@ -4554,7 +2317,7 @@ it.effect("carries a slice on without sending the rows it already sent", () => [4], ); assert.deepStrictEqual(result.nextCursors, { - "github.com acme/web": "2026-07-02T00:00:00Z|2|3,3,4", + "github.com acme/web": "2026-07-02T00:00:00Z|2|3,4", }); }), ); @@ -4571,7 +2334,7 @@ it.effect("reads a workspace larger than one search in chunks, and merges them", }), ), providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequestsAcross: (input) => { asked.push(input.repositories.length); return Effect.succeed({ @@ -4591,7 +2354,7 @@ it.effect("reads a workspace larger than one search in chunks, and merges them", assert.strictEqual(result.entries.length, 101); }), ); -it.effect("asks on its own for a repository a search answered nothing for", () => +it.effect("asks on its own for a repository a search could not vouch for", () => Effect.gen(function* () { const separately: string[] = []; const service = yield* makeService({ @@ -4600,7 +2363,7 @@ it.effect("asks on its own for a repository a search answered nothing for", () = project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ repository }) => { separately.push(repository); return repository === "acme/docs" @@ -4611,6 +2374,7 @@ it.effect("asks on its own for a repository a search answered nothing for", () = Effect.succeed({ items: [batchedChangeRequest(1, "acme/web", "2026-07-03T00:00:00Z")], truncated: false, + unresolved: ["acme/docs"], }), }), ], @@ -4632,7 +2396,7 @@ it.effect("asks on its own for a repository a search answered nothing for", () = ); }), ); -it.effect("reads the repositories one at a time when the search itself fails", () => +it.effect("believes a search's silence about a repository it vouches for", () => Effect.gen(function* () { const separately: string[] = []; const service = yield* makeService({ @@ -4641,25 +2405,27 @@ it.effect("reads the repositories one at a time when the search itself fails", ( project({ id: "p2", title: "docs", workspaceRoot: "/b", repository: "acme/docs" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequests: ({ repository }) => { separately.push(repository); - return Effect.succeed({ - items: [changeRequest(1, "2026-07-02T00:00:00Z")], - truncated: false, - continues: true, - }); + return Effect.succeed({ items: [], truncated: false, continues: true }); }, - listChangeRequestsAcross: () => Effect.fail(requestFailed), + listChangeRequestsAcross: () => + Effect.succeed({ + items: [batchedChangeRequest(1, "acme/web", "2026-07-03T00:00:00Z")], + truncated: false, + }), }), ], }); const result = yield* service.list({ state: "open" }); - assert.deepStrictEqual(separately.toSorted(), ["acme/docs", "acme/web"]); - assert.deepStrictEqual(result.errors, []); - assert.strictEqual(result.entries.length, 2); + assert.deepStrictEqual(separately, []); + assert.deepStrictEqual( + result.entries.map((entry) => entry.number), + [1], + ); }), ); it.effect("fills in the line counts for the rows it is given", () => @@ -4677,7 +2443,7 @@ it.effect("fills in the line counts for the rows it is given", () => }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { listChangeRequestStats: (input) => { asked.push(input.changeRequests); return Effect.succeed([ @@ -4685,7 +2451,7 @@ it.effect("fills in the line counts for the rows it is given", () => ]); }, }), - fakeProvider(SourceControlProviderKind.make("gitlab")), + fakePullRequestProvider(SourceControlProviderKind.make("gitlab")), ], }); @@ -4715,58 +2481,6 @@ it.effect("fills in the line counts for the rows it is given", () => ]); }), ); -it.effect( - "reuses counts across overlapping pages until expiry, explicit invalidation, or a reference changes", - () => - Effect.gen(function* () { - const asked: number[][] = []; - const ref = (number: number) => ({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number, - }); - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequestStats: (input) => { - asked.push(input.changeRequests.map((ref) => ref.number)); - return Effect.succeed( - input.changeRequests.map((ref) => ({ ...ref, additions: 12, deletions: 3 })), - ); - }, - }), - ], - }); - - yield* service.listStats({ refs: [ref(1), ref(2)] }); - const overlapping = yield* service.listStats({ refs: [ref(2), ref(3)] }); - assert.deepStrictEqual( - overlapping.stats.map((stat) => stat.number), - [2, 3], - ); - yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] }); - assert.deepStrictEqual(asked, [[1, 2], [3]]); - - yield* service.invalidate({ reference: ref(2) }); - yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] }); - assert.deepStrictEqual(asked, [[1, 2], [3], [2]]); - - yield* TestClock.adjust("61 seconds"); - yield* service.listStats({ refs: [ref(1), ref(2), ref(3)] }); - assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3]]); - - yield* service.refreshAfterTurn("p1" as ProjectId); - yield* service.listStats({ refs: [ref(1)] }); - assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3], [1]]); - - yield* service.invalidate({}); - yield* service.listStats({ refs: [ref(1)] }); - assert.deepStrictEqual(asked, [[1, 2], [3], [2], [1, 2, 3], [1], [1]]); - }), -); it.effect("reads the fresh diff when detail or summary discovers a changed revision", () => Effect.gen(function* () { @@ -4779,7 +2493,7 @@ it.effect("reads the fresh diff when detail or summary discovers a changed revis const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequest: () => Effect.sync(() => ({ ...hostedChangeRequest("body"), updatedAt: revision })), getChangeRequestSummary: () => @@ -4800,184 +2514,26 @@ it.effect("reads the fresh diff when detail or summary discovers a changed revis const coldSummary = yield* service.summary(reference).pipe(Effect.forkChild()); yield* Deferred.await(summaryStarted); - yield* service.detail(reference); - assert.strictEqual((yield* service.diff(reference)).patch, "old patch"); - revision = "2026-07-02T00:01:00Z"; - patch = "new patch"; - yield* TestClock.adjust("61 seconds"); - yield* service.detail(reference); - yield* Effect.yieldNow; - assert.strictEqual((yield* service.detail(reference)).updatedAt, revision); - yield* Deferred.succeed(releaseSummary, undefined); - yield* Fiber.join(coldSummary); - yield* service.summary(reference, { recoverTransientFailure: false }); - assert.strictEqual((yield* service.diff(reference)).patch, "new patch"); - assert.strictEqual(diffCalls, 2); - - revision = "2026-07-02T00:02:00Z"; - patch = "summary-discovered patch"; - yield* TestClock.adjust("61 seconds"); - yield* service.summary(reference, { recoverTransientFailure: false }); - assert.strictEqual((yield* service.diff(reference)).patch, patch); - assert.strictEqual(diffCalls, 3); - }), -); - -it.effect("keeps the rows when the line counts cannot be read", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequestStats: () => Effect.fail(requestFailed), - }), - ], - }); - - const result = yield* service.listStats({ - refs: [{ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }], - }); - - assert.deepStrictEqual(result.stats, []); - }), -); - -it.effect( - "serves core detail without waiting for activity, and shares activity between clients", - () => - Effect.gen(function* () { - let coreCalls = 0; - let activityCalls = 0; - let statsCalls = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequestStats: () => { - statsCalls += 1; - return Effect.succeed([]); - }, - getChangeRequest: () => { - coreCalls += 1; - return Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - body: "Ready before the conversation", - changedFiles: 2, - mergedAt: null, - closedAt: null, - reviewers: [], - checks: [], - mergeCapabilities: { merge: true, squash: true, rebase: true }, - viewerPermissions: { - actions: ["merge"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }, - }); - }, - getChangeRequestActivity: () => { - activityCalls += 1; - return Effect.succeed({ - comments: [], - commentCount: 0, - commentsTruncated: true, - reviewThreadsTruncated: true, - reviewThreads: [], - commits: [], - }); - }, - }), - ], - }); - - const core = yield* service.detail(reference); - assert.strictEqual(core.body, "Ready before the conversation"); - assert.strictEqual(coreCalls, 1); - assert.strictEqual(activityCalls, 0); - - const counts = yield* service.listStats({ refs: [reference] }); - assert.strictEqual(statsCalls, 0); - assert.deepStrictEqual(counts.stats, [ - { - ...reference, - additions: core.additions, - deletions: core.deletions, - }, - ]); - - const activities = yield* Effect.all( - [service.activity(reference), service.activity(reference)], - { - concurrency: 2, - }, - ); - assert.strictEqual(activityCalls, 1); - assert.isTrue(activities.every((activity) => activity.reviewThreadsTruncated === true)); - - yield* service.invalidate({ reference }); - yield* service.activity(reference); - assert.strictEqual(activityCalls, 2); - }), -); - -it.effect("shares linked summaries and reuses them for display without asking the host again", () => - Effect.gen(function* () { - let calls = 0; - let failing = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.sync(() => { - calls += 1; - return failing; - }).pipe( - Effect.tap(() => Effect.yieldNow), - Effect.flatMap((shouldFail) => - shouldFail - ? Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getChangeRequestSummary", - reason: "failed", - detail: "HTTP 504", - }), - ) - : Effect.succeed(changeRequest(1, "2026-07-02T00:00:00Z")), - ), - ), - }), - ], - }); - - yield* Effect.all( - [ - service.summary(reference, { recoverTransientFailure: false }), - service.summary(reference, { recoverTransientFailure: false }), - ], - { concurrency: "unbounded" }, - ); - assert.strictEqual(calls, 1); - + yield* service.detail(reference); + assert.strictEqual((yield* service.diff(reference)).patch, "old patch"); + revision = "2026-07-02T00:01:00Z"; + patch = "new patch"; yield* TestClock.adjust("61 seconds"); - failing = true; - const strict = yield* Effect.flip(service.summary({ ...reference, allowStale: false })); - assert.strictEqual(strict._tag, "PullRequestOperationError"); - - const stale = yield* service.summary(reference); - assert.strictEqual(stale.updatedAt, "2026-07-02T00:00:00Z"); - assert.strictEqual(calls, 2); + yield* service.detail(reference); + yield* Effect.yieldNow; + assert.strictEqual((yield* service.detail(reference)).updatedAt, revision); + yield* Deferred.succeed(releaseSummary, undefined); + yield* Fiber.join(coldSummary); + yield* service.summary(reference, { recoverTransientFailure: false }); + assert.strictEqual((yield* service.diff(reference)).patch, "new patch"); + assert.strictEqual(diffCalls, 2); - yield* service.invalidate({ reference }); - const invalidated = yield* Effect.flip(service.summary(reference)); - assert.strictEqual(invalidated._tag, "PullRequestOperationError"); + revision = "2026-07-02T00:02:00Z"; + patch = "summary-discovered patch"; + yield* TestClock.adjust("61 seconds"); + yield* service.summary(reference, { recoverTransientFailure: false }); + assert.strictEqual((yield* service.diff(reference)).patch, patch); + assert.strictEqual(diffCalls, 3); }), ); @@ -4998,9 +2554,9 @@ it.effect("keeps routed reads separate when the GitHub account changes", () => project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { capabilities: { - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities, + ...fakePullRequestProvider(SourceControlProviderKind.make("github")).capabilities, viewedFiles: "host", }, getFilesViewed: () => @@ -5064,9 +2620,9 @@ it.effect("isolates routed caches for two credentials belonging to the same acco project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { capabilities: { - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities, + ...fakePullRequestProvider(SourceControlProviderKind.make("github")).capabilities, viewedFiles: "host", }, getFilesViewed: () => @@ -5126,7 +2682,7 @@ it.effect("rejects mismatched routing credentials before use and preserves actio const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getRoutingIdentity: () => Effect.succeed({ accountId: "101", viewer: "octocat" }), withVerifiedCredential: (_, use) => use({ @@ -5172,64 +2728,6 @@ it.effect("rejects mismatched routing credentials before use and preserves actio }), ); -it.effect("answers a known pull request immediately while the host refreshes", () => - Effect.gen(function* () { - const gate = yield* Deferred.make(); - let calls = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => - Effect.gen(function* () { - calls += 1; - if (calls > 1) yield* Deferred.await(gate); - return hostedChangeRequest("cached body", 4); - }), - }), - ], - }); - - const first = yield* service.detail(reference); - assert.strictEqual(first.body, "cached body"); - assert.strictEqual(first.additions, 4); - - yield* TestClock.adjust("61 seconds"); - const second = yield* service.detail(reference); - assert.strictEqual(second.body, "cached body"); - assert.strictEqual(second.additions, 4); - yield* Effect.yieldNow; - assert.strictEqual(calls, 2); - }), -); - -it.effect("does not ask the host again for a linked summary it already holds", () => - Effect.gen(function* () { - let calls = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequestSummary: () => - Effect.sync(() => { - calls += 1; - return changeRequest(1, "2026-07-02T00:00:00Z"); - }), - }), - ], - }); - - const first = yield* service.summary(reference); - assert.strictEqual(first.title, "Change request 1"); - yield* TestClock.adjust("61 seconds"); - const second = yield* service.summary(reference); - assert.strictEqual(second.title, "Change request 1"); - assert.strictEqual(calls, 1); - }), -); - it.effect( "opening detail preserves enriched linked summaries and updates draft and diff fields", () => @@ -5240,7 +2738,7 @@ it.effect( project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequestSummary: () => Effect.succeed({ ...changeRequest(1, "2026-07-02T00:00:00Z"), @@ -5272,379 +2770,181 @@ it.effect( }), ); -it.effect("reuses an observed merged state for strict settlement reads", () => +it.effect("notifies linked threads when detail changes draft status in either direction", () => Effect.gen(function* () { + let isDraft = true; + let updatedAt = "2026-07-02T00:00:00Z"; 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequest: () => - Effect.succeed({ - ...hostedChangeRequest("merged body", 4), - state: "merged", - updatedAt: "2026-07-03T00:00:00Z", - }), - getChangeRequestSummary: () => Effect.die("strict merged state must not refresh"), + Effect.sync(() => ({ ...hostedChangeRequest("body"), isDraft, updatedAt })), }), ], }); + const changes = yield* service.subscribeStateChanges; + const read = () => service.detail({ ...reference, allowStale: false }); + yield* read(); + yield* read(); + isDraft = false; + yield* service.invalidate({ reference }); + yield* read(); + yield* read(); + isDraft = true; + yield* service.invalidate({ reference }); + yield* read(); - yield* service.detail(reference); + isDraft = false; + updatedAt = "2026-07-01T00:00:00Z"; + yield* service.invalidate({ reference }); + yield* read(); - const summary = yield* service.summary(reference, { recoverTransientFailure: false }); - assert.strictEqual(summary.state, "merged"); - assert.strictEqual(summary.updatedAt, "2026-07-03T00:00:00Z"); + // A different PR ends collection after all the synchronous notifications above. + yield* service.reportState({ reference: { ...reference, number: 2 }, state: "open" }); + const events = yield* Stream.runCollect( + changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })), + ); + assert.deepStrictEqual(events, [ + { host: "github.com", repository: "acme/web", number: 1 }, + { host: "github.com", repository: "acme/web", number: 1 }, + { host: "github.com", repository: "acme/web", number: 1 }, + ]); }), ); -it.effect("announces state a detail read sees first or newly", () => +it.effect("deduplicates routed PR reports without dropping draft changes", () => Effect.gen(function* () { - let detail = { - state: "open" as "open" | "closed" | "merged", - updatedAt: "2026-07-02T00:00:00Z", - }; - let summaryState: "open" | "merged" = "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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("body"), ...detail }), - getChangeRequestSummary: () => - Effect.succeed({ - ...changeRequest(1, "2026-07-04T00:00:00Z"), - state: summaryState, - }), - }), - ], - }); - const announced: Array = []; - yield* Stream.runForEach(yield* service.subscribeStateChanges, (key) => - Effect.sync(() => announced.push(`${key.host}/${key.repository}#${key.number}`)), - ).pipe(Effect.forkChild({ startImmediately: true })); - const readDetail = Effect.gen(function* () { - yield* service.invalidate({ reference }); - yield* service.detail(reference); - yield* Effect.yieldNow; + providers: [fakePullRequestProvider(SourceControlProviderKind.make("github"))], }); - - yield* readDetail; - yield* readDetail; - assert.deepStrictEqual(announced, ["github.com/acme/web#1"]); - - detail = { state: "closed", updatedAt: "2026-07-03T00:00:00Z" }; - yield* readDetail; - assert.strictEqual(announced.length, 2); - - summaryState = "merged"; - yield* service.summary(reference, { recoverTransientFailure: false }); - yield* Effect.yieldNow; - assert.strictEqual(announced.length, 2); - detail = { state: "merged", updatedAt: "2026-07-04T00:00:00Z" }; - yield* readDetail; - assert.strictEqual(announced.length, 3); - - detail = { state: "open", updatedAt: "2026-07-03T00:00:00Z" }; - yield* readDetail; - assert.strictEqual(announced.length, 3); + const changes = yield* service.subscribeStateChanges; + for (const isDraft of [true, true, false, false, true]) { + yield* service.reportState({ reference, state: "open", isDraft }); + } + yield* service.reportState({ reference, state: "open" }); + yield* service.reportState({ reference, state: "open" }); + yield* service.reportState({ reference: { ...reference, number: 2 }, state: "open" }); + const events = yield* Stream.runCollect( + changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })), + ); + assert.deepStrictEqual( + events.map((event) => event.number), + [1, 1, 1, 1], + ); }), ); -it.effect("announces a reported state without trusting it", () => +it.effect("preserves check observation time on cache hits and advances it on refresh", () => Effect.gen(function* () { - let detail = { state: "open" as "open" | "closed", updatedAt: "2026-07-02T00:00:00Z" }; + let reads = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => Effect.succeed({ ...hostedChangeRequest("body"), ...detail }), + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequestChecks: () => + Effect.sync(() => { + reads += 1; + return { state: "open" as const, checks: [] }; + }), }), ], }); - const announced: Array = []; - yield* Stream.runForEach(yield* service.subscribeStateChanges, (key) => - Effect.sync(() => announced.push(`${key.host}/${key.repository}#${key.number}`)), - ).pipe(Effect.forkChild({ startImmediately: true })); - const note = (state: "open" | "closed" | "merged") => - service.reportState({ reference, state }).pipe(Effect.andThen(Effect.yieldNow)); - const readDetail = Effect.gen(function* () { - yield* service.invalidate({ reference }); - yield* service.detail(reference); - yield* Effect.yieldNow; - }); - - yield* readDetail; - yield* note("closed"); - yield* note("closed"); - assert.strictEqual(announced.length, 2); - yield* TestClock.adjust("5 minutes"); - yield* note("closed"); - assert.strictEqual(announced.length, 3); - - yield* note("open"); - assert.strictEqual(announced.length, 4); - - yield* note("merged"); - detail = { state: "closed", updatedAt: "2026-07-03T00:00:00Z" }; - yield* readDetail; - assert.strictEqual(announced.length, 6); + yield* TestClock.setTime(1_000); + const first = yield* service.checks(reference); + expect(first).toMatchObject({ observedAt: 1_000 }); + yield* TestClock.adjust("1 second"); + expect(yield* service.checks(reference)).toEqual(first); + expect(reads).toBe(1); + yield* TestClock.adjust("15 seconds"); + expect(yield* service.checks(reference)).toMatchObject({ observedAt: 17_000 }); + expect(reads).toBe(2); }), ); -it.effect("does not let a stale detail reopen overwrite a fresher linked summary", () => +it.effect("reuses an observed merged state for strict settlement reads", () => Effect.gen(function* () { - const gate = yield* Deferred.make(); - let detailCalls = 0; - let summaryTitle = "old title"; - let summaryState: "open" | "merged" = "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: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { getChangeRequest: () => - Effect.gen(function* () { - detailCalls += 1; - if (detailCalls > 1) yield* Deferred.await(gate); - return hostedChangeRequest("old body", 4); - }), - getChangeRequestSummary: () => Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - title: summaryTitle, - state: summaryState, + ...hostedChangeRequest("merged body", 4), + state: "merged", + updatedAt: "2026-07-03T00:00:00Z", }), + getChangeRequestSummary: () => Effect.die("strict merged state must not refresh"), }), ], }); - const first = yield* service.detail(reference); - assert.strictEqual(first.title, "Change request 1"); - - summaryTitle = "merged title"; - summaryState = "merged"; - yield* TestClock.adjust("61 seconds"); - const settled = yield* service.summary(reference, { recoverTransientFailure: false }); - assert.strictEqual(settled.title, "merged title"); - assert.strictEqual(settled.state, "merged"); - - yield* TestClock.adjust("16 seconds"); - const stale = yield* service.detail(reference); - assert.strictEqual(stale.title, "Change request 1"); - yield* Effect.yieldNow; - - const display = yield* service.summary(reference); - assert.strictEqual(display.title, "merged title"); - assert.strictEqual(display.state, "merged"); - assert.strictEqual(detailCalls, 2); + yield* service.detail(reference); - summaryTitle = "updated after merge"; - yield* TestClock.adjust("61 seconds"); - assert.strictEqual((yield* service.summary(reference)).title, "merged title"); - const refreshed = yield* service.summary({ ...reference, allowStale: false }); - assert.strictEqual(refreshed.title, "updated after merge"); - assert.strictEqual(refreshed.state, "merged"); + const summary = yield* service.summary(reference, { recoverTransientFailure: false }); + assert.strictEqual(summary.state, "merged"); + assert.strictEqual(summary.updatedAt, "2026-07-03T00:00:00Z"); }), ); -it.effect("does not let a still-cached detail overwrite a fresher linked summary", () => +it.effect("does not let a stale detail reopen overwrite a fresher linked summary", () => Effect.gen(function* () { + const gate = yield* Deferred.make(); + let detailCalls = 0; let summaryTitle = "old title"; let summaryState: "open" | "merged" = "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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => Effect.succeed(hostedChangeRequest("old body", 4)), - getChangeRequestSummary: () => - Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - title: summaryTitle, - state: summaryState, - }), - }), - ], - }); - - const first = yield* service.detail(reference); - assert.strictEqual(first.title, "Change request 1"); - - summaryTitle = "merged title"; - summaryState = "merged"; - const settled = yield* service.summary(reference, { recoverTransientFailure: false }); - assert.strictEqual(settled.state, "merged"); - - const cached = yield* service.detail(reference); - assert.strictEqual(cached.title, "Change request 1"); - yield* Effect.yieldNow; - - const display = yield* service.summary(reference); - assert.strictEqual(display.title, "merged title"); - assert.strictEqual(display.state, "merged"); - }), -); - -it.effect("tells the client when the host has no pull request under that number", () => - Effect.gen(function* () { - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 121 }; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => - Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getChangeRequest", - reason: "not-found", - detail: "Pull request not found. Check the PR number or URL and try again.", - }), - ), - }), - ], - }); - - const error = yield* Effect.flip(service.detail(reference)); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.strictEqual(error._tag === "PullRequestOperationError" && error.reason, "not-found"); - }), -); - -it.effect("keeps recent detail on a transient refresh failure but not after invalidation", () => - Effect.gen(function* () { - let failing = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => - failing - ? Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getChangeRequest", - reason: "failed", - detail: "spawn gh EAGAIN", - }), - ) - : Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - body: "last good body", - changedFiles: 2, - mergedAt: null, - closedAt: null, - reviewers: [], - checks: [], - mergeCapabilities: { merge: true, squash: true, rebase: true }, - viewerPermissions: { - actions: ["merge"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }, - }), - }), - ], - }); - - yield* service.detail(reference); - yield* TestClock.adjust("61 seconds"); - failing = true; - const strict = yield* Effect.flip(service.detail({ ...reference, allowStale: false })); - assert.strictEqual(strict._tag, "PullRequestOperationError"); - const stale = yield* service.detail(reference); - assert.strictEqual(stale.body, "last good body"); - - yield* service.invalidate({ reference }); - const invalidated = yield* Effect.flip(service.detail(reference)); - assert.strictEqual(invalidated._tag, "PullRequestOperationError"); - }), -); - -it.effect("carries an armed auto-merge through to the detail, and silence as silence", () => - Effect.gen(function* () { - const detailWith = (autoMergeEnabled: boolean | undefined) => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => - Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - body: "", - changedFiles: 0, - mergedAt: null, - closedAt: null, - reviewers: [], - checks: [], - mergeCapabilities: { merge: true, squash: true, rebase: true }, - viewerPermissions: { - actions: ["merge"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }, - ...(autoMergeEnabled === undefined ? {} : { autoMergeEnabled }), - }), - }), - ], - }); - return yield* service.detail({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - }); - }); - - assert.strictEqual((yield* detailWith(true)).autoMergeEnabled, true); - assert.strictEqual((yield* detailWith(false)).autoMergeEnabled, false); - assert.isUndefined((yield* detailWith(undefined)).autoMergeEnabled); - }), -); - -it.effect("narrows the rows of a host that ignored the filters it was handed", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "web", - workspaceRoot: "/a", - repository: "acme/web", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - listChangeRequests: () => + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getChangeRequest: () => + Effect.gen(function* () { + detailCalls += 1; + if (detailCalls > 1) yield* Deferred.await(gate); + return hostedChangeRequest("old body", 4); + }), + getChangeRequestSummary: () => Effect.succeed({ - items: [ - { ...changeRequest(1, "2026-07-02T00:00:00Z"), isDraft: true }, - changeRequest(2, "2026-07-01T00:00:00Z"), - ], - truncated: false, - continues: false, + ...changeRequest(1, "2026-07-02T00:00:00Z"), + title: summaryTitle, + state: summaryState, }), }), ], }); - const result = yield* service.list({ state: "open", filters: { draft: "hide" } }); + const first = yield* service.detail(reference); + assert.strictEqual(first.title, "Change request 1"); - assert.deepStrictEqual( - result.entries.map((entry) => entry.number), - [2], - ); + summaryTitle = "merged title"; + summaryState = "merged"; + yield* TestClock.adjust("61 seconds"); + const settled = yield* service.summary(reference, { recoverTransientFailure: false }); + assert.strictEqual(settled.title, "merged title"); + assert.strictEqual(settled.state, "merged"); + + yield* TestClock.adjust("16 seconds"); + const stale = yield* service.detail(reference); + assert.strictEqual(stale.title, "Change request 1"); + yield* Effect.yieldNow; + + const display = yield* service.summary(reference); + assert.strictEqual(display.title, "merged title"); + assert.strictEqual(display.state, "merged"); + assert.strictEqual(detailCalls, 2); + + summaryTitle = "updated after merge"; + yield* TestClock.adjust("61 seconds"); + assert.strictEqual((yield* service.summary(reference)).title, "merged title"); + const refreshed = yield* service.summary({ ...reference, allowStale: false }); + assert.strictEqual(refreshed.title, "updated after merge"); + assert.strictEqual(refreshed.state, "merged"); }), ); @@ -5665,7 +2965,7 @@ it.effect("keeps a row of a host that ignored the filters if any name of a label }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { listChangeRequests: () => Effect.succeed({ items: [ @@ -5693,45 +2993,6 @@ it.effect("keeps a row of a host that ignored the filters if any name of a label }), ); -it.effect('resolves an author filter of "me" to the viewer before narrowing a host\'s rows', () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "web", - workspaceRoot: "/a", - repository: "acme/web", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - listChangeRequests: () => - Effect.succeed({ - items: [ - changeRequest(1, "2026-07-02T00:00:00Z"), - { - ...changeRequest(2, "2026-07-01T00:00:00Z"), - author: { login: "bilal", name: null, avatarUrl: null }, - }, - ], - truncated: false, - continues: false, - }), - }), - ], - }); - - const result = yield* service.list({ state: "open", filters: { author: "me" } }); - - assert.deepStrictEqual( - result.entries.map((entry) => entry.number), - [2], - ); - }), -); - it.effect.each([false, true])( "authorizes stack rebases and refreshes sibling layers (cross-host: %s)", (crossHost) => @@ -5767,7 +3028,7 @@ it.effect.each([false, true])( }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { capabilities, getViewerPermissions: () => Effect.succeed({ @@ -5813,564 +3074,257 @@ it.effect.each([false, true])( ); stackRebase = true; stackActions = false; - assert.strictEqual( - (yield* Effect.flip(service.runAction(input)))._tag, - "PullRequestOperationError", - ); - assert.strictEqual(taken, 1); - yield* service.summary(unrelated); - assert.strictEqual(summaryReads, 1); - stackActions = true; - mutationFails = true; - yield* Effect.flip(service.runAction(input)); - assert.strictEqual(taken, 2); - yield* service.summary(unrelated); - assert.strictEqual(summaryReads, 2); - }), -); - -it.effect("refuses a way of updating a branch that the host or the viewer does not allow", () => - Effect.gen(function* () { - let taken: string | null = null; - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge", "close", "update-branch"], - mergeMethods: ["merge"], - updateMethods: ["merge"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getViewerPermissions: () => - Effect.succeed({ - actions: ["close", "update-branch"], - comment: true, - resolve: true, - verdicts: ["comment"], - requestReviewers: false, - updateMethods: ["merge"], - }), - runAction: (input) => { - taken = input.updateMethod ?? "default"; - return Effect.void; - }, - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - - const error = yield* Effect.flip( - service.runAction({ ...reference, action: "update-branch", updateMethod: "rebase" }), - ); - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.strictEqual(taken, null); - - yield* service.runAction({ ...reference, action: "update-branch", updateMethod: "merge" }); - assert.strictEqual(taken, "merge"); - }), -); - -it.effect("refuses to merge a target branch into a source branch on a host that only rebases", () => - Effect.gen(function* () { - let taken = 0; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge", "close", "update-branch"], - mergeMethods: ["merge"], - updateMethods: ["rebase"], - search: true, - reactions: true, - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getViewerPermissions: () => - Effect.succeed({ - actions: ["close", "update-branch"], - comment: true, - resolve: true, - verdicts: ["comment"], - requestReviewers: false, - updateMethods: ["rebase"], - }), - runAction: () => { - taken += 1; - return Effect.void; - }, - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "group/project", number: 1 }; - - const error = yield* Effect.flip( - service.runAction({ ...reference, action: "update-branch", updateMethod: "merge" }), - ); - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.strictEqual(taken, 0); - - yield* service.runAction({ ...reference, action: "update-branch", updateMethod: "rebase" }); - assert.strictEqual(taken, 1); - }), -); - -it.effect("judges the review filter only on a host that summarises its reviews", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - project({ - id: "p2", - title: "on gitlab", - workspaceRoot: "/b", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - listChangeRequests: () => - Effect.succeed({ - items: [ - { ...changeRequest(1, "2026-07-02T00:00:00Z"), reviewDecision: null }, - { - ...changeRequest(2, "2026-07-02T00:00:00Z"), - reviewDecision: "approved" as const, - }, - ], - truncated: false, - continues: true, - }), - }), - fakeProvider(SourceControlProviderKind.make("gitlab"), { - listChangeRequests: () => - Effect.succeed({ - items: [changeRequest(3, "2026-07-02T00:00:00Z")], - truncated: false, - continues: true, - }), - }), - ], - }); - - const none = yield* service.list({ state: "open", filters: { review: "none" } }); - assert.deepStrictEqual(none.entries.map((entry) => entry.number).toSorted(), [1, 3]); - - const approved = yield* service.list({ state: "open", filters: { review: "approved" } }); - assert.deepStrictEqual(approved.entries.map((entry) => entry.number).toSorted(), [2, 3]); - }), -); - -it.effect("sends only the words a rewrite carries", () => - Effect.gen(function* () { - const received: Array<{ title?: string | undefined; body?: string | undefined }> = []; - 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - updateChangeRequest: (input) => { - received.push({ title: input.title, body: input.body }); - return Effect.void; - }, - }), - ], - }); - - yield* service.update({ ...reference, title: "A better title" }); - yield* service.update({ ...reference, body: "" }); - yield* service.update({ ...reference, title: "Both", body: "at once" }); - - assert.deepStrictEqual(received, [ - { title: "A better title", body: undefined }, - { title: undefined, body: "" }, - { title: "Both", body: "at once" }, - ]); - }), -); - -it.effect("refuses a rewrite that changes nothing, before any call is made", () => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - updateChangeRequest: () => Effect.die("must not be called"), - }), - ], - }); - - const error = yield* Effect.flip( - service.update({ projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }), - ); - - assert.strictEqual(error._tag, "PullRequestOperationError"); - assert.include(error.message, "Nothing was changed."); - }), + assert.strictEqual( + (yield* Effect.flip(service.runAction(input)))._tag, + "PullRequestOperationError", + ); + assert.strictEqual(taken, 1); + yield* service.summary(unrelated); + assert.strictEqual(summaryReads, 1); + stackActions = true; + mutationFails = true; + yield* Effect.flip(service.runAction(input)); + assert.strictEqual(taken, 2); + yield* service.summary(unrelated); + assert.strictEqual(summaryReads, 2); + }), ); -it.effect("refuses to rewrite anything on a host that never claimed it", () => +it.effect("refuses a way of updating a branch that the host or the viewer does not allow", () => Effect.gen(function* () { + let taken: string | null = null; const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { capabilities: { diff: true, comment: true, - actions: ["merge"], + actions: ["merge", "close", "update-branch"], mergeMethods: ["merge"], + updateMethods: ["merge"], search: true, reactions: true, review: FULL_REVIEW, reviewers: FULL_REVIEWERS, }, - updateChangeRequest: () => Effect.die("must not be called"), - updateComment: () => Effect.die("must not be called"), + getViewerPermissions: () => + Effect.succeed({ + actions: ["close", "update-branch"], + comment: true, + resolve: true, + verdicts: ["comment"], + requestReviewers: false, + updateMethods: ["merge"], + }), + runAction: (input) => { + taken = input.updateMethod ?? "default"; + return Effect.void; + }, }), ], }); const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const rewriteRefused = yield* Effect.flip(service.update({ ...reference, title: "New" })); - const commentRefused = yield* Effect.flip( - service.updateComment({ - ...reference, - commentId: "IC_1", - kind: "issue-comment", - body: "New", - }), + const error = yield* Effect.flip( + service.runAction({ ...reference, action: "update-branch", updateMethod: "rebase" }), ); + assert.strictEqual(error._tag, "PullRequestOperationError"); + assert.strictEqual(taken, null); - assert.include(rewriteRefused.message, "cannot rewrite a change request."); - assert.include(commentRefused.message, "cannot rewrite a comment."); + yield* service.runAction({ ...reference, action: "update-branch", updateMethod: "merge" }); + assert.strictEqual(taken, "merge"); }), ); -it.effect("passes a rewritten remark through with the id and kind it arrived under", () => +it.effect("keeps reading a host's thinned-out slices until a filtered page is full", () => Effect.gen(function* () { - let received: { id: string; kind: string; body: string } | null = null; + const reads: Array = []; + const rows = Array.from({ length: 40 }, (_, index) => ({ + ...changeRequest(index + 1, `2026-07-${String(40 - index).padStart(2, "0")}T00:00:00Z`), + labels: index % 2 === 0 ? [{ name: "bug", color: null }] : [], + })); const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + projects: [ + project({ + id: "p1", + title: "on gitlab", + workspaceRoot: "/a", + repository: "group/project", + provider: SourceControlProviderKind.make("gitlab"), + }), + ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - updateComment: (input) => { - received = { id: input.commentId, kind: input.kind, body: input.body }; - return Effect.void; + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + listChangeRequests: (input) => { + const delivered = input.cursor?.delivered ?? 0; + reads.push(delivered); + return Effect.succeed({ + items: rows.slice(delivered, delivered + input.limit), + truncated: delivered + input.limit < rows.length, + continues: true, + }); }, }), ], }); - yield* service.updateComment({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - commentId: "PRRC_1", - kind: "review-comment", - body: "Second thoughts", - }); + const bugs = yield* service.list({ state: "open", limit: 4, filters: { labels: [["bug"]] } }); + assert.deepStrictEqual( + bugs.entries.map((entry) => entry.number), + [1, 3, 5, 7], + ); + assert.deepStrictEqual(reads, [0, 4]); - assert.deepStrictEqual(received, { - id: "PRRC_1", - kind: "review-comment", - body: "Second thoughts", + reads.length = 0; + const none = yield* service.list({ + state: "open", + limit: 4, + filters: { labels: [["missing"]] }, }); + assert.deepStrictEqual(none.entries, []); + assert.strictEqual(reads.length, 5); + assert.match(Object.values(none.nextCursors)[0] ?? "", /\|20\|/); }), ); -it.effect("refuses a remark rewritten into nothing but whitespace", () => +it.effect("hands a host's own resume position back on the next read", () => Effect.gen(function* () { + const resumed: Array = []; const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - updateComment: () => Effect.die("must not be called"), + projects: [ + project({ + id: "p1", + title: "on gitlab", + workspaceRoot: "/a", + repository: "group/project", + provider: SourceControlProviderKind.make("gitlab"), }), ], - }); - - const error = yield* Effect.flip( - service.updateComment({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - commentId: "IC_1", - kind: "issue-comment", - body: " \n ", - }), - ); - - assert.include(error.message, "A comment cannot be empty."); - }), -); - -it.effect("forgets the cached detail after a rewrite or terminal turn", () => - Effect.gen(function* () { - let coreCalls = 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: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => { - coreCalls += 1; + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + listChangeRequests: (input) => { + resumed.push(input.cursor?.resumeAfter); return Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - body: "", - changedFiles: 0, - mergedAt: null, - closedAt: null, - reviewers: [], - checks: [], - mergeCapabilities: { merge: true, squash: true, rebase: true }, - viewerPermissions: { - actions: ["merge"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }, + items: [changeRequest(resumed.length, "2026-07-02T00:00:00Z")], + truncated: true, + continues: true, + resumeAfter: `2026-07-01T00:00:00.000Z~${resumed.length}`, }); }, }), ], }); - yield* service.detail(reference); - yield* service.update({ ...reference, title: "Renamed" }); - yield* service.detail(reference); - assert.strictEqual(coreCalls, 2); - - yield* service.refreshAfterTurn("p1" as ProjectId); - yield* service.detail(reference); - assert.strictEqual(coreCalls, 3); - }), -); - -it.effect("names the signed-in account in the detail, and says nothing where the host cannot", () => - Effect.gen(function* () { - const detailFrom = (provider: PullRequestProviderApi) => - Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), - ], - providers: [provider], - }); - return yield* service.detail({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - }); - }); - const readable = fakeProvider(SourceControlProviderKind.make("github"), { - getChangeRequest: () => - Effect.succeed({ - ...changeRequest(1, "2026-07-02T00:00:00Z"), - body: "", - changedFiles: 0, - mergedAt: null, - closedAt: null, - reviewers: [], - checks: [], - mergeCapabilities: { merge: true, squash: true, rebase: true }, - viewerPermissions: { - actions: ["merge"], - comment: true, - resolve: true, - verdicts: ["comment", "approve", "request-changes"], - requestReviewers: true, - }, - }), - }); - - const named = yield* detailFrom(readable); - const unnamed = yield* detailFrom({ - ...readable, - getViewer: () => - Effect.fail(unusable(SourceControlProviderKind.make("github"), "unauthenticated")), - }); - - assert.strictEqual(named.viewer, "bilal"); - assert.strictEqual(unnamed.viewer, undefined); + const first = yield* service.list({ state: "open", limit: 1 }); + yield* service.list({ state: "open", limit: 1, cursors: first.nextCursors }); + assert.deepStrictEqual(resumed, [undefined, "2026-07-01T00:00:00.000Z~1"]); }), ); -it.effect("keeps the diff cached across a file being ticked off", () => +it.effect("judges the review filter only on a host that summarises its reviews", () => Effect.gen(function* () { - let diffReads = 0; - let viewedReads = 0; - let state: "viewed" | "dismissed" = "viewed"; const service = yield* makeService({ projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + project({ + id: "p2", + title: "on gitlab", + workspaceRoot: "/b", + repository: "group/project", + provider: SourceControlProviderKind.make("gitlab"), + }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - viewedFiles: "host", - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getDiff: () => { - diffReads += 1; - return Effect.succeed({ patch: "@@", truncated: false, nextCursor: null }); - }, - getFilesViewed: () => { - viewedReads += 1; - return Effect.succeed({ - files: [{ path: "src/a.ts", state }], + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + listChangeRequests: () => + Effect.succeed({ + items: [ + { ...changeRequest(1, "2026-07-02T00:00:00Z"), reviewDecision: null }, + { + ...changeRequest(2, "2026-07-02T00:00:00Z"), + reviewDecision: "approved" as const, + }, + ], truncated: false, - }); - }, - setFilesViewed: () => Effect.void, + continues: true, + }), + }), + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + listChangeRequests: () => + Effect.succeed({ + items: [changeRequest(3, "2026-07-02T00:00:00Z")], + truncated: false, + continues: true, + }), }), ], }); - const reference = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 }; - - yield* service.diff(reference); - yield* service.filesViewed(reference); - yield* service.setFilesViewed({ ...reference, files: [{ path: "src/a.ts", viewed: false }] }); - yield* service.diff(reference); - yield* service.filesViewed(reference); - assert.strictEqual(diffReads, 1); - assert.strictEqual(viewedReads, 2); + const none = yield* service.list({ state: "open", filters: { review: "none" } }); + assert.deepStrictEqual(none.entries.map((entry) => entry.number).toSorted(), [1, 3]); - state = "dismissed"; - yield* service.invalidate({ reference, filesViewedOnly: true }); - yield* service.diff(reference); - assert.deepStrictEqual((yield* service.filesViewed(reference)).files, [ - { path: "src/a.ts", state: "dismissed" }, - ]); - assert.strictEqual(diffReads, 1); - assert.strictEqual(viewedReads, 3); + const approved = yield* service.list({ state: "open", filters: { review: "approved" } }); + assert.deepStrictEqual(approved.entries.map((entry) => entry.number).toSorted(), [2, 3]); }), ); -it.effect("returns large diff slices intact without retaining them in either cache", () => +it.effect("partial host viewed writes invalidate marks but keep the diff cached", () => Effect.gen(function* () { - let reads = 0; - const patch = "\u{1f4bb}".repeat(140_000); + let diffReads = 0; + const states = new Map([ + ["a.ts", "unviewed"], + ["b.ts", "unviewed"], + ]); const service = yield* makeService({ projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + capabilities: { + ...fakePullRequestProvider(SourceControlProviderKind.make("github")).capabilities, + viewedFiles: "host", + }, getDiff: () => Effect.sync(() => { - reads += 1; - return { patch, truncated: false, nextCursor: "2" }; + diffReads += 1; + return { patch: "@@", truncated: false, nextCursor: null }; }), - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - for (const input of [ - reference, - { ...reference, cursor: "2" }, - { ...reference, commit: "a".repeat(40) }, - ]) { - const before = reads; - assert.deepStrictEqual(yield* service.diff(input), { - patch, - truncated: false, - nextCursor: "2", - }); - assert.deepStrictEqual(yield* service.diff(input), { - patch, - truncated: false, - nextCursor: "2", - }); - assert.strictEqual(reads, before + 2); - } - }), -); - -it.effect("caches a small replacement after releasing a large diff", () => - Effect.gen(function* () { - let reads = 0; - const largePatch = "x".repeat(300_000); - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getDiff: () => - Effect.sync(() => { - reads += 1; - return { - patch: reads === 1 ? largePatch : "@@ small replacement", - truncated: false, - nextCursor: null, - }; + getFilesViewed: () => + Effect.sync(() => ({ + files: [...states].map(([path, state]) => ({ path, state })), + truncated: false, + })), + setFilesViewed: () => + Effect.gen(function* () { + states.set("a.ts", "viewed"); + return yield* new PullRequestProviderError({ + provider: SourceControlProviderKind.make("github"), + operation: "setFilesViewed", + reason: "failed", + detail: "Second mutation refused", + }); }), }), ], }); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - assert.strictEqual((yield* service.diff(reference)).patch, largePatch); - assert.strictEqual((yield* service.diff(reference)).patch, "@@ small replacement"); - assert.strictEqual((yield* service.diff(reference)).patch, "@@ small replacement"); - assert.strictEqual(reads, 2); - }), -); - -it.effect("releases an expired diff nobody reads again", () => - Effect.gen(function* () { - NodeV8.setFlagsFromString("--expose-gc"); - const collect = NodeVM.runInNewContext("gc") as () => void; - const settle = Effect.promise(async () => { - // A weak reference keeps its target for the rest of the job that created it. - await new Promise((resolve) => setImmediate(resolve)); - collect(); - }); - const service = yield* makeService({ - projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getDiff: () => Effect.sync(() => ({ patch: "@@", truncated: false, nextCursor: null })), - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; - const read = (input: Parameters[0]) => - Effect.map(service.diff(input), (result) => new WeakRef(result)); - const page = yield* read(reference); - const commit = yield* read({ ...reference, commit: "a".repeat(40) }); - - yield* TestClock.adjust("9 minutes"); - yield* settle; - assert.isDefined(page.deref()); - assert.isDefined(commit.deref()); - - yield* TestClock.adjust("2 minutes"); - yield* settle; - assert.isUndefined(page.deref()); - assert.isUndefined(commit.deref()); + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 10 }; + yield* service.diff(ref); + assert.deepStrictEqual((yield* service.filesViewed(ref)).files, [ + { path: "a.ts", state: "unviewed" }, + { path: "b.ts", state: "unviewed" }, + ]); + yield* Effect.flip( + service.setFilesViewed({ + ...ref, + files: [...states.keys()].map((path) => ({ path, viewed: true })), + }), + ); + yield* service.diff(ref); + assert.strictEqual(diffReads, 1); + assert.deepStrictEqual((yield* service.filesViewed(ref)).files, [ + { path: "a.ts", state: "viewed" }, + { path: "b.ts", state: "unviewed" }, + ]); }), ); @@ -6379,7 +3333,7 @@ const environmentViewedProvider = ( asked: Array>, unreadable: ReadonlySet = new Set(), ) => - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { capabilities: { diff: true, comment: true, @@ -6430,73 +3384,54 @@ const GITLAB_REFERENCE = { number: 1, }; -it.effect("tracks Forgejo viewed files through its diff and refuses truncated baselines", () => +it.effect("tracks environment viewed files by revision and refuses a baseline it cannot read", () => Effect.gen(function* () { - let alpha = "b485fe5"; - let truncated = false; - let diffReads = 0; - const provider = yield* ForgejoPullRequestProvider.make.pipe( - Effect.provide( - Layer.mock(ForgejoCli.ForgejoCli)({ - api: (input) => { - assert.strictEqual(input.host, "forge.example:3000"); - const viewer = input.path === "user"; - if (!viewer) { - assert.strictEqual(input.repository, "reviewer/project"); - assert.strictEqual(input.path, "repos/reviewer/project/pulls/1.diff"); - diffReads++; - } - return Effect.succeed({ - exitCode: ChildProcessSpawner.ExitCode(0), - stdout: viewer - ? JSON.stringify({ login: "reviewer" }) - : truncated - ? `diff --git a/alpha.ts b/alpha.ts\nindex eb2d7c5..${alpha} 100644\n` - : [ - "diff --git a/alpha.ts b/alpha.ts", - `index eb2d7c5..${alpha} 100644`, - "diff --git a/beta.ts b/beta.ts", - "index b39e8b3..5851425 100644", - 'diff --git "a/caf\\303\\251 notes.txt" "b/caf\\303\\251 notes.txt"', - "index ffd99ce..6dd9855 100644", - "diff --git a/deleted.txt b/deleted.txt", - "deleted file mode 100644", - "index 233f5c6..0000000", - "diff --git a/old.txt b/renamed.txt", - "similarity index 100%", - "rename from old.txt", - "rename to renamed.txt", - "", - ].join("\n"), - stderr: "", - stdoutTruncated: !viewer && truncated, - stderrTruncated: false, - }); - }, - }), - ), - ); + const revisions = new Map([ + ["alpha.ts", "b485fe5"], + ["beta.ts", "5851425"], + ["café notes.txt", "6dd9855"], + ["deleted.txt", "0000000"], + ["renamed.txt", ""], + ]); + let unreadable = false; + let revisionReads = 0; const service = yield* makeService({ projects: [ project({ - id: "forgejo", - title: "on forgejo", - workspaceRoot: "/forgejo", - repository: "reviewer/project", - provider: SourceControlProviderKind.make("forgejo"), - host: "forge.example:3000", - remoteUrl: "http://forge.example:3000/reviewer/project.git", + id: "p1", + title: "on gitlab", + workspaceRoot: "/a", + repository: "group/project", + provider: SourceControlProviderKind.make("gitlab"), }), ], - providers: [provider], + providers: [ + { + ...environmentViewedProvider(revisions, []), + getFileRevisions: (input) => + Effect.suspend(() => { + revisionReads++; + return unreadable + ? Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("gitlab"), + operation: "getFileRevisions", + reason: "failed", + detail: "The diff exceeded the output limit.", + }), + ) + : Effect.succeed({ + revisions: new Map( + input.paths.map((path) => [path, revisions.get(path) ?? ""] as const), + ), + complete: true, + }); + }), + }, + ], }); - const reference = { - projectId: "forgejo" as ProjectId, - repository: "reviewer/project", - host: "forge.example:3000", - number: 1, - }; - const paths = ["alpha.ts", "beta.ts", "café notes.txt", "deleted.txt", "renamed.txt"]; + const reference = GITLAB_REFERENCE; + const paths = [...revisions.keys()]; yield* service.setFilesViewed({ ...reference, files: paths.map((path) => ({ path, viewed: true })), @@ -6505,9 +3440,9 @@ it.effect("tracks Forgejo viewed files through its diff and refuses truncated ba new Map((yield* service.filesViewed(reference)).files.map((file) => [file.path, file.state])), new Map(paths.map((path) => [path, "viewed"])), ); - assert.strictEqual(diffReads, 1); + assert.strictEqual(revisionReads, 1); - alpha = "aabbccd"; + revisions.set("alpha.ts", "aabbccd"); yield* service.invalidate({ reference }); assert.deepStrictEqual( new Map((yield* service.filesViewed(reference)).files.map((file) => [file.path, file.state])), @@ -6521,13 +3456,13 @@ it.effect("tracks Forgejo viewed files through its diff and refuses truncated ba (yield* service.filesViewed(reference)).files.some((file) => file.path === "beta.ts"), ); - truncated = true; + unreadable = true; yield* service.invalidate({ reference }); yield* service.setFilesViewed({ ...reference, files: [{ path: "beta.ts", viewed: true }], }); - truncated = false; + unreadable = false; yield* service.invalidate({ reference }); assert.deepStrictEqual( (yield* service.filesViewed(reference)).files.find((file) => file.path === "beta.ts"), @@ -6658,176 +3593,6 @@ it.effect("keeps viewed files itself for a host that keeps none of its own", () }), ); -it.effect("holds what a whole-change answer carried, so the next tick reads nothing", () => - Effect.gen(function* () { - const asked: Array> = []; - const head = new Map([ - ["src/a.ts", "blob-a"], - ["src/b.ts", "blob-b"], - ]); - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - { - ...environmentViewedProvider(head, []), - getFileRevisions: (input) => { - asked.push(input.paths); - return Effect.succeed({ revisions: head, complete: true }); - }, - }, - ], - }); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }); - - assert.deepStrictEqual(asked, [["src/a.ts"]]); - const marked = yield* service.filesViewed(GITLAB_REFERENCE); - assert.deepStrictEqual( - [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)), - [ - { path: "src/a.ts", state: "viewed" }, - { path: "src/b.ts", state: "viewed" }, - ], - ); - - yield* TestClock.adjust("2 minutes"); - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }); - assert.deepStrictEqual(asked, [["src/a.ts"], ["src/b.ts"]]); - }), -); - -it.effect("reads the marks without asking the host what the head has every time", () => - Effect.gen(function* () { - const asked: Array> = []; - const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), asked); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - yield* TestClock.adjust("20 seconds"); - const marked = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual(marked.files, [{ path: "src/a.ts", state: "viewed" }]); - assert.deepStrictEqual(asked, [["src/a.ts"]]); - }), -); - -it.effect("answers the marks from what it last heard while it asks the host again", () => - Effect.gen(function* () { - const asked: Array> = []; - const revisions = new Map([["src/a.ts", "blob-a"]]); - const service = yield* environmentViewedService(revisions, asked); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - revisions.set("src/a.ts", "blob-a-again"); - yield* TestClock.adjust("90 seconds"); - const held = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual(held.files, [{ path: "src/a.ts", state: "viewed" }]); - assert.strictEqual(asked.length, 2); - - yield* TestClock.adjust("20 seconds"); - const caught = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual(caught.files, [{ path: "src/a.ts", state: "dismissed" }]); - assert.strictEqual(asked.length, 2); - }), -); - -it.effect("asks the host about a file it has not been asked about before", () => - Effect.gen(function* () { - const asked: Array> = []; - const service = yield* environmentViewedService( - new Map([ - ["src/a.ts", "blob-a"], - ["src/b.ts", "blob-b"], - ]), - asked, - ); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - yield* TestClock.adjust("20 seconds"); - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }); - yield* TestClock.adjust("20 seconds"); - const marked = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual( - [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)), - [ - { path: "src/a.ts", state: "viewed" }, - { path: "src/b.ts", state: "viewed" }, - ], - ); - assert.deepStrictEqual(asked, [["src/a.ts"], ["src/b.ts"]]); - }), -); - -it.effect("does not let a press about one file keep another file's version alive", () => - Effect.gen(function* () { - const asked: Array> = []; - const revisions = new Map([ - ["src/a.ts", "blob-a"], - ["src/b.ts", "blob-b"], - ]); - const service = yield* environmentViewedService(revisions, asked); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - yield* TestClock.adjust("40 seconds"); - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }); - assert.deepStrictEqual(asked, [["src/a.ts"], ["src/b.ts"]]); - - revisions.set("src/a.ts", "blob-a-again"); - yield* TestClock.adjust("30 seconds"); - yield* service.filesViewed(GITLAB_REFERENCE); - assert.strictEqual(asked.length, 3); - - yield* TestClock.adjust("20 seconds"); - const caught = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual( - [...caught.files].toSorted((left, right) => left.path.localeCompare(right.path)), - [ - { path: "src/a.ts", state: "dismissed" }, - { path: "src/b.ts", state: "viewed" }, - ], - ); - }), -); - it.effect("reports a file pushed to since it was cleared as changed", () => Effect.gen(function* () { const revisions = new Map([ @@ -6857,26 +3622,6 @@ it.effect("reports a file pushed to since it was cleared as changed", () => }), ); -it.effect("clears a mark again when the file is put back", () => - Effect.gen(function* () { - const asked: Array> = []; - const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), asked); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: false }], - }); - const marked = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual(marked.files, []); - assert.deepStrictEqual(asked, [["src/a.ts"]]); - }), -); - it.effect("keeps a deleted file cleared, which the head has no version of at all", () => Effect.gen(function* () { const service = yield* environmentViewedService(new Map(), []); @@ -6915,146 +3660,30 @@ it.effect("leaves a mark alone when the host could not say what the head has of yield* service.invalidate({ reference: GITLAB_REFERENCE }); const marked = yield* service.filesViewed(GITLAB_REFERENCE); - assert.deepStrictEqual( - [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)), - [ - { path: "src/a.ts", state: "dismissed" }, - { path: "src/past-the-cut.ts", state: "viewed" }, - ], - ); - }), -); - -it.effect("keeps a file cleared that the press could not learn a version for", () => - Effect.gen(function* () { - const revisions = new Map([["src/past-the-cut.ts", "blob-b"]]); - const unreadable = new Set(["src/past-the-cut.ts"]); - const service = yield* environmentViewedService(revisions, [], unreadable); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/past-the-cut.ts", viewed: true }], - }); - unreadable.delete("src/past-the-cut.ts"); - yield* service.invalidate({ reference: GITLAB_REFERENCE }); - - assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/past-the-cut.ts", state: "viewed" }, - ]); - }), -); - -it.effect("keeps the version it last heard when a later read of the head stops short", () => - Effect.gen(function* () { - const asked: Array> = []; - const revisions = new Map([["src/a.ts", "blob-a"]]); - const unreadable = new Set(); - const service = yield* environmentViewedService(revisions, asked, unreadable); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - revisions.set("src/a.ts", "blob-a-again"); - yield* service.invalidate({ reference: GITLAB_REFERENCE }); - assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/a.ts", state: "dismissed" }, - ]); - - unreadable.add("src/a.ts"); - yield* TestClock.adjust("90 seconds"); - yield* service.filesViewed(GITLAB_REFERENCE); - yield* TestClock.adjust("20 seconds"); - - assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/a.ts", state: "dismissed" }, - ]); - }), -); - -it.effect("re-asks what the head has of a marked file after a whole-workspace refresh", () => - Effect.gen(function* () { - const revisions = new Map([["src/a.ts", "blob-a"]]); - const service = yield* environmentViewedService(revisions, []); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - revisions.set("src/a.ts", "blob-a-again"); - yield* service.invalidate({}); - - assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/a.ts", state: "dismissed" }, - ]); - }), -); - -it.effect("forgets what the head had of a marked file once a mutation moves the head", () => - Effect.gen(function* () { - const revisions = new Map([["src/a.ts", "blob-a"]]); - const service = yield* environmentViewedService(revisions, []); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - revisions.set("src/a.ts", "blob-a-again"); - yield* service.runAction({ ...GITLAB_REFERENCE, action: "merge" }); - - assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/a.ts", state: "dismissed" }, - ]); - }), -); - -it.effect("still reports its own marks when the host will not say what the head has", () => - Effect.gen(function* () { - let answering = true; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - capabilities: { - diff: true, - comment: true, - actions: ["merge"], - mergeMethods: ["merge"], - search: true, - reactions: true, - viewedFiles: "environment", - review: FULL_REVIEW, - reviewers: FULL_REVIEWERS, - }, - getFilesViewed: () => Effect.die("the host keeps no marks of its own"), - setFilesViewed: () => Effect.die("the host keeps no marks of its own"), - getFileRevisions: (input) => - answering - ? Effect.succeed({ - revisions: new Map(input.paths.map((path) => [path, "blob-a"] as const)), - }) - : Effect.fail(requestFailed), - }), + assert.deepStrictEqual( + [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)), + [ + { path: "src/a.ts", state: "dismissed" }, + { path: "src/past-the-cut.ts", state: "viewed" }, ], - }); + ); + }), +); + +it.effect("forgets what the head had of a marked file once a mutation moves the head", () => + Effect.gen(function* () { + const revisions = new Map([["src/a.ts", "blob-a"]]); + const service = yield* environmentViewedService(revisions, []); yield* service.setFilesViewed({ ...GITLAB_REFERENCE, files: [{ path: "src/a.ts", viewed: true }], }); - answering = false; - yield* service.invalidate({ reference: GITLAB_REFERENCE }); + revisions.set("src/a.ts", "blob-a-again"); + yield* service.runAction({ ...GITLAB_REFERENCE, action: "merge" }); assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/a.ts", state: "viewed" }, + { path: "src/a.ts", state: "dismissed" }, ]); }), ); @@ -7073,7 +3702,7 @@ it.effect("finishes two presses on one file in the order they were made", () => }), ], providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { capabilities: { diff: true, comment: true, @@ -7122,7 +3751,8 @@ const azureViewedService = (projects: ReadonlyArray) makeService({ projects, providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + ...keyedByCanonicalKey, capabilities: { diff: true, comment: true, @@ -7194,97 +3824,6 @@ it.effect("keeps environment marks apart from another change request's", () => }), ); -it.effect("bounds the paths one change request's held revisions carry", () => - Effect.gen(function* () { - const asked: Array> = []; - const service = yield* environmentViewedService(new Map(), asked); - const batch = (prefix: string, count: number) => - Array.from({ length: count }, (_, index) => ({ - path: `${prefix}/${String(index).padStart(4, "0")}.ts`, - viewed: true, - })); - const press = (prefix: string, count: number) => - service.setFilesViewed({ ...GITLAB_REFERENCE, files: batch(prefix, count) }); - - yield* press("a", MAX_FILE_REVISION_PATHS / 2); - yield* press("b", MAX_FILE_REVISION_PATHS / 2); - yield* press("c", 1); - const pressed = asked.length; - - yield* service.filesViewed(GITLAB_REFERENCE); - - assert.strictEqual(asked.length, pressed + 1); - assert.ok(asked.at(-1)?.includes("a/0000.ts")); - }), -); - -it.effect("keeps the marked paths when a whole-change answer is wider than the cap", () => - Effect.gen(function* () { - const head = new Map( - Array.from( - { length: MAX_FILE_REVISION_PATHS + 178 }, - (_, index) => - [`src/f${String(index).padStart(4, "0")}.ts`, `blob-${String(index)}`] as const, - ), - ); - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - { - ...environmentViewedProvider(head, []), - getFileRevisions: () => Effect.succeed({ revisions: head, complete: true }), - }, - ], - }); - const ticked = ["src/f0000.ts", "src/f0500.ts"]; - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: ticked.map((path) => ({ path, viewed: true })), - }); - for (const path of ticked) head.set(path, "blob-moved"); - yield* TestClock.adjust("11 minutes"); - const marked = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.deepStrictEqual( - [...marked.files].toSorted((left, right) => left.path.localeCompare(right.path)), - [ - { path: "src/f0000.ts", state: "dismissed" }, - { path: "src/f0500.ts", state: "dismissed" }, - ], - ); - }), -); - -it.effect("keeps the change request being ticked through, not the one pressed first", () => - Effect.gen(function* () { - const asked: Array> = []; - const service = yield* environmentViewedService(new Map([["src/a.ts", "blob-a"]]), asked); - const press = (number: number) => - service.setFilesViewed({ - ...GITLAB_REFERENCE, - number, - files: [{ path: "src/a.ts", viewed: true }], - }); - - yield* press(1); - for (let filled = 0; filled < FILE_REVISIONS_CACHE_CAPACITY; filled += 1) { - yield* press(2 + filled); - yield* press(1); - } - - assert.strictEqual(asked.length, 1 + FILE_REVISIONS_CACHE_CAPACITY); - }), -); - const environmentViewedServiceWithViewer = ( revisions: Map, getViewer: PullRequestProviderApi["getViewer"], @@ -7302,320 +3841,44 @@ const environmentViewedServiceWithViewer = ( providers: [{ ...environmentViewedProvider(revisions, []), getViewer }], }); -it.effect("keeps one reader's marks on a host that names nobody", () => - Effect.gen(function* () { - const service = yield* environmentViewedServiceWithViewer( - new Map([["src/a.ts", "blob-a"]]), - () => Effect.succeed(""), - ); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - - assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ - { path: "src/a.ts", state: "viewed" }, - ]); - }), -); - -it.effect("puts a listing and a press for one host on a single viewer lookup", () => - Effect.gen(function* () { - let viewerLookups = 0; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - { - ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []), - getViewer: () => - Effect.gen(function* () { - viewerLookups += 1; - yield* Effect.yieldNow; - return "bilal"; - }), - }, - ], - }); - - yield* Effect.all([service.list({ state: "open" }), service.filesViewed(GITLAB_REFERENCE)], { - concurrency: 2, - }); - - assert.strictEqual(viewerLookups, 1); - }), -); - -it.effect("carries a bounded number of its own marks and says it held more", () => - Effect.gen(function* () { - const asked: Array> = []; - const paths = Array.from( - { length: PullRequestFilesViewed.MAX_FILES_VIEWED_ROWS + 40 }, - (_, at) => `src/f${String(at).padStart(4, "0")}.ts`, - ); - const service = yield* environmentViewedService( - new Map(paths.map((path) => [path, "blob"] as const)), - asked, - ); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: paths.map((path) => ({ path, viewed: true })), - }); - const read = yield* service.filesViewed(GITLAB_REFERENCE); - - assert.lengthOf(read.files, PullRequestFilesViewed.MAX_FILES_VIEWED_ROWS); - assert.strictEqual(read.truncated, true); - }), -); - -it.effect("records a press while the host is backing off", () => - Effect.gen(function* () { - let viewerLookups = 0; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - { - ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []), - getViewer: () => - Effect.sync(() => { - viewerLookups += 1; - return "bilal"; - }), - getFileRevisions: () => - Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("gitlab"), - operation: "getFileRevisions", - reason: "rate-limited", - detail: "API rate limit exceeded.", - retryAt: 60 * 60 * 1_000, - }), - ), - }, - ], - }); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - yield* TestClock.adjust("11 minutes"); - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }); - - assert.deepStrictEqual( - [...(yield* service.filesViewed(GITLAB_REFERENCE)).files].toSorted((left, right) => - left.path.localeCompare(right.path), - ), - [ - { path: "src/a.ts", state: "viewed" }, - { path: "src/b.ts", state: "viewed" }, - ], - ); - assert.strictEqual(viewerLookups, 2); - }), -); - -it.effect("asks who is reading through a pause only for the press that is waiting on it", () => - Effect.gen(function* () { - let viewerLookups = 0; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - { - ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []), - getViewer: () => - Effect.sync(() => { - viewerLookups += 1; - return "bilal"; - }), - listChangeRequests: () => - Effect.succeed({ items: [], truncated: false, continues: true }), - getFileRevisions: () => - Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("gitlab"), - operation: "getFileRevisions", - reason: "rate-limited", - detail: "API rate limit exceeded.", - retryAt: 60 * 60 * 1_000, - }), - ), - }, - ], - }); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/a.ts", viewed: true }], - }); - assert.strictEqual(viewerLookups, 1); - yield* TestClock.adjust("11 minutes"); - - const listed = yield* Effect.flip(service.list({ state: "open", involvement: "all" })); - assert.strictEqual(listed._tag, "PullRequestOperationError"); - assert.strictEqual(viewerLookups, 1); - - yield* service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }); - assert.strictEqual(viewerLookups, 2); - }), -); - -it.effect("does not ask a paused host who is reading again after the ask failed", () => - Effect.gen(function* () { - let viewerLookups = 0; - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - { - ...environmentViewedProvider(new Map([["src/a.ts", "blob-a"]]), []), - getViewer: () => - Effect.suspend(() => { - viewerLookups += 1; - return Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("gitlab"), - operation: "getViewer", - reason: "failed", - detail: "glab exited with status 1", - }), - ); - }), - listChangeRequests: () => - Effect.succeed({ items: [], truncated: false, continues: true }), - runAction: () => - Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("gitlab"), - operation: "runAction", - reason: "rate-limited", - detail: "API rate limit exceeded.", - retryAt: 60 * 60 * 1_000, - }), - ), - }, - ], - }); - - yield* Effect.flip(service.filesViewed(GITLAB_REFERENCE)); - assert.strictEqual(viewerLookups, 1); - yield* Effect.flip(service.runAction({ ...GITLAB_REFERENCE, action: "merge" })); - - yield* Effect.flip(service.list({ state: "open", involvement: "all" })); - yield* TestClock.adjust("11 minutes"); - yield* Effect.flip(service.list({ state: "open", involvement: "all" })); - assert.strictEqual(viewerLookups, 1); - }), -); - -it.effect("refuses the marks when the host could not be asked who is reading", () => - Effect.gen(function* () { - let answering = true; - const service = yield* environmentViewedServiceWithViewer( - new Map([["src/a.ts", "blob-a"]]), - () => - answering - ? Effect.succeed("bilal") - : Effect.fail( - new PullRequestProviderError({ - provider: SourceControlProviderKind.make("gitlab"), - operation: "getViewer", - reason: "failed", - detail: "glab exited with status 1", - }), - ), +it.effect("keeps one reader's marks on a host that names nobody", () => + Effect.gen(function* () { + const service = yield* environmentViewedServiceWithViewer( + new Map([["src/a.ts", "blob-a"]]), + () => Effect.succeed(""), ); yield* service.setFilesViewed({ ...GITLAB_REFERENCE, files: [{ path: "src/a.ts", viewed: true }], }); - answering = false; - yield* TestClock.adjust("11 minutes"); - - const read = yield* Effect.flip(service.filesViewed(GITLAB_REFERENCE)); - const write = yield* Effect.flip( - service.setFilesViewed({ - ...GITLAB_REFERENCE, - files: [{ path: "src/b.ts", viewed: true }], - }), - ); - assert.strictEqual(read._tag, "PullRequestOperationError"); - assert.strictEqual(write._tag, "PullRequestOperationError"); - answering = true; assert.deepStrictEqual((yield* service.filesViewed(GITLAB_REFERENCE)).files, [ { path: "src/a.ts", state: "viewed" }, ]); }), ); -it.effect("refuses to track viewed files on a host that does not", () => +it.effect("carries a bounded number of its own marks and says it held more", () => Effect.gen(function* () { - const service = yield* makeService({ - projects: [ - project({ - id: "p1", - title: "on gitlab", - workspaceRoot: "/a", - repository: "group/project", - provider: SourceControlProviderKind.make("gitlab"), - }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("gitlab"), { - getFilesViewed: () => Effect.die("must not be called"), - setFilesViewed: () => Effect.die("must not be called"), - }), - ], - }); - const reference = { projectId: "p1" as ProjectId, repository: "group/project", number: 1 }; - - const read = yield* Effect.flip(service.filesViewed(reference)); - const write = yield* Effect.flip( - service.setFilesViewed({ ...reference, files: [{ path: "a.ts", viewed: true }] }), + const asked: Array> = []; + const paths = Array.from( + { length: PullRequestFilesViewed.MAX_FILES_VIEWED_ROWS + 40 }, + (_, at) => `src/f${String(at).padStart(4, "0")}.ts`, + ); + const service = yield* environmentViewedService( + new Map(paths.map((path) => [path, "blob"] as const)), + asked, ); - assert.strictEqual(read._tag, "PullRequestOperationError"); - assert.strictEqual(write._tag, "PullRequestOperationError"); + yield* service.setFilesViewed({ + ...GITLAB_REFERENCE, + files: paths.map((path) => ({ path, viewed: true })), + }); + const read = yield* service.filesViewed(GITLAB_REFERENCE); + + assert.lengthOf(read.files, PullRequestFilesViewed.MAX_FILES_VIEWED_ROWS); + assert.strictEqual(read.truncated, true); }), ); @@ -7634,7 +3897,8 @@ it.effect("keeps Azure continuation cursors separate for repositories with the s }), ), providers: [ - fakeProvider(SourceControlProviderKind.make("azure-devops"), { + fakePullRequestProvider(SourceControlProviderKind.make("azure-devops"), { + ...keyedByCanonicalKey, listChangeRequests: (input) => Effect.sync(() => { seen.push(input.cwd); @@ -7656,181 +3920,391 @@ it.effect("keeps Azure continuation cursors separate for repositories with the s }), ); -it.effect.each([ - { action: "merge", environmentValue: true, projectValue: false, expected: false }, - { action: "merge", environmentValue: false, projectValue: true, expected: true }, - { action: "merge", environmentValue: true, projectValue: undefined, expected: true }, - { action: "merge", environmentValue: false, projectValue: undefined, expected: false }, - { action: "enable-auto-merge", environmentValue: true, projectValue: false, expected: false }, - { action: "enable-auto-merge", environmentValue: false, projectValue: true, expected: true }, - { action: "enable-auto-merge", environmentValue: true, projectValue: undefined, expected: true }, -] as const)( - "resolves agent credits for $action with environment=$environmentValue and project=$projectValue", - ({ action, environmentValue, projectValue, expected }) => - Effect.gen(function* () { - const calls: boolean[] = []; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "web", workspaceRoot: "/w", repository: "acme/web" }), - ], - settings: { - ...DEFAULT_SERVER_SETTINGS, - removeAgentCreditsOnMerge: environmentValue, - projectSettingsOverrides: - projectValue === undefined - ? {} - : { - ["p1" as ProjectId]: { removeAgentCreditsOnMerge: projectValue }, - }, +it.effect("pauses uncached activity on a host after one activity read is rate limited", () => + Effect.gen(function* () { + let activityReads = 0; + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "web", + workspaceRoot: "/repo", + repository: "acme/web", + provider: "gitlab", + host: "gitlab.example.test", + }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("gitlab"), { + getChangeRequestActivity: () => + Effect.suspend(() => { + activityReads++; + return Effect.fail( + new PullRequestProviderError({ + provider: SourceControlProviderKind.make("gitlab"), + operation: "getChangeRequestActivity", + reason: "rate-limited", + detail: "API rate limit exceeded.", + }), + ); + }), + }), + ], + }); + const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + + expect(yield* Effect.result(service.activity(reference))).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "PullRequestOperationError", + cause: { _tag: "PullRequestProviderError", reason: "rate-limited" }, + }, + }); + assert.strictEqual(activityReads, 1); + + // A different change request cannot reuse the first request's cached failure. + expect(yield* Effect.result(service.activity({ ...reference, number: 2 }))).toMatchObject({ + _tag: "Failure", + failure: { + _tag: "PullRequestOperationError", + cause: { + _tag: "PullRequestProviderError", + reason: "rate-limited", + cause: { + _tag: "SourceControlRateLimitPausedError", + host: "gitlab.example.test", + }, }, - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - capabilities: { - ...fakeProvider(SourceControlProviderKind.make("github")).capabilities, - actions: ["merge", "enable-auto-merge"], - }, - getChangeRequestSummary: () => Effect.succeed(changeRequest(1, "2026-07-02T00:00:00Z")), - getViewerPermissions: () => - Effect.succeed({ - actions: ["merge", "enable-auto-merge"], - comment: true, - resolve: true, - verdicts: ["comment"], - requestReviewers: false, - }), - runAction: (input) => - Effect.sync(() => { - calls.push(input.removeAgentCreditsOnMerge === true); - }), - }), - ], - }); - yield* service.runAction({ - projectId: "p1" as ProjectId, - repository: "acme/web", - number: 1, - action, - }); - assert.deepStrictEqual(calls, [expected]); - }), + }, + }); + assert.strictEqual(activityReads, 1); + }), ); -it.effect("expands only files the change request changes, across every slice of its diff", () => +it.effect("authorizes cold source reads with paginated paths without fetching patch hunks", () => Effect.gen(function* () { - const read: Array = []; + const pages: Array = []; + const contents: Array = []; const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getDiff: (input) => - Effect.succeed( - input.cursor === undefined - ? { - patch: [ - "diff --git a/src/old.ts b/src/new.ts", - "rename from src/old.ts", - "rename to src/new.ts", - "--- a/src/old.ts", - "+++ b/src/new.ts", - "", - ].join("\n"), - truncated: false, - nextCursor: "2", - } - : { - patch: [ - "diff --git a/gone.md b/gone.md", - "deleted file mode 100644", - "--- a/gone.md", - "+++ /dev/null", - "", - ].join("\n"), - truncated: false, - nextCursor: null, - }, - ), + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getDiff: () => Effect.die("Membership must not fetch patch hunks"), + getDiffFilePaths: (input) => + Effect.sync(() => { + pages.push(input.cursor); + return input.cursor === undefined + ? { files: [{ oldPath: "before.ts", newPath: "after.ts" }], nextCursor: "next" } + : { files: [{ oldPath: "gone.ts", newPath: "gone.ts" }], nextCursor: null }; + }), getDiffFileContents: (input) => Effect.sync(() => { - read.push(`${input.oldPath}->${input.newPath}`); - return { oldContents: "old", newContents: "new" }; + contents.push(`${input.oldPath}->${input.newPath}`); + return { oldContents: "before", newContents: "after" }; }), }), ], }); - const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 }; - + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; yield* service.diffFileContents({ ...ref, changeType: "rename-changed", - oldPath: "src/old.ts", - newPath: "src/new.ts", + oldPath: "before.ts", + newPath: "after.ts", }); yield* service.diffFileContents({ ...ref, changeType: "deleted", - oldPath: "gone.md", - newPath: "gone.md", + oldPath: "gone.ts", + newPath: "gone.ts", }); - const outside = yield* service - .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" }) - .pipe(Effect.flip); - const halfRename = yield* service - .diffFileContents({ + for (const [oldPath, newPath] of [ + [".env", ".env"], + ["../after.ts", "../after.ts"], + ["secret.ts", "after.ts"], + ] as const) { + const error = yield* service + .diffFileContents({ ...ref, changeType: "change", oldPath, newPath }) + .pipe(Effect.flip); + assert.strictEqual(error.reason, "not-found"); + } + assert.deepStrictEqual(pages, [undefined, "next"]); + assert.deepStrictEqual(contents, ["before.ts->after.ts", "gone.ts->gone.ts"]); + }), +); + +it.effect.each(["commit", "credential", "expiry", "refresh"] as const)( + "keeps cold metadata membership in its original scope through an in-flight %s", + (boundary) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + let credential = "broad"; + let pathReads = 0; + let contentReads = 0; + const service = yield* makeService({ + projects: [ + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + withVerifiedCredential: (_, use) => + Effect.suspend(() => + use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), + ), + getDiff: () => Effect.die("Membership must not fetch patch hunks"), + getDiffFilePaths: (input) => + Effect.gen(function* () { + assert.strictEqual(input.cwd, "/a"); + assert.strictEqual(input.host, "github.com"); + assert.strictEqual(input.repository, "acme/web"); + if (++pathReads !== 1) return { files: [], nextCursor: null }; + assert.strictEqual( + input.commit, + boundary === "commit" ? "a".repeat(40) : undefined, + ); + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + return { + files: [{ oldPath: "private.ts", newPath: "private.ts" }], + nextCursor: null, + }; + }), + getDiffFileContents: () => + Effect.sync(() => { + contentReads += 1; + return { oldContents: "old", newContents: "new" }; + }), + }), + ], + }); + const input = { + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + host: "github.com", + expectedAccountId: "101", + changeType: "change" as const, + oldPath: "private.ts", + newPath: "private.ts", + }; + const initial = boundary === "commit" ? { ...input, commit: "a".repeat(40) } : input; + const loading = yield* Effect.forkChild( + service.withRoutingCredential(initial, service.diffFileContents(initial)), + ); + yield* Deferred.await(started); + if (boundary === "expiry") yield* TestClock.adjust("61 seconds"); + if (boundary === "refresh") yield* service.invalidate({ reference: input }); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(loading); + if (boundary === "credential") credential = "restricted"; + const error = yield* service + .withRoutingCredential(input, service.diffFileContents(input)) + .pipe(Effect.flip); + assert.strictEqual(error.reason, "not-found"); + assert.strictEqual(pathReads, 2); + assert.strictEqual(contentReads, 1); + }), +); + +it.effect( + "reuses loaded oversized diff slices to expand only files the change request changes", + () => + Effect.gen(function* () { + const read: Array = []; + const diffReads: Array = []; + const service = yield* makeService({ + projects: [ + project({ + id: "p1", + title: "t3code", + workspaceRoot: "/a", + repository: "pingdotgg/t3code", + }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getDiff: (input) => + Effect.sync(() => { + diffReads.push(input.cursor); + return input.cursor === undefined + ? { + patch: [ + "diff --git a/src/old.ts b/src/new.ts", + "rename from src/old.ts", + "rename to src/new.ts", + "--- a/src/old.ts", + "+++ b/src/new.ts", + `+${"x".repeat(300_000)}`, + "", + ].join("\n"), + truncated: false, + nextCursor: "2", + } + : { + patch: [ + "diff --git a/gone.md b/gone.md", + "deleted file mode 100644", + "--- a/gone.md", + "+++ /dev/null", + `-${"x".repeat(300_000)}`, + "", + ].join("\n"), + truncated: false, + nextCursor: null, + }; + }), + getDiffFileContents: (input) => + Effect.sync(() => { + read.push(`${input.oldPath}->${input.newPath}`); + return { oldContents: "old", newContents: "new" }; + }), + }), + ], + }); + const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 }; + + yield* service.diff(ref); + yield* service.diff({ ...ref, cursor: "2" }); + + yield* service.diffFileContents({ ...ref, - changeType: "change", - oldPath: "src/secret.ts", + changeType: "rename-changed", + oldPath: "src/old.ts", newPath: "src/new.ts", - }) - .pipe(Effect.flip); + }); + yield* service.diffFileContents({ + ...ref, + changeType: "deleted", + oldPath: "gone.md", + newPath: "gone.md", + }); + const outside = yield* service + .diffFileContents({ ...ref, changeType: "deleted", oldPath: ".env", newPath: ".env" }) + .pipe(Effect.flip); + const halfRename = yield* service + .diffFileContents({ + ...ref, + changeType: "change", + oldPath: "src/secret.ts", + newPath: "src/new.ts", + }) + .pipe(Effect.flip); - assert.strictEqual(outside._tag, "PullRequestOperationError"); - assert.strictEqual(halfRename._tag, "PullRequestOperationError"); - assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]); - }), + assert.strictEqual(outside._tag, "PullRequestOperationError"); + assert.strictEqual(halfRename._tag, "PullRequestOperationError"); + assert.deepStrictEqual(read, ["src/old.ts->src/new.ts", "gone.md->gone.md"]); + assert.deepStrictEqual(diffReads, [undefined, "2"]); + }), ); -it.effect("checks expanded files against a diff too large to cache without fetching it again", () => - Effect.gen(function* () { - let diffReads = 0; - const filler = `+${"x".repeat(300 * 1024)}`; - const service = yield* makeService({ - projects: [ - project({ id: "p1", title: "t3code", workspaceRoot: "/a", repository: "pingdotgg/t3code" }), - ], - providers: [ - fakeProvider(SourceControlProviderKind.make("github"), { - getDiff: () => - Effect.sync(() => { - diffReads += 1; - return { - patch: ["a.ts", "b.ts"] - .flatMap((name) => [ - `diff --git a/${name} b/${name}`, - `--- a/${name}`, - `+++ b/${name}`, - "@@ -0,0 +1 @@", - filler, - ]) - .join("\n"), +// Refresh and expiry are covered by the in-flight test below; repository and number share the ref key. +it.effect.each(["commit", "credential"] as const)( + "does not reuse loaded diff membership after changing %s", + (boundary) => + Effect.gen(function* () { + let credential = "broad"; + let diffReads = 0; + let contentReads = 0; + const service = yield* makeService({ + projects: [ + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + withVerifiedCredential: (_, use) => + Effect.suspend(() => + use({ accountId: "101", viewer: "octocat", credentialFingerprint: credential }), + ), + getDiff: () => + Effect.sync(() => ({ + patch: + ++diffReads === 1 + ? `diff --git a/private.ts b/private.ts\n--- a/private.ts\n+++ b/private.ts\n+${"x".repeat(300_000)}\n` + : "", truncated: false, nextCursor: null, - }; - }), - getDiffFileContents: () => Effect.succeed({ oldContents: "old", newContents: "new" }), - }), - ], - }); - const ref = { projectId: "p1" as ProjectId, repository: "pingdotgg/t3code", number: 1 }; - for (const name of ["a.ts", "b.ts"]) { - yield* service.diffFileContents({ + })), + getDiffFileContents: () => + Effect.sync(() => { + contentReads += 1; + return { oldContents: "old", newContents: "new" }; + }), + }), + ], + }); + const ref = { + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + host: "github.com", + expectedAccountId: "101", + }; + // Load at a commit and expand without one so the commit must be part of the membership key. + const loaded = boundary === "commit" ? { ...ref, commit: "a".repeat(40) } : ref; + yield* service.withRoutingCredential(loaded, service.diff(loaded)); + if (boundary === "credential") credential = "restricted"; + const input = { ...ref, - changeType: "change", - oldPath: name, - newPath: name, + changeType: "change" as const, + oldPath: "private.ts", + newPath: "private.ts", + }; + const error = yield* service + .withRoutingCredential(input, service.diffFileContents(input)) + .pipe(Effect.flip); + assert.strictEqual(error._tag, "PullRequestOperationError"); + assert.strictEqual(error.reason, "not-found"); + assert.strictEqual(diffReads, 2); + assert.strictEqual(contentReads, 0); + }), +); + +it.effect.each(["expiry", "refresh"] as const)( + "keeps a loaded diff's original membership scope through an in-flight %s", + (boundary) => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + let diffReads = 0; + const service = yield* makeService({ + projects: [ + project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" }), + ], + providers: [ + fakePullRequestProvider(SourceControlProviderKind.make("github"), { + getDiff: () => + Effect.gen(function* () { + if (++diffReads !== 1) return { patch: "", truncated: false, nextCursor: null }; + yield* Deferred.succeed(started, undefined); + yield* Deferred.await(release); + return { + patch: `diff --git a/private.ts b/private.ts\n--- a/private.ts\n+++ b/private.ts\n+${"x".repeat(300_000)}\n`, + truncated: false, + nextCursor: null, + }; + }), + getDiffFileContents: () => Effect.die("an expired file must not be read"), + }), + ], }); - } - assert.strictEqual(diffReads, 1); - }), + const ref = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 }; + const loading = yield* Effect.forkChild(service.diff(ref)); + yield* Deferred.await(started); + if (boundary === "expiry") yield* TestClock.adjust("61 seconds"); + else yield* service.invalidate({ reference: ref }); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(loading); + const error = yield* service + .diffFileContents({ + ...ref, + changeType: "change", + oldPath: "private.ts", + newPath: "private.ts", + }) + .pipe(Effect.flip); + assert.strictEqual(error._tag, "PullRequestOperationError"); + assert.strictEqual(error.reason, "not-found"); + assert.strictEqual(diffReads, 2); + }), ); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 328e32526c1ea..b37cf7d57667f 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -1,9 +1,4 @@ -import { - canonicalRepositoryKey, - isSshRemoteUrl, - sourceControlRepositorySelector, -} from "@t3tools/shared/sourceControl"; -import { normalizeGitRemoteUrl } from "@t3tools/shared/git"; +import { isSshRemoteUrl } from "@t3tools/shared/sourceControl"; import { parseDiffFilePaths } from "@t3tools/source-control-core/server/diffFileRevisions"; import * as Cache from "effect/Cache"; import * as Cause from "effect/Cause"; @@ -23,8 +18,6 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import { PullRequestOperationError, PullRequestUnavailableError, - pullRequestHostOf, - pullRequestProviderRequirement, resolvePullRequestAuthorFilter, type OrchestrationProjectShell, type ProjectId, @@ -40,6 +33,7 @@ import { type PullRequestDiffFileContentsResult, type PullRequestDiffStat, type PullRequestDiffInput, + type PullRequestChangeBreakdown, type PullRequestFilesViewedResult, type PullRequestDiffResult, type PullRequestInvalidateInput, @@ -50,6 +44,10 @@ import { type PullRequestListProjectError, type PullRequestListResult, type PullRequestListStatsInput, + type PullRequestFilterOptions, + type PullRequestFilterOptionsInput, + type PullRequestActor, + type PullRequestLabel, type PullRequestListStatsResult, type PullRequestProviderSummary, type PullRequestReactionInput, @@ -77,16 +75,19 @@ import { type ThreadPullRequestKey, } from "@t3tools/contracts"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; -import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts"; import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; +import type { SourceControlProviderContext } from "@t3tools/source-control-core/server/SourceControlProvider"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { type ProviderChangeRequest, + type ProviderDiffFilePaths, + type ProviderFilterOptionPage, type ProviderListCursor, type ProviderChangeRequestWatchFingerprint, type PullRequestProviderApi, @@ -95,12 +96,16 @@ import { import * as PullRequestReadCache from "./PullRequestReadCache.ts"; import * as PullRequestProviderRegistry from "./PullRequestProviderRegistry.ts"; import * as ViewedFiles from "./pullRequestViewedFiles.ts"; +import { toChangeBreakdown } from "./pullRequestChangeBreakdown.ts"; export interface PullRequestMergeEvent extends PullRequestRef { readonly mergedAt: string; } -type PullRequestReading = Pick; +type PullRequestReading = Pick< + PullRequestSummary, + "state" | "isDraft" | "updatedAt" | "observedAt" +>; function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) { if (current === undefined) return true; @@ -109,21 +114,13 @@ function supersedesReading(current: PullRequestReading | undefined, next: PullRe return (next.observedAt ?? -Infinity) >= (current.observedAt ?? -Infinity); } -/** - * 99 and not 100, because every provider asks its host for one row over this to probe for a next - * page: 99 requests 100, which is exactly what a page of GitHub's API serves — GraphQL refuses - * `first` over 100 with EXCESSIVE_PAGINATION and REST clamps `per_page` to it — and what GitLab - * caps `per_page` at. - */ +// Providers request one extra row; 99 stays within GitHub/GitLab's 100-row API limit. const DEFAULT_REPOSITORY_LIST_LIMIT = 99; const REPOSITORY_CONCURRENCY = 12; const REPOSITORY_SEARCH_CHUNK = 100; +const FILTERED_LIST_READS = 5; -/** - * Every read leaves the process — a CLI per repository, against hosts whose limits are low - * (GitHub's search API allows ~30 requests a minute) — so answers are shared for a short while and - * concurrent identical reads share one request. - */ +// Host reads spawn CLIs and hit low quotas; briefly share results and identical in-flight reads. const LIST_CACHE_TTL = Duration.seconds(30); const DETAIL_CACHE_TTL = Duration.seconds(60); const MERGED_DETAIL_CACHE_TTL = Duration.minutes(10); @@ -138,7 +135,6 @@ const FILES_VIEWED_CACHE_TTL = Duration.seconds(15); const DIFF_STALE_WINDOW = Duration.minutes(10); const DIFF_SWEEP_INTERVAL = Duration.minutes(1); const VIEWER_CACHE_TTL = Duration.minutes(10); -const SEARCH_VISIBILITY_TTL = Duration.minutes(10); const STALE_DETAIL_WINDOW = Duration.minutes(10); const isPullRequestProviderError = Schema.is(PullRequestProviderError); const LIST_CACHE_CAPACITY = 64; @@ -169,6 +165,9 @@ export class PullRequestService extends Context.Service< readonly listStats: ( input: PullRequestListStatsInput, ) => Effect.Effect; + readonly filterOptions: ( + input: PullRequestFilterOptionsInput, + ) => Effect.Effect; readonly routing: ( input: PullRequestRef, ) => Effect.Effect; @@ -230,6 +229,9 @@ export class PullRequestService extends Context.Service< readonly setFilesViewed: ( input: PullRequestSetFilesViewedInput, ) => Effect.Effect; + readonly changeBreakdown: ( + input: PullRequestRef, + ) => Effect.Effect; readonly runAction: (input: PullRequestActionInput) => Effect.Effect; readonly update: (input: PullRequestUpdateInput) => Effect.Effect; readonly comment: (input: PullRequestCommentInput) => Effect.Effect; @@ -286,7 +288,7 @@ const ACTION_ACCESS_REFUSALS: Record = { reopen: "You need write access on this repository, or to have opened this change request, to reopen it.", "enable-auto-merge": - "You need write access on this repository to have it merged for you once it is ready.", + "Auto-merge needs write access on this repository, and the repository has to allow it.", "disable-auto-merge": "You need write access on this repository to stop it being merged for you once it is ready.", revert: "You need write access on this repository to open a revert pull request.", @@ -304,9 +306,7 @@ export interface SupportedProject { readonly api: PullRequestProviderApi; readonly repository: string; readonly host: string; - /** - * Unique where `repository` is not: Azure's is a bare name that repeats across an organisation. - */ + /** Unlike Azure repository names, remotes are unique across an organization. */ readonly remote: string; readonly repositoryKey: string | null; } @@ -333,7 +333,7 @@ interface ListCursor extends ProviderListCursor { } const LIST_CURSOR_PATTERN = - /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?$/; + /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2}))\|(\d{1,9})\|(\d{1,9}(?:,\d{1,9})*)?(?:\|([\w.:~+-]{1,128}))?$/; function parseListCursor(raw: string): ListCursor | null { const match = LIST_CURSOR_PATTERN.exec(raw); @@ -343,6 +343,7 @@ function parseListCursor(raw: string): ListCursor | null { updatedBefore: match[1]!, delivered: Number(match[2]), seenAt: seenAt === undefined ? [] : seenAt.split(",").map(Number), + ...(match[4] === undefined ? {} : { resumeAfter: match[4] }), }; } @@ -350,24 +351,19 @@ function listCursorKey(host: string, repository: string): string { return `${host} ${repository.toLowerCase()}`; } -/** - * A slice that ends on the same instant it began on has to keep the earlier rows excluded as - * well as its own, or the read after it would hand them over again. - */ +// Preserve exclusions across slices sharing a timestamp to avoid redelivery. function nextListCursor( previous: ListCursor | undefined, fetched: ReadonlyArray, delivered: ReadonlyArray, /** A provider may consume malformed offset-paged rows that never appear in `delivered`. */ cursorAdvance = delivered.length, + resumeAfter?: string, ): string | null { if (fetched.length === 0) return null; - // Taken from what the host answered rather than from what survived de-duplication: a slice can - // be entirely rows already sent — a hundred change requests touched in the same second is one - // repository's boring afternoon — and reading "nothing new" as "nothing left" would end the - // walk on the instant it was stuck on, with everything older unreachable for good. + // Use all fetched rows: a slice containing only duplicates must still advance to older rows. const oldest = fetched.reduce((left, right) => (right.updatedAt < left.updatedAt ? right : left)); - return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance); + return listCursorAt(previous, oldest.updatedAt, fetched, cursorAdvance, resumeAfter); } function listCursorAt( @@ -375,48 +371,61 @@ function listCursorAt( boundary: string, fetched: ReadonlyArray, deliveredCount: number, + resumeAfter?: string, ): string { - const seenAt = [ + const seenAt = new Set([ ...(previous?.updatedBefore === boundary ? previous.seenAt : []), ...fetched.filter((item) => item.updatedAt === boundary).map((item) => item.number), - ]; - return `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${seenAt.join(",")}`; + ]); + const cursor = `${boundary}|${(previous?.delivered ?? 0) + deliveredCount}|${[...seenAt].join(",")}`; + return resumeAfter === undefined ? cursor : `${cursor}|${resumeAfter}`; } function isProviderUnusable(error: PullRequestProviderError): boolean { return error.reason === "missing-tool" || error.reason === "unauthenticated"; } -function providerDetail(error: PullRequestProviderError): string { - if (!isProviderUnusable(error)) return error.detail; - return ( - pullRequestProviderRequirement( - error.provider, - error.reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated", - ) ?? error.detail - ); +type UnavailableRequirementOf = ( + kind: SourceControlProviderKind, +) => PullRequestProviderApi["unavailableRequirement"]; + +function unavailableRequirement( + requirementOf: UnavailableRequirementOf, + error: PullRequestProviderError, +): string | undefined { + const requirement = requirementOf(error.provider); + if (requirement === undefined) return undefined; + return error.reason === "missing-tool" ? requirement.missing : requirement.unauthenticated; } -function toUnavailableError(error: PullRequestProviderError): PullRequestUnavailableError { - return new PullRequestUnavailableError({ - reason: error.reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated", - provider: error.provider, - cause: error, - }); +function providerDetail( + requirementOf: UnavailableRequirementOf, + error: PullRequestProviderError, +): string { + if (!isProviderUnusable(error)) return error.detail; + return unavailableRequirement(requirementOf, error) ?? error.detail; } -function toPullRequestError( - operation: string, -): (error: PullRequestProviderError) => PullRequestError { - return (error) => - isProviderUnusable(error) - ? toUnavailableError(error) - : new PullRequestOperationError({ - operation, - detail: error.detail, - ...(error.reason === "not-found" ? { reason: "not-found" as const } : {}), - cause: error, - }); +function toPullRequestErrorWith( + requirementOf: UnavailableRequirementOf, +): (operation: string) => (error: PullRequestProviderError) => PullRequestError { + return (operation) => (error) => { + if (isProviderUnusable(error)) { + const requirement = unavailableRequirement(requirementOf, error); + return new PullRequestUnavailableError({ + reason: error.reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated", + provider: error.provider, + ...(requirement === undefined ? {} : { requirement }), + cause: error, + }); + } + return new PullRequestOperationError({ + operation, + detail: error.detail, + ...(error.reason === "not-found" ? { reason: "not-found" as const } : {}), + cause: error, + }); + }; } function withRateLimitBackoff( @@ -478,7 +487,13 @@ function withRateLimitBackoff( ...(api.mergeMessageRewrite === undefined ? {} : { mergeMessageRewrite: api.mergeMessageRewrite }), + ...(api.unavailableRequirement === undefined + ? {} + : { unavailableRequirement: api.unavailableRequirement }), ...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }), + ...(api.readsPublicHostWithoutCheckout === undefined + ? {} + : { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }), getViewer: options?.viewerAllowsPause === true ? interactive("getViewer", api.getViewer) @@ -529,12 +544,18 @@ function withRateLimitBackoff( }), getViewerPermissions: interactive("getViewerPermissions", api.getViewerPermissions), getDiff: wrap("getDiff", api.getDiff), + ...(api.getDiffFilePaths === undefined + ? {} + : { getDiffFilePaths: wrap("getDiffFilePaths", api.getDiffFilePaths) }), ...(api.getDiffFileContents === undefined ? {} : { getDiffFileContents: wrap("getDiffFileContents", api.getDiffFileContents) }), ...(api.getFilesViewed === undefined ? {} : { getFilesViewed: wrap("getFilesViewed", api.getFilesViewed) }), + ...(api.getFileStats === undefined + ? {} + : { getFileStats: wrap("getFileStats", api.getFileStats) }), ...(api.setFilesViewed === undefined ? {} : { setFilesViewed: interactive("setFilesViewed", api.setFilesViewed) }), @@ -558,6 +579,17 @@ function withRateLimitBackoff( ? {} : { listLabelCandidates: interactive("listLabelCandidates", api.listLabelCandidates) }), ...(api.setLabels === undefined ? {} : { setLabels: interactive("setLabels", api.setLabels) }), + ...(api.listRepositoryLabels === undefined + ? {} + : { listRepositoryLabels: interactive("listRepositoryLabels", api.listRepositoryLabels) }), + ...(api.searchRepositoryAuthors === undefined + ? {} + : { + searchRepositoryAuthors: interactive( + "searchRepositoryAuthors", + api.searchRepositoryAuthors, + ), + }), replyToThread: interactive("replyToThread", api.replyToThread), setReaction: interactive("setReaction", api.setReaction), setThreadResolution: interactive("setThreadResolution", api.setThreadResolution), @@ -567,6 +599,67 @@ function withRateLimitBackoff( Record, never>; } +const FILTER_OPTIONS_LIMIT = 100; + +/** + * Exact matches first, then names that begin with the query, then the rest, so a short query + * still puts the obvious answer at the top of a long list. + */ +function rankFilterOptions( + pages: ReadonlyArray>, + input: { + readonly query: string | undefined; + readonly keyOf: (item: A) => string; + readonly textsOf: (item: A) => ReadonlyArray; + }, +): { readonly items: ReadonlyArray; readonly truncated: boolean } { + const query = input.query?.trim().toLowerCase() ?? ""; + const unique = new Map(); + for (const page of pages) { + for (const item of page.items) { + const key = input.keyOf(item).toLowerCase(); + if (!unique.has(key)) unique.set(key, item); + } + } + const rank = (item: A) => { + const texts = input.textsOf(item).flatMap((text) => (text ? [text.toLowerCase()] : [])); + if (query.length === 0) return 0; + if (texts.includes(query)) return 0; + if (texts.some((text) => text.startsWith(query))) return 1; + if (texts.some((text) => text.includes(query))) return 2; + return null; + }; + const ranked = [...unique.values()] + .flatMap((item) => { + const score = rank(item); + return score === null ? [] : [{ item, score, key: input.keyOf(item) }]; + }) + .toSorted( + (left, right) => + left.score - right.score || + left.key.localeCompare(right.key, undefined, { sensitivity: "base" }), + ); + return { + items: ranked.slice(0, FILTER_OPTIONS_LIMIT).map(({ item }) => item), + truncated: ranked.length > FILTER_OPTIONS_LIMIT || pages.some((page) => page.truncated), + }; +} + +const remoteHostKey = (recognized: SourceControlProviderInfo, remoteUrl: string) => + `${recognized.baseUrl}\n${isSshRemoteUrl(remoteUrl) ? "ssh" : "web"}`; + +/** An HTTP remote names its server's web host, port included. */ +function httpRemoteHost(remoteUrl: string): string | null { + try { + const remote = new URL(remoteUrl); + return remote.protocol === "http:" || remote.protocol === "https:" + ? remote.host.toLowerCase() + : null; + } catch { + return null; + } +} + // Capture before the provider read so a slow response keeps its original freshness through caches. const observeRead = Effect.fnUntraced(function* (read: Effect.Effect) { const observedAt = yield* Clock.currentTimeMillis; @@ -578,6 +671,9 @@ export const make = Effect.gen(function* () { const stateChanges = yield* PubSub.sliding(64); const pullRequestRefreshes = yield* SubscriptionRef.make(0); const registry = yield* PullRequestProviderRegistry.PullRequestProviderRegistry; + const requirementOf: UnavailableRequirementOf = (kind) => + registry.get(kind)?.unavailableRequirement; + const toPullRequestError = toPullRequestErrorWith(requirementOf); const serverSettings = yield* ServerSettings.ServerSettingsService; const projects = yield* ProjectService.ProjectService; const repositoryIdentities = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; @@ -586,83 +682,131 @@ export const make = Effect.gen(function* () { const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository; const readCache = yield* PullRequestReadCache.PullRequestReadCache; - const refineUnknownProjectKinds = ( + /** + * Where each project's remote is served from, by the remote's recognised base URL: a remote no + * definition placed is identified by the hosting CLIs, and a host whose remotes may not name + * its web server says which one does. One project per base URL and transport answers for all + * of them. + */ + const resolveRemoteHosts = Effect.fn("PullRequestService.resolveRemoteHosts")(function* ( projects: ReadonlyArray, filter: Pick, - ) => { - type RefinementCandidate = { + ) { + type Candidate = { readonly project: OrchestrationProjectShell; - readonly provider: SourceControlProviderInfo; - readonly remoteName: string; - readonly remoteUrl: string; + readonly context: SourceControlProviderContext; }; - const refinements = new Map(); + const candidatesByKey = new Map(); for (const project of projects) { if (filter.projectId !== undefined && project.id !== filter.projectId) continue; const identity = project.repositoryIdentity; if ( - (identity?.provider !== "unknown" && - !(identity?.provider === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl))) || - sourceControlRepositorySelector(project.repositoryIdentity) === null + !identity || + identity.provider === undefined || + sourceControlDefinitions.repositorySelector(identity) === null ) continue; - const host = pullRequestHostOf(identity, SourceControlProviderKind.make("unknown")); + if (identity.provider !== "unknown") { + const provider = yield* sourceControlProviders + .get(identity.provider) + .pipe(Effect.orElseSucceed(() => null)); + if (provider?.resolveRemoteWebHost === undefined) continue; + } + const host = sourceControlDefinitions.changeRequestHost(identity, "unknown"); if ( filter.host !== undefined && host !== "unknown" && host !== filter.host.toLowerCase() && - pullRequestHostOf(identity, SourceControlProviderKind.make("forgejo")) !== - filter.host.toLowerCase() && + httpRemoteHost(identity.locator.remoteUrl) !== filter.host.toLowerCase() && !isSshRemoteUrl(identity.locator.remoteUrl) ) { continue; } const { remoteName, remoteUrl } = identity.locator; - const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl); - if (provider !== null) { - const candidates = refinements.get(provider.baseUrl); - const candidate = { project, provider, remoteName, remoteUrl }; - if (candidates === undefined) refinements.set(provider.baseUrl, [candidate]); - else candidates.push(candidate); - } + const recognized = sourceControlDefinitions.recognizeRemote(remoteUrl); + if (recognized === null) continue; + const candidate = { + project, + context: { + provider: + identity.provider === "unknown" + ? recognized + : { ...recognized, kind: identity.provider }, + remoteName, + remoteUrl, + ...(filter.host !== undefined && isSshRemoteUrl(remoteUrl) + ? { requestedHost: filter.host } + : {}), + }, + }; + const key = remoteHostKey(recognized, remoteUrl); + const candidates = candidatesByKey.get(key); + if (candidates === undefined) candidatesByKey.set(key, [candidate]); + else candidates.push(candidate); } - return Effect.forEach( - refinements, - ([baseUrl, candidates]) => - Effect.firstSuccessOf( - candidates.map(({ project, provider, remoteName, remoteUrl }) => - Effect.suspend(() => - sourceControlProviders.resolveHandle({ - cwd: project.workspaceRoot, - context: { - provider: - provider.kind === "forgejo" - ? { ...provider, kind: SourceControlProviderKind.make("unknown") } - : provider, - remoteName, - remoteUrl, - ...(filter.host !== undefined && isSshRemoteUrl(remoteUrl) - ? { requestedHost: filter.host } - : {}), - }, - }), - ).pipe( - Effect.flatMap((handle) => { - const refined = handle.context?.provider; - return refined === undefined || refined.kind === "unknown" - ? Effect.fail(undefined) - : Effect.succeed(refined); - }), + const resolveContext = (input: { + readonly cwd: string; + readonly context: SourceControlProviderContext; + }) => sourceControlProviders.resolveHandle(input).pipe(Effect.map((handle) => handle.context)); + type RemoteHost = { readonly kind: SourceControlProviderKind; readonly host: string | null }; + const resolveCandidate = ({ project, context }: Candidate) => + (context.provider.kind === "unknown" + ? resolveContext({ cwd: project.workspaceRoot, context }).pipe( + Effect.map((resolved) => + resolved === null || resolved.provider.kind === "unknown" + ? null + : { context: resolved, discovered: true }, ), - ), - ).pipe( - Effect.map((provider) => [baseUrl, provider] as const), - Effect.orElseSucceed(() => [baseUrl, null] as const), + ) + : Effect.succeed({ context, discovered: false }) + ).pipe( + Effect.flatMap((found) => + found === null + ? Effect.succeed(null) + : sourceControlProviders.get(found.context.provider.kind).pipe( + Effect.flatMap( + (provider) => + provider.resolveRemoteWebHost?.({ + cwd: project.workspaceRoot, + context: found.context, + // A remote discovery just placed is not looked up a second time. + resolveContext: found.discovered + ? () => Effect.succeed(found.context) + : resolveContext, + }) ?? Effect.succeed(null), + ), + Effect.orElseSucceed(() => null), + Effect.map((host): RemoteHost => ({ kind: found.context.provider.kind, host })), + ), ), + Effect.orElseSucceed(() => null), + ); + + // An SSH remote whose web host one checkout could not name may be named by the next; a + // kind found without a host still stands if none can. + const resolveKey = Effect.fn("PullRequestService.resolveRemoteHost")(function* ( + candidates: ReadonlyArray, + ) { + let fallback: RemoteHost | null = null; + for (const candidate of candidates) { + const resolved = yield* resolveCandidate(candidate); + if (resolved === null) continue; + if (resolved.host !== null || !isSshRemoteUrl(candidate.context.remoteUrl)) { + return resolved; + } + fallback ??= resolved; + } + return fallback; + }); + + return yield* Effect.forEach( + candidatesByKey, + ([key, candidates]) => + resolveKey(candidates).pipe(Effect.map((resolved) => [key, resolved] as const)), { concurrency: REPOSITORY_CONCURRENCY }, ).pipe(Effect.map((resolved) => new Map(resolved))); - }; + }); const listWorkspaceProjects = ( filter: Pick, @@ -694,11 +838,11 @@ export const make = Effect.gen(function* () { ), ), Effect.flatMap((projects) => - refineUnknownProjectKinds(projects, filter).pipe( - Effect.map((refinedProviders) => ({ refinedProviders, projects })), + resolveRemoteHosts(projects, filter).pipe( + Effect.map((remoteHosts) => ({ remoteHosts, projects })), ), ), - Effect.map(({ refinedProviders, projects }) => { + Effect.map(({ remoteHosts, projects }) => { const supported: SupportedProject[] = []; const unimplemented = new Map< string, @@ -710,22 +854,18 @@ export const make = Effect.gen(function* () { if (filter.projectId !== undefined && project.id !== filter.projectId) continue; if (filter.projectIds !== undefined && !filter.projectIds.includes(project.id)) continue; const identity = project.repositoryIdentity; - let kind = identity?.provider as SourceControlProviderKind | undefined; - const repository = sourceControlRepositorySelector(project.repositoryIdentity); + let kind = identity?.provider; + const repository = sourceControlDefinitions.repositorySelector( + project.repositoryIdentity, + ); if (!identity || kind === undefined || repository === null) continue; - let refinedProvider: SourceControlProviderInfo | null | undefined; - if ( - kind === "unknown" || - (kind === "forgejo" && isSshRemoteUrl(identity.locator.remoteUrl)) - ) { - const provider = detectSourceControlProviderFromRemoteUrl(identity.locator.remoteUrl); - refinedProvider = provider === null ? null : refinedProviders.get(provider.baseUrl); - kind = refinedProvider?.kind ?? kind; - } - const host = - refinedProvider?.kind === "forgejo" - ? new URL(refinedProvider.baseUrl).host.toLowerCase() - : pullRequestHostOf(identity, kind); + const recognized = sourceControlDefinitions.recognizeRemote(identity.locator.remoteUrl); + const remote = + recognized === null + ? undefined + : remoteHosts.get(remoteHostKey(recognized, identity.locator.remoteUrl)); + kind = remote?.kind ?? kind; + const host = remote?.host ?? sourceControlDefinitions.changeRequestHost(identity, kind); if (filter.host !== undefined && host !== filter.host.toLowerCase()) { continue; } @@ -752,19 +892,20 @@ export const make = Effect.gen(function* () { api: withRateLimitBackoff(api, host, rateLimits), repository, host, - remote: repositoryKey ?? normalizeGitRemoteUrl(`https://${host}/${repository}`), + remote: + repositoryKey ?? + sourceControlDefinitions.repositoryKeyFromRemote(`https://${host}/${repository}`), repositoryKey: - repositoryKey === null ? null : canonicalRepositoryKey(repositoryKey.toLowerCase()), + repositoryKey === null + ? null + : sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()), }); } return { supported, unimplemented, viewerRoots }; }), ); - /** - * Azure derives its organization from the checkout, so it requires a matching - * repository. - */ + // Azure derives organization from the checkout; require the matching repository. const requireProject = (ref: PullRequestRef): Effect.Effect => listWorkspaceProjects({ projectId: ref.projectId }).pipe( Effect.flatMap(({ supported }): Effect.Effect => { @@ -785,11 +926,13 @@ export const make = Effect.gen(function* () { }), ); } - const repositoryKey = canonicalRepositoryKey(`${host}/${repository}`.toLowerCase()); - // Azure SSH and legacy clone hosts differ from the browser URL's host. Compare - // the complete repository identity before narrowing those checkouts by host. + const referenceKey = `${host}/${repository}`.toLowerCase(); + const repositoryKey = sourceControlDefinitions.canonicalRepositoryKey(referenceKey); + // A host that spells one repository several ways (Azure's SSH and legacy clone hosts) + // can differ from the browser URL's host. Compare the complete repository identity + // before narrowing those checkouts by host. return listWorkspaceProjects( - repositoryKey.startsWith("dev.azure.com/") ? {} : { host }, + sourceControlDefinitions.findByRepositoryKey(referenceKey) ? {} : { host }, ).pipe( Effect.flatMap(({ supported }) => { const onHost = supported.filter((candidate) => candidate.host === host); @@ -806,11 +949,9 @@ export const make = Effect.gen(function* () { onHost.find((candidate) => candidate.repositoryKey === null); if (route === undefined) { return Effect.gen(function* () { - const provider = ["github.com", "bitbucket.org", "codeberg.org"].includes(host) - ? detectSourceControlProviderFromRemoteUrl(`https://${host}/${repository}.git`) - : null; - const api = provider === null ? null : registry.get(provider.kind); - if (api !== null) { + const publicHost = sourceControlDefinitions.findByPublicHost(host); + const api = publicHost === undefined ? null : registry.get(publicHost.kind); + if (api?.readsPublicHostWithoutCheckout) { const selected = yield* projects.getShell(ref.projectId).pipe( Effect.mapError( (cause) => @@ -828,7 +969,9 @@ export const make = Effect.gen(function* () { api: withRateLimitBackoff(api, host, rateLimits), repository, host, - remote: normalizeGitRemoteUrl(`https://${host}/${repository}`), + remote: sourceControlDefinitions.repositoryKeyFromRemote( + `https://${host}/${repository}`, + ), repositoryKey: null, }; } @@ -843,7 +986,9 @@ export const make = Effect.gen(function* () { : { ...route, repository, - remote: normalizeGitRemoteUrl(`https://${host}/${repository}`), + remote: sourceControlDefinitions.repositoryKeyFromRemote( + `https://${host}/${repository}`, + ), }, ); }), @@ -863,12 +1008,7 @@ export const make = Effect.gen(function* () { }; }); - /** - * Every write goes through it: the page hides what a viewer may not do, and a request that - * arrived without passing through the page — or after the access behind it was withdrawn — must - * not be handed to a provider on the client's word. Read freshly for that reason, rather than - * taken from whatever the detail said when the page loaded. - */ + // Access can change after page load; recheck every write. const viewerPermissionsOf = ( project: SupportedProject, ref: PullRequestRef, @@ -946,8 +1086,7 @@ export const make = Effect.gen(function* () { }, { capacity: VIEWER_CACHE_CAPACITY, - // This short entry exists to keep simultaneous cold page reads on one in-flight lookup; - // failures remain retryable. + // Share cold-page lookups briefly; keep failures retryable. timeToLive: (exit) => Exit.isSuccess(exit) && exit.value.error === null ? Duration.seconds(1) : Duration.zero, }, @@ -968,16 +1107,12 @@ export const make = Effect.gen(function* () { } const forHost = projects.filter((project) => project.host === host); const api = forHost[0]!.api; - // Every checkout on the host, not just the ones that survived de-duplication: one - // unreadable worktree would otherwise report the whole host as signed out. + // Include deduplicated checkouts too; one unreadable worktree must not mark the whole host signed out. const roots = viewerRoots.get(host) ?? forHost.map(({ project }) => project.workspaceRoot); const key = JSON.stringify([host, api.kind, [...new Set(roots)].sort()]); if (options?.allowPaused === true) return Cache.get(viewerFlights, key); - // The pause is checked here rather than inside the lookup, so that it holds back the - // callers nobody is waiting on without splitting the flight they share with a press. - // A failed lookup is held nowhere, so letting a background read through would spawn - // this host's CLI on every refresh for as long as the pause lasted, and re-extend it. + // Check pauses outside the shared lookup so background reads cannot spawn repeated failing CLIs and extend the pause. return rateLimits.check({ provider: api.kind, host }).pipe( Effect.flatMap(() => Cache.get(viewerFlights, key)), Effect.catch((error) => @@ -1000,10 +1135,7 @@ export const make = Effect.gen(function* () { { concurrency: REPOSITORY_CONCURRENCY }, ); - /** - * `checks` is absent because no listed row carries its check state: that one filter is - * the host's alone, and a row nobody narrowed stays rather than being guessed at. - */ + // Only the host can filter checks; listed rows have no check state. const matchesRowFilters = ( item: ProviderChangeRequest, filters: PullRequestListFilters | undefined, @@ -1068,297 +1200,304 @@ export const make = Effect.gen(function* () { }; }; - // A repository that has appeared in a host search is known to be indexed there. Empty - // authored/reviewing searches for that same repository are therefore real empty answers, not - // a reason to issue the two-command per-repository fallback again. - const searchVisibleAt = new Map(); - const searchVisibilityKey = (host: string, repository: string) => - `${host}\n${repository.trim().toLowerCase()}`; - - const listUncached: PullRequestService["Service"]["list"] = (input) => - Effect.gen(function* () { - const involvement = input.involvement ?? "all"; - const continuation = yield* decodeCursors(input.cursors); - const { - supported: projects, - unimplemented, - viewerRoots, - } = yield* listWorkspaceProjects(input); - const projectCounts = new Map(); - for (const { host } of projects) { - projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1); - } - - const viewerResults = yield* resolveViewers(projects, viewerRoots); - const viewers: Record = {}; - for (const result of viewerResults) { - if (result.viewer !== null) viewers[result.host] = result.viewer; - } - - const providers: ReadonlyArray = [ - ...viewerResults.map((result) => { - const capabilities = projects.find((project) => project.host === result.host)?.api - .capabilities; - return { - host: result.host, - kind: result.kind, - searchesOnHost: capabilities?.search ?? false, - actions: capabilities?.actions ?? [], - projectCount: projectCounts.get(result.host) ?? 1, - configured: result.viewer !== null, - detail: result.error === null ? null : providerDetail(result.error), - }; - }), - ...[...unimplemented].map(([host, { kind, projectCount }]) => ({ - host, - kind, - searchesOnHost: false, - actions: [], - projectCount, - configured: false, - detail: "This host cannot be browsed here yet.", - })), - ]; + const listUncached: PullRequestService["Service"]["list"] = Effect.fn( + "PullRequestService.listUncached", + )(function* (input) { + const involvement = input.involvement ?? "all"; + const continuation = yield* decodeCursors(input.cursors); + const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input); + const projectCounts = new Map(); + for (const { host } of projects) { + projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1); + } - const selected = - continuation === null - ? projects - : projects.filter(({ cursorKey }) => continuation.has(cursorKey)); - const readable = selected.filter(({ host }) => viewers[host] !== undefined); - const unreadable = selected - .filter(({ host }) => viewers[host] === undefined) - .map(({ project, repository }) => ({ - projectId: project.id, - projectTitle: project.title, - message: `${repository} could not be read.`, - })); - if (readable.length === 0) { - const errors = viewerResults.flatMap((result) => - result.error === null || !selected.some(({ host }) => host === result.host) - ? [] - : [result.error], - ); - const blocking = errors.find(isProviderUnusable) ?? errors[0]; - if (blocking) { - return yield* toPullRequestError("list")(blocking); - } + const viewerResults = yield* resolveViewers(projects, viewerRoots); + const viewers: Record = {}; + for (const result of viewerResults) { + if (result.viewer !== null) viewers[result.host] = result.viewer; + } + const providers: ReadonlyArray = [ + ...viewerResults.map((result) => { + const capabilities = projects.find((project) => project.host === result.host)?.api + .capabilities; return { - viewers: viewers as PullRequestListResult["viewers"], - providers, - entries: [], - errors: [], - truncated: false, - nextCursors: {}, + host: result.host, + kind: result.kind, + searchesOnHost: capabilities?.search ?? false, + actions: capabilities?.actions ?? [], + projectCount: projectCounts.get(result.host) ?? 1, + configured: result.viewer !== null, + detail: result.error === null ? null : providerDetail(requirementOf, result.error), }; + }), + ...[...unimplemented].map(([host, { kind, projectCount }]) => ({ + host, + kind, + searchesOnHost: false, + actions: [], + projectCount, + configured: false, + detail: "This host cannot be browsed here yet.", + })), + ]; + + const selected = + continuation === null + ? projects + : projects.filter(({ cursorKey }) => continuation.has(cursorKey)); + const readable = selected.filter(({ host }) => viewers[host] !== undefined); + const unreadable = selected + .filter(({ host }) => viewers[host] === undefined) + .map(({ project, repository }) => ({ + projectId: project.id, + projectTitle: project.title, + message: `${repository} could not be read.`, + })); + if (readable.length === 0) { + const errors = viewerResults.flatMap((result) => + result.error === null || !selected.some(({ host }) => host === result.host) + ? [] + : [result.error], + ); + const blocking = errors.find(isProviderUnusable) ?? errors[0]; + if (blocking) { + return yield* toPullRequestError("list")(blocking); } - const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT; - const cursorOf = (project: SupportedProject): ListCursor | undefined => - continuation?.get(project.cursorKey); - - const readRepository = (project: SupportedProject): Effect.Effect => { - { - const viewer = viewers[project.host]!; - const key = project.cursorKey; - const cursor = cursorOf(project); - return project.api - .listChangeRequests({ - cwd: project.project.workspaceRoot, - repository: project.repository, - host: project.host, - state: input.state, - involvement, - viewer, - limit, - query: input.query, - filters: input.filters, - ...(cursor === undefined - ? {} - : { - cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered }, - }), - }) - .pipe( - observeRead, - Effect.map(({ value: page, observedAt }): RepositoryBatch => { - // The boundary instant was asked for inclusively, so the rows already sent at it - // come back with the slice. Dropping them here rather than asking for strictly - // older is what keeps their neighbours at the same instant from being skipped. - const items = - cursor === undefined - ? page.items - : page.items.filter( - (item) => - item.updatedAt !== cursor.updatedBefore || - !cursor.seenAt.includes(item.number), - ); - return { - key, - entries: items - .filter((item) => matchesRowFilters(item, input.filters, viewer)) - .map((item) => toEntry({ project, item, viewer, observedAt })), - errors: [], - truncated: page.truncated, - nextCursor: - page.continues && page.truncated - ? nextListCursor(cursor, page.items, items, page.cursorAdvance) - : null, - }; - }), - Effect.orElseSucceed((): RepositoryBatch => ({ - key, - entries: [], - errors: [ - { - projectId: project.project.id, - projectTitle: project.project.title, - message: `${project.repository} could not be read.`, - }, - ], - truncated: false, - nextCursor: null, - })), - ); - } + return { + viewers: viewers as PullRequestListResult["viewers"], + providers, + entries: [], + errors: [], + truncated: false, + nextCursors: {}, }; + } - const readTogether = ( - chunk: ReadonlyArray, - ): Effect.Effect> => { - const first = chunk[0]!; - const readAcross = first.api.listChangeRequestsAcross; - const separately = () => - Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY }); - if (readAcross === undefined) return separately(); - const viewer = viewers[first.host]!; - const cursor = cursorOf(first); - return readAcross({ - cwd: first.project.workspaceRoot, - host: first.host, - repositories: chunk.map((project) => project.repository), - state: input.state, - involvement, - viewer, - limit, - query: input.query, - filters: input.filters, - ...(cursor === undefined - ? {} - : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }), - }).pipe( - observeRead, - Effect.flatMap(({ value: page, observedAt }) => - Effect.flatMap(Clock.currentTimeMillis, (now) => { - const rows = new Map>(); - for (const [key, visibleAt] of searchVisibleAt) { - if (now - visibleAt > Duration.toMillis(SEARCH_VISIBILITY_TTL)) { - searchVisibleAt.delete(key); - } - } - for (const item of page.items) { - const key = item.repository.trim().toLowerCase(); - const held = rows.get(key); - if (held === undefined) rows.set(key, [item]); - else held.push(item); - searchVisibleAt.set(searchVisibilityKey(first.host, item.repository), now); - } - const boundary = page.items.reduce( - (oldest, item) => - oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest, - null, - ); - return Effect.forEach( - chunk, - (project): Effect.Effect => { - const fetched = rows.get(project.repository.trim().toLowerCase()) ?? []; - // GitHub does not index every repository for search — a renamed one answers for - // its old name with silence rather than with an error — so a repository the - // search said nothing at all about is read on its own, once, before it is - // believed. Only on its first slice: after that it has a boundary to carry on - // from, and silence past one means the rows are older rather than absent. - const lastVisible = searchVisibleAt.get( - searchVisibilityKey(project.host, project.repository), - ); - const searchIsKnownVisible = - !page.truncated && - lastVisible !== undefined && - now - lastVisible <= Duration.toMillis(SEARCH_VISIBILITY_TTL); - if ( - fetched.length === 0 && - cursorOf(project) === undefined && - !searchIsKnownVisible - ) { - return readRepository(project); - } - const cursorHere = cursorOf(project); - const items = - cursorHere === undefined - ? fetched - : fetched.filter( - (item) => - item.updatedAt !== cursorHere.updatedBefore || - !cursorHere.seenAt.includes(item.number), - ); - return Effect.succeed({ - key: project.cursorKey, - entries: items - .filter((item) => matchesRowFilters(item, input.filters, viewer)) - .map((item) => toEntry({ project, item, viewer, observedAt })), - errors: [], - truncated: page.truncated, - nextCursor: - page.truncated && boundary !== null - ? listCursorAt(cursorHere, boundary, fetched, items.length) - : null, - }); - }, - { concurrency: REPOSITORY_CONCURRENCY }, - ); + const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT; + const cursorOf = (project: SupportedProject): ListCursor | undefined => + continuation?.get(project.cursorKey); + + const readSlice = ( + project: SupportedProject, + cursor: ListCursor | undefined, + ): Effect.Effect => { + { + const viewer = viewers[project.host]!; + const key = project.cursorKey; + return project.api + .listChangeRequests({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + state: input.state, + involvement, + viewer, + limit, + query: input.query, + filters: input.filters, + ...(cursor === undefined + ? {} + : { + cursor: { + updatedBefore: cursor.updatedBefore, + delivered: cursor.delivered, + seenAt: cursor.seenAt, + resumeAfter: cursor.resumeAfter, + }, + }), + }) + .pipe( + observeRead, + Effect.map(({ value: page, observedAt }): RepositoryBatch => { + // The boundary instant was asked for inclusively, so the rows already sent at it + // come back with the slice. Dropping them here rather than asking for strictly + // older is what keeps their neighbours at the same instant from being skipped. + const items = + cursor === undefined + ? page.items + : page.items.filter( + (item) => + item.updatedAt !== cursor.updatedBefore || + !cursor.seenAt.includes(item.number), + ); + return { + key, + entries: items + .filter((item) => matchesRowFilters(item, input.filters, viewer)) + .map((item) => toEntry({ project, item, viewer, observedAt })), + errors: [], + truncated: page.truncated, + nextCursor: + page.continues && page.truncated + ? nextListCursor( + cursor, + page.items, + items, + page.cursorAdvance, + page.resumeAfter, + ) + : null, + }; }), + Effect.orElseSucceed((): RepositoryBatch => ({ + key, + entries: [], + errors: [ + { + projectId: project.project.id, + projectTitle: project.project.title, + message: `${project.repository} could not be read.`, + }, + ], + truncated: false, + nextCursor: null, + })), + ); + } + }; + + // Filters a host cannot apply thin out the slices it hands over, so a repository keeps + // reading until it has a page's worth or runs out. The reads are bounded: a filter that + // matches nothing would otherwise walk the repository's whole history in one request. + const readRepository = (project: SupportedProject): Effect.Effect => { + const fill = (batch: RepositoryBatch, reads: number): Effect.Effect => { + const cursor = batch.nextCursor === null ? null : parseListCursor(batch.nextCursor); + if ( + input.filters === undefined || + cursor === null || + batch.entries.length >= limit || + reads >= FILTERED_LIST_READS + ) { + return Effect.succeed(batch); + } + return readSlice(project, cursor).pipe( + Effect.flatMap((next) => + // A slice that failed keeps the cursor before it, so the reader can try again. + next.errors.length > 0 + ? Effect.succeed(batch) + : fill({ ...next, entries: [...batch.entries, ...next.entries] }, reads + 1), ), - Effect.catch(separately), ); }; + return readSlice(project, cursorOf(project)).pipe(Effect.flatMap((batch) => fill(batch, 1))); + }; - const together = new Map>(); - const separate: Array = []; - for (const project of readable) { - if (project.api.listChangeRequestsAcross === undefined) { - separate.push(project); - continue; - } - const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`; - const group = together.get(key); - if (group === undefined) together.set(key, [project]); - else group.push(project); - } - const reads: Array>> = separate.map((project) => - readRepository(project).pipe(Effect.map((batch) => [batch])), + const readTogether = ( + chunk: ReadonlyArray, + ): Effect.Effect> => { + const first = chunk[0]!; + const readAcross = first.api.listChangeRequestsAcross; + const separately = () => + Effect.forEach(chunk, readRepository, { concurrency: REPOSITORY_CONCURRENCY }); + if (readAcross === undefined) return separately(); + const viewer = viewers[first.host]!; + const cursor = cursorOf(first); + return readAcross({ + cwd: first.project.workspaceRoot, + host: first.host, + repositories: chunk.map((project) => project.repository), + state: input.state, + involvement, + viewer, + limit, + query: input.query, + filters: input.filters, + ...(cursor === undefined + ? {} + : { cursor: { updatedBefore: cursor.updatedBefore, delivered: cursor.delivered } }), + }).pipe( + observeRead, + Effect.flatMap(({ value: page, observedAt }) => { + const rows = new Map>(); + for (const item of page.items) { + const key = item.repository.trim().toLowerCase(); + const held = rows.get(key); + if (held === undefined) rows.set(key, [item]); + else held.push(item); + } + const unresolved = new Set( + (page.unresolved ?? []).map((repository) => repository.trim().toLowerCase()), + ); + const boundary = page.items.reduce( + (oldest, item) => + oldest === null || item.updatedAt < oldest ? item.updatedAt : oldest, + null, + ); + return Effect.forEach( + chunk, + (project): Effect.Effect => { + const key = project.repository.trim().toLowerCase(); + const fetched = rows.get(key) ?? []; + if (fetched.length === 0 && unresolved.has(key)) return readRepository(project); + const cursorHere = cursorOf(project); + const items = + cursorHere === undefined + ? fetched + : fetched.filter( + (item) => + item.updatedAt !== cursorHere.updatedBefore || + !cursorHere.seenAt.includes(item.number), + ); + return Effect.succeed({ + key: project.cursorKey, + entries: items + .filter((item) => matchesRowFilters(item, input.filters, viewer)) + .map((item) => toEntry({ project, item, viewer, observedAt })), + errors: [], + truncated: page.truncated, + nextCursor: + page.truncated && boundary !== null + ? listCursorAt(cursorHere, boundary, fetched, items.length) + : null, + }); + }, + { concurrency: REPOSITORY_CONCURRENCY }, + ); + }), + Effect.catch(separately), ); - for (const group of together.values()) { - for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) { - reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK))); - } - } - const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat(); + }; - const nextCursors: Record = {}; - for (const batch of batches) { - if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor; + const together = new Map>(); + const separate: Array = []; + for (const project of readable) { + if (project.api.listChangeRequestsAcross === undefined) { + separate.push(project); + continue; } + const key = `${project.host}\n${cursorOf(project)?.updatedBefore ?? ""}`; + const group = together.get(key); + if (group === undefined) together.set(key, [project]); + else group.push(project); + } + const reads: Array>> = separate.map((project) => + readRepository(project).pipe(Effect.map((batch) => [batch])), + ); + for (const group of together.values()) { + for (let start = 0; start < group.length; start += REPOSITORY_SEARCH_CHUNK) { + reads.push(readTogether(group.slice(start, start + REPOSITORY_SEARCH_CHUNK))); + } + } + const batches = (yield* Effect.all(reads, { concurrency: REPOSITORY_CONCURRENCY })).flat(); - return { - viewers: viewers as PullRequestListResult["viewers"], - providers, - entries: batches - .flatMap((batch) => batch.entries) - .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)), - errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)], - truncated: batches.some((batch) => batch.truncated), - nextCursors, - }; - }); + const nextCursors: Record = {}; + for (const batch of batches) { + if (batch.nextCursor !== null) nextCursors[batch.key] = batch.nextCursor; + } + + return { + viewers: viewers as PullRequestListResult["viewers"], + providers, + entries: batches + .flatMap((batch) => batch.entries) + .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)), + errors: [...unreadable, ...batches.flatMap((batch) => batch.errors)], + truncated: batches.some((batch) => batch.truncated), + nextCursors, + }; + }); const viewerOf = (project: SupportedProject): Effect.Effect => routingCredential.pipe( @@ -1389,39 +1528,37 @@ export const make = Effect.gen(function* () { host, }) .pipe(Effect.mapError(toPullRequestError("routeIdentity"))); - return { ...identity, host, provider: "github" as const }; + return { ...identity, host, provider: api.kind }; }); - const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = ( - input, - operation, - ) => - Effect.gen(function* () { - if (input.expectedAccountId === undefined) return yield* operation; - const rejected = () => - new PullRequestOperationError({ - operation: "routeIdentity", - detail: "The GitHub account could not be verified before starting the operation.", - }); - const project = yield* requireProject(input).pipe(Effect.mapError(rejected)); - const api = registry.get(project.api.kind); - if ( - api?.withVerifiedCredential === undefined || - input.host?.toLowerCase() !== project.host.toLowerCase() - ) { - return yield* rejected(); - } - const result = yield* api - .withVerifiedCredential( - { cwd: project.project.workspaceRoot, host: project.host }, - (identity) => - identity.accountId === input.expectedAccountId - ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result) - : Effect.fail(rejected()), - ) - .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) })); - return yield* Effect.fromResult(result); - }); + const withRoutingCredential: PullRequestService["Service"]["withRoutingCredential"] = Effect.fn( + "PullRequestService.withRoutingCredential", + )(function* (input, operation) { + if (input.expectedAccountId === undefined) return yield* operation; + const rejected = () => + new PullRequestOperationError({ + operation: "routeIdentity", + detail: "The signed-in account could not be verified before starting the operation.", + }); + const project = yield* requireProject(input).pipe(Effect.mapError(rejected)); + const api = registry.get(project.api.kind); + if ( + api?.withVerifiedCredential === undefined || + input.host?.toLowerCase() !== project.host.toLowerCase() + ) { + return yield* rejected(); + } + const result = yield* api + .withVerifiedCredential( + { cwd: project.project.workspaceRoot, host: project.host }, + (identity) => + identity.accountId === input.expectedAccountId + ? operation.pipe(Effect.provideService(routingCredential, identity), Effect.result) + : Effect.fail(rejected()), + ) + .pipe(Effect.catchTags({ PullRequestProviderError: () => Effect.fail(rejected()) })); + return yield* Effect.fromResult(result); + }); const routing = Effect.fn("PullRequestService.routing")(function* (input: PullRequestRef) { const project = yield* requireProject(input); @@ -1746,11 +1883,7 @@ export const make = Effect.gen(function* () { const scope = yield* Effect.scope; const runFork = Effect.runForkWith(context); - /** - * A lookup that failed is refused rather than answered as the unnamed reader: a momentarily - * signed-out CLI would otherwise hide every tick this reader has made and file the next press - * under rows that are orphaned once it recovers. - */ + // Refuse failed viewer lookups; unnamed fallbacks hide marks and orphan subsequent writes. const requiredViewerOf = ( project: SupportedProject, operation: string, @@ -1771,7 +1904,7 @@ export const make = Effect.gen(function* () { // Deliberately not `invalidatedByMutation`: ticking a file off says nothing about the // change request, and dropping a 300-file diff on every checkbox is the whole cost of // the feature. - Effect.tap(() => Effect.sync(() => bumpFilesViewedEpoch(ref))), + Effect.ensuring(Effect.sync(() => bumpFilesViewedEpoch(ref))), ), ), ); @@ -1809,9 +1942,7 @@ export const make = Effect.gen(function* () { }), ); } - // A strategy the host does not offer must be refused rather than passed on: every - // provider maps an unrecognised method to its own default, so asking Azure DevOps to - // rebase would quietly merge instead of failing. + // Refuse unsupported strategies; providers silently map unrecognized methods to their default. if ( input.mergeMethod !== undefined && !project.api.capabilities.mergeMethods.includes(input.mergeMethod) @@ -1975,12 +2106,7 @@ export const make = Effect.gen(function* () { }), ); - /** - * Neither is a question a permission read answers: every host lets the person who wrote - * something rewrite it whatever access they have otherwise, and none of them reports that as a - * permission — so a check here could only guess, and a wrong guess takes the control away from - * the one person certain to be allowed. - */ + // Hosts let authors edit without reporting that permission; checking it would wrongly deny access. const update: PullRequestService["Service"]["update"] = (input) => requireProject(input).pipe( Effect.flatMap((project): Effect.Effect => { @@ -2175,10 +2301,7 @@ export const make = Effect.gen(function* () { }), ); - /** - * Every host with reactions takes one from whoever can read the change request, so there - * is no access left to check that reading it has not already settled. - */ + // Hosts permit reactions from any reader; reading the PR already checks access. const setReaction: PullRequestService["Service"]["setReaction"] = (input) => requireProject(input).pipe( Effect.flatMap((project): Effect.Effect => { @@ -2276,6 +2399,61 @@ export const make = Effect.gen(function* () { }), ); + const filterOptions: PullRequestService["Service"]["filterOptions"] = Effect.fn( + "PullRequestService.filterOptions", + )(function* (input) { + const { supported } = yield* listWorkspaceProjects(input); + // Worktrees of one checkout are separate projects over the same repository. + const repositories = [ + ...new Map(supported.map((project) => [project.cursorKey, project])).values(), + ]; + const refOf = (project: SupportedProject) => ({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + query: input.query, + }); + // One repository the host cannot read leaves the others' options standing, as a listing does. + const gather = ( + read: ( + project: SupportedProject, + ) => Effect.Effect, PullRequestProviderError> | undefined, + ) => + Effect.forEach( + repositories, + (project): Effect.Effect>> => { + const page = read(project); + return page === undefined + ? Effect.succeed([]) + : page.pipe( + Effect.map((answered) => [answered]), + Effect.orElseSucceed(() => []), + ); + }, + { concurrency: REPOSITORY_CONCURRENCY }, + ).pipe(Effect.map((pages) => pages.flat())); + if (input.kind === "labels") { + const pages = yield* gather((project) => + project.api.listRepositoryLabels?.(refOf(project)), + ); + const { items, truncated } = rankFilterOptions(pages, { + query: input.query, + keyOf: (label) => label.name, + textsOf: (label) => [label.name], + }); + return { labels: items, authors: [], truncated }; + } + const pages = yield* gather((project) => + project.api.searchRepositoryAuthors?.(refOf(project)), + ); + const { items, truncated } = rankFilterOptions(pages, { + query: input.query, + keyOf: (author) => author.login, + textsOf: (author) => [author.login, author.name], + }); + return { labels: [], authors: items, truncated }; + }); + const labelCandidates: PullRequestService["Service"]["labelCandidates"] = (input) => requireProject(input).pipe( Effect.flatMap((project): Effect.Effect => { @@ -2347,78 +2525,78 @@ export const make = Effect.gen(function* () { * The line counts for rows already on the page, which the listing left out because on GitHub * they cost more than everything else on the row put together. */ - const listStatsUncached: PullRequestService["Service"]["listStats"] = (input) => - Effect.gen(function* () { - if (input.refs.length === 0) return { stats: [] }; - const { supported } = yield* listWorkspaceProjects({}); - const byProject = new Map(supported.map((project) => [project.project.id, project])); - const wanted = new Map< - string, - { readonly project: SupportedProject; readonly number: number } - >(); - for (const ref of input.refs) { - const project = byProject.get(ref.projectId); - if ( - project === undefined || - project.api.listChangeRequestStats === undefined || - project.repository.toLowerCase() !== ref.repository.trim().toLowerCase() - ) { - continue; - } - wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number }); - } - const byHost = new Map>(); - for (const entry of wanted.values()) { - const held = byHost.get(entry.project.host); - if (held === undefined) byHost.set(entry.project.host, [entry]); - else held.push(entry); + const listStatsUncached: PullRequestService["Service"]["listStats"] = Effect.fn( + "PullRequestService.listStatsUncached", + )(function* (input) { + if (input.refs.length === 0) return { stats: [] }; + const { supported } = yield* listWorkspaceProjects({}); + const byProject = new Map(supported.map((project) => [project.project.id, project])); + const wanted = new Map< + string, + { readonly project: SupportedProject; readonly number: number } + >(); + for (const ref of input.refs) { + const project = byProject.get(ref.projectId); + if ( + project === undefined || + project.api.listChangeRequestStats === undefined || + project.repository.toLowerCase() !== ref.repository.trim().toLowerCase() + ) { + continue; } - const stats = yield* Effect.forEach( - [...byHost.values()], - (entries) => { - const first = entries[0]!; - const readStats = first.project.api.listChangeRequestStats; - if (readStats === undefined) - return Effect.succeed>([]); - const projectsByRepository = new Map( - entries.map((entry) => [ - `${entry.project.repository.toLowerCase()} ${entry.number}`, - entry.project, - ]), - ); - return readStats({ - cwd: first.project.project.workspaceRoot, - host: first.project.host, - changeRequests: entries.map((entry) => ({ - repository: entry.project.repository, - number: entry.number, - })), - }).pipe( - Effect.map((read) => - read.flatMap((stat): ReadonlyArray => { - const project = projectsByRepository.get( - `${stat.repository.toLowerCase()} ${stat.number}`, - ); - return project === undefined - ? [] - : [ - { - projectId: project.project.id, - repository: project.repository, - number: stat.number, - additions: stat.additions, - deletions: stat.deletions, - }, - ]; - }), - ), - Effect.orElseSucceed((): ReadonlyArray => []), - ); - }, - { concurrency: REPOSITORY_CONCURRENCY }, - ); - return { stats: stats.flat() }; - }); + wanted.set(`${project.project.id} ${ref.number}`, { project, number: ref.number }); + } + const byHost = new Map>(); + for (const entry of wanted.values()) { + const held = byHost.get(entry.project.host); + if (held === undefined) byHost.set(entry.project.host, [entry]); + else held.push(entry); + } + const stats = yield* Effect.forEach( + [...byHost.values()], + (entries) => { + const first = entries[0]!; + const readStats = first.project.api.listChangeRequestStats; + if (readStats === undefined) return Effect.succeed>([]); + const projectsByRepository = new Map( + entries.map((entry) => [ + `${entry.project.repository.toLowerCase()} ${entry.number}`, + entry.project, + ]), + ); + return readStats({ + cwd: first.project.project.workspaceRoot, + host: first.project.host, + changeRequests: entries.map((entry) => ({ + repository: entry.project.repository, + number: entry.number, + })), + }).pipe( + Effect.map((read) => + read.flatMap((stat): ReadonlyArray => { + const project = projectsByRepository.get( + `${stat.repository.toLowerCase()} ${stat.number}`, + ); + return project === undefined + ? [] + : [ + { + projectId: project.project.id, + repository: project.repository, + number: stat.number, + additions: stat.additions, + deletions: stat.deletions, + }, + ]; + }), + ), + Effect.orElseSucceed((): ReadonlyArray => []), + ); + }, + { concurrency: REPOSITORY_CONCURRENCY }, + ); + return { stats: stats.flat() }; + }); const revalidate = (read: Effect.Effect) => Effect.context().pipe( @@ -2446,8 +2624,7 @@ export const make = Effect.gen(function* () { return Effect.flatMap(Clock.currentTimeMillis, (now) => { const snapshot = held.get(key); if (snapshot === undefined || now - snapshot.at > staleMs) return recorded; - // Run as its own fiber rather than a child: the caller is answered and gone before the - // refresh lands. + // Use an independent fiber; refresh outlives the answered caller. return revalidate(recorded).pipe(Effect.as(snapshot.value)); }); }; @@ -2514,8 +2691,7 @@ export const make = Effect.gen(function* () { const lastGoodSummary = makeLastGoodRead(DETAIL_CACHE_CAPACITY); const lastGoodDetail = makeLastGoodRead(DETAIL_CACHE_CAPACITY); - // The counter is shared and monotonic so a scope re-entering `refEpochs` after eviction can - // never mint a key an old entry still has. + // A shared monotonic counter prevents evicted scopes reusing epochs held by old entries. let epochCounter = 0; let listingsEpoch = 0; const refEpochs = new Map(); @@ -2546,8 +2722,6 @@ export const make = Effect.gen(function* () { } mergedEpochs.set(scope, projectEpochs.get(ref.projectId) ?? projectEpochFloor); }; - // Keys carry the reference back out of the cache loader, so the slot layout is shared with - // `refOfCacheKey` rather than read positionally at every loader. const refCacheKey = (ref: CredentialRef) => JSON.stringify([ refEpoch(ref), @@ -2780,7 +2954,11 @@ export const make = Effect.gen(function* () { host: project.host, number: input.number, }) - .pipe(Effect.mapError(toPullRequestError("checks"))), + .pipe( + Effect.mapError(toPullRequestError("checks")), + observeRead, + Effect.map(({ value, observedAt }) => ({ ...value, observedAt })), + ), ), ); }, @@ -2869,8 +3047,7 @@ export const make = Effect.gen(function* () { }); const shouldReplaceHeldSummary = (key: string, next: PullRequestSummary) => supersedesReading(lastGoodSummary.peek(key), next); - // The newest state a detail read found per pull request, whatever cache epoch or credential - // it read under. Summary reads stay out: they would hide a change from the detail read after. + // Keep newest detail states across epochs/credentials; summary reads would mask subsequent detail changes. const detailStates = new Map(); const noteDetailReading = (ref: PullRequestRef, next: PullRequestSummary) => Effect.suspend(() => { @@ -2884,10 +3061,12 @@ export const make = Effect.gen(function* () { } detailStates.set(scope, { state: next.state, + isDraft: next.isDraft, updatedAt: next.updatedAt, observedAt: next.observedAt, }); - return current?.state !== next.state && ref.host !== undefined + return (current?.state !== next.state || current?.isDraft !== next.isDraft) && + ref.host !== undefined ? PubSub.publish(stateChanges, { host: ref.host, repository: ref.repository, @@ -2895,26 +3074,37 @@ export const make = Effect.gen(function* () { }) : Effect.void; }); - // The last state each routed read reported, kept apart from `detailStates`: an unverified report - // must never outrank a reading this environment made itself. + // Keep routed reports separate; unverified reports must not outrank this environment's reads. const reportedStates = new Map< string, - { readonly state: PullRequestState; readonly atMs: number } + { + readonly state: PullRequestState; + readonly isDraft: boolean | undefined; + readonly atMs: number; + } >(); - const reportState: PullRequestService["Service"]["reportState"] = ({ reference, state }) => + const reportState: PullRequestService["Service"]["reportState"] = ({ + reference, + state, + isDraft, + }) => Effect.all([canonicalRef(reference), Clock.currentTimeMillis]).pipe( Effect.flatMap(([ref, nowMs]) => Effect.suspend(() => { const scope = refScope(ref); const reported = reportedStates.get(scope); - if (reported?.state === state && nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS) + if ( + reported?.state === state && + reported.isDraft === isDraft && + nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS + ) return Effect.void; reportedStates.delete(scope); if (reportedStates.size >= REF_EPOCH_CAPACITY) { const oldest = reportedStates.keys().next().value; if (oldest !== undefined) reportedStates.delete(oldest); } - reportedStates.set(scope, { state, atMs: nowMs }); + reportedStates.set(scope, { state, isDraft, atMs: nowMs }); return ref.host === undefined ? Effect.void : PubSub.publish(stateChanges, { @@ -2927,9 +3117,7 @@ export const make = Effect.gen(function* () { ); const detail: PullRequestService["Service"]["detail"] = (input) => { const key = refCacheKey(input); - // Skip the write when that read is older than a later strict summary — - // display reuse would otherwise keep the regression and never ask the host - // again. + // Skip reads older than strict summaries; caching them would preserve regressions without asking the host again. const read = Cache.get(detailCache, key).pipe( Effect.tap((value) => { if (value.state === "merged") noteMerged(input); @@ -2959,6 +3147,32 @@ export const make = Effect.gen(function* () { }, ); + const changeBreakdownCache = yield* Cache.makeWith( + (key: string) => { + const ref = refOfCacheKey(key); + return requireProject(ref).pipe( + Effect.flatMap((project) => { + const read = project.api.getFileStats; + if (read === undefined) return Effect.succeed(null); + return read({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: ref.number, + }).pipe( + Effect.map(toChangeBreakdown), + Effect.mapError(toPullRequestError("changeBreakdown")), + ); + }), + ); + }, + { + capacity: DETAIL_CACHE_CAPACITY, + timeToLive: (exit, key) => + Exit.isSuccess(exit) ? detailTimeToLive(lastGoodSummary.peek(key)?.state) : Duration.zero, + }, + ); + const previewCache = yield* Cache.makeWith( (key: string) => { return previewUncached(refOfCacheKey(key)); @@ -2992,7 +3206,14 @@ export const make = Effect.gen(function* () { ...refOfCacheKey(reference), ...(cursor === null ? {} : { cursor }), ...(commit === null ? {} : { commit }), - } as PullRequestDiffInput); + } as PullRequestDiffInput).pipe( + observeRead, + Effect.map(({ value, observedAt }) => { + // Keep the loader's epoch and read time if a refresh occurs during the provider read. + diffFiles.record(JSON.stringify([reference, cursor, commit]), value, observedAt); + return value; + }), + ); }, { capacity: DIFF_CACHE_CAPACITY, @@ -3003,13 +3224,9 @@ export const make = Effect.gen(function* () { }, }, ); - /** - * Both diff holders drop an expired value only when its own key is read again, and a diff's key - * moves with every push, so a closed page's patches would stay held until the server restarted. - */ + // Diffs expire only when their keys are reread; push-dependent keys leave closed pages' patches retained. let diffSweepPending = false; - // Forked from the service's own context, in one step with the flag: a caller's interruption - // cannot strand the flag, and its request is not kept alive by the wait. + // Fork in service context atomically with the flag to avoid stranded flags and retained caller requests. const armDiffSweep = () => { if (diffSweepPending) return; diffSweepPending = true; @@ -3066,8 +3283,7 @@ export const make = Effect.gen(function* () { timeToLive: (exit) => (Exit.isSuccess(exit) ? FILES_VIEWED_CACHE_TTL : Duration.zero), }, ); - // Canonicalised before it is keyed: both epochs are bumped against the remote's own spelling, - // so a reference keyed as the client spelled it would never see a refresh or a press. + // Key canonical refs to match epochs bumped with the remote's spelling. const filesViewed: PullRequestService["Service"]["filesViewed"] = (input) => canonicalRef(input).pipe( Effect.flatMap((ref) => @@ -3249,10 +3465,7 @@ export const make = Effect.gen(function* () { ); }); - /** - * The file names in each diff slice, keyed as the slice is. Names stay small when a patch is too - * large to cache, so expanding a file in a large change request does not fetch its diff again. - */ + // Cache small filename lists even when patches exceed limits, avoiding diff refetches on file expansion. const diffFiles = (() => { const held = new Map< string, @@ -3266,36 +3479,56 @@ export const make = Effect.gen(function* () { const fileKey = (oldPath: string, newPath: string) => JSON.stringify([oldPath, newPath]); const sliceKey = (input: PullRequestDiffInput) => JSON.stringify([refCacheKey(input), input.cursor ?? null, input.commit ?? null]); - const read = (input: PullRequestDiffInput) => - Effect.gen(function* () { - const key = sliceKey(input); - const now = yield* Clock.currentTimeMillis; - const cached = held.get(key); - if (cached !== undefined && now - cached.at <= ttlMs) return cached; - const slice = yield* diff(input); - const entry = { - at: now, - files: new Set( - parseDiffFilePaths(slice.patch).map((file) => - fileKey(file.oldPath ?? file.newPath ?? "", file.newPath ?? file.oldPath ?? ""), - ), - ), + const recordPaths = (key: string, slice: ProviderDiffFilePaths, at: number) => { + const entry = { + at, + files: new Set(slice.files.map((file) => fileKey(file.oldPath, file.newPath))), + nextCursor: slice.nextCursor, + }; + held.delete(key); + if (held.size >= DIFF_CACHE_CAPACITY) { + const oldest = held.keys().next().value; + if (oldest !== undefined) held.delete(oldest); + } + held.set(key, entry); + return entry; + }; + const record = (key: string, slice: PullRequestDiffResult, at: number) => + recordPaths( + key, + { + files: parseDiffFilePaths(slice.patch).map((file) => ({ + oldPath: file.oldPath ?? file.newPath ?? "", + newPath: file.newPath ?? file.oldPath ?? "", + })), nextCursor: slice.nextCursor, - }; - held.delete(key); - if (held.size >= DIFF_CACHE_CAPACITY) { - const oldest = held.keys().next().value; - if (oldest !== undefined) held.delete(oldest); - } - held.set(key, entry); - return entry; - }); - return { read: credentialCached(read), fileKey }; + }, + at, + ); + const read = Effect.fn("PullRequestService.read")(function* (input: PullRequestDiffInput) { + const key = sliceKey(input); + const now = yield* Clock.currentTimeMillis; + const cached = held.get(key); + if (cached !== undefined && now - cached.at <= ttlMs) return cached; + const project = yield* requireProject(input); + if (project.api.capabilities.diff && project.api.getDiffFilePaths) { + const slice = yield* project.api + .getDiffFilePaths({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + ...(input.cursor === undefined ? {} : { cursor: input.cursor }), + ...(input.commit === undefined ? {} : { commit: input.commit }), + }) + .pipe(Effect.mapError(toPullRequestError("diffFileContents"))); + return recordPaths(key, slice, now); + } + const slice = yield* diff(input); + return record(key, slice, now); + }); + return { read: credentialCached(read), record, fileKey }; })(); - /** - * Whether the change request, or the one commit asked for, changes this file under these names. - * Walks the same slices the reader was shown, reading only their file names once held. - */ const changesFile = (input: PullRequestDiffFileContentsInput) => { const wanted = diffFiles.fileKey(input.oldPath, input.newPath); const walk = (cursor: string | undefined): Effect.Effect => @@ -3316,9 +3549,7 @@ export const make = Effect.gen(function* () { ); return walk(undefined); }; - // Only the files the change request itself changes: these are read with the project's own - // credential, and a reader who may look at the change request may not thereby read the rest of - // the repository. + // PR read access does not grant arbitrary repository reads with the project credential; restrict to changed files. const diffFileContents: PullRequestService["Service"]["diffFileContents"] = (input) => changesFile(input).pipe( Effect.flatMap((changed) => @@ -3339,6 +3570,7 @@ export const make = Effect.gen(function* () { routingIdentity, withRoutingCredential, list, + filterOptions, listStats: (input) => Effect.forEach(input.refs, (ref) => canonicalRef(ref).pipe(Effect.option)).pipe( Effect.flatMap((refs) => listStats({ ...input, refs: refs.flatMap(Option.toArray) })), @@ -3368,6 +3600,9 @@ export const make = Effect.gen(function* () { diffFileContents, filesViewed: credentialCached(filesViewed), setFilesViewed, + changeBreakdown: credentialCached((input) => + Cache.get(changeBreakdownCache, refCacheKey(input)), + ), runAction: runActionAndInvalidate, update: invalidatedByMutation(update), comment: invalidatedByMutation(comment), diff --git a/apps/server/src/pullRequest/http.ts b/apps/server/src/pullRequest/http.ts index 746e29a506a65..0e9f353900eb3 100644 --- a/apps/server/src/pullRequest/http.ts +++ b/apps/server/src/pullRequest/http.ts @@ -6,7 +6,7 @@ import { annotateEnvironmentRequest, requireEnvironmentScope } from "../auth/htt import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts"; import * as PullRequestService from "./PullRequestService.ts"; -/** The patch is often the largest PR payload and benefits from HTTP compression and flow control. */ +// Large patches benefit from HTTP compression and flow control. export const layer = HttpApiBuilder.group( EnvironmentHttpApi, "pullRequests", diff --git a/apps/server/src/pullRequest/linkedThreads.test.ts b/apps/server/src/pullRequest/linkedThreads.test.ts index 8b1d276420291..230758714b381 100644 --- a/apps/server/src/pullRequest/linkedThreads.test.ts +++ b/apps/server/src/pullRequest/linkedThreads.test.ts @@ -101,16 +101,6 @@ it.effect( ) `; } - yield* sql` - INSERT INTO orchestration_v2_projection_threads ( - thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, - created_at, updated_at, payload_json - ) VALUES ( - 'legacy-single', 'project-1', 'legacy-single', 'codex', 'full-access', 'default', - ${createdAt}, ${createdAt}, - '{"linkedPullRequest":{"projectId":"project-1","repository":"acme/web","number":7,"url":"https://github.com/acme/web/pull/7"}}' - ) - `; yield* sql` INSERT INTO orchestration_v2_projection_threads ( thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, @@ -169,7 +159,6 @@ it.effect( threads: [ { id: "archived", projectId: "project-1", title: "archived", archivedAt }, { id: "active", projectId: "project-1", title: "active", archivedAt: null }, - { id: "legacy-single", projectId: "project-1", title: "legacy-single", archivedAt: null }, ], }); assert.deepStrictEqual( diff --git a/apps/server/src/pullRequest/linkedThreads.ts b/apps/server/src/pullRequest/linkedThreads.ts index f5bf1d9c286c3..c7a2b01946a2b 100644 --- a/apps/server/src/pullRequest/linkedThreads.ts +++ b/apps/server/src/pullRequest/linkedThreads.ts @@ -1,14 +1,14 @@ import { - legacyThreadPullRequestKey, normalizeThreadPullRequestKey, threadPullRequestKeysEqual, -} from "@t3tools/shared/threadPullRequests"; +} from "../sourceControl/threadPullRequests.ts"; import { PullRequestLinkedThreadsResult, PullRequestOperationError, type ThreadPullRequestKey, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; @@ -23,7 +23,7 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre projectId: string; title: string; archivedAt: string | null; - host: string | null; + host: string; repository: string; number: number; url: string; @@ -39,27 +39,10 @@ export const listLinkedPullRequestThreads = Effect.fn("listLinkedPullRequestThre WHERE json_extract(link.value, '$.number') = ${key.number} AND json_extract(link.value, '$.source') != 'stack-dismissed' AND t.deleted_at IS NULL - UNION ALL - SELECT t.thread_id AS id, t.project_id AS "projectId", t.title, - t.archived_at AS "archivedAt", NULL AS host, - json_extract(t.payload_json, '$.linkedPullRequest.repository') AS repository, - json_extract(t.payload_json, '$.linkedPullRequest.number') AS number, - json_extract(t.payload_json, '$.linkedPullRequest.url') AS url, - t.updated_at AS "updatedAt" - FROM orchestration_v2_projection_threads AS t - WHERE json_type(t.payload_json, '$.pullRequests') IS NULL - AND json_type(t.payload_json, '$.linkedPullRequest') = 'object' - AND json_extract(t.payload_json, '$.linkedPullRequest.number') = ${key.number} - AND t.deleted_at IS NULL ORDER BY "updatedAt" DESC, id ASC - `; + `.pipe(NodeSqliteClient.readOnly); const threads = rows - .filter((row) => - threadPullRequestKeysEqual( - row.host === null ? legacyThreadPullRequestKey(row) : { ...row, host: row.host }, - key, - ), - ) + .filter((row) => threadPullRequestKeysEqual(row, key)) .map(({ id, projectId, title, archivedAt }) => ({ id, projectId, title, archivedAt })); return yield* decodeLinkedThreads({ threads }); }, diff --git a/apps/server/src/pullRequest/pullRequestChangeBreakdown.ts b/apps/server/src/pullRequest/pullRequestChangeBreakdown.ts new file mode 100644 index 0000000000000..eaaf50c0d868c --- /dev/null +++ b/apps/server/src/pullRequest/pullRequestChangeBreakdown.ts @@ -0,0 +1,21 @@ +import type { PullRequestChangeBreakdown } from "@t3tools/contracts"; +import { classifyChangedFile } from "@t3tools/shared/changedFileKind"; +import type { ProviderFileStats } from "@t3tools/source-control-core/server/PullRequestProvider"; + +export function toChangeBreakdown(stats: ProviderFileStats): PullRequestChangeBreakdown { + if (stats.truncated) return null; + const empty = () => ({ additions: 0, deletions: 0 }); + const breakdown = { + code: empty(), + tests: empty(), + mocks: empty(), + generated: empty(), + docs: empty(), + }; + for (const file of stats.files) { + const bucket = breakdown[classifyChangedFile(file.path)]; + bucket.additions += file.additions; + bucket.deletions += file.deletions; + } + return breakdown; +} diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideInput.test.ts b/apps/server/src/pullRequest/pullRequestReviewGuideInput.test.ts deleted file mode 100644 index 3db791492c6d2..0000000000000 --- a/apps/server/src/pullRequest/pullRequestReviewGuideInput.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import type { PullRequestActivity, PullRequestReviewThread } from "@t3tools/contracts"; - -import { settledReviewSummary } from "./pullRequestReviewGuideInput.ts"; - -const thread = ( - overrides: Partial & { body?: string; login?: string }, -): PullRequestReviewThread => ({ - id: overrides.id ?? "t1", - path: overrides.path ?? "src/a.ts", - line: 1, - side: "right", - isResolved: overrides.isResolved ?? false, - isOutdated: overrides.isOutdated ?? false, - comments: [ - { - id: "c1", - author: { login: overrides.login ?? "macroscope[bot]", name: null, avatarUrl: null }, - body: overrides.body ?? "Possible null dereference", - createdAt: "2026-10-01T00:00:00.000Z", - url: null, - }, - ], -}); - -const activity = (reviewThreads: ReadonlyArray): PullRequestActivity => ({ - comments: [], - commentCount: 0, - commentsTruncated: false, - reviewThreads, - commits: [], -}); - -describe("settledReviewSummary", () => { - it("lists resolved and outdated threads and leaves open ones for the guide", () => { - const summary = settledReviewSummary( - activity([ - thread({ id: "open", path: "src/open.ts", body: "Still open" }), - thread({ id: "resolved", path: "src/a.ts", isResolved: true }), - thread({ - id: "outdated", - path: "src/b.ts", - isOutdated: true, - login: "julius", - body: "Rename this \n\nplease", - }), - ]), - ); - - expect(summary).toBe( - [ - "- src/a.ts (resolved, macroscope[bot]): Possible null dereference", - "- src/b.ts (outdated, julius): Rename this please", - ].join("\n"), - ); - }); -}); diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts b/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts index 353c10eb52602..2f483490e86ed 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts @@ -11,7 +11,7 @@ function oneLine(text: string): string { return flat.length > SETTLED_REMARK_CHARS ? `${flat.slice(0, SETTLED_REMARK_CHARS)}…` : flat; } -export function settledReviewSummary(activity: PullRequestActivity): string { +function settledReviewSummary(activity: PullRequestActivity): string { return activity.reviewThreads .filter((thread) => thread.isResolved || thread.isOutdated) .flatMap((thread) => { diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts index 233013ac7146d..69479b1ccfeed 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts @@ -121,18 +121,6 @@ describe("normalizeReviewGuide", () => { expect(result.stops).toHaveLength(1); }); - it("keeps a long excerpt to its first 25 lines", () => { - const long = parseReviewGuideChange( - "big.ts\0", - "--- a/big.ts\n+++ b/big.ts\n@@ -0,0 +1,100 @@\n", - ); - const result = normalizeReviewGuide( - guide({ stops: [stop({ excerpts: [excerpt("big.ts", 1, 100)] })] }), - long, - ); - expect(result.stops[0]?.excerpts).toEqual([excerpt("big.ts", 1, 25)]); - }); - it("drops notes outside the stop's remaining excerpts", () => { const result = normalizeReviewGuide( guide({ diff --git a/apps/server/src/pullRequest/pullRequestSyncKey.test.ts b/apps/server/src/pullRequest/pullRequestSyncKey.test.ts index 2b21e20d15fcd..48db0795edbab 100644 --- a/apps/server/src/pullRequest/pullRequestSyncKey.test.ts +++ b/apps/server/src/pullRequest/pullRequestSyncKey.test.ts @@ -1,19 +1,17 @@ -import { ProjectId } from "@t3tools/contracts"; +import { ProjectId, SourceControlProviderKind } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { pullRequestSyncKey } from "./pullRequestSyncKey.ts"; describe("pullRequestSyncKey", () => { const reference = { projectId: ProjectId.make("project"), repository: "web", number: 7 }; - it.each([ - "dev.azure.com/org/project/_git/web", - "ssh.dev.azure.com/v3/org/project/web", - "vs-ssh.visualstudio.com/v3/org/project/web", - "org.visualstudio.com/defaultcollection/project/_git/web", - ])("resolves hostless and checkout-host Azure references for %s", (canonicalKey) => { + // Every spelling of the key reaches dev.azure.com through the definition's canonical key, + // which the Azure DevOps package tests. + it("resolves hostless and checkout-host references named by the bare repository", () => { + const canonicalKey = "ssh.dev.azure.com/v3/org/project/web"; const identity = { canonicalKey, - provider: "azure-devops", + provider: SourceControlProviderKind.make("azure-devops"), name: "web", displayName: canonicalKey.split("/").slice(1).join("/"), locator: { diff --git a/apps/server/src/pullRequest/pullRequestSyncKey.ts b/apps/server/src/pullRequest/pullRequestSyncKey.ts index 3b5ecc380d031..1e74563fd6104 100644 --- a/apps/server/src/pullRequest/pullRequestSyncKey.ts +++ b/apps/server/src/pullRequest/pullRequestSyncKey.ts @@ -1,43 +1,39 @@ -import { - pullRequestHostOf, - type PullRequestRef, - type RepositoryIdentity, - SourceControlProviderKind, - type ThreadPullRequestKey, -} from "@t3tools/contracts"; -import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl"; -import { normalizeThreadPullRequestKey } from "@t3tools/shared/threadPullRequests"; +import type { PullRequestRef, RepositoryIdentity, ThreadPullRequestKey } from "@t3tools/contracts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; +import { normalizeThreadPullRequestKey } from "../sourceControl/threadPullRequests.ts"; export function pullRequestSyncKey( reference: PullRequestRef, identity?: RepositoryIdentity | null, ): ThreadPullRequestKey | null { - if (identity?.provider === "azure-devops" && !reference.repository.includes("/")) { + const host = identity + ? sourceControlDefinitions.changeRequestHost(identity, identity.provider) + : undefined; + // A host whose tools select a repository by something other than its path (Azure DevOps takes + // the bare name) can only key such a reference through the project's own repository. + const definition = identity?.provider + ? sourceControlDefinitions.find(identity.provider) + : undefined; + if (identity && definition?.repositorySelector && !reference.repository.includes("/")) { if ( reference.repository.toLowerCase() !== - sourceControlRepositorySelector(identity)?.toLowerCase() || - (reference.host !== undefined && - reference.host.toLowerCase() !== - pullRequestHostOf(identity, SourceControlProviderKind.make("azure-devops"))) + definition.repositorySelector(identity)?.toLowerCase() || + (reference.host !== undefined && reference.host.toLowerCase() !== host) ) return null; - const [host, ...repository] = identity.canonicalKey.split("/"); - if (!host || repository.length === 0) return null; + const [projectHost, ...repository] = identity.canonicalKey.split("/"); + if (!projectHost || repository.length === 0) return null; return normalizeThreadPullRequestKey({ - host, + host: projectHost, repository: repository.join("/"), number: reference.number, }); } - const host = - reference.host ?? - (identity - ? pullRequestHostOf(identity, identity.provider as SourceControlProviderKind) - : undefined); - return host === undefined + const resolvedHost = reference.host ?? host; + return resolvedHost === undefined ? null : normalizeThreadPullRequestKey({ - host, + host: resolvedHost, repository: reference.repository, number: reference.number, }); diff --git a/apps/server/src/pullRequest/pullRequestViewedFiles.ts b/apps/server/src/pullRequest/pullRequestViewedFiles.ts index 59402ee1d9c77..596808eb46a07 100644 --- a/apps/server/src/pullRequest/pullRequestViewedFiles.ts +++ b/apps/server/src/pullRequest/pullRequestViewedFiles.ts @@ -19,13 +19,13 @@ import type { PullRequestError, SupportedProject } from "./PullRequestService.ts const FILE_REVISIONS_CACHE_TTL = Duration.seconds(60); const FILE_REVISIONS_STALE_WINDOW = Duration.minutes(10); -export const FILE_REVISIONS_CACHE_CAPACITY = 64; +const FILE_REVISIONS_CACHE_CAPACITY = 64; /** * Bounds a single scope, not how many scopes are held: a reader ticking one file after * another renews the same scope and grows it without limit otherwise. */ -export const MAX_FILE_REVISION_PATHS = 1_000; +const MAX_FILE_REVISION_PATHS = 1_000; interface FileRevisionsDependencies { readonly runFork: (effect: Effect.Effect) => unknown; @@ -46,10 +46,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { const heldFileRevisions = new Map(); const refreshingFileRevisions = new Set(); - /** - * Spelled from the project rather than the reference, since a reference arrives however - * the client spelled it while the epoch is bumped against the remote's own spelling. - */ + // Epochs use remote spelling; canonicalize client refs before keying. const fileRevisionsKey = (project: SupportedProject, ref: PullRequestRef) => [ refEpoch({ ...ref, host: project.host, repository: project.repository }), @@ -92,8 +89,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { const oldest = heldFileRevisions.keys().next().value; if (oldest !== undefined) heldFileRevisions.delete(oldest); } - // The entry is only as fresh as its oldest revision: stamping it with `now` on a partial - // answer would let an old revision ride past the point it should have been re-read. + // Partial answers retain the oldest timestamp so carried revisions cannot outlive their freshness. const stamped = [...revisions.keys()].every((path) => answer.revisions.has(path)) ? at : (carried?.at ?? at); @@ -110,11 +106,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { return paths.every((path) => held.asked.has(path)) ? held : null; }; - /** - * `held` answers from a stale value and refetches off the critical path, since a badge a - * moment behind beats a page that won't paint until the host answers; `fresh` is for the - * press itself, which must not store a revision the head already moved off. - */ + // Held reads refresh off the critical path; presses need fresh revisions to avoid saving obsolete heads. const fileRevisionsOf = ( project: SupportedProject, ref: PullRequestRef, @@ -124,8 +116,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { ): Effect.Effect | null, PullRequestError> => { const read = project.api.getFileRevisions; if (read === undefined) return Effect.succeed(null); - // Suspended, so a held answer costs the host nothing: a provider is free to do its work as - // the request is built rather than as the effect is run. + // Suspend request construction too; providers may start work while building requests. const fetch = Effect.suspend(() => { const key = fileRevisionsKey(project, ref); return read({ @@ -147,8 +138,7 @@ const makeFileRevisions = (dependencies: FileRevisionsDependencies) => { return Effect.succeed(held.revisions); if (freshness === "fresh") return fetch; if (refreshingFileRevisions.has(key)) return Effect.succeed(held.revisions); - // Its own fiber rather than a child: the caller has been answered and is gone before this - // lands. + // Refresh independently; it outlives the answered caller. return Effect.sync(() => { refreshingFileRevisions.add(key); runFork( @@ -174,10 +164,7 @@ export interface Dependencies extends FileRevisionsDependencies { ) => Effect.Effect; } -// A plain factory rather than a `Context.Service` (against the preference in -// `.repos/effect-smol/LLMS.md`): the held revisions, refresh set, and write gates are only correct -// at one instance per service, and a layer provided at two points would give two of each behind -// one epoch counter. +// Use one factory instance per service; multiple layers would duplicate revision state and gates behind one epoch. export const make = (dependencies: Dependencies) => { const { filesViewedStore, requireProject, requiredViewerOf, toPullRequestError } = dependencies; const { fileRevisionsOf } = makeFileRevisions(dependencies); @@ -196,11 +183,11 @@ export const make = (dependencies: Dependencies) => { cause, }); - const environmentFilesViewed = ( - project: SupportedProject, - ref: PullRequestRef, - ): Effect.Effect => - Effect.gen(function* () { + const environmentFilesViewed = Effect.fn("pullRequestViewedFiles.environmentFilesViewed")( + function* ( + project: SupportedProject, + ref: PullRequestRef, + ): Effect.fn.Return { const viewer = yield* requiredViewerOf(project, "filesViewed"); const held = yield* filesViewedStore .list(filesViewedScope(project, ref.number, viewer)) @@ -234,12 +221,10 @@ export const make = (dependencies: Dependencies) => { }), truncated: held.truncated, }; - }); + }, + ); - /** - * A tick's host round trip is slower than an untick's, so unordered presses could finish - * out of order and leave a stale tick standing over a later untick. - */ + // Serialize presses so slower tick lookups cannot overwrite later unticks. const filesViewedGates = new Map< string, { readonly gate: Semaphore.Semaphore; pending: number } @@ -250,9 +235,7 @@ export const make = (dependencies: Dependencies) => { number: number, write: Effect.Effect, ) => - // Suspended rather than generated, so finding the gate, putting it in and taking a place in - // its queue are one step: yielding for `Semaphore.make` between the lookup and the insert - // lets two presses each make a gate of their own and neither wait on the other. + // Atomically find, register and queue on gates; yielding during creation lets concurrent presses use separate gates. Effect.suspend(() => { const key = `${project.project.id} ${project.remote} ${number}`; const held = filesViewedGates.get(key); @@ -271,11 +254,11 @@ export const make = (dependencies: Dependencies) => { ); }); - const environmentSetFilesViewed = ( - project: SupportedProject, - input: PullRequestSetFilesViewedInput, - ): Effect.Effect => - Effect.gen(function* () { + const environmentSetFilesViewed = Effect.fn("pullRequestViewedFiles.environmentSetFilesViewed")( + function* ( + project: SupportedProject, + input: PullRequestSetFilesViewedInput, + ): Effect.fn.Return { const viewer = yield* requiredViewerOf(project, "setFilesViewed"); const cleared = input.files.filter((file) => file.viewed).map((file) => file.path); const revisions = @@ -293,9 +276,7 @@ export const make = (dependencies: Dependencies) => { yield* filesViewedStore .set({ ...filesViewedScope(project, input.number, viewer), - // A path left out of the answer stores with no baseline, not the empty revision, since - // the empty revision is itself an answer and would misreport the file once it turns - // out to have a version after all. + // Missing paths have null baselines; empty revision means confirmed deletion. files: input.files.map((file) => ({ path: file.path, revision: revisions?.get(file.path) ?? null, @@ -304,7 +285,8 @@ export const make = (dependencies: Dependencies) => { viewedAt, }) .pipe(Effect.mapError(toFilesViewedStoreError("setFilesViewed"))); - }); + }, + ); const filesViewed = (input: PullRequestRef) => requireProject(input).pipe( diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 285f2cfe1f9bc..3ed240d754cce 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -187,6 +187,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( catchUp.shellSnapshotReads += 1; return { schemaVersion: 2, snapshotSequence: 1, threads: [], archivedThreads: [] }; }), + listActiveSubagentThreadIds: unused, readShellSnapshot: unused, ensureLegacyTranscript: unused, dispatch: unused, @@ -214,6 +215,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( settleThread: unused, interruptThread: unused, stopWorkflow: () => Effect.die("unused stopWorkflow"), + awaitBackgroundTasks: unused, stopDelegatedTasks: unused, getThreadEventSequence: unused, recoverDelegatedTask: unused, @@ -287,45 +289,6 @@ const makeTestRelay = Effect.fnUntraced(function* ( }); describe("AgentAwarenessRelay", () => { - it("ignores transcript and tool updates but retains activity and metadata changes", () => { - for (const type of [ - "message.updated", - "turn-item.updated", - "provider-turn.updated", - "thread.visited", - "thread.pinned", - ] as const) { - assert.isFalse(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type })); - } - for (const type of [ - "run.created", - "run.updated", - "runtime-request.updated", - "subagent.updated", - "provider-thread.updated", - "thread.metadata-updated", - "thread.model-selection-updated", - "thread.provider-switched", - "thread.archived", - "thread.unarchived", - "thread.deleted", - ] as const) { - assert.isTrue(AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type })); - } - }); - - it("does not publish imported thread creation as new agent activity", () => { - assert.isFalse( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ - type: "thread.created", - payload: { historyOrigin: "v1_import" }, - }), - ); - assert.isTrue( - AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({ type: "thread.created", payload: {} }), - ); - }); - it.effect("coalesces queued updates and reruns a thread dirtied during publishing", () => Effect.gen(function* () { const started = yield* Deferred.make(); @@ -390,22 +353,6 @@ describe("AgentAwarenessRelay", () => { }), ); - it.effect("stops before shell reads when disabled and republishes after re-enabling", () => - Effect.gen(function* () { - const { relay, secrets, secretReads, shellReads, publications } = yield* makeTestRelay(); - yield* relay.publishThread(THREAD_ID); - yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false")); - const previousReads = secretReads.length; - yield* relay.publishThread(THREAD_ID); - assert.deepEqual(secretReads.slice(previousReads), [PUBLISH_AGENT_ACTIVITY_SECRET]); - assert.equal(shellReads.length, 1); - assert.equal(publications.length, 1); - yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")); - yield* relay.publishThread(THREAD_ID); - assert.equal(publications.length, 2); - }), - ); - it.effect("republishes unchanged state with fresh credentials after relinking", () => Effect.gen(function* () { const { relay, secrets, publications } = yield* makeTestRelay(); @@ -428,347 +375,183 @@ describe("AgentAwarenessRelay", () => { }), ); - it.effect("a stalled response body releases later threads and uses bounded retries", () => - Effect.gen(function* () { - const bodyStarted = Promise.withResolvers(); - const secondRead = yield* Deferred.make(); - const currentShell = yield* Ref.make(shell()); - const { relay, publications } = yield* makeTestRelay({ - readShell: (threadId) => - threadId === SECOND_THREAD_ID - ? Deferred.succeed(secondRead, undefined).pipe( - Effect.as(shell({ id: SECOND_THREAD_ID })), - ) - : Ref.get(currentShell), - respond: (attempt) => { - if (attempt !== 1) return new Response("relay unavailable", { status: 503 }); - const response = new Response(null, { - headers: { "content-type": "application/json" }, - }); - return Object.assign(response, { - arrayBuffer: () => { - bodyStarted.resolve(); - return new Promise(() => {}); - }, - }); - }, - }); - const first = yield* relay.publishThread(THREAD_ID).pipe(Effect.forkChild); - yield* Effect.promise(() => bodyStarted.promise); - const second = yield* relay.publishThread(SECOND_THREAD_ID).pipe(Effect.forkChild); - yield* TestClock.adjust("9999 millis"); - assert.equal(publications.length, 1); - yield* Ref.set(currentShell, shell({ title: "Latest title" })); - yield* TestClock.adjust("1 millis"); - assert.isTrue(yield* Deferred.isDone(secondRead)); - yield* Fiber.join(first); - yield* Fiber.join(second); - assert.equal(publications.length, 2); - assert.isTrue(publications[1]?.url.includes(SECOND_THREAD_ID) ?? false); - for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) { - const attempts = publications.length; - yield* TestClock.adjust(delay - 1); + it.effect.each(["completed", "failed"] as const)( + "publishes a tombstone when a %s thread is settled through a domain event", + (status) => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const pulls = yield* Queue.unbounded(); + const { relay, currentShell, publications } = yield* makeTestRelay({ + domainEvents: Stream.fromEffectRepeat( + Queue.offer(pulls, undefined).pipe(Effect.andThen(Queue.take(events))), + ), + }); + yield* relay.start(); + yield* Queue.take(pulls); + yield* relay.publishThread(THREAD_ID); + const terminal = shell({ status }); + yield* Ref.set(currentShell, terminal); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(publications.length, attempts); - yield* TestClock.adjust(1); + assert.equal(publications[1]?.state?.phase, status); + + const now = yield* DateTime.now; + const settled = { + ...terminal, + settledOverride: "settled" as const, + settledAt: now, + lastVisitedAt: null, + }; + yield* Ref.set(currentShell, settled); + yield* Queue.offer(events, { + id: EventId.make("event:settled"), + type: "thread.settled", + threadId: THREAD_ID, + occurredAt: now, + payload: settled, + }); + yield* Queue.take(pulls); yield* relay.drain; - assert.equal(publications.length, attempts + 2); - assert.equal(publications[attempts]?.state?.threadTitle, "Latest title"); - } - yield* TestClock.adjust("1 minute"); - yield* relay.drain; - assert.equal(publications.length, 12); - }), + assert.equal(publications.length, 2); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + assert.equal(publications.length, 3); + assert.equal(publications[2]?.state, null); + }).pipe(Effect.scoped), ); - it.effect("retries a failed final state without another thread event", () => + it.effect("holds a completion through a continuation gap, then publishes it once", () => Effect.gen(function* () { - const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({ - respond: (attempt) => - attempt === 2 - ? new Response("relay unavailable", { status: 503 }) - : Response.json({ ok: true, deliveries: [] }), - }); + const { relay, currentShell, publications } = yield* makeTestRelay(); yield* relay.publishThread(THREAD_ID); - yield* Ref.set( - currentShell, - shell({ - status: "completed", - latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }), - }), - ); + yield* Ref.set(currentShell, shell({ status: "completed" })); yield* relay.publishThread(THREAD_ID); - assert.equal(publications.length, 2); - yield* TestClock.adjust("1 second"); - yield* relay.drain; - assert.equal(publications.length, 3); - assert.equal(publications[2]?.state?.phase, "completed"); - yield* TestClock.adjust("1 minute"); + yield* Ref.set(currentShell, shell()); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(shellReads.length, 3); - }), - ); + assert.deepEqual( + publications.map((publication) => publication.state?.phase), + ["running"], + ); - it.effect("retries the latest shell and credentials with first-completion confirmation", () => - Effect.gen(function* () { - const { relay, secrets, currentShell, publications } = yield* makeTestRelay({ - respond: (attempt) => - attempt === 1 - ? new Response("relay unavailable", { status: 503 }) - : Response.json({ ok: true, deliveries: [] }), - }); + yield* Ref.set(currentShell, shell({ status: "completed" })); yield* relay.publishThread(THREAD_ID); - yield* Ref.set( - currentShell, - shell({ - status: "completed", - title: "Final title", - latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }), - }), - ); - yield* secrets.set( - RELAY_ENVIRONMENT_CREDENTIAL_SECRET, - new TextEncoder().encode("credential-2"), - ); - yield* TestClock.adjust("1 second"); - yield* relay.drain; assert.equal(publications.length, 1); yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(publications.length, 2); - assert.equal(publications[1]?.authorization, "Bearer credential-2"); - assert.equal(publications[1]?.state?.phase, "completed"); - assert.equal(publications[1]?.state?.threadTitle, "Final title"); + assert.deepEqual( + publications.map((publication) => publication.state?.phase), + ["running", "completed"], + ); }), ); - it.effect("cancels a stale retry when a newer update publishes successfully", () => + it.effect("still publishes a completion when the thread settles during the hold", () => Effect.gen(function* () { - const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({ - respond: (attempt) => - attempt === 1 - ? new Response("relay unavailable", { status: 503 }) - : Response.json({ ok: true, deliveries: [] }), - }); + const { relay, currentShell, publications } = yield* makeTestRelay(); yield* relay.publishThread(THREAD_ID); - yield* Ref.set(currentShell, shell({ title: "New title" })); + const completed = shell({ status: "completed" }); + yield* Ref.set(currentShell, completed); yield* relay.publishThread(THREAD_ID); - assert.equal(publications.length, 2); - assert.equal(publications[1]?.state?.threadTitle, "New title"); - yield* TestClock.adjust("1 minute"); - yield* relay.drain; - assert.equal(shellReads.length, 2); - }), - ); - - it.effect.each(["disable", "unlink"] as const)( - "stops retries before shell reads after %s", - (change) => - Effect.gen(function* () { - const { relay, secrets, shellReads, publications } = yield* makeTestRelay({ - respond: () => new Response("relay unavailable", { status: 503 }), - }); - yield* relay.publishThread(THREAD_ID); - if (change === "disable") { - yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false")); - } else { - yield* secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET); - } - yield* TestClock.adjust("1 second"); - yield* relay.drain; - yield* TestClock.adjust("1 minute"); - yield* relay.drain; - assert.equal(publications.length, 1); - assert.equal(shellReads.length, 1); - }), - ); - - it.effect("recovers from a transient configuration read failure", () => - Effect.gen(function* () { - let failRead = false; - const { relay, shellReads, publications } = yield* makeTestRelay({ - failSecretRead: (name) => failRead && name === PUBLISH_AGENT_ACTIVITY_SECRET, + yield* Ref.set(currentShell, { + ...completed, + settledOverride: "settled", + settledAt: yield* DateTime.now, + lastVisitedAt: null, }); - failRead = true; yield* relay.publishThread(THREAD_ID); - assert.equal(shellReads.length, 0); - failRead = false; - yield* TestClock.adjust("1 second"); + yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(publications.length, 1); - assert.equal(publications[0]?.state?.phase, "running"); + assert.deepEqual( + publications.map((publication) => publication.state?.phase ?? null), + ["running", "completed"], + ); + + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; + assert.deepEqual( + publications.map((publication) => publication.state?.phase ?? null), + ["running", "completed", null], + ); }), ); - it.effect("bounds retry attempts and resets the budget for a newer update", () => + it.effect("drops a held completion when a queued continuation hides the thread", () => Effect.gen(function* () { - const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({ - respond: () => new Response("relay unavailable", { status: 503 }), - }); + const { relay, currentShell, publications } = yield* makeTestRelay(); yield* relay.publishThread(THREAD_ID); - let attempts = 1; - for (const delay of [1_000, 2_000, 4_000, 8_000, 16_000]) { - yield* TestClock.adjust(delay - 1); - yield* relay.drain; - assert.equal(publications.length, attempts); - yield* TestClock.adjust(1); - yield* relay.drain; - attempts += 1; - assert.equal(publications.length, attempts); - } - yield* TestClock.adjust("1 minute"); - yield* relay.drain; - assert.equal(publications.length, 6); - assert.equal(shellReads.length, 6); - yield* Ref.set(currentShell, shell({ title: "New update" })); + yield* Ref.set(currentShell, shell({ status: "completed" })); yield* relay.publishThread(THREAD_ID); - yield* TestClock.adjust("1 second"); + yield* Ref.set(currentShell, shell({ status: "queued" })); + yield* relay.publishThread(THREAD_ID); + yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(publications.length, 8); - assert.equal(publications[7]?.state?.threadTitle, "New update"); + assert.notInclude( + publications.map((publication) => publication.state?.phase ?? null), + "completed", + ); }), ); - it.effect("retries a confirmed completion without restarting its confirmation window", () => + it.effect("retries a failed completion even after the thread settles", () => Effect.gen(function* () { const { relay, currentShell, publications } = yield* makeTestRelay({ respond: (attempt) => - attempt <= 2 - ? new Response("relay unavailable", { status: 503 }) + attempt === 2 + ? new Response("unavailable", { status: 503 }) : Response.json({ ok: true, deliveries: [] }), }); - yield* Ref.set( - currentShell, - shell({ - status: "completed", - latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }), - }), - ); + yield* relay.publishThread(THREAD_ID); + const completed = shell({ status: "completed" }); + yield* Ref.set(currentShell, completed); yield* relay.publishThread(THREAD_ID); yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(publications.length, 1); + yield* Ref.set(currentShell, { + ...completed, + settledOverride: "settled", + settledAt: yield* DateTime.now, + lastVisitedAt: null, + }); yield* TestClock.adjust("1 second"); yield* relay.drain; - assert.equal(publications.length, 2); - yield* TestClock.adjust("2 seconds"); - yield* relay.drain; - assert.equal(publications.length, 3); - assert.isTrue(publications.every((publication) => publication.state?.phase === "completed")); - yield* TestClock.adjust("1 minute"); - yield* relay.drain; - assert.equal(publications.length, 3); - }), - ); + assert.deepEqual( + publications.map((publication) => publication.state?.phase ?? null), + ["running", "completed", "completed"], + ); - it.effect("does not reset an exhausted retry budget for old confirmation timers", () => - Effect.gen(function* () { - let unavailable = false; - const { relay, currentShell, shellReads, publications } = yield* makeTestRelay({ - respond: () => - unavailable - ? new Response("relay unavailable", { status: 503 }) - : Response.json({ ok: true, deliveries: [] }), - }); - yield* relay.publishThread(THREAD_ID); - for (let i = 0; i < 6; i++) { - yield* Ref.set(currentShell, null); - yield* relay.publishThread(THREAD_ID); - yield* Ref.set(currentShell, shell()); - yield* relay.publishThread(THREAD_ID); - yield* TestClock.adjust(1); - } - unavailable = true; - yield* Ref.set(currentShell, shell({ status: "failed" })); - yield* relay.publishThread(THREAD_ID); - yield* TestClock.adjust(1_000); - yield* relay.drain; - yield* TestClock.adjust(2_000); - yield* relay.drain; - yield* TestClock.adjust(1_994); - yield* relay.drain; - for (let i = 0; i < 5; i++) { - yield* TestClock.adjust(1); - yield* relay.drain; - } - const attempts = publications.length; - const reads = shellReads.length; - yield* TestClock.adjust("1 minute"); + yield* TestClock.adjust("5 seconds"); yield* relay.drain; - assert.equal(publications.length, attempts); - assert.equal(shellReads.length, reads); + assert.equal(publications.at(-1)?.state ?? null, null); }), ); - it.effect("confirms tombstones and cancels stale confirmations when activity recovers", () => + it.effect("keeps settled live work until its awaited monitor finishes", () => Effect.gen(function* () { const { relay, currentShell, publications } = yield* makeTestRelay(); yield* relay.publishThread(THREAD_ID); - yield* Ref.set(currentShell, null); - yield* relay.publishThread(THREAD_ID); - assert.equal(publications.length, 1); - yield* Ref.set(currentShell, shell()); + const held = shell({ + status: "completed", + settledOverride: "settled", + pendingBackgroundTasks: [{ taskId: "watch", kind: "monitor", awaited: true }], + }); + yield* Ref.set(currentShell, held); yield* relay.publishThread(THREAD_ID); yield* TestClock.adjust("5 seconds"); yield* relay.drain; assert.equal(publications.length, 1); - yield* Ref.set(currentShell, null); + assert.equal(publications[0]?.state?.phase, "running"); + + yield* Ref.set(currentShell, { ...held, pendingBackgroundTasks: [] }); yield* relay.publishThread(THREAD_ID); - assert.equal(publications.length, 1); yield* TestClock.adjust("5 seconds"); yield* relay.drain; assert.equal(publications.length, 2); assert.equal(publications[1]?.state, null); }), ); - - it.effect.each([ - { label: "live", archived: false }, - { label: "archived", archived: true }, - ])("never publishes tombstones for $label subagent threads", ({ archived }) => - Effect.gen(function* () { - const { relay, currentShell, publications } = yield* makeTestRelay(); - yield* Ref.set( - currentShell, - shell({ - lineage: { - rootThreadId: THREAD_ID, - parentThreadId: THREAD_ID, - relationshipToParent: "subagent", - }, - ...(archived ? { archivedAt: yield* DateTime.now } : {}), - }), - ); - yield* relay.publishThread(THREAD_ID); - yield* TestClock.adjust("5 seconds"); - yield* relay.drain; - assert.equal(publications.length, 0); - }), - ); - - it.effect("confirms a first completed state and respects disabling during confirmation", () => - Effect.gen(function* () { - const { relay, secrets, currentShell, publications } = yield* makeTestRelay(); - yield* Ref.set( - currentShell, - shell({ - status: "completed", - latestRunCompletedAt: DateTime.add(yield* DateTime.now, { seconds: 1 }), - }), - ); - yield* relay.publishThread(THREAD_ID); - assert.equal(publications.length, 0); - yield* TestClock.adjust("5 seconds"); - yield* relay.drain; - assert.equal(publications[0]?.state?.phase, "completed"); - yield* Ref.set(currentShell, null); - yield* relay.publishThread(THREAD_ID); - yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("false")); - yield* TestClock.adjust("5 seconds"); - yield* relay.drain; - assert.equal(publications.length, 1); - }), - ); it.effect("publishes a held completion when its background item ends, not on tool output", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; @@ -921,6 +704,8 @@ describe("AgentAwarenessRelay", () => { yield* deliver( itemEvent("event:held-item:end", item("item:tool", { ...background, status: "completed" })), ); + yield* TestClock.adjust("5 seconds"); + yield* relay.drain; assert.deepEqual( publications.map((publication) => publication.state?.phase), ["running", "completed"], @@ -928,69 +713,3 @@ describe("AgentAwarenessRelay", () => { }).pipe(Effect.scoped, Effect.provide(ProjectionStore.layerMemory)), ); }); - -describe("startup catch-up", { concurrent: false }, () => { - const link = (secrets: ServerSecretStore.ServerSecretStore["Service"]) => - Effect.all( - [ - secrets.set(RELAY_URL_SECRET, new TextEncoder().encode("https://relay.example.test")), - secrets.set(RELAY_ISSUER_SECRET, new TextEncoder().encode("https://relay.example.test")), - secrets.set(RELAY_ENVIRONMENT_CREDENTIAL_SECRET, new TextEncoder().encode("credential-1")), - ], - { discard: true }, - ); - const enablePublishing = (secrets: ServerSecretStore.ServerSecretStore["Service"]) => - secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, new TextEncoder().encode("true")); - const linkChecks = (secretReads: ReadonlyArray) => - secretReads.filter((name) => name === RELAY_URL_SECRET).length; - - it.effect("checks an unlinked environment once a minute and still catches up once linked", () => - Effect.gen(function* () { - const { relay, secrets, secretReads, catchUp } = yield* makeTestRelay({ linked: false }); - yield* enablePublishing(secrets); - yield* relay.start(); - - yield* TestClock.adjust("10 minutes"); - const checksBeforeWindow = linkChecks(secretReads); - yield* TestClock.adjust("10 minutes"); - assert.equal(linkChecks(secretReads) - checksBeforeWindow, 10); - assert.equal(catchUp.shellSnapshotReads, 0); - - yield* link(secrets); - yield* TestClock.adjust("1 minute"); - assert.equal(catchUp.shellSnapshotReads, 1); - }).pipe(Effect.scoped), - ); - - it.effect("publishes at once when this process links while the check is backed off", () => - Effect.gen(function* () { - const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false }); - yield* enablePublishing(secrets); - yield* relay.start(); - - yield* TestClock.adjust("10 minutes"); - yield* link(secrets); - yield* TestClock.adjust("1 second"); - assert.equal(catchUp.shellSnapshotReads, 0); - - yield* relay.requestCatchUp(); - yield* TestClock.adjust("1 second"); - assert.equal(catchUp.shellSnapshotReads, 1); - }).pipe(Effect.scoped), - ); - - it.effect("catches up within 5 s when another process enables publishing on a link", () => - Effect.gen(function* () { - const { relay, secrets, catchUp } = yield* makeTestRelay({ linked: false }); - yield* link(secrets); - yield* relay.start(); - - yield* TestClock.adjust("10 minutes"); - assert.equal(catchUp.shellSnapshotReads, 0); - - yield* enablePublishing(secrets); - yield* TestClock.adjust("5 seconds"); - assert.equal(catchUp.shellSnapshotReads, 1); - }).pipe(Effect.scoped), - ); -}); diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index fb21aa6e70dd4..e59065400b2d9 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -73,7 +73,7 @@ function isTurnItemPayload( ); } -export function shouldPublishAgentAwarenessEvent( +function shouldPublishAgentAwarenessEvent( event: Pick & { readonly payload?: unknown }, ): boolean { if ( @@ -93,6 +93,7 @@ export function shouldPublishAgentAwarenessEvent( case "thread.metadata-updated": case "thread.pull-request-link-updated": case "thread.pull-request-synced": + case "thread.settled": case "thread.model-selection-updated": case "thread.provider-switched": case "run.created": @@ -101,8 +102,9 @@ export function shouldPublishAgentAwarenessEvent( case "subagent.updated": case "provider-thread.updated": return true; - case "thread.settled": + // Unsettling must not re-alert a dismissed result. case "thread.unsettled": + case "thread.guest-share-updated": case "thread.snoozed": case "thread.unsnoozed": case "thread.auto-settle-set": @@ -146,8 +148,7 @@ export const makeAgentAwarenessPublishWorker = Effect.fnUntraced(function* ( const enqueue = (threadId: ThreadId) => Effect.suspend(() => { if (queued.has(threadId)) return Effect.void; - // Removing the ID when processing starts allows one new queue entry - // for updates received while the current snapshot is being published. + // Remove queued IDs when processing starts so publication can queue one later update. queued.add(threadId); return worker.enqueue(threadId); }).pipe(Effect.uninterruptible); @@ -358,7 +359,7 @@ export function resolveAgentAwarenessRelayActiveThreadIds(input: { .map((thread) => thread.id); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const secrets = yield* ServerSecretStore.ServerSecretStore; const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; @@ -408,10 +409,10 @@ export const make = Effect.gen(function* () { let cachedRelayClient: Effect.Success> | undefined; let publishedRelayConfig: NonNullable> | undefined; - // The confirming publish is re-enqueued through the same drainable worker as - // every other publish, so a confirmed tombstone can never race an in-flight - // live update; a recovered state clears the deadline. + // Confirm through the same worker so tombstones cannot race live updates; recovery clears the deadline. const publishConfirmDeadlines = new Map(); + // Threads whose confirmation holds a completion, so a thread that settles during the hold still alerts. + const heldCompletions = new Set(); let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect = () => Effect.void; const publishRetries = new Map< ThreadId, @@ -430,6 +431,7 @@ export const make = Effect.gen(function* () { publishedRelayConfig = undefined; cachedRelayClient = undefined; publishConfirmDeadlines.clear(); + heldCompletions.clear(); yield* Ref.set(publishedStateByThreadRef, new Map()); }); @@ -462,66 +464,61 @@ export const make = Effect.gen(function* () { } const environmentId = yield* serverEnvironment.getEnvironmentId; - const publishState = (input: { + const publishState = Effect.fn("relay.agent_activity.publish")(function* (input: { readonly projectId: string | null; readonly state: RelayAgentActivityState | null; readonly reason: string; - }) => - Effect.gen(function* () { - if (cachedRelayClient === undefined) { - cachedRelayClient = yield* makeRelayClient(relayConfig); - } - const relayClient = cachedRelayClient; - const proof = yield* makePublishProof({ - privateKey: cloudLinkKeyPair.privateKey, - relayIssuer: relayConfig.issuer, - environmentId, - threadId, - state: input.state, - jti: yield* crypto.randomUUIDv4(), - }); + }) { + if (cachedRelayClient === undefined) { + cachedRelayClient = yield* makeRelayClient(relayConfig); + } + const relayClient = cachedRelayClient; + const proof = yield* makePublishProof({ + privateKey: cloudLinkKeyPair.privateKey, + relayIssuer: relayConfig.issuer, + environmentId, + threadId, + state: input.state, + jti: yield* crypto.randomUUIDv4(), + }); - yield* Effect.logInfo("publishing agent activity for thread", { - environmentId, - threadId, - projectId: input.projectId, - statePhase: input.state?.phase ?? null, - hasState: input.state !== null, - reason: input.reason, - }); + yield* Effect.logInfo("publishing agent activity for thread", { + environmentId, + threadId, + projectId: input.projectId, + statePhase: input.state?.phase ?? null, + hasState: input.state !== null, + reason: input.reason, + }); - const response = yield* relayClient.server - .publishAgentActivity({ - params: { - environmentId, - threadId, - }, - payload: { - state: input.state, - proof, - }, - }) - .pipe(Effect.timeout("10 seconds")); - - yield* Effect.logInfo("agent activity publish completed", { - environmentId, - threadId, - ok: response.ok, - deliveries: deliveryStats(response.deliveries), - }); - }).pipe(Effect.withSpan("relay.agent_activity.publish"), withRelayClientTracing); + const response = yield* relayClient.server + .publishAgentActivity({ + params: { + environmentId, + threadId, + }, + payload: { + state: input.state, + proof, + }, + }) + .pipe(Effect.timeout("10 seconds")); + + yield* Effect.logInfo("agent activity publish completed", { + environmentId, + threadId, + ok: response.ok, + deliveries: deliveryStats(response.deliveries), + }); + }); - // Per-thread shell read: this publish runs for every activity-relevant - // domain event, so materializing the full shell here would make the cost - // of one thread's activity proportional to how many threads exist. + // Read only this thread; full shell reads would make each activity event scale with all threads. const threadShell = yield* threads.getThreadShell(threadId); if ( threadShell?.lineage.relationshipToParent === "subagent" && !(yield* Ref.get(publishedStateByThreadRef)).has(threadId) ) { - // Subagents never project activity, so the relay holds no row to clear. - // Their events would otherwise publish a tombstone each, and every - // publish re-delivers the user's aggregate. + // Subagents have no relay rows to clear; per-event tombstones would needlessly redeliver user aggregates. return; } const thread = @@ -546,11 +543,9 @@ export const make = Effect.gen(function* () { if (Option.isNone(thread) || !terminalWorkSinceStart(thread.value, startedAt)) return; } if (publishedStateByThread.get(threadId) === publishIdentity) { - // The projection is back at (or never left) the last published state, so - // any pending deferred confirmation is moot. Leaving the deadline in - // place would let a much later transient null find it already expired - // and publish a tombstone immediately, skipping the deferral window. + // Clear moot deadlines so later transient nulls cannot skip their deferral window. publishConfirmDeadlines.delete(threadId); + heldCompletions.delete(threadId); yield* Effect.logDebug("agent activity publish skipped; projected state unchanged", { environmentId, threadId, @@ -559,16 +554,15 @@ export const make = Effect.gen(function* () { return; } - // - null (tombstone) while the previous published state was live: deletes - // the thread from every armed card mid-conversation. - // - completed as the thread's FIRST published state: sessions boot at - // "ready" before their first turn, which projects as completed for an - // instant and sends a spurious Done notification at thread birth. + // Confirm tombstones over live state to avoid removing active cards. + // Confirm completion: a run can end moments before its continuation starts, and the relay + // alerts on every move into completed. const requiresConfirmation = (snapshot.state === null && publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) || - (snapshot.state?.phase === "completed" && !publishedStateByThread.has(threadId)); + snapshot.state?.phase === "completed"; if (requiresConfirmation) { + if (snapshot.state?.phase === "completed") heldCompletions.add(threadId); const nowMs = (yield* DateTime.now).epochMilliseconds; const deadline = publishConfirmDeadlines.get(threadId); if (deadline === undefined) { @@ -593,8 +587,38 @@ export const make = Effect.gen(function* () { statePhase: snapshot.state?.phase ?? null, shell: describeThreadShellForAwareness(thread), }); + // Settled during the hold, not resumed: alert the current completion, then clear the card + // on a new window. Only settlement may hide it; queued or silent runs also project to null. + const unsettled = + snapshot.state === null && + heldCompletions.has(threadId) && + Option.isSome(thread) && + thread.value.settledOverride === "settled" + ? resolveAgentAwarenessRelayPublishSnapshot({ + environmentId, + threadId, + thread: Option.some({ ...thread.value, settledOverride: null }), + project, + }) + : null; + if (unsettled?.state?.phase === "completed") { + const completion = unsettled.state; + yield* publishState({ + projectId: unsettled.projectId, + state: completion, + reason: unsettled.reason, + }).pipe(withRelayClientTracing); + heldCompletions.delete(threadId); + publishConfirmDeadlines.set(threadId, nowMs + 5_000); + yield* Ref.update(publishedStateByThreadRef, (publishedStates) => + new Map(publishedStates).set(threadId, agentAwarenessPublishIdentity(completion)), + ); + yield* schedulePublishConfirm(threadId); + return; + } } else { publishConfirmDeadlines.delete(threadId); + heldCompletions.delete(threadId); } if (snapshot.reason === "thread-not-found") { @@ -614,8 +638,9 @@ export const make = Effect.gen(function* () { projectId: snapshot.projectId, state: snapshot.state, reason: snapshot.reason, - }); + }).pipe(withRelayClientTracing); publishConfirmDeadlines.delete(threadId); + heldCompletions.delete(threadId); yield* Ref.update(publishedStateByThreadRef, (publishedStates) => { const nextPublishedStates = new Map(publishedStates); if (snapshot.state === null) { @@ -657,8 +682,7 @@ export const make = Effect.gen(function* () { const attempts = publishRetries.get(threadId)?.attempts ?? 0; const delayMs = RELAY_AGENT_ACTIVITY_RETRY_DELAYS_MS[attempts]; if (delayMs === undefined) { - // Keep the exhausted budget until fresh activity or a successful publish - // clears it; an old confirmation timer must not start another retry series. + // Retain exhausted budgets until activity or success resets them; old timers must not restart retries. yield* Effect.logWarning("agent activity publish retry budget exhausted", { threadId }); return; } @@ -729,31 +753,33 @@ export const make = Effect.gen(function* () { // Many environments never link, so while unlinked the retry backs off from 5 // s to 60 s. A linked environment keeps the 5 s retry, because `t3 connect - // publish` can turn publishing on from another process. - const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) => - Effect.gen(function* () { - let unlinkedRetryDelayMs = 5_000; - while (!(yield* Ref.get(activeSnapshotPublishedRef))) { - const result = yield* publishActiveThreadsUnsafe.pipe( - Effect.orElseSucceed(() => "failed" as const), - ); - if (result === "published") { - yield* Ref.set(activeSnapshotPublishedRef, true); - if (logEnabledWhenReady) { - const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); - yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", { - relayUrl: relayConfig?.url, - }); - } - return; - } - const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000; - yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests)); - if (result === "unlinked") { - unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000); + // publish` can turn publishing on from another process. Keep this untraced: + // an unlinked environment can retry for the lifetime of the process. + const publishActiveThreadsOnceWhenConfigured = Effect.fnUntraced(function* ( + logEnabledWhenReady: boolean, + ) { + let unlinkedRetryDelayMs = 5_000; + while (!(yield* Ref.get(activeSnapshotPublishedRef))) { + const result = yield* publishActiveThreadsUnsafe.pipe( + Effect.orElseSucceed(() => "failed" as const), + ); + if (result === "published") { + yield* Ref.set(activeSnapshotPublishedRef, true); + if (logEnabledWhenReady) { + const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null)); + yield* Effect.logInfo("agent activity publishing enabled after link reconciliation", { + relayUrl: relayConfig?.url, + }); } + return; } - }); + const retryDelayMs = result === "unlinked" ? unlinkedRetryDelayMs : 5_000; + yield* Effect.race(Effect.sleep(retryDelayMs), Queue.take(catchUpRequests)); + if (result === "unlinked") { + unlinkedRetryDelayMs = Math.min(unlinkedRetryDelayMs * 2, 60_000); + } + } + }); schedulePublishConfirm = (threadId) => Effect.forkIn( diff --git a/apps/server/src/relay/HeldHooksWaker.ts b/apps/server/src/relay/HeldHooksWaker.ts index 5046d62dccfdd..9fee885aa8199 100644 --- a/apps/server/src/relay/HeldHooksWaker.ts +++ b/apps/server/src/relay/HeldHooksWaker.ts @@ -33,8 +33,7 @@ export const layer = Layer.effectDiscard( ), ); yield* runtime.tunnelConnected.pipe( - // cloudflared registers several connections per (re)connect within a - // few seconds; they are one wake. + // Coalesce cloudflared's several connections per reconnect into one wake. Stream.debounce("3 seconds"), Stream.runForEach(() => wake), Effect.forkScoped, diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts index 50c8ea2b76324..616643c6e1e9e 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts @@ -1,94 +1,12 @@ // @effect-diagnostics nodeBuiltinImport:off -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; import { it } from "@effect/vitest"; -import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; -import * as PubSub from "effect/PubSub"; -import * as Ref from "effect/Ref"; -import { assert, describe, expect } from "vite-plus/test"; +import { describe, expect } from "vite-plus/test"; -import { - type DesktopTelemetryReceiverHealth, - initialDesktopTelemetryContactAt, - isDesktopTelemetryContactStale, - recordDesktopTelemetrySampleHealth, - requireDesktopTelemetryWriteProgress, - resolveDesktopTelemetrySnapshotStaleAfterMs, - writeAllToFileDescriptor, -} from "./DesktopTelemetryReceiver.ts"; +import { requireDesktopTelemetryWriteProgress } from "./DesktopTelemetryReceiver.ts"; describe("DesktopTelemetryReceiver", () => { - it("degrades a hello-only stream after the first-sample deadline", () => { - expect(isDesktopTelemetryContactStale(Option.some(1_000), 90_999)).toBe(false); - expect(isDesktopTelemetryContactStale(Option.some(1_000), 91_000)).toBe(true); - expect(isDesktopTelemetryContactStale(Option.none(), 1_000_000)).toBe(false); - }); - - it("starts the stale deadline as soon as a telemetry descriptor is opened", () => { - expect(initialDesktopTelemetryContactAt(7, 1_000)).toEqual(Option.some(1_000)); - expect(initialDesktopTelemetryContactAt(undefined, 1_000)).toEqual(Option.none()); - }); - - it("keeps the snapshot deadline beyond the configured idle polling interval", () => { - expect(resolveDesktopTelemetrySnapshotStaleAfterMs(30_000, 120_000)).toBe(150_000); - expect(resolveDesktopTelemetrySnapshotStaleAfterMs(60_000, 600_000)).toBe(630_000); - expect(resolveDesktopTelemetrySnapshotStaleAfterMs(1_000, 1_000)).toBe(90_000); - }); - - it.effect("publishes the latest sample timestamp while health remains healthy", () => - Effect.scoped( - Effect.gen(function* () { - const initialSample = DateTime.makeUnsafe(1_000); - const nextSample = DateTime.makeUnsafe(2_000); - const health = yield* Ref.make({ - status: "healthy", - lastSampleAt: Option.some(initialSample), - lastError: Option.none(), - }); - const healthChanges = yield* PubSub.sliding(4); - const subscription = yield* PubSub.subscribe(healthChanges); - - yield* recordDesktopTelemetrySampleHealth(health, healthChanges, nextSample); - const published = yield* PubSub.take(subscription).pipe(Effect.timeout("1 second")); - - expect(DateTime.toEpochMillis(Option.getOrThrow(published.lastSampleAt))).toBe(2_000); - }), - ), - ); - - it.effect("writes control messages through the asynchronous descriptor path", () => - Effect.acquireUseRelease( - Effect.sync(() => { - const directory = NodeFS.mkdtempSync( - NodePath.join(NodeOS.tmpdir(), "t3-desktop-telemetry-control-test-"), - ); - const path = NodePath.join(directory, "control.ndjson"); - return { - directory, - path, - fd: NodeFS.openSync(path, "w"), - }; - }), - ({ fd, path }) => - Effect.gen(function* () { - const payload = Buffer.from('{"type":"setDiagnosticsDemand","enabled":true}\n'); - yield* writeAllToFileDescriptor(fd, payload); - NodeFS.fsyncSync(fd); - - assert.equal(NodeFS.readFileSync(path, "utf8"), payload.toString("utf8")); - }), - ({ directory, fd }) => - Effect.sync(() => { - NodeFS.closeSync(fd); - NodeFS.rmSync(directory, { recursive: true, force: true }); - }), - ), - ); - it.effect("models a zero-byte control write as a stalled descriptor", () => Effect.gen(function* () { const error = yield* requireDesktopTelemetryWriteProgress(7, 42, 0).pipe(Effect.flip); diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts index a911c2b05d3d6..4fec32dd76c10 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts @@ -202,7 +202,7 @@ const isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch); const isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed); const isStreamFailed = Schema.is(DesktopTelemetryStreamFailed); -export function isDesktopTelemetryContactStale( +function isDesktopTelemetryContactStale( lastContactAtMs: Option.Option, nowMs: number, ): boolean { @@ -212,7 +212,7 @@ export function isDesktopTelemetryContactStale( ); } -export function resolveDesktopTelemetrySnapshotStaleAfterMs( +function resolveDesktopTelemetrySnapshotStaleAfterMs( activeIntervalMs: number, idleIntervalMs: number, ): number { @@ -222,14 +222,14 @@ export function resolveDesktopTelemetrySnapshotStaleAfterMs( ); } -export function initialDesktopTelemetryContactAt( +function initialDesktopTelemetryContactAt( desktopTelemetryFd: number | undefined, nowMs: number, ): Option.Option { return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs); } -export const recordDesktopTelemetrySampleHealth = Effect.fn( +const recordDesktopTelemetrySampleHealth = Effect.fn( "resourceTelemetry.desktopTelemetryReceiver.recordSampleHealth", )(function* ( health: Ref.Ref, @@ -322,7 +322,7 @@ export function requireDesktopTelemetryWriteProgress( : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes })); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () { const config = yield* ServerConfig.ServerConfig; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -458,8 +458,7 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make") if (config.desktopTelemetryFd !== undefined) { const fd = config.desktopTelemetryFd; - // The parent waits for this server before closing its pipe. Socket reads - // can be cancelled; filesystem reads would keep process.exit waiting. + // The parent waits before closing; use cancellable socket reads so filesystem reads cannot block exit. const readable = yield* Effect.acquireRelease( Effect.try({ try: () => new NodeNet.Socket({ fd, readable: true, writable: false }), diff --git a/apps/server/src/resourceTelemetry/HostResources.ts b/apps/server/src/resourceTelemetry/HostResources.ts index 1cc53e1de2f13..4788689046af3 100644 --- a/apps/server/src/resourceTelemetry/HostResources.ts +++ b/apps/server/src/resourceTelemetry/HostResources.ts @@ -32,8 +32,7 @@ function darwinAvailableMemory(output: string): number | null { const inactive = /^Pages inactive:\s+(\d+)\./m.exec(output)?.[1]; const speculative = /^Pages speculative:\s+(\d+)\./m.exec(output)?.[1]; if (!pageSize || !free || !inactive || !speculative) return null; - // vm_stat subtracts speculative pages from its printed "Pages free" count. - // Adding them here counts each reclaimable page once; purgeable pages overlap. + // vm_stat excludes speculative from free; add it once, without overlapping purgeable pages. const available = (Number(free) + Number(inactive) + Number(speculative)) * Number(pageSize); return Number.isSafeInteger(available) && Number(pageSize) > 0 ? available : null; } diff --git a/apps/server/src/resourceTelemetry/Model.test.ts b/apps/server/src/resourceTelemetry/Model.test.ts index 0b855eaef5ffd..25c119ed47f9c 100644 --- a/apps/server/src/resourceTelemetry/Model.test.ts +++ b/apps/server/src/resourceTelemetry/Model.test.ts @@ -447,45 +447,6 @@ describe("resource telemetry process model", () => { expect(second.groups.backend.ioWriteBytes).toBe(3_000); }); - it("derives deltas at the constrained 15-second sampling cadence", () => { - const first = merge({ - native: nativeSnapshot(BASE_TIME_MS, [ - processSample({ - pid: SERVER_PID, - ppid: 1, - startTimeMs: 1_000, - cpuTimeMs: 1_000, - ioReadBytes: 10_000, - ioWriteBytes: 20_000, - }), - ]), - }); - const second = merge({ - previous: first, - native: nativeSnapshot( - BASE_TIME_MS + 15_000, - [ - processSample({ - pid: SERVER_PID, - ppid: 1, - startTimeMs: 1_000, - cpuTimeMs: 2_500, - ioReadBytes: 25_000, - ioWriteBytes: 50_000, - }), - ], - 2, - ), - }); - - expect(second.processes[0]?.cpuPercent).toBe(10); - expect(second.processes[0]?.ioReadBytesPerSecond).toBe(1_000); - expect(second.processes[0]?.ioWriteBytesPerSecond).toBe(2_000); - expect(second.groups.backend.cpuTimeMs).toBe(1_500); - expect(second.groups.backend.ioReadBytes).toBe(15_000); - expect(second.groups.backend.ioWriteBytes).toBe(30_000); - }); - it("preserves native rates while applying a desktop-only update", () => { const first = merge({ native: nativeSnapshot(BASE_TIME_MS, [ diff --git a/apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts b/apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts index 44bb9c7c20029..46af99cb9dfd6 100644 --- a/apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts +++ b/apps/server/src/resourceTelemetry/NativeTelemetryClient.test.ts @@ -1,36 +1,14 @@ -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import * as NodeServices from "@effect/platform-node/NodeServices"; import type { HostPowerSnapshot } from "@t3tools/contracts"; -import { - RESOURCE_MONITOR_PROTOCOL_VERSION, - ResourceMonitorCommand, - type ResourceMonitorHelloEvent, -} from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; -import * as Layer from "effect/Layer"; -import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as Schema from "effect/Schema"; -import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; -import * as Sink from "effect/Sink"; -import * as Stream from "effect/Stream"; -import { ChildProcessSpawner } from "effect/process"; -import * as ServerConfig from "../config.ts"; -import * as NativeTelemetryClient from "./NativeTelemetryClient.ts"; -import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts"; import { - canCommandNativeTelemetrySidecar, - canRequestNativeTelemetryRetry, commitCollectionControlUpdate, - retainRecentNativeTelemetryFailures, - resolveNativeSampleIntervalMs, synchronizeCollectionControlOnStart, } from "./NativeTelemetryClient.ts"; @@ -47,142 +25,6 @@ const basePower: HostPowerSnapshot = { updatedAt: DateTime.makeUnsafe("2026-06-17T12:00:00.000Z"), }; -describe("resolveNativeSampleIntervalMs", () => { - it("keeps a recovery cadence while suspended and backs off under host constraints", () => { - expect(resolveNativeSampleIntervalMs({ ...basePower, suspended: true }, 1)).toBe(15_000); - expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 1)).toBe(15_000); - expect(resolveNativeSampleIntervalMs({ ...basePower, lowPowerMode: "true" }, 1)).toBe(15_000); - expect(resolveNativeSampleIntervalMs({ ...basePower, thermalState: "critical" }, 1)).toBe( - 15_000, - ); - expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 1)).toBe(5_000); - }); - - it("stops timed sampling without a live subscriber and serves live diagnostics at 1Hz", () => { - const unknown: HostPowerSnapshot = { - ...basePower, - source: "unknown", - stale: true, - }; - expect(resolveNativeSampleIntervalMs(unknown, 0)).toBe(0); - expect(resolveNativeSampleIntervalMs(unknown, 1)).toBe(1_000); - expect(resolveNativeSampleIntervalMs({ ...basePower, locked: "true" }, 0)).toBe(0); - expect(resolveNativeSampleIntervalMs({ ...basePower, onBattery: "true" }, 0)).toBe(0); - expect(resolveNativeSampleIntervalMs(basePower, 0)).toBe(0); - expect(resolveNativeSampleIntervalMs(basePower, 1)).toBe(1_000); - }); -}); - -const decodeCommandLine = Schema.decodeUnknownSync(Schema.fromJsonString(ResourceMonitorCommand)); - -const hello: ResourceMonitorHelloEvent = { - version: RESOURCE_MONITOR_PROTOCOL_VERSION, - type: "hello", - sidecarVersion: "test", - sidecarPid: 4242, - platform: "linux", - arch: "x64", - capabilities: { - cumulativeCpuTime: true, - currentCpuPercent: true, - residentMemory: true, - virtualMemory: true, - ioBytes: true, - processStartTime: true, - processTree: true, - }, -}; - -describe("NativeTelemetryClient", () => { - it.effect("asks the sidecar for timed samples only while a live subscriber exists", () => - Effect.gen(function* () { - const commands = yield* Queue.unbounded(); - const spawner = ChildProcessSpawner.make(() => - Effect.succeed( - ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(hello.sidecarPid), - exitCode: Effect.never, - isRunning: Effect.succeed(true), - kill: () => Effect.void, - unref: Effect.succeed(Effect.void), - stdin: Sink.forEach((chunk: Uint8Array) => - Effect.forEach(new TextDecoder().decode(chunk).split("\n").filter(Boolean), (line) => - Queue.offer(commands, decodeCommandLine(line)), - ), - ), - stdout: Stream.encodeText(Stream.make(`${JSON.stringify(hello)}\n`)).pipe( - Stream.concat(Stream.never), - ), - stderr: Stream.empty, - all: Stream.empty, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - }), - ), - ); - const client = yield* NativeTelemetryClient.make().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(ResourceMonitorBinary.ResourceMonitorBinary, { - resolve: Effect.succeed("/test/t3-resource-monitor"), - }), - ); - - const configure = yield* Queue.take(commands); - expect(configure).toMatchObject({ type: "configure", sampleIntervalMs: 0 }); - expect(yield* Queue.take(commands)).toMatchObject({ type: "setExternalProcesses" }); - - const live = yield* Scope.make(); - yield* client.snapshots.pipe(Stream.runDrain, Effect.forkIn(live)); - expect(yield* Queue.take(commands)).toMatchObject({ - type: "setSampleInterval", - sampleIntervalMs: 1_000, - }); - expect(yield* Queue.take(commands)).toMatchObject({ type: "setStreaming", enabled: true }); - - yield* Scope.close(live, Exit.void); - expect(yield* Queue.take(commands)).toMatchObject({ - type: "setSampleInterval", - sampleIntervalMs: 0, - }); - expect(yield* Queue.take(commands)).toMatchObject({ type: "setStreaming", enabled: false }); - expect((yield* client.health).sampleIntervalMs).toBe(0); - }).pipe( - Effect.provide( - Layer.mergeAll( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-native-telemetry-test-" }), - NodeCrypto.layer, - ).pipe(Layer.provideMerge(NodeServices.layer)), - ), - ), - ); -}); - -describe("canRequestNativeTelemetryRetry", () => { - it("only accepts retry while the supervisor is waiting without a live sidecar", () => { - expect(canRequestNativeTelemetryRetry("degraded", false)).toBe(true); - expect(canRequestNativeTelemetryRetry("unavailable", false)).toBe(true); - expect(canRequestNativeTelemetryRetry("degraded", true)).toBe(false); - expect(canRequestNativeTelemetryRetry("healthy", false)).toBe(false); - expect(canRequestNativeTelemetryRetry("starting", false)).toBe(false); - }); -}); - -describe("canCommandNativeTelemetrySidecar", () => { - it("keeps on-demand recovery commands available while a live sidecar is degraded", () => { - expect(canCommandNativeTelemetrySidecar("healthy", true)).toBe(true); - expect(canCommandNativeTelemetrySidecar("degraded", true)).toBe(true); - expect(canCommandNativeTelemetrySidecar("unavailable", true)).toBe(false); - expect(canCommandNativeTelemetrySidecar("degraded", false)).toBe(false); - }); -}); - -describe("retainRecentNativeTelemetryFailures", () => { - it("expires old failures so an isolated crash restarts from the initial backoff", () => { - expect(retainRecentNativeTelemetryFailures([0, 30_000], 90_001)).toEqual([]); - expect(retainRecentNativeTelemetryFailures([30_000, 60_000], 90_000)).toEqual([30_000, 60_000]); - }); -}); - describe("commitCollectionControlUpdate", () => { it.effect("retains desired demand and retries unapplied sidecar state", () => Effect.gen(function* () { diff --git a/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts b/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts index 9d252fadb4f7a..55eeb2f855195 100644 --- a/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts +++ b/apps/server/src/resourceTelemetry/NativeTelemetryClient.ts @@ -261,7 +261,7 @@ function isThermallyConstrained(snapshot: HostPowerSnapshot): boolean { // Without a live subscriber the sidecar does not sample on a timer, so an idle server // never walks the process table. History then covers only time with a subscriber. -export function resolveNativeSampleIntervalMs( +function resolveNativeSampleIntervalMs( snapshot: HostPowerSnapshot, liveSubscriberCount: number, ): number { @@ -279,23 +279,22 @@ export function resolveNativeSampleIntervalMs( return SAMPLE_INTERVAL_MS; } -export function commitCollectionControlUpdate( +// Desktop power samples also commit control state; avoid a span for each sample. +export const commitCollectionControlUpdate = Effect.fnUntraced(function* ( desiredState: Ref.Ref, appliedState: Ref.Ref, update: (current: CollectionControl) => CollectionControl, apply: (previous: CollectionControl, next: CollectionControl) => Effect.Effect, -): Effect.Effect { - return Effect.gen(function* () { - const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => { - const next = update(previous); - return [[previous, next] as const, next]; - }); - const previousApplied = yield* Ref.get(appliedState); - yield* apply(previousApplied, next); - yield* Ref.set(appliedState, next); - return [previousDesired, next] as const; +): Effect.fn.Return { + const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => { + const next = update(previous); + return [[previous, next] as const, next]; }); -} + const previousApplied = yield* Ref.get(appliedState); + yield* apply(previousApplied, next); + yield* Ref.set(appliedState, next); + return [previousDesired, next] as const; +}); export function synchronizeCollectionControlOnStart( mutex: Semaphore.Semaphore, @@ -337,7 +336,7 @@ function restartDelay(attempt: number): Duration.Duration { return Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY); } -export function retainRecentNativeTelemetryFailures( +function retainRecentNativeTelemetryFailures( failures: ReadonlyArray, now: number, ): ReadonlyArray { @@ -348,21 +347,21 @@ function errorMessage(error: NativeTelemetryClientError): string { return error.message; } -export function canRequestNativeTelemetryRetry( +function canRequestNativeTelemetryRetry( status: ResourceTelemetrySourceStatus, hasHandle: boolean, ): boolean { return status !== "healthy" && status !== "starting" && !hasHandle; } -export function canCommandNativeTelemetrySidecar( +function canCommandNativeTelemetrySidecar( status: ResourceTelemetrySourceStatus, hasHandle: boolean, ): boolean { return hasHandle && (status === "healthy" || status === "degraded"); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(function* () { const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -411,23 +410,22 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu Effect.asVoid, ); - const failPending = (error: NativeTelemetryClientError) => - Effect.gen(function* () { - const samples = yield* Ref.getAndSet(pendingSamples, new Map()); - const processTables = yield* Ref.getAndSet(pendingProcessTables, new Map()); - const histories = yield* Ref.getAndSet(pendingHistories, new Map()); - yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), { - discard: true, - }); - yield* Effect.forEach(processTables.values(), (deferred) => Deferred.fail(deferred, error), { - discard: true, - }); - yield* Effect.forEach( - histories.values(), - (request) => Deferred.fail(request.deferred, error), - { discard: true }, - ); + const failPending = Effect.fn("NativeTelemetryClient.failPending")(function* ( + error: NativeTelemetryClientError, + ) { + const samples = yield* Ref.getAndSet(pendingSamples, new Map()); + const processTables = yield* Ref.getAndSet(pendingProcessTables, new Map()); + const histories = yield* Ref.getAndSet(pendingHistories, new Map()); + yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), { + discard: true, + }); + yield* Effect.forEach(processTables.values(), (deferred) => Deferred.fail(deferred, error), { + discard: true, + }); + yield* Effect.forEach(histories.values(), (request) => Deferred.fail(request.deferred, error), { + discard: true, }); + }); const writeCommand = ( handle: ChildProcessSpawner.ChildProcessHandle, @@ -777,9 +775,11 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu Effect.forkScoped, ); - const applyCollectionControl = Effect.fn( - "resourceTelemetry.nativeTelemetryClient.applyCollectionControl", - )(function* (previous: CollectionControl, next: CollectionControl) { + // Desktop power samples reach this even when the control state has not changed. + const applyCollectionControl = Effect.fnUntraced(function* ( + previous: CollectionControl, + next: CollectionControl, + ) { const current = yield* Ref.get(state); if (canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) { const handle = Option.getOrThrow(current.handle); @@ -842,10 +842,9 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu }), ); - const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] = ( - processes, - ) => - Effect.gen(function* () { + // Desktop telemetry refreshes this process set on every sample. + const setExternalProcesses: NativeTelemetryClient["Service"]["setExternalProcesses"] = + Effect.fnUntraced(function* (processes) { yield* Ref.set(externalProcesses, [...processes]); const current = yield* Ref.get(state); if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) return; @@ -856,64 +855,65 @@ export const make = Effect.fn("resourceTelemetry.nativeTelemetryClient.make")(fu }); }); - const readHistory: NativeTelemetryClient["Service"]["readHistory"] = (windowMs) => - Effect.gen(function* () { - const current = yield* Ref.get(state); - if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) { - return yield* new NativeTelemetryUnavailable({ - reason: Option.getOrElse(current.lastError, () => "sidecar is not running"), - }); - } - const requestId = yield* crypto.randomUUIDv4().pipe( - Effect.mapError( - (cause) => - new NativeTelemetryCommandFailed({ - operation: "createHistoryRequestId", - cause, - }), - ), - ); - const deferred = yield* Deferred.make< - ReadonlyArray, - NativeTelemetryClientError - >(); - yield* Ref.update(pendingHistories, (pending) => { - const next = new Map(pending); - next.set(requestId, { deferred, snapshots: [] }); - return next; + const readHistory: NativeTelemetryClient["Service"]["readHistory"] = Effect.fn( + "NativeTelemetryClient.readHistory", + )(function* (windowMs) { + const current = yield* Ref.get(state); + if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) { + return yield* new NativeTelemetryUnavailable({ + reason: Option.getOrElse(current.lastError, () => "sidecar is not running"), }); - return yield* writeCommand(Option.getOrThrow(current.handle), { - version: RESOURCE_MONITOR_PROTOCOL_VERSION, - type: "readHistory", - requestId, - windowMs: Math.max(0, Math.round(windowMs)), - }).pipe( - Effect.andThen( - Deferred.await(deferred).pipe( - Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT), - Effect.flatMap( - Option.match({ - onNone: () => - Effect.fail( - new NativeTelemetryRequestTimedOut({ - operation: "readHistory", - timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT), - }), - ), - onSome: Effect.succeed, - }), - ), - ), - ), - Effect.ensuring( - Ref.update(pendingHistories, (pending) => { - const next = new Map(pending); - next.delete(requestId); - return next; + } + const requestId = yield* crypto.randomUUIDv4().pipe( + Effect.mapError( + (cause) => + new NativeTelemetryCommandFailed({ + operation: "createHistoryRequestId", + cause, }), - ), - ); + ), + ); + const deferred = yield* Deferred.make< + ReadonlyArray, + NativeTelemetryClientError + >(); + yield* Ref.update(pendingHistories, (pending) => { + const next = new Map(pending); + next.set(requestId, { deferred, snapshots: [] }); + return next; }); + return yield* writeCommand(Option.getOrThrow(current.handle), { + version: RESOURCE_MONITOR_PROTOCOL_VERSION, + type: "readHistory", + requestId, + windowMs: Math.max(0, Math.round(windowMs)), + }).pipe( + Effect.andThen( + Deferred.await(deferred).pipe( + Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new NativeTelemetryRequestTimedOut({ + operation: "readHistory", + timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT), + }), + ), + onSome: Effect.succeed, + }), + ), + ), + ), + Effect.ensuring( + Ref.update(pendingHistories, (pending) => { + const next = new Map(pending); + next.delete(requestId); + return next; + }), + ), + ); + }); const sampleNow: NativeTelemetryClient["Service"]["sampleNow"] = Effect.gen(function* () { const current = yield* Ref.get(state); diff --git a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts new file mode 100644 index 0000000000000..694803b648420 --- /dev/null +++ b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.test.ts @@ -0,0 +1,59 @@ +import { assert, describe, it } from "@effect/vitest"; +import type { ResourceTelemetryProcess } from "@t3tools/contracts"; + +import { groupProcesses } from "./ProcessGroupMetrics.ts"; + +const process = ( + pid: number, + ppid: number, + name: string, + category: ResourceTelemetryProcess["category"] = "server-child", + command = name, +) => + ({ + identity: { pid, startTimeMs: 1 }, + ppid, + name, + command, + category, + residentBytes: pid * 1_000, + cpuPercent: pid, + }) as ResourceTelemetryProcess; + +describe("groupProcesses", () => { + it("sums each direct child of the server with its whole subtree", () => { + const totals = groupProcesses([ + process(10, 1, "node", "server"), + process(11, 10, "t3-resource-mon", "resource-monitor"), + process(20, 10, "claude"), + process(21, 20, "bash"), + process(22, 21, "cargo"), + process(30, 10, "codex"), + process(40, 10, "zsh"), + process(50, 10, "chrome-headless"), + process(60, 10, "git", "server-child", "git checkout claude/fix"), + process(70, 99, "orphan"), + // An older Claude package runs as a script under node. + process( + 80, + 10, + "node", + "server-child", + "node /opt/node_modules/@anthropic-ai/claude-code/cli.js", + ), + process(90, 10, "node", "server-child", "node /srv/tools/report.js"), + ]); + + assert.deepStrictEqual(Object.fromEntries(totals), { + server: { residentBytes: 10_000, cpuPercent: 10, count: 1 }, + "resource-monitor": { residentBytes: 11_000, cpuPercent: 11, count: 1 }, + // The agent's shell and the build it ran belong to the agent, not the terminal group. + claude: { residentBytes: 143_000, cpuPercent: 143, count: 4 }, + codex: { residentBytes: 30_000, cpuPercent: 30, count: 1 }, + terminal: { residentBytes: 40_000, cpuPercent: 40, count: 1 }, + browser: { residentBytes: 50_000, cpuPercent: 50, count: 1 }, + // `git` whose arguments mention claude, a parentless process, and a node script. + other: { residentBytes: 220_000, cpuPercent: 220, count: 3 }, + }); + }); +}); diff --git a/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts new file mode 100644 index 0000000000000..6f8f29c37161f --- /dev/null +++ b/apps/server/src/resourceTelemetry/ProcessGroupMetrics.ts @@ -0,0 +1,125 @@ +import type { ResourceTelemetryProcess } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Metric from "effect/Metric"; + +import * as ServerConfig from "../config.ts"; +import { metricAttributes } from "../observability/Metrics.ts"; +import * as ResourceTelemetry from "./ResourceTelemetry.ts"; + +const SAMPLE_INTERVAL = "1 minute"; + +const residentBytes = Metric.gauge("t3_process_group_resident_bytes", { + description: "Resident memory of the server's processes, summed by group.", + attributes: { unit: "By" }, +}); +const cpuPercent = Metric.gauge("t3_process_group_cpu_percent", { + description: "CPU use of the server's processes, summed by group; 100 is one full core.", + attributes: { unit: "%" }, +}); +const processCount = Metric.gauge("t3_process_group_count", { + description: "Processes in each group.", + attributes: { unit: "{process}" }, +}); + +// Each direct child of the server names the group of its whole subtree. A fixed set keeps one +// series per group per server, however many agents and processes come and go. +const PROVIDER_GROUPS: ReadonlyArray = [ + [/codex/, "codex"], + [/claude/, "claude"], + [/cursor/, "cursor"], + [/opencode/, "opencode"], + [/grok/, "grok"], + [/antigravity|gemini/, "antigravity"], +]; +const OTHER_GROUPS: ReadonlyArray = [ + [/chrom/, "browser"], + [/^(?:ba|z|fi|da|c)?sh(?:\.exe)?$|^pwsh|^powershell|^cmd\.exe$/, "terminal"], +]; +// A CLI shipped as a script runs under a JavaScript runtime, so its process name is the +// runtime's (older Claude packages run `node .../@anthropic-ai/claude-code/cli.js`). Only those +// are matched by command line; any other name is matched by name alone, so a shell or `git` +// whose arguments mention a provider stays in its own group. +const SCRIPT_RUNTIME = /^(?:node|bun|deno)(?:\.exe)?$/; + +const match = (groups: ReadonlyArray, text: string) => + groups.find(([pattern]) => pattern.test(text))?.[1]; + +const childGroup = (name: string, command: string) => { + const lowerName = name.toLowerCase(); + if (SCRIPT_RUNTIME.test(lowerName)) + return match(PROVIDER_GROUPS, command.toLowerCase()) ?? "other"; + return match(PROVIDER_GROUPS, lowerName) ?? match(OTHER_GROUPS, lowerName) ?? "other"; +}; + +export interface ProcessGroupTotals { + readonly residentBytes: number; + readonly cpuPercent: number; + readonly count: number; +} + +export function groupProcesses( + processes: ReadonlyArray, +): ReadonlyMap { + const byPid = new Map(processes.map((process) => [process.identity.pid, process])); + const serverPid = processes.find((process) => process.category === "server")?.identity.pid; + const groupOf = (process: ResourceTelemetryProcess): string => { + if (process.category === "server") return "server"; + if (process.category === "resource-monitor") return "resource-monitor"; + if (process.category.startsWith("electron-")) return "electron"; + let current = process; + // Bounded by the table size, in case a reused PID makes the parent chain loop. + for (let step = 0; step < processes.length; step++) { + if (current.ppid === serverPid) return childGroup(current.name, current.command); + const parent = byPid.get(current.ppid); + if (parent === undefined) break; + current = parent; + } + return "other"; + }; + const totals = new Map(); + for (const process of processes) { + const group = groupOf(process); + const total = totals.get(group) ?? { residentBytes: 0, cpuPercent: 0, count: 0 }; + totals.set(group, { + residentBytes: total.residentBytes + process.residentBytes, + cpuPercent: total.cpuPercent + process.cpuPercent, + count: total.count + 1, + }); + } + return totals; +} + +/** + * Exports process totals by group while OTLP metrics export is on. Sampling walks the process + * table, which an idle server otherwise never does, so only a server exporting metrics pays for + * it, once a minute. + */ +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + if (config.otlpMetricsUrl === undefined) return; + const telemetry = yield* ResourceTelemetry.ResourceTelemetry; + // A group that empties reads zero rather than holding its last value. + const seen = new Set(); + const sample = Effect.fn("ProcessGroupMetrics.sample")(function* () { + const totals = groupProcesses((yield* telemetry.refresh).processes); + for (const group of totals.keys()) seen.add(group); + for (const group of seen) { + const total = totals.get(group) ?? { residentBytes: 0, cpuPercent: 0, count: 0 }; + const attributes = metricAttributes({ group }); + yield* Metric.update(Metric.withAttributes(residentBytes, attributes), total.residentBytes); + yield* Metric.update(Metric.withAttributes(cpuPercent, attributes), total.cpuPercent); + yield* Metric.update(Metric.withAttributes(processCount, attributes), total.count); + } + }); + yield* sample().pipe( + Effect.catch((error) => + Effect.logDebug("process group metrics sample failed", { error: error.message }), + ), + Effect.andThen(Effect.sleep(SAMPLE_INTERVAL)), + Effect.forever, + Effect.forkScoped, + ); + }), +); diff --git a/apps/server/src/resourceTelemetry/ResourceAttribution.ts b/apps/server/src/resourceTelemetry/ResourceAttribution.ts index 374564bb7d88e..a8943a35f32df 100644 --- a/apps/server/src/resourceTelemetry/ResourceAttribution.ts +++ b/apps/server/src/resourceTelemetry/ResourceAttribution.ts @@ -32,7 +32,7 @@ function nonNegativeInteger(value: number | undefined, fallback: number): number return Math.max(0, Math.round(value)); } -export const make = Effect.fn("resourceTelemetry.resourceAttribution.make")(function* () { +const make = Effect.fn("resourceTelemetry.resourceAttribution.make")(function* () { const entries = yield* Ref.make(new Map()); const record: ResourceAttribution["Service"]["record"] = (input) => diff --git a/apps/server/src/resourceTelemetry/ResourceMonitorBinary.test.ts b/apps/server/src/resourceTelemetry/ResourceMonitorBinary.test.ts index 1f30be9477188..232d89b7aa50c 100644 --- a/apps/server/src/resourceTelemetry/ResourceMonitorBinary.test.ts +++ b/apps/server/src/resourceTelemetry/ResourceMonitorBinary.test.ts @@ -1,14 +1,14 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { afterEach, assert, describe, expect, it, vi } from "@effect/vitest"; +import { afterEach, assert, describe, it, vi } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import * as ServerConfig from "../config.ts"; import * as ResourceMonitorBinary from "./ResourceMonitorBinary.ts"; -// The override checks POSIX exec bits on a real file under a linux platform -// mock; NTFS never reports those bits, so the check cannot be satisfied there. +// NTFS lacks POSIX exec bits required by this Linux-mocked override check. const windowsHost = HostProcess.Platform.defaultValue() === "win32"; describe("ResourceMonitorBinary", () => { @@ -16,56 +16,6 @@ describe("ResourceMonitorBinary", () => { vi.restoreAllMocks(); }); - it.effect("skips Linux libc detection on Windows", () => - Effect.gen(function* () { - const getReport = vi.spyOn(process.report, "getReport").mockImplementation(() => { - throw new Error("Linux libc detection must not run on Windows"); - }); - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-resource-monitor-binary-", - }); - const binaryPath = `${baseDir}/t3-resource-monitor.exe`; - yield* fileSystem.writeFileString(binaryPath, "binary"); - - const service = yield* ResourceMonitorBinary.make().pipe( - Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(HostProcess.Architecture, "arm64"), - Effect.provideService(HostProcess.Environment, { - T3CODE_RESOURCE_MONITOR_PATH: binaryPath, - }), - ); - - assert.equal(yield* service.resolve, binaryPath); - expect(getReport).not.toHaveBeenCalled(); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect.skipIf(windowsHost)("resolves an executable override", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-resource-monitor-binary-", - }); - const binaryPath = `${baseDir}/t3-resource-monitor`; - yield* fileSystem.writeFileString(binaryPath, "binary"); - yield* fileSystem.chmod(binaryPath, 0o755); - - const service = yield* ResourceMonitorBinary.make().pipe( - Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), - Effect.provideService(HostProcess.Platform, "linux"), - Effect.provideService(HostProcess.Architecture, "x64"), - Effect.provideService(ResourceMonitorBinary.ResourceMonitorHostLinuxLibc, "musl"), - Effect.provideService(HostProcess.Environment, { - T3CODE_RESOURCE_MONITOR_PATH: binaryPath, - }), - ); - - assert.equal(yield* service.resolve, binaryPath); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - it.effect.skipIf(windowsHost)("resolves an executable override on an unsupported platform", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -115,6 +65,7 @@ describe("ResourceMonitorBinary", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + // regression: #16838 a directory resolved as the resource monitor binary it.effect("rejects a directory override", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -137,22 +88,49 @@ describe("ResourceMonitorBinary", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect("rejects unsupported platform and architecture pairs", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const baseDir = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-resource-monitor-binary-", - }); - const service = yield* ResourceMonitorBinary.make().pipe( - Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), - Effect.provideService(HostProcess.Platform, "freebsd"), - Effect.provideService(HostProcess.Architecture, "ia32"), - Effect.provideService(HostProcess.Environment, {}), - ); - const error = yield* Effect.flip(service.resolve); - - assert.instanceOf(error, ResourceMonitorBinary.ResourceMonitorBinaryUnsupported); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + it.effect.each(["release", "debug"])( + "resolves a cargo %s binary from the built server layout", + (profile) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-resource-monitor-binary-", + }); + const projectDirectory = path.join(baseDir, "repo"); + const distDirectory = path.join(projectDirectory, "apps", "server", "dist"); + const binaryDirectory = path.join( + projectDirectory, + "native", + "resource-monitor", + "target", + profile, + ); + const binaryPath = path.join(binaryDirectory, "t3-resource-monitor.exe"); + yield* fileSystem.makeDirectory(distDirectory, { recursive: true }); + yield* fileSystem.makeDirectory(binaryDirectory, { recursive: true }); + yield* fileSystem.writeFileString(binaryPath, "binary"); + yield* fileSystem.chmod(binaryPath, 0o755); + + const service = yield* ResourceMonitorBinary.make().pipe( + // The bundled module lives in dist rather than src/resourceTelemetry. + Effect.provideService(Path.Path, { + ...path, + resolve: (...segments) => + path.resolve( + ...segments.map((segment) => + segment === import.meta.dirname ? distDirectory : segment, + ), + ), + }), + Effect.provide(ServerConfig.layerTest(projectDirectory, baseDir)), + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Architecture, "arm64"), + Effect.provideService(HostProcess.Environment, {}), + ); + + assert.equal(yield* service.resolve, binaryPath); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); it.effect("rejects bundled glibc binaries on musl Linux hosts", () => diff --git a/apps/server/src/resourceTelemetry/ResourceMonitorBinary.ts b/apps/server/src/resourceTelemetry/ResourceMonitorBinary.ts index c7f69f5668c2f..f249197d8510a 100644 --- a/apps/server/src/resourceTelemetry/ResourceMonitorBinary.ts +++ b/apps/server/src/resourceTelemetry/ResourceMonitorBinary.ts @@ -146,6 +146,20 @@ export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(fu environment.T3CODE_RESOURCE_MONITOR_PATH, config.resourceMonitorPath, ].filter((candidate): candidate is string => Boolean(candidate)); + const cargoOutputDirectories = + rustTarget === undefined + ? [] + : [ + path.join("target", rustTarget, "release"), + path.join("target", "release"), + path.join("target", "debug"), + ]; + const sourceCandidates = [ + path.resolve(import.meta.dirname, "../../../../native/resource-monitor"), + path.resolve(import.meta.dirname, "../../../native/resource-monitor"), + ].flatMap((crateDirectory) => + cargoOutputDirectories.map((directory) => path.join(crateDirectory, directory, executableName)), + ); const bundledCandidates = platformKey === undefined || rustTarget === undefined ? [] @@ -153,30 +167,7 @@ export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(fu path.resolve(import.meta.dirname, "resource-monitor", platformKey, executableName), path.resolve(import.meta.dirname, "resource-monitor", executableName), path.resolve(import.meta.dirname, "../resource-monitor", executableName), - path.resolve( - import.meta.dirname, - "../../../../native/resource-monitor/target", - rustTarget, - "release", - executableName, - ), - path.resolve( - import.meta.dirname, - "../../../native/resource-monitor/target", - rustTarget, - "release", - executableName, - ), - path.resolve( - import.meta.dirname, - "../../../../native/resource-monitor/target/release", - executableName, - ), - path.resolve( - import.meta.dirname, - "../../../../native/resource-monitor/target/debug", - executableName, - ), + ...sourceCandidates, ]; if (overrideCandidates.length === 0 && bundledCandidates.length === 0) { return ResourceMonitorBinary.of({ @@ -198,8 +189,7 @@ export const make = Effect.fn("resourceTelemetry.resourceMonitorBinary.make")(fu const stat = yield* fileSystem.stat(candidate).pipe(Effect.option); if (Option.isSome(stat)) { - // Directories are executable-looking on win32, where the exec-bit test - // below is skipped, and only fail later at spawn. + // Windows skips exec-bit checks, so directories would otherwise pass until spawn. const unusable = stat.value.type === "Directory" || (platform !== "win32" && (stat.value.mode & 0o111) === 0); diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts index c4273d7336aca..c12e2e44ed7eb 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetry.test.ts @@ -6,7 +6,6 @@ import type { import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -14,13 +13,20 @@ import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import * as DesktopTelemetryReceiver from "./DesktopTelemetryReceiver.ts"; import * as NativeTelemetryClient from "./NativeTelemetryClient.ts"; import * as ResourceAttribution from "./ResourceAttribution.ts"; import * as ResourceTelemetry from "./ResourceTelemetry.ts"; +// ResourceTelemetry classifies process.pid as the server, so fixture PIDs are +// offsets from it. Fixed PIDs collide whenever the test worker is assigned one. +const SERVER_PID = process.pid; +const CODEX_PID = SERVER_PID + 1; +const SHORT_LIVED_CHILD_PID = SERVER_PID + 2; +const ELECTRON_PID = SERVER_PID + 3; +const MONITOR_PID = SERVER_PID + 4; + function processSample( input: Partial & Pick, @@ -50,14 +56,14 @@ function nativeSnapshot(input: { }): ResourceMonitorSnapshotEvent { const processes = [ processSample({ - pid: process.pid, + pid: SERVER_PID, ppid: 1, startTimeMs: 100, cpuTimeMs: input.sequence * 10, }), processSample({ - pid: 4_242, - ppid: process.pid, + pid: CODEX_PID, + ppid: SERVER_PID, startTimeMs: 200, name: "codex", command: "codex app-server", @@ -65,7 +71,7 @@ function nativeSnapshot(input: { ioWriteBytes: input.childWriteBytes, }), processSample({ - pid: 5_000, + pid: ELECTRON_PID, ppid: 1, startTimeMs: 300, name: "electron", @@ -73,8 +79,8 @@ function nativeSnapshot(input: { cpuTimeMs: input.sequence * 20, }), processSample({ - pid: 9_000, - ppid: process.pid, + pid: MONITOR_PID, + ppid: SERVER_PID, startTimeMs: 400, name: "t3-resource-monitor", command: "t3-resource-monitor", @@ -111,7 +117,7 @@ function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot type: "desktopTelemetry", sequence: 1, sampledAtUnixMs, - electronPid: 5_000, + electronPid: ELECTRON_PID, power: { source: "electron-main", idle: "false", @@ -127,7 +133,7 @@ function desktopSnapshot(sampledAtUnixMs: number): DesktopHostTelemetrySnapshot speedLimitPercent: Option.some(90), electronProcesses: [ { - pid: 5_000, + pid: ELECTRON_PID, creationTimeMs: 300, type: "Browser", name: "electron", @@ -154,17 +160,17 @@ describe("ResourceTelemetry", () => { childWriteBytes: index * 100, }); const processes = sample.processes - .filter((entry) => entry.pid === process.pid || entry.pid === 4_242) + .filter((entry) => entry.pid === SERVER_PID || entry.pid === CODEX_PID) .map((entry) => - entry.pid === 4_242 + entry.pid === CODEX_PID ? { ...entry, startTimeMs: index } : { ...entry, ioWriteBytes: index * 100 }, ); if (index === 0 || index === 2) { processes.push( processSample({ - pid: 4_243, - ppid: process.pid, + pid: SHORT_LIVED_CHILD_PID, + ppid: SERVER_PID, startTimeMs: 500, cpuTimeMs: index === 0 ? 100 : 350, ioWriteBytes: index === 0 ? 1_000 : 5_000, @@ -192,18 +198,20 @@ describe("ResourceTelemetry", () => { expect(history.topProcesses).toHaveLength(sampleCount + 2); expect( - history.topProcesses.find((entry) => entry.identity.pid === process.pid), + history.topProcesses.find((entry) => entry.identity.pid === SERVER_PID), ).toMatchObject({ sampleCount, cpuTimeMs: (sampleCount - 1) * 10, ioWriteBytes: (sampleCount - 1) * 100, }); - const children = history.topProcesses.filter((entry) => entry.identity.pid === 4_242); + const children = history.topProcesses.filter((entry) => entry.identity.pid === CODEX_PID); expect(children).toHaveLength(sampleCount); for (const child of children) { expect(child).toMatchObject({ sampleCount: 1, cpuTimeMs: 0, ioWriteBytes: 0 }); } - expect(history.topProcesses.find((entry) => entry.identity.pid === 4_243)).toMatchObject({ + expect( + history.topProcesses.find((entry) => entry.identity.pid === SHORT_LIVED_CHILD_PID), + ).toMatchObject({ sampleCount: 2, cpuTimeMs: 250, ioWriteBytes: 4_000, @@ -216,87 +224,6 @@ describe("ResourceTelemetry", () => { }), ); - it.effect("enables live native and Electron collection only while changes are retained", () => - Effect.gen(function* () { - const sampledAtUnixMs = DateTime.toEpochMillis(yield* DateTime.now); - const sample = nativeSnapshot({ - sequence: 1, - sampledAtUnixMs, - childCpuTimeMs: 100, - childWriteBytes: 1_000, - }); - const demandChanges = yield* Ref.make>([]); - const layerNative = NativeTelemetryClient.layerTest({ - sampleNow: Effect.succeed(nativeGeneration(sample, 0)), - health: Effect.succeed({ - status: "healthy", - hello: Option.none(), - lastSampleAt: Option.none(), - lastError: Option.none(), - restartCount: 0, - sampleIntervalMs: 1_000, - }), - }); - const layerDesktop = DesktopTelemetryReceiver.layerTest({ - latest: Effect.succeedSome(desktopSnapshot(sampledAtUnixMs)), - setDiagnosticsDemand: (enabled) => - Ref.update(demandChanges, (changes) => [...changes, enabled]), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide(Layer.mergeAll(layerNative, layerDesktop, ResourceAttribution.layer)), - ); - - const live = yield* Stream.runHead( - Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - return telemetry.changes; - }).pipe(Stream.unwrap), - ).pipe(Effect.provide(layerTelemetry)); - - expect(Option.isSome(live)).toBe(true); - expect(yield* Ref.get(demandChanges)).toEqual([true, false]); - }), - ); - - it.effect("releases live demand when acquisition is interrupted by an idle collector", () => - Effect.gen(function* () { - const sampledAtUnixMs = DateTime.toEpochMillis(yield* DateTime.now); - const demandChanges = yield* Ref.make>([]); - 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({ - latest: Effect.succeedSome(desktopSnapshot(sampledAtUnixMs)), - setDiagnosticsDemand: (enabled) => - Ref.update(demandChanges, (changes) => [...changes, enabled]), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide(Layer.mergeAll(layerNative, layerDesktop, ResourceAttribution.layer)), - ); - - const resultFiber = yield* Stream.runHead( - Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - return telemetry.changes; - }).pipe(Stream.unwrap), - ).pipe(Effect.timeoutOption("10 millis"), Effect.provide(layerTelemetry), Effect.forkChild); - yield* Effect.yieldNow; - yield* TestClock.adjust("10 millis"); - const result = yield* Fiber.join(resultFiber); - - expect(Option.isNone(result)).toBe(true); - expect(yield* Ref.get(demandChanges)).toEqual([true, false]); - }), - ); - it.effect( "attributes an initial Electron root from the identity recorded by the native snapshot", () => @@ -307,7 +234,7 @@ describe("ResourceTelemetry", () => { sampledAtUnixMs, childCpuTimeMs: 100, childWriteBytes: 1_000, - externalProcesses: [{ pid: 5_000, startTimeMs: 300 }], + externalProcesses: [{ pid: ELECTRON_PID, startTimeMs: 300 }], }); const desktop = { ...desktopSnapshot(sampledAtUnixMs), @@ -336,9 +263,9 @@ describe("ResourceTelemetry", () => { return yield* telemetry.refresh; }).pipe(Effect.provide(layerTelemetry)); - expect(snapshot.processes.find((entry) => entry.identity.pid === 5_000)?.category).toBe( - "electron-main", - ); + expect( + snapshot.processes.find((entry) => entry.identity.pid === ELECTRON_PID)?.category, + ).toBe("electron-main"); expect(snapshot.groups.electron.processStarts).toBe(1); expect(snapshot.groups.backend.processStarts).toBe(3); }), @@ -405,73 +332,6 @@ describe("ResourceTelemetry", () => { ), ); - it.effect("retains desktop health changes while aggregate telemetry initializes", () => - Effect.scoped( - Effect.gen(function* () { - const health = yield* Ref.make({ - status: "starting", - lastSampleAt: Option.none(), - lastError: Option.none(), - }); - const healthChanges = - yield* PubSub.sliding(4); - const healthSubscribed = yield* Deferred.make(); - const finishDesktopSnapshot = yield* Deferred.make(); - const layerDesktop = DesktopTelemetryReceiver.layerTest({ - health: Ref.get(health), - subscribeHealth: Effect.gen(function* () { - const subscription = yield* PubSub.subscribe(healthChanges); - const latest = yield* Ref.get(health); - yield* Deferred.succeed(healthSubscribed, undefined); - return { - latest, - changes: Stream.fromSubscription(subscription), - }; - }), - subscribe: Deferred.await(finishDesktopSnapshot).pipe( - Effect.as({ - latest: Option.none(), - changes: Stream.empty, - }), - ), - }); - const layerTelemetry = ResourceTelemetry.layer.pipe( - Layer.provide( - Layer.mergeAll( - NativeTelemetryClient.layerTest(), - layerDesktop, - ResourceAttribution.layer, - ), - ), - ); - const resultFiber = yield* Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - while (true) { - const snapshot = yield* telemetry.latest; - if (snapshot.health.desktop.status === "degraded") return snapshot; - yield* Effect.yieldNow; - } - }).pipe(Effect.provide(layerTelemetry), Effect.timeout("1 second"), Effect.forkChild); - - yield* Deferred.await(healthSubscribed); - const degraded: DesktopTelemetryReceiver.DesktopTelemetryReceiverHealth = { - status: "degraded", - lastSampleAt: Option.none(), - lastError: Option.some("desktop telemetry failed"), - }; - yield* Ref.set(health, degraded); - yield* PubSub.publish(healthChanges, degraded); - yield* Deferred.succeed(finishDesktopSnapshot, undefined); - - const snapshot = yield* Fiber.join(resultFiber); - expect(snapshot.health.desktop.status).toBe("degraded"); - expect(Option.getOrNull(snapshot.health.desktop.lastError)).toBe( - "desktop telemetry failed", - ); - }), - ), - ); - it.effect("atomically subscribes while a desktop update is being rebuilt", () => Effect.scoped( Effect.gen(function* () { @@ -539,183 +399,4 @@ describe("ResourceTelemetry", () => { }), ), ); - - it.effect("combines native, Electron, attribution, retry, and history data", () => - Effect.gen(function* () { - const startedAt = DateTime.toEpochMillis(yield* DateTime.now); - const samples = [ - nativeSnapshot({ - sequence: 1, - sampledAtUnixMs: startedAt, - childCpuTimeMs: 100, - childWriteBytes: 1_000, - }), - nativeSnapshot({ - sequence: 2, - sampledAtUnixMs: startedAt + 1_000, - childCpuTimeMs: 350, - childWriteBytes: 5_000, - }), - nativeSnapshot({ - sequence: 1, - sampledAtUnixMs: startedAt + 2_000, - childCpuTimeMs: 500, - childWriteBytes: 7_000, - }), - ] as const; - const sampleIndex = yield* Ref.make(0); - const externalProcesses = yield* Ref.make< - ReadonlyArray<{ readonly pid: number; readonly startTimeMs?: number }> - >([]); - const retryCount = yield* Ref.make(0); - const nativeHealth = yield* Ref.make({ - status: "healthy", - hello: Option.some({ - version: 3, - type: "hello", - sidecarVersion: "0.1.0", - sidecarPid: 9_000, - platform: "test", - arch: "test", - capabilities: { - cumulativeCpuTime: true, - currentCpuPercent: true, - residentMemory: true, - virtualMemory: true, - ioBytes: true, - processStartTime: true, - processTree: true, - }, - }), - lastSampleAt: Option.some(DateTime.makeUnsafe(startedAt)), - lastError: Option.none(), - restartCount: 2, - sampleIntervalMs: 1_000, - }); - const nativeHealthChanges = - yield* PubSub.sliding(4); - const layerNative = NativeTelemetryClient.layerTest({ - setExternalProcesses: (processes) => Ref.set(externalProcesses, processes), - readHistory: () => Effect.succeed(samples.slice(0, 2)), - sampleNow: Ref.modify(sampleIndex, (index) => { - const sampleIndex = Math.min(index, samples.length - 1); - return [nativeGeneration(samples[sampleIndex]!, sampleIndex === 2 ? 3 : 2), index + 1]; - }), - retry: Ref.updateAndGet(retryCount, (count) => count + 1).pipe(Effect.as(true)), - health: Ref.get(nativeHealth), - subscribeHealth: Effect.gen(function* () { - const subscription = yield* PubSub.subscribe(nativeHealthChanges); - const latest = yield* Ref.get(nativeHealth); - return { - latest, - changes: Stream.fromSubscription(subscription), - }; - }), - }); - const layerDesktop = DesktopTelemetryReceiver.layerTest({ - latest: Effect.succeedSome(desktopSnapshot(startedAt)), - health: Effect.succeed({ - status: "healthy", - lastSampleAt: Option.some(DateTime.makeUnsafe(startedAt)), - lastError: Option.none(), - }), - }); - const layerAttribution = ResourceAttribution.layer; - const layerDependencies = Layer.mergeAll(layerNative, layerDesktop, layerAttribution); - const layerTelemetry = ResourceTelemetry.layer.pipe(Layer.provide(layerDependencies)); - const layer = Layer.mergeAll(layerDependencies, layerTelemetry); - - yield* Effect.gen(function* () { - const telemetry = yield* ResourceTelemetry.ResourceTelemetry; - const attribution = yield* ResourceAttribution.ResourceAttribution; - - expect(yield* Ref.get(externalProcesses)).toEqual([{ pid: 5_000, startTimeMs: 300 }]); - - yield* attribution.record({ - component: "provider-event-log", - operation: "append", - logicalWriteBytes: 512, - count: 2, - durationMs: 4, - }); - const first = yield* telemetry.refresh; - expect(first.groups.backend.processCount).toBe(2); - expect(first.groups.electron.processCount).toBe(1); - expect(first.groups.monitor.processCount).toBe(1); - expect(first.power.onBattery).toBe("true"); - expect(Option.getOrNull(first.speedLimitPercent)).toBe(90); - expect(first.attribution.entries).toEqual([ - { - component: "provider-event-log", - operation: "append", - logicalReadBytes: 0, - logicalWriteBytes: 512, - count: 2, - durationMs: 4, - }, - ]); - - yield* TestClock.adjust(Duration.seconds(1)); - const second = yield* telemetry.refresh; - const codex = second.processes.find((entry) => entry.identity.pid === 4_242); - expect(codex?.cpuPercent).toBe(25); - expect(codex?.ioWriteBytesPerSecond).toBe(4_000); - expect(second.groups.backend.ioWriteBytes).toBe(4_000); - expect(second.health.collectionDurationMicros).toBe(300); - expect(second.health.scannedProcessCount).toBe(80); - expect(second.health.inaccessibleProcessCount).toBe(1); - - const history = yield* telemetry.readHistory({ - windowMs: 60_000, - bucketMs: 10_000, - }); - expect(history.retainedSampleCount).toBeGreaterThan(0); - expect( - history.topProcesses.find((entry) => entry.identity.pid === 4_242)?.sampleCount, - ).toBe(2); - expect(history.topProcesses.find((entry) => entry.identity.pid === 4_242)?.cpuTimeMs).toBe( - 250, - ); - expect( - history.topProcesses.find((entry) => entry.identity.pid === 4_242)?.ioWriteBytes, - ).toBe(4_000); - expect(history.buckets.reduce((total, bucket) => total + bucket.ioWriteBytes, 0)).toBe( - 4_000, - ); - - const retry = yield* telemetry.retry; - expect(retry.accepted).toBe(true); - expect(yield* Ref.get(retryCount)).toBe(1); - - yield* Ref.update(nativeHealth, (current) => ({ - ...current, - hello: Option.map(current.hello, (hello) => ({ - ...hello, - sidecarPid: 9_001, - })), - restartCount: 3, - })); - yield* TestClock.adjust(Duration.seconds(1)); - const restarted = yield* telemetry.refresh; - expect(DateTime.toEpochMillis(restarted.readAt)).toBe(startedAt + 2_000); - expect(Option.getOrNull(restarted.health.sidecarPid)).toBe(9_001); - - yield* Ref.update(nativeHealth, (current) => ({ - ...current, - status: "degraded" as const, - lastError: Option.some("collector exited"), - })); - yield* PubSub.publish(nativeHealthChanges, yield* Ref.get(nativeHealth)); - yield* Effect.yieldNow; - const healthUpdate = yield* telemetry.latest; - expect(healthUpdate.health.native.status).toBe("degraded"); - expect(Option.getOrNull(healthUpdate.health.native.lastError)).toBe("collector exited"); - const degradedHistory = yield* telemetry.readHistory({ - windowMs: 60_000, - bucketMs: 10_000, - }); - expect(degradedHistory.health.native.status).toBe("degraded"); - }).pipe(Effect.provide(layer)); - }), - ); }); diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetry.ts b/apps/server/src/resourceTelemetry/ResourceTelemetry.ts index 0563ab7b107ad..7516640dca922 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetry.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetry.ts @@ -142,7 +142,7 @@ function buildHealth(input: { }; } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(function* () { const nativeClient = yield* NativeTelemetryClient.NativeTelemetryClient; const desktopReceiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver; @@ -333,8 +333,9 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi const ingestNative = (snapshot: NativeTelemetryClient.NativeTelemetrySnapshot) => rebuild({ nativeSnapshot: snapshot, updatePrevious: true }); - const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) => - Effect.gen(function* () { + const ingestDesktop = + /* Desktop samples arrive continuously; avoid a span per telemetry sample. */ + Effect.fnUntraced(function* (snapshot: DesktopHostTelemetrySnapshot) { const electronRoot = snapshot.electronProcesses.find( (process) => process.pid === snapshot.electronPid, ); @@ -412,39 +413,38 @@ export const make = Effect.fn("resourceTelemetry.resourceTelemetry.make")(functi ); const liveChanges = Stream.unwrap(Effect.map(subscribe, ({ changes }) => changes)); - const readHistory: ResourceTelemetry["Service"]["readHistory"] = (input) => - Effect.gen(function* () { - const readAt = yield* DateTime.now; - const normalizedInput = normalizeResourceTelemetryHistoryInput(input); - const historyResult = yield* Effect.result( - nativeClient.readHistory(normalizedInput.windowMs), - ); - if (Result.isFailure(historyResult)) { - yield* Effect.logWarning("Failed to read native resource telemetry history", { - cause: historyResult.failure.message, - }); - } - const [nativeHealth, desktopHealth] = yield* Effect.all([ - nativeClient.health, - desktopReceiver.health, - ]); - const current = yield* Ref.get(state); - return buildResourceTelemetryHistory({ - readAt, - windowMs: normalizedInput.windowMs, - bucketMs: normalizedInput.bucketMs, - sampleIntervalMs: nativeHealth.sampleIntervalMs, - serverPid: process.pid, - sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid), - desktopSnapshot: current.desktopSnapshot, - snapshots: Result.isSuccess(historyResult) ? historyResult.success : [], - health: buildHealth({ - native: nativeHealth, - desktop: desktopHealth, - nativeSnapshot: current.nativeSnapshot, - }), + const readHistory: ResourceTelemetry["Service"]["readHistory"] = Effect.fn( + "ResourceTelemetry.readHistory", + )(function* (input) { + const readAt = yield* DateTime.now; + const normalizedInput = normalizeResourceTelemetryHistoryInput(input); + const historyResult = yield* Effect.result(nativeClient.readHistory(normalizedInput.windowMs)); + if (Result.isFailure(historyResult)) { + yield* Effect.logWarning("Failed to read native resource telemetry history", { + cause: historyResult.failure.message, }); + } + const [nativeHealth, desktopHealth] = yield* Effect.all([ + nativeClient.health, + desktopReceiver.health, + ]); + const current = yield* Ref.get(state); + return buildResourceTelemetryHistory({ + readAt, + windowMs: normalizedInput.windowMs, + bucketMs: normalizedInput.bucketMs, + sampleIntervalMs: nativeHealth.sampleIntervalMs, + serverPid: process.pid, + sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid), + desktopSnapshot: current.desktopSnapshot, + snapshots: Result.isSuccess(historyResult) ? historyResult.success : [], + health: buildHealth({ + native: nativeHealth, + desktop: desktopHealth, + nativeSnapshot: current.nativeSnapshot, + }), }); + }); yield* nativeHealthSubscription.changes.pipe( Stream.runForEach(() => refreshHealth), Effect.forkScoped, diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.test.ts b/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.test.ts index fff4588c8468e..236c0893bd7a8 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.test.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.test.ts @@ -8,10 +8,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; -import { - buildResourceTelemetryHistory, - normalizeResourceTelemetryHistoryInput, -} from "./ResourceTelemetryHistory.ts"; +import { buildResourceTelemetryHistory } from "./ResourceTelemetryHistory.ts"; const SERVER_PID = 100; const ELECTRON_PID = 200; @@ -132,13 +129,6 @@ function desktopSnapshot(): DesktopHostTelemetrySnapshot { } describe("buildResourceTelemetryHistory", () => { - it("normalizes query bounds before requesting native history", () => { - expect(normalizeResourceTelemetryHistoryInput({ windowMs: 0, bucketMs: 0 })).toEqual({ - windowMs: 1_000, - bucketMs: 1_000, - }); - }); - it("replays native snapshots on demand without applying current Electron metrics", () => { const history = buildResourceTelemetryHistory({ readAt: DateTime.makeUnsafe(STARTED_AT_MS + 2_000), @@ -230,24 +220,6 @@ describe("buildResourceTelemetryHistory", () => { expect(child?.ioWriteBytes).toBe(4_000); }); - it("uses an exact current Electron identity for slightly older native samples", () => { - const history = buildResourceTelemetryHistory({ - readAt: DateTime.makeUnsafe(STARTED_AT_MS + 2_000), - windowMs: 10_000, - bucketMs: 10_000, - sampleIntervalMs: 1_000, - serverPid: SERVER_PID, - sidecarPid: Option.none(), - desktopSnapshot: Option.some(desktopSnapshot()), - snapshots: [snapshot(1, STARTED_AT_MS, 100, 1_000)], - health, - }); - - expect( - history.topProcesses.find((process) => process.identity.pid === ELECTRON_PID)?.category, - ).toBe("electron-main"); - }); - it("uses the preceding sample as a baseline without attributing pre-window deltas", () => { const readAtMs = STARTED_AT_MS + 10_000; const history = buildResourceTelemetryHistory({ diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts index 74602efb62a5d..4df56454cfc58 100644 --- a/apps/server/src/review/ReviewService.test.ts +++ b/apps/server/src/review/ReviewService.test.ts @@ -3,7 +3,6 @@ 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 SqlClient from "effect/sql/SqlClient"; import { ProjectId } from "@t3tools/contracts"; @@ -24,7 +23,6 @@ function layer(input: { readonly previousWorktreesDirectories?: ReadonlyArray; readonly projectRoots?: ReadonlyArray | "unavailable"; readonly threadWorktrees?: ReadonlyArray<{ worktreePath: string; deleted?: boolean }>; - /** What `git worktree list` reports for every project. */ readonly gitWorktrees?: ReadonlyArray; }) { const projectRoots = input.projectRoots ?? []; @@ -121,39 +119,6 @@ describe("ReviewService", () => { }).pipe(Effect.provide(NodeServices.layer)), ); - it.effect("attributes file-content workspace violations to the file-content operation", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); - const outsideRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-outside-" }); - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); - const detectCalls: Array<{ readonly cwd: string }> = []; - - const error = yield* Effect.gen(function* () { - const review = yield* ReviewService.ReviewService; - return yield* review - .getDiffFileContents({ - cwd: outsideRoot, - sourceKind: "working-tree", - changeType: "change", - baseRef: "HEAD", - headRef: null, - oldPath: "file.ts", - newPath: "file.ts", - }) - .pipe(Effect.flip); - }).pipe(Effect.provide(layer({ workspaceRoot, baseDir, detectCalls }))); - - assert.strictEqual(error._tag, "VcsRepositoryDetectionError"); - assert.strictEqual(error.operation, "ReviewService.getDiffFileContents"); - assert.match( - "detail" in error ? error.detail : "", - /must stay within the configured workspace root/, - ); - assert.deepStrictEqual(detectCalls, []); - }).pipe(Effect.provide(NodeServices.layer)), - ); - it.effect("allows previous custom worktree locations but never a filesystem root", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -209,7 +174,6 @@ describe("ReviewService", () => { assert.strictEqual((yield* review(projectRoot, [projectRoot])).cwd, projectRoot); assert.strictEqual((yield* review(projectChild, [projectRoot])).cwd, projectChild); - // A child whose name starts with `..` is still inside. const dottedChild = `${projectRoot}/..feature`; yield* fs.makeDirectory(dottedChild); assert.strictEqual((yield* review(dottedChild, [projectRoot])).cwd, dottedChild); @@ -230,11 +194,9 @@ describe("ReviewService", () => { const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); const project = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-project-" }); - // Checkouts outside every managed folder, as `git worktree add ../feature` makes. const bound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-bound-" }); const deleted = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-deleted-" }); const unbound = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-unbound-" }); - // A client can set a thread's path to any folder; git doesn't list this one. const claimed = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-claimed-" }); yield* fs.makeDirectory(`${bound}/sub`); @@ -253,9 +215,7 @@ describe("ReviewService", () => { { worktreePath: bound }, { worktreePath: claimed }, { worktreePath: deleted, deleted: true }, - // A relative path would resolve against the server's own cwd. { worktreePath: "t3-review-relative" }, - // A filesystem root would make every folder look bound. { worktreePath: "/" }, ], }), @@ -299,45 +259,4 @@ describe("ReviewService", () => { assert.strictEqual(result.cwd, checkout); }).pipe(Effect.provide(NodeServices.layer)), ); - - it.effect("allows diff preview cwd inside the configured workspace root", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); - const detectCalls: Array<{ readonly cwd: string }> = []; - - const result = yield* Effect.gen(function* () { - const review = yield* ReviewService.ReviewService; - return yield* review.getDiffPreview({ cwd: workspaceRoot }); - }).pipe(Effect.provide(layer({ workspaceRoot, baseDir, detectCalls }))); - - assert.strictEqual(result.cwd, workspaceRoot); - assert.deepStrictEqual(result.sources, []); - assert.deepStrictEqual(detectCalls, [{ cwd: workspaceRoot }]); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("preserves unexpected path-resolution failures", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" }); - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" }); - const invalidCwd = `${workspaceRoot}\0invalid`; - const detectCalls: Array<{ readonly cwd: string }> = []; - - const error = yield* Effect.gen(function* () { - const review = yield* ReviewService.ReviewService; - return yield* review.getDiffPreview({ cwd: invalidCwd }).pipe(Effect.flip); - }).pipe(Effect.provide(layer({ workspaceRoot, baseDir, detectCalls }))); - - assert.strictEqual(error._tag, "VcsRepositoryDetectionError"); - if (error._tag !== "VcsRepositoryDetectionError") return; - assert.strictEqual(error.operation, "ReviewService.assertWorkspaceBoundCwd.canonicalizePath"); - assert.strictEqual(error.cwd, invalidCwd); - assert.match(error.detail, /Failed to resolve a path/); - assert.instanceOf(error.cause, PlatformError.PlatformError); - assert.deepStrictEqual(detectCalls, []); - }).pipe(Effect.provide(NodeServices.layer)), - ); }); diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts index 488cc84be0a70..48c412a4bbc72 100644 --- a/apps/server/src/review/ReviewService.ts +++ b/apps/server/src/review/ReviewService.ts @@ -32,7 +32,7 @@ export class ReviewService extends Context.Service< } >()("t3/review/ReviewService") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/rpcInitialItems.memory.test.ts b/apps/server/src/rpcInitialItems.memory.test.ts deleted file mode 100644 index 981269d52c70b..0000000000000 --- a/apps/server/src/rpcInitialItems.memory.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off - memory assertions run in an isolated Node process with explicit GC. -import * as NodeChildProcess from "node:child_process"; -import * as NodeURL from "node:url"; -import * as NodeUtil from "node:util"; -import { expect, it } from "vite-plus/test"; - -const execFile = NodeUtil.promisify(NodeChildProcess.execFile); - -it.each(["prefix", "snapshot", "replay"])( - "releases delivered %s history while RPC subscriptions remain open", - async (mode) => { - const root = NodeURL.fileURLToPath(new URL("../../../", import.meta.url)); - const fixture = NodeURL.fileURLToPath( - new URL("./testkit/RpcInitialMemory.fixture.mjs", import.meta.url), - ); - const { stdout } = await execFile(process.execPath, ["--expose-gc", fixture, root, mode]); - const result = JSON.parse(stdout) as { - checkpoints: ReadonlyArray<{ subscriptions: number; retained: number }>; - }; - expect( - result.checkpoints.map(({ subscriptions, retained }) => ({ subscriptions, retained })), - ).toEqual([ - { subscriptions: 2, retained: 0 }, - { subscriptions: 4, retained: 0 }, - ]); - }, -); diff --git a/apps/server/src/rpcInitialItems.ts b/apps/server/src/rpcInitialItems.ts index 172a3a897a32a..6f3409858920f 100644 --- a/apps/server/src/rpcInitialItems.ts +++ b/apps/server/src/rpcInitialItems.ts @@ -6,8 +6,7 @@ export function rpcInitialItems(items: ReadonlyArray): Stream.Stream { return Stream.unwrap( Effect.sync(() => { const initial = pending; - // concat keeps its initial stream definition alive during the live tail. - // That definition must no longer own delivered snapshots or replay rows. + // concat retains the initial stream during live tailing; release delivered snapshots and rows. pending = undefined; return initial === undefined ? Stream.empty : Stream.fromIterable(initial); }), diff --git a/apps/server/src/scheduledTasks/RelayDeliveryProof.ts b/apps/server/src/scheduledTasks/RelayDeliveryProof.ts index 767d2fa7bb962..0f33869c387ea 100644 --- a/apps/server/src/scheduledTasks/RelayDeliveryProof.ts +++ b/apps/server/src/scheduledTasks/RelayDeliveryProof.ts @@ -1,9 +1,4 @@ -/** - * The relay's delivery id, receive time and trace context arrive as plain - * headers, and the webhook URL can also be called directly, so they are only - * trusted alongside a proof the relay signed with its mint key. A request - * without a valid proof is handled as a direct request. - */ +// Trust relay headers only with a mint-key-signed proof; otherwise handle the webhook as a direct request. import { RelayHookDeliveryProofPayload } from "@t3tools/contracts/relay"; import { normalizeRelayIssuer, @@ -44,8 +39,8 @@ export class RelayDeliveryProof extends Context.Service< const make = Effect.gen(function* () { const secrets = yield* ServerSecretStore.ServerSecretStore; const environment = yield* ServerEnvironment.ServerEnvironment; - const verify: RelayDeliveryProof["Service"]["verify"] = (input) => - Effect.gen(function* () { + const verify: RelayDeliveryProof["Service"]["verify"] = Effect.fn("webhook.verifyRelayDelivery")( + function* (input) { const proof = input.headers[RELAY_HOOK_DELIVERY_HEADER]; const deliveryId = input.headers["x-t3-relay-delivery-id"]; const receivedAt = input.headers["x-t3-relay-received-at"]; @@ -80,7 +75,9 @@ const make = Effect.gen(function* () { return Option.none(); } return Option.some({ deliveryId, receivedAt }); - }).pipe(Effect.orElseSucceed(Option.none), Effect.withSpan("webhook.verifyRelayDelivery")); + }, + Effect.orElseSucceed(Option.none), + ); return RelayDeliveryProof.of({ verify }); }); diff --git a/apps/server/src/scheduledTasks/Schedule.test.ts b/apps/server/src/scheduledTasks/Schedule.test.ts index e989768188d03..f5973969747f7 100644 --- a/apps/server/src/scheduledTasks/Schedule.test.ts +++ b/apps/server/src/scheduledTasks/Schedule.test.ts @@ -1,36 +1,9 @@ import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { - isMissedFixedTimeRun, - isSameSchedule, - nextScheduledRunAt, - parseTimeOfDay, -} from "./Schedule.ts"; +import { isSameSchedule, nextScheduledRunAt } from "./Schedule.ts"; describe("scheduled task schedule calculation", () => { - it("parses 24-hour times", () => { - expect(parseTimeOfDay("09:30")).toEqual({ hour: 9, minute: 30 }); - expect(parseTimeOfDay("23:59")).toEqual({ hour: 23, minute: 59 }); - expect(parseTimeOfDay("25:00")).toBeNull(); - }); - - it("calculates interval schedules from the supplied instant", () => { - const next = nextScheduledRunAt( - { type: "interval", everyMs: 5 * 60_000 }, - DateTime.makeUnsafe("2026-07-01T16:00:00.000Z"), - ); - expect(next ? DateTime.formatIso(DateTime.toUtc(next)) : null).toBe("2026-07-01T16:05:00.000Z"); - }); - - it("clamps legacy sub-minute intervals to the one-minute execution floor", () => { - const next = nextScheduledRunAt( - { type: "interval", everyMs: 1_000 }, - DateTime.makeUnsafe("2026-07-01T16:00:00.000Z"), - ); - expect(next ? DateTime.formatIso(DateTime.toUtc(next)) : null).toBe("2026-07-01T16:01:00.000Z"); - }); - it("skips to the next matching fixed-time weekday", () => { const next = nextScheduledRunAt( { type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2, 3, 4, 5] }, @@ -53,18 +26,6 @@ describe("scheduled task schedule calculation", () => { expect(parts?.minute).toBe(0); }); - it("skips fixed-time runs missed by more than the grace window", () => { - const fixedTime = { type: "fixed_time", timeOfDay: "09:00" } as const; - const dueAt = DateTime.makeUnsafe("2026-07-01T09:00:00.000Z"); - const withinGrace = DateTime.makeUnsafe("2026-07-01T09:05:00.000Z"); - const pastGrace = DateTime.makeUnsafe("2026-07-01T15:00:00.000Z"); - expect(isMissedFixedTimeRun(fixedTime, dueAt, withinGrace)).toBe(false); - expect(isMissedFixedTimeRun(fixedTime, dueAt, pastGrace)).toBe(true); - expect(isMissedFixedTimeRun({ type: "interval", everyMs: 60_000 }, dueAt, pastGrace)).toBe( - false, - ); - }); - it("compares schedules structurally", () => { expect( isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 60_000 }), @@ -115,17 +76,4 @@ describe("scheduled task schedule calculation", () => { ), ).toBe(false); }); - - it.each([ - ["9:00", "09:00"], - ["09:00", "9:00"], - ["0:30", "00:30"], - ])("treats %s and %s as the same fixed-time schedule", (before, after) => { - expect( - isSameSchedule( - { type: "fixed_time", timeOfDay: before }, - { type: "fixed_time", timeOfDay: after }, - ), - ).toBe(true); - }); }); diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts index 3952a7fc3318e..d97ea43ae6bad 100644 --- a/apps/server/src/scheduledTasks/Schedule.ts +++ b/apps/server/src/scheduledTasks/Schedule.ts @@ -3,7 +3,7 @@ import * as DateTime from "effect/DateTime"; const MINUTE_MS = 60_000; -export function parseTimeOfDay(value: string): { hour: number; minute: number } | null { +function parseTimeOfDay(value: string): { hour: number; minute: number } | null { const match = /^([01]?\d|2[0-3]):([0-5]\d)$/.exec(value.trim()); if (!match) return null; return { hour: Number(match[1]), minute: Number(match[2]) }; @@ -15,11 +15,8 @@ export function nextScheduledRunAt( ): DateTime.DateTime | null { if (schedule.type === "webhook") return null; if (schedule.type === "interval") { - // Persisted rows created before the one-minute floor remain readable, but - // they must not retain their old high-frequency execution rate. - return DateTime.add(from, { - milliseconds: Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS), - }); + // Intervals advance elapsed time, including across daylight-saving changes. + return DateTime.addDuration(from, Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS)); } const time = parseTimeOfDay(schedule.timeOfDay); @@ -52,9 +49,7 @@ export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedul } if (a.type === "webhook") return b.type === "webhook"; if (b.type !== "fixed_time") return false; - // The contract accepts padded and unpadded hours ("9:00" and "09:00"), so - // compare the parsed time — string equality would treat a format-only edit - // as a schedule change and recompute the pending run. + // Compare parsed times so padded-hour edits do not reschedule pending runs. const aTime = parseTimeOfDay(a.timeOfDay); const bTime = parseTimeOfDay(b.timeOfDay); return ( diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts new file mode 100644 index 0000000000000..4a1a58505c5cb --- /dev/null +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts @@ -0,0 +1,131 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { expect, it } from "@effect/vitest"; +import { ScheduledTaskUpsertInput } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; +import { afterEach, vi } from "vite-plus/test"; + +import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; +import * as Scheduler from "../scheduling/Scheduler.ts"; +import * as SecretRequests from "../secrets/SecretRequests.ts"; +import { ServerActivation } from "../serverActivation.ts"; +import * as ScheduledTaskService from "./ScheduledTaskService.ts"; + +afterEach(() => vi.unstubAllEnvs()); + +const dependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => Effect.die("synthetic dispatch failure"), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), +); +const serviceLayer = ScheduledTaskService.layer.pipe(Layer.provide(dependencies)); +const decodeInput = Schema.decodeUnknownEffect(ScheduledTaskUpsertInput); +const input = { + commandId: "interval-duration", + title: "Interval review", + prompt: "Review the open pull requests.", + enabled: true, + projectId: "project-interval-duration", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", +}; + +it.effect.each([ + { + zone: "America/New_York", + from: "2026-03-08T06:30:00.000Z", + everyMs: 7_200_000, + expected: "2026-03-08T08:30:00.000Z", + }, + { + zone: "America/New_York", + from: "2026-11-01T05:30:00.000Z", + everyMs: 7_200_000, + expected: "2026-11-01T07:30:00.000Z", + }, + { + zone: "America/New_York", + from: "2026-11-01T06:30:00.000Z", + everyMs: 60_000, + expected: "2026-11-01T06:31:00.000Z", + }, + { + zone: "UTC", + from: "2026-11-01T06:30:00.000Z", + everyMs: 60_000, + expected: "2026-11-01T06:31:00.000Z", + }, + { + zone: "Asia/Tokyo", + from: "2026-03-08T06:30:00.000Z", + everyMs: 7_200_000, + expected: "2026-03-08T08:30:00.000Z", + }, +] as const)("persists elapsed interval $zone from $from", ({ zone, from, everyMs, expected }) => + Effect.gen(function* () { + vi.stubEnv("TZ", zone); + yield* TestClock.setTime(Date.parse(from)); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const decoded = yield* decodeInput({ ...input, schedule: { type: "interval", everyMs } }); + const created = yield* service.upsert(decoded); + expect(created.task.nextRunAt).toBe(expected); + expect((yield* service.list()).tasks[0]?.nextRunAt).toBe(expected); + + const paused = yield* service.setEnabled({ id: created.task.id, enabled: false }); + expect(paused.task.nextRunAt).toBeNull(); + const resumed = yield* service.setEnabled({ id: created.task.id, enabled: true }); + expect(resumed.task.nextRunAt).toBe(expected); + + // Exercise completion rescheduling without starting any provider process. + const completed = yield* service.runNow({ id: created.task.id }); + expect(completed.task.lastRunStatus).toBe("failed"); + expect(completed.threadId).toBeNull(); + expect(completed.task.runCount).toBe(1); + expect(completed.task.nextRunAt).toBe(expected); + expect((yield* service.list()).tasks[0]?.nextRunAt).toBe(expected); + }).pipe(Effect.provide(serviceLayer)); + }).pipe( + // Keep the real scheduler parked while exercising finite service actions. + Effect.provideService(ServerActivation, Effect.never), + Effect.provide(SqlitePersistence.layerMemory), + ), +); + +it.effect.each([ + { from: "2026-03-07T23:30:00.000Z", expected: "2026-03-08T13:00:00.000Z" }, + { from: "2026-10-31T23:30:00.000Z", expected: "2026-11-01T14:00:00.000Z" }, +] as const)("keeps fixed-time schedules on the local calendar from $from", ({ from, expected }) => + Effect.gen(function* () { + vi.stubEnv("TZ", "America/New_York"); + yield* TestClock.setTime(Date.parse(from)); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const decoded = yield* decodeInput({ + ...input, + schedule: { type: "fixed_time", timeOfDay: "09:00" }, + }); + const created = yield* service.upsert(decoded); + expect(created.task.nextRunAt).toBe(expected); + expect((yield* service.list()).tasks[0]?.nextRunAt).toBe(expected); + }).pipe(Effect.provide(serviceLayer)); + }).pipe( + Effect.provideService(ServerActivation, Effect.never), + Effect.provide(SqlitePersistence.layerMemory), + ), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts index c562134f0d8ba..09e1d7674044f 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.schedule.test.ts @@ -11,6 +11,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; @@ -22,6 +23,10 @@ it.effect("rejects a stale form save after deletion while preserving explicit-id NodeCrypto.layer, Scheduler.layer, Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), Layer.mock(ThreadManagementService.ThreadManagementService)({}), Layer.mock(SecretRequests.SecretRequests)({}), ); @@ -65,6 +70,10 @@ it.effect("preserves a due run when a save only pads the scheduled hour", () => NodeCrypto.layer, Scheduler.layer, Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), Layer.mock(ThreadManagementService.ThreadManagementService)({}), Layer.mock(SecretRequests.SecretRequests)({}), ); @@ -107,3 +116,54 @@ it.effect("preserves a due run when a save only pads the scheduled hour", () => }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("keeps the task list order when a toggle or edit rewrites updated_at", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-07-01T09:00:00.000Z")); + const layerDependencies = Layer.mergeAll( + NodeCrypto.layer, + Scheduler.layer, + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const input = (id: string) => ({ + id, + title: id, + prompt: "Review the open pull requests.", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: "project-stable-order", + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + const listedIds = service + .list() + .pipe(Effect.map(({ tasks }) => tasks.map((task) => String(task.id)))); + + const older = yield* service.upsert(yield* decodeUpsertInput(input("scheduled-task:older"))); + yield* TestClock.adjust("1 second"); + yield* service.upsert(yield* decodeUpsertInput(input("scheduled-task:newer"))); + const order = ["scheduled-task:newer", "scheduled-task:older"]; + expect(yield* listedIds).toEqual(order); + + yield* TestClock.adjust("1 second"); + const toggled = yield* service.setEnabled({ id: older.task.id, enabled: false }); + expect(toggled.task.updatedAt > older.task.updatedAt).toBe(true); + expect(yield* listedIds).toEqual(order); + + yield* TestClock.adjust("1 second"); + const edit = { ...input(older.task.id), requireExisting: true, title: "Edited" }; + yield* service.upsert(yield* decodeUpsertInput({ ...edit, enabled: false })); + expect(yield* listedIds).toEqual(order); + }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index 8b8dc61850a40..c1dcdd22abbae 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -3,13 +3,21 @@ import * as NodeUtil from "node:util"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, it } from "@effect/vitest"; -import { ScheduledTaskError } from "@t3tools/contracts"; +import { + ProjectId, + ProviderInstanceId, + ScheduledTaskError, + ScheduledTaskId, + ThreadId, +} from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Fiber from "effect/Fiber"; +import * as Stream from "effect/Stream"; import * as Deferred from "effect/Deferred"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; @@ -18,6 +26,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; @@ -170,8 +179,6 @@ it.effect( yield* insertRow(sql, { ...row, enabled: 1 }, now); } - // it.effect freezes the clock; pin it just past the seeded due time so - // the poll sees the rows as due. yield* TestClock.setTime(Date.parse(now) + 1_000); const dispatched = yield* Ref.make(0); const lastDispatched = yield* Deferred.make(); @@ -195,6 +202,10 @@ it.effect( Effect.andThen(Effect.die(new Error("test launch failure"))), ), }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), Layer.mock(ThreadManagementService.ThreadManagementService)({}), Layer.mock(SecretRequests.SecretRequests)({}), NodeCrypto.layer, @@ -202,8 +213,7 @@ it.effect( ), ), ); - // The poll loop delays before its first pass, so the frozen test - // clock must advance once to trigger it. + // The poll delays before its first pass; advance the frozen clock once. yield* TestClock.adjust("6 seconds"); yield* Deferred.await(lastDispatched); const inflight = yield* sql<{ @@ -289,6 +299,10 @@ it.effect( Effect.andThen(Effect.die(new Error("test launch failure"))), ), }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), Layer.mock(ThreadManagementService.ThreadManagementService)({}), Layer.mock(SecretRequests.SecretRequests)({}), NodeCrypto.layer, @@ -321,3 +335,70 @@ it.effect( ); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("thread cleanup notifies subscribers and a finishing run cannot recreate the task", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const subscribed = yield* Deferred.make(); + const running = yield* Deferred.make(); + const removed = yield* Deferred.make(); + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + sendToThread: () => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen(Effect.die("test dispatch failure")), + ), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Scheduler.layer, + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const threadId = ThreadId.make("thread:deleted-during-run"); + const { task } = yield* service.upsert({ + id: ScheduledTaskId.make("task:deleted-during-run"), + title: "Check orchestration", + prompt: "Check progress", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: ProjectId.make("project:test"), + threadId, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + yield* service.subscribeList().pipe( + Stream.runForEach(({ tasks }) => { + const current = tasks.find((candidate) => candidate.id === task.id); + if (current === undefined) return Deferred.succeed(removed, undefined); + return current.lastRunStatus === "running" + ? Deferred.succeed(running, undefined) + : Deferred.succeed(subscribed, undefined); + }), + Effect.forkChild, + ); + yield* Deferred.await(subscribed); + const run = yield* service.runNow({ id: task.id }).pipe(Effect.forkChild); + yield* Deferred.await(started); + yield* Deferred.await(running); + yield* service.deleteForThread(threadId); + yield* Deferred.await(removed); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(run); + assert.lengthOf((yield* service.list()).tasks, 0); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 482ed1669d1af..7e39452c2b52b 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -15,6 +15,7 @@ import { type ScheduledTaskListWebhookDeliveriesResult, type ScheduledTaskRotateWebhookTokenInput, type ScheduledTaskWebhookDeliveryOutcome, + type ScheduledTaskWebhookFilter, type ScheduledTaskListResult, type ScheduledTaskMutationResult, type ScheduledTaskRunNowInput, @@ -28,6 +29,8 @@ import * as Crypto from "effect/Crypto"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Exit from "effect/Exit"; import * as Duration from "effect/Duration"; import * as Metric from "effect/Metric"; import * as Layer from "effect/Layer"; @@ -41,6 +44,7 @@ import * as Stream from "effect/Stream"; import * as SqlClient from "effect/sql/SqlClient"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as Metrics from "../observability/Metrics.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; @@ -52,15 +56,38 @@ import { renderWebhookPrompt, type WebhookRequest, } from "./webhookTemplate.ts"; +import { + acceptWebhookDedupe, + acceptImmediateWebhookDedupe, + releaseWebhookReplay, + decodePendingTask, + decodePendingRequest, + dedupeError, +} from "./webhookDedupe.ts"; +import { describeFailedWebhookFilter, findFailedWebhookFilter } from "./webhookFilter.ts"; import { constantTimeEquals, verifyWebhookSignature } from "./webhookVerification.ts"; export const WEBHOOK_ROUTE_PREFIX = "/api/hooks"; +const isScheduledTaskError = Schema.is(ScheduledTaskError); +const PROMPT_TOO_LONG = "The filled-in prompt is too long."; const WEBHOOK_DELIVERY_RETENTION = 50; +const WEBHOOK_DEDUPE_DELIVERY_RETENTION = 20; +const WEBHOOK_FILTERED_DELIVERY_RETENTION = 20; +const WEBHOOK_DEDUPE_LOG_PER_MINUTE = 10; +const WEBHOOK_FILTERED_LOG_PER_MINUTE = 10; const WEBHOOK_DELIVERY_LOG_BODY_LIMIT = 64 * 1024; const WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT = 64 * 1024; const WEBHOOK_MAX_QUEUED_PER_TASK = 20; -/** Accepted deliveries per task per minute, enforced here as well as on the relay because the tunnel hostname is public too. */ +// Enforce the relay's per-task/minute limit here too; tunnel hostnames are public. const WEBHOOK_RATE_LIMIT_PER_MINUTE = 60; +const LEGACY_DELIVERY_OUTCOMES: ReadonlySet = new Set([ + "accepted", + "dispatch_failed", + "rejected_signature", + "disabled", + "rate_limited", + "expired", +]); interface WebhookOrigin { readonly relayHookBaseUrl: string | null; @@ -92,7 +119,7 @@ class WebhookDeliverySkipped extends Data.TaggedError("WebhookDeliverySkipped")< }> {} interface RateWindow { - readonly accepted: ReadonlyArray; + readonly accepted: ReadonlyArray<{ readonly at: number }>; readonly rejectedLogged: boolean; } @@ -107,12 +134,14 @@ export interface WebhookTriggerRequest extends WebhookRequest { export type WebhookDeliveryOutcome = | "accepted" | "duplicate" + | "coalesced" | "prompt_too_long" | "queue_full" | "rate_limited" | "disabled" | "rejected_signature" | "expired" + | "filtered" | "not_found" | "error"; @@ -120,7 +149,7 @@ export type WebhookTriggerResult = | { readonly _tag: "accepted"; readonly deliveryId: ScheduledTaskWebhookDeliveryId; - readonly outcome: "accepted" | "duplicate" | "prompt_too_long"; + readonly outcome: "accepted" | "duplicate" | "coalesced" | "prompt_too_long" | "filtered"; } | { readonly _tag: "not_found" } | { readonly _tag: "rejected_signature" } @@ -131,6 +160,9 @@ export type WebhookTriggerResult = } | { readonly _tag: "expired" }; +const webhookFilters = (filters: ReadonlyArray | undefined) => + filters?.length ? { filters } : {}; + const decodeTask = Schema.decodeUnknownEffect(ScheduledTask); const decodeTaskId = Schema.decodeUnknownOption(ScheduledTaskId); const decodeScheduleJson = Schema.decodeUnknownEffect( @@ -188,6 +220,7 @@ interface WebhookDeliveryRow { readonly signature_verified: number; readonly missing_fields_json: string; readonly rendered_prompt: string | null; + readonly pending_window: number; readonly error: string | null; } @@ -205,9 +238,15 @@ export class ScheduledTaskService extends Context.Service< readonly delete: ( input: ScheduledTaskDeleteInput, ) => Effect.Effect; + /** Deletes only tasks that still target this thread, including their webhook deliveries. */ + readonly deleteForThread: (threadId: ThreadId) => Effect.Effect; + /** The dispatched thread, or null if dispatch failed; leaves the task's binding unchanged. */ readonly runNow: ( input: ScheduledTaskRunNowInput, - ) => Effect.Effect; + ) => Effect.Effect< + ScheduledTaskRunNowResult & { readonly threadId: ThreadId | null }, + ScheduledTaskError + >; readonly rotateWebhookToken: ( input: ScheduledTaskRotateWebhookTokenInput, ) => Effect.Effect; @@ -217,11 +256,7 @@ export class ScheduledTaskService extends Context.Service< readonly getWebhookDelivery: ( input: ScheduledTaskGetWebhookDeliveryInput, ) => Effect.Effect; - /** - * Verifies, logs and dispatches one webhook request. Returns as soon as the - * delivery is logged; the run itself continues in the background so senders - * with short timeouts get their answer immediately. - */ + /** Verifies, logs and dispatches; returns after logging while the run continues in the background. */ readonly triggerWebhook: ( request: WebhookTriggerRequest, ) => Effect.Effect; @@ -247,8 +282,7 @@ function nextRunAt( from: DateTime.DateTime, ): string | null { if (!task.enabled) return null; - // A stored interval can decode yet overflow the representable DateTime - // range; an unrepresentable occurrence means the task has no next run. + // Decoded intervals can overflow DateTime; unrepresentable occurrences have no next run. try { const next = nextScheduledRunAt(task.schedule, from); return next !== null && Number.isFinite(DateTime.toEpochMillis(next)) ? iso(next) : null; @@ -280,8 +314,9 @@ function webhookEndpoint( }; } -const decodeRow = (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) => - Effect.gen(function* () { +// Runs per task row; list and lookup operations already own the span. +const decodeRow = Effect.fnUntraced( + function* (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) { const schedule = yield* decodeScheduleJson(row.schedule_json); const webhook = schedule.type === "webhook" ? webhookEndpoint(row, origin) : undefined; const workspaceStrategy = yield* decodeWorkspaceStrategyJson(row.workspace_strategy_json); @@ -309,15 +344,18 @@ const decodeRow = (row: ScheduledTaskRow, origin: WebhookOrigin | null = null) = runCount: row.run_count, ...(webhook === undefined ? {} : { webhook }), }); - }).pipe( - Effect.mapError((cause) => { - const taskId = decodeTaskId(row.task_id); - return taskError("Could not decode schedule task row.", { - ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}), - cause, - }); - }), - ); + }, + (effect, row, _origin?) => + effect.pipe( + Effect.mapError((cause) => { + const taskId = decodeTaskId(row.task_id); + return taskError("Could not decode schedule task row.", { + ...(Option.isSome(taskId) ? { taskId: taskId.value } : {}), + cause, + }); + }), + ), +); export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(function* ( now: DateTime.DateTime, @@ -328,15 +366,13 @@ export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(funct WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ${iso(now)} AND last_run_status <> 'running' ORDER BY next_run_at ASC, task_id ASC - `; + `.pipe(NodeSqliteClient.readOnly); const tasks: ScheduledTask[] = []; for (const row of rows) { const decoded = yield* Effect.result(decodeRow(row)); if (Result.isSuccess(decoded)) { const task = decoded.success; - // next_run_at is a freeform string at the schema level; a stored value - // that cannot parse as a DateTime would defect the poll below, so the - // row is skipped here like any other corrupt row. + // next_run_at is freeform; skip unparseable values before they defect the poll. if (task.nextRunAt === null || Option.isSome(DateTime.make(task.nextRunAt))) { tasks.push(task); } else { @@ -361,24 +397,33 @@ export const layer = Layer.effect( const crypto = yield* Crypto.Crypto; const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; const secretRequests = yield* SecretRequests.SecretRequests; const scheduler = yield* Scheduler.Scheduler; const readWebhookOrigin = yield* ScheduledTaskWebhookOrigin; const webhookPermits = yield* Ref.make>( new Map(), ); - // Keyed by task id and creation time, so deliveries of a deleted task that - // finish late release their own count, never a recreated task's. + // Include creation time so late deliveries cannot decrement a recreated task's count. const webhookQueued = yield* Ref.make>(new Map()); const webhookRateWindows = yield* Ref.make>(new Map()); + const webhookRejectedRateWindows = yield* Ref.make>( + new Map(), + ); + const webhookDedupeLogWindows = yield* Ref.make< + ReadonlyMap> + >(new Map()); + const pendingInFlight = yield* Ref.make>(new Set()); + const webhookFilteredLogWindows = yield* Ref.make< + ReadonlyMap> + >(new Map()); const activeRuns = yield* Ref.make>(new Set()); - // Sliding(1) coalesces the dirty-signal: every notification triggers a - // full list() re-emit anyway, so a slow subscriber only ever needs the - // latest signal — an unbounded backlog would just grow memory. + // Notifications re-emit the full list; slow subscribers need only the newest dirty signal. const changesPubSub = yield* PubSub.sliding(1); const notifyChanged = PubSub.publish(changesPubSub, undefined).pipe(Effect.asVoid); - const selectAllRows = () => sql` + const selectAllRows = () => + sql` SELECT task_id, title, @@ -403,8 +448,10 @@ export const layer = Layer.effect( webhook_token, webhook_secret FROM scheduled_tasks - ORDER BY updated_at DESC, task_id ASC - `; + -- Not updated_at: toggles, runs and edits rewrite it, and clients render + -- this order as-is, so rows would move under the pointer. + ORDER BY created_at DESC, task_id ASC + `.pipe(NodeSqliteClient.readOnly); const listRows = Effect.fn("ScheduledTaskService.listRows")(function* () { const rows = yield* selectAllRows(); @@ -412,7 +459,8 @@ export const layer = Layer.effect( return yield* Effect.forEach(rows, (row) => decodeRow(row, origin), { concurrency: 1 }); }); - const getRows = (id: ScheduledTaskId) => sql` + const getRows = (id: ScheduledTaskId) => + sql` SELECT task_id, title, @@ -438,7 +486,7 @@ export const layer = Layer.effect( webhook_secret FROM scheduled_tasks WHERE task_id = ${id} - `; + `.pipe(NodeSqliteClient.readOnly); const findTask = Effect.fn("ScheduledTaskService.findTask")(function* (id: ScheduledTaskId) { const rows = yield* getRows(id).pipe( @@ -476,11 +524,8 @@ export const layer = Layer.effect( return task; }); - // Run-state columns (last_run_*, run_count) are intentionally absent from - // the conflict clause: they are owned by the run transitions below, and a - // concurrent settings save must not overwrite an in-flight increment. - // Check existence in the write itself so an edit cannot undo a deletion - // that landed after upsert loaded the previous task. + // Run transitions own run-state columns; settings saves must not overwrite them. + // Check existence in the write so edits cannot undo concurrent deletion. const saveTask = ( task: ScheduledTask, requireExisting: boolean, @@ -590,11 +635,12 @@ export const layer = Layer.effect( ), ); - const markRunning = (id: ScheduledTaskId, startedAtIso: string) => + const markRunning = (id: ScheduledTaskId, startedAtIso: string, webhookDeliveryId?: string) => sql<{ task_id: string }>` UPDATE scheduled_tasks SET updated_at = ${startedAtIso}, last_run_at = ${startedAtIso}, + last_run_webhook_delivery_id = ${webhookDeliveryId ?? null}, last_run_status = 'running', last_run_error = NULL WHERE task_id = ${id} @@ -632,13 +678,11 @@ export const layer = Layer.effect( ), ); - // Best-effort escape hatch: if anything fails between markRunning and - // markCompleted, write a full terminal record so runDueTasks neither skips - // the task forever (it filters out 'running' rows) nor re-fires it - // immediately: the dispatch may already have gone out, so next_run_at must - // advance and run_count must count the attempt. - const releaseStuckRun = (task: ScheduledTask, message: string) => - Effect.gen(function* () { + // A failure between markRunning and markCompleted must still write a terminal record: + // runDueTasks skips 'running' rows forever, and the dispatch may already have gone out, + // so next_run_at must advance. Pending webhook attempts count only with their completion. + const releaseStuckRun = Effect.fn("ScheduledTaskService.releaseStuckRun")( + function* (task: ScheduledTask, message: string, pendingDeliveryId?: string) { const now = yield* localNow; const reread = yield* Effect.result(findTask(task.id)); if (Result.isSuccess(reread) && reread.success === null) return; @@ -649,23 +693,33 @@ export const layer = Layer.effect( last_run_error = ${message}, next_run_at = ${nextRunAt(source, now)}, updated_at = ${iso(now)}, - run_count = run_count + 1 + run_count = run_count + CASE WHEN EXISTS ( + SELECT 1 FROM scheduled_task_webhook_pending + WHERE delivery_id = ${pendingDeliveryId ?? null} AND state = 'running' + ) THEN 0 ELSE 1 END WHERE task_id = ${task.id} AND last_run_status = 'running' `; yield* notifyChanged; - }).pipe( - Effect.catch((cause) => - Effect.logWarning("Could not release stuck schedule task run", { - taskId: task.id, - cause, - }), + }, + (effect, task, _message, _pendingDeliveryId) => + effect.pipe( + Effect.catch((cause) => + Effect.logWarning("Could not release stuck schedule task run", { + taskId: task.id, + cause, + }), + ), ), - ); + ); const runTask = Effect.fn("ScheduledTaskService.runTask")(function* ( task: ScheduledTask, trigger: "scheduled" | "manual" | "webhook", - webhook?: { readonly deliveryId: string; readonly prompt: string }, + webhook?: { + readonly deliveryId: string; + readonly prompt: string; + readonly dispatched: Ref.Ref; + }, ) { const reserved = yield* Ref.modify(activeRuns, (active) => { if (active.has(task.id)) return [false, active] as const; @@ -677,16 +731,14 @@ export const layer = Layer.effect( if (trigger !== "scheduled") { return yield* taskError("Schedule task is already running.", { taskId: task.id }); } - return task; + return { task, threadId: null }; } return yield* Effect.gen(function* () { const startedAt = yield* localNow; const startedAtIso = iso(startedAt); - // The in-memory snapshot may be stale: re-read before touching run - // state. The task may have been deleted, paused, or postponed since - // the poll loaded it — none of those may fire. + // Re-read stale poll snapshots so deleted, paused or postponed tasks cannot fire. const active = yield* findTask(task.id); if (active === null) { if (webhook !== undefined) { @@ -697,8 +749,15 @@ export const layer = Layer.effect( if (trigger !== "scheduled") { return yield* taskError("Schedule task not found.", { taskId: task.id }); } - return task; + return { task, threadId: null }; } + if ( + webhook !== undefined && + (yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId} AND state = 'completed'`.pipe( + NodeSqliteClient.readOnly, + )).length > 0 + ) + return { task: { ...active, lastRunStatus: "succeeded" as const }, threadId: null }; const parsedNextRunAt = active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt); if ( @@ -707,11 +766,9 @@ export const layer = Layer.effect( Option.isNone(parsedNextRunAt) || DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt)) ) { - return active; + return { task: active, threadId: null }; } - // A queued delivery must not run a task that was paused, deleted and - // recreated under the same id, or switched to another trigger while - // it waited for its turn. + // Reject queued deliveries after pause, same-id recreation or trigger changes. if (webhook !== undefined) { const reason = active.createdAt !== task.createdAt @@ -724,7 +781,22 @@ export const layer = Layer.effect( if (reason !== null) return yield* new WebhookDeliverySkipped({ reason }); } - yield* markRunning(active.id, startedAtIso); + if (webhook === undefined) yield* markRunning(active.id, startedAtIso); + else + yield* sql + .withTransaction( + Effect.gen(function* () { + yield* markRunning(active.id, startedAtIso, webhook.deliveryId); + // Recovery must distinguish this delivery from other windows waiting on the same task. + yield* sql`UPDATE scheduled_task_webhook_pending SET state = 'running' WHERE delivery_id = ${webhook.deliveryId}`; + }), + ) + .pipe( + Effect.mapError((cause) => + taskError("Could not start webhook run.", { taskId: task.id, cause }), + ), + ); + yield* notifyChanged; const fireKey = @@ -736,50 +808,55 @@ export const layer = Layer.effect( // A webhook prompt was rendered from the row when the request arrived. const prompt = webhook?.prompt ?? active.prompt; - // Effect.exit (not Effect.result) so defects and interruptions in the - // dispatch are also captured and recorded as a failed run instead of - // aborting before markCompleted. + // Capture defects and interrupts too so dispatch failures still reach markCompleted. const result = active.threadId === null ? yield* Effect.exit( - threadLaunch.launch({ - commandId, - projectId: active.projectId, - title: active.title, - modelSelection: active.modelSelection, - runtimeMode: active.runtimeMode, - interactionMode: active.interactionMode, - workspaceStrategy: active.workspaceStrategy, - initialMessage: { + threadLaunch + .launch({ + commandId, + projectId: active.projectId, + title: active.title, + modelSelection: active.modelSelection, + runtimeMode: active.runtimeMode, + interactionMode: active.interactionMode, + workspaceStrategy: active.workspaceStrategy, + initialMessage: { + messageId, + scheduledTaskId: active.id, + text: prompt, + attachments: [], + }, + createdBy: active.createdBy, + creationSource: active.creationSource, + }) + .pipe(Effect.map((launched) => launched.threadId)), + ) + : yield* Effect.exit( + // The stored selection only seeds fresh threads. A bound run + // follows the thread's current provider, so it passes none. + threadManagement + .sendToThread({ + projectId: active.projectId, + commandId, + threadId: ThreadId.make(active.threadId), messageId, scheduledTaskId: active.id, text: prompt, attachments: [], - }, - createdBy: active.createdBy, - creationSource: active.creationSource, - }), - ) - : yield* Effect.exit( - threadManagement.sendToThread({ - projectId: active.projectId, - commandId, - threadId: ThreadId.make(active.threadId), - messageId, - scheduledTaskId: active.id, - text: prompt, - attachments: [], - modelSelection: active.modelSelection, - mode: "queue", - createdBy: active.createdBy, - creationSource: active.creationSource, - }), + mode: "queue", + createdBy: active.createdBy, + creationSource: active.creationSource, + }) + .pipe(Effect.as(ThreadId.make(active.threadId))), ); - const completedAt = yield* localNow; const runSucceeded = result._tag === "Success"; + if (webhook !== undefined && runSucceeded) yield* Ref.set(webhook.dispatched, true); + const completedAt = yield* localNow; const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const); const lastRunError = runSucceeded ? null : errorMessage(result.cause); + const threadId = runSucceeded ? result.value : null; const current = yield* findTask(task.id); const scheduleSource = current ?? task; const completed: ScheduledTask = { @@ -795,7 +872,7 @@ export const layer = Layer.effect( // startedAtIso in the guard ensures this writes only to the row this // run marked as running — a task deleted mid-run and recreated with // the same id (idempotent commandId replay) must not be stamped. - yield* markCompleted({ + const completion = markCompleted({ id: task.id, completedAtIso: completed.updatedAt, nextRunAtIso: completed.nextRunAt, @@ -803,11 +880,32 @@ export const layer = Layer.effect( error: lastRunError, startedAtIso, }); + if (webhook === undefined) yield* completion; + else + yield* sql + .withTransaction( + Effect.gen(function* () { + const pending = + yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`; + if (pending.length === 0) yield* completion; + else { + const counted = + yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"} + WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`; + if (counted.length > 0) yield* completion; + } + }), + ) + .pipe( + Effect.mapError((cause) => + taskError("Could not record webhook completion.", { taskId: task.id, cause }), + ), + ); yield* notifyChanged; } - return completed; + return { task: completed, threadId }; }).pipe( - Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause))), + Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause), webhook?.deliveryId)), Effect.ensuring( Ref.update(activeRuns, (active) => { const next = new Set(active); @@ -865,8 +963,7 @@ export const layer = Layer.effect( ); }); - // Recover from a crash or hard shutdown mid-run: rows stuck in 'running' - // would otherwise be skipped by the due-task filter forever. + // Recover crash-left running rows that the due-task filter would otherwise skip forever. yield* Effect.gen(function* () { const rows = yield* selectAllRows(); const stuck = rows.filter((row) => row.last_run_status === "running"); @@ -884,7 +981,11 @@ export const layer = Layer.effect( last_run_error = 'Run was interrupted by a server restart.', next_run_at = ${nextRunAt(decoded.success, now)}, updated_at = ${iso(now)}, - run_count = run_count + 1 + run_count = run_count + CASE WHEN EXISTS ( + SELECT 1 FROM scheduled_task_webhook_pending + WHERE task_id IS ${row.task_id} AND state = 'running' + AND delivery_id = scheduled_tasks.last_run_webhook_delivery_id + ) THEN 0 ELSE 1 END WHERE task_id IS ${row.task_id} AND last_run_status = 'running' `; return; @@ -898,7 +999,11 @@ export const layer = Layer.effect( SET last_run_status = 'failed', last_run_error = 'Run was interrupted by a server restart.', updated_at = ${iso(now)}, - run_count = run_count + 1 + run_count = run_count + CASE WHEN EXISTS ( + SELECT 1 FROM scheduled_task_webhook_pending + WHERE task_id IS ${row.task_id} AND state = 'running' + AND delivery_id = scheduled_tasks.last_run_webhook_delivery_id + ) THEN 0 ELSE 1 END WHERE task_id IS ${row.task_id} AND last_run_status = 'running' `; }), @@ -922,8 +1027,7 @@ export const layer = Layer.effect( const subscribeList: ScheduledTaskService["Service"]["subscribeList"] = () => Stream.unwrap( Effect.gen(function* () { - // Subscribe before taking the snapshot so a change landing between - // the two is buffered by the subscription rather than dropped. + // Subscribe before reading to buffer concurrent changes. const subscription = yield* PubSub.subscribe(changesPubSub); return Stream.concat( Stream.fromEffect(list()), @@ -932,125 +1036,145 @@ export const layer = Layer.effect( }), ); - const upsert: ScheduledTaskService["Service"]["upsert"] = (input) => - Effect.gen(function* () { - const now = yield* localNow; - const uuid = - input.commandId === undefined - ? yield* crypto - .randomUUIDv4() - .pipe( - Effect.mapError((cause) => - taskError("Could not generate schedule task id.", { cause }), - ), - ) - : null; - const id = - input.id ?? - ScheduledTaskId.make( - input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`, - ); - // Look up by the *resolved* id so idempotent creates (commandId replays) - // keep their run history, and so real load failures propagate instead - // of silently resetting an existing row. - const existingTask = yield* findTask(id); - // Keep the existing next_run_at when the schedule itself is untouched: - // editing a title or prompt must not postpone (or resurrect) a due - // run — only schedule/enabled changes restart the clock. - const schedule: ScheduledTask["schedule"] = - input.schedule.type === "webhook" - ? { - type: "webhook", - signature: - input.schedule.signature == null - ? null - : { - header: input.schedule.signature.header.toLowerCase(), - encoding: input.schedule.signature.encoding, - prefix: input.schedule.signature.prefix, - }, - maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null, + const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn( + "ScheduledTaskService.upsert", + )(function* (input) { + const now = yield* localNow; + const uuid = + input.commandId === undefined + ? yield* crypto + .randomUUIDv4() + .pipe( + Effect.mapError((cause) => + taskError("Could not generate schedule task id.", { cause }), + ), + ) + : null; + const id = + input.id ?? + ScheduledTaskId.make( + input.commandId ? `scheduled-task:${input.commandId}` : `scheduled-task:${uuid}`, + ); + // Look up by the *resolved* id so idempotent creates (commandId replays) + // keep their run history, and so real load failures propagate instead + // of silently resetting an existing row. + const existingTask = yield* findTask(id); + // Keep the existing next_run_at when the schedule itself is untouched: + // editing a title or prompt must not postpone (or resurrect) a due + // run — only schedule/enabled changes restart the clock. + const schedule: ScheduledTask["schedule"] = + input.schedule.type === "webhook" + ? { + type: "webhook", + signature: + input.schedule.signature == null + ? null + : { + header: input.schedule.signature.header.toLowerCase(), + encoding: input.schedule.signature.encoding, + prefix: input.schedule.signature.prefix, + }, + maxDeliveryAgeMinutes: input.schedule.maxDeliveryAgeMinutes ?? null, + ...(input.schedule.dedupe === undefined + ? existingTask?.schedule.type === "webhook" && + existingTask.schedule.dedupe !== undefined + ? { dedupe: existingTask.schedule.dedupe } + : {} + : { dedupe: input.schedule.dedupe }), + ...webhookFilters( + // Omitted keeps the stored filters, so a client that predates + // them can re-save a task without clearing them. + input.schedule.filters ?? + (existingTask?.schedule.type === "webhook" + ? existingTask.schedule.filters + : undefined), + ), + } + : input.schedule; + const webhook = + input.schedule.type === "webhook" + ? yield* Effect.gen(function* () { + const existing = existingTask === null ? null : yield* findWebhookCredentials(id); + const token = existing?.token ?? (yield* newWebhookToken); + const signature = input.schedule.type === "webhook" ? input.schedule.signature : null; + // A secretRef is a value the user entered for an agent; this + // save consumes it, so it cannot be used again. A replay of a + // save that already used it keeps the secret that save stored. + const replay = input.commandId !== undefined && existing?.secret != null; + const fromRef = + signature?.secretRef === undefined + ? undefined + : yield* secretRequests + .consume({ ref: signature.secretRef, projectId: input.projectId }) + .pipe( + Effect.catch((error) => + replay + ? Effect.succeed(undefined) + : Effect.fail(taskError(error.message, { taskId: id })), + ), + ); + // A ref, when given, is the only source: a plain secret sent + // alongside it must not replace what a replayed save stored. + const provided = signature?.secretRef === undefined ? signature?.secret : fromRef; + const secret = signature == null ? null : (provided ?? existing?.secret ?? null); + const secretChanged = + signature == null || provided !== undefined || existing === null; + if (signature != null && secret === null) { + return yield* taskError("A webhook signature check needs a signing secret.", { + taskId: id, + }); } - : input.schedule; - const webhook = - input.schedule.type === "webhook" - ? yield* Effect.gen(function* () { - const existing = existingTask === null ? null : yield* findWebhookCredentials(id); - const token = existing?.token ?? (yield* newWebhookToken); - const signature = - input.schedule.type === "webhook" ? input.schedule.signature : null; - // A secretRef is a value the user entered for an agent; this - // save consumes it, so it cannot be used again. A replay of a - // save that already used it keeps the secret that save stored. - const replay = input.commandId !== undefined && existing?.secret != null; - const fromRef = - signature?.secretRef === undefined - ? undefined - : yield* secretRequests - .consume({ ref: signature.secretRef, projectId: input.projectId }) - .pipe( - Effect.catch((error) => - replay - ? Effect.succeed(undefined) - : Effect.fail(taskError(error.message, { taskId: id })), - ), - ); - // A ref, when given, is the only source: a plain secret sent - // alongside it must not replace what a replayed save stored. - const provided = signature?.secretRef === undefined ? signature?.secret : fromRef; - const secret = signature == null ? null : (provided ?? existing?.secret ?? null); - const secretChanged = - signature == null || provided !== undefined || existing === null; - if (signature != null && secret === null) { - return yield* taskError("A webhook signature check needs a signing secret.", { - taskId: id, - }); - } - return { token, secret, secretChanged }; - }) - : { token: null, secret: null, secretChanged: true }; - const scheduleUnchanged = - existingTask !== null && - existingTask.enabled === input.enabled && - isSameSchedule(existingTask.schedule, schedule); - const task: ScheduledTask = { - id, - title: input.title, - prompt: input.prompt, - enabled: input.enabled, - schedule, - projectId: input.projectId, - threadId: input.threadId ?? null, - workspaceStrategy: input.workspaceStrategy, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - createdBy: existingTask?.createdBy ?? input.createdBy ?? "user", - creationSource: input.creationSource ?? "web", - createdAt: existingTask?.createdAt ?? iso(now), - updatedAt: iso(now), - nextRunAt: scheduleUnchanged - ? existingTask.nextRunAt - : nextRunAt({ enabled: input.enabled, schedule }, now), - lastRunAt: existingTask?.lastRunAt ?? null, - lastRunStatus: existingTask?.lastRunStatus ?? "never", - lastRunError: existingTask?.lastRunError ?? null, - runCount: existingTask?.runCount ?? 0, - }; - yield* saveTask(task, input.requireExisting === true, webhook); - yield* notifyChanged; - return { task: (yield* findTask(id)) ?? task }; - }); + return { token, secret, secretChanged }; + }) + : { token: null, secret: null, secretChanged: true }; + const workspaceStrategy: ScheduledTask["workspaceStrategy"] = + input.workspaceStrategy.type === "worktree" && + (yield* managedFolders.isScratchProject(input.projectId)) + ? { type: "root" } + : input.workspaceStrategy; + const scheduleUnchanged = + existingTask !== null && + existingTask.enabled === input.enabled && + isSameSchedule(existingTask.schedule, schedule); + const task: ScheduledTask = { + id, + title: input.title, + prompt: input.prompt, + enabled: input.enabled, + schedule, + projectId: input.projectId, + threadId: input.threadId ?? null, + workspaceStrategy, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + createdBy: existingTask?.createdBy ?? input.createdBy ?? "user", + creationSource: input.creationSource ?? "web", + createdAt: existingTask?.createdAt ?? iso(now), + updatedAt: iso(now), + nextRunAt: scheduleUnchanged + ? existingTask.nextRunAt + : nextRunAt({ enabled: input.enabled, schedule }, now), + lastRunAt: existingTask?.lastRunAt ?? null, + lastRunStatus: existingTask?.lastRunStatus ?? "never", + lastRunError: existingTask?.lastRunError ?? null, + runCount: existingTask?.runCount ?? 0, + }; + yield* saveTask(task, input.requireExisting === true, webhook); + yield* notifyChanged; + return { task: (yield* findTask(id)) ?? task }; + }); - const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = (input) => - Effect.gen(function* () { - const existing = yield* loadTask(input.id); - if (existing.enabled === input.enabled) return { task: existing }; - const now = yield* localNow; - const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now); - // RETURNING so a task deleted between the load and this UPDATE is a - // visible not-found error, not a false success. - const updated = yield* sql<{ task_id: string }>` + const setEnabled: ScheduledTaskService["Service"]["setEnabled"] = Effect.fn( + "ScheduledTaskService.setEnabled", + )(function* (input) { + const existing = yield* loadTask(input.id); + if (existing.enabled === input.enabled) return { task: existing }; + const now = yield* localNow; + const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now); + // RETURNING so a task deleted between the load and this UPDATE is a + // visible not-found error, not a false success. + const updated = yield* sql<{ task_id: string }>` UPDATE scheduled_tasks SET enabled = ${input.enabled ? 1 : 0}, next_run_at = ${next}, @@ -1058,81 +1182,129 @@ export const layer = Layer.effect( WHERE task_id = ${input.id} RETURNING task_id `.pipe( - Effect.mapError((cause) => - taskError("Could not update schedule task.", { taskId: input.id, cause }), - ), - ); - if (updated.length === 0) { - return yield* taskError("Schedule task not found.", { taskId: input.id }); - } - yield* notifyChanged; - return { - task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) }, - }; - }); + Effect.mapError((cause) => + taskError("Could not update schedule task.", { taskId: input.id, cause }), + ), + ); + if (updated.length === 0) { + return yield* taskError("Schedule task not found.", { taskId: input.id }); + } + yield* notifyChanged; + return { + task: { ...existing, enabled: input.enabled, nextRunAt: next, updatedAt: iso(now) }, + }; + }); + + const forgetWebhookTask = (id: ScheduledTaskId) => + Effect.all( + [ + Ref.update(webhookRateWindows, (windows) => { + const next = new Map(windows); + next.delete(id); + return next; + }), + Ref.update(webhookRejectedRateWindows, (windows) => { + const next = new Map(windows); + next.delete(id); + return next; + }), + Ref.update(webhookDedupeLogWindows, (windows) => { + const next = new Map(windows); + next.delete(id); + return next; + }), + Ref.update(webhookFilteredLogWindows, (windows) => { + const next = new Map(windows); + next.delete(id); + return next; + }), + Ref.update(webhookPermits, (permits) => { + const next = new Map(permits); + next.delete(id); + return next; + }), + ], + { discard: true }, + ); const deleteTask: ScheduledTaskService["Service"]["delete"] = (input) => deleteRow(input.id).pipe( - Effect.andThen( - Effect.all([ - Ref.update(webhookRateWindows, (windows) => { - const next = new Map(windows); - next.delete(input.id); - return next; - }), - Ref.update(webhookPermits, (permits) => { - const next = new Map(permits); - next.delete(input.id); - return next; - }), - ]), - ), + Effect.andThen(forgetWebhookTask(input.id)), Effect.andThen(notifyChanged), Effect.as({ id: input.id }), ); - const runNow: ScheduledTaskService["Service"]["runNow"] = (input: ScheduledTaskRunNowInput) => - Effect.gen(function* () { - const task = yield* loadTask(input.id); - if (task.schedule.type === "webhook") { - return yield* taskError("Webhook tasks run when their URL receives a request.", { - taskId: input.id, - }); - } - const next = yield* runTask(task, "manual").pipe( + const deleteForThread = Effect.fn("ScheduledTaskService.deleteForThread")(function* ( + threadId: ThreadId, + ) { + // Check the current binding in the transaction: an automation may have + // been unbound or moved since thread deletion queued this cleanup. + const removed = yield* sql + .withTransaction( + Effect.gen(function* () { + yield* sql` + DELETE FROM scheduled_task_webhook_deliveries + WHERE task_id IN (SELECT task_id FROM scheduled_tasks WHERE thread_id = ${threadId}) + `; + return yield* sql<{ task_id: ScheduledTaskId }>` + DELETE FROM scheduled_tasks WHERE thread_id = ${threadId} RETURNING task_id + `; + }), + ) + .pipe( Effect.mapError((cause) => - taskError("Could not run schedule task.", { taskId: input.id, cause }), + taskError("Could not delete thread's schedule tasks.", { cause }), ), ); - return { task: next }; + yield* Effect.forEach(removed, ({ task_id }) => forgetWebhookTask(task_id), { + discard: true, }); + if (removed.length > 0) yield* notifyChanged; + }); - const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = (input) => - Effect.gen(function* () { - const task = yield* loadTask(input.id); - if (task.schedule.type !== "webhook") { - return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id }); - } - const token = yield* newWebhookToken; - const now = yield* localNow; - // Matching created_at keeps a rotation from landing on a task deleted - // and recreated under the same id since it was loaded. - const updated = yield* sql<{ task_id: string }>` + const runNow: ScheduledTaskService["Service"]["runNow"] = Effect.fn( + "ScheduledTaskService.runNow", + )(function* (input: ScheduledTaskRunNowInput) { + const task = yield* loadTask(input.id); + if (task.schedule.type === "webhook") { + return yield* taskError("Webhook tasks run when their URL receives a request.", { + taskId: input.id, + }); + } + return yield* runTask(task, "manual").pipe( + Effect.mapError((cause) => + taskError("Could not run schedule task.", { taskId: input.id, cause }), + ), + ); + }); + + const rotateWebhookToken: ScheduledTaskService["Service"]["rotateWebhookToken"] = Effect.fn( + "ScheduledTaskService.rotateWebhookToken", + )(function* (input) { + const task = yield* loadTask(input.id); + if (task.schedule.type !== "webhook") { + return yield* taskError("Only webhook tasks have a URL token.", { taskId: input.id }); + } + const token = yield* newWebhookToken; + const now = yield* localNow; + // Matching created_at keeps a rotation from landing on a task deleted + // and recreated under the same id since it was loaded. + const updated = yield* sql<{ task_id: string }>` UPDATE scheduled_tasks SET webhook_token = ${token}, updated_at = ${iso(now)} WHERE task_id = ${input.id} AND created_at = ${task.createdAt} RETURNING task_id `.pipe( - Effect.mapError((cause) => - taskError("Could not rotate webhook token.", { taskId: input.id, cause }), - ), - ); - if (updated.length === 0) { - return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id }); - } - yield* notifyChanged; - return { task: yield* loadTask(input.id) }; - }); + Effect.mapError((cause) => + taskError("Could not rotate webhook token.", { taskId: input.id, cause }), + ), + ); + if (updated.length === 0) { + return yield* taskError("Schedule task was deleted or replaced.", { taskId: input.id }); + } + yield* notifyChanged; + return { task: yield* loadTask(input.id) }; + }); const deliveryHeaders = (row: WebhookDeliveryRow): Readonly> => Option.getOrElse(decodeHeadersJson(row.headers_json), () => ({})); @@ -1145,6 +1317,7 @@ export const layer = Layer.effect( bodyBytes: row.body_bytes, outcome: row.outcome as ScheduledTaskWebhookDeliveryOutcome, signatureVerified: row.signature_verified === 1, + pendingWindow: row.outcome === "accepted" && row.pending_window === 1, missingFields: Option.getOrElse(decodeMissingFieldsJson(row.missing_fields_json), () => []), error: row.error, }); @@ -1153,41 +1326,73 @@ export const layer = Layer.effect( input, ) => sql` - SELECT * FROM scheduled_task_webhook_deliveries - WHERE task_id = ${input.id} + SELECT d.*, EXISTS (SELECT 1 FROM scheduled_task_webhook_pending p + WHERE p.delivery_id = d.delivery_id AND p.state IN ('pending', 'dispatching')) AS pending_window + FROM scheduled_task_webhook_deliveries d WHERE task_id = ${input.id} ORDER BY received_at DESC, rowid DESC `.pipe( - Effect.map((rows) => ({ deliveries: rows.map(decodeDeliverySummary) })), + NodeSqliteClient.readOnly, + Effect.map((rows) => ({ + deliveries: rows + .filter( + (row) => input.acceptAnyOutcome === true || LEGACY_DELIVERY_OUTCOMES.has(row.outcome), + ) + .map(decodeDeliverySummary), + })), Effect.mapError((cause) => taskError("Could not list webhook deliveries.", { taskId: input.id, cause }), ), ); - const getWebhookDelivery: ScheduledTaskService["Service"]["getWebhookDelivery"] = (input) => - Effect.gen(function* () { - const rows = yield* sql` - SELECT * FROM scheduled_task_webhook_deliveries - WHERE task_id = ${input.id} AND delivery_id = ${input.deliveryId} + const getWebhookDelivery: ScheduledTaskService["Service"]["getWebhookDelivery"] = Effect.fn( + "ScheduledTaskService.getWebhookDelivery", + )(function* (input) { + const rows = yield* sql` + SELECT d.*, EXISTS (SELECT 1 FROM scheduled_task_webhook_pending p + WHERE p.delivery_id = d.delivery_id AND p.state IN ('pending', 'dispatching')) AS pending_window + FROM scheduled_task_webhook_deliveries d WHERE task_id = ${input.id} AND delivery_id = ${input.deliveryId} `.pipe( - Effect.mapError((cause) => - taskError("Could not load webhook delivery.", { taskId: input.id, cause }), - ), - ); - const row = rows[0]; - if (row === undefined) { - return yield* taskError("Webhook delivery not found.", { taskId: input.id }); - } - return { - delivery: { - ...decodeDeliverySummary(row), - query: row.query, - headers: deliveryHeaders(row), - body: row.body, - bodyTruncated: row.body_truncated === 1, - renderedPrompt: row.rendered_prompt, - }, - }; - }); + NodeSqliteClient.readOnly, + Effect.mapError((cause) => + taskError("Could not load webhook delivery.", { taskId: input.id, cause }), + ), + ); + const row = rows[0]; + if ( + row === undefined || + (input.acceptAnyOutcome !== true && !LEGACY_DELIVERY_OUTCOMES.has(row.outcome)) + ) { + return yield* taskError("Webhook delivery not found.", { taskId: input.id }); + } + return { + delivery: { + ...decodeDeliverySummary(row), + query: row.query, + headers: deliveryHeaders(row), + body: row.body, + bodyTruncated: row.body_truncated === 1, + renderedPrompt: row.rendered_prompt, + }, + }; + }); + + const deliveryRequestBody = (request: WebhookTriggerRequest) => { + const truncated = request.body.byteLength > WEBHOOK_DELIVERY_LOG_BODY_LIMIT; + return { + truncated, + body: truncated + ? new TextDecoder().decode(request.body.subarray(0, WEBHOOK_DELIVERY_LOG_BODY_LIMIT)) + : request.bodyText, + }; + }; + const replaceDeliveryRequest = (deliveryId: string, request: WebhookTriggerRequest) => { + const logged = deliveryRequestBody(request); + return sql`UPDATE scheduled_task_webhook_deliveries SET + method = ${request.method}, query = ${redactQuery(request.query)}, + headers_json = ${encodeHeadersJson(redactHeaders(request.headers))}, body = ${logged.body}, + body_bytes = ${request.body.byteLength}, body_truncated = ${logged.truncated ? 1 : 0} + WHERE delivery_id = ${deliveryId}`.pipe(Effect.asVoid, Effect.mapError(dedupeError)); + }; const recordDelivery = (input: { readonly id: string; @@ -1200,15 +1405,11 @@ export const layer = Layer.effect( readonly renderedPrompt: string | null; readonly error?: string; }) => { - const truncated = input.request.body.byteLength > WEBHOOK_DELIVERY_LOG_BODY_LIMIT; - const loggedBody = truncated - ? new TextDecoder().decode(input.request.body.subarray(0, WEBHOOK_DELIVERY_LOG_BODY_LIMIT)) - : input.request.bodyText; + const { truncated, body: loggedBody } = deliveryRequestBody(input.request); return sql .withTransaction( Effect.gen(function* () { - // Conditional on the task existing, so a delivery racing a delete - // cannot leave rows that a recreated task with the same id would show. + // Require the task to exist so deletes cannot leave deliveries for a recreated task. yield* sql` INSERT INTO scheduled_task_webhook_deliveries ( delivery_id, task_id, received_at, method, query, headers_json, body, @@ -1234,15 +1435,28 @@ export const layer = Layer.effect( rendered_prompt = excluded.rendered_prompt, error = excluded.error `; + // Each suppression bucket retains its own rows, never real run history. + const bucket = (outcome: string, error: string | undefined) => + outcome === "filtered" + ? "filtered" + : outcome === "duplicate" || + outcome === "coalesced" || + outcome === "rate_limited" || + error === PROMPT_TOO_LONG + ? "dedupe" + : "main"; + const retentionBucket = bucket(input.outcome, input.error); + const rowBucket = sql.literal(`CASE WHEN outcome = 'filtered' THEN 'filtered' + WHEN outcome IN ('duplicate', 'coalesced', 'rate_limited') OR error = 'The filled-in prompt is too long.' THEN 'dedupe' + ELSE 'main' END`); yield* sql` DELETE FROM scheduled_task_webhook_deliveries - WHERE task_id = ${input.taskId} + WHERE task_id = ${input.taskId} AND ${rowBucket} = ${retentionBucket} AND delivery_id NOT IN ( SELECT delivery_id FROM scheduled_task_webhook_deliveries - WHERE task_id = ${input.taskId} - -- rowid breaks timestamp ties in arrival order; delivery ids are random. + WHERE task_id = ${input.taskId} AND ${rowBucket} = ${retentionBucket} ORDER BY received_at DESC, rowid DESC - LIMIT ${WEBHOOK_DELIVERY_RETENTION} + LIMIT ${retentionBucket === "main" ? WEBHOOK_DELIVERY_RETENTION : retentionBucket === "filtered" ? WEBHOOK_FILTERED_DELIVERY_RETENTION : WEBHOOK_DEDUPE_DELIVERY_RETENTION} ) `; }), @@ -1261,13 +1475,15 @@ export const layer = Layer.effect( WHERE delivery_id = ${deliveryId} `.pipe(Effect.ignore); - /** - * Sliding one-minute window counting every request with a valid token, - * including ones the signature check later rejects. - */ - const takeRateSlot = (id: ScheduledTaskId, nowMs: number) => + /** Sliding one-minute window for deliveries that can start work. */ + const takeRateSlot = ( + id: ScheduledTaskId, + nowMs: number, + rateWindows = webhookRateWindows, + reservation = { at: nowMs }, + ) => Ref.modify( - webhookRateWindows, + rateWindows, ( windows, ): readonly [ @@ -1275,7 +1491,7 @@ export const layer = Layer.effect( ReadonlyMap, ] => { const current = windows.get(id); - const recent = (current?.accepted ?? []).filter((at) => nowMs - at < 60_000); + const recent = (current?.accepted ?? []).filter((entry) => nowMs - entry.at < 60_000); if (recent.length >= WEBHOOK_RATE_LIMIT_PER_MINUTE) { const first = current?.rejectedLogged !== true; return [ @@ -1285,48 +1501,150 @@ export const layer = Layer.effect( } return [ "allowed", - new Map(windows).set(id, { accepted: [...recent, nowMs], rejectedLogged: false }), + new Map(windows).set(id, { accepted: [...recent, reservation], rejectedLogged: false }), ]; }, ); - const webhookPermit = (id: ScheduledTaskId) => - Effect.gen(function* () { - const existing = (yield* Ref.get(webhookPermits)).get(id); - if (existing !== undefined) return existing; - const created = yield* Semaphore.make(1); - return yield* Ref.modify(webhookPermits, (permits) => { - const raced = permits.get(id); - return raced === undefined - ? [created, new Map(permits).set(id, created)] - : [raced, permits]; - }); + const takeDedupeLogSlot = (id: ScheduledTaskId, nowMs: number) => + Ref.modify(webhookDedupeLogWindows, (windows) => { + const recent = (windows.get(id) ?? []).filter((at) => nowMs - at < 60_000); + return recent.length >= WEBHOOK_DEDUPE_LOG_PER_MINUTE + ? ([false, windows] as const) + : ([true, new Map(windows).set(id, [...recent, nowMs])] as const); }); + const releaseReplay = (deliveryId: string) => + releaseWebhookReplay(deliveryId).pipe( + Effect.provideService(SqlClient.SqlClient, sql), + Effect.mapError(dedupeError), + ); + /** Sliding one-minute window of filtered requests written to the delivery log. */ + const takeFilteredLogSlot = (id: ScheduledTaskId, nowMs: number) => + Ref.modify( + webhookFilteredLogWindows, + (windows): readonly [boolean, ReadonlyMap>] => { + const recent = (windows.get(id) ?? []).filter((at) => nowMs - at < 60_000); + return recent.length >= WEBHOOK_FILTERED_LOG_PER_MINUTE + ? [false, windows] + : [true, new Map(windows).set(id, [...recent, nowMs])]; + }, + ); + + const webhookPermit = Effect.fn("ScheduledTaskService.webhookPermit")(function* ( + id: ScheduledTaskId, + ) { + const existing = (yield* Ref.get(webhookPermits)).get(id); + if (existing !== undefined) return existing; + const created = yield* Semaphore.make(1); + return yield* Ref.modify(webhookPermits, (permits) => { + const raced = permits.get(id); + return raced === undefined + ? [created, new Map(permits).set(id, created)] + : [raced, permits]; + }); + }); const serviceScope = yield* Effect.scope; - const observeDelivery = ( + const releaseFailedDelivery = Effect.fn("ScheduledTaskService.releaseFailedDelivery")( + function* (deliveryId: string) { + yield* releaseReplay(deliveryId); + yield* sql`DELETE FROM scheduled_task_webhook_relay_deliveries WHERE relay_delivery_id IN ( + SELECT substr(value, ${"delivery:relay:".length + 1}) FROM scheduled_task_webhook_pending, json_each(delivery_ids_json) + WHERE delivery_id = ${deliveryId} AND value LIKE 'delivery:relay:%' + )`.pipe(Effect.mapError(dedupeError)); + if (deliveryId.startsWith("delivery:relay:")) + yield* sql`DELETE FROM scheduled_task_webhook_relay_deliveries WHERE relay_delivery_id = ${deliveryId.slice("delivery:relay:".length)}`.pipe( + Effect.mapError(dedupeError), + ); + }, + (effect) => sql.withTransaction(effect).pipe(Effect.mapError(dedupeError)), + ); + + const runWebhookDelivery = Effect.fn("ScheduledTaskService.runWebhookDelivery")(function* ( + task: ScheduledTask, + deliveryId: string, + prompt: string, + ) { + const runOutcome = (outcome: "started" | "skipped" | "failed") => + Effect.all([ + Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }), + Metrics.increment(Metrics.webhookRunsTotal, { outcome }), + ]); + const dispatched = yield* Ref.make(false); + return yield* runTask(task, "webhook", { deliveryId, prompt, dispatched }).pipe( + Effect.flatMap(({ task: completed }) => + completed.lastRunStatus === "failed" + ? runOutcome("failed").pipe( + Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")), + Effect.andThen(releaseFailedDelivery(deliveryId)), + ) + : runOutcome("started"), + ), + Effect.catchTags({ + WebhookDeliverySkipped: (skipped) => + runOutcome("skipped").pipe( + Effect.andThen(markDeliveryFailed(deliveryId, skipped.reason)), + Effect.andThen(releaseFailedDelivery(deliveryId)), + ), + }), + Effect.as(true), + // Dispatch success owns the replay key even if later bookkeeping fails. + Effect.catchCause((cause) => + Effect.gen(function* () { + const started = yield* Ref.get(dispatched); + yield* Effect.logWarning("Webhook dispatch failed", { taskId: task.id, cause }); + yield* runOutcome(started ? "started" : "failed"); + yield* markDeliveryFailed( + deliveryId, + started + ? "The run started, but completion could not be recorded." + : "The run failed to start.", + ); + if (!started) { + yield* sql + .withTransaction( + Effect.gen(function* () { + const counted = + yield* sql`UPDATE scheduled_task_webhook_pending SET state = 'failed' + WHERE delivery_id = ${deliveryId} AND state = 'running' RETURNING delivery_id`; + if (counted.length > 0) + yield* sql`UPDATE scheduled_tasks SET run_count = run_count + 1 + WHERE task_id = ${task.id} AND created_at = ${task.createdAt}`; + }), + ) + .pipe(Effect.mapError(dedupeError)); + yield* releaseFailedDelivery(deliveryId); + } + // Pending windows retry the same command id to finish bookkeeping. + return !started; + }), + ), + ); + }); + + // Delivery attributes belong to the enclosing triggerWebhook span. + const observeDelivery = Effect.fnUntraced(function* ( request: WebhookTriggerRequest, outcome: WebhookDeliveryOutcome, receivedAt: DateTime.DateTime | undefined, now: DateTime.DateTime | undefined, - ) => - Effect.gen(function* () { - const source = request.relayDeliveryId === undefined ? "direct" : "relay"; - yield* Effect.annotateCurrentSpan({ - "scheduled_task.webhook.outcome": outcome, - "scheduled_task.webhook.source": source, - }); - yield* Metrics.increment(Metrics.webhookDeliveriesTotal, { outcome, source }); - if (request.receivedAt !== undefined && receivedAt !== undefined && now !== undefined) { - const heldMs = Math.max( - 0, - DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt), - ); - yield* Effect.annotateCurrentSpan({ "scheduled_task.webhook.held_ms": heldMs }); - yield* Metric.update(Metrics.webhookHeldDelay, Duration.millis(heldMs)); - } + ) { + const source = request.relayDeliveryId === undefined ? "direct" : "relay"; + yield* Effect.annotateCurrentSpan({ + "scheduled_task.webhook.outcome": outcome, + "scheduled_task.webhook.source": source, }); + yield* Metrics.increment(Metrics.webhookDeliveriesTotal, { outcome, source }); + if (request.receivedAt !== undefined && receivedAt !== undefined && now !== undefined) { + const heldMs = Math.max( + 0, + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt), + ); + yield* Effect.annotateCurrentSpan({ "scheduled_task.webhook.held_ms": heldMs }); + yield* Metric.update(Metrics.webhookHeldDelay, Duration.millis(heldMs)); + } + }); const triggerWebhook: ScheduledTaskService["Service"]["triggerWebhook"] = (request) => triggerWebhookUnobserved(request).pipe( @@ -1342,248 +1660,476 @@ export const layer = Layer.effect( }), ); - const triggerWebhookUnobserved = (request: WebhookTriggerRequest) => - Effect.gen(function* () { - const taskId = decodeTaskId(request.hookId); - const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe( - Effect.as({ _tag: "not_found" as const }), - ); - if (Option.isNone(taskId)) return yield* notFound; - const rows = yield* getRows(taskId.value).pipe( - Effect.mapError((cause) => - taskError("Could not load schedule task.", { taskId: taskId.value, cause }), - ), - ); - const row = rows[0]; - // A wrong token is indistinguishable from an unknown hook, so the URL - // does not reveal which hooks exist. - if ( - row === undefined || - row.webhook_token === null || - !constantTimeEquals(request.token, row.webhook_token) - ) { - return yield* notFound; - } - const task = yield* decodeRow(row); - yield* Effect.annotateCurrentSpan({ "scheduled_task.id": task.id }); - const schedule = task.schedule; - if (schedule.type !== "webhook") return yield* notFound; + // triggerWebhook owns the operation span and its task-id annotation. + const triggerWebhookUnobserved = Effect.fnUntraced(function* (request: WebhookTriggerRequest) { + const taskId = decodeTaskId(request.hookId); + const notFound = observeDelivery(request, "not_found", undefined, undefined).pipe( + Effect.as({ _tag: "not_found" as const }), + ); + if (Option.isNone(taskId)) return yield* notFound; + const rows = yield* getRows(taskId.value).pipe( + Effect.mapError((cause) => + taskError("Could not load schedule task.", { taskId: taskId.value, cause }), + ), + ); + const row = rows[0]; + // A wrong token is indistinguishable from an unknown hook, so the URL + // does not reveal which hooks exist. + if ( + row === undefined || + row.webhook_token === null || + !constantTimeEquals(request.token, row.webhook_token) + ) { + return yield* notFound; + } + const task = yield* decodeRow(row); + yield* Effect.annotateCurrentSpan({ "scheduled_task.id": task.id }); + const schedule = task.schedule; + if (schedule.type !== "webhook") return yield* notFound; - const now = yield* localNow; - // Anyone can reach the tunnel directly and set the relay's header, so - // a receive time is never later than now: a future one would pin the - // delivery in the log and slip past the task's max age. - const receivedAt = - request.receivedAt === undefined - ? now - : DateTime.min( - Option.getOrElse(DateTime.make(request.receivedAt), () => now), - now, - ); - const observe = (outcome: WebhookDeliveryOutcome) => - observeDelivery(request, outcome, receivedAt, now); - const deliveryId = ScheduledTaskWebhookDeliveryId.make( - request.relayDeliveryId === undefined - ? `delivery:${yield* crypto - .randomUUIDv4() - .pipe( - Effect.mapError((cause) => - taskError("Could not generate delivery id.", { cause }), - ), - )}` - : `delivery:relay:${request.relayDeliveryId}`, - ); - // Claimed in its own table, kept longer than the relay holds a request, - // because the delivery log is trimmed. A rate-limited delivery stays - // held on the relay, so it must give up its claim or the next pass - // would treat it as already delivered. - const releaseClaim = (result: A) => - request.relayDeliveryId === undefined - ? Effect.succeed(result) - : sql` + const now = yield* localNow; + // Anyone can reach the tunnel directly and set the relay's header, so + // a receive time is never later than now: a future one would pin the + // delivery in the log and slip past the task's max age. + const receivedAt = + request.receivedAt === undefined + ? now + : DateTime.min( + Option.getOrElse(DateTime.make(request.receivedAt), () => now), + now, + ); + const observe = (outcome: WebhookDeliveryOutcome) => + observeDelivery(request, outcome, receivedAt, now); + const deliveryId = ScheduledTaskWebhookDeliveryId.make( + request.relayDeliveryId === undefined + ? `delivery:${yield* crypto + .randomUUIDv4() + .pipe( + Effect.mapError((cause) => taskError("Could not generate delivery id.", { cause })), + )}` + : `delivery:relay:${request.relayDeliveryId}`, + ); + // Claimed in its own table, kept longer than the relay holds a request, + // because the delivery log is trimmed. A rate-limited delivery stays + // held on the relay, so it must give up its claim or the next pass + // would treat it as already delivered. + let claimAcquired = false; + const releaseClaim = (result: A) => + !claimAcquired || request.relayDeliveryId === undefined + ? Effect.succeed(result) + : sql` DELETE FROM scheduled_task_webhook_relay_deliveries WHERE relay_delivery_id = ${request.relayDeliveryId} `.pipe(Effect.ignore, Effect.as(result)); - // From the claim until the run is forked nothing may interrupt: a - // request dropped in between (the relay hangs up after its timeout) - // would leave a claimed delivery that never runs, or a queue slot that - // is never released. - return yield* Effect.uninterruptible( - Effect.gen(function* () { - if (request.relayDeliveryId !== undefined) { - const claimed = yield* sql<{ relay_delivery_id: string }>` + // From the claim until the run is forked nothing may interrupt: a + // request dropped in between (the relay hangs up after its timeout) + // would leave a claimed delivery that never runs, or a queue slot that + // is never released. + return yield* Effect.uninterruptible( + Effect.gen(function* () { + if (request.relayDeliveryId !== undefined) { + const claimed = yield* sql<{ relay_delivery_id: string }>` INSERT INTO scheduled_task_webhook_relay_deliveries (relay_delivery_id, task_id, seen_at) VALUES (${request.relayDeliveryId}, ${task.id}, ${iso(now)}) ON CONFLICT (relay_delivery_id) DO NOTHING RETURNING relay_delivery_id `.pipe( - Effect.mapError((cause) => - taskError("Could not record webhook delivery.", { taskId: task.id, cause }), - ), - ); - if (claimed.length === 0) { - yield* observe("duplicate"); - return { _tag: "accepted" as const, deliveryId, outcome: "duplicate" as const }; - } - yield* sql` + Effect.mapError((cause) => + taskError("Could not record webhook delivery.", { taskId: task.id, cause }), + ), + ); + if (claimed.length === 0) { + yield* observe("duplicate"); + return { _tag: "accepted" as const, deliveryId, outcome: "duplicate" as const }; + } + claimAcquired = true; + yield* sql` DELETE FROM scheduled_task_webhook_relay_deliveries WHERE seen_at < ${iso(DateTime.subtract(now, { hours: 48 }))} `.pipe(Effect.ignore); - } - const log = ( - outcome: ScheduledTaskWebhookDeliveryOutcome, - details: { - readonly signatureVerified?: boolean; - readonly missing?: ReadonlyArray; - readonly renderedPrompt?: string; - readonly error?: string; - } = {}, - ) => - recordDelivery({ - id: deliveryId, - taskId: task.id, - receivedAt: iso(receivedAt), - request, - outcome, - signatureVerified: details.signatureVerified ?? false, - missing: details.missing ?? [], - renderedPrompt: details.renderedPrompt ?? null, - ...(details.error === undefined ? {} : { error: details.error }), - }); + } + const log = ( + outcome: ScheduledTaskWebhookDeliveryOutcome, + details: { + readonly signatureVerified?: boolean; + readonly missing?: ReadonlyArray; + readonly renderedPrompt?: string; + readonly error?: string; + } = {}, + ) => + recordDelivery({ + id: deliveryId, + taskId: task.id, + receivedAt: iso(receivedAt), + request, + outcome, + signatureVerified: details.signatureVerified ?? false, + missing: details.missing ?? [], + renderedPrompt: details.renderedPrompt ?? null, + ...(details.error === undefined ? {} : { error: details.error }), + }); - // Only the first rejected request in a window is logged, so a flood - // cannot write rows or push the real deliveries out of the log. - const slot = yield* takeRateSlot(task.id, DateTime.toEpochMillis(now)); - if (slot !== "allowed") { - if (slot === "first_rejected") yield* log("rate_limited"); - yield* observe("rate_limited"); - return yield* releaseClaim({ - _tag: "rate_limited" as const, - outcome: "rate_limited" as const, + // Reject floods before signature work or rejection-log writes; valid + // deliveries give this reservation back once validation succeeds. + const rejectionReservation = { at: DateTime.toEpochMillis(now) }; + const rejectionSlot = yield* takeRateSlot( + task.id, + DateTime.toEpochMillis(now), + webhookRejectedRateWindows, + rejectionReservation, + ); + if (rejectionSlot !== "allowed") { + if (rejectionSlot === "first_rejected") yield* log("rate_limited"); + yield* observe("rate_limited"); + return yield* releaseClaim({ _tag: "rate_limited", outcome: "rate_limited" } as const); + } + if (!task.enabled) { + yield* log("disabled"); + yield* observe("disabled"); + return { _tag: "disabled" as const }; + } + const signature = schedule.signature; + if (signature !== null) { + const verified = + row.webhook_secret !== null && + verifyWebhookSignature({ + signature, + secret: row.webhook_secret, + headers: request.headers, + body: request.body, }); + if (!verified) { + yield* log("rejected_signature"); + yield* observe("rejected_signature"); + return { _tag: "rejected_signature" as const }; } - if (!task.enabled) { - yield* log("disabled"); - yield* observe("disabled"); - return { _tag: "disabled" as const }; - } - const signature = schedule.signature; - if (signature !== null) { - const verified = - row.webhook_secret !== null && - verifyWebhookSignature({ - signature, - secret: row.webhook_secret, - headers: request.headers, - body: request.body, - }); - if (!verified) { - yield* log("rejected_signature"); - yield* observe("rejected_signature"); - return { _tag: "rejected_signature" as const }; - } - } - const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null; - if ( - maxAgeMinutes !== null && - DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) > - maxAgeMinutes * 60_000 - ) { - yield* log("expired", { signatureVerified: signature !== null }); - yield* observe("expired"); - return { _tag: "expired" as const }; - } + } + const maxAgeMinutes = schedule.maxDeliveryAgeMinutes ?? null; + if ( + maxAgeMinutes !== null && + DateTime.toEpochMillis(now) - DateTime.toEpochMillis(receivedAt) > + maxAgeMinutes * 60_000 + ) { + yield* log("expired", { signatureVerified: signature !== null }); + yield* observe("expired"); + return { _tag: "expired" as const }; + } - const frameId = yield* crypto.randomBytes(6).pipe( - Effect.map((bytes) => Buffer.from(bytes).toString("hex")), - Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })), - ); - const rendered = renderWebhookPrompt(task.prompt, request, frameId); - // Providers trim the prompt before checking, so whitespace around - // it is free. - if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { - yield* log("dispatch_failed", { + const refundRejectionSlot = Ref.update(webhookRejectedRateWindows, (windows) => { + const current = windows.get(task.id); + if (current === undefined) return windows; + return new Map(windows).set(task.id, { + ...current, + accepted: current.accepted.filter((entry) => entry !== rejectionReservation), + }); + }); + + const failedFilter = findFailedWebhookFilter(schedule.filters ?? [], request); + if (failedFilter !== null) { + if (yield* takeFilteredLogSlot(task.id, DateTime.toEpochMillis(now))) { + yield* log("filtered", { signatureVerified: signature !== null, - missing: rendered.missing, - renderedPrompt: rendered.prompt, - error: "The filled-in prompt is too long.", + error: describeFailedWebhookFilter(failedFilter), }); - yield* observe("prompt_too_long"); - return { _tag: "accepted" as const, deliveryId, outcome: "prompt_too_long" as const }; } - // Bound the deliveries one task holds, so steady traffic to a stuck - // task cannot pile up parked fibers. - const queueKey = `${task.id}\u0000${task.createdAt}`; - const queued = yield* Ref.modify(webhookQueued, (counts) => { - const count = counts.get(queueKey) ?? 0; - return count >= WEBHOOK_MAX_QUEUED_PER_TASK - ? ([false, counts] as const) - : ([true, new Map(counts).set(queueKey, count + 1)] as const); + yield* refundRejectionSlot; + yield* observe("filtered"); + return yield* releaseClaim({ + _tag: "accepted" as const, + deliveryId, + outcome: "filtered" as const, }); - if (!queued) { - yield* observe("queue_full"); - return yield* releaseClaim({ - _tag: "rate_limited" as const, - outcome: "queue_full" as const, - }); - } - const release = Ref.update(webhookQueued, (counts) => { + } + + const runWindow = (yield* Ref.get(webhookRateWindows)).get(task.id); + if ( + schedule.dedupe === undefined && + (runWindow?.accepted.filter((entry) => DateTime.toEpochMillis(now) - entry.at < 60_000) + .length ?? 0) >= WEBHOOK_RATE_LIMIT_PER_MINUTE + ) { + if ((yield* takeRateSlot(task.id, DateTime.toEpochMillis(now))) === "first_rejected") + yield* log("rate_limited"); + yield* observe("rate_limited"); + return yield* releaseClaim({ _tag: "rate_limited", outcome: "rate_limited" } as const); + } + const reserve = takeRateSlot(task.id, DateTime.toEpochMillis(now)).pipe( + Effect.flatMap((slot) => (slot === "allowed" ? Effect.void : Effect.fail(slot))), + ); + const queueKey = `${task.id}\u0000${task.createdAt}`; + const checkCapacity = Effect.gen(function* () { + const [row] = yield* sql<{ + count: number; + }>`SELECT COUNT(*) AS count FROM scheduled_task_webhook_pending + WHERE task_id = ${task.id} AND state IN ('pending', 'dispatching', 'running')`; + if ( + (row?.count ?? 0) + ((yield* Ref.get(webhookQueued)).get(queueKey) ?? 0) >= + WEBHOOK_MAX_QUEUED_PER_TASK + ) + return yield* Effect.fail("queue_full" as const); + }).pipe( + Effect.mapError((cause) => (cause === "queue_full" ? cause : dedupeError(cause))), + ); + const admit = (effect: Effect.Effect) => + sql.withTransaction(effect).pipe( + Effect.catch((cause) => + cause === "first_rejected" || cause === "rejected" || cause === "queue_full" + ? Effect.succeed({ + outcome: + cause === "queue_full" + ? ("queue_full" as const) + : ("rate_limited" as const), + log: cause === "first_rejected", + }) + : Effect.fail(isScheduledTaskError(cause) ? cause : dedupeError(cause)), + ), + ); + const deduped = + schedule.dedupe === undefined + ? "run" + : yield* admit( + Effect.gen(function* () { + const outcome = yield* acceptWebhookDedupe( + task, + request, + deliveryId, + DateTime.toEpochMillis(now), + reserve, + takeDedupeLogSlot(task.id, DateTime.toEpochMillis(now)), + checkCapacity, + (ownerId) => replaceDeliveryRequest(ownerId, request), + ).pipe(Effect.provideService(SqlClient.SqlClient, sql)); + if ( + outcome === "pending" || + outcome === "coalesced" || + (outcome === "duplicate" && + (yield* takeDedupeLogSlot(task.id, DateTime.toEpochMillis(now)))) + ) + yield* log(outcome === "pending" ? "accepted" : outcome, { + signatureVerified: signature !== null, + }); + return outcome; + }), + ); + if (typeof deduped !== "string") { + yield* refundRejectionSlot; + if (deduped.log) yield* log("rate_limited"); + yield* observe(deduped.outcome); + return yield* releaseClaim({ _tag: "rate_limited", outcome: deduped.outcome } as const); + } + if (deduped !== "run") { + if (deduped !== "coalesced" && deduped !== "coalesced_unlogged") + yield* refundRejectionSlot; + const outcome = + deduped === "pending" + ? "accepted" + : deduped === "coalesced_unlogged" + ? "coalesced" + : deduped; + yield* observe(outcome); + if (deduped === "duplicate") + return yield* releaseClaim({ _tag: "accepted", deliveryId, outcome } as const); + claimAcquired = false; + return { _tag: "accepted", deliveryId, outcome } as const; + } + const frameId = yield* crypto.randomBytes(6).pipe( + Effect.map((bytes) => Buffer.from(bytes).toString("hex")), + Effect.mapError((cause) => taskError("Could not generate frame id.", { cause })), + ); + const rendered = renderWebhookPrompt(task.prompt, request, frameId); + // Providers trim the prompt before checking, so whitespace around + // it is free. + if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + yield* log("dispatch_failed", { + signatureVerified: signature !== null, + missing: rendered.missing, + renderedPrompt: rendered.prompt, + error: PROMPT_TOO_LONG, + }); + yield* releaseReplay(deliveryId); + yield* observe("prompt_too_long"); + return yield* releaseClaim({ + _tag: "accepted" as const, + deliveryId, + outcome: "prompt_too_long" as const, + }); + } + // Bound the deliveries one task holds, so steady traffic to a stuck + // task cannot pile up parked fibers. + yield* refundRejectionSlot; + let queueReserved = false; + const release = Effect.suspend(() => { + if (!queueReserved) return Effect.void; + queueReserved = false; + return Ref.update(webhookQueued, (counts) => { const next = new Map(counts); const count = (next.get(queueKey) ?? 1) - 1; if (count <= 0) next.delete(queueKey); else next.set(queueKey, count); return next; }); - yield* log("accepted", { - signatureVerified: signature !== null, - missing: rendered.missing, - renderedPrompt: rendered.prompt, - }).pipe(Effect.onError(() => release)); - yield* observe("accepted"); - const permit = yield* webhookPermit(task.id); - const runOutcome = (outcome: "started" | "skipped" | "failed") => - Effect.all([ - Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }), - Metrics.increment(Metrics.webhookRunsTotal, { outcome }), - ]); - yield* runTask(task, "webhook", { deliveryId, prompt: rendered.prompt }).pipe( - Effect.flatMap((completed) => - completed.lastRunStatus === "failed" - ? runOutcome("failed").pipe( - Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")), - ) - : runOutcome("started"), + }); + // Serialize immediate reservations with persisted window admission. + const reserveImmediate = Effect.gen(function* () { + yield* checkCapacity; + yield* reserve; + yield* Ref.update(webhookQueued, (counts) => + new Map(counts).set(queueKey, (counts.get(queueKey) ?? 0) + 1), + ); + queueReserved = true; + }); + const admitted = yield* admit( + Effect.gen(function* () { + const outcome = yield* acceptImmediateWebhookDedupe( + task, + request, + deliveryId, + DateTime.toEpochMillis(now), + reserveImmediate, + ).pipe(Effect.provideService(SqlClient.SqlClient, sql)); + if (outcome === "duplicate") { + if (yield* takeDedupeLogSlot(task.id, DateTime.toEpochMillis(now))) + yield* log("duplicate", { signatureVerified: signature !== null }); + } else + yield* log("accepted", { + signatureVerified: signature !== null, + missing: rendered.missing, + renderedPrompt: rendered.prompt, + }); + return outcome; + }), + ).pipe(Effect.onError(() => release)); + if (typeof admitted !== "string") { + yield* release; + if (admitted.log) yield* log("rate_limited"); + yield* observe(admitted.outcome); + return yield* releaseClaim({ + _tag: "rate_limited", + outcome: admitted.outcome, + } as const); + } + if (admitted === "duplicate") { + yield* release; + yield* observe("duplicate"); + return yield* releaseClaim({ + _tag: "accepted", + deliveryId, + outcome: "duplicate", + } as const); + } + yield* observe("accepted"); + const permit = yield* webhookPermit(task.id); + yield* runWebhookDelivery(task, deliveryId, rendered.prompt).pipe( + permit.withPermits(1), + Effect.ensuring(release), + Effect.forkIn(serviceScope), + ); + // Dispatch owns the accepted delivery now; retries must keep its claim. + claimAcquired = false; + return { _tag: "accepted" as const, deliveryId, outcome: "accepted" as const }; + }).pipe( + Effect.onError(() => + Effect.all([ + releaseClaim(undefined), + (request.relayDeliveryId === undefined || claimAcquired + ? releaseReplay(deliveryId) + : Effect.void + ).pipe(Effect.ignore), + ]), + ), + ), + ); + }); + + const dispatchPending = Effect.fn("ScheduledTaskService.dispatchPendingWebhooks")(function* () { + const now = DateTime.toEpochMillis(yield* localNow); + yield* sql`UPDATE scheduled_task_webhook_pending SET state = 'dispatching' WHERE state = 'pending' AND due_at <= ${now}`; + const tasks = yield* sql<{ task_id: ScheduledTaskId }>` + SELECT DISTINCT task_id FROM scheduled_task_webhook_pending WHERE state IN ('dispatching', 'running', 'completed', 'failed') + `.pipe(NodeSqliteClient.readOnly); + yield* Effect.forEach( + tasks, + ({ task_id: taskId }) => + Effect.gen(function* () { + const reserved = yield* Ref.modify(pendingInFlight, (active) => + active.has(taskId) + ? ([false, active] as const) + : ([true, new Set(active).add(taskId)] as const), + ); + if (!reserved) return; + const permit = yield* webhookPermit(taskId); + // One worker per task waits on its permit, then drains persisted rows in order. + // Other tasks remain independent and ticks never reload an active task's payloads. + const dispatch = Effect.gen(function* () { + while (true) { + const [entry] = yield* sql<{ + delivery_id: string; + task_json: string; + request_json: string; + state: string; + }>` + SELECT delivery_id, task_json, request_json, state FROM scheduled_task_webhook_pending + WHERE task_id = ${taskId} AND state IN ('dispatching', 'running', 'completed', 'failed') ORDER BY due_at, rowid LIMIT 1 + `.pipe(NodeSqliteClient.readOnly); + if (entry === undefined) return; + const remove = sql`DELETE FROM scheduled_task_webhook_pending WHERE delivery_id = ${entry.delivery_id}`; + if (entry.state === "completed" || entry.state === "failed") { + if (entry.state === "failed") { + yield* markDeliveryFailed(entry.delivery_id, "The run failed to start."); + yield* releaseFailedDelivery(entry.delivery_id); + } + yield* remove; + continue; + } + const prepared = yield* Effect.gen(function* () { + const task = yield* decodePendingTask(entry.task_json); + const request = yield* decodePendingRequest(entry.request_json); + const frameId = Buffer.from(yield* crypto.randomBytes(6)).toString("hex"); + return { task, rendered: renderWebhookPrompt(task.prompt, request, frameId) }; + }).pipe(Effect.exit); + if (Exit.isFailure(prepared)) { + if (Cause.hasInterruptsOnly(prepared.cause)) + return yield* Effect.failCause(prepared.cause); + yield* markDeliveryFailed( + entry.delivery_id, + "The pending webhook payload could not be prepared.", + ); + yield* releaseFailedDelivery(entry.delivery_id); + yield* remove; + continue; + } + const { task, rendered } = prepared.value; + if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + yield* markDeliveryFailed(entry.delivery_id, PROMPT_TOO_LONG); + yield* releaseFailedDelivery(entry.delivery_id); + } else { + yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; + if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) + return; + } + yield* remove; + } + }); + yield* dispatch.pipe( + permit.withPermits(1), + Effect.catch((cause) => + Effect.logWarning("Pending webhook dispatch failed", { cause }), ), - Effect.catchTags({ - WebhookDeliverySkipped: (skipped) => - runOutcome("skipped").pipe( - Effect.andThen(markDeliveryFailed(deliveryId, skipped.reason)), - ), - }), - // The log is readable over RPC, so it gets a fixed reason; the - // cause, which can carry request data, stays in the server log. - Effect.catchCause((cause) => - Effect.logWarning("Webhook dispatch failed", { taskId: task.id, cause }).pipe( - Effect.andThen(runOutcome("failed")), - Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")), - ), + Effect.ensuring( + Ref.update(pendingInFlight, (active) => { + const next = new Set(active); + next.delete(taskId); + return next; + }), ), - permit.withPermits(1), - Effect.withSpan("ScheduledTaskService.runWebhookDelivery", { - root: true, - attributes: { - "scheduled_task.id": task.id, - "scheduled_task.webhook.delivery_id": deliveryId, - }, - }), - Effect.ensuring(release), + Effect.withSpan("ScheduledTaskService.dispatchPendingWebhook", { root: true }), Effect.forkIn(serviceScope), ); - return { _tag: "accepted" as const, deliveryId, outcome: "accepted" as const }; }), - ); - }); + { discard: true }, + ); + }); + yield* scheduler.register("webhook-coalescing", dispatchPending()); return ScheduledTaskService.of({ list, @@ -1591,6 +2137,7 @@ export const layer = Layer.effect( upsert, setEnabled, delete: deleteTask, + deleteForThread, runNow, rotateWebhookToken, listWebhookDeliveries, diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index 007329df40d91..127f61444029a 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -3,27 +3,119 @@ import * as NodeCrypto from "node:crypto"; import * as NodePlatformCrypto from "@effect/platform-node/NodeCrypto"; import { assert, it } from "@effect/vitest"; -import { ScheduledTaskUpsertInput, SecretRequestError } from "@t3tools/contracts"; +import { + ScheduledTaskUpsertInput, + ScheduledTaskWebhookDeliveryId, + SecretRequestError, +} from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Crypto from "effect/Crypto"; 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 Metric from "effect/Metric"; import * as Queue from "effect/Queue"; import * as EffectScheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; +import * as Tracer from "effect/Tracer"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; +import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; import * as ScheduledTaskService from "./ScheduledTaskService.ts"; +import { renderWebhookPrompt } from "./webhookTemplate.ts"; const decodeUpsertInput = Schema.decodeUnknownEffect(ScheduledTaskUpsertInput); +it.effect( + "preserves omitted dedupe settings, releases duplicate claims, and retains coalesced claims", + () => + withService(({ service, sql, launches }) => + Effect.gen(function* () { + const dedupe = { + replayKey: "{{headers.delivery-id}}", + coalesceKey: "{{body.group}}", + coalesceWindowSeconds: 10, + }; + const { task } = yield* service.upsert( + yield* webhookTaskInput({ schedule: { type: "webhook", dedupe } }), + ); + const updated = yield* service.upsert(yield* webhookTaskInput()); + assert.deepEqual( + updated.task.schedule.type === "webhook" && updated.task.schedule.dedupe, + dedupe, + ); + const request = (id: string, bodyText = "{}", relayDeliveryId?: string) => + requestFor(task, { + headers: { "delivery-id": id }, + bodyText, + body: new TextEncoder().encode(bodyText), + ...(relayDeliveryId === undefined ? {} : { relayDeliveryId }), + }); + yield* service.triggerWebhook(request("A")); + yield* Queue.take(launches); + yield* service.triggerWebhook(request("B1", '{"group":"B"}')); + for (let i = 0; i < 5; i++) { + const duplicate = yield* service.triggerWebhook(request("A", "{}", `duplicate-${i}`)); + assert.equal(duplicate._tag === "accepted" && duplicate.outcome, "duplicate"); + const coalesced = yield* service.triggerWebhook( + request(`B${i + 2}`, '{"group":"B"}', `coalesced-${i}`), + ); + assert.equal(coalesced._tag === "accepted" && coalesced.outcome, "coalesced"); + } + const claims = yield* sql<{ + relay_delivery_id: string; + }>`SELECT relay_delivery_id FROM scheduled_task_webhook_relay_deliveries ORDER BY relay_delivery_id`; + assert.deepEqual( + claims.map((claim) => claim.relay_delivery_id), + Array.from({ length: 5 }, (_, i) => `coalesced-${i}`), + ); + assert.isTrue( + (yield* service.listWebhookDeliveries({ id: task.id })).deliveries.every( + (delivery) => delivery.outcome !== "duplicate" && delivery.outcome !== "coalesced", + ), + ); + const fresh = yield* service.triggerWebhook(request("C", "{}", "duplicate-0")); + assert.equal(fresh._tag === "accepted" && fresh.outcome, "accepted"); + yield* Queue.take(launches); + const cleared = yield* service.upsert( + yield* webhookTaskInput({ schedule: { type: "webhook", dedupe: {} } }), + ); + assert.deepEqual( + cleared.task.schedule.type === "webhook" && cleared.task.schedule.dedupe, + {}, + ); + }), + ), +); + +const waitForSpan = (work: Effect.Effect, name: string) => + Effect.gen(function* () { + const done = yield* Deferred.make(); + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (...args) => { + end(...args); + if (span.name === name) Deferred.doneUnsafe(done, Effect.void); + }; + return span; + }, + }); + const result = yield* work.pipe(Effect.withTracer(tracer)); + yield* Deferred.await(done); + return result; + }); + +const drainPendingDispatch = (workers: Map>) => + waitForSpan(workers.get("webhook-coalescing")!, "ScheduledTaskService.dispatchPendingWebhook"); + type LaunchInput = ThreadLaunchService.ThreadLaunchInput; const webhookTaskInput = (overrides: Record = {}) => @@ -64,22 +156,83 @@ const withService = ( body: (input: { readonly service: ScheduledTaskService.ScheduledTaskService["Service"]; readonly launches: Queue.Queue; + readonly sql: SqlClient.SqlClient; readonly secretsByRef: Map; }) => Effect.Effect, - options: { readonly gate?: Deferred.Deferred; readonly relayHookBaseUrl?: string } = {}, + options: { + readonly onFrame?: () => void; + readonly frameGate?: { + readonly started: Deferred.Deferred; + readonly release: Deferred.Deferred; + }; + readonly completedLaunches?: Set; + readonly failLaunches?: { remaining: number }; + readonly gate?: Deferred.Deferred; + readonly gateForTask?: (input: LaunchInput) => Deferred.Deferred | undefined; + readonly relayHookBaseUrl?: string; + readonly sql?: SqlClient.SqlClient; + readonly workers?: Map>; + } = {}, ) => Effect.gen(function* () { const launches = yield* Queue.unbounded(); const secretsByRef = new Map(); const layerDependencies = Layer.mergeAll( - NodePlatformCrypto.layer, - Scheduler.layer, + options.frameGate === undefined && options.onFrame === undefined + ? NodePlatformCrypto.layer + : Layer.effect( + Crypto.Crypto, + Effect.gen(function* () { + const crypto = yield* Crypto.Crypto; + return { + ...crypto, + randomBytes: (size: number) => + Effect.suspend(() => { + if (size === 6) options.onFrame?.(); + return size === 6 && options.frameGate !== undefined + ? Deferred.succeed(options.frameGate.started, undefined).pipe( + Effect.andThen(Deferred.await(options.frameGate.release)), + Effect.andThen(crypto.randomBytes(size)), + ) + : crypto.randomBytes(size); + }), + }; + }), + ).pipe(Layer.provide(NodePlatformCrypto.layer)), + options.workers === undefined + ? Scheduler.layer + : Layer.succeed(Scheduler.Scheduler, { + register: (name: string, work: Effect.Effect) => + Effect.gen(function* () { + const context = yield* Effect.context(); + options.workers!.set(name, work.pipe(Effect.provideContext(context), Effect.orDie)); + }), + }), Layer.mock(ThreadLaunchService.ThreadLaunchService)({ launch: (input) => - Queue.offer(launches, input).pipe( - Effect.andThen(options.gate ? Deferred.await(options.gate) : Effect.void), - Effect.as({ threadId: "thread-1", resumed: false } as never), - ), + Effect.suspend(() => { + if (options.completedLaunches?.has(input.commandId)) + return Effect.succeed({ threadId: "thread-1", resumed: false } as never); + options.completedLaunches?.add(input.commandId); + return Queue.offer(launches, input).pipe( + Effect.andThen( + (options.gateForTask?.(input) ?? options.gate) + ? Deferred.await((options.gateForTask?.(input) ?? options.gate)!) + : Effect.void, + ), + Effect.andThen( + Effect.sync(() => { + if (options.failLaunches && options.failLaunches.remaining-- > 0) + throw new Error("injected start failure"); + }), + ), + Effect.as({ threadId: "thread-1", resumed: false } as never), + ); + }), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), }), Layer.mock(ThreadManagementService.ThreadManagementService)({}), Layer.mock(SecretRequests.SecretRequests)({ @@ -98,9 +251,20 @@ const withService = ( ); return yield* Effect.gen(function* () { const service = yield* ScheduledTaskService.ScheduledTaskService; - return yield* body({ service, launches, secretsByRef }); - }).pipe(Effect.provide(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies)))); - }).pipe(Effect.provide(SqlitePersistence.layerMemory)); + const sql = yield* SqlClient.SqlClient; + return yield* body({ service, launches, sql, secretsByRef }); + }).pipe( + Effect.provide( + Layer.fresh(ScheduledTaskService.layer.pipe(Layer.provide(layerDependencies))), + ), + ); + }).pipe( + Effect.provide( + options.sql === undefined + ? SqlitePersistence.layerMemory + : Layer.succeed(SqlClient.SqlClient, options.sql), + ), + ); it.effect("dispatches exactly the rendered prompt and logs the delivery", () => withService(({ service, launches }) => @@ -123,7 +287,10 @@ it.effect("dispatches exactly the rendered prompt and logs the delivery", () => `scheduled-task:${task.id}:webhook:${result._tag === "accepted" ? result.deliveryId : ""}`, ); - const { deliveries } = yield* service.listWebhookDeliveries({ id: task.id }); + const { deliveries } = yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + }); assert.equal(deliveries.length, 1); assert.equal(deliveries[0]?.outcome, "accepted"); const { delivery } = yield* service.getWebhookDelivery({ @@ -133,7 +300,6 @@ it.effect("dispatches exactly the rendered prompt and logs the delivery", () => assert.equal(delivery.body, new TextDecoder().decode(pullRequestBody)); assert.equal(delivery.renderedPrompt, launched.initialMessage?.text); - // Each delivery gets its own frame, so a request can't predict the tag that closes it. yield* service.triggerWebhook(requestFor(task)); const next = framed.exec((yield* Queue.take(launches)).initialMessage?.text ?? "")?.[1]; assert.isDefined(next); @@ -179,7 +345,11 @@ it.effect("answers not found for a wrong token or unknown hook without logging", assert.equal(wrongToken._tag, "not_found"); const unknown = yield* service.triggerWebhook(requestFor(task, { hookId: "missing" })); assert.equal(unknown._tag, "not_found"); - assert.equal((yield* service.listWebhookDeliveries({ id: task.id })).deliveries.length, 0); + assert.equal( + (yield* service.listWebhookDeliveries({ id: task.id, acceptAnyOutcome: true })).deliveries + .length, + 0, + ); }), ), ); @@ -244,9 +414,10 @@ it.effect("checks the configured signature and keeps the secret write-only", () ); assert.isTrue(resaved.task.webhook?.hasSecret); - const outcomes = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries.map( - (delivery) => [delivery.outcome, delivery.signatureVerified], - ); + const outcomes = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries.map((delivery) => [delivery.outcome, delivery.signatureVerified]); assert.deepEqual(outcomes.toSorted(), [ ["accepted", true], ["rejected_signature", false], @@ -267,48 +438,6 @@ it.effect("logs but does not run deliveries to a disabled task, and refuses run ), ); -it.effect("queues a burst of deliveries instead of dropping them", () => - Effect.gen(function* () { - const gate = yield* Deferred.make(); - yield* withService( - ({ service, launches }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput()); - const results = yield* Effect.forEach([1, 2, 3], () => - service.triggerWebhook(requestFor(task)), - ); - assert.deepEqual( - results.map((result) => result._tag), - ["accepted", "accepted", "accepted"], - ); - yield* Queue.take(launches); - yield* Deferred.succeed(gate, undefined); - const rest = yield* Effect.all([Queue.take(launches), Queue.take(launches)]); - assert.equal(new Set(rest.map((launch) => launch.commandId)).size, 2); - }), - { gate }, - ); - }), -); - -it.effect("rate limits a hook past 60 deliveries a minute", () => - withService(({ service }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false })); - const results = yield* Effect.forEach(Array.from({ length: 61 }), () => - service.triggerWebhook(requestFor(task)), - ); - assert.equal(results.at(-2)?._tag, "disabled"); - assert.equal(results.at(-1)?._tag, "rate_limited"); - yield* Effect.forEach([1, 2, 3], () => service.triggerWebhook(requestFor(task))); - const outcomes = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries.map( - (delivery) => delivery.outcome, - ); - assert.equal(outcomes.filter((outcome) => outcome === "rate_limited").length, 1); - }), - ), -); - it.effect("a save carrying a stale token cannot undo a rotation", () => withService(({ service }) => Effect.gen(function* () { @@ -321,29 +450,6 @@ it.effect("a save carrying a stale token cannot undo a rotation", () => ), ); -it.effect("keeps the newest 50 deliveries when they share a timestamp", () => - withService(({ service }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false })); - const ids = yield* Effect.forEach(Array.from({ length: 55 }), (_, index) => - service.triggerWebhook(requestFor(task, { query: `n=${index}` })).pipe(Effect.as(index)), - ); - const { deliveries } = yield* service.listWebhookDeliveries({ id: task.id }); - assert.equal(deliveries.length, 50); - const first = yield* service.getWebhookDelivery({ - id: task.id, - deliveryId: deliveries[0]!.id, - }); - const last = yield* service.getWebhookDelivery({ - id: task.id, - deliveryId: deliveries.at(-1)!.id, - }); - assert.equal(first.delivery.query, `n=${ids.at(-1)}`); - assert.equal(last.delivery.query, "n=5"); - }), - ), -); - it.effect("keeps credential headers and query values out of the delivery log", () => withService(({ service }) => Effect.gen(function* () { @@ -359,7 +465,10 @@ it.effect("keeps credential headers and query values out of the delivery log", ( }, }), ); - const [summary] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; + const [summary] = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries; const { delivery } = yield* service.getWebhookDelivery({ id: task.id, deliveryId: summary!.id, @@ -456,87 +565,6 @@ it.effect("a save without a secret keeps a secret changed after it was read", () ), ); -it.effect("caps deliveries waiting behind a stuck run", () => - Effect.gen(function* () { - const gate = yield* Deferred.make(); - yield* withService( - ({ service, launches }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput()); - yield* service.triggerWebhook(requestFor(task)); - yield* Queue.take(launches); - const waiting = yield* Effect.forEach(Array.from({ length: 20 }), () => - service.triggerWebhook(requestFor(task)), - ); - assert.equal(waiting.filter((result) => result._tag === "accepted").length, 19); - assert.equal(waiting.at(-1)?._tag, "rate_limited"); - const logged = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; - assert.equal(logged.length, 20); - yield* Deferred.succeed(gate, undefined); - }), - { gate }, - ); - }), -); - -it.effect("logs a body's first 64 KiB by bytes, not characters", () => - withService(({ service }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false })); - const text = "界".repeat(30_000); - const body = new TextEncoder().encode(text); - yield* service.triggerWebhook(requestFor(task, { body, bodyText: text })); - const [summary] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; - const { delivery } = yield* service.getWebhookDelivery({ - id: task.id, - deliveryId: summary!.id, - }); - assert.isTrue(delivery.bodyTruncated); - assert.isAtMost(new TextEncoder().encode(delivery.body).byteLength, 64 * 1024 + 3); - }), - ), -); - -it.effect("counts the prompt as the provider does, without surrounding whitespace", () => - withService(({ service, launches }) => - Effect.gen(function* () { - // Values are framed, so only an empty placeholder can leave padding at the edge. - const { task } = yield* service.upsert( - yield* webhookTaskInput({ prompt: `{{body.none}}${" ".repeat(2_000)}{{body.text}}` }), - ); - const text = JSON.stringify({ text: "x".repeat(119_000) }); - const result = yield* service.triggerWebhook( - requestFor(task, { body: new TextEncoder().encode(text), bodyText: text }), - ); - assert.equal(result._tag, "accepted"); - yield* Queue.take(launches); - }), - ), -); - -it.effect("does not start a run when the filled-in prompt is too long", () => - withService(({ service, launches }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ prompt: "{{body}}" })); - const text = "x".repeat(200_000); - const body = new TextEncoder().encode(text); - const result = yield* service.triggerWebhook(requestFor(task, { body, bodyText: text })); - assert.equal(result._tag, "accepted"); - assert.equal(yield* Queue.size(launches), 0); - const { delivery } = yield* service.getWebhookDelivery({ - id: task.id, - deliveryId: result._tag === "accepted" ? result.deliveryId : ("" as never), - }); - assert.equal(delivery.outcome, "dispatch_failed"); - assert.equal(delivery.error, "The filled-in prompt is too long."); - assert.equal(delivery.renderedPrompt?.length, 64 * 1024); - const ok = yield* service.triggerWebhook(requestFor(task)); - assert.equal(ok._tag, "accepted"); - yield* Queue.take(launches); - }), - ), -); - it.effect("a held request already delivered directly runs only once", () => withService(({ service, launches }) => Effect.gen(function* () { @@ -550,12 +578,65 @@ it.effect("a held request already delivered directly runs only once", () => assert.equal(direct._tag, "accepted"); assert.deepEqual(replayed, { ...direct, outcome: "duplicate" } as typeof replayed); yield* Queue.take(launches); - const logged = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; + const logged = (yield* service.listWebhookDeliveries({ id: task.id, acceptAnyOutcome: true })) + .deliveries; assert.equal(logged.length, 1); }), ), ); +it.effect("relay retries recover failed acceptance without releasing another request's claim", () => + withService(({ service, launches, sql }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* webhookTaskInput()); + const request = requestFor(task, { relayDeliveryId: "retry-after-log-failure" }); + yield* sql` + CREATE TRIGGER fail_webhook_delivery_log + BEFORE INSERT ON scheduled_task_webhook_deliveries + BEGIN + SELECT RAISE(FAIL, 'injected delivery log failure'); + END + `; + const error = yield* service.triggerWebhook(request).pipe(Effect.flip); + assert.equal(error.message, "Could not record webhook delivery."); + assert.equal(yield* Queue.size(launches), 0); + assert.isEmpty( + (yield* service.listWebhookDeliveries({ id: task.id, acceptAnyOutcome: true })).deliveries, + ); + yield* sql`DROP TRIGGER fail_webhook_delivery_log`; + + const retried = yield* Effect.all( + [service.triggerWebhook(request), service.triggerWebhook(request)], + { concurrency: "unbounded" }, + ); + assert.deepEqual( + retried.map((result) => (result._tag === "accepted" ? result.outcome : result._tag)).sort(), + ["accepted", "duplicate"], + ); + assert.include((yield* Queue.take(launches)).commandId, request.relayDeliveryId!); + + yield* sql` + CREATE TRIGGER fail_webhook_claim + BEFORE INSERT ON scheduled_task_webhook_relay_deliveries + BEGIN + SELECT RAISE(FAIL, 'injected claim failure'); + END + `; + const retryError = yield* service.triggerWebhook(request).pipe(Effect.flip); + assert.equal(retryError.message, "Could not record webhook delivery."); + yield* sql`DROP TRIGGER fail_webhook_claim`; + const replayed = yield* service.triggerWebhook(request); + assert.equal(replayed._tag === "accepted" ? replayed.outcome : replayed._tag, "duplicate"); + assert.equal(yield* Queue.size(launches), 0); + assert.equal( + (yield* service.listWebhookDeliveries({ id: task.id, acceptAnyOutcome: true })).deliveries + .length, + 1, + ); + }), + ), +); + it.effect("a held request whose sender hung up mid-request still runs", () => withService(({ service, launches }) => Effect.gen(function* () { @@ -599,57 +680,6 @@ it.effect("a held request runs once even after the log has trimmed it", () => ), ); -it.effect("a rate-limited held request can run on a later pass", () => - withService(({ service, launches }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false })); - yield* Effect.forEach(Array.from({ length: 60 }), () => - service.triggerWebhook(requestFor(task)), - ); - const limited = yield* service.triggerWebhook(requestFor(task, { relayDeliveryId: "later" })); - assert.equal(limited._tag, "rate_limited"); - yield* service.upsert(yield* webhookTaskInput()); - yield* TestClock.adjust("61 seconds"); - const retried = yield* service.triggerWebhook(requestFor(task, { relayDeliveryId: "later" })); - assert.equal(retried._tag, "accepted"); - yield* Queue.take(launches); - }), - ), -); - -it.effect("logs a held request at the time the relay received it", () => - withService(({ service }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false })); - const receivedAt = DateTime.formatIso(DateTime.subtract(yield* DateTime.now, { minutes: 5 })); - yield* service.triggerWebhook(requestFor(task, { relayDeliveryId: "relay-2", receivedAt })); - const [delivery] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; - assert.equal(delivery?.receivedAt, receivedAt); - }), - ), -); - -it.effect("a receive time in the future counts as now", () => - withService(({ service, launches }) => - Effect.gen(function* () { - const { task } = yield* service.upsert( - yield* webhookTaskInput({ schedule: { type: "webhook", maxDeliveryAgeMinutes: 30 } }), - ); - const now = yield* DateTime.now; - const result = yield* service.triggerWebhook( - requestFor(task, { - relayDeliveryId: "future", - receivedAt: DateTime.formatIso(DateTime.add(now, { days: 365 })), - }), - ); - assert.equal(result._tag, "accepted"); - yield* Queue.take(launches); - const [delivery] = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; - assert.equal(delivery?.receivedAt, DateTime.formatIso(now)); - }), - ), -); - it.effect("skips a held request older than the task's max age", () => withService(({ service, launches }) => Effect.gen(function* () { @@ -668,41 +698,15 @@ it.effect("skips a held request older than the task's max age", () => requestFor(task, { relayDeliveryId: "fresh", receivedAt: fresh }), ); assert.equal(ok._tag, "accepted"); - const outcomes = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries.map( - (delivery) => delivery.outcome, - ); + const outcomes = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries.map((delivery) => delivery.outcome); assert.includeMembers(outcomes, ["expired", "accepted"]); }), ), ); -it.effect("runs a held request of any age when no max age is set", () => - withService(({ service }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput()); - const now = yield* DateTime.now; - const result = yield* service.triggerWebhook( - requestFor(task, { - relayDeliveryId: "ancient", - receivedAt: DateTime.formatIso(DateTime.subtract(now, { hours: 23 })), - }), - ); - assert.equal(result._tag, "accepted"); - }), - ), -); - -it.effect("deleting a task removes its delivery log", () => - withService(({ service }) => - Effect.gen(function* () { - const { task } = yield* service.upsert(yield* webhookTaskInput({ enabled: false })); - yield* service.triggerWebhook(requestFor(task)); - yield* service.delete({ id: task.id }); - assert.equal((yield* service.listWebhookDeliveries({ id: task.id })).deliveries.length, 0); - }), - ), -); - const githubSignature = (secret: string) => `sha256=${NodeCrypto.createHmac("sha256", secret).update(pullRequestBody).digest("hex")}`; @@ -811,23 +815,868 @@ it.effect("a signature without any secret is refused", () => ), ); -const signatureFor = (secret: string) => - `sha256=${NodeCrypto.createHmac("sha256", secret).update(pullRequestBody).digest("hex")}`; +it.effect("dedupes replay keys per task, persists them, and expires them after seven days", () => + withService( + ({ service, launches, sql }) => + Effect.gen(function* () { + const schedule = { type: "webhook", dedupe: { replayKey: "{{headers.delivery-id}}" } }; + const { task } = yield* service.upsert(yield* webhookTaskInput({ schedule })); + const request = requestFor(task, { headers: { "delivery-id": "A" } }); + const first = yield* service.triggerWebhook(request); + assert.equal(first._tag === "accepted" && first.outcome, "accepted"); + yield* Queue.take(launches); + const replay = yield* service.triggerWebhook(request); + assert.equal(replay._tag === "accepted" && replay.outcome, "duplicate"); + assert.equal(yield* Queue.size(launches), 0); + const other = yield* service.upsert( + yield* webhookTaskInput({ id: "scheduled-task:other", schedule }), + ); + yield* service.triggerWebhook(requestFor(other.task, { headers: request.headers })); + yield* Queue.take(launches); + yield* withService( + ({ service: restarted }) => + Effect.gen(function* () { + const replay = yield* restarted.triggerWebhook(request); + assert.equal(replay._tag === "accepted" && replay.outcome, "duplicate"); + }), + { sql, workers: new Map() }, + ); + yield* TestClock.adjust("7 days"); + const expired = yield* service.triggerWebhook(request); + assert.equal(expired._tag === "accepted" && expired.outcome, "accepted"); + yield* Queue.take(launches); + assert.include( + (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries.map((d) => d.outcome), + "duplicate", + ); + }), + { workers: new Map() }, + ), +); -const deliveriesCounted = (outcome: string, source: "relay" | "direct") => - Metric.snapshot.pipe( - Effect.map((snapshots) => { - const found = snapshots.find( - (snapshot) => - snapshot.id === "t3_webhook_deliveries_total" && - snapshot.attributes?.outcome === outcome && - snapshot.attributes?.source === source, +it.effect.each([1, 3])( + "coalesces %i deliveries into one run with the latest body, headers and query", + (count) => { + const workers = new Map>(); + return withService( + ({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: "{{body.value}} {{headers.version}} {{query.version}}", + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{body.key}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + for (let value = 1; value <= count; value++) { + const bodyText = JSON.stringify({ key: "B", value }); + yield* service.triggerWebhook( + requestFor(task, { + bodyText, + body: new TextEncoder().encode(bodyText), + headers: { version: String(value) }, + query: `version=${value}`, + }), + ); + if (value < count) yield* TestClock.adjust("2 seconds"); + } + const owner = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries.find((delivery) => delivery.outcome === "accepted")!; + assert.isTrue(owner.pendingWindow); + const beforeDispatch = (yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: owner.id, + acceptAnyOutcome: true, + })).delivery; + assert.isTrue(beforeDispatch.pendingWindow); + assert.equal(beforeDispatch.body, JSON.stringify({ key: "B", value: count })); + assert.equal(beforeDispatch.headers.version, String(count)); + assert.equal(beforeDispatch.query, `version=${count}`); + assert.equal( + beforeDispatch.bodyBytes, + new TextEncoder().encode(beforeDispatch.body).byteLength, + ); + assert.equal(yield* Queue.size(launches), 0); + yield* workers.get("webhook-coalescing")!; + assert.equal(yield* Queue.size(launches), 0); + yield* TestClock.adjust(count === 1 ? "10 seconds" : "6 seconds"); + yield* workers.get("webhook-coalescing")!; + const launched = yield* Queue.take(launches); + assert.equal( + (launched.initialMessage!.text.match(new RegExp(`>${count}<`, "g")) ?? []).length, + 3, + ); + yield* workers.get("webhook-coalescing")!; + assert.equal(yield* Queue.size(launches), 0); + const outcomes = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries.map((d) => d.outcome); + const afterDispatch = (yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: owner.id, + acceptAnyOutcome: true, + })).delivery; + assert.isFalse(afterDispatch.pendingWindow); + assert.equal(afterDispatch.body, beforeDispatch.body); + assert.include(afterDispatch.renderedPrompt!, `>${count}<`); + assert.equal(outcomes.filter((o) => o === "accepted").length, 1); + assert.equal(outcomes.filter((o) => o === "coalesced").length, count - 1); + }), + { workers }, + ); + }, +); + +it.effect("recovers a persisted coalescing window after restarting the service", () => { + const workers = new Map>(); + return withService( + ({ service, sql }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{headers.content-type}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + yield* service.triggerWebhook(requestFor(task)); + yield* TestClock.adjust("4 seconds"); + const restartedWorkers = new Map>(); + yield* withService( + ({ launches }) => + Effect.gen(function* () { + yield* restartedWorkers.get("webhook-coalescing")!; + assert.equal(yield* Queue.size(launches), 0); + yield* TestClock.adjust("6 seconds"); + yield* restartedWorkers.get("webhook-coalescing")!; + yield* Queue.take(launches); + yield* restartedWorkers.get("webhook-coalescing")!; + assert.equal(yield* Queue.size(launches), 0); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_pending`).length, 0); + }), + { sql, workers: restartedWorkers }, + ); + }), + { workers }, + ); +}); + +it.effect("rolls back replay and pending state when recording a delivery fails", () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { + replayKey: "{{headers.content-type}}", + coalesceKey: "{{headers.content-type}}", + coalesceWindowSeconds: 10, + }, + }, + }), + ); + yield* sql`CREATE TRIGGER fail_dedupe_log BEFORE INSERT ON scheduled_task_webhook_deliveries BEGIN SELECT RAISE(FAIL, 'injected'); END`; + yield* service.triggerWebhook(requestFor(task)).pipe(Effect.flip); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_pending`).length, 0); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_replay_keys`).length, 0); + yield* sql`DROP TRIGGER fail_dedupe_log`; + const retry = yield* service.triggerWebhook(requestFor(task)); + assert.equal(retry._tag === "accepted" && retry.outcome, "accepted"); + yield* TestClock.adjust("10 seconds"); + yield* workers.get("webhook-coalescing")!; + yield* Queue.take(launches); + }), + { workers }, + ); +}); + +it.effect("queue-full deliveries release replay keys so a later retry runs", () => + Effect.gen(function* () { + const gate = yield* Deferred.make(); + yield* withService( + ({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { type: "webhook", dedupe: { replayKey: "{{headers.delivery-id}}" } }, + }), + ); + const request = (i: number) => + requestFor(task, { headers: { "delivery-id": String(i) } }); + for (let i = 0; i < 20; i++) yield* service.triggerWebhook(request(i)); + yield* Queue.take(launches); + const full = yield* service.triggerWebhook(request(20)); + assert.equal(full._tag === "rate_limited" && full.outcome, "queue_full"); + yield* Deferred.succeed(gate, undefined); + for (let i = 1; i < 20; i++) yield* Queue.take(launches); + const retry = yield* service.triggerWebhook(request(20)); + assert.equal(retry._tag === "accepted" && retry.outcome, "accepted"); + yield* Queue.take(launches); + }), + { gate }, + ); + }), +); + +it.effect.each(["task_json", "request_json"] as const)( + "removes corrupt pending %s instead of retrying forever", + (column) => { + const workers = new Map>(); + return withService( + ({ service, sql }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { + replayKey: "{{body}}", + coalesceKey: "{{body}}", + coalesceWindowSeconds: 10, + }, + }, + }), + ); + yield* service.triggerWebhook(requestFor(task)); + yield* sql`UPDATE scheduled_task_webhook_pending SET ${sql(column)} = 'broken'`; + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_pending`).length, 0); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_replay_keys`).length, 0); + assert.equal( + (yield* service.listWebhookDeliveries({ id: task.id })).deliveries[0]!.outcome, + "dispatch_failed", + ); + yield* workers.get("webhook-coalescing")!; + }), + { workers }, + ); + }, +); + +it.effect( + "restarting after a coalesced launch before pending deletion does not launch or count it twice", + () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{body}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + const accepted = yield* service.triggerWebhook(requestFor(task)); + yield* sql`CREATE TRIGGER fail_pending_delete BEFORE DELETE ON scheduled_task_webhook_pending BEGIN SELECT RAISE(FAIL,'crash after launch'); END`; + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + const launch = yield* Queue.take(launches); + assert.equal( + launch.commandId, + `scheduled-task:${task.id}:webhook:${accepted._tag === "accepted" && accepted.deliveryId}`, + ); + assert.equal((yield* service.list()).tasks[0]!.runCount, 1); + assert.equal( + (yield* sql`SELECT * FROM scheduled_task_webhook_pending WHERE state = 'completed'`) + .length, + 1, + ); + yield* sql`DROP TRIGGER fail_pending_delete`; + const restartedWorkers = new Map>(); + yield* withService( + ({ service: restarted, launches: secondLaunches }) => + Effect.gen(function* () { + yield* drainPendingDispatch(restartedWorkers); + assert.equal(yield* Queue.size(secondLaunches), 0); + assert.equal((yield* restarted.list()).tasks[0]!.runCount, 1); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_pending`).length, 0); + }), + { sql, workers: restartedWorkers }, + ); + }), + { workers }, + ); + }, +); + +it.effect("guards bad-signature floods separately from valid run admission", () => + withService(({ service, sql }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + signature: { header: "signature", encoding: "hex", prefix: "", secret: "secret" }, + }, + }), + ); + const results = yield* Effect.forEach(Array.from({ length: 75 }), () => + service.triggerWebhook(requestFor(task)), + ); + assert.equal(results.filter((result) => result._tag === "rejected_signature").length, 60); + assert.equal(results.filter((result) => result._tag === "rate_limited").length, 15); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_deliveries`).length, 51); + }), + ), +); + +it.effect("start failures release both replay keys and relay claims for redelivery", () => + withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { type: "webhook", dedupe: { replayKey: "{{body}}" } }, + }), + ); + const request = requestFor(task, { relayDeliveryId: "failed-start" }); + yield* waitForSpan( + service.triggerWebhook(request), + "ScheduledTaskService.runWebhookDelivery", + ); + yield* Queue.take(launches); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_replay_keys`).length, 0); + assert.equal((yield* sql`SELECT * FROM scheduled_task_webhook_relay_deliveries`).length, 0); + const retry = yield* waitForSpan( + service.triggerWebhook(request), + "ScheduledTaskService.runWebhookDelivery", + ); + assert.equal(retry._tag === "accepted" && retry.outcome, "accepted"); + yield* Queue.take(launches); + assert.equal((yield* service.list()).tasks[0]!.lastRunStatus, "succeeded"); + }), + { failLaunches: { remaining: 1 } }, + ), +); + +it.effect("main retention keeps fifty runs and preserves filtered and dedupe buckets", () => + withService(({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* webhookTaskInput()); + yield* service.triggerWebhook(requestFor(task)); + yield* Queue.take(launches); + for (const outcome of ["filtered", "duplicate"]) { + yield* sql`WITH RECURSIVE n(value) AS (SELECT 1 UNION ALL SELECT value + 1 FROM n WHERE value < 20) + INSERT INTO scheduled_task_webhook_deliveries + SELECT ${outcome} || n.value, d.task_id, d.received_at, d.method, d.query, d.headers_json, d.body, + d.body_bytes, d.body_truncated, ${outcome}, d.signature_verified, d.missing_fields_json, d.rendered_prompt, d.error + FROM n CROSS JOIN (SELECT * FROM scheduled_task_webhook_deliveries WHERE outcome = 'accepted' LIMIT 1) d`; + } + for (let i = 0; i < 59; i++) { + assert.equal((yield* service.triggerWebhook(requestFor(task)))._tag, "accepted"); + yield* Queue.take(launches); + } + const counts = yield* sql<{ + outcome: string; + count: number; + }>`SELECT outcome, COUNT(*) AS count FROM scheduled_task_webhook_deliveries GROUP BY outcome ORDER BY outcome`; + assert.deepEqual(counts, [ + { outcome: "accepted", count: 50 }, + { outcome: "duplicate", count: 20 }, + { outcome: "filtered", count: 20 }, + ]); + }), + ), +); + +it.effect( + "a valid request refunds its own reservation without expiring an interleaved rejection", + () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + yield* withService( + ({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + signature: { header: "signature", encoding: "hex", prefix: "", secret: "secret" }, + }, + }), + ); + const signature = NodeCrypto.createHmac("sha256", "secret") + .update(pullRequestBody) + .digest("hex"); + const valid = yield* service + .triggerWebhook(requestFor(task, { headers: { signature } })) + .pipe(Effect.forkChild); + yield* Deferred.await(started); + yield* TestClock.adjust("30 seconds"); + assert.equal( + (yield* service.triggerWebhook(requestFor(task)))._tag, + "rejected_signature", + ); + yield* Deferred.succeed(release, undefined); + assert.equal((yield* Fiber.join(valid))._tag, "accepted"); + yield* Queue.take(launches); + // Only the valid reservation would have expired now; the rejection must still count. + yield* TestClock.adjust("31 seconds"); + for (let i = 0; i < 59; i++) + assert.equal( + (yield* service.triggerWebhook(requestFor(task)))._tag, + "rejected_signature", + ); + assert.equal((yield* service.triggerWebhook(requestFor(task)))._tag, "rate_limited"); + }), + { frameGate: { started, release } }, + ); + }), +); + +it.effect("keeps replay keys when dispatch succeeds but completion bookkeeping fails", () => + withService(({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { replayKey: "{{body}}" }, + }, + }), + ); + yield* sql`CREATE TRIGGER fail_completion BEFORE UPDATE ON scheduled_tasks + WHEN NEW.last_run_status = 'succeeded' BEGIN SELECT RAISE(FAIL, 'completion unavailable'); END`; + yield* waitForSpan( + service.triggerWebhook(requestFor(task)), + "ScheduledTaskService.runWebhookDelivery", ); - return found?.type === "Counter" ? Number(found.state.count) : 0; + yield* Queue.take(launches); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_replay_keys`).length, 1); + yield* sql`DROP TRIGGER fail_completion`; + const retry = yield* service.triggerWebhook(requestFor(task)); + assert.equal(retry._tag === "accepted" && retry.outcome, "duplicate"); + assert.equal(yield* Queue.size(launches), 0); + assert.equal((yield* service.list()).tasks[0]!.runCount, 1); }), + ), +); + +it.effect.each([119_000, 120_000])( + "bounds coalesced prompt logs and checks trimmed length for %i body characters", + (length) => { + const workers = new Map>(); + return withService( + ({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: `{{body.absent}}${" ".repeat(10_000)}{{body.text}}`, + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{body.group}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + const bodyText = JSON.stringify({ group: "B", text: "x".repeat(length) }); + const accepted = yield* service.triggerWebhook( + requestFor(task, { bodyText, body: new TextEncoder().encode(bodyText) }), + ); + assert.equal(accepted._tag, "accepted"); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + const delivery = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries[0]!; + if (length === 119_000) { + const launch = yield* Queue.take(launches); + assert.isAbove(launch.initialMessage!.text.length, 120_000); + assert.equal(delivery.outcome, "accepted"); + const detail = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: delivery.id, + }); + assert.equal(detail.delivery.renderedPrompt!.length, 64 * 1024); + } else { + assert.equal(yield* Queue.size(launches), 0); + assert.equal(delivery.outcome, "dispatch_failed"); + assert.equal(delivery.error, "The filled-in prompt is too long."); + } + }), + { workers }, + ); + }, +); + +it.effect.each([1, 11])( + "keeps relay claims for %i coalesced updates after their window closes", + (count) => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: "{{body.value}}", + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{body.group}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + const request = (value: number) => { + const bodyText = JSON.stringify({ group: "B", value }); + return requestFor(task, { + relayDeliveryId: `coalesced-relay-${value}`, + bodyText, + body: new TextEncoder().encode(bodyText), + }); + }; + yield* service.triggerWebhook(request(0)); + for (let i = 1; i <= count; i++) { + const result = yield* service.triggerWebhook(request(i)); + assert.equal(result._tag === "accepted" && result.outcome, "coalesced"); + } + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_relay_deliveries`).length, + count + 1, + ); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + assert.include((yield* Queue.take(launches)).initialMessage!.text, `>${count}<`); + const retry = yield* service.triggerWebhook(request(count)); + assert.equal(retry._tag === "accepted" && retry.outcome, "duplicate"); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + assert.equal((yield* service.list()).tasks[0]!.runCount, 1); + assert.equal(yield* Queue.size(launches), 0); + }), + { workers }, + ); + }, +); + +it.effect("failed windows release every member's replay key and relay claim", () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: "{{body.value}}", + schedule: { + type: "webhook", + dedupe: { + replayKey: "{{headers.delivery-id}}", + coalesceKey: "{{body.group}}", + coalesceWindowSeconds: 10, + }, + }, + }), + ); + const request = (id: string) => { + const bodyText = JSON.stringify({ group: "same", value: id }); + return requestFor(task, { + bodyText, + body: new TextEncoder().encode(bodyText), + headers: { "delivery-id": id }, + relayDeliveryId: id, + }); + }; + yield* service.triggerWebhook(request("A")); + for (let i = 0; i < 12; i++) yield* service.triggerWebhook(request(`B${i}`)); + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_relay_deliveries`).length, + 13, + ); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + yield* Queue.take(launches); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_replay_keys`).length, 0); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_relay_deliveries`).length, 0); + const retry = yield* service.triggerWebhook(request("B11")); + assert.equal(retry._tag === "accepted" && retry.outcome, "accepted"); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + assert.include((yield* Queue.take(launches)).initialMessage!.text, "B11"); + assert.equal((yield* service.list()).tasks[0]!.runCount, 2); + }), + { workers, failLaunches: { remaining: 1 } }, + ); +}); + +it.effect( + "recovery finishes failed-window claim cleanup without counting the attempt twice", + () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { + replayKey: "{{headers.delivery-id}}", + coalesceKey: "{{body}}", + coalesceWindowSeconds: 10, + }, + }, + }), + ); + const request = (id: string) => + requestFor(task, { headers: { "delivery-id": id }, relayDeliveryId: id }); + yield* service.triggerWebhook(request("A")); + yield* service.triggerWebhook(request("B")); + yield* sql`CREATE TRIGGER fail_claim_cleanup BEFORE DELETE ON scheduled_task_webhook_relay_deliveries + BEGIN SELECT RAISE(FAIL, 'cleanup unavailable'); END`; + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + yield* Queue.take(launches); + assert.equal((yield* service.list()).tasks[0]!.runCount, 1); + assert.equal( + (yield* sql<{ state: string }>`SELECT state FROM scheduled_task_webhook_pending`)[0]! + .state, + "failed", + ); + yield* sql`DROP TRIGGER fail_claim_cleanup`; + const restartedWorkers = new Map>(); + yield* withService( + ({ service: restarted, launches: restartedLaunches }) => + Effect.gen(function* () { + yield* drainPendingDispatch(restartedWorkers); + assert.equal(yield* Queue.size(restartedLaunches), 0); + assert.equal((yield* restarted.list()).tasks[0]!.runCount, 1); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_replay_keys`).length, + 0, + ); + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_relay_deliveries`).length, + 0, + ); + const retry = yield* restarted.triggerWebhook(request("B")); + assert.equal(retry._tag === "accepted" && retry.outcome, "accepted"); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(restartedWorkers); + yield* Queue.take(restartedLaunches); + assert.equal((yield* restarted.list()).tasks[0]!.runCount, 2); + }), + { sql, workers: restartedWorkers }, + ); + }), + { workers, failLaunches: { remaining: 1 } }, + ); + }, +); + +it.effect("dispatches an overdue window exactly once after its deadline passed while stopped", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const task = yield* withService( + ({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{body}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + yield* service.triggerWebhook(requestFor(task)); + assert.equal(yield* Queue.size(launches), 0); + return task; + }), + { sql, workers: new Map() }, + ); + // The first service scope is closed before the deadline advances. + yield* TestClock.adjust("30 seconds"); + const restartedWorkers = new Map>(); + yield* withService( + ({ service, launches }) => + Effect.gen(function* () { + yield* drainPendingDispatch(restartedWorkers); + yield* Queue.take(launches); + for (let i = 0; i < 3; i++) yield* restartedWorkers.get("webhook-coalescing")!; + assert.equal(yield* Queue.size(launches), 0); + assert.equal((yield* service.list()).tasks[0]!.runCount, 1); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + }), + { sql, workers: restartedWorkers }, + ); + const secondRestartWorkers = new Map>(); + yield* withService( + ({ service, launches }) => + Effect.gen(function* () { + yield* secondRestartWorkers.get("webhook-coalescing")!; + assert.equal(yield* Queue.size(launches), 0); + assert.equal( + (yield* service.list()).tasks.find((entry) => entry.id === task.id)!.runCount, + 1, + ); + }), + { sql, workers: secondRestartWorkers }, + ); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); + +it.effect("removes a window with a render defect and dispatches the task's next window", () => { + const workers = new Map>(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: "{{body.deep}}", + schedule: { + type: "webhook", + dedupe: { + replayKey: "{{headers.delivery-id}}", + coalesceKey: "{{headers.group}}", + coalesceWindowSeconds: 10, + }, + }, + }), + ); + const request = (id: string, bodyText: string) => + requestFor(task, { + bodyText, + body: new TextEncoder().encode(bodyText), + headers: { "delivery-id": id, group: id }, + relayDeliveryId: id, + }); + const bad = request( + "bad-render", + '{"deep":' + "[".repeat(20000) + "0" + "]".repeat(20000) + "}", + ); + assert.throws(() => renderWebhookPrompt(task.prompt, bad, "frame"), RangeError); + const accepted = yield* service.triggerWebhook(bad); + assert.equal(accepted._tag, "accepted"); + yield* service.triggerWebhook(request("good-render", '{"deep":"next window"}')); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + assert.include((yield* Queue.take(launches)).initialMessage!.text, "next window"); + assert.equal(yield* Queue.size(launches), 0); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_replay_keys WHERE delivery_id = 'delivery:relay:bad-render'`) + .length, + 0, + ); + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_relay_deliveries WHERE relay_delivery_id = 'bad-render'`) + .length, + 0, + ); + const failed = (yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: ScheduledTaskWebhookDeliveryId.make("delivery:relay:bad-render"), + acceptAnyOutcome: true, + })).delivery; + assert.equal(failed.outcome, "dispatch_failed"); + assert.equal(failed.error, "The pending webhook payload could not be prepared."); + yield* workers.get("webhook-coalescing")!; + assert.equal((yield* service.list()).tasks[0]!.runCount, 1); + }), + { workers }, ); +}); + +it.effect.each([false, true])( + "counts an interrupted immediate run beside an unrelated running window (corrupt task: %s)", + (corrupt) => { + const workers = new Map>(); + const completedLaunches = new Set(); + return Effect.gen(function* () { + const gate = yield* Deferred.make(); + yield* withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: "{{body.value}}", + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{headers.group}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + const window = yield* service.triggerWebhook( + requestFor(task, { headers: { group: "old" }, bodyText: '{"value":"old"}' }), + ); + yield* sql`CREATE TRIGGER fail_old_completion BEFORE UPDATE ON scheduled_tasks + WHEN NEW.last_run_status = 'succeeded' BEGIN SELECT RAISE(FAIL, 'completion unavailable'); END`; + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + yield* Queue.take(launches); + yield* sql`DROP TRIGGER fail_old_completion`; + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE state = 'running'`) + .length, + 1, + ); + const immediate = yield* service.triggerWebhook( + requestFor(task, { bodyText: '{"value":"immediate"}' }), + ); + yield* Queue.take(launches); + const [before] = yield* sql<{ + last_run_webhook_delivery_id: string; + model_selection_json: string; + run_count: number; + }>`SELECT last_run_webhook_delivery_id, model_selection_json, run_count FROM scheduled_tasks WHERE task_id = ${task.id}`; + assert.equal( + before!.last_run_webhook_delivery_id, + immediate._tag === "accepted" ? immediate.deliveryId : "", + ); + assert.notEqual( + before!.last_run_webhook_delivery_id, + window._tag === "accepted" ? window.deliveryId : "", + ); + assert.equal(before!.run_count, 0); + if (corrupt) + yield* sql`UPDATE scheduled_tasks SET model_selection_json = 'broken' WHERE task_id = ${task.id}`; + const restartedWorkers = new Map>(); + yield* withService( + ({ service: restarted, launches: recoveredLaunches }) => + Effect.gen(function* () { + const [recovered] = yield* sql<{ + run_count: number; + last_run_status: string; + }>`SELECT run_count, last_run_status FROM scheduled_tasks WHERE task_id = ${task.id}`; + assert.equal(recovered!.run_count, 1); + assert.equal(recovered!.last_run_status, "failed"); + if (corrupt) + yield* sql`UPDATE scheduled_tasks SET model_selection_json = ${before!.model_selection_json} WHERE task_id = ${task.id}`; + yield* drainPendingDispatch(restartedWorkers); + assert.equal(yield* Queue.size(recoveredLaunches), 0); + assert.equal((yield* restarted.list()).tasks[0]!.runCount, 2); + assert.equal( + (yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, + 0, + ); + yield* restartedWorkers.get("webhook-coalescing")!; + assert.equal((yield* restarted.list()).tasks[0]!.runCount, 2); + }), + { sql, workers: restartedWorkers, completedLaunches }, + ); + }), + { + workers, + completedLaunches, + gateForTask: (input) => + input.initialMessage?.text.includes(">immediate<") ? gate : undefined, + }, + ); + }); + }, +); -it.effect("counts each handled request by what happened to it", () => +it.effect("checks filters after the signature and max age, and runs only matching deliveries", () => withService(({ service, launches }) => Effect.gen(function* () { const { task } = yield* service.upsert( @@ -838,36 +1687,204 @@ it.effect("counts each handled request by what happened to it", () => header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=", - secret: "github-secret", + secret: "s3cret", }, + maxDeliveryAgeMinutes: 30, + filters: [ + { path: "headers.x-github-event", op: "equals", value: "pull_request" }, + { path: "body.action", op: "in", value: ["opened", "reopened"] }, + ], }, }), ); - const before = { - accepted: yield* deliveriesCounted("accepted", "direct"), - rejected: yield* deliveriesCounted("rejected_signature", "direct"), - notFound: yield* deliveriesCounted("not_found", "direct"), - relayAccepted: yield* deliveriesCounted("accepted", "relay"), - duplicate: yield* deliveriesCounted("duplicate", "relay"), - }; - const signed = { - "content-type": "application/json", - "x-hub-signature-256": signatureFor("github-secret"), + const delivery = ( + event: string, + action: string, + options: { readonly signed?: boolean; readonly receivedAt?: string } = {}, + ) => { + const body = new TextEncoder().encode( + JSON.stringify({ action, pull_request: { url: "https://github.com/org/repo/pull/45" } }), + ); + const signature = `sha256=${NodeCrypto.createHmac("sha256", "s3cret").update(body).digest("hex")}`; + return requestFor(task, { + headers: { + "content-type": "application/json", + "x-github-event": event, + ...(options.signed === false ? {} : { "x-hub-signature-256": signature }), + }, + body, + bodyText: new TextDecoder().decode(body), + ...(options.receivedAt === undefined + ? {} + : { relayDeliveryId: "old", receivedAt: options.receivedAt }), + }); }; - yield* service.triggerWebhook(requestFor(task, { headers: signed })); - yield* Queue.take(launches); - yield* service.triggerWebhook(requestFor(task)); - yield* service.triggerWebhook(requestFor(task, { token: "wrong" })); - const relayed = requestFor(task, { headers: signed, relayDeliveryId: "relay-1" }); - yield* service.triggerWebhook(relayed); + const now = yield* DateTime.now; + const old = DateTime.formatIso(DateTime.subtract(now, { minutes: 31 })); + + // A request failing a filter is still refused first for its signature or age. + const unsigned = yield* service.triggerWebhook(delivery("push", "opened", { signed: false })); + assert.equal(unsigned._tag, "rejected_signature"); + const tooOld = yield* service.triggerWebhook(delivery("push", "opened", { receivedAt: old })); + assert.equal(tooOld._tag, "expired"); + + const wrongEvent = yield* service.triggerWebhook(delivery("push", "opened")); + const wrongAction = yield* service.triggerWebhook(delivery("pull_request", "closed")); + assert.deepInclude(wrongEvent, { _tag: "accepted", outcome: "filtered" }); + assert.deepInclude(wrongAction, { _tag: "accepted", outcome: "filtered" }); + assert.equal(yield* Queue.size(launches), 0); + const [listed] = (yield* service.list()).tasks; + assert.equal(listed?.runCount, 0); + assert.equal(listed?.lastRunStatus, "never"); + + const matched = yield* service.triggerWebhook(delivery("pull_request", "opened")); + assert.deepInclude(matched, { _tag: "accepted", outcome: "accepted" }); + assert.include((yield* Queue.take(launches)).initialMessage?.text ?? "", "pull/45"); + + const deliveries = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries; + const filtered = deliveries + .filter((entry) => entry.outcome === "filtered") + .map((entry) => [entry.signatureVerified, entry.error]); + assert.sameDeepMembers(filtered, [ + [true, "Filter 1 (headers.x-github-event) did not match."], + [true, "Filter 2 (body.action) did not match."], + ]); + }), + ), +); + +const pullRequestFilterInput = () => + webhookTaskInput({ + schedule: { + type: "webhook", + filters: [{ path: "headers.x-github-event", op: "equals", value: "pull_request" }], + }, + }); +const githubEvent = (event: string) => ({ + headers: { "content-type": "application/json", "x-github-event": event }, +}); + +it.effect("a filtered relay delivery releases its claim, so a redelivery is evaluated again", () => + withService(({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* pullRequestFilterInput()); + const held = { relayDeliveryId: "relay-filtered" }; + const first = yield* service.triggerWebhook( + requestFor(task, { ...held, ...githubEvent("push") }), + ); + const again = yield* service.triggerWebhook( + requestFor(task, { ...held, ...githubEvent("push") }), + ); + assert.deepInclude(first, { _tag: "accepted", outcome: "filtered" }); + assert.deepInclude(again, { _tag: "accepted", outcome: "filtered" }); + const ran = yield* service.triggerWebhook( + requestFor(task, { ...held, ...githubEvent("pull_request") }), + ); + assert.deepInclude(ran, { _tag: "accepted", outcome: "accepted" }); yield* Queue.take(launches); - yield* service.triggerWebhook(relayed); + const replayed = yield* service.triggerWebhook( + requestFor(task, { ...held, ...githubEvent("pull_request") }), + ); + assert.deepInclude(replayed, { _tag: "accepted", outcome: "duplicate" }); + }), + ), +); - assert.equal((yield* deliveriesCounted("accepted", "direct")) - before.accepted, 1); - assert.equal((yield* deliveriesCounted("rejected_signature", "direct")) - before.rejected, 1); - assert.equal((yield* deliveriesCounted("not_found", "direct")) - before.notFound, 1); - assert.equal((yield* deliveriesCounted("accepted", "relay")) - before.relayAccepted, 1); - assert.equal((yield* deliveriesCounted("duplicate", "relay")) - before.duplicate, 1); +it.effect("leaves filtered rows out of the list for clients that only decode older outcomes", () => + withService(({ service, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* pullRequestFilterInput()); + yield* service.triggerWebhook(requestFor(task, githubEvent("push"))); + yield* service.triggerWebhook(requestFor(task, githubEvent("pull_request"))); + yield* Queue.take(launches); + const legacy = (yield* service.listWebhookDeliveries({ id: task.id })).deliveries; + assert.deepEqual( + legacy.map((delivery) => delivery.outcome), + ["accepted"], + ); + const current = (yield* service.listWebhookDeliveries({ + id: task.id, + acceptAnyOutcome: true, + })).deliveries; + assert.sameMembers( + current.map((delivery) => delivery.outcome), + ["accepted", "filtered"], + ); }), ), ); + +it.effect("filters run before replay and coalescing without claiming ignored deliveries", () => { + const workers = new Map>(); + return withService( + ({ service, launches, sql }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + prompt: "{{body.value}}", + schedule: { + type: "webhook", + filters: [{ path: "body.run", op: "equals", value: "true" }], + dedupe: { + replayKey: "{{headers.delivery-id}}", + coalesceKey: "{{body.group}}", + coalesceWindowSeconds: 10, + }, + }, + }), + ); + const request = (id: string, run: boolean, value: string) => { + const bodyText = JSON.stringify({ run, group: "B", value }); + return requestFor(task, { + headers: { "delivery-id": id }, + bodyText, + body: new TextEncoder().encode(bodyText), + relayDeliveryId: id, + }); + }; + const ignored = yield* service.triggerWebhook(request("A", false, "ignored")); + assert.deepInclude(ignored, { _tag: "accepted", outcome: "filtered" }); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_replay_keys`).length, 0); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`).length, 0); + assert.equal((yield* sql`SELECT 1 FROM scheduled_task_webhook_relay_deliveries`).length, 0); + const filteredId = ignored._tag === "accepted" ? ignored.deliveryId : assert.fail(); + const oldClient = yield* service + .getWebhookDelivery({ id: task.id, deliveryId: filteredId }) + .pipe(Effect.result); + assert.equal(oldClient._tag, "Failure"); + const currentClient = yield* service.getWebhookDelivery({ + id: task.id, + deliveryId: filteredId, + acceptAnyOutcome: true, + }); + assert.equal(currentClient.delivery.outcome, "filtered"); + assert.deepInclude(yield* service.triggerWebhook(request("A", true, "first")), { + _tag: "accepted", + outcome: "accepted", + }); + assert.deepInclude( + yield* service.triggerWebhook({ + ...request("A", false, "ignored replay"), + relayDeliveryId: "ignored-replay", + }), + { _tag: "accepted", outcome: "filtered" }, + ); + assert.deepInclude(yield* service.triggerWebhook(request("B", false, "ignored update")), { + _tag: "accepted", + outcome: "filtered", + }); + assert.deepInclude(yield* service.triggerWebhook(request("B", true, "latest")), { + _tag: "accepted", + outcome: "coalesced", + }); + yield* TestClock.adjust("10 seconds"); + yield* drainPendingDispatch(workers); + assert.include((yield* Queue.take(launches)).initialMessage!.text, "latest"); + assert.equal(yield* Queue.size(launches), 0); + }), + { workers }, + ); +}); diff --git a/apps/server/src/scheduledTasks/webhookDedupe.ts b/apps/server/src/scheduledTasks/webhookDedupe.ts new file mode 100644 index 0000000000000..21d40b25ac5ed --- /dev/null +++ b/apps/server/src/scheduledTasks/webhookDedupe.ts @@ -0,0 +1,128 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Keys need a deterministic digest, not random bytes. +import * as NodeCrypto from "node:crypto"; +import { ScheduledTask, ScheduledTaskError } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import { renderWebhookPrompt, type WebhookRequest } from "./webhookTemplate.ts"; + +function key(template: string | undefined, request: WebhookRequest): string { + if (template === undefined) return ""; + const rendered = renderWebhookPrompt(template, request, "", true); + return rendered.missing.length > 0 || rendered.prompt === "" + ? "" + : NodeCrypto.createHash("sha256").update(rendered.prompt).digest("hex"); +} + +export const releaseWebhookReplay = Effect.fn("ScheduledTaskService.releaseWebhookReplay")( + function* (deliveryId: string) { + const sql = yield* SqlClient.SqlClient; + yield* sql`DELETE FROM scheduled_task_webhook_replay_keys WHERE delivery_id = ${deliveryId}`; + }, +); + +const hasReplayKey = Effect.fn(function* (taskId: string, replayKey: string, now: number) { + const sql = yield* SqlClient.SqlClient; + return ( + replayKey !== "" && + (yield* sql`SELECT 1 FROM scheduled_task_webhook_replay_keys + WHERE task_id = ${taskId} AND replay_key = ${replayKey} AND expires_at > ${now}`).length > 0 + ); +}); +const claimReplayKey = Effect.fn(function* ( + taskId: string, + replayKey: string, + deliveryId: string, + now: number, +) { + if (replayKey === "") return; + const sql = yield* SqlClient.SqlClient; + yield* sql`DELETE FROM scheduled_task_webhook_replay_keys WHERE expires_at <= ${now}`; + yield* sql`INSERT INTO scheduled_task_webhook_replay_keys (task_id, replay_key, delivery_id, expires_at) + VALUES (${taskId}, ${replayKey}, ${deliveryId}, ${now + 7 * 24 * 60 * 60 * 1000})`; +}); + +export const acceptWebhookDedupe = Effect.fn("ScheduledTaskService.acceptWebhookDedupe")(function* ( + task: ScheduledTask, + request: WebhookRequest, + deliveryId: string, + now: number, + reserve: Effect.Effect, + reserveCoalescedLog: Effect.Effect, + checkCapacity: Effect.Effect, + replaceDeliveryRequest: (ownerId: string) => Effect.Effect, +) { + const sql = yield* SqlClient.SqlClient; + const dedupe = task.schedule.type === "webhook" ? task.schedule.dedupe : undefined; + if (dedupe === undefined) return "run" as const; + const replayKey = key(dedupe.replayKey, request); + if (yield* hasReplayKey(task.id, replayKey, now)) return "duplicate" as const; + const coalesceKey = key(dedupe.coalesceKey, request); + if (coalesceKey === "") return "run" as const; + const pending = yield* sql<{ + delivery_id: string; + }>`SELECT delivery_id FROM scheduled_task_webhook_pending + WHERE task_id = ${task.id} AND coalesce_key = ${coalesceKey} AND state = 'pending' AND due_at > ${now}`; + const logCoalesced = pending.length > 0 ? yield* reserveCoalescedLog : true; + if (pending.length === 0) { + yield* checkCapacity; + yield* reserve; + } + // Coalesced requests retain their validation slot, bounding writes without dropping accepted payloads. + yield* claimReplayKey(task.id, replayKey, pending[0]?.delivery_id ?? deliveryId, now); + const requestJson = yield* encodePendingRequest({ + method: request.method, + path: request.path, + query: request.query, + headers: request.headers, + bodyText: request.bodyText, + }); + if (pending.length > 0) { + yield* sql`UPDATE scheduled_task_webhook_pending SET request_json = ${requestJson}, + delivery_ids_json = json_insert(delivery_ids_json, '$[#]', ${deliveryId}) WHERE delivery_id = ${pending[0]!.delivery_id}`; + yield* replaceDeliveryRequest(pending[0]!.delivery_id); + return logCoalesced ? ("coalesced" as const) : ("coalesced_unlogged" as const); + } + // Expired windows are immutable, even if the scheduler has not dispatched them yet. + yield* sql`UPDATE scheduled_task_webhook_pending SET state = 'dispatching' + WHERE task_id = ${task.id} AND coalesce_key = ${coalesceKey} AND state = 'pending' AND due_at <= ${now}`; + yield* sql`INSERT INTO scheduled_task_webhook_pending (delivery_id, task_id, coalesce_key, due_at, task_json, request_json, delivery_ids_json) + VALUES (${deliveryId}, ${task.id}, ${coalesceKey}, ${now + (dedupe.coalesceWindowSeconds ?? 120) * 1000}, ${yield* encodePendingTask(task)}, ${requestJson}, json_array(${deliveryId}))`; + return "pending" as const; +}); + +export const acceptImmediateWebhookDedupe = Effect.fn( + "ScheduledTaskService.acceptImmediateWebhookDedupe", +)(function* ( + task: ScheduledTask, + request: WebhookRequest, + deliveryId: string, + now: number, + reserve: Effect.Effect, +) { + const replayKey = key( + task.schedule.type === "webhook" ? task.schedule.dedupe?.replayKey : undefined, + request, + ); + if (yield* hasReplayKey(task.id, replayKey, now)) return "duplicate" as const; + yield* reserve; + yield* claimReplayKey(task.id, replayKey, deliveryId, now); + return "run" as const; +}); + +const PendingTaskJson = Schema.fromJsonString(ScheduledTask); +const encodePendingTask = Schema.encodeEffect(PendingTaskJson); +export const decodePendingTask = Schema.decodeUnknownEffect(PendingTaskJson); +const PendingRequestJson = Schema.fromJsonString( + Schema.Struct({ + method: Schema.String, + path: Schema.String, + query: Schema.String, + headers: Schema.Record(Schema.String, Schema.String), + bodyText: Schema.String, + }), +); +const encodePendingRequest = Schema.encodeEffect(PendingRequestJson); +export const decodePendingRequest = Schema.decodeUnknownEffect(PendingRequestJson); +export const dedupeError = (cause: unknown) => + new ScheduledTaskError({ message: "Could not persist webhook dedupe state.", cause }); diff --git a/apps/server/src/scheduledTasks/webhookFilter.test.ts b/apps/server/src/scheduledTasks/webhookFilter.test.ts new file mode 100644 index 0000000000000..1194a1aed5177 --- /dev/null +++ b/apps/server/src/scheduledTasks/webhookFilter.test.ts @@ -0,0 +1,95 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { findFailedWebhookFilter } from "./webhookFilter.ts"; +import type { WebhookRequest } from "./webhookTemplate.ts"; + +const issueComment: WebhookRequest = { + method: "POST", + path: "/api/hooks/task-1", + query: "", + headers: { "content-type": "application/json", "x-github-event": "issue_comment" }, + bodyText: JSON.stringify({ + action: "created", + issue: { number: 7, labels: [{ name: "bug" }, { name: "needs more info" }], assignees: [] }, + comment: { user: { login: "reporter", type: "User" } }, + }), +}; + +describe("findFailedWebhookFilter", () => { + it("matches a wildcard path when any element matches", () => { + assert.isNull( + findFailedWebhookFilter( + [ + { path: "body.issue.labels[].name", op: "equals", value: "needs more info" }, + { path: "body.issue.labels[].name", op: "in", value: ["needs more info", "triage"] }, + { path: "body.issue.labels[].name", op: "startsWith", value: "needs" }, + { path: "body.issue.labels[].name", op: "exists" }, + ], + issueComment, + ), + ); + assert.deepEqual( + findFailedWebhookFilter( + [{ path: "body.issue.labels[].name", op: "equals", value: "wontfix" }], + issueComment, + ), + { index: 0, path: "body.issue.labels[].name" }, + ); + }); + + it("fails notEquals on a wildcard path when any element equals the value", () => { + assert.deepEqual( + findFailedWebhookFilter( + [{ path: "body.issue.labels[].name", op: "notEquals", value: "bug" }], + issueComment, + ), + { index: 0, path: "body.issue.labels[].name" }, + ); + assert.isNull( + findFailedWebhookFilter( + [{ path: "body.issue.labels[].name", op: "notEquals", value: "wontfix" }], + issueComment, + ), + ); + }); + + it("treats an empty or missing wildcard list as nothing to match", () => { + assert.deepEqual( + findFailedWebhookFilter( + [{ path: "body.issue.assignees[].login", op: "exists" }], + issueComment, + ), + { index: 0, path: "body.issue.assignees[].login" }, + ); + assert.isNull( + findFailedWebhookFilter( + [{ path: "body.issue.assignees[].login", op: "notEquals", value: "anyone" }], + issueComment, + ), + ); + assert.deepEqual( + findFailedWebhookFilter([{ path: "body.issue.number[].x", op: "exists" }], issueComment), + { index: 0, path: "body.issue.number[].x" }, + ); + }); + + it("still compares scalars without a wildcard", () => { + assert.isNull( + findFailedWebhookFilter( + [ + { path: "body.action", op: "equals", value: "created" }, + { path: "body.comment.user.type", op: "notEquals", value: "Bot" }, + ], + issueComment, + ), + ); + // A list without a wildcard in the path only satisfies exists. + assert.deepEqual( + findFailedWebhookFilter( + [{ path: "body.issue.labels", op: "equals", value: "bug" }], + issueComment, + ), + { index: 0, path: "body.issue.labels" }, + ); + }); +}); diff --git a/apps/server/src/scheduledTasks/webhookFilter.ts b/apps/server/src/scheduledTasks/webhookFilter.ts new file mode 100644 index 0000000000000..882f300364288 --- /dev/null +++ b/apps/server/src/scheduledTasks/webhookFilter.ts @@ -0,0 +1,65 @@ +import type { ScheduledTaskWebhookFilter } from "@t3tools/contracts"; + +import { webhookExpressionResolver, type WebhookRequest } from "./webhookTemplate.ts"; + +export interface FailedWebhookFilter { + readonly index: number; + readonly path: string; +} + +function scalarText(value: unknown): string | undefined { + if (typeof value === "string") return value; + if (typeof value === "number" || typeof value === "boolean") return String(value); + return undefined; +} + +function matchesScalar(filter: ScheduledTaskWebhookFilter, text: string): boolean { + switch (filter.op) { + case "equals": + return text === filter.value; + case "notEquals": + return text !== filter.value; + case "in": + return filter.value.includes(text); + case "startsWith": + return text.startsWith(filter.value); + case "exists": + return true; + } +} + +/** + * Placeholders render null as missing, so filters treat it the same way. A + * path with a `[]` wildcard resolves to a list: `equals`, `in` and + * `startsWith` match when any element does, `notEquals` only when none equals + * the value, and `exists` when the list has an element. + */ +function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean { + if (Array.isArray(value) && /\[\]/.test(filter.path)) { + const texts = value.map(scalarText).filter((text): text is string => text !== undefined); + if (filter.op === "notEquals") return texts.every((text) => text !== filter.value); + return texts.some((text) => matchesScalar(filter, text)); + } + if (filter.op === "exists") return value !== undefined && value !== null; + const text = scalarText(value); + if (text === undefined) return false; + return matchesScalar(filter, text); +} + +/** The first filter the request fails, or null when every filter matches. */ +export function findFailedWebhookFilter( + filters: ReadonlyArray, + request: WebhookRequest, +): FailedWebhookFilter | null { + if (filters.length === 0) return null; + const resolve = webhookExpressionResolver(request); + for (const [index, filter] of filters.entries()) { + if (!matchesWebhookFilter(filter, resolve(filter.path))) return { index, path: filter.path }; + } + return null; +} + +/** Filters are numbered from 1, in the order the settings form lists them. */ +export function describeFailedWebhookFilter(failed: FailedWebhookFilter): string { + return `Filter ${failed.index + 1} (${failed.path}) did not match.`; +} diff --git a/apps/server/src/scheduledTasks/webhookRoute.test.ts b/apps/server/src/scheduledTasks/webhookRoute.test.ts index 31261660c6235..5ef605be0ab42 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.test.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.test.ts @@ -113,35 +113,6 @@ const post = ( ) => new Request(`http://env.local${path}`, { method: "POST", body, headers }); describe("webhook route", () => { - it("passes the raw request to the service and answers 202 with the delivery id", async () => { - let received: WebhookTriggerRequest | undefined; - const { handler, dispose } = handlerFor((request) => { - received = request; - return Effect.succeed({ - _tag: "accepted", - deliveryId: ScheduledTaskWebhookDeliveryId.make("delivery:1"), - outcome: "accepted", - }); - }); - try { - const response = await handler( - post("/api/hooks/scheduled-task%3Ahook/tok?x=1", '{"a":1}', { - "Content-Type": "application/json", - "X-GitHub-Event": "push", - }), - ); - expect(response.status).toBe(202); - expect(await response.json()).toEqual({ deliveryId: "delivery:1" }); - expect(received?.hookId).toBe("scheduled-task:hook"); - expect(received?.token).toBe("tok"); - expect(received?.query).toBe("x=1"); - expect(received?.headers["x-github-event"]).toBe("push"); - expect(received?.bodyText).toBe('{"a":1}'); - } finally { - await dispose(); - } - }); - it.live("trusts the relay's delivery id and receive time only with its signed proof", () => Effect.gen(function* () { const received: Array = []; @@ -222,6 +193,7 @@ describe("webhook route", () => { [{ _tag: "accepted", deliveryId, outcome: "accepted" }, 202, "accepted"], [{ _tag: "accepted", deliveryId, outcome: "duplicate" }, 202, "duplicate"], [{ _tag: "accepted", deliveryId, outcome: "prompt_too_long" }, 202, "prompt_too_long"], + [{ _tag: "accepted", deliveryId, outcome: "filtered" }, 202, "filtered"], [{ _tag: "not_found" }, 404, "not_found"], [{ _tag: "rejected_signature" }, 401, "rejected_signature"], [{ _tag: "disabled" }, 409, "disabled"], @@ -235,39 +207,13 @@ describe("webhook route", () => { const response = await handler(post("/api/hooks/id/tok", "{}")); expect(response.status).toBe(status); expect(response.headers.get("x-t3-hook-outcome")).toBe(outcome); + if (status === 429) expect(await response.json()).toEqual({ error: outcome }); } finally { await dispose(); } } }); - it.live("joins the relay's trace only for requests the relay forwarded", () => - Effect.gen(function* () { - const parents: Array = []; - const { handler, dispose } = handlerFor(() => - Effect.gen(function* () { - const span = yield* Effect.currentParentSpan.pipe(Effect.option); - parents.push(span._tag === "Some" ? span.value.traceId : undefined); - return { _tag: "not_found" } as const; - }), - ); - const send = (headers: Record) => - Effect.promise(() => handler(post("/api/hooks/id/tok", "{}", headers))); - const traceparent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; - const receivedAt = "2026-10-04T10:00:00.000Z"; - const relayHeaders = { - "x-t3-relay-delivery-id": "relay-1", - "x-t3-relay-received-at": receivedAt, - }; - const proof = yield* relayProof({ deliveryId: "relay-1", receivedAt, hookId: "id" }); - yield* send({ ...relayHeaders, traceparent, "x-t3-relay-delivery": proof }); - yield* send({ ...relayHeaders, traceparent }); - yield* send({ traceparent }); - yield* Effect.promise(() => dispose()); - expect(parents).toEqual(["0af7651916cd43dd8448eb211c80319c", undefined, undefined]); - }), - ); - it("rejects oversized bodies and malformed paths before reaching the service", async () => { let calls = 0; const { handler, dispose } = handlerFor(() => { diff --git a/apps/server/src/scheduledTasks/webhookRoute.ts b/apps/server/src/scheduledTasks/webhookRoute.ts index aa1b25a6351c0..e43d9d81c930d 100644 --- a/apps/server/src/scheduledTasks/webhookRoute.ts +++ b/apps/server/src/scheduledTasks/webhookRoute.ts @@ -17,7 +17,7 @@ import * as ScheduledTaskService from "./ScheduledTaskService.ts"; /** The relay enforces the same cap. */ export const WEBHOOK_MAX_BODY_BYTES = 1024 * 1024; -/** Response header naming what happened to the request; the relay records it. */ +// The relay records this outcome header. const WEBHOOK_OUTCOME_HEADER = "x-t3-hook-outcome"; const json = (status: number, body: Record, outcome: string) => @@ -33,98 +33,98 @@ export const layer = HttpApiBuilder.group( * The endpoint is raw so the signature is checked over the exact body * bytes; the service checks the token and signature. */ - const handler = ({ + // Only verified relay deliveries join a trace; direct requests keep their existing context. + const handler = Effect.fnUntraced(function* ({ params, request, }: { readonly params: { readonly hookId: string; readonly token: string }; readonly request: HttpServerRequest.HttpServerRequest; - }) => - Effect.gen(function* () { - const contentLength = Number(request.headers["content-length"] ?? "0"); - if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) { - return json(413, { error: "body_too_large" }, "body_too_large"); - } - // Chunked requests carry no content-length, so the reader itself is capped. - const body = yield* request.arrayBuffer.pipe( - Effect.map((buffer) => new Uint8Array(buffer)), - Effect.provideService( - HttpIncomingMessage.MaxBodySize, - ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES), - ), - Effect.option, - ); - const tooLarge = (error: string) => - Metrics.increment(Metrics.webhookDeliveriesTotal, { - outcome: "body_too_large", - source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct", - }).pipe(Effect.as(json(413, { error }, "body_too_large"))); - if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable"); - if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) { - return yield* tooLarge("body_too_large"); - } + }) { + const contentLength = Number(request.headers["content-length"] ?? "0"); + if (!Number.isFinite(contentLength) || contentLength > WEBHOOK_MAX_BODY_BYTES) { + return json(413, { error: "body_too_large" }, "body_too_large"); + } + // Chunked requests carry no content-length, so the reader itself is capped. + const body = yield* request.arrayBuffer.pipe( + Effect.map((buffer) => new Uint8Array(buffer)), + Effect.provideService( + HttpIncomingMessage.MaxBodySize, + ByteSize.bytes(WEBHOOK_MAX_BODY_BYTES), + ), + Effect.option, + ); + const tooLarge = (error: string) => + Metrics.increment(Metrics.webhookDeliveriesTotal, { + outcome: "body_too_large", + source: request.headers["x-t3-relay-delivery-id"] ? "relay" : "direct", + }).pipe(Effect.as(json(413, { error }, "body_too_large"))); + if (Option.isNone(body)) return yield* tooLarge("body_too_large_or_unreadable"); + if (body.value.byteLength > WEBHOOK_MAX_BODY_BYTES) { + return yield* tooLarge("body_too_large"); + } - const headers: Record = {}; - for (const [name, value] of Object.entries(request.headers)) { - if (typeof value === "string") headers[name.toLowerCase()] = value; - } - const queryIndex = request.url.indexOf("?"); - // The relay's delivery id and receive time count only with its signed - // proof; the URL can also be called directly. The receive time matters - // for requests the relay held while we were offline. - const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId }); - const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined; - const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined; + const headers: Record = {}; + for (const [name, value] of Object.entries(request.headers)) { + if (typeof value === "string") headers[name.toLowerCase()] = value; + } + const queryIndex = request.url.indexOf("?"); + // The relay's delivery id and receive time count only with its signed + // proof; the URL can also be called directly. The receive time matters + // for requests the relay held while we were offline. + const relay = yield* relayDeliveryProof.verify({ headers, hookId: params.hookId }); + const relayDeliveryId = Option.isSome(relay) ? relay.value.deliveryId : undefined; + const relayReceivedAt = Option.isSome(relay) ? relay.value.receivedAt : undefined; - // A relay delivery joins the relay's trace, and goes to the T3 Connect - // tracer with it. Anyone else's traceparent is never trusted. - const relayParent = Option.isSome(relay) - ? HttpTraceContext.fromHeaders(request.headers) - : Option.none(); - const result = yield* scheduledTasks - .triggerWebhook({ - hookId: params.hookId, - token: params.token, - method: request.method, - path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`, - query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1), - headers, - body: body.value, - bodyText: new TextDecoder().decode(body.value), - ...(relayDeliveryId ? { relayDeliveryId } : {}), - ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}), - }) - .pipe( - Option.isSome(relayParent) - ? (effect) => - effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing) - : (effect) => effect, - Effect.catchCause((cause) => - Effect.logWarning("Webhook delivery failed").pipe( - Effect.annotateLogs({ hookId: params.hookId }), - Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })), - Effect.as({ _tag: "error" as const }), - ), + // A relay delivery joins the relay's trace, and goes to the T3 Connect + // tracer with it. Anyone else's traceparent is never trusted. + const relayParent = Option.isSome(relay) + ? HttpTraceContext.fromHeaders(request.headers) + : Option.none(); + const result = yield* scheduledTasks + .triggerWebhook({ + hookId: params.hookId, + token: params.token, + method: request.method, + path: `${ScheduledTaskService.WEBHOOK_ROUTE_PREFIX}/${encodeURIComponent(params.hookId)}`, + query: queryIndex === -1 ? "" : request.url.slice(queryIndex + 1), + headers, + body: body.value, + bodyText: new TextDecoder().decode(body.value), + ...(relayDeliveryId ? { relayDeliveryId } : {}), + ...(relayReceivedAt ? { receivedAt: relayReceivedAt } : {}), + }) + .pipe( + Option.isSome(relayParent) + ? (effect) => + effect.pipe(Effect.withParentSpan(relayParent.value), withRelayClientTracing) + : (effect) => effect, + Effect.catchCause((cause) => + Effect.logWarning("Webhook delivery failed").pipe( + Effect.annotateLogs({ hookId: params.hookId }), + Effect.andThen(Effect.logDebug("Webhook delivery failure cause", { cause })), + Effect.as({ _tag: "error" as const }), ), - ); + ), + ); - switch (result._tag) { - case "accepted": - return json(202, { deliveryId: result.deliveryId }, result.outcome); - case "not_found": - return json(404, { error: "hook_not_found" }, "not_found"); - case "rejected_signature": - return json(401, { error: "invalid_signature" }, "rejected_signature"); - case "disabled": - return json(409, { error: "hook_disabled" }, "disabled"); - case "rate_limited": - return json(429, { error: "rate_limited" }, result.outcome); - case "expired": - return json(410, { error: "delivery_too_old" }, "expired"); - case "error": - return json(500, { error: "internal_error" }, "error"); - } - }); + switch (result._tag) { + case "accepted": + return json(202, { deliveryId: result.deliveryId }, result.outcome); + case "not_found": + return json(404, { error: "hook_not_found" }, "not_found"); + case "rejected_signature": + return json(401, { error: "invalid_signature" }, "rejected_signature"); + case "disabled": + return json(409, { error: "hook_disabled" }, "disabled"); + case "rate_limited": + return json(429, { error: result.outcome }, result.outcome); + case "expired": + return json(410, { error: "delivery_too_old" }, "expired"); + case "error": + return json(500, { error: "internal_error" }, "error"); + } + }); return handlers .handleRaw("webhookPost", handler) .handleRaw("webhookPut", handler) diff --git a/apps/server/src/scheduledTasks/webhookTemplate.test.ts b/apps/server/src/scheduledTasks/webhookTemplate.test.ts index 6f8f3474fb51c..eaee34f52da39 100644 --- a/apps/server/src/scheduledTasks/webhookTemplate.test.ts +++ b/apps/server/src/scheduledTasks/webhookTemplate.test.ts @@ -54,7 +54,6 @@ describe("renderWebhookPrompt", () => { { ...githubPullRequest, bodyText: JSON.stringify({ text }) }, "id", ); - // The adapters' pattern finds only the template's own mention. const mentions = [...rendered.prompt.matchAll(SKILL_MENTION_PATTERN)].map((match) => match[2]); assert.deepEqual(mentions, ["review"]); // Codex and Pi read `$name` after any character, digits included. @@ -77,34 +76,6 @@ describe("renderWebhookPrompt", () => { assert.deepEqual(collectComposerContextReferences(rendered.prompt), []); }); - it("reads headers case-insensitively, query parameters and array indexes", () => { - const rendered = renderWebhookPrompt( - "{{ headers.X-GitHub-Event }} #{{body.pull_request.number}} {{body.pull_request.labels.0}} {{query.source}}", - githubPullRequest, - "id", - ); - assert.equal( - rendered.prompt, - `pull_request #45 bug github${NOTE}`, - ); - }); - - it("renders objects as JSON and the raw body and request on request", () => { - const rendered = renderWebhookPrompt( - "{{body.pull_request.labels}}|{{body}}", - githubPullRequest, - "id", - ); - assert.equal( - rendered.prompt, - `[\n "bug"\n]|${githubPullRequest.bodyText}${NOTE}`, - ); - const request = renderWebhookPrompt("{{request}}", githubPullRequest, "id").prompt; - assert.isTrue(request.startsWith("POST /api/hooks/task-1?source=github\n")); - assert.include(request, "x-github-event: pull_request"); - assert.isTrue(request.endsWith(`${githubPullRequest.bodyText}${NOTE}`)); - }); - it("renders missing fields empty and reports them once", () => { const rendered = renderWebhookPrompt( "a={{body.nope}} b={{body.nope}} c={{headers.x-missing}} d={{unknown}}", @@ -115,22 +86,6 @@ describe("renderWebhookPrompt", () => { assert.deepEqual(rendered.missing, ["body.nope", "headers.x-missing", "unknown"]); }); - it("leaves empty values unframed and does not report them missing", () => { - const rendered = renderWebhookPrompt("{{body}}", { ...githubPullRequest, bodyText: "" }, "id"); - assert.equal(rendered.prompt, ""); - assert.deepEqual(rendered.missing, []); - }); - - it("trims placeholder whitespace before resolving and reporting missing fields", () => { - const rendered = renderWebhookPrompt( - "{{\tbody.action\n}}|{{ body.nope }}|{{\nbody.nope\t}}|{{ \t\n }}", - githubPullRequest, - "id", - ); - assert.equal(rendered.prompt, `opened|||${NOTE}`); - assert.deepEqual(rendered.missing, ["body.nope", ""]); - }); - it("preserves unclosed whitespace-heavy placeholders and resolves later valid ones", () => { const unfinished = `Notify {{${" ".repeat(1024)}body`; const rendered = renderWebhookPrompt( @@ -209,6 +164,23 @@ describe("renderWebhookPrompt", () => { ); }); + it("renders a [] wildcard as the list of matching values", () => { + const rendered = renderWebhookPrompt( + "Labels: {{body.pull_request.labels[]}} Names: {{body.reviewers[].login}}", + { + ...githubPullRequest, + bodyText: JSON.stringify({ + pull_request: { labels: ["bug", "ui"] }, + reviewers: [{ login: "ada" }, { name: "no login" }, { login: "bob" }], + }), + }, + "id", + true, + ); + assert.equal(rendered.prompt, 'Labels: [\n "bug",\n "ui"\n] Names: [\n "ada",\n "bob"\n]'); + assert.deepEqual(rendered.missing, []); + }); + it("does not resolve inherited object properties", () => { const rendered = renderWebhookPrompt( "{{body.constructor}}{{body.__proto__}}{{headers.constructor}}{{headers.__proto__}}", diff --git a/apps/server/src/scheduledTasks/webhookTemplate.ts b/apps/server/src/scheduledTasks/webhookTemplate.ts index b129704f0abe3..fc43dbff921ed 100644 --- a/apps/server/src/scheduledTasks/webhookTemplate.ts +++ b/apps/server/src/scheduledTasks/webhookTemplate.ts @@ -1,14 +1,5 @@ -/** - * Anyone who can call the URL chooses these values, so each one is wrapped in - * `` tags and a closing note marks the tagged text as - * untrusted request data. The caller picks a fresh random ID per request, so a - * request can't close its own frame. Mentions inside a value are broken so - * they never act; the template's own mentions still do. - * - * Credential-looking headers and query parameters are redacted wherever the - * whole set renders (`{{request}}`, `{{headers}}`, `{{query}}`), as in the - * delivery log. Naming one (`{{headers.authorization}}`) gives its raw value. - */ +// Frame untrusted values with unpredictable per-request tags and break their mentions, preserving template mentions. +// Whole-set placeholders redact credentials; named placeholders return raw values. export interface WebhookRequest { readonly method: string; @@ -56,17 +47,8 @@ export function redactQuery(query: string): string { // Trim after matching so unclosed placeholders cannot backtrack over whitespace partitions. const PLACEHOLDER = /\{\{([^{}]*)\}\}/g; -/** - * Syntax an adapter or provider CLI may act on before the model reads the - * prompt: `$name` skill mentions (any currency sign, after any character in - * Codex and Pi), `@` file, agent and plugin mentions (after punctuation or - * letters in some CLIs), a `/name` command word mid-text, and `t3-context:` - * links. A word joiner goes after every currency sign and `@`, after a `/` - * that starts a single-segment word, and inside the `t3-context` scheme and - * any `webhook-data` name, so a value can't forge a frame tag. - * Checked against Claude Code 2.1.296, Codex 0.162.1, Pi 1.2.0 and dsh - * 0.2.0-rc.2; other agents may parse more. - */ +// Break mentions before provider CLI parsing, including currency signs, embedded @, commands, context links and frame tags. +// Checked with Claude Code 2.1.296, Codex 0.162.1, Pi 1.2.0 and dsh 0.2.0-rc.2; others may parse more. const MENTION = /[\p{Sc}@]|(?<=^|\s)\/(?=[^\s/]+(?:\s|$))|t3-context(?=:)|webhook(?=-data)/giu; function parseBody(request: WebhookRequest): unknown { @@ -74,8 +56,7 @@ function parseBody(request: WebhookRequest): unknown { if (contentType.includes("application/x-www-form-urlencoded")) { return Object.fromEntries(new URLSearchParams(request.bodyText)); } - // Senders are inconsistent about content types, so any body that parses - // as JSON is addressable. + // Senders mislabel content types; accept any parseable JSON body. try { return JSON.parse(request.bodyText) as unknown; } catch { @@ -83,12 +64,30 @@ function parseBody(request: WebhookRequest): unknown { } } +const WILDCARD = /^(.*)\[\]$/; + +/** + * Walks `segments` from `root`. A segment ending in `[]` names an array and + * the rest of the path applies to each element, so `labels[].name` resolves + * to the list of every label's name. Elements without the rest of the path + * are dropped; a wildcard on a non-array resolves to undefined. + */ function lookup(root: unknown, segments: ReadonlyArray): unknown { let current = root; - for (const segment of segments) { + for (const [index, segment] of segments.entries()) { if (current === null || typeof current !== "object") return undefined; - if (!Object.hasOwn(current, segment)) return undefined; - current = (current as Record)[segment]; + const wildcard = WILDCARD.exec(segment); + const key = wildcard ? wildcard[1]! : segment; + if (!Object.hasOwn(current, key)) return undefined; + current = (current as Record)[key]; + if (!wildcard) continue; + if (!Array.isArray(current)) return undefined; + const rest = segments.slice(index + 1); + return current.flatMap((element) => { + const value = rest.length === 0 ? element : lookup(element, rest); + if (value === undefined) return []; + return rest.some((part) => WILDCARD.test(part)) && Array.isArray(value) ? value : [value]; + }); } return current; } @@ -112,16 +111,17 @@ function formatWebhookRequest(request: WebhookRequest): string { ].join("\n"); } -export function renderWebhookPrompt( - template: string, +/** + * Resolves a placeholder expression (`body.action`, `headers.x-github-event`) + * against the request. Webhook filters share it, so both read the same value. + */ +export function webhookExpressionResolver( request: WebhookRequest, - frameId: string, -): RenderedWebhookPrompt { - const missing: string[] = []; +): (expression: string) => unknown { let body: { parsed: unknown } | undefined; const parsedBody = () => (body ??= { parsed: parseBody(request) }).parsed; - const resolve = (expression: string): unknown => { + return (expression) => { const [root, ...segments] = expression.split("."); switch (root) { case "request": @@ -143,6 +143,16 @@ export function renderWebhookPrompt( return undefined; } }; +} + +export function renderWebhookPrompt( + template: string, + request: WebhookRequest, + frameId: string, + raw = false, +): RenderedWebhookPrompt { + const missing: string[] = []; + const resolve = webhookExpressionResolver(request); const tag = `webhook-data-${frameId}`; let framed = false; @@ -150,12 +160,12 @@ export function renderWebhookPrompt( const expression = rawExpression.trim(); const value = resolve(expression); const text = value === undefined || value === null ? undefined : stringify(value); - if (text === undefined) { + if (text === undefined || (raw && text === "")) { if (!missing.includes(expression)) missing.push(expression); return ""; } - // An empty value carries no request data, so it needs no frame or note. if (text === "") return ""; + if (raw) return text; framed = true; return `<${tag}>${text.replace(MENTION, "$&\u2060")}`; }); diff --git a/apps/server/src/scheduledTasks/webhookVerification.test.ts b/apps/server/src/scheduledTasks/webhookVerification.test.ts index b5c2b676084c0..330128bfb1a00 100644 --- a/apps/server/src/scheduledTasks/webhookVerification.test.ts +++ b/apps/server/src/scheduledTasks/webhookVerification.test.ts @@ -12,11 +12,6 @@ const hmac = () => NodeCrypto.createHmac("sha256", secret).update(body); describe("verifyWebhookSignature", () => { const github = { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=" } as const; - it("accepts a GitHub-style hex signature with prefix", () => { - const headers = { "x-hub-signature-256": `sha256=${hmac().digest("hex")}` }; - assert.isTrue(verifyWebhookSignature({ signature: github, secret, headers, body })); - }); - it("rejects a tampered body, a wrong secret, a missing header and a missing prefix", () => { const valid = `sha256=${hmac().digest("hex")}`; const tampered = new TextEncoder().encode('{"action":"closed"}'); diff --git a/apps/server/src/scheduling/Scheduler.integration.test.ts b/apps/server/src/scheduling/Scheduler.integration.test.ts deleted file mode 100644 index 1409697a79886..0000000000000 --- a/apps/server/src/scheduling/Scheduler.integration.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { assert, expect, it } from "@effect/vitest"; -import { - CommandId, - DEFAULT_SERVER_SETTINGS, - ProjectId, - ProviderInstanceId, - RunId, - ThreadId, - type OrchestrationV2ServerCommand, - type OrchestrationV2ThreadShell, -} from "@t3tools/contracts"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Queue from "effect/Queue"; -import * as Ref from "effect/Ref"; -import * as SqlClient from "effect/sql/SqlClient"; -import * as TestClock from "effect/testing/TestClock"; - -import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; -import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; -import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; -import * as UsageLimitRecoveryWorker from "../orchestration-v2/UsageLimitRecoveryWorker.ts"; -import * as SqlitePersistence from "../persistence/Sqlite.ts"; -import * as ScheduledTasks from "../scheduledTasks/ScheduledTaskService.ts"; -import * as SecretRequests from "../secrets/SecretRequests.ts"; -import * as ServerSettings from "../serverSettings.ts"; -import * as Scheduler from "./Scheduler.ts"; - -it.effect.each(["on time", "after restart"])( - "runs Scheduled Tasks and a persisted limit retry through the same scheduler %s", - (scenario) => - Effect.gen(function* () { - const now = yield* DateTime.now; - const resetAt = DateTime.formatIso(DateTime.add(now, { seconds: 60 })); - const thread: OrchestrationV2ThreadShell = { - id: ThreadId.make("thread:limited"), - projectId: ProjectId.make("project:test"), - title: "Limited", - providerInstanceId: ProviderInstanceId.make("codex"), - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - createdBy: "user", - creationSource: "web", - branch: null, - worktreePath: null, - lineage: { - rootThreadId: ThreadId.make("thread:limited"), - parentThreadId: null, - relationshipToParent: null, - }, - forkedFrom: null, - activeProviderThreadId: null, - latestRunId: RunId.make("run:limited"), - latestRunCompletedAt: now, - activeRunId: null, - status: "failed", - lastErrorClass: "usage_limit", - usageLimitResetAt: resetAt, - pendingRuntimeRequest: null, - latestVisibleMessage: null, - latestUserMessageAt: now, - hasActionableProposedPlan: false, - itemCount: 1, - visibleItemCount: 1, - createdAt: now, - updatedAt: now, - archivedAt: null, - settledOverride: null, - settledAt: null, - lastVisitedAt: null, - pinnedAt: null, - deletedAt: null, - limitRecovery: { - runId: RunId.make("run:limited"), - resetAt, - autoResume: true, - requestId: CommandId.make("recovery:choice"), - }, - }; - if (scenario === "after restart") { - yield* TestClock.adjust("65 seconds"); - } - const current = yield* Ref.make(thread); - const commands = yield* Ref.make>([]); - const receipts = yield* Queue.unbounded<"task" | "retry">(); - const layerDependencies = Layer.mergeAll( - NodeCrypto.layer, - Layer.mock(ThreadLaunchService.ThreadLaunchService)({ - launch: () => - Queue.offer(receipts, "task").pipe( - Effect.andThen(Effect.die("fixture dispatch failure")), - ), - }), - Layer.mock(ThreadManagementService.ThreadManagementService)({ - dispatch: (command) => - Ref.update(commands, (all) => [...all, command]).pipe( - Effect.andThen( - Ref.update(current, (shell) => ({ ...shell, status: "running" as const })), - ), - Effect.andThen(Queue.offer(receipts, "retry")), - Effect.as({ sequence: 1, storedEvents: [] }), - ), - }), - Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getLimitRecoveryCandidates: () => - Ref.get(current).pipe( - Effect.map((shell) => (shell.status === "failed" ? [shell] : [])), - ), - }), - Layer.mock(ServerSettings.ServerSettingsService)({ - getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS), - }), - Layer.mock(SecretRequests.SecretRequests)({}), - ); - const layerWorkers = Layer.mergeAll( - ScheduledTasks.layer, - UsageLimitRecoveryWorker.layer, - ).pipe(Layer.provide(layerDependencies), Layer.provide(Scheduler.layer)); - yield* Effect.gen(function* () { - const tasks = yield* ScheduledTasks.ScheduledTaskService; - const { task } = yield* tasks.upsert({ - title: "Scheduled work", - prompt: "Run scheduled work", - enabled: true, - schedule: { type: "interval", everyMs: 60_000 }, - projectId: thread.projectId, - workspaceStrategy: { type: "root" }, - modelSelection: thread.modelSelection, - runtimeMode: thread.runtimeMode, - interactionMode: thread.interactionMode, - }); - const sql = yield* SqlClient.SqlClient; - yield* sql`UPDATE scheduled_tasks SET next_run_at = ${resetAt} WHERE task_id = ${task.id}`; - if (scenario === "on time") { - yield* TestClock.adjust("55 seconds"); - assert.deepEqual(yield* Ref.get(commands), []); - } - yield* TestClock.adjust("5 seconds"); - assert.deepEqual([yield* Queue.take(receipts), yield* Queue.take(receipts)].sort(), [ - "retry", - "task", - ]); - const delivered = yield* Ref.get(commands); - assert.equal(delivered.length, 1); - expect(delivered[0]).toMatchObject({ - type: "message.dispatch", - usageLimitContinuationOfRunId: thread.latestRunId, - usageLimitRecoveryRequestId: thread.limitRecovery!.requestId, - text: "Continue where you left off.", - }); - }).pipe(Effect.provide(layerWorkers)); - }).pipe(Effect.provide(SqlitePersistence.layerMemory)), -); diff --git a/apps/server/src/secrets/SecretRequests.test.ts b/apps/server/src/secrets/SecretRequests.test.ts index b751b0b205c52..f9bb937f7bdda 100644 --- a/apps/server/src/secrets/SecretRequests.test.ts +++ b/apps/server/src/secrets/SecretRequests.test.ts @@ -1,23 +1,25 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { ProjectId, type OrchestrationV2ServerCommand, + SecretRef, ThreadId, TurnItemId, } from "@t3tools/contracts"; -import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Metric from "effect/Metric"; -import * as TestClock from "effect/testing/TestClock"; import * as Tracer from "effect/Tracer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; +import * as TestClock from "effect/testing/TestClock"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; -import * as ServerConfig from "../config.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as SecretRequests from "./SecretRequests.ts"; @@ -33,6 +35,8 @@ const withService = ( }) => Effect.Effect, options: { readonly threadId?: ThreadId; + readonly delivery?: "file"; + readonly directory?: string; readonly runStatus?: string; readonly removeFails?: boolean; readonly closedFirst?: boolean; @@ -51,6 +55,7 @@ const withService = ( Layer.succeed( ServerSecretStore.ServerSecretStore, ServerSecretStore.ServerSecretStore.of({ + ...(options.directory === undefined ? {} : { directory: options.directory }), get: (name) => Effect.yieldNow.pipe(Effect.as(Option.fromNullishOr(stored.get(name)))), set: (name, value) => Effect.sync(() => void stored.set(name, value)), create: (name, value) => @@ -101,6 +106,7 @@ const withService = ( type: "secret_request", label: "GitHub token", reason: "Used as GH_TOKEN.", + ...(options.delivery === undefined ? {} : { delivery: options.delivery }), secretStatus, }, ], @@ -211,24 +217,6 @@ it.effect("a save whose record failed can be saved again", () => ), ); -it.effect("a save whose record and cleanup both failed is finished by saving again", () => - withService( - ({ service }) => - Effect.gen(function* () { - yield* service - .answer({ threadId, turnItemId, answer: { type: "save", secret: "ghp_secret" } }) - .pipe(Effect.flip); - yield* service.answer({ - threadId, - turnItemId, - answer: { type: "save", secret: "ghp_secret" }, - }); - assert.isTrue(Option.isSome(yield* service.savedRef({ threadId, turnItemId }))); - }), - { failedRecords: 1, removeFails: true }, - ), -); - it.effect("a ref only works in the project it was entered for", () => withService(({ service }) => Effect.gen(function* () { @@ -343,48 +331,6 @@ it.effect("refuses an answer once the agent that asked has stopped", () => ), ); -it.effect("drops values nobody used once they expire, and keeps the rest", () => - Effect.gen(function* () { - const store = yield* ServerSecretStore.ServerSecretStore; - const encode = (savedAt: number) => - new TextEncoder().encode( - `{"projectId":"project-1","value":"ghp_secret","savedAt":${savedAt}}`, - ); - yield* TestClock.adjust("2 days"); - const now = yield* Clock.currentTimeMillis; - const stale = `secret-request-${"a".repeat(32)}`; - const fresh = `secret-request-${"b".repeat(32)}`; - yield* store.set(stale, encode(now - 25 * 60 * 60 * 1000)); - yield* store.set(fresh, encode(now)); - yield* store.set("unrelated", new Uint8Array([1])); - - yield* Effect.gen(function* () { - yield* SecretRequests.SecretRequests; - }).pipe( - Effect.provide( - SecretRequests.layer.pipe( - Layer.provide(Layer.mock(ThreadManagementService.ThreadManagementService)({})), - ), - ), - Effect.scoped, - ); - - assert.isTrue(Option.isNone(yield* store.get(stale))); - assert.isTrue(Option.isSome(yield* store.get(fresh))); - assert.isTrue(Option.isSome(yield* store.get("unrelated"))); - assert.isTrue(Option.isSome(yield* store.get("secret-request-salt"))); - }).pipe( - Effect.provide( - ServerSecretStore.layer.pipe( - Layer.provideMerge( - ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-requests-" }), - ), - Layer.provideMerge(NodeServices.layer), - ), - ), - ), -); - it.effect("a used value that cannot be deleted is not handed out", () => withService( ({ service }) => @@ -401,3 +347,113 @@ it.effect("a used value that cannot be deleted is not handed out", () => { removeFails: true }, ), ); + +const SECRET_FILE_TTL_MS = 24 * 60 * 60 * 1000; + +it.effect("a file request moves its value to an owner-only file, once", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" }); + const file = yield* withService( + ({ service, stored, dispatched }) => + Effect.gen(function* () { + yield* service.answer({ + threadId, + turnItemId, + answer: { type: "save", secret: "cf_token'$(id)" }, + }); + assert.include(dispatched[0] as object, { secretStatus: "saved", delivery: "file" }); + const file = yield* service.saveToFile({ threadId, turnItemId }); + assert.equal(yield* fs.readFileString(file), "cf_token'$(id)"); + assert.deepEqual(valuesOf(stored), []); + if ((yield* HostProcess.Platform) !== "win32") { + assert.equal((yield* fs.stat(file)).mode & 0o777, 0o600); + assert.equal((yield* fs.stat(path.dirname(file))).mode & 0o777, 0o700); + } + // A retried request_secret gets the same file; the value is never a ref again. + assert.equal(yield* service.saveToFile({ threadId, turnItemId }), file); + const ref = SecretRef.make(`secret-ref:${path.basename(file)}`); + const reused = yield* service.consume({ ref, projectId }).pipe(Effect.flip); + assert.equal(reused.reason, "ref_unavailable"); + return file; + }), + { delivery: "file", directory }, + ); + + const { mtime } = yield* fs.stat(file); + yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS); + yield* withService(() => Effect.void, { directory }); + assert.isTrue(yield* fs.exists(file)); + yield* TestClock.setTime(Option.getOrThrow(mtime).getTime() + SECRET_FILE_TTL_MS + 1); + yield* withService(() => Effect.void, { directory }); + assert.isFalse(yield* fs.exists(file)); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("a failed file write keeps the value, so the request can retry", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" }); + yield* withService( + ({ service }) => + Effect.gen(function* () { + yield* service.answer({ + threadId, + turnItemId, + answer: { type: "save", secret: "cf_token" }, + }); + const ref = Option.getOrThrow(yield* service.savedRef({ threadId, turnItemId })); + const name = ref.slice("secret-ref:".length); + // A non-empty directory where the partial file goes makes the write fail. + const partial = path.join(directory, "files", `${name}.partial`); + yield* fs.makeDirectory(path.join(partial, "block"), { recursive: true }); + const failed = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip); + assert.equal(failed.reason, "store_failed"); + yield* fs.remove(partial, { recursive: true }); + const file = yield* service.saveToFile({ threadId, turnItemId }); + assert.equal(yield* fs.readFileString(file), "cf_token"); + }), + { delivery: "file", directory }, + ); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("a file is not delivered while its stored copy cannot be removed", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "secret-files-test-" }); + yield* withService( + ({ service }) => + Effect.gen(function* () { + yield* service.answer({ + threadId, + turnItemId, + answer: { type: "save", secret: "cf_token" }, + }); + const first = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip); + assert.equal(first.reason, "consume_failed"); + // A retry finds the file but still will not hand it out until the removal works. + const retried = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip); + assert.equal(retried.reason, "consume_failed"); + }), + { delivery: "file", directory, removeFails: true }, + ); + }).pipe(Effect.provide(NodeServices.layer)), +); + +it.effect("a secret the card promised to keep from the agent is never written to a file", () => + withService(({ service, stored }) => + Effect.gen(function* () { + yield* service.answer({ + threadId, + turnItemId, + answer: { type: "save", secret: "ghp_secret" }, + }); + const refused = yield* service.saveToFile({ threadId, turnItemId }).pipe(Effect.flip); + assert.equal(refused.reason, "not_a_file_request"); + assert.isTrue(valuesOf(stored).some((value) => value.includes("ghp_secret"))); + }), + ), +); diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.ts index fadad6ea743b2..7c8e961dbd2eb 100644 --- a/apps/server/src/secrets/SecretRequests.ts +++ b/apps/server/src/secrets/SecretRequests.ts @@ -1,9 +1,6 @@ -/** - * The user's answer goes straight to the server's secret store under a - * one-use SecretRef; orchestration only records the request and its status. - * A tool that needs the value takes the ref and consumes it, so the value - * never reaches the transcript, projections, clients, or model context. - */ +// Answers stay in the secret store behind one-use refs; orchestration records only request status. +// Consuming tools keep values out of transcripts, projections, clients and model context. +// A `file` request instead moves its value to an owner-only file for the agent's own shell. import { CommandId, SecretRef, @@ -21,6 +18,7 @@ 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 Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; @@ -34,6 +32,7 @@ const storeName = (ref: SecretRef) => `secret-request-${ref.slice(SECRET_REF_PRE const REF_PATTERN = /^secret-ref:[0-9a-f]{32}$/; const SECRET_REF_TTL_MS = 24 * 60 * 60 * 1000; const STORE_NAME_PATTERN = /^(secret-request-[0-9a-f]{32})\.bin$/; +const FILE_NAME_PATTERN = /^[0-9a-f]{32}(\.partial)?$/; const refFor = (salt: string, threadId: ThreadId, turnItemId: string) => SecretRef.make( @@ -61,20 +60,28 @@ export class SecretRequests extends Context.Service< readonly ref: SecretRef; readonly projectId: ProjectId; }) => Effect.Effect; + /** Moves a saved `file` request's value to an owner-only file and returns its path. */ + readonly saveToFile: (input: { + readonly threadId: ThreadId; + readonly turnItemId: string; + }) => Effect.Effect; } >()("t3/secrets/SecretRequests") {} const make = Effect.gen(function* () { const store = yield* ServerSecretStore.ServerSecretStore; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const threadManagement = yield* ThreadManagementService.ThreadManagementService; + // Beside the store's own files so the same owner-only directory and cleanup rules apply. + const filesDir = store.directory === undefined ? undefined : path.join(store.directory, "files"); const salt = Buffer.from( yield* store.getOrCreateRandom("secret-request-salt", 32).pipe(Effect.orDie), ).toString("hex"); - const answer: SecretRequests["Service"]["answer"] = (input) => - Effect.gen(function* () { + const answer: SecretRequests["Service"]["answer"] = Effect.fn("SecretRequests.answer")( + function* (input) { yield* Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId, "secret_request.answer": input.answer.type, @@ -96,10 +103,8 @@ const make = Effect.gen(function* () { if (run === undefined || ThreadManagementService.isTerminalRunStatus(run.status)) { return yield* new SecretRequestError({ reason: "agent_stopped" }); } - // Store first: the card only says saved once the value is kept. Create, - // not set: a second answer racing this one must not replace the value. - // A value already there on a card still pending is an earlier save whose - // record failed and could not be cleaned up; recording it finishes that save. + // Create before recording so racing answers cannot overwrite values or show saved before storage. + // Existing values on pending cards finish earlier saves whose recording failed. if (input.answer.type === "save") { const encoded = yield* encodeStored({ projectId: records.thread.projectId, @@ -130,12 +135,12 @@ const make = Effect.gen(function* () { label: item.label, reason: item.reason, ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }), + ...(item.delivery === undefined ? {} : { delivery: item.delivery }), secretStatus, }) .pipe( Effect.mapError((cause) => new SecretRequestError({ reason: "record_failed", cause })), - // The card still says pending, so the user can save again; the value - // stored above would make that retry look already answered. + // Clear failed saves so the pending card can be answered again. Effect.tapError(() => input.answer.type === "save" ? removeLogged(storeName(refFor(salt, input.threadId, item.id))) @@ -143,9 +148,7 @@ const make = Effect.gen(function* () { ), ); if (input.answer.type !== "save") return; - // A request is answered once: if the agent's wait closed the card between - // the checks above and this record, the record changed nothing. Nobody - // will receive the ref, so the value is deleted rather than left to expire. + // The wait may have closed the card; delete unrecorded answers because no one receives their refs. const recorded = yield* threadManagement .getThreadRecords(input.threadId, ["turnItems"], { turnItemTypes: ["secret_request"], @@ -159,14 +162,16 @@ const make = Effect.gen(function* () { yield* removeLogged(storeName(refFor(salt, input.threadId, item.id))); return yield* new SecretRequestError({ reason: "agent_stopped" }); } - }).pipe(Effect.withSpan("SecretRequests.answer")); + }, + ); - const savedRef: SecretRequests["Service"]["savedRef"] = (input) => - Effect.gen(function* () { + const savedRef: SecretRequests["Service"]["savedRef"] = Effect.fn("SecretRequests.savedRef")( + function* (input) { const ref = refFor(salt, input.threadId, input.turnItemId); const stored = yield* store.get(storeName(ref)).pipe(Effect.orElseSucceed(Option.none)); return Option.map(stored, () => ref); - }); + }, + ); const removeLogged = (name: string) => store.remove(name).pipe( @@ -178,8 +183,7 @@ const make = Effect.gen(function* () { ), ); - // get and remove are separate store calls; one consumer at a time keeps two - // concurrent calls from both reading a ref before either deletes it. + // Serialize get/remove so concurrent consumers cannot read the same one-use ref. const consumeLock = yield* Semaphore.make(1); const consume: SecretRequests["Service"]["consume"] = (input) => consumeRef(input).pipe( @@ -191,30 +195,93 @@ const make = Effect.gen(function* () { Effect.withSpan("SecretRequests.consume"), ); - const consumeRef = (input: { readonly ref: SecretRef; readonly projectId: ProjectId }) => - Effect.gen(function* () { - if (!REF_PATTERN.test(input.ref)) - return yield* new SecretRequestError({ reason: "invalid_ref" }); - const stored = yield* store - .get(storeName(input.ref)) - .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause }))); - const decoded = Option.flatMap(stored, (bytes) => - decodeStored(new TextDecoder().decode(bytes)), + /** A live ref's value, left in the store. */ + const readRef = Effect.fn("SecretRequests.readRef")(function* (input: { + readonly ref: SecretRef; + readonly projectId: ProjectId; + }) { + if (!REF_PATTERN.test(input.ref)) + return yield* new SecretRequestError({ reason: "invalid_ref" }); + const stored = yield* store + .get(storeName(input.ref)) + .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "read_failed", cause }))); + const decoded = Option.flatMap(stored, (bytes) => + decodeStored(new TextDecoder().decode(bytes)), + ); + if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) { + return yield* new SecretRequestError({ reason: "ref_unavailable" }); + } + if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) { + yield* removeLogged(storeName(input.ref)); + return yield* new SecretRequestError({ reason: "ref_expired" }); + } + return decoded.value.value; + }); + + const consumeRef = Effect.fn("SecretRequests.consumeRef")(function* (input: { + readonly ref: SecretRef; + readonly projectId: ProjectId; + }) { + const value = yield* readRef(input); + // One use: the value moves into whatever consumed it. If it cannot be + // deleted, it is not handed out, so a ref is never used twice. + if (!(yield* removeLogged(storeName(input.ref)))) { + return yield* new SecretRequestError({ reason: "consume_failed" }); + } + return value; + }); + + const saveToFile: SecretRequests["Service"]["saveToFile"] = Effect.fn( + "SecretRequests.saveToFile", + )(function* (input) { + const records = yield* threadManagement + .getThreadRecords(input.threadId, ["turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], + }) + .pipe(Effect.mapError((cause) => new SecretRequestError({ reason: "load_failed", cause }))); + const item = records.turnItems.find((candidate) => candidate.id === input.turnItemId); + // Only a card that told the user the agent's commands can read the value may write it out. + if ( + item?.type !== "secret_request" || + item.secretStatus !== "saved" || + item.delivery !== "file" + ) { + return yield* new SecretRequestError({ reason: "not_a_file_request" }); + } + if (filesDir === undefined) return yield* new SecretRequestError({ reason: "store_failed" }); + const ref = refFor(salt, input.threadId, item.id); + const file = path.join(filesDir, ref.slice(SECRET_REF_PREFIX.length)); + return yield* Effect.gen(function* () { + // One use: the file counts as delivered only once the stored copy is gone. A retry with the + // same clientRequestId gets the file the first call wrote and finishes that removal. + const removeStored = removeLogged(storeName(ref)).pipe( + Effect.flatMap((removed) => + removed ? Effect.succeed(file) : new SecretRequestError({ reason: "consume_failed" }), + ), ); - if (Option.isNone(decoded) || decoded.value.projectId !== input.projectId) { - return yield* new SecretRequestError({ reason: "ref_unavailable" }); + if (yield* fileSystem.exists(file).pipe(Effect.orElseSucceed(() => false))) { + return yield* removeStored; } - if ((yield* Clock.currentTimeMillis) - decoded.value.savedAt > SECRET_REF_TTL_MS) { - yield* removeLogged(storeName(input.ref)); - return yield* new SecretRequestError({ reason: "ref_expired" }); - } - // One use: the value moves into whatever consumed it. If it cannot be - // deleted, it is not handed out, so a ref is never used twice. - if (!(yield* removeLogged(storeName(input.ref)))) { - return yield* new SecretRequestError({ reason: "consume_failed" }); - } - return decoded.value.value; - }); + // The stored value goes only after the file is complete, so a failed write can retry. + const value = yield* readRef({ ref, projectId: records.thread.projectId }); + const partial = `${file}.partial`; + yield* fileSystem.makeDirectory(filesDir, { recursive: true, mode: 0o700 }).pipe( + Effect.andThen(fileSystem.chmod(filesDir, 0o700)), + Effect.andThen(fileSystem.remove(partial, { force: true })), + // `wx` never follows or replaces an existing path. + Effect.andThen( + fileSystem.writeFile(partial, new TextEncoder().encode(value), { + flag: "wx", + mode: 0o600, + }), + ), + Effect.andThen(fileSystem.rename(partial, file)), + Effect.mapError((cause) => new SecretRequestError({ reason: "store_failed", cause })), + ); + return yield* removeStored; + }).pipe(consumeLock.withPermits(1)); + }); const sweepExpired = Effect.gen(function* () { if (store.directory === undefined) return; @@ -237,14 +304,32 @@ const make = Effect.gen(function* () { Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret refs", cause)), Effect.withSpan("SecretRequests.sweepExpired"), ); - yield* sweepExpired; - yield* sweepExpired.pipe( + const sweepExpiredFiles = Effect.gen(function* () { + if (filesDir === undefined || !(yield* fileSystem.exists(filesDir))) return; + const now = yield* Clock.currentTimeMillis; + let removed = 0; + for (const name of yield* fileSystem.readDirectory(filesDir)) { + if (!FILE_NAME_PATTERN.test(name)) continue; + const file = path.join(filesDir, name); + const { mtime } = yield* fileSystem.stat(file); + if (Option.exists(mtime, (time) => now - time.getTime() <= SECRET_REF_TTL_MS)) continue; + yield* fileSystem.remove(file); + removed += 1; + } + yield* Effect.annotateCurrentSpan({ "secret_request.expired_files_removed": removed }); + }).pipe( + Effect.catchCause((cause) => Effect.logWarning("Could not sweep expired secret files", cause)), + Effect.withSpan("SecretRequests.sweepExpiredFiles"), + ); + const sweep = Effect.andThen(sweepExpired, sweepExpiredFiles); + yield* sweep; + yield* sweep.pipe( Effect.delay("1 hour"), Effect.repeat(Schedule.spaced("1 hour")), Effect.forkScoped, ); - return SecretRequests.of({ answer, savedRef, consume }); + return SecretRequests.of({ answer, savedRef, consume, saveToFile }); }); export const layer = Layer.effect(SecretRequests, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 2d35647f09485..1a3b6f52d4e80 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -1,13 +1,12 @@ import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay"; -import * as Clock from "effect/Clock"; import * as Random from "effect/Random"; -import * as Semaphore from "effect/Semaphore"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +// Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -21,16 +20,19 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; -import * as Schedule from "effect/Schedule"; import { FetchHttpClient, HttpRouter, HttpServer } from "effect/http"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; import * as ServerConfig from "./config.ts"; -import { withUntracedRequests } from "./http.ts"; +import { withUnloggedCredentialRequests, withUntracedRequests } from "./http.ts"; import * as ServerHttp from "./http.ts"; -import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts"; +import { + guardHttpResponseWriteErrors, + rejectRequestsUntilServing, +} from "./httpResponseErrorGuard.ts"; +import { layerSpeechToTextRoute } from "./speechToText/SpeechToTextRoute.ts"; import { fixPath } from "./os-jank.ts"; import * as Ws from "./ws.ts"; import * as AgentScopeLive from "./process/agentScope.ts"; @@ -45,6 +47,7 @@ import * as PullRequestReviewGuides from "./persistence/PullRequestReviewGuides. import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; +import * as DelegatedTaskAnalytics from "./telemetry/DelegatedTaskAnalytics.ts"; import * as ProviderEventIngestor from "./orchestration-v2/ProviderEventIngestor.ts"; import * as ModelManifest from "./provider/ModelManifest.ts"; import * as ResetCreditCoordinator from "./provider/resetCreditCoordinator.ts"; @@ -58,6 +61,7 @@ import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRe import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as CheckpointStore from "./checkpointing/CheckpointStore.ts"; import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts"; +import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControl/sourceControlDefinitions.ts"; import * as TextGeneration from "./textGeneration/TextGeneration.ts"; import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts"; import * as ProjectSettingsOverrideSweep from "./provider/ProjectSettingsOverrideSweep.ts"; @@ -121,6 +125,7 @@ import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as AuthHttp from "./auth/http.ts"; import * as ReplayMarkers from "./auth/replayMarkers.ts"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; +import * as CodexManagedTokenBroker from "./provider/CodexManagedTokenBroker.ts"; import * as WebhookRoute from "./scheduledTasks/webhookRoute.ts"; import * as RelayDeliveryProof from "./scheduledTasks/RelayDeliveryProof.ts"; import * as HeldHooksWaker from "./relay/HeldHooksWaker.ts"; @@ -137,14 +142,17 @@ import { } from "./cloud/config.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import * as CloudHttp from "./cloud/http.ts"; +import * as GuestHttp from "./guest/http.ts"; import * as CloudLink from "./cloud/CloudLink.ts"; +import * as ConnectReachability from "./cloud/ConnectReachability.ts"; import { pendingServiceUpdateExists } from "./cloud/updateHandoff.ts"; import * as RelayTracing from "./cloud/relayTracing.ts"; import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts"; import { MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER, - MANAGED_TUNNEL_RECOVERY_COOLDOWN, + makeManagedTunnelRecovery, managedTunnelStartupAction, + retryDesiredLinkReconcile, retryManagedTunnelRegistration, } from "./cloud/managedTunnelStartup.ts"; import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts"; @@ -160,23 +168,27 @@ import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryR import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts"; import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts"; import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts"; +import * as ProcessGroupMetrics from "./resourceTelemetry/ProcessGroupMetrics.ts"; import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as AntigravityUsage from "./provider/Drivers/AntigravityUsage.ts"; +import { MuseUsageHome } from "@t3tools/provider-muse/server"; import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader"; import * as CursorKeychain from "@t3tools/provider-cursor/server/CursorKeychain"; import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsageAccounts"; import * as UsageService from "./usage/UsageService.ts"; +import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; -import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; +import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts"; import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts"; import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; import * as EventStoreV2 from "./orchestration-v2/EventStore.ts"; import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts"; import { makePersistedServerRuntimeState } from "./serverRuntimeState.ts"; +import { acceptsPrivateNetworkConnection, loopbackUrlHostForAddress } from "./startupAccess.ts"; import * as OrchestrationHttp from "./orchestration-v2/http.ts"; import * as ProjectHttp from "./project/http.ts"; import * as NetService from "@t3tools/shared/Net"; @@ -184,15 +196,12 @@ import * as RelayClient from "@t3tools/shared/relayClient"; import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale"; import * as ServerActivation from "./serverActivation.ts"; -// MCP handoff thread IDs include escaped provenance and can exceed find-my-way's -// 100-character default for one path segment. +// Escaped MCP handoff provenance can exceed find-my-way's 100-character segment default. const HTTP_ROUTER_CONFIG = { maxParamLength: 512, } as const; -// Effect's default preemptive shutdown waits 20s before finalizing request scopes. -// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer -// already closes the websocket gracefully. +// Skip Effect's default 20 s grace; WebSocket scope finalizers already close connections gracefully. const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0; const layerResourceAttribution = ResourceAttribution.layer; const layerApplicationObservability = EventLoopMonitor.layer.pipe( @@ -200,8 +209,7 @@ const layerApplicationObservability = EventLoopMonitor.layer.pipe( Layer.provideMerge(layerResourceAttribution), ); -// One rotating store behind both logger views, so driver instances never race -// its rotation. +// Share rotation state so driver loggers cannot race. const layerProviderEventLoggers = Layer.effect( ProviderEventLoggers.ProviderEventLoggers, Effect.gen(function* () { @@ -246,8 +254,7 @@ const layerHostPowerMonitor = HostPowerMonitor.layer.pipe( Layer.provide(layerDesktopTelemetryReceiver), ); -// Reuses DesktopTelemetryReceiverLayerLive: a fresh receiver layer here -// would open a second reader on the desktop telemetry fd. +// A fresh receiver layer would open a second reader on the desktop telemetry fd. const layerDesktopAppUpdate = DesktopAppUpdate.layer.pipe( Layer.provide(layerDesktopTelemetryReceiver), ); @@ -261,6 +268,8 @@ const layerUsage = UsageService.layer.pipe( Layer.provide( Layer.mergeAll( AntigravityUsage.layer, + MuseUsageHome.layer, + CodexUsageHistory.layer, CursorUsageAccounts.layer.pipe( Layer.provide(CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer))), ), @@ -274,6 +283,7 @@ const layerResourceDiagnostics = Layer.mergeAll( layerResourceTelemetry, ProcessDiagnostics.layer.pipe(Layer.provide(layerResourceTelemetry)), ProcessResourceMonitor.layer.pipe(Layer.provide(layerResourceTelemetry)), + ProcessGroupMetrics.layer.pipe(Layer.provide(layerResourceTelemetry)), ); const layerRelayClient = Layer.unwrap( @@ -286,16 +296,31 @@ const layerRelayClient = Layer.unwrap( const layerHttpServer = Layer.unwrap( Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; - return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), { - host: config.host ?? "127.0.0.1", - port: config.port, - gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS, - // Context takeover stays enabled (ws default) so the compression - // window is shared across frames — that also makes small frames cheap - // to compress, so no size threshold is set (ws only honors - // `threshold` when context takeover is disabled). - websocket: { perMessageDeflate: true }, - }); + return NodeHttpServer.layer( + () => { + const server = rejectRequestsUntilServing( + guardHttpResponseWriteErrors(NodeHttp.createServer()), + ); + if (config.privateNetworkOnly) { + server.on("connection", (socket) => { + if (!acceptsPrivateNetworkConnection(socket)) { + socket.destroy(); + } + }); + } + return server; + }, + { + host: config.host ?? "127.0.0.1", + port: config.port, + gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS, + // Context takeover stays enabled (ws default) so the compression + // window is shared across frames — that also makes small frames cheap + // to compress, so no size threshold is set (ws only honors + // `threshold` when context takeover is disabled). + websocket: { perMessageDeflate: true }, + }, + ); }), ); @@ -317,9 +342,7 @@ const layerRepositoryIdentityResolver = Layer.effect( const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; return yield* RepositoryIdentityResolver.make({ refine: Effect.fn(function* (identity: RepositoryIdentity) { - for (const kind of SourceControlBuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS.map( - (driver) => driver.kind, - )) { + for (const { kind } of BUILT_IN_SOURCE_CONTROL_DRIVER_LIST) { const provider = yield* registry.get(kind); if (provider.refineRepositoryIdentity === undefined) continue; const refined = yield* provider.refineRepositoryIdentity({ @@ -393,6 +416,7 @@ const layerVcs = Layer.empty.pipe( Layer.provideMerge( VcsStatusBroadcaster.layer.pipe( Layer.provide(layerGitWorkflow), + Layer.provide(VcsStatusBroadcaster.layerAutomaticFetchInterval), // The orchestration runtime also consumes the broadcaster (run // finalization), so the policy cannot read the store from the runtime's // output. @@ -487,7 +511,6 @@ const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( Layer.provide(ProviderEventIngestor.layerAnalytics), Layer.provide(layerCheckpointStore), Layer.provide(layerGitWorkflow), - Layer.provide(ResourceCleanupService.layer), Layer.provide( RunFinalizationService.layerObserver.pipe( Layer.provide(ProjectionStoreV2.layer), @@ -506,6 +529,10 @@ const layerThreadSettlementWorker = Layer.effectDiscard( ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer)); +const layerIdleCompactionWorker = Layer.effectDiscard( + IdleCompactionService.make.pipe(Effect.flatMap((service) => service.start())), +).pipe(Layer.provide(ProjectionStoreV2.layer)); + const layerThreadPullRequestWorker = Layer.effectDiscard( ThreadPullRequestService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(layerPullRequestService)); @@ -546,6 +573,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( AgentAwarenessRelay.layer, HeldHooksWaker.layer, layerThreadSettlementWorker, + layerIdleCompactionWorker, StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)), DatabaseStorage.layer.pipe( Layer.provide(ProjectionMaintenance.layer), @@ -554,6 +582,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ), ), layerThreadPullRequestWorker, + DelegatedTaskAnalytics.layer, Layer.effectDiscard( Effect.gen(function* () { const service = yield* PullRequestSyncReactor.PullRequestSyncReactor; @@ -635,6 +664,7 @@ const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe( Layer.provideMerge(ProjectEnrichmentService.layer), Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, layerProjectFaviconResolver)), Layer.provideMerge(layerRepositoryIdentityResolver), + Layer.provideMerge(CodexManagedTokenBroker.layer), Layer.provideMerge(layerServerEnvironment), Layer.provideMerge(layerAuth), Layer.provideMerge(ServerSecretStore.layer), @@ -686,6 +716,8 @@ const layerMakeRoutes = Layer.mergeAll( ServerHttp.layerOtlpTracesProxyRoute, ServerHttp.layerAssetRoute, ServerHttp.layerAttachmentUploadRoute, + GuestHttp.layer, + layerSpeechToTextRoute, DeviceHubProxy.layer, ServerBrowserStream.routeLayer, ServerHttp.layerStaticAndDevRoute, @@ -699,8 +731,7 @@ const layerMakeRoutes = Layer.mergeAll( Layer.provide( PullRequestReviewGuideService.layer.pipe(Layer.provide(PullRequestReviewGuides.layer)), ), - // Both transports consume the same service instance, so caches single-flight across clients - // and mutations observed on WebSocket invalidate patches subsequently read over HTTP. + // Share the service so HTTP/WS clients single-flight reads and invalidate each other's cached patches. Layer.provide(layerPullRequestService), Layer.provide(ServerBrowser.layer.pipe(Layer.provide(DesktopBrowserChannel.layer))), Layer.provide(PreviewBrowser.layer), @@ -775,7 +806,7 @@ const layerMakeServer = Layer.unwrap( return yield* ensureTailscaleServe({ localPort, servePort: config.tailscaleServePort, - localHost: "127.0.0.1", + localHost: loopbackUrlHostForAddress(address), }).pipe( Effect.as({ localPort, servePort: config.tailscaleServePort }), Effect.tap(() => @@ -828,11 +859,8 @@ const layerMakeServer = Layer.unwrap( ), Effect.asVoid, ); - // The previous server is already gone, so the trial owns cleanup - // immediately; the pending-state check keeps the tunnel for normal - // commit or rollback, while the launcher's explicit-stop marker allows - // it to be released. Other runtimes wait for activation so a failed - // standby cannot tear down the active runtime's tunnel. + // Trials own cleanup immediately after the old server exits, retaining tunnels for commit/rollback unless explicitly stopped. + // Other runtimes wait for activation so failed standbys cannot tear down active tunnels. const cleanupBeforeActivation = yield* pendingServiceUpdateExists; if (cleanupBeforeActivation) { yield* Effect.addFinalizer(() => releaseManagedTunnel); @@ -845,44 +873,28 @@ const layerMakeServer = Layer.unwrap( const server = yield* HttpServer.HttpServer; const address = server.address; if (typeof address === "string" || !("port" in address)) return; - const localOrigin = `http://127.0.0.1:${address.port}`; + const localOrigin = `http://${loopbackUrlHostForAddress(address)}:${address.port}`; const endpointRuntime = yield* CloudManagedEndpointRuntime.CloudManagedEndpointRuntime; - const recoveryLock = yield* Semaphore.make(1); - let lastRecoveryAtMillis = 0; + const runManagedTunnelRecovery = yield* makeManagedTunnelRecovery({ + recover: (config: RelayManagedEndpointRuntimeConfig) => + cloudLink.recoverManagedTunnel(localOrigin, config, { + retryRuntimeFailures: true, + }), + isRetryable: (error) => + CloudLink.shouldRetryCloudLink(error) && + error._tag !== "CloudLinkEndpointUnavailableError", + }); const recoverManagedTunnel = (config: RelayManagedEndpointRuntimeConfig) => - recoveryLock.withPermits(1)( - Effect.gen(function* () { - const elapsed = (yield* Clock.currentTimeMillis) - lastRecoveryAtMillis; - const wait = Duration.toMillis(MANAGED_TUNNEL_RECOVERY_COOLDOWN) - elapsed; - if (wait > 0) yield* Effect.sleep(Duration.millis(wait)); - lastRecoveryAtMillis = yield* Clock.currentTimeMillis; - }).pipe( - Effect.andThen( - cloudLink.recoverManagedTunnel(localOrigin, config, { - retryRuntimeFailures: true, - }), - ), - Effect.retry({ - while: (error) => - CloudLink.shouldRetryCloudLink(error) && - error._tag !== "CloudLinkEndpointUnavailableError", - schedule: Schedule.exponential("1 second").pipe( - Schedule.modifyDelay(({ duration }) => - Effect.succeed(Duration.min(duration, Duration.seconds(30))), - ), - Schedule.jittered, - ), - }), - Effect.tap((recovered) => - recovered ? Effect.logInfo("T3 Connect managed tunnel recovered") : Effect.void, - ), - Effect.catchCause((cause) => - Cause.hasInterrupts(cause) - ? Effect.interrupt - : Effect.logWarning("Failed to recover the T3 Connect managed tunnel", { - cause, - }), - ), + runManagedTunnelRecovery(config).pipe( + Effect.tap((recovered) => + recovered ? Effect.logInfo("T3 Connect managed tunnel recovered") : Effect.void, + ), + Effect.catchCause((cause) => + Cause.hasInterrupts(cause) + ? Effect.interrupt + : Effect.logWarning("Failed to recover the T3 Connect managed tunnel", { + cause, + }), ), ); yield* endpointRuntime.recoveryRequests.pipe( @@ -898,8 +910,7 @@ const layerMakeServer = Layer.unwrap( ), ) : false; - // A failed read must not end this fiber before it registers - // recovery and starts consuming recovery requests. + // Recover reads so this fiber still registers and consumes recovery requests. const desiredCliLinkMode = wantsCliLink ? yield* CloudCliState.readCliDesiredLinkMode.pipe( Effect.catch((cause) => @@ -909,8 +920,7 @@ const layerMakeServer = Layer.unwrap( ), ) : null; - // A publish-only link must not expose the host, even if a managed - // config from an earlier link is still stored. + // Publish-only links must not expose the host through old managed configs. const startedConfirmed = desiredCliLinkMode === "publish_only" ? false @@ -960,8 +970,7 @@ const layerMakeServer = Layer.unwrap( }).pipe(Effect.as({ status: "unavailable" as const })), ), ); - // Spread those registrations so an auto-update wave does not hit - // the relay all at once. + // Jitter registrations so update waves do not hit the relay simultaneously. if (!startedConfirmed && desiredCliLinkMode !== "publish_only") { const jitter = yield* Random.nextIntBetween( 0, @@ -984,15 +993,13 @@ const layerMakeServer = Layer.unwrap( const reconciledMode = yield* cloudLink .reconcileDesiredLinkIfStillDesired(localOrigin) .pipe( - Effect.retry({ - while: CloudLink.shouldRetryCloudLink, - schedule: Schedule.exponential("1 second").pipe( - Schedule.modifyDelay(({ duration }) => - Effect.succeed(Duration.min(duration, Duration.seconds(30))), + (reconcile) => + retryDesiredLinkReconcile(reconcile, CloudLink.shouldRetryCloudLink, (cause) => + Effect.logWarning( + "T3 Connect relay is still unavailable; retrying the desired link in the background", + { cause }, ), - Schedule.upTo({ duration: "10 minutes" }), ), - }), Effect.tap((mode) => mode === null ? Effect.void @@ -1034,6 +1041,7 @@ const layerMakeServer = Layer.unwrap( const layerRoutes = HttpRouter.serve(layerMakeRoutes.pipe(Layer.provide(layerLauncher)), { disableLogger: !config.logWebSocketEvents, routerConfig: HTTP_ROUTER_CONFIG, + middleware: withUnloggedCredentialRequests, }).pipe( withUntracedRequests, Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)), @@ -1048,7 +1056,7 @@ const layerMakeServer = Layer.unwrap( ); return layerServerApplication.pipe( - Layer.provide(CloudLink.layer), + Layer.provide(CloudLink.layer.pipe(Layer.provideMerge(ConnectReachability.layer))), Layer.provideMerge(layerRuntimeServices), Layer.provideMerge( McpSessionRegistry.layer.pipe( diff --git a/apps/server/src/serverActivation.test.ts b/apps/server/src/serverActivation.test.ts deleted file mode 100644 index dc41b884ab36c..0000000000000 --- a/apps/server/src/serverActivation.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { expect, it } from "@effect/vitest"; -import * as Deferred from "effect/Deferred"; -import * as Effect from "effect/Effect"; - -import * as ServerActivation from "./serverActivation.ts"; - -it.effect("proves a root is parked before returning and releases it with one gate", () => - Effect.scoped( - Effect.gen(function* () { - const activation = yield* Deferred.make(); - const ran = yield* Deferred.make(); - - yield* ServerActivation.forkParked(Deferred.succeed(ran, undefined)).pipe( - Effect.provideService(ServerActivation.ServerActivation, Deferred.await(activation)), - ); - expect(yield* Deferred.isDone(ran)).toBe(false); - - yield* Deferred.succeed(activation, undefined); - yield* Deferred.await(ran); - expect(yield* Deferred.isDone(ran)).toBe(true); - }), - ), -); diff --git a/apps/server/src/serverActivation.ts b/apps/server/src/serverActivation.ts index c43cd259ef66f..2945951d847a0 100644 --- a/apps/server/src/serverActivation.ts +++ b/apps/server/src/serverActivation.ts @@ -9,21 +9,20 @@ export class ServerActivation extends Context.Reference | un { defaultValue: () => undefined }, ) {} -export const forkParkedFiber = ( +export const forkParkedFiber = Effect.fn("serverActivation.forkParkedFiber")(function* ( effect: Effect.Effect, -): Effect.Effect, never, Scope.Scope | R> => - Effect.gen(function* () { - const activation = yield* ServerActivation; - if (activation === undefined) { - return yield* Effect.forkScoped(effect); - } - const parked = yield* Deferred.make(); - const fiber = yield* Effect.forkScoped( - Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)), - ); - yield* Deferred.await(parked); - return fiber; - }); +): Effect.fn.Return, never, Scope.Scope | R> { + const activation = yield* ServerActivation; + if (activation === undefined) { + return yield* Effect.forkScoped(effect); + } + const parked = yield* Deferred.make(); + const fiber = yield* Effect.forkScoped( + Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)), + ); + yield* Deferred.await(parked); + return fiber; +}); export const forkParked = ( effect: Effect.Effect, diff --git a/apps/server/src/serverLifecycleEvents.test.ts b/apps/server/src/serverLifecycleEvents.test.ts deleted file mode 100644 index 28ba41125b57f..0000000000000 --- a/apps/server/src/serverLifecycleEvents.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { EnvironmentId } from "@t3tools/contracts"; -import { assert, it } from "@effect/vitest"; -import { assertTrue } from "@effect/vitest/utils"; -import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; - -import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; - -it.effect( - "publishes lifecycle events without subscribers and snapshots the latest welcome/ready", - () => - Effect.gen(function* () { - const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; - const environment = { - environmentId: EnvironmentId.make("environment-test"), - label: "Test environment", - platform: { os: "darwin" as const, arch: "arm64" as const }, - serverVersion: "0.0.0-test", - capabilities: { repositoryIdentity: true }, - }; - - const welcome = yield* lifecycleEvents - .publish({ - version: 1, - type: "welcome", - payload: { - environment, - cwd: "/tmp/project", - projectName: "project", - }, - }) - .pipe(Effect.timeoutOption("50 millis")); - assertTrue(Option.isSome(welcome)); - assert.equal(welcome.value.sequence, 1); - - const ready = yield* lifecycleEvents - .publish({ - version: 1, - type: "ready", - payload: { - at: "2026-01-01T00:00:00.000Z", - environment, - }, - }) - .pipe(Effect.timeoutOption("50 millis")); - assertTrue(Option.isSome(ready)); - assert.equal(ready.value.sequence, 2); - - yield* lifecycleEvents.publish({ - version: 1, - type: "legacyThreadMigration", - payload: { - status: "running", - totalThreadCount: 12, - }, - }); - yield* lifecycleEvents.publish({ - version: 1, - type: "legacyThreadMigration", - payload: { - status: "complete", - totalThreadCount: 12, - }, - }); - - const snapshot = yield* lifecycleEvents.snapshot; - assert.equal(snapshot.sequence, 4); - assert.deepEqual(snapshot.events.map((event) => event.type).toSorted(), [ - "legacyThreadMigration", - "ready", - "welcome", - ]); - const migration = snapshot.events.find((event) => event.type === "legacyThreadMigration"); - assert.equal(migration?.payload.status, "complete"); - }).pipe(Effect.provide(ServerLifecycleEvents.layer)), -); diff --git a/apps/server/src/serverLogger.test.ts b/apps/server/src/serverLogger.test.ts index 23eb39b3f5f76..fec4db2541517 100644 --- a/apps/server/src/serverLogger.test.ts +++ b/apps/server/src/serverLogger.test.ts @@ -1,12 +1,15 @@ import * as NodePath from "@effect/platform-node/NodePath"; import { assert, describe, it } from "@effect/vitest"; import * as NodeOS from "node:os"; +import * as NodeUtil from "node:util"; + import { ExternalLauncherBrowserSpawnError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import * as ConfigProvider from "effect/ConfigProvider"; +import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; +import * as Redactable from "effect/Redactable"; import * as Path from "effect/Path"; import * as Tracer from "effect/Tracer"; import * as HttpClient from "effect/http/HttpClient"; @@ -92,24 +95,6 @@ const layerConfig = (overrides: Partial) = }), ).pipe(Layer.provide(NodePath.layer)); -/** - * The export is asserted after the layer's scope closes, which is where the - * exporter flushes whatever the interval did not. - */ -const logThrough = (overrides: Partial) => - Effect.gen(function* () { - const requests: Array = []; - yield* Effect.log("server logger under test").pipe( - Effect.provide( - ServerLogger.layer.pipe( - Layer.provide(layerConfig(overrides)), - Layer.provide(layerCollector(requests)), - ), - ), - ); - return requests; - }); - /** * Runs `program` (one log line by default) inside a span so the tracer logger * has somewhere to attach an event, then reports both what the collector @@ -147,97 +132,79 @@ const logInSpanThrough = ( return { requests, spans }; }); +const printThroughConsole = (fields: object) => + Effect.gen(function* () { + const printed: Array = []; + const testConsole = { + ...globalThis.console, + log: (...args: ReadonlyArray) => { + printed.push(NodeUtil.format(...args)); + }, + } satisfies Console.Console; + yield* Effect.logWarning("pull request watch check failed", fields).pipe( + Effect.provide( + ServerLogger.layer.pipe(Layer.provide(layerConfig({})), Layer.provide(layerCollector([]))), + ), + Effect.provideService(Console.Console, testConsole), + ); + return printed.join("\n"); + }); + describe("ServerLoggerLive", () => { - it.effect("exports log records to the configured logs endpoint", () => + it.effect("exports a resource that names whether the desktop app launched the server", () => Effect.gen(function* () { - const requests = yield* logThrough({ + const { requests } = yield* logInSpanThrough({ otlpLogsUrl: "https://collector.example.com/v1/logs", + mode: "desktop", }); - assert.lengthOf(requests, 1); - const [request] = requests; - assert.strictEqual(request?.url, "https://collector.example.com/v1/logs"); - assert.include(request?.body ?? "", "server logger under test"); - assert.include(request?.body ?? "", "t3code-server"); - assert.include(request?.body ?? "", "service.runtime"); + const body = requests.map((request) => request.body).join("\n"); + assert.include(body, '"key":"t3code.server.managed_by","value":{"stringValue":"desktop"}'); + assert.notInclude(body, "service.mode"); }), ); - it.effect("keeps its service name while OTEL resource attributes add dimensions", () => + it.effect("prints a cause passed as a log field instead of collapsing it", () => Effect.gen(function* () { - const requests = yield* logThrough({ - otlpLogsUrl: "https://collector.example.com/v1/logs", - }).pipe( - Effect.provide( - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { - OTEL_SERVICE_NAME: "renamed", - OTEL_RESOURCE_ATTRIBUTES: - "service.name=renamed,service.namespace=renamed,deployment.environment.name=development", - }, - }), - ), - ), - ); - - assert.lengthOf(requests, 1); - const body = requests[0]?.body ?? ""; - assert.include(body, '"stringValue":"t3code-server"'); - assert.include(body, "deployment.environment.name"); - assert.include(body, '"key":"service.namespace","value":{"stringValue":"t3code"}'); - assert.notInclude(body, "renamed"); - }), - ); - - it.effect("stays off the network when no logs endpoint is configured", () => - Effect.gen(function* () { - const requests = yield* logThrough({}); + const output = yield* printThroughConsole({ + threadId: "thread-1", + cause: Cause.fail(new Error("gh: HTTP 502 from api.github.com")), + }); - assert.lengthOf(requests, 0); + assert.include(output, "threadId: 'thread-1'"); + assert.include(output, "gh: HTTP 502 from api.github.com"); + assert.notInclude(output, "[Object]"); }), ); - it.effect("sends the headers and wire format the log signal asked for", () => + // regression: #16642 logs printed causes as [Object] + it.effect("leaves getters uncalled while printing a cause field", () => Effect.gen(function* () { - const requests = yield* logThrough({ - otlpLogsUrl: "https://collector.example.com/v1/logs", - otlpLogsExport: { - ...DEFAULT_SIGNAL_EXPORT, - protocol: "http/protobuf", - headers: { "x-scope": "logs" }, + const output = yield* printThroughConsole({ + cause: Cause.fail(new Error("upstream refused")), + get detail(): string { + throw new Error("getter must not run"); }, }); - assert.lengthOf(requests, 1); - assert.strictEqual(requests[0]?.headers["x-scope"], "logs"); - assert.strictEqual(requests[0]?.headers["content-type"], "application/x-protobuf"); - }), - ); - - it.effect("attaches log messages to the active span when no logs endpoint is configured", () => - Effect.gen(function* () { - const { requests, spans } = yield* logInSpanThrough({}); - - assert.lengthOf(requests, 0); - assert.lengthOf(spans, 1); - assert.deepEqual( - spans[0]?.events.map(([name]) => name), - ["server logger under test"], - ); + assert.include(output, "upstream refused"); + assert.notInclude(output, "getter must not run"); }), ); - it.effect("stops duplicating messages onto the span once log records are exported", () => + it.effect("leaves a message with its own redaction hook to that hook", () => Effect.gen(function* () { - const { requests, spans } = yield* logInSpanThrough({ - otlpLogsUrl: "https://collector.example.com/v1/logs", + const output = yield* printThroughConsole({ + token: "secret-token-value", + cause: Cause.fail(new Error("upstream refused")), + [Redactable.symbolRedactable](this: { readonly cause: unknown }) { + return { token: "", cause: Cause.isCause(this.cause) ? "cause" : "missing" }; + }, }); - assert.lengthOf(requests, 1); - assert.include(requests[0]?.body ?? "", "server logger under test"); - assert.lengthOf(spans, 1); - assert.lengthOf(spans[0]?.events ?? [], 0); + assert.include(output, "token: ''"); + assert.include(output, "cause: 'cause'"); + assert.notInclude(output, "secret-token-value"); }), ); @@ -279,7 +246,6 @@ describe("ServerLoggerLive", () => { it.effect("keeps the token out of traces when the browser fails to open", () => Effect.gen(function* () { - // A failed launch records its error, which names the target, on its span. const failingLaunch = maybeOpenBrowser(pairingUrl).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.ts index 2b61d843f2542..d138175029799 100644 --- a/apps/server/src/serverLogger.ts +++ b/apps/server/src/serverLogger.ts @@ -1,14 +1,47 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SharedObservability from "@t3tools/shared/observability"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; +import * as Redactable from "effect/Redactable"; import * as References from "effect/References"; import * as OtlpExporter from "effect/observability/OtlpExporter"; import * as OtlpLogger from "effect/observability/OtlpLogger"; import * as ServerConfig from "./config.ts"; +// consolePretty collapses Cause fields via util.inspect; render them with Cause.pretty like standalone arguments. +const consolePretty = (): Logger.Logger => { + const pretty = Logger.consolePretty(); + return Logger.make((options) => + pretty.log({ + ...options, + message: Array.isArray(options.message) + ? options.message.map(prettyCauseFields) + : prettyCauseFields(options.message), + }), + ); +}; + +function prettyCauseFields(value: unknown): unknown { + if (typeof value !== "object" || value === null) return value; + const prototype: unknown = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) return value; + // A message with its own redaction hook already decides how it prints. + if (Redactable.isRedactable(value)) return value; + // Copy descriptors to preserve symbols without invoking getters. + const descriptors = Object.getOwnPropertyDescriptors(value); + let changed = false; + for (const descriptor of Object.values(descriptors)) { + if ("value" in descriptor && Cause.isCause(descriptor.value)) { + descriptor.value = Cause.pretty(descriptor.value); + changed = true; + } + } + return changed ? Object.create(prototype, descriptors) : value; +} + export const layer = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const hostName = yield* HostProcess.Hostname; @@ -25,17 +58,12 @@ export const layer = Effect.gen(function* () { resource: ServerConfig.otlpResource(config, hostName), }); - // `Logger.layer` writes the whole logger set rather than adding to it, so - // every logger the server wants has to be named in this one call. - // `Logger.tracerLogger` reaches a collector by attaching each message to the - // active span as a span event, which covers only messages logged inside a - // recorded span and files them under traces. The OTLP logger carries the same - // messages as log records stamped with their trace and span ids, so it is a - // superset: keeping both would export every in-span message twice. + // Logger.layer replaces the whole set; name every logger here. + // OTLP includes traced messages as log records, so also using tracerLogger would duplicate in-span exports. const layerLogger = Logger.layer( otlpLogger === undefined - ? [Logger.consolePretty(), Logger.tracerLogger] - : [Logger.consolePretty(), otlpLogger], + ? [consolePretty(), Logger.tracerLogger] + : [consolePretty(), otlpLogger], { mergeWithExisting: false }, ).pipe( Layer.provide(OtlpExporter.layerFlusher), diff --git a/apps/server/src/serverOwnership.ts b/apps/server/src/serverOwnership.ts index 4c4811de09e50..1959735425515 100644 --- a/apps/server/src/serverOwnership.ts +++ b/apps/server/src/serverOwnership.ts @@ -8,10 +8,25 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Crypto from "effect/Crypto"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Runtime from "effect/Runtime"; import * as Schema from "effect/Schema"; +import { + BOOT_SERVICE_LAUNCHD_LABEL, + BOOT_SERVICE_PLIST_FILE, + BOOT_SERVICE_UNIT_FILE, + bootServiceBaseDirOf, +} from "./cloud/bootService.ts"; +import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts"; +import { + SERVICE_LAUNCHER_CONTEXT_ENV, + SERVICE_RESTART_PENDING_FILE, + SERVICE_STATE_FILE, + compareExactServiceVersions, + serviceStateActiveVersion, +} from "./cloud/serviceProtocol.ts"; import * as ProcessRunner from "./processRunner.ts"; import { clearPersistedServerRuntimeState, @@ -25,8 +40,7 @@ export class ServerAlreadyRunningError extends Schema.TaggedError()( + "OlderBootServiceError", + { baseDir: Schema.String }, +) { + override readonly [Runtime.errorExitCode] = SERVER_EXIT_CODE_STATE_DIR_OWNED; + + override get message(): string { + return `A T3 Code background service set up for ${this.baseDir} may still run a release without the ownership lock. On that machine, try \`t3 update\` and let it restart (or run \`t3 service restart\` if the update is already installed). If the older launcher cannot update, run \`t3 service uninstall\`, then reinstall with \`t3 service install\` from a current CLI. You can also leave the service uninstalled. Pass \`--base-dir ${this.baseDir}\` to each command, and use \`npx t3@latest\` if \`t3\` is not installed or is outdated. Then retry. No server was stopped.`; + } +} + export class ServerOwnershipError extends Schema.TaggedError()( "ServerOwnershipError", { stateDir: Schema.String, cause: Schema.Defect() }, @@ -48,10 +73,7 @@ const isSqliteBusy = (cause: unknown) => (("errcode" in cause && cause.errcode === 5) || ("code" in cause && cause.code === "SQLITE_BUSY")); -/** - * Servers from before this lock only publish `server-runtime.json`. Treat - * their record as stale only when the process start time proves PID reuse. - */ +// Pre-lock servers publish only runtime state; require start-time proof of PID reuse before treating it as stale. const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* ( state: PersistedServerRuntimeState, ) { @@ -83,6 +105,75 @@ const legacyOwnerIsLive = Effect.fn("legacyOwnerIsLive")(function* ( return !Number.isFinite(startedAt) || startedAt <= recordedAt + 1_000; }); +// Pre-lock services become invisible when another server replaces their runtime +// record. Unreadable configuration or an unavailable manager allows startup. +const olderBootServiceHome = Effect.fn("olderBootServiceHome")( + function* (stateDir: string) { + if ( + (yield* ServiceLauncherHostProcess).connected && + (yield* HostProcess.Environment)[SERVICE_LAUNCHER_CONTEXT_ENV] !== undefined + ) { + return undefined; + } + const platform = yield* HostProcess.Platform; + const uid = yield* HostProcess.UserId; + if (platform !== "linux" && (platform !== "darwin" || uid === undefined)) return undefined; + + const homeDir = yield* HostProcess.HomeDirectory; + const fs = yield* FileSystem.FileSystem; + const runner = yield* ProcessRunner.ProcessRunner; + const unitPath = + platform === "darwin" + ? NodePath.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE) + : NodePath.join(homeDir, ".config", "systemd", "user", BOOT_SERVICE_UNIT_FILE); + const baseDir = bootServiceBaseDirOf(yield* fs.readFileString(unitPath)); + if ( + baseDir === undefined || + (yield* fs.realPath(NodePath.join(baseDir, "userdata"))) !== (yield* fs.realPath(stateDir)) + ) { + return undefined; + } + const runtimeDir = NodePath.join(baseDir, "runtime"); + const version = serviceStateActiveVersion( + yield* fs.readFileString(NodePath.join(runtimeDir, SERVICE_STATE_FILE)), + ); + if (version === undefined) return undefined; + const run = (command: string, args: ReadonlyArray) => + runner.run({ command, args, timeout: Duration.seconds(5), maxOutputBytes: 65_536 }); + let loaded: boolean; + if (platform === "darwin") { + loaded = + (yield* run("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`])).code === 0; + if (!loaded) { + const disabled = yield* run("launchctl", ["print-disabled", `gui/${uid}`]); + // Older macOS versions print `true` instead of `disabled`. + if ( + disabled.code !== 0 || + disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => disabled`) || + disabled.stdout.includes(`"${BOOT_SERVICE_LAUNCHD_LABEL}" => true`) + ) + return undefined; + } + } else { + const active = yield* run("systemctl", ["--user", "is-active", BOOT_SERVICE_UNIT_FILE]); + // A unit waiting out its Restart= delay is activating, with exit code 3. + loaded = active.code === 0 || (active.code === 3 && active.stdout.trim() === "activating"); + if (!loaded) { + const enabled = yield* run("systemctl", ["--user", "is-enabled", BOOT_SERVICE_UNIT_FILE]); + if (enabled.code !== 0 || enabled.stdout.trim() !== "enabled") return undefined; + } + } + // A deferred update names the staged runtime, not the loaded service's runtime. + if (loaded && (yield* fs.exists(NodePath.join(runtimeDir, SERVICE_RESTART_PENDING_FILE)))) { + return baseDir; + } + // Stable 0.1.0 shipped the ownership lock. Earlier lock-aware prereleases + // are conservatively refused because older runtimes expose no capability marker. + return compareExactServiceVersions(version, "0.1.0") < 0 ? baseDir : undefined; + }, + Effect.orElseSucceed(() => undefined), +); + /** * Hold an exclusive lock on the state directory until the scope closes. The * lock is an exclusive transaction on `server-owner.sqlite`, which never holds @@ -137,6 +228,10 @@ export const acquireServerOwnership = Effect.fn("acquireServerOwnership")(functi ) { return yield* new ServerAlreadyRunningError({ stateDir }); } + const olderServiceHome = yield* olderBootServiceHome(stateDir); + if (olderServiceHome !== undefined) { + return yield* new OlderBootServiceError({ baseDir: olderServiceHome }); + } return { publish: (state: PersistedServerRuntimeState) => diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts index a919f6720fbfa..59f6b67f04509 100644 --- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts +++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts @@ -5,6 +5,7 @@ import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; 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 Path from "effect/Path"; import { HttpServer } from "effect/http"; @@ -30,6 +31,7 @@ import { ServerActivation } from "./serverActivation.ts"; import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; import * as ServerSettings from "./serverSettings.ts"; +import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; @@ -163,6 +165,9 @@ it.effect("parks automatic pull until activation without delaying command readin ), }), 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)({}), diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 48666f55ce7e7..c1fef2623ae8f 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -1,53 +1,245 @@ import { assert, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { DEFAULT_SERVER_SETTINGS, - DEFAULT_MODEL, ProjectId, ProviderInstanceId, + ProviderDriverKind, + CommandId, + EnvironmentId, + type ServerLifecycleStreamEvent, } from "@t3tools/contracts"; +import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability"; +import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; +import { HttpServer } from "effect/http"; +import * as NetAddress from "effect/net/NetAddress"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Ref from "effect/Ref"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import * as ServerConfig from "./config.ts"; import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; +import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; +import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; +import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; +import * as Keybindings from "./keybindings.ts"; +import * as EffectWorker from "./orchestration-v2/EffectWorker.ts"; +import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; +import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; +import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; +import * as ProviderRuntimeRecovery from "./orchestration-v2/ProviderRuntimeRecoveryService.ts"; +import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; +import * as ThreadLaunch from "./orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadManagement from "./orchestration-v2/ThreadManagementService.ts"; +import * as ExternalLauncher from "./process/externalLauncher.ts"; +import * as ProjectService from "./project/ProjectService.ts"; +import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; +import { ServerActivation } from "./serverActivation.ts"; +import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; +import * as ServerSettings from "./serverSettings.ts"; +import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; +import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; -it("uses the canonical Codex model for auto-bootstrap", () => { - assert.deepEqual(ServerRuntimeStartup.getAutoBootstrapThreadModelSelection(), { - instanceId: ProviderInstanceId.make("codex"), - model: DEFAULT_MODEL, - }); -}); - -it.effect("starts without scanning or rebuilding projection history", () => - Effect.gen(function* () { - const calls = yield* Ref.make>([]); - const record = (label: string) => Ref.update(calls, (current) => [...current, label]); - - const result = yield* ServerRuntimeStartup.runOrderedV2StartupPhases({ - importLegacyShells: record("import"), - recover: record("recover").pipe(Effect.as({ closedRequests: 2 })), - recoverDelegatedTasks: record("delegated"), - startEffectWorker: record("worker"), - autoBootstrap: record("bootstrap").pipe(Effect.as({ projectId: "project-1" })), - }); - - assert.deepEqual(yield* Ref.get(calls), [ - "import", - "recover", - "delegated", - "worker", - "bootstrap", - ]); - assert.deepEqual(result, { - recovery: { closedRequests: 2 }, - bootstrap: { projectId: "project-1" }, - }); - }), +it.effect.each([ + "disabled-codex", + "disabled-default", + "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 }, + }), + }), + 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)({ + getShellSnapshot: () => + Effect.succeed({ + threads: [], + archivedThreads: [], + schemaVersion: 1, + snapshotSequence: 0, + }), + }), + 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, + prepareTrial: Effect.succeed(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), + ); + }), + ), ); it.effect("interrupts the effect worker when awareness relay startup fails", () => @@ -113,21 +305,6 @@ it.effect("enqueueCommand fails queued work when readiness fails", () => ), ); -it.effect("resolveWelcomeBase derives cwd and project name from server config", () => - Effect.gen(function* () { - const welcome = yield* ServerRuntimeStartup.resolveWelcomeBase.pipe( - Effect.provideService(ServerConfig.ServerConfig, { - cwd: "/tmp/startup-project", - } as never), - ); - - assert.deepStrictEqual(welcome, { - cwd: "/tmp/startup-project", - projectName: "startup-project", - }); - }), -); - it.effect("automatic pull only updates enabled, behind, clean default-branch checkouts", () => Effect.gen(function* () { const pulled: string[] = []; diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 78d9d3f0e0bd6..43b37a6a056d0 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -45,6 +45,7 @@ import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; import * as ServerSettings from "./serverSettings.ts"; import { forkParked, forkParkedFiber } from "./serverActivation.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; +import { getServerOwners } from "./telemetry/Identify.ts"; import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { @@ -109,37 +110,39 @@ export const makeCommandGate = Effect.gen(function* () { ); yield* Effect.forkScoped(commandWorker); + const enqueueCommand = Effect.fn("serverRuntimeStartup.enqueueCommand")(function* ( + effect: Effect.Effect, + ): Effect.fn.Return { + const readinessState = yield* Ref.get(commandReadinessState); + if (readinessState === "ready") { + return yield* effect; + } + if (readinessState !== "pending") { + return yield* readinessState; + } + + const result = yield* Deferred.make(); + yield* Queue.offer(commandQueue, { + run: Deferred.await(commandReady).pipe( + Effect.flatMap(() => effect), + Effect.exit, + Effect.flatMap((exit) => settleQueuedCommand(result, exit)), + ), + }); + return yield* Deferred.await(result); + }); + return { awaitCommandReady: Deferred.await(commandReady), signalCommandReady: Effect.gen(function* () { yield* Ref.set(commandReadinessState, "ready"); yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie); }), - failCommandReady: (error) => - Effect.gen(function* () { - yield* Ref.set(commandReadinessState, error); - yield* Deferred.fail(commandReady, error).pipe(Effect.orDie); - }), - enqueueCommand: (effect: Effect.Effect) => - Effect.gen(function* () { - const readinessState = yield* Ref.get(commandReadinessState); - if (readinessState === "ready") { - return yield* effect; - } - if (readinessState !== "pending") { - return yield* readinessState; - } - - const result = yield* Deferred.make(); - yield* Queue.offer(commandQueue, { - run: Deferred.await(commandReady).pipe( - Effect.flatMap(() => effect), - Effect.exit, - Effect.flatMap((exit) => settleQueuedCommand(result, exit)), - ), - }); - return yield* Deferred.await(result); - }), + failCommandReady: Effect.fn("serverRuntimeStartup.failCommandReady")(function* (error) { + yield* Ref.set(commandReadinessState, error); + yield* Deferred.fail(commandReady, error).pipe(Effect.orDie); + }), + enqueueCommand, } satisfies CommandGate; }); @@ -172,9 +175,10 @@ const recordStartupHeartbeat = Effect.gen(function* () { threadCount, projectCount, }); + yield* analytics.recordOwners(yield* getServerOwners, "server"); }); -export const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({ +const getAutoBootstrapThreadModelSelection = (): ModelSelection => ({ instanceId: ProviderInstanceId.make("codex"), model: DEFAULT_MODEL, }); @@ -244,7 +248,7 @@ export const autoPullProjects = Effect.fn("autoPullProjects")(function* ( ); }); -export const resolveWelcomeBase = Effect.gen(function* () { +const resolveWelcomeBase = Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; const segments = serverConfig.cwd.split(/[/\\]/).filter(Boolean); const projectName = segments[segments.length - 1] ?? "project"; @@ -283,22 +287,38 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () { if (existingThread === undefined) { const serverSettings = yield* ServerSettings.ServerSettingsService; const settings = yield* serverSettings.getSettings; - const launched = yield* threadLaunch.launch({ - commandId: CommandId.make(yield* randomUUID), - projectId: project.id, - title: "New thread", - modelSelection: - resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ?? - threadModelSelection, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - runtimeMode: resolveProjectSettings(settings, project.id, project).settings - .defaultRuntimeMode, - workspaceStrategy: { type: "root" }, - createdBy: "system", - creationSource: "server", - }); + const launched = yield* threadLaunch + .launch({ + commandId: CommandId.make(yield* randomUUID), + projectId: project.id, + title: "New thread", + modelSelection: + resolveProjectSettings(settings, project.id, project).settings.defaultModelSelection ?? + threadModelSelection, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: resolveProjectSettings(settings, project.id, project).settings + .defaultRuntimeMode, + workspaceStrategy: { type: "root" }, + createdBy: "system", + creationSource: "server", + }) + .pipe( + // The bootstrap thread is optional; its launch must not prevent opening the app. + Effect.catchTags({ + ThreadManagementProviderInstanceDisabledError: (error) => + Effect.logInfo("Skipped bootstrap thread because its provider instance is disabled", { + projectId: project.id, + instanceId: error.instanceId, + }).pipe(Effect.as(undefined)), + ThreadLaunchError: (error) => + Effect.logWarning("Failed to launch bootstrap thread", { + projectId: project.id, + operation: error.operation, + }).pipe(Effect.as(undefined)), + }), + ); bootstrapProjectId = project.id; - bootstrapThreadId = launched.threadId; + bootstrapThreadId = launched?.threadId; } else { bootstrapProjectId = project.id; bootstrapThreadId = existingThread.id; @@ -325,44 +345,37 @@ const resolveStartupBrowserTarget = Effect.gen(function* () { : yield* serverAuth.issueStartupPairingUrl(baseTarget); }); -/** - * Prints the startup pairing URL to stdout, where `t3` users and the dev runner - * read it. The URL carries a one-time admin token, so it skips the logger: log - * records also land in the trace file and any configured OTLP collector. - */ +/** Prints the one-time admin pairing URL to stdout only; logger records reach trace files and collectors. */ export const announceStartupPairingUrl = (pairingUrl: string) => Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe( - // Indented to match the annotation line the pretty logger printed before. Effect.andThen(Console.log(` pairingUrl: ${pairingUrl}`)), ); -// No URL here: the browser target carries the pairing token, which -// announceStartupPairingUrl has already printed to stdout. +// Pairing tokens belong only in announceStartupPairingUrl's stdout output. export const logBrowserAutoOpenUnavailable = Effect.logInfo("browser auto-open unavailable", { hint: "Open the pairing URL above in your browser.", }); -export const maybeOpenBrowser = (target: string) => - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - if (serverConfig.noBrowser) { - return; - } - const externalLauncher = yield* ExternalLauncher.ExternalLauncher; +export const maybeOpenBrowser = Effect.fn("serverRuntimeStartup.maybeOpenBrowser")(function* ( + target: string, +) { + const serverConfig = yield* ServerConfig.ServerConfig; + if (serverConfig.noBrowser) { + return; + } + const externalLauncher = yield* ExternalLauncher.ExternalLauncher; - yield* externalLauncher.launchBrowser(target).pipe( - // The target carries the pairing token, and a failed launch records its - // command line on the span, so this call stays out of traces. - Effect.withTracerEnabled(false), - Effect.catch(() => logBrowserAutoOpenUnavailable), - ); - }); + yield* externalLauncher.launchBrowser(target).pipe( + // The target carries the pairing token, and a failed launch records its + // command line on the span, so this call stays out of traces. + Effect.withTracerEnabled(false), + Effect.catch(() => logBrowserAutoOpenUnavailable), + ); +}); const runStartupPhase = (phase: string, effect: Effect.Effect) => effect.pipe( - // Attributes on the span itself, not annotateSpans: an annotation follows - // every fiber forked inside the phase, such as the effect worker, for the - // life of the server. + // Use span attributes; annotations would follow long-lived forked fibers for the server's lifetime. Effect.withSpan(`server.startup.${phase}`, { attributes: { "startup.phase": phase } }), ); @@ -397,313 +410,309 @@ export const startEffectWorkerWithRelay = Effect.fn( ); }); -export function runOrderedV2StartupPhases< - Import, - Recovery, - Bootstrap, - ImportError, - RecoveryError, - DelegationError, - WorkerError, - BootstrapError, - ImportContext, - RecoveryContext, - DelegationContext, - WorkerContext, - BootstrapContext, ->(input: { - readonly importLegacyShells: Effect.Effect; - readonly recover: Effect.Effect; - readonly recoverDelegatedTasks: Effect.Effect; - readonly startEffectWorker: Effect.Effect; - readonly autoBootstrap: Effect.Effect; -}) { - return Effect.gen(function* () { +const runOrderedV2StartupPhases = Effect.fn("serverRuntimeStartup.runOrderedV2StartupPhases")( + function* < + Import, + Recovery, + Bootstrap, + ImportError, + RecoveryError, + DelegationError, + WorkerError, + BootstrapError, + ImportContext, + RecoveryContext, + DelegationContext, + WorkerContext, + BootstrapContext, + >(input: { + readonly importLegacyShells: Effect.Effect; + readonly recover: Effect.Effect; + readonly recoverDelegatedTasks: Effect.Effect; + readonly startEffectWorker: Effect.Effect; + readonly autoBootstrap: Effect.Effect; + }) { yield* input.importLegacyShells; const recovery = yield* input.recover; yield* input.recoverDelegatedTasks; yield* input.startEffectWorker; const bootstrap = yield* input.autoBootstrap; return { recovery, bootstrap } as const; - }); -} + }, +); -const make = (options?: StartupOptions) => - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const keybindings = yield* Keybindings.Keybindings; - const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; - const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; - const orchestrator = yield* Orchestrator.OrchestratorV2; - const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; - const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; - const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; - const crypto = yield* Crypto.Crypto; - const launcher = yield* ServiceLauncherClient.ServiceLauncherClient; - - const commandGate = yield* makeCommandGate; - const httpListening = yield* Deferred.make(); - const effectWorkerFiber = yield* Ref.make | null>(null); - - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - yield* commandGate.failCommandReady( - new ServerRuntimeStartupError({ - mode: serverConfig.mode, - host: serverConfig.host ?? null, - port: serverConfig.port, - cause: "Server runtime is shutting down.", - }), - ); - const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null); - if (workerFiber !== null) { - yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore); - } - yield* providerRuntimeRecovery.prepareForShutdown.pipe( - Effect.ensuring(providerSessions.shutdown), - ); - const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown"); - yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation); - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("V2 orchestration shutdown reconciliation failed", { - cause: Cause.pretty(cause), +const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: StartupOptions) { + const serverConfig = yield* ServerConfig.ServerConfig; + const keybindings = yield* Keybindings.Keybindings; + const legacyV1ThreadImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; + const providerRuntimeRecovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; + const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; + const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents; + const serverSettings = yield* ServerSettings.ServerSettingsService; + const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; + const crypto = yield* Crypto.Crypto; + const launcher = yield* ServiceLauncherClient.ServiceLauncherClient; + + const commandGate = yield* makeCommandGate; + const httpListening = yield* Deferred.make(); + const effectWorkerFiber = yield* Ref.make | null>(null); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + yield* commandGate.failCommandReady( + new ServerRuntimeStartupError({ + mode: serverConfig.mode, + host: serverConfig.host ?? null, + port: serverConfig.port, + cause: "Server runtime is shutting down.", + }), + ); + const workerFiber = yield* Ref.getAndSet(effectWorkerFiber, null); + if (workerFiber !== null) { + yield* Fiber.interrupt(workerFiber).pipe(Effect.ignore); + } + yield* providerRuntimeRecovery.prepareForShutdown.pipe( + Effect.ensuring(providerSessions.shutdown), + ); + const reconciliation = yield* providerRuntimeRecovery.reconcile("shutdown"); + yield* Effect.logInfo("V2 orchestration shutdown reconciliation completed", reconciliation); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("V2 orchestration shutdown reconciliation failed", { + cause: Cause.pretty(cause), + }), + ), + ), + ); + + const startup = Effect.gen(function* () { + yield* Effect.logDebug("startup phase: starting keybindings runtime"); + yield* runStartupPhase( + "keybindings.start", + keybindings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start keybindings runtime", { + path: error.configPath, + detail: error.detail, + cause: error.cause, }), ), ), ); - const startup = Effect.gen(function* () { - yield* Effect.logDebug("startup phase: starting keybindings runtime"); - yield* runStartupPhase( - "keybindings.start", - keybindings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start keybindings runtime", { - path: error.configPath, - detail: error.detail, - cause: error.cause, - }), - ), + yield* Effect.logDebug("startup phase: starting server settings runtime"); + yield* runStartupPhase( + "settings.start", + serverSettings.start.pipe( + Effect.catch((error) => + Effect.logWarning("failed to start server settings runtime", { + path: error.settingsPath, + operation: error.operation, + providerInstanceId: error.providerInstanceId, + environmentVariable: error.environmentVariable, + cause: error.cause, + }), ), - ); + ), + ); - yield* Effect.logDebug("startup phase: starting server settings runtime"); - yield* runStartupPhase( - "settings.start", - serverSettings.start.pipe( - Effect.catch((error) => - Effect.logWarning("failed to start server settings runtime", { - path: error.settingsPath, - operation: error.operation, - providerInstanceId: error.providerInstanceId, - environmentVariable: error.environmentVariable, - cause: error.cause, - }), + const welcomeBase = yield* resolveWelcomeBase; + const environment = yield* serverEnvironment.getDescriptor; + const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount; + if (legacyMigrationThreadCount > 0) { + yield* lifecycleEvents.publish({ + version: 1, + type: "legacyThreadMigration", + payload: { + status: "running", + totalThreadCount: legacyMigrationThreadCount, + }, + }); + } + const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({ + importLegacyShells: runStartupPhase( + "orchestration-v2.legacy-v1.import-shells", + legacyV1ThreadImporter.reconcileShells.pipe( + Effect.tap((summary) => + summary.importedThreadCount === 0 + ? Effect.void + : Effect.logInfo("Imported legacy v1 thread shells", summary), ), ), - ); + ), + recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover), + recoverDelegatedTasks: runStartupPhase( + "orchestration-v2.delegated-tasks.recover", + orchestrator.recoverDelegatedTasks, + ), + startEffectWorker: runStartupPhase( + "orchestration-v2.effect-worker.start", + startEffectWorkerWithRelay({ + runWorker: EffectWorker.runDaemon, + startRelay: agentAwarenessRelay.start(), + workerFiberRef: effectWorkerFiber, + }), + ), + autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd + ? runStartupPhase( + "welcome.autobootstrap", + resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)), + ) + : Effect.succeed({}) + ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)), + }); + yield* Effect.logInfo("V2 orchestration recovery completed", recovery); + // Runs after activation: the status check fetches every enabled project's + // remote, and awaiting it here held command readiness for that long. + yield* runStartupPhase( + "projects.auto-pull", + Effect.gen(function* () { + const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells(); + const settings = yield* serverSettings.getSettings; + yield* autoPullProjects(projects, settings); + }), + ).pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to load projects for automatic pull", { cause }), + ), + forkParked, + ); - const welcomeBase = yield* resolveWelcomeBase; - const environment = yield* serverEnvironment.getDescriptor; - const legacyMigrationThreadCount = yield* legacyV1ThreadImporter.pendingThreadCount; - if (legacyMigrationThreadCount > 0) { - yield* lifecycleEvents.publish({ - version: 1, - type: "legacyThreadMigration", - payload: { - status: "running", - totalThreadCount: legacyMigrationThreadCount, - }, - }); - } - const { recovery, bootstrap: bootstrapTargets } = yield* runOrderedV2StartupPhases({ - importLegacyShells: runStartupPhase( - "orchestration-v2.legacy-v1.import-shells", - legacyV1ThreadImporter.reconcileShells.pipe( - Effect.tap((summary) => - summary.importedThreadCount === 0 - ? Effect.void - : Effect.logInfo("Imported legacy v1 thread shells", summary), + const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe( + Effect.tap((summary) => + summary.importedThreadCount === 0 + ? Effect.void + : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary), + ), + ); + yield* ( + legacyMigrationThreadCount > 0 + ? importPendingTranscripts.pipe( + Effect.tap(() => + lifecycleEvents.publish({ + version: 1, + type: "legacyThreadMigration", + payload: { + status: "complete", + totalThreadCount: legacyMigrationThreadCount, + }, + }), ), - ), - ), - recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover), - recoverDelegatedTasks: runStartupPhase( - "orchestration-v2.delegated-tasks.recover", - orchestrator.recoverDelegatedTasks, - ), - startEffectWorker: runStartupPhase( - "orchestration-v2.effect-worker.start", - startEffectWorkerWithRelay({ - runWorker: EffectWorker.runDaemon, - startRelay: agentAwarenessRelay.start(), - workerFiberRef: effectWorkerFiber, - }), - ), - autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd - ? runStartupPhase( - "welcome.autobootstrap", - resolveAutoBootstrapWelcomeTargets.pipe(Effect.provideService(Crypto.Crypto, crypto)), - ) - : Effect.succeed({}) - ).pipe(Effect.map((targets): AutoBootstrapWelcomeTargets => targets)), - }); - yield* Effect.logInfo("V2 orchestration recovery completed", recovery); - // Runs after activation: the status check fetches every enabled project's - // remote, and awaiting it here held command readiness for that long. - yield* runStartupPhase( - "projects.auto-pull", - Effect.gen(function* () { - const projects = yield* (yield* ProjectStore.ProjectStoreV2).listShells(); - const settings = yield* serverSettings.getSettings; - yield* autoPullProjects(projects, settings); - }), - ).pipe( - Effect.catch((cause) => - Effect.logWarning("Failed to load projects for automatic pull", { cause }), - ), - forkParked, - ); + ) + : importPendingTranscripts + ).pipe(forkParked); - const importPendingTranscripts = legacyV1ThreadImporter.importPendingTranscripts.pipe( - Effect.tap((summary) => - summary.importedThreadCount === 0 - ? Effect.void - : Effect.logInfo("Hydrated legacy v1 thread transcripts", summary), - ), - ); - yield* ( - legacyMigrationThreadCount > 0 - ? importPendingTranscripts.pipe( - Effect.tap(() => - lifecycleEvents.publish({ - version: 1, - type: "legacyThreadMigration", - payload: { - status: "complete", - totalThreadCount: legacyMigrationThreadCount, - }, - }), - ), - ) - : importPendingTranscripts - ).pipe(forkParked); - - yield* forkParked( - Effect.gen(function* () { - yield* Effect.logDebug("startup phase: recording startup heartbeat"); - yield* recordStartupHeartbeat.pipe( - Effect.withSpan("server.startup.heartbeat.record", { - attributes: { "startup.phase": "heartbeat.record" }, - }), - Effect.ignoreCause({ log: true }), + yield* forkParked( + Effect.gen(function* () { + yield* Effect.logDebug("startup phase: recording startup heartbeat"); + yield* recordStartupHeartbeat.pipe( + Effect.withSpan("server.startup.heartbeat.record", { + attributes: { "startup.phase": "heartbeat.record" }, + }), + Effect.ignoreCause({ log: true }), + ); + if (serverConfig.startupPresentation === "headless") { + yield* Effect.logDebug("startup phase: headless access info"); + const accessInfo = yield* issueHeadlessServeAccessInfo(); + yield* runStartupPhase( + "headless.output", + Console.log(formatHeadlessServeOutput(accessInfo)), ); - if (serverConfig.startupPresentation === "headless") { - yield* Effect.logDebug("startup phase: headless access info"); - const accessInfo = yield* issueHeadlessServeAccessInfo(); - yield* runStartupPhase( - "headless.output", - Console.log(formatHeadlessServeOutput(accessInfo)), - ); - } else { - yield* Effect.logDebug("startup phase: browser open check"); - const startupBrowserTarget = yield* resolveStartupBrowserTarget; - if (serverConfig.mode !== "desktop") { - yield* announceStartupPairingUrl(startupBrowserTarget); - } - yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget)); + } else { + yield* Effect.logDebug("startup phase: browser open check"); + const startupBrowserTarget = yield* resolveStartupBrowserTarget; + if (serverConfig.mode !== "desktop") { + yield* announceStartupPairingUrl(startupBrowserTarget); } - }), - ); - - yield* Effect.logDebug("startup phase: waiting for http listener"); - yield* runStartupPhase("http.wait", Deferred.await(httpListening)); - yield* runStartupPhase( - "auxiliary-roots.parked", - options?.awaitAuxiliaryParked ?? Effect.void, - ); + yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget)); + } + }), + ); - const updateOutcome = yield* launcher.prepareTrial; + yield* Effect.logDebug("startup phase: waiting for http listener"); + yield* runStartupPhase("http.wait", Deferred.await(httpListening)); + yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void); - yield* Effect.logDebug("startup phase: publishing welcome event", { - environmentId: environment.environmentId, - cwd: welcomeBase.cwd, - projectName: welcomeBase.projectName, - bootstrapProjectId: bootstrapTargets.bootstrapProjectId, - bootstrapThreadId: bootstrapTargets.bootstrapThreadId, - }); - yield* runStartupPhase( - "welcome.publish", - lifecycleEvents.publish({ - version: 1, - type: "welcome", - payload: { - environment, - ...welcomeBase, - ...bootstrapTargets, - }, - }), - ); + const updateOutcome = yield* launcher.prepareTrial; - yield* options?.activate ?? Effect.void; - yield* Effect.logDebug("Accepting commands"); - yield* commandGate.signalCommandReady; - yield* Effect.logDebug("startup phase: publishing ready event"); - yield* runStartupPhase( - "ready.publish", - lifecycleEvents.publish({ - version: 1, - type: "ready", - payload: { - at: DateTime.formatIso(yield* DateTime.now), - environment, - ...(updateOutcome === undefined ? {} : { updateOutcome }), - }, - }), - ); - yield* Effect.logDebug("startup phase: complete"); - yield* flushCompileCache; - }).pipe( - Effect.withSpan("server.startup", { - kind: "server", - root: true, - attributes: { - "server.mode": serverConfig.mode, - "server.port": serverConfig.port, - "server.host": serverConfig.host ?? "default", + yield* Effect.logDebug("startup phase: publishing welcome event", { + environmentId: environment.environmentId, + cwd: welcomeBase.cwd, + projectName: welcomeBase.projectName, + bootstrapProjectId: bootstrapTargets.bootstrapProjectId, + bootstrapThreadId: bootstrapTargets.bootstrapThreadId, + }); + yield* runStartupPhase( + "welcome.publish", + lifecycleEvents.publish({ + version: 1, + type: "welcome", + payload: { + environment, + ...welcomeBase, + ...bootstrapTargets, }, }), ); - yield* Effect.forkScoped( - Effect.exit(startup).pipe( - Effect.flatMap((startupExit) => { - if (Exit.isSuccess(startupExit)) return Effect.void; - const error = new ServerRuntimeStartupError({ - mode: serverConfig.mode, - host: serverConfig.host ?? null, - port: serverConfig.port, - cause: startupExit.cause, - }); - return Effect.logError("server runtime startup failed", { - cause: Cause.pretty(startupExit.cause), - }).pipe( - Effect.andThen(commandGate.failCommandReady(error)), - Effect.andThen(options?.abort?.(error) ?? Effect.void), - ); - }), - ), + yield* options?.activate ?? Effect.void; + yield* Effect.logDebug("Accepting commands"); + yield* commandGate.signalCommandReady; + yield* Effect.logDebug("startup phase: publishing ready event"); + yield* runStartupPhase( + "ready.publish", + lifecycleEvents.publish({ + version: 1, + type: "ready", + payload: { + at: DateTime.formatIso(yield* DateTime.now), + environment, + ...(updateOutcome === undefined ? {} : { updateOutcome }), + }, + }), ); + yield* Effect.logDebug("startup phase: complete"); + yield* flushCompileCache; + }).pipe( + Effect.withSpan("server.startup", { + kind: "server", + root: true, + attributes: { + "server.mode": serverConfig.mode, + "server.port": serverConfig.port, + "server.host": serverConfig.host ?? "default", + }, + }), + ); - return { - awaitCommandReady: commandGate.awaitCommandReady, - markHttpListening: Deferred.succeed(httpListening, undefined), - enqueueCommand: commandGate.enqueueCommand, - } satisfies ServerRuntimeStartup["Service"]; - }); + yield* Effect.forkScoped( + Effect.exit(startup).pipe( + Effect.flatMap((startupExit) => { + if (Exit.isSuccess(startupExit)) return Effect.void; + const error = new ServerRuntimeStartupError({ + mode: serverConfig.mode, + host: serverConfig.host ?? null, + port: serverConfig.port, + cause: startupExit.cause, + }); + return Effect.logError("server runtime startup failed", { + cause: Cause.pretty(startupExit.cause), + }).pipe( + Effect.andThen(commandGate.failCommandReady(error)), + Effect.andThen(options?.abort?.(error) ?? Effect.void), + ); + }), + ), + ); + + return { + awaitCommandReady: commandGate.awaitCommandReady, + markHttpListening: Deferred.succeed(httpListening, undefined), + enqueueCommand: commandGate.enqueueCommand, + } satisfies ServerRuntimeStartup["Service"]; +}); export const layerWithOptions = (options?: StartupOptions) => Layer.effect(ServerRuntimeStartup, make(options)); diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts index 34ab05bc3a708..abafbc7e24f62 100644 --- a/apps/server/src/serverRuntimeState.test.ts +++ b/apps/server/src/serverRuntimeState.test.ts @@ -1,27 +1,144 @@ import { assert, describe, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; -import * as References from "effect/References"; -import * as Schema from "effect/Schema"; +import * as Runtime from "effect/Runtime"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts"; +import { ServiceLauncherHostProcess } from "./cloud/serviceLauncherClient.ts"; +import { SERVICE_LAUNCHER_CONTEXT_ENV } from "./cloud/serviceProtocol.ts"; import * as ProcessRunner from "./processRunner.ts"; import * as ServerOwnership from "./serverOwnership.ts"; import * as ServerRuntimeState from "./serverRuntimeState.ts"; -const isServerRuntimeStateError = Schema.is(ServerRuntimeState.ServerRuntimeStateError); +const startBesideBootService = Effect.fn("test.startBesideBootService")(function* (input: { + readonly platform: "darwin" | "linux"; + readonly outputs: Readonly>; + readonly unitServesOtherHome?: boolean; + readonly restartPending?: boolean; + readonly activeVersion?: string; + readonly npmRuntime?: boolean; + readonly missingServiceState?: boolean; + readonly environment?: NodeJS.ProcessEnv; + readonly connected?: boolean; +}) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-owner-boot-service-" }); + const t3Home = path.join(root, ".t3"); + const serviceHome = input.unitServesOtherHome ? path.join(root, "other") : t3Home; + for (const home of [t3Home, serviceHome]) { + yield* fs.makeDirectory(path.join(home, "userdata"), { recursive: true }); + } + yield* fs.makeDirectory(path.join(serviceHome, "runtime")); + const activeVersion = input.activeVersion ?? "0.0.42"; + if (!input.missingServiceState) { + yield* fs.writeFileString( + path.join(serviceHome, "runtime", "service-state.json"), + JSON.stringify({ protocol: input.npmRuntime ? 2 : 3, activeVersion }), + ); + } + if (input.npmRuntime) { + const versionDir = path.join(serviceHome, "runtime", "versions", activeVersion); + const entryPath = path.join(versionDir, "node_modules", "t3", "dist", "bin.mjs"); + yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true }); + yield* fs.writeFileString(entryPath, ""); + } + + if (input.restartPending) { + yield* fs.writeFileString( + path.join(serviceHome, "runtime", ".restart-pending"), + `${activeVersion}\n`, + ); + } + const plan = { + program: input.npmRuntime + ? ["/usr/bin/node", path.join(serviceHome, "runtime", "service-launcher.mjs")] + : [], + baseDir: serviceHome, + logPath: "", + unitPath: "", + }; + const [unitPath, unit] = + input.platform === "darwin" + ? [ + path.join(root, "Library", "LaunchAgents", "com.t3tools.t3code.service.plist"), + renderBootServicePlist(plan, { homeDir: root, environmentPath: "" }), + ] + : [ + path.join(root, ".config", "systemd", "user", "t3code.service"), + renderBootServiceUnit(plan), + ]; + yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true }); + yield* fs.writeFileString(unitPath, unit); -interface CapturedLog { - readonly message: unknown; - readonly annotations: Readonly>; -} + const probes: string[] = []; + const runner = ProcessRunner.ProcessRunner.of({ + run: (run) => + Effect.gen(function* () { + const probe = `${path.basename(run.command)} ${run.args.find((arg) => !arg.startsWith("--"))}`; + probes.push(probe); + const output = input.outputs[probe]; + return yield* output === undefined + ? Effect.fail( + new ProcessRunner.ProcessSpawnError({ + command: run.command, + argumentCount: run.args.length, + cause: new Error("not found"), + }), + ) + : Effect.succeed({ + stdout: output.stdout ?? "", + stderr: "", + code: ChildProcessSpawner.ExitCode(output.code), + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }); + }), + }); + const result = yield* Effect.scoped( + ServerOwnership.acquireServerOwnership(path.join(t3Home, "userdata", "server-runtime.json")), + ).pipe( + Effect.provideService(ProcessRunner.ProcessRunner, runner), + Effect.provideService(HostProcess.Platform, input.platform), + Effect.provideService(HostProcess.UserId, 501), + Effect.provideService(HostProcess.HomeDirectory, root), + Effect.provideService(HostProcess.Environment, input.environment ?? {}), + Effect.provideService(ServiceLauncherHostProcess, { + connected: input.connected ?? false, + send: () => false, + on: () => undefined, + off: () => undefined, + }), + Effect.result, + ); + assert.includeMembers( + ["launchctl print", "launchctl print-disabled", "systemctl is-active", "systemctl is-enabled"], + probes, + ); + return { result, t3Home }; +}); describe("server ownership", () => { - const layerOwnership = ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)); + // An empty home, so no boot service unit installed on this machine is read. + const layerOwnership = Layer.mergeAll( + ProcessRunner.layer, + Layer.effect( + HostProcess.HomeDirectory, + Effect.gen(function* () { + return yield* (yield* FileSystem.FileSystem).makeTempDirectoryScoped(); + }), + ), + Layer.succeed(HostProcess.Environment, {}), + ).pipe(Layer.provideMerge(NodeServices.layer)); const makeState = ServerRuntimeState.makePersistedServerRuntimeState({ config: { host: undefined, devUrl: undefined }, port: 3773, @@ -79,8 +196,8 @@ describe("server ownership", () => { const state = yield* makeState; yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, - // @effect-diagnostics-next-line globalDateInEffect:off - Legacy identity uses the real process start time, not TestClock. - state: { ...state, startedAt: new Date().toISOString() }, + // Any record time after this process started proves the PID was not reused. + state: { ...state, startedAt: "2100-01-01T00:00:00.000Z" }, }); const refused = yield* Effect.scoped(ServerOwnership.acquireServerOwnership(statePath)).pipe( Effect.flip, @@ -115,188 +232,168 @@ describe("server ownership", () => { assert.equal(Option.getOrThrow(remaining).ownerId, "other-owner"); }).pipe(Effect.provide(layerOwnership)), ); -}); - -describe("serverRuntimeState", () => { - it.effect("persists and reads the runtime state", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-server-runtime-state-test-", - }); - const statePath = path.join(root, "runtime", "server.json"); - const state: ServerRuntimeState.PersistedServerRuntimeState = { - version: 1, - pid: 123, - host: "127.0.0.1", - port: 4_971, - origin: "http://127.0.0.1:4971", - devUrl: "http://localhost:5733/", - startedAt: "2026-06-20T00:00:00.000Z", - }; - - yield* ServerRuntimeState.persistServerRuntimeState({ path: statePath, state }); - const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath); - - assert.deepEqual(Option.getOrThrow(restored), state); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("records the dev web URL when the server fronts a dev server", () => - Effect.gen(function* () { - const state = yield* ServerRuntimeState.makePersistedServerRuntimeState({ - config: { host: undefined, devUrl: new URL("http://localhost:5733") }, - port: 13_773, - }); - - assert.equal(state.devUrl, "http://localhost:5733/"); - assert.equal(state.origin, "http://127.0.0.1:13773"); - - const withoutDev = yield* ServerRuntimeState.makePersistedServerRuntimeState({ - config: { host: undefined, devUrl: undefined }, - port: 13_773, - }); - assert.isFalse("devUrl" in withoutDev); - }), - ); - - it.effect("marks a service-supervised server so CLIs can tell it from a manual one", () => - Effect.gen(function* () { - const managed = yield* ServerRuntimeState.makePersistedServerRuntimeState({ - config: { host: undefined, devUrl: undefined }, - port: 13_773, - serviceManaged: true, - }); - const manual = yield* ServerRuntimeState.makePersistedServerRuntimeState({ - config: { host: undefined, devUrl: undefined }, - port: 13_773, - }); - - assert.isTrue(managed.serviceManaged); - assert.isFalse("serviceManaged" in manual); - }), - ); - it.effect("treats a missing runtime state file as absent", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-server-runtime-state-test-", - }); - - const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState( - path.join(root, "missing.json"), - ); - - assert.isTrue(Option.isNone(restored)); - }).pipe(Effect.provide(NodeServices.layer)), - ); - - it.effect("preserves malformed state decode failures", () => { - const logs: CapturedLog[] = []; - const logger = Logger.make(({ fiber, message }) => { - logs.push({ - message, - annotations: fiber.getRef(References.CurrentLogAnnotations), - }); - }); - - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-server-runtime-state-test-", - }); - const statePath = path.join(root, "server.json"); - yield* fileSystem.writeFileString(statePath, "{not json"); - - const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath); + describe("beside an installed boot service", () => { + it.effect("refuses an old active or scheduled service even without its runtime record", () => + Effect.gen(function* () { + for (const fixture of [ + { + platform: "darwin", + outputs: { "launchctl print": { code: 0 } }, + }, + { + platform: "darwin", + outputs: { + "launchctl print": { code: 113 }, + "launchctl print-disabled": { + code: 0, + stdout: '"com.t3tools.t3code.service" => false', + }, + }, + }, + { + platform: "linux", + outputs: { + // Restart= keeps an otherwise disabled service alive during its restart delay. + "systemctl is-active": { code: 3, stdout: "activating\n" }, + "systemctl is-enabled": { code: 1, stdout: "disabled\n" }, + }, + }, + { + platform: "linux", + outputs: { + "systemctl is-active": { code: 3, stdout: "inactive\n" }, + "systemctl is-enabled": { code: 0, stdout: "enabled\n" }, + }, + }, + { + platform: "darwin", + outputs: { "launchctl print": { code: 0 } }, + environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" }, + }, + ] as const) { + const { result, t3Home } = yield* startBesideBootService(fixture); + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + assert.equal(result.failure._tag, "OlderBootServiceError"); + assert.equal(Runtime.getErrorExitCode(result.failure), 78); + assert.include(result.failure.message, t3Home); + assert.include(result.failure.message, "t3 update"); + assert.include(result.failure.message, "t3 service restart"); + assert.include(result.failure.message, "No server was stopped"); + } + }).pipe(Effect.provide(NodeServices.layer)), + ); - assert.isTrue(Option.isNone(restored)); - assert.equal(logs[0]?.message, `Failed to decode server runtime state at ${statePath}.`); - const error = logs[0]?.annotations.cause; - assert.isTrue(isServerRuntimeStateError(error)); - if (isServerRuntimeStateError(error)) { - assert.equal(error.operation, "decode"); - assert.equal(error.statePath, statePath); - assert.equal(error.message, `Failed to decode server runtime state at ${statePath}.`); - assert.deepInclude(error.cause, { _tag: "SchemaError" }); - } - }).pipe( - Effect.provide( - Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })), - ), + it.effect( + "refuses an active npm-installed service with no standalone executable or runtime record", + () => + Effect.gen(function* () { + const { result } = yield* startBesideBootService({ + platform: "linux", + activeVersion: "0.0.40", + npmRuntime: true, + outputs: { + "systemctl is-active": { code: 0, stdout: "active\n" }, + }, + }); + assert.equal(result._tag, "Failure"); + if (result._tag !== "Failure") return; + assert.equal(result.failure._tag, "OlderBootServiceError"); + assert.equal(Runtime.getErrorExitCode(result.failure), 78); + }).pipe(Effect.provide(NodeServices.layer)), ); - }); - it.effect("preserves runtime state read failures", () => { - const logs: CapturedLog[] = []; - const logger = Logger.make(({ fiber, message }) => { - logs.push({ - message, - annotations: fiber.getRef(References.CurrentLogAnnotations), - }); - }); + it.effect("refuses while the loaded service has not restarted into its lock-aware update", () => + Effect.gen(function* () { + const { result } = yield* startBesideBootService({ + platform: "darwin", + restartPending: true, + activeVersion: "0.1.0", + outputs: { + "launchctl print": { code: 0 }, + }, + }); + assert.equal(result._tag === "Failure" && result.failure._tag, "OlderBootServiceError"); + }).pipe(Effect.provide(NodeServices.layer)), + ); - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-server-runtime-state-test-", - }); - const statePath = path.join(root, "server.json"); - yield* fileSystem.makeDirectory(statePath); + it.effect("allows lock-aware stable services that are loaded or stopped and enabled", () => + Effect.gen(function* () { + for (const fixture of [ + { + platform: "darwin", + outputs: { + "launchctl print": { code: 0 }, + }, + }, + { + platform: "linux", + outputs: { + "systemctl is-active": { code: 3, stdout: "inactive\n" }, + "systemctl is-enabled": { code: 0, stdout: "enabled\n" }, + }, + }, + ] as const) { + const { result } = yield* startBesideBootService({ ...fixture, activeVersion: "0.1.0" }); + assert.equal(result._tag, "Success"); + } + }).pipe(Effect.provide(NodeServices.layer)), + ); - const restored = yield* ServerRuntimeState.readPersistedServerRuntimeState(statePath); + it.effect("allows services that cannot compete for this home", () => + Effect.gen(function* () { + const outputs = { + "launchctl print": { code: 0 }, + }; + for (const fixture of [ + { platform: "darwin", outputs, unitServesOtherHome: true }, + { + platform: "darwin", + outputs, + environment: { [SERVICE_LAUNCHER_CONTEXT_ENV]: "{}" }, + connected: true, + }, + { + platform: "darwin", + outputs: { + "launchctl print": { code: 113 }, + "launchctl print-disabled": { + code: 0, + stdout: '"com.t3tools.t3code.service" => disabled', + }, + }, + }, + { + platform: "linux", + outputs: { + "systemctl is-active": { code: 3, stdout: "inactive\n" }, + "systemctl is-enabled": { code: 1, stdout: "disabled\n" }, + }, + }, + ] as const) { + const { result } = yield* startBesideBootService(fixture); + assert.equal(result._tag, "Success"); + } + }).pipe(Effect.provide(NodeServices.layer)), + ); - assert.isTrue(Option.isNone(restored)); - assert.equal(logs[0]?.message, `Failed to read server runtime state at ${statePath}.`); - const error = logs[0]?.annotations.cause; - assert.isTrue(isServerRuntimeStateError(error)); - if (isServerRuntimeStateError(error)) { - assert.equal(error.operation, "read"); - assert.equal(error.statePath, statePath); - assert.equal(error.message, `Failed to read server runtime state at ${statePath}.`); - assert.deepInclude(error.cause, { _tag: "PlatformError" }); - } - }).pipe( - Effect.provide( - Layer.merge(NodeServices.layer, Logger.layer([logger], { mergeWithExisting: false })), - ), + it.effect("allows startup when the service configuration or manager is unavailable", () => + Effect.gen(function* () { + for (const fixture of [ + { outputs: {} }, + { + outputs: { + "launchctl print": { code: 113 }, + "launchctl print-disabled": { code: 1 }, + }, + }, + { outputs: { "launchctl print": { code: 0 } }, missingServiceState: true }, + ]) { + const { result } = yield* startBesideBootService({ platform: "darwin", ...fixture }); + assert.equal(result._tag, "Success"); + } + }).pipe(Effect.provide(NodeServices.layer)), ); }); - - it.effect("preserves runtime state persistence failures", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-server-runtime-state-test-", - }); - const blockedDirectory = path.join(root, "not-a-directory"); - const statePath = path.join(blockedDirectory, "server.json"); - yield* fileSystem.writeFileString(blockedDirectory, "blocked"); - - const error = yield* ServerRuntimeState.persistServerRuntimeState({ - path: statePath, - state: { - version: 1, - pid: 123, - port: 4_971, - origin: "http://127.0.0.1:4971", - startedAt: "2026-06-20T00:00:00.000Z", - }, - }).pipe(Effect.flip); - - assert.isTrue(isServerRuntimeStateError(error)); - if (isServerRuntimeStateError(error)) { - assert.equal(error.operation, "persist"); - assert.equal(error.statePath, statePath); - assert.equal(error.message, `Failed to persist server runtime state at ${statePath}.`); - assert.deepInclude(error.cause, { _tag: "PlatformError" }); - } - }).pipe(Effect.provide(NodeServices.layer)), - ); }); diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index 140020614fd7c..aca62ebb01ecf 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -14,6 +14,7 @@ export const PersistedServerRuntimeState = Schema.Struct({ pid: Schema.Int, ownerId: Schema.optional(Schema.String), host: Schema.optional(Schema.String), + privateNetworkOnly: Schema.optional(Schema.Boolean), port: Schema.Int, origin: Schema.String, // Dev is single-origin: browsers must pair through this URL, not `origin`. @@ -51,7 +52,10 @@ const runtimeOriginForConfig = ( }; export const makePersistedServerRuntimeState = (input: { - readonly config: Pick; + readonly config: Pick< + ServerConfig.ServerConfig["Service"], + "host" | "privateNetworkOnly" | "devUrl" + >; readonly port: number; readonly serviceManaged?: boolean; }): Effect.Effect => @@ -59,6 +63,7 @@ export const makePersistedServerRuntimeState = (input: { version: 1, pid: process.pid, ...(input.config.host ? { host: input.config.host } : {}), + ...(input.config.privateNetworkOnly ? { privateNetworkOnly: true } : {}), port: input.port, origin: runtimeOriginForConfig(input.config, input.port), ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}), @@ -85,35 +90,33 @@ export const persistServerRuntimeState = (input: { ), ); -export const clearPersistedServerRuntimeState = (path: string) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - yield* fs.remove(path, { force: true }).pipe( - Effect.mapError( - (cause) => - new ServerRuntimeStateError({ - operation: "clear", - statePath: path, - cause, +export const clearPersistedServerRuntimeState = Effect.fn( + "serverRuntimeState.clearPersistedServerRuntimeState", +)(function* (path: string) { + const fs = yield* FileSystem.FileSystem; + yield* fs.remove(path, { force: true }).pipe( + Effect.mapError( + (cause) => + new ServerRuntimeStateError({ + operation: "clear", + statePath: path, + cause, + }), + ), + Effect.catchTags({ + ServerRuntimeStateError: (error) => + Effect.logWarning(error.message).pipe( + Effect.annotateLogs({ + operation: error.operation, + statePath: error.statePath, + cause: error, }), - ), - Effect.catchTags({ - ServerRuntimeStateError: (error) => - Effect.logWarning(error.message).pipe( - Effect.annotateLogs({ - operation: error.operation, - statePath: error.statePath, - cause: error, - }), - ), - }), - ); - }); + ), + }), + ); +}); -/** - * Signal 0 delivers nothing; it only reports whether the pid exists. EPERM - * means it exists but belongs to another user, which still counts as alive. - */ +/** Signal 0 only probes existence; EPERM still means alive. */ export const isProcessAlive = (pid: number): boolean => { if (!Number.isInteger(pid) || pid <= 0) return false; try { @@ -124,8 +127,10 @@ export const isProcessAlive = (pid: number): boolean => { } }; -export const readPersistedServerRuntimeState = (path: string) => - Effect.gen(function* () { +export const readPersistedServerRuntimeState = Effect.fn( + "serverRuntimeState.readPersistedServerRuntimeState", +)( + function* (path: string) { const fs = yield* FileSystem.FileSystem; const raw = yield* fs.readFileString(path).pipe( Effect.matchEffect({ @@ -162,16 +167,16 @@ export const readPersistedServerRuntimeState = (path: string) => }), ), ); - }).pipe( - Effect.catchTags({ - ServerRuntimeStateError: (error) => - Effect.logWarning(error.message).pipe( - Effect.annotateLogs({ - operation: error.operation, - statePath: error.statePath, - cause: error, - }), - Effect.as(Option.none()), - ), - }), - ); + }, + Effect.catchTags({ + ServerRuntimeStateError: (error) => + Effect.logWarning(error.message).pipe( + Effect.annotateLogs({ + operation: error.operation, + statePath: error.statePath, + cause: error, + }), + Effect.as(Option.none()), + ), + }), +); diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 5287c5a3dbd9d..602375323b3f8 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -8,14 +8,12 @@ import { ProviderInstanceId, resolveProviderInstanceEnabled, ServerSettings, - ServerSettingsPatch, UsageLimitSourceId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; import { assert, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Duration from "effect/Duration"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; @@ -24,7 +22,6 @@ import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import * as SqlClient from "effect/sql/SqlClient"; import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; import { sourceControlHostSecretName } from "./sourceControl/sourceControlHostSecrets.ts"; @@ -34,7 +31,6 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; import * as ServerSettingsModule from "./serverSettings.ts"; import { resolveProviderInstanceTerminalEnvironment } from "./terminal/Manager.ts"; -const decodeSettingsPatch = Schema.decodeUnknownEffect(ServerSettingsPatch); const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings); const decodeServerSettingsJson = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings)); @@ -216,6 +212,29 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); + it.effect("moves an idle compaction mode saved in the legacy switch to its own field", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const service = yield* ServerSettingsModule.ServerSettingsService; + yield* fs.writeFileString(config.settingsPath, `{ "compactIdleThreads": "off" }`); + + const settings = yield* service.getSettings; + // Shipped clients decode the switch as a boolean and drop the config otherwise. + assert.strictEqual(settings.compactIdleThreads, false); + assert.equal(settings.idleCompaction, "off"); + }).pipe(Effect.provide(layerServerSettings())), + ); + + it.effect("tells clients it reads idle compaction modes before any settings are saved", () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const settings = yield* service.getSettings; + assert.equal(settings.idleCompaction, "onReturn"); + assert.strictEqual(settings.compactIdleThreads, false); + }).pipe(Effect.provide(layerServerSettings())), + ); + it.effect("saves through a symlinked settings file without replacing the link", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -238,154 +257,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("reloads when the destination of a symlinked settings file changes", () => - Effect.scoped( - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const service = yield* ServerSettingsModule.ServerSettingsService; - const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); - const linkedSettingsPath = path.join(dotfiles, "settings.json"); - yield* fs.writeFileString(linkedSettingsPath, `{ "responseStreamingMode": "turn" }`); - yield* fs.remove(config.settingsPath, { force: true }); - yield* fs.symlink(linkedSettingsPath, config.settingsPath); - yield* service.start; - const changes = yield* service.subscribeChanges; - - yield* writeFileStringAtomically({ - filePath: linkedSettingsPath, - contents: `{ "responseStreamingMode": "paragraph" }`, - }); - - const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds")); - assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph"); - }), - ).pipe(TestClock.withLive, Effect.provide(layerServerSettings())), - ); - - it.effect("follows a settings link that is repointed to another directory", () => - Effect.scoped( - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const service = yield* ServerSettingsModule.ServerSettingsService; - const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); - const firstSettingsPath = path.join(dotfiles, "first", "settings.json"); - const secondSettingsPath = path.join(dotfiles, "second", "settings.json"); - yield* fs.makeDirectory(path.dirname(firstSettingsPath), { recursive: true }); - yield* fs.makeDirectory(path.dirname(secondSettingsPath), { recursive: true }); - yield* fs.writeFileString(firstSettingsPath, `{ "responseStreamingMode": "turn" }`); - yield* fs.writeFileString(secondSettingsPath, `{ "responseStreamingMode": "paragraph" }`); - yield* fs.remove(config.settingsPath, { force: true }); - yield* fs.symlink(firstSettingsPath, config.settingsPath); - yield* service.start; - - const repointChanges = yield* service.subscribeChanges; - yield* fs.remove(config.settingsPath); - yield* fs.symlink(secondSettingsPath, config.settingsPath); - const repointed = yield* repointChanges.pipe(Stream.runHead, Effect.timeout("2 seconds")); - assert.equal(Option.getOrUndefined(repointed)?.responseStreamingMode, "paragraph"); - - const editChanges = yield* service.subscribeChanges; - yield* writeFileStringAtomically({ - filePath: secondSettingsPath, - contents: `{ "responseStreamingMode": "turn" }`, - }); - const edited = yield* editChanges.pipe(Stream.runHead, Effect.timeout("2 seconds")); - assert.equal(Option.getOrUndefined(edited)?.responseStreamingMode, "turn"); - }), - ).pipe(TestClock.withLive, Effect.provide(layerServerSettings())), - ); - - it.effect("reloads when a dangling settings link gets its destination", () => - Effect.scoped( - Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const service = yield* ServerSettingsModule.ServerSettingsService; - const dotfiles = yield* fs.makeTempDirectoryScoped({ prefix: "t3-settings-dotfiles-" }); - const linkedSettingsPath = path.join(dotfiles, "not-yet", "settings.json"); - yield* fs.remove(config.settingsPath, { force: true }); - yield* fs.symlink(linkedSettingsPath, config.settingsPath); - yield* service.start; - const changes = yield* service.subscribeChanges; - - yield* writeFileStringAtomically({ - filePath: linkedSettingsPath, - contents: `{ "responseStreamingMode": "paragraph" }`, - }); - - const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds")); - assert.equal(Option.getOrUndefined(change)?.responseStreamingMode, "paragraph"); - }), - ).pipe(TestClock.withLive, Effect.provide(layerServerSettings())), - ); - - it.effect("preserves context when reading a provider environment secret fails", () => { - const platformCause = PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "readFile", - pathOrDescriptor: "provider environment secret", - description: "Secret backend unavailable.", - }); - const cause = new ServerSecretStore.SecretStoreReadError({ - resource: "provider environment secret", - cause: platformCause, - }); - const layerConfig = Layer.fresh( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3code-server-settings-secret-failure-test-", - }), - ); - const layerSettings = ServerSettingsModule.layer.pipe( - Layer.provide(layerFailingSecretStore(cause)), - Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)), - Layer.provideMerge(layerConfig), - ); - - return Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - yield* fileSystem.writeFileString( - serverConfig.settingsPath, - '{"providerInstances":{"codex_personal":{"driver":"codex","environment":[{"name":"OPENROUTER_API_KEY","value":"","sensitive":true,"valueRedacted":true}],"config":{}}}}', - ); - - const error = yield* Effect.flip(serverSettings.getSettings); - - assert.deepInclude(error, { - _tag: "ServerSettingsError", - operation: "read-secret", - providerInstanceId: "codex_personal", - environmentVariable: "OPENROUTER_API_KEY", - }); - assert.strictEqual(error.cause, cause); - assert.notInclude(error.message, cause.message); - }).pipe(Effect.provide(layerSettings)); - }); - - it.effect("identifies provider history query failures", () => - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const sql = yield* SqlClient.SqlClient; - yield* sql`DROP TABLE projection_thread_sessions`; - - const error = yield* Effect.flip(serverSettings.getSettings); - - assert.deepInclude(error, { - _tag: "ServerSettingsError", - operation: "read-provider-history", - settingsPath: serverConfig.settingsPath, - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect("retries a failed settings read instead of keeping the failure", () => Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; @@ -408,23 +279,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("decodes nested settings patches", () => - Effect.gen(function* () { - assert.deepEqual( - yield* decodeSettingsPatch({ - textGenerationModelSelection: { - options: [{ id: "fastMode", value: false }], - }, - }), - { - textGenerationModelSelection: { - options: [{ id: "fastMode", value: false }], - }, - }, - ); - }), - ); - it.effect( "decodes legacy object-shaped textGenerationModelSelection.options from settings.json", () => @@ -488,6 +342,70 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); + it.effect("keeps an external settings edit that the watcher has not reloaded yet", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const serverSettings = yield* ServerSettingsModule.ServerSettingsService; + yield* serverSettings.getSettings; + + yield* writeFileStringAtomically({ + filePath: config.settingsPath, + contents: `{ "responseStreamingMode": "turn" }`, + }); + yield* serverSettings.updateSettings({ + observability: { otlpTracesUrl: "http://localhost:4318/v1/traces" }, + }); + + const saved = yield* decodeServerSettingsJson(yield* fs.readFileString(config.settingsPath)); + assert.equal(saved.responseStreamingMode, "turn"); + assert.equal(saved.observability.otlpTracesUrl, "http://localhost:4318/v1/traces"); + + yield* writeFileStringAtomically({ + filePath: config.settingsPath, + contents: `{ "responseStreamingMode": "paragraph" }`, + }); + const instanceId = ProviderInstanceId.make("acpRegistry_kilo"); + yield* serverSettings.updateProviderInstance({ + operation: "upsert", + instanceId, + instance: { + driver: ProviderDriverKind.make("acpRegistry"), + displayName: "Kilo", + config: { agentId: "kilo", distribution: "auto" }, + }, + }); + + const afterProviderSave = yield* decodeServerSettingsJson( + yield* fs.readFileString(config.settingsPath), + ); + assert.equal(afterProviderSave.responseStreamingMode, "paragraph"); + assert.equal(afterProviderSave.providerInstances[instanceId]?.displayName, "Kilo"); + }).pipe(Effect.provide(layerServerSettings())), + ); + + it.effect("refuses to save over a settings file it cannot parse", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const serverSettings = yield* ServerSettingsModule.ServerSettingsService; + yield* serverSettings.getSettings; + const raw = `{ "responseStreamingMode": "turn", `; + yield* fs.writeFileString(config.settingsPath, raw); + + const error = yield* Effect.flip( + serverSettings.updateSettings({ + observability: { otlpTracesUrl: "http://localhost:4318/v1/traces" }, + }), + ); + + assert.equal(error.operation, "read-file"); + assert.equal(error.settingsPath, config.settingsPath); + assert.instanceOf(error.cause, Error); + assert.equal(yield* fs.readFileString(config.settingsPath), raw); + }).pipe(Effect.provide(layerServerSettings())), + ); + it.effect("creates provider instances atomically without overwriting a concurrent add", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsModule.ServerSettingsService; @@ -627,33 +545,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { ).pipe(Effect.provide(layerServerSettings())), ); - it.effect("persists and broadcasts thread settlement settings", () => - Effect.scoped( - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const changes = yield* serverSettings.subscribeChanges; - - const next = yield* serverSettings.updateSettings({ - sidebarAutoSettleAfterDays: null, - sidebarAutoSettleOnMerge: false, - }); - const change = Option.getOrUndefined(yield* Stream.runHead(changes)); - const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); - - const persisted = JSON.parse(raw) as Record; - - assert.strictEqual(next.sidebarAutoSettleAfterDays, null); - assert.isFalse(next.sidebarAutoSettleOnMerge); - assert.strictEqual(change?.sidebarAutoSettleAfterDays, null); - assert.isFalse(change?.sidebarAutoSettleOnMerge); - assert.strictEqual(persisted.sidebarAutoSettleAfterDays, null); - assert.isFalse(persisted.sidebarAutoSettleOnMerge); - }), - ).pipe(Effect.provide(layerServerSettings())), - ); - it.effect("preserves model when switching providers via textGenerationModelSelection", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsModule.ServerSettingsService; @@ -689,31 +580,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("preserves custom provider instance text generation selections", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - - const next = yield* serverSettings.updateSettings({ - providerInstances: { - [ProviderInstanceId.make("claude_openrouter")]: { - driver: ProviderDriverKind.make("claudeAgent"), - enabled: true, - config: { customModels: ["openai/gpt-5.5"] }, - }, - }, - textGenerationModelSelection: { - instanceId: ProviderInstanceId.make("claude_openrouter"), - model: "openai/gpt-5.5", - }, - }); - - assert.deepEqual(next.textGenerationModelSelection, { - instanceId: ProviderInstanceId.make("claude_openrouter"), - model: "openai/gpt-5.5", - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect( "keeps a custom instance's selection when the driver's default instance is disabled", () => @@ -829,7 +695,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - // A backend behind a custom model may refuse the built-in default (#12651). + // A backend behind a custom model may refuse the built-in default. it.effect("falls back to the thread default when it is a custom model on that instance", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsModule.ServerSettingsService; @@ -867,32 +733,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("preserves enabled text generation selections for non-built-in drivers", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const instanceId = ProviderInstanceId.make("openrouter_text"); - - const next = yield* serverSettings.updateSettings({ - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("openrouter"), - enabled: true, - config: { customModels: ["openai/gpt-5.5"] }, - }, - }, - textGenerationModelSelection: { - instanceId, - model: "openai/gpt-5.5", - }, - }); - - assert.deepEqual(next.textGenerationModelSelection, { - instanceId, - model: "openai/gpt-5.5", - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect( "preserves the source control writer selection when its provider instance is disabled", () => @@ -959,76 +799,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("drops stale text generation options when resetting model selection", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - - yield* serverSettings.updateSettings({ - textGenerationModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - options: createModelSelection( - ProviderInstanceId.make("codex"), - DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - [ - { id: "reasoningEffort", value: "high" }, - { id: "fastMode", value: true }, - ], - ).options!, - }, - }); - - const next = yield* serverSettings.updateSettings({ - textGenerationModelSelection: { - instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId, - model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - }, - }); - - assert.deepEqual(next.textGenerationModelSelection, { - instanceId: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.instanceId, - model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model, - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - - it.effect("replaces provider instance maps when clearing optional fields", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const codexId = ProviderInstanceId.make("codex"); - - yield* serverSettings.updateSettings({ - providerInstances: { - [codexId]: { - driver: ProviderDriverKind.make("codex"), - displayName: "Codex Work", - accentColor: "#7c3aed", - enabled: true, - config: { homePath: "~/.codex" }, - }, - }, - }); - - const next = yield* serverSettings.updateSettings({ - providerInstances: { - [codexId]: { - driver: ProviderDriverKind.make("codex"), - displayName: "Codex Work", - enabled: true, - config: { homePath: "~/.codex" }, - }, - }, - }); - - assert.deepEqual(next.providerInstances[codexId], { - driver: ProviderDriverKind.make("codex"), - displayName: "Codex Work", - enabled: true, - config: { homePath: "~/.codex" }, - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect("moves customized legacy provider settings into default instances on load", () => Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; @@ -1155,20 +925,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("runs provider history only for files that still carry the legacy map", () => - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - yield* fileSystem.writeFileString(serverConfig.settingsPath, "{}"); - yield* recordProviderUsage("grok"); - - const settings = yield* serverSettings.getSettings; - - assert.deepEqual(settings.providerInstances, {}); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect("migrates legacy providers from an invalid file without rewriting it", () => Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; @@ -1190,22 +946,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("skips a disabled provider instance when picking the text generation fallback", () => - Effect.gen(function* () { - const serverConfig = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - yield* fileSystem.writeFileString( - serverConfig.settingsPath, - '{"providerInstances":{"codex":{"driver":"codex","enabled":false,"config":{}}}}', - ); - - const settings = yield* serverSettings.getSettings; - - assert.equal(settings.textGenerationModelSelection.instanceId, "claudeAgent"); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect("keeps a default-off provider's new instance disabled and sparse on disk", () => Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; @@ -1264,85 +1004,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("folds in-config enabled flags arriving through updates", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const grokId = ProviderInstanceId.make("grok"); - - const next = yield* serverSettings.updateSettings({ - providerInstances: { - [grokId]: { - driver: ProviderDriverKind.make("grok"), - enabled: true, - config: { enabled: false, binaryPath: "/opt/grok" }, - }, - }, - }); - - assert.deepEqual(next.providerInstances[grokId], { - driver: ProviderDriverKind.make("grok"), - enabled: false, - config: { binaryPath: "/opt/grok" }, - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - - it.effect("trims observability settings when updates are applied", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - - const next = yield* serverSettings.updateSettings({ - addProjectBaseDirectory: " ~/Development ", - observability: { - otlpTracesUrl: " http://localhost:4318/v1/traces ", - otlpMetricsUrl: " http://localhost:4318/v1/metrics ", - otlpLogsUrl: " http://localhost:4318/v1/logs ", - }, - }); - - assert.equal(next.addProjectBaseDirectory, "~/Development"); - assert.deepEqual(next.observability, { - otlpTracesUrl: "http://localhost:4318/v1/traces", - otlpMetricsUrl: "http://localhost:4318/v1/metrics", - otlpLogsUrl: "http://localhost:4318/v1/logs", - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - - it.effect("writes only non-default settings to disk", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const serverConfig = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - yield* serverSettings.updateSettings({ - addProjectBaseDirectory: "~/Development", - observability: { - otlpTracesUrl: "http://localhost:4318/v1/traces", - otlpMetricsUrl: "http://localhost:4318/v1/metrics", - }, - automaticGitFetchInterval: Duration.seconds(10), - }); - - const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); - assert.deepEqual(JSON.parse(raw), { - addProjectBaseDirectory: "~/Development", - observability: { - otlpTracesUrl: "http://localhost:4318/v1/traces", - otlpMetricsUrl: "http://localhost:4318/v1/metrics", - }, - backgroundActivity: { - schemaVersion: 1, - profile: "custom", - baseProfile: "balanced", - overrides: { - automaticGitFetchInterval: 10_000, - }, - }, - automaticGitFetchInterval: 10_000, - }); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect("keeps the inline value on disk when secret migration fails", () => { const cause = new ServerSecretStore.SecretStorePersistError({ resource: "provider environment secret", @@ -1526,6 +1187,17 @@ it.layer(NodeServices.layer)("server settings", (it) => { enabled: true, }, }, + easDeviceHosts: [ + { + kind: "eas", + id: "eas", + label: "EAS Simulator", + accessToken: "expo-secret", + maxSessionMinutes: 30, + idleMinutes: 10, + maxConcurrentSessions: 2, + }, + ], }); const values = [ "config-secret", @@ -1534,6 +1206,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { "bitbucket-secret", "gitcafe-secret", "quota-secret", + "expo-secret", ]; const client = ServerSettingsModule.redactServerSettingsForClient(saved); const disk = yield* fs.readFileString(config.settingsPath); @@ -1548,6 +1221,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { providerInstances: client.providerInstances, sourceControlHosts: client.sourceControlHosts, usageLimitSources: client.usageLimitSources, + easDeviceHosts: client.easDeviceHosts, }); for (const value of values) assert.include(JSON.stringify(echoed), value); const renamed = yield* service.updateProviderInstance({ @@ -1616,6 +1290,44 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettingsWithSecrets())), ); + it.effect("keeps speech-to-text API keys in the secret store", () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const store = yield* ServerSecretStore.ServerSecretStore; + const saved = yield* service.updateSettings({ + speechToText: { + provider: "groq", + language: "de", + providers: { groq: { apiKey: "groq-secret", model: "whisper-large-v3" } }, + }, + }); + assert.strictEqual(saved.speechToText.providers.groq?.apiKey, "groq-secret"); + const client = ServerSettingsModule.redactServerSettingsForClient(saved); + assert.strictEqual(client.speechToText.providers.groq?.apiKey, "••••••"); + assert.strictEqual(client.speechToText.providers.groq?.model, "whisper-large-v3"); + assert.notInclude(yield* fs.readFileString(config.settingsPath), "groq-secret"); + const secretName = "speech-to-text-Z3JvcQ-YXBpS2V5"; + assert.isTrue(Option.isSome(yield* store.get(secretName))); + + // Echoing the marker back while editing another field keeps the stored key. + const edited = yield* service.updateSettings({ + speechToText: { + providers: { groq: { apiKey: "••••••", model: "whisper-large-v3-turbo" } }, + }, + }); + assert.strictEqual(edited.speechToText.providers.groq?.apiKey, "groq-secret"); + assert.strictEqual(edited.speechToText.providers.groq?.model, "whisper-large-v3-turbo"); + + const cleared = yield* service.updateSettings({ + speechToText: { providers: { groq: { apiKey: "" } } }, + }); + assert.strictEqual(cleared.speechToText.providers.groq?.apiKey, ""); + assert.isTrue(Option.isNone(yield* store.get(secretName))); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + it.effect("moves saved provider credentials to the secret store when settings load", () => Effect.gen(function* () { const service = yield* ServerSettingsModule.ServerSettingsService; @@ -1650,7 +1362,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { assert.notInclude(yield* fs.readFileString(config.settingsPath), value); assert.notInclude(JSON.stringify(client), value); } - // Editing another field from the client's copy keeps the saved password. const clientConfig = client.providerInstances[opencode]?.config as Record; const edited = yield* service.updateProviderInstance({ operation: "upsert", @@ -1667,69 +1378,6 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(layerServerSettings())), ); - it.effect("stores sensitive provider instance environment values outside settings.json", () => - Effect.gen(function* () { - const serverSettings = yield* ServerSettingsModule.ServerSettingsService; - const serverConfig = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const instanceId = ProviderInstanceId.make("codex_personal"); - - const next = yield* serverSettings.updateSettings({ - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("codex"), - environment: [ - { name: "OPENROUTER_API_KEY", value: "sk-or-secret", sensitive: true }, - { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, - ], - config: {}, - }, - }, - }); - - assert.deepEqual(next.providerInstances[instanceId]?.environment, [ - { - name: "OPENROUTER_API_KEY", - value: "sk-or-secret", - sensitive: true, - valueRedacted: true, - }, - { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, - ]); - - const raw = yield* fileSystem.readFileString(serverConfig.settingsPath); - assert.notInclude(raw, "sk-or-secret"); - assert.deepEqual(JSON.parse(raw).providerInstances.codex_personal.environment, [ - { - name: "OPENROUTER_API_KEY", - value: "", - sensitive: true, - valueRedacted: true, - }, - { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, - ]); - - const roundTripped = yield* serverSettings.updateSettings({ - providerInstances: { - [instanceId]: { - driver: ProviderDriverKind.make("codex"), - displayName: "Codex Personal", - environment: [ - { name: "OPENROUTER_API_KEY", value: "", sensitive: true, valueRedacted: true }, - { name: "ANTHROPIC_BASE_URL", value: "https://openrouter.ai/api", sensitive: false }, - ], - config: {}, - }, - }, - }); - - assert.equal( - roundTripped.providerInstances[instanceId]?.environment?.[0]?.value, - "sk-or-secret", - ); - }).pipe(Effect.provide(layerServerSettings())), - ); - it.effect( "keeps source control host secrets in the secret store and tells clients only that one is set", () => diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index ad9a81f2d2040..3131c84d880e7 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -15,6 +15,8 @@ import { ServerSettings, ServerSettingsError, type ServerSettingsPatch, + globalIdleCompaction, + withIdleCompaction, } from "@t3tools/contracts"; import * as Cache from "effect/Cache"; import * as Cause from "effect/Cause"; @@ -23,6 +25,7 @@ import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Equal from "effect/Equal"; import * as Effect from "effect/Effect"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -67,18 +70,13 @@ const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings); const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder(); -/** - * Old settings files can hold both flags with conflicting values; an explicit false on either - * side wins so a user's disable is never silently undone. - */ +// Conflicting flags resolve to false to preserve user disables. const foldProviderInstanceEnabledFlags = (settings: ServerSettings): ServerSettings => { let changed = false; const providerInstances: Record = {}; for (const [instanceId, instance] of Object.entries(settings.providerInstances)) { const config = instance.config; - // Only fold boolean flags: a malformed `enabled` (e.g. `"false"`) must - // stay in the blob so driver schema validation flags it instead of the - // fold silently repairing the config. + // Leave malformed flags for driver schema validation rather than silently repairing them. if ( config === null || typeof config !== "object" || @@ -117,6 +115,7 @@ const normalizeServerSettings = ( encodeServerSettings(settings).pipe( Effect.flatMap(decodeServerSettings), Effect.map(foldProviderInstanceEnabledFlags), + Effect.map((next) => withIdleCompaction(next, globalIdleCompaction(next))), Effect.map((next) => ({ ...next, ...deriveLegacyProjectOverrides(next) })), Effect.mapError( (cause) => @@ -193,78 +192,71 @@ export class ServerSettingsService extends Context.Service< readonly streamChanges: Stream.Stream; - /** - * Use this before reading a snapshot when changes between the snapshot and - * a lazily started stream must not be lost. - */ + /** Subscribe before reading a snapshot to retain changes before lazy stream startup. */ readonly subscribeChanges: Effect.Effect, never, Scope.Scope>; } >()("t3/serverSettings/ServerSettingsService") { static readonly layerTest = (overrides: DeepPartial = {}) => layerTest(overrides); } -const makeTest = (overrides: DeepPartial = {}) => - Effect.gen(function* () { - const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } = - overrides; - const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge); - const initialSettings = yield* normalizeServerSettings({ - ...merged, - ...(automaticGitFetchInterval !== undefined - ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration } - : {}), - ...(providerHealthRefreshInterval !== undefined - ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration } - : {}), - }); - const currentSettingsRef = yield* Ref.make(initialSettings); - const writeSemaphore = yield* Semaphore.make(1); - const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)); - - const updateTestSettings = ( - update: (current: ServerSettings) => Effect.Effect, - ): Effect.Effect => - writeSemaphore.withPermits(1)( - Ref.get(currentSettingsRef).pipe( - Effect.flatMap(update), - Effect.flatMap(normalizeServerSettings), - Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)), - Effect.map(resolveTextGenerationProvider), - ), - ); - - return { - start: Effect.void, - ready: Effect.void, - getSettings, - updateSettings: (patch) => - updateTestSettings((currentSettings) => - Effect.succeed(applyServerSettingsPatch(currentSettings, patch)), - ), - updateProviderInstance: (mutation, patch = {}) => - updateTestSettings((currentSettings) => - Effect.gen(function* () { - yield* ensureProviderInstanceMutationAllowed( - currentSettings, - mutation, - "test settings", - ); - const patched = applyServerSettingsPatch(currentSettings, patch); - return applyProviderInstanceMutation(patched, mutation); - }), - ), - withSettingsSnapshot: (use) => - writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))), - streamChanges: Stream.empty, - subscribeChanges: Effect.succeed(Stream.empty), - } satisfies ServerSettingsService["Service"]; +const makeTest = Effect.fn("serverSettings.makeTest")(function* ( + overrides: DeepPartial = {}, +) { + const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } = + overrides; + const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge); + const initialSettings = yield* normalizeServerSettings({ + ...merged, + ...(automaticGitFetchInterval !== undefined + ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration } + : {}), + ...(providerHealthRefreshInterval !== undefined + ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration } + : {}), }); + const currentSettingsRef = yield* Ref.make(initialSettings); + const writeSemaphore = yield* Semaphore.make(1); + const getSettings = Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)); + + const updateTestSettings = ( + update: (current: ServerSettings) => Effect.Effect, + ): Effect.Effect => + writeSemaphore.withPermits(1)( + Ref.get(currentSettingsRef).pipe( + Effect.flatMap(update), + Effect.flatMap(normalizeServerSettings), + Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)), + Effect.map(resolveTextGenerationProvider), + ), + ); + + return { + start: Effect.void, + ready: Effect.void, + getSettings, + updateSettings: (patch) => + updateTestSettings((currentSettings) => + Effect.succeed(applyServerSettingsPatch(currentSettings, patch)), + ), + updateProviderInstance: (mutation, patch = {}) => + updateTestSettings((currentSettings) => + Effect.gen(function* () { + yield* ensureProviderInstanceMutationAllowed(currentSettings, mutation, "test settings"); + const patched = applyServerSettingsPatch(currentSettings, patch); + return applyProviderInstanceMutation(patched, mutation); + }), + ), + withSettingsSnapshot: (use) => + writeSemaphore.withPermits(1)(getSettings.pipe(Effect.flatMap(use))), + streamChanges: Stream.empty, + subscribeChanges: Effect.succeed(Stream.empty), + } satisfies ServerSettingsService["Service"]; +}); export const layerTest = (overrides: DeepPartial = {}) => Layer.effect(ServerSettingsService, makeTest(overrides)); -// Migrate saved token delivery without accepting it in settings writes or -// letting one retired value reset the rest of the environment's settings. +// Accept retired token delivery only on load so one old value cannot reset all settings. const PersistedResponseStreamingMode = Schema.Union([ ResponseStreamingMode, Schema.Literal("token"), @@ -495,9 +487,7 @@ interface LegacyProjectSettingsRow { readonly scripts: string; } -/** - * Marked with `projectSettingsFolded` so a later reset in the UI survives restarts. - */ +// projectSettingsFolded prevents restarts from undoing later UI resets. function foldLegacyProjectSettings( settings: ServerSettings, rows: ReadonlyArray, @@ -530,8 +520,7 @@ function foldLegacyProjectSettings( for (const [projectId, value] of Object.entries(settings.projectAutoPullOverrides)) { set(projectId, "defaultAutoPull", value); } - // A stored null meant "reset to machine defaults", which is now plain - // inheritance; the project's own aggregate scripts must not resurface. + // A stored null resets to machine defaults, so the project's aggregate scripts must not resurface. const resetScripts = new Set(); for (const [projectId, value] of Object.entries(settings.projectScriptOverrides)) { if (value === null) resetScripts.add(projectId); @@ -625,8 +614,8 @@ const make = Effect.gen(function* () { ), ); - const moveInlineSettingsSecrets = (settings: ServerSettings) => - Effect.gen(function* () { + const moveInlineSettingsSecrets = Effect.fn("serverSettings.moveInlineSettingsSecrets")( + function* (settings: ServerSettings) { const pending: SettingsSecret[] = []; mapSettingsSecrets(settings, (secret) => { if (secret.kind === "field" && !secret.redacted && secret.value.length > 0) { @@ -652,15 +641,14 @@ const make = Effect.gen(function* () { return mapSettingsSecrets(settings, (secret) => moved.has(secret.secretName) ? { value: "", redacted: true } : secret, ); - }); + }, + ); const loadSettingsFromDisk = Effect.gen(function* () { let settings = DEFAULT_SERVER_SETTINGS; let legacyProviders: Readonly> | undefined; let legacySourceControl: Parameters[1] = {}; - // A file that failed to decode must stay on disk for the user to repair; - // the fold below only writes when it started from the file's real contents. - let settingsFileTrusted = true; + let parseFailure = Option.none(); if (yield* readConfigExists) { const raw = yield* readRawConfig; @@ -675,10 +663,10 @@ const make = Effect.gen(function* () { } if (decoded._tag === "Failure" || legacySettings._tag === "Failure") { const failure = decoded._tag === "Failure" ? decoded : legacySettings; - settingsFileTrusted = false; // The file may hold an opt-out we can no longer read; never resume threads on a guess. settings = { ...DEFAULT_SERVER_SETTINGS, continueThreadsAfterServerUpdate: false }; if (failure._tag === "Failure") { + parseFailure = Option.some(Cause.squash(failure.cause)); yield* Effect.logWarning("failed to parse settings.json, using defaults", { path: settingsPath, issues: Cause.pretty(failure.cause), @@ -689,7 +677,13 @@ const make = Effect.gen(function* () { settings = decoded.value; } } + // Settings saved by a server that kept the mode in `compactIdleThreads` move + // it to `idleCompaction`, so that switch goes to clients as a boolean. The + // defaults gain the field too, which tells clients this server reads modes. + settings = withIdleCompaction(settings, globalIdleCompaction(settings)); + // A file that failed to decode must stay on disk for the user to repair. + const settingsFileTrusted = Option.isNone(parseFailure); const providerHistory = yield* sql<{ readonly providerName: string; readonly providerInstanceId: string | null; @@ -706,6 +700,7 @@ const make = Effect.gen(function* () { FROM provider_session_runtime WHERE provider_name IN ('cursor', 'grok', 'opencode') `.pipe( + NodeSqliteClient.readOnly, Effect.mapError( (cause) => new ServerSettingsError({ @@ -729,6 +724,7 @@ const make = Effect.gen(function* () { FROM projection_projects WHERE deleted_at IS NULL `.pipe( + NodeSqliteClient.readOnly, Effect.mapError( (cause) => new ServerSettingsError({ @@ -747,9 +743,7 @@ const make = Effect.gen(function* () { const folded = settingsFileTrusted ? foldLegacyProjectSettings(loaded, legacyProjectRows) : loaded; - // Copied, not moved: the old entry is removed only after the new file is written. A token - // that cannot be read or copied leaves the retired keys in place, so the migration runs again - // on the next load instead of dropping it. + // Remove retired keys only after copying secrets and writing the new file; failures retry on next load. const legacySecretsCopied = yield* Effect.forEach( settingsFileTrusted ? migrateLegacySourceControlSettings(folded, legacySourceControl).secretMoves @@ -787,23 +781,23 @@ const make = Effect.gen(function* () { yield* secretStore.remove(move.from).pipe(Effect.ignore); } } - return migrated; + return { settings: migrated, parseFailure }; }); - const settingsCache = yield* Cache.makeWith( - () => loadSettingsFromDisk, - { - capacity: 1, - timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero), - }, - ); + const settingsCache = yield* Cache.makeWith((_key: typeof cacheKey) => loadSettingsFromDisk, { + capacity: 1, + timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero), + }); - const getSettingsFromCache = Cache.get(settingsCache, cacheKey); + const getSettingsFromCache = Cache.get(settingsCache, cacheKey).pipe( + Effect.map((loaded) => loaded.settings), + ); + const reloadSettings = Cache.invalidate(settingsCache, cacheKey).pipe( + Effect.andThen(Cache.get(settingsCache, cacheKey)), + ); - const materializeSettingsSecrets = ( - settings: ServerSettings, - ): Effect.Effect => - Effect.gen(function* () { + const materializeSettingsSecrets = Effect.fn("serverSettings.materializeSettingsSecrets")( + function* (settings: ServerSettings): Effect.fn.Return { const storedSecrets = new Map(); const pending = new Map(); mapSettingsSecrets(settings, (secret) => { @@ -835,7 +829,8 @@ const make = Effect.gen(function* () { : secret.value, redacted: secret.sensitive && secret.kind === "environment" && secret.redacted, })); - }); + }, + ); const materializeChanges = (changes: Stream.Stream) => changes.pipe( @@ -1001,7 +996,14 @@ const make = Effect.gen(function* () { ): Effect.Effect => writeSemaphore.withPermits(1)( Effect.gen(function* () { - const current = yield* getSettingsFromCache; + const { settings: current, parseFailure } = yield* reloadSettings; + if (Option.isSome(parseFailure)) { + return yield* new ServerSettingsError({ + settingsPath, + operation: "read-file", + cause: parseFailure.value, + }); + } const updated = yield* update(current); const persisted = yield* persistSettingsSecrets(current, updated); const next = yield* normalizeServerSettings(persisted.settings); @@ -1021,7 +1023,7 @@ const make = Effect.gen(function* () { return materializedExit.value; }), ); - yield* Cache.set(settingsCache, cacheKey, next); + yield* Cache.set(settingsCache, cacheKey, { settings: next, parseFailure: Option.none() }); yield* emitChange(next); return resolveTextGenerationProvider(materialized); }), @@ -1038,8 +1040,7 @@ const make = Effect.gen(function* () { const revalidateAndEmit = writeSemaphore.withPermits(1)( Effect.gen(function* () { - yield* Cache.invalidate(settingsCache, cacheKey); - const settings = yield* getSettingsFromCache; + const { settings } = yield* reloadSettings; yield* emitChange(settings); }), ); @@ -1076,9 +1077,7 @@ const make = Effect.gen(function* () { const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); - // A symlinked settings file is rewritten in its destination's directory, - // which a watch on the link's directory never sees. The link is resolved - // again whenever it changes, so repointing it moves the watch along. + // Watch symlink targets' directories for rewrites; re-resolve link changes to follow repointing. const watchLinkTarget = Effect.gen(function* () { const linkTargetPath = yield* resolveSymlinkTarget(settingsPath).pipe( Effect.provideService(FileSystem.FileSystem, fs), @@ -1106,8 +1105,7 @@ const make = Effect.gen(function* () { ), ); - // Editors emit multiple events per save (truncate, write, rename) and - // `fs.watch` can fire before the content has been flushed to disk. + // Saves emit multiple events; fs.watch may fire before content is flushed. const debouncedSettingsEvents = Stream.merge( watchFileChanges(settingsPath), linkTargetEvents, @@ -1128,8 +1126,7 @@ const make = Effect.gen(function* () { const startup = Effect.gen(function* () { yield* startWatcher; - yield* Cache.invalidate(settingsCache, cacheKey); - yield* getSettingsFromCache; + yield* reloadSettings; }); const startupExit = yield* Effect.exit(startup); diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 3381b76305369..70550f2379272 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -12,7 +12,8 @@ import { vi } from "vite-plus/test"; import { databaseBackupBlocker, Launcher, - PREPARED_TIMEOUT_MS, + main, + readServiceEnvironment, type BackupSpaceProbe, readServiceState, writeServiceState, @@ -21,9 +22,9 @@ import { compareExactServiceVersions, decodeServiceState, isExactServiceVersion, + SERVICE_ENV_FILE, SERVICE_LAUNCHER_PROTOCOL, SERVICE_RESTART_PENDING_FILE, - SERVICE_STOP_MARKER_FILE, } from "./cloud/serviceProtocol.ts"; const spawnedChildren = vi.hoisted((): Array => []); @@ -126,20 +127,50 @@ const writeFakeRuntime = ( }); it.layer(NodeServices.layer)("service state persistence", (it) => { - it.effect("durably replaces and strictly reads one state document", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-test-" }); - const statePath = path.join(root, "runtime", "service-state.json"); - const state = { - protocol: SERVICE_LAUNCHER_PROTOCOL, - activeVersion: "0.0.31", - } as const; - - yield* Effect.promise(() => writeServiceState(statePath, state)); - assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), state); - }), + it.effect( + "loads optional service.env literally without changing inherited or managed variables", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-env-" }); + const inherited = Object.freeze({ + PATH: "inherited-path", + T3CODE_HOME: root, + T3_BOOT_SERVICE_UNIT: "managed-unit", + T3_SERVICE_LAUNCHER_CONTEXT: "managed-context", + T3CODE_PORT: "ambient", + }); + assert.deepEqual( + yield* Effect.promise(() => readServiceEnvironment(root, inherited)), + inherited, + ); + yield* fs.writeFileString( + path.join(root, SERVICE_ENV_FILE), + [ + "# service configuration", + "export T3CODE_PORT=1234 # inline comment", + 'T3CODE_TOKEN="literal $HOME ${USER} $(whoami) # token"', + 'MULTILINE="first\nsecond"', + "EMPTY=", + "PATH=/bad", + "Path=/bad", + "T3CODE_HOME=/bad", + "t3code_home=/bad", + "T3_BOOT_SERVICE_UNIT=bad", + "t3_boot_service_unit=bad", + "T3_SERVICE_LAUNCHER_CONTEXT=bad", + "t3_service_launcher_context=bad", + ].join("\n"), + ); + assert.deepEqual(yield* Effect.promise(() => readServiceEnvironment(root, inherited)), { + ...inherited, + T3CODE_PORT: "1234", + T3CODE_TOKEN: "literal $HOME ${USER} $(whoami) # token", + MULTILINE: "first\nsecond", + EMPTY: "", + }); + }), ); it.effect("a fresh launcher clears a restart deferred by t3 update", () => @@ -222,34 +253,6 @@ it.layer(NodeServices.layer)("service state persistence", (it) => { }), ); - it.effect("serializes shutdown with launcher recovery", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-stop-" }); - const statePath = path.join(root, "runtime", "service-state.json"); - yield* writeFakeRuntime( - fs, - path, - path.join(root, "runtime", "versions", "1.0.0"), - "setInterval(() => {}, 1_000);\n", - ); - yield* Effect.promise(() => - writeServiceState(statePath, { - protocol: SERVICE_LAUNCHER_PROTOCOL, - activeVersion: "1.0.0", - }), - ); - - const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath))); - const running = launcher.run(); - const stopping = launcher.stop("SIGTERM"); - assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE))); - yield* Effect.promise(() => stopping); - yield* Effect.promise(() => running); - }), - ); - it.effect("commits only after the trial reports prepared", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -303,21 +306,33 @@ if (context.update?.status === "pending") { }), ); - it.effect("rolls back a trial that reports the wrong update ID", () => + it.effect("rolls back invalid trials with the startup environment", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-rollback-" }); const statePath = path.join(root, "runtime", "service-state.json"); const databasePath = path.join(root, "userdata", "state.sqlite"); + const observationsPath = path.join(root, "environment-observations.jsonl"); + const envPath = path.join(root, SERVICE_ENV_FILE); + yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n"); + vi.stubEnv("T3CODE_HOME", root); + vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited"); + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true }); yield* fs.writeFileString(databasePath, "before trial"); const encodedDatabasePath = JSON.stringify(databasePath); const childSource = ` +import { appendFileSync, writeFileSync } from "node:fs"; const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT); +appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({ + token: process.env.T3CODE_TEST_SERVICE_TOKEN, + update: context.update?.status ?? "active", +}) + "\\n"); if (context.update?.status === "pending") { process.send({ type: "prepared", updateId: "wrong-update" }); } else if (context.update === undefined) { + writeFileSync(${JSON.stringify(envPath)}, "T3CODE_TEST_SERVICE_TOKEN=changed\\n"); process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: ${encodedDatabasePath} }); setInterval(() => {}, 1_000); } else { @@ -339,9 +354,8 @@ if (context.update?.status === "pending") { }), ); - const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath))); yield* Effect.promise(() => - launcher.run().then( + main().then( () => Promise.reject(new Error("launcher unexpectedly completed")), () => Promise.resolve(), ), @@ -354,85 +368,20 @@ if (context.update?.status === "pending") { state.update?.status === "rolled-back" ? state.update.reason : undefined, "invalid-prepared", ); + const observations = (yield* fs.readFileString(observationsPath)) + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + assert.deepEqual(observations, [ + { token: "initial", update: "active" }, + { token: "initial", update: "pending" }, + { token: "initial", update: "rolled-back" }, + ]); + assert.equal(process.env.T3CODE_TEST_SERVICE_TOKEN, "inherited"); + assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n"); }), ); - it.effect.each([ - { prepares: true, status: "committed", activeVersion: "1.1.0" }, - { prepares: false, status: "rolled-back", activeVersion: "1.0.0" }, - ] as const)( - "gives a trial the full prepared window (prepares: $prepares)", - ({ prepares, status, activeVersion }) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-slow-" }); - const statePath = path.join(root, "runtime", "service-state.json"); - const databasePath = path.join(root, "userdata", "state.sqlite"); - yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true }); - yield* fs.writeFileString(databasePath, "before trial"); - const childSource = ` -const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT); -if (context.update?.status !== "pending") process.exit(0); -process.on("message", (message) => { - if (message.type === "test-prepare") process.send({ type: "prepared", updateId: context.update.id }); - if (message.type === "committed") process.exit(0); -}); -setInterval(() => {}, 1_000); -`; - for (const version of ["1.0.0", "1.1.0"]) { - yield* writeFakeRuntime( - fs, - path, - path.join(root, "runtime", "versions", version), - childSource, - ); - } - yield* Effect.promise(() => - writeServiceState(statePath, { - protocol: SERVICE_LAUNCHER_PROTOCOL, - activeVersion: "1.0.0", - update: { - id: "update-1", - fromVersion: "1.0.0", - targetVersion: "1.1.0", - dbPath: databasePath, - status: "pending", - }, - }), - ); - - // Effect schedules on setImmediate, so faking only timeouts leaves it running. - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers())); - const launcher = new Launcher( - root, - yield* Effect.promise(() => readServiceState(statePath)), - ); - const running = launcher.run().then( - () => Promise.reject(new Error("launcher unexpectedly completed")), - () => Promise.resolve(), - ); - yield* Effect.promise(() => - vi.waitFor(() => assert.equal(vi.getTimerCount(), 1), { timeout: 10_000 }), - ); - yield* Effect.promise(() => vi.advanceTimersByTimeAsync(121_000)); - if (prepares) spawnedChildren.at(-1)!.send({ type: "test-prepare" }); - else yield* Effect.promise(() => vi.advanceTimersByTimeAsync(PREPARED_TIMEOUT_MS)); - yield* Effect.promise(() => running); - - const state = yield* Effect.promise(() => readServiceState(statePath)); - assert.equal(state.activeVersion, activeVersion); - assert.equal(state.update?.status, status); - if (!prepares) { - assert.equal( - state.update?.status === "rolled-back" ? state.update.reason : undefined, - "prepared-timeout", - ); - } - }), - ); - it.effect.each(["file", "symlink", "dangling symlink"] as const)( "restores the database when a migrating trial exits, with the database a %s", (kind) => @@ -693,41 +642,4 @@ setInterval(() => {}, 1_000); assert.include(blocker ?? "", "The server was not stopped"); }), ); - - it.effect("fails the backup check when the database cannot be inspected", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-blocker-" }); - const error = yield* Effect.promise(() => - databaseBackupBlocker(root, path.join(root, "missing.sqlite"), { - readFreeBytes: () => Promise.resolve(0), - }).then( - () => undefined, - (cause: unknown) => cause, - ), - ); - assert.equal((error as NodeJS.ErrnoException | undefined)?.code, "ENOENT"); - }), - ); - - it.effect("recognizes a clone into the backup directory on this filesystem", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-clone-" }); - const databasePath = path.join(root, "userdata", "state.sqlite"); - yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true }); - yield* fs.writeFileString(databasePath, "database"); - const blocker = yield* Effect.promise(() => - databaseBackupBlocker(root, databasePath, { readFreeBytes: () => Promise.resolve(0) }), - ); - assert.include( - blocker ?? "", - // oxlint-disable-next-line t3code/no-global-process-runtime -- mirrors the standalone launcher's own platform check. - process.platform === "darwin" ? "1.0 GB needed, 0.0 GB free" : "GB needed, 0.0 GB free", - ); - assert.deepEqual(yield* fs.readDirectory(path.join(root, "runtime", "db-backup")), []); - }), - ); }); diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 86470023dcb18..9f764b788efe2 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -1,14 +1,12 @@ // @effect-diagnostics nodeBuiltinImport:off // @effect-diagnostics globalTimers:off -// The launcher supervises the server child for the boot service and must keep -// working across server versions, so it stays on Node built-ins with no Effect -// runtime: it is the one part of the executable that cannot depend on the -// rest of it being loadable. +// The launcher must survive unloadable server versions; use Node built-ins without Effect. import * as NodeChildProcess from "node:child_process"; import * as NodeCrypto from "node:crypto"; import * as NodeFS from "node:fs"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; +import * as NodeUtil from "node:util"; import type { PendingServiceUpdate, @@ -23,6 +21,7 @@ import { decodeServiceLauncherChildMessage, isExactServiceVersion, parseServiceState, + SERVICE_ENV_FILE, SERVICE_LAUNCHER_CONTEXT_ENV, SERVICE_LAUNCHER_PROTOCOL, SERVICE_STATE_FILE, @@ -35,10 +34,9 @@ const HANDOFF_DELAY_MS = 2_000; * Migrations count toward it and can scale with the database: tens of GB on a cold page cache * take minutes. A missed window rolls back the database, so the next attempt pays the same cost. */ -export const PREPARED_TIMEOUT_MS = 30 * 60_000; +const PREPARED_TIMEOUT_MS = 30 * 60_000; const TERMINATE_GRACE_MS = 5_000; -// Matches SERVER_EXIT_CODE_STATE_DIR_OWNED in contracts. The standalone -// launcher stays independent of the Effect-backed contracts package. +// Match contracts' SERVER_EXIT_CODE_STATE_DIR_OWNED without depending on Effect. const STATE_DIR_OWNED_EXIT_CODE = 78; type TerminalStatus = "committed" | "rolled-back" | "failed"; @@ -85,6 +83,36 @@ async function pathExists(target: string): Promise { } } +const MANAGED_SERVICE_ENV_NAMES = new Set([ + "PATH", + "T3CODE_HOME", + "T3_BOOT_SERVICE_UNIT", + SERVICE_LAUNCHER_CONTEXT_ENV, +]); + +export async function readServiceEnvironment( + baseDir: string, + inherited: NodeJS.ProcessEnv = process.env, +): Promise { + const environment = { ...inherited }; + let contents: string; + try { + contents = await NodeFSP.readFile(NodePath.join(baseDir, SERVICE_ENV_FILE), "utf8"); + } catch (cause) { + if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return environment; + throw cause; + } + for (const [name, value] of Object.entries(NodeUtil.parseEnv(contents))) { + if ( + /^[A-Za-z_][A-Za-z0-9_]*$/.test(name) && + !MANAGED_SERVICE_ENV_NAMES.has(name.toUpperCase()) + ) { + environment[name] = value; + } + } + return environment; +} + // Opened read-write: Windows refuses to flush a handle without write access. async function syncFile(filePath: string): Promise { const handle = await NodeFSP.open(filePath, "r+"); @@ -95,9 +123,7 @@ async function syncFile(filePath: string): Promise { } } -// Flushes a directory entry so a rename into it survives power loss. Windows -// has no directory fsync: the handle opens but sync fails with EPERM, and -// NTFS journals the rename on its own. +// Fsync makes renames durable; Windows returns EPERM and NTFS journals them itself. async function syncDirectory(directory: string): Promise { const handle = await NodeFSP.open(directory, "r"); try { @@ -115,14 +141,11 @@ function runCp(args: ReadonlyArray): Promise { }); } -/** - * Node's own clone flag is not used: on macOS `fs.copyFile` falls back to a full copy. - */ +// macOS fs.copyFile clone flags fall back to full copies. async function copyDatabaseFile(source: string, destination: string): Promise { // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; - // `cp -c` replaces the destination with a new file, which would cut a - // hard-linked database off from its other links; copy into it instead. + // cp -c replaces files and breaks hard links; copy into hard-linked destinations instead. const hardLinked = platform === "darwin" && ((await NodeFSP.stat(destination).catch(() => undefined))?.nlink ?? 1) > 1; @@ -136,10 +159,7 @@ async function copyDatabaseFile(source: string, destination: string): Promise { // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; @@ -204,10 +219,7 @@ const filesystemBackupSpaceProbe: BackupSpaceProbe = { canClone: backupCanClone, }; -/** - * Runs before the server is stopped so a full disk refuses the update instead of causing an - * outage and a cold restart. - */ +/** Check before stopping the server so full disks refuse updates without an outage. */ export async function databaseBackupBlocker( baseDir: string, dbPath: string, @@ -230,10 +242,7 @@ export async function databaseBackupBlocker( return `Not enough free disk space to back up the database before updating: ${gb(needed)} GB needed, ${gb(free)} GB free. Free up disk space and try again. The server was not stopped.`; } -/** - * A completed backup is never overwritten because a restarted launcher may be looking at - * database writes from an earlier attempt by the same trial. - */ +// Preserve completed backups; restarted trials may already have changed the live database. async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise { const backupDir = databaseBackupDir(baseDir, pending.id); if (await pathExists(backupDir)) return; @@ -263,7 +272,7 @@ const restoreMarkerPath = (baseDir: string, updateId: string) => const databaseRestorePending = (baseDir: string, pending: PendingServiceUpdate) => pathExists(restoreMarkerPath(baseDir, pending.id)); -/** Mark rollback before changing live files so launcher recovery cannot boot a partial restore. */ +// Mark before live writes so recovery cannot boot a partial restore. async function markDatabaseRestorePending(backupDir: string): Promise { const markerPath = NodePath.join(backupDir, RESTORE_MARKER); if (!(await pathExists(markerPath))) { @@ -277,11 +286,7 @@ async function markDatabaseRestorePending(backupDir: string): Promise { } } -/** - * The file a restore writes for `path`: where its symlinks lead, even when the - * last target is missing, as after a crash between `cp -c` removing a file - * and cloning over it. - */ +// Resolve symlink targets even if a crashed cp -c left the final target missing. async function restoreTarget(path: string): Promise { let current = path; for (let hops = 0; hops < 40; hops++) { @@ -296,8 +301,7 @@ async function restoreTarget(path: string): Promise { throw cause; }); if (link === undefined) return current; - // Joined without normalizing: a `..` in the link must follow directory links - // the way the filesystem does, not cancel a path segment. + // Do not normalize .. before following directory symlinks; match filesystem resolution. current = NodePath.isAbsolute(link) ? link : `${await NodeFSP.realpath(NodePath.dirname(current))}${NodePath.sep}${link}`; @@ -318,8 +322,7 @@ async function restoreDatabaseBackup( const livePath = `${pending.dbPath}${suffix}`; const source = databaseBackupFile(backupDir, suffix); if (await pathExists(source)) { - // A clone replaces its destination, so restore into the file a symlinked - // database resolves to and keep the link itself. + // Restore into the symlink target; cloning would replace the link. const target = await restoreTarget(livePath); await copyDatabaseFile(source, target); await syncFile(target); @@ -443,14 +446,19 @@ export class Launcher { #done = false; readonly #completion = Promise.withResolvers(); readonly #backupSpaceProbe: Partial | undefined; + readonly #environment: Readonly; constructor( baseDir: string, state: ServiceState, - options: { readonly backupSpaceProbe?: Partial } = {}, + options: { + readonly backupSpaceProbe?: Partial; + readonly environment?: Readonly; + } = {}, ) { this.#baseDir = baseDir; this.#backupSpaceProbe = options.backupSpaceProbe; + this.#environment = { ...(options.environment ?? process.env) }; this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE); this.#state = state; } @@ -489,9 +497,7 @@ export class Launcher { } async stop(signal: NodeJS.Signals): Promise { - // This must happen synchronously at signal receipt. A queued update - // transition may already be terminating the active child, and that child - // needs to see the marker in its shutdown finalizer. + // Write synchronously on signal receipt; a terminating child needs the marker in its finalizer. try { NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 }); } catch {} @@ -502,9 +508,7 @@ export class Launcher { this.#stopRequested = true; this.#clearTimer(); this.#enqueue(async () => { - // Let an update transition already in progress start its replacement - // before this queued stop tears it down. That replacement owns the - // pre-activation tunnel cleanup path and observes the marker above. + // Let in-progress updates start replacements first; replacements observe the marker and own pre-activation tunnel cleanup. this.#stopping = true; const child = this.#child?.process; this.#child = null; @@ -521,13 +525,7 @@ export class Launcher { } async #recover(): Promise { - // A fresh launcher means servers are running again: any stop marker from - // a previous explicit stop is stale and must not make a future update - // handoff release its tunnel. A restart deferred by `t3 update` is done - // no matter who restarted the service, but only once this launcher is - // the version the marker waits for: a launcher that came up between the - // CLI writing the marker and writing the new state still runs the old - // version, and the marker has to outlive it. + // Clear old stop markers to preserve future tunnels; clear restart-pending only for the awaited version to avoid CLI races. await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined); const restartPending = restartPendingPath(this.#baseDir); const awaitedVersion = await NodeFSP.readFile(restartPending, "utf8").catch(() => undefined); @@ -581,7 +579,7 @@ export class Launcher { }; const spawnArguments = runtimeSpawnArguments(paths); const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, { - env: { ...process.env, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) }, + env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) }, stdio: ["inherit", "inherit", "inherit", "ipc"], }); await new Promise((resolve, reject) => { @@ -663,8 +661,7 @@ export class Launcher { await reject("The requested target runtime is missing or incomplete."); return; } - // A check that cannot run refuses the update too: the alternative is - // stopping the server without knowing whether the backup fits. + // Failed checks must refuse updates rather than stop the server with unknown backup capacity. const backupBlocker = await databaseBackupBlocker( this.#baseDir, message.dbPath, @@ -775,11 +772,7 @@ export class Launcher { throw new Error(`Active child exited unexpectedly (${String(code ?? signal ?? "unknown")}).`); } - /** - * Exiting would make systemd or launchd start another refused server, so stay - * idle until stopped or restarted. A pending update fails without restoring - * its backup: the other owner may have written to the database since. - */ + // Stay idle to avoid supervisor restart loops; never restore backups over another owner's possible writes. async #idleWhileStateDirOwned(): Promise { this.#clearTimer(); const pending = this.#state.update; @@ -829,7 +822,8 @@ export async function main(): Promise { if (baseDir === undefined || baseDir === "") { throw new Error("T3CODE_HOME is required by the T3 Code service launcher."); } + const environment = await readServiceEnvironment(baseDir); const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE); const state = await readServiceState(statePath); - await new Launcher(baseDir, state).run(); + await new Launcher(baseDir, state, { environment }).run(); } diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index 82ef745ff00b6..2693a22820da4 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -2,7 +2,9 @@ import { AntigravitySettings, ClaudeSettings, CodexSettings, + EasDeviceHostConfig, type ServerSettings, + SpeechToTextProviderSettings, UsageLimitSourceConfig, secretSettingsFields, } from "@t3tools/contracts"; @@ -31,6 +33,8 @@ const providerSecretFields = new Map([ ), ]); const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig); +const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig); +const speechToTextSecretFields = secretSettingsFields(SpeechToTextProviderSettings); const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url"); export interface SettingsSecret { @@ -142,5 +146,34 @@ export function mapSettingsSecrets( ]), ) as ServerSettings["usageLimitSources"]; - return { ...settings, providerInstances, sourceControlHosts, usageLimitSources }; + const easDeviceHosts = settings.easDeviceHosts.map( + (host) => + mapFields( + host, + easDeviceHostSecretFields, + (field, serverHost) => + `device-host-${encode(host.id)}-${encode(field)}` + + (serverHost === null ? "" : `-${encode(serverHost)}`), + ) as EasDeviceHostConfig, + ); + + const speechToTextProviders = Object.fromEntries( + Object.entries(settings.speechToText.providers).map(([provider, fields]) => [ + provider, + mapFields( + fields, + speechToTextSecretFields, + (field) => `speech-to-text-${encode(provider)}-${encode(field)}`, + ), + ]), + ) as ServerSettings["speechToText"]["providers"]; + + return { + ...settings, + providerInstances, + sourceControlHosts, + usageLimitSources, + easDeviceHosts, + speechToText: { ...settings.speechToText, providers: speechToTextProviders }, + }; } diff --git a/apps/server/src/sourceControl/BitbucketApi.test.ts b/apps/server/src/sourceControl/BitbucketApi.test.ts deleted file mode 100644 index 5a2c1eaceee00..0000000000000 --- a/apps/server/src/sourceControl/BitbucketApi.test.ts +++ /dev/null @@ -1,1174 +0,0 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; -import { assert, it, vi } from "@effect/vitest"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as ConfigProvider from "effect/ConfigProvider"; -import * as DateTime from "effect/DateTime"; -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 Option from "effect/Option"; -import * as Schema from "effect/Schema"; -import * as TestClock from "effect/testing/TestClock"; -import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; - -import { GitCommandError } from "@t3tools/contracts"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as ServerSettings from "../serverSettings.ts"; -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; -import type * as VcsDriver from "../vcs/VcsDriver.ts"; -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts"; -import * as VcsProcess from "../vcs/VcsProcess.ts"; - -const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError); - -const bitbucketPullRequest = { - id: 42, - title: "Add Bitbucket provider", - state: "OPEN", - updated_on: "2026-01-02T00:00:00.000Z", - links: { - html: { - href: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42", - }, - }, - source: { - branch: { name: "feature/source-control" }, - repository: { - full_name: "octocat/t3code", - workspace: { slug: "octocat" }, - }, - }, - destination: { - branch: { name: "main" }, - repository: { - full_name: "pingdotgg/t3code", - workspace: { slug: "pingdotgg" }, - }, - }, -}; - -const repositoryJson = { - full_name: "pingdotgg/t3code", - links: { - html: { href: "https://bitbucket.org/pingdotgg/t3code" }, - clone: [ - { name: "https", href: "https://bitbucket.org/pingdotgg/t3code.git" }, - { name: "ssh", href: "git@bitbucket.org:pingdotgg/t3code.git" }, - ], - }, - mainbranch: { name: "main" }, -}; - -function makeLayer(input: { - readonly response: (request: HttpClientRequest.HttpClientRequest) => Response; - readonly requestFailure?: ( - request: HttpClientRequest.HttpClientRequest, - ) => HttpClientError.HttpClientError; - readonly stall?: boolean; - readonly git?: Partial; - readonly env?: Record; -}) { - const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) => - input.stall - ? Effect.never - : input.requestFailure - ? Effect.fail(input.requestFailure(request)) - : Effect.succeed(HttpClientResponse.fromWeb(request, input.response(request))), - ); - const gitMock = { - readConfigValue: vi.fn(() => - Effect.succeed("git@bitbucket.org:pingdotgg/t3code.git"), - ), - resolvePrimaryRemoteName: vi.fn< - GitVcsDriver.GitVcsDriver["Service"]["resolvePrimaryRemoteName"] - >(() => Effect.succeed("origin")), - ensureRemote: vi.fn(() => - Effect.succeed("octocat"), - ), - fetchRemoteBranch: vi.fn( - () => Effect.void, - ), - fetchRemoteTrackingBranch: vi.fn< - GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"] - >(() => Effect.void), - setBranchUpstream: vi.fn( - () => Effect.void, - ), - switchRef: vi.fn((request) => - Effect.succeed({ refName: request.refName }), - ), - listLocalBranchNames: vi.fn(() => - Effect.succeed([]), - ), - }; - const git = { - ...gitMock, - ...input.git, - } satisfies Partial; - - const driver = { - listRemotes: vi.fn(() => - Effect.succeed({ - remotes: [ - { - name: "origin", - url: "git@bitbucket.org:pingdotgg/t3code.git", - pushUrl: Option.none(), - isPrimary: true, - }, - ], - freshness: { - source: "live-local" as const, - observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"), - expiresAt: Option.none(), - }, - }), - ), - } satisfies Partial; - - const resolve = vi.fn(() => - Effect.succeed({ - kind: "git" as const, - repository: { - kind: "git" as const, - rootPath: "/repo", - metadataPath: null, - freshness: { - source: "live-local" as const, - observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"), - expiresAt: Option.none(), - }, - }, - driver: driver as unknown as VcsDriver.VcsDriver["Service"], - }), - ); - - const layer = BitbucketApi.layer.pipe( - Layer.provide(ServerSourceControlHost.layer), - Layer.provide(Layer.mock(VcsProcess.VcsProcess)({})), - Layer.provide( - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => execute(request)), - ), - ), - Layer.provide( - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ - resolve, - }), - ), - Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)), - Layer.provide( - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: input.env ?? { - T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0", - T3CODE_BITBUCKET_EMAIL: "user@example.com", - T3CODE_BITBUCKET_API_TOKEN: "token", - }, - }), - ), - ), - Layer.provideMerge(ServerSettings.layerTest()), - Layer.provideMerge(NodeServices.layer), - ); - - return { execute, git: gitMock, resolve, listRemotes: driver.listRemotes, layer }; -} - -it.effect("parses pull request responses from the Bitbucket REST API", () => { - const { execute, layer } = makeLayer({ - response: () => - Response.json({ - ...bitbucketPullRequest, - }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const result = yield* bitbucket.getPullRequest({ - cwd: "/repo", - reference: "#42", - }); - - assert.deepStrictEqual(result, { - number: 42, - title: "Add Bitbucket provider", - url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42", - baseRefName: "main", - headRefName: "feature/source-control", - state: "open", - updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")), - isCrossRepository: true, - headRepositoryNameWithOwner: "octocat/t3code", - headRepositoryOwnerLogin: "octocat", - }); - assert.strictEqual( - execute.mock.calls[0]?.[0].url, - "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests/42", - ); - }).pipe(Effect.provide(layer)); -}); - -it.effect("lists pull requests with Bitbucket state and source branch query params", () => { - const { execute, layer } = makeLayer({ - response: () => - Response.json({ - values: [ - { - ...bitbucketPullRequest, - id: 7, - state: "MERGED", - source: { - branch: { name: "feature/merged" }, - repository: { full_name: "pingdotgg/t3code" }, - }, - }, - ], - }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const result = yield* bitbucket.listPullRequests({ - cwd: "/repo", - headSelector: "origin:feature/merged", - state: "merged", - limit: 10, - }); - - assert.strictEqual(result[0]?.state, "merged"); - const request = execute.mock.calls[0]?.[0]; - assert.strictEqual( - request?.url, - "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests", - ); - assert.deepStrictEqual(request?.urlParams.params, [ - ["pagelen", "10"], - ["sort", "-updated_on"], - ["q", 'source.branch.name = "feature/merged" AND state = "MERGED"'], - ["state", "MERGED"], - ]); - }).pipe(Effect.provide(layer)); -}); - -it.effect("lists closed pull requests with both closed Bitbucket states", () => { - const { execute, layer } = makeLayer({ - response: () => - Response.json({ - values: [], - }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - yield* bitbucket.listPullRequests({ - cwd: "/repo", - headSelector: "feature/closed", - state: "closed", - limit: 10, - }); - - assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [ - ["pagelen", "10"], - ["sort", "-updated_on"], - [ - "q", - 'source.branch.name = "feature/closed" AND (state = "DECLINED" OR state = "SUPERSEDED")', - ], - ["state", "DECLINED"], - ["state", "SUPERSEDED"], - ]); - }).pipe(Effect.provide(layer)); -}); - -it.effect("expands all-state pull request listing instead of relying on Bitbucket defaults", () => { - const { execute, layer } = makeLayer({ - response: () => - Response.json({ - values: [], - }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - yield* bitbucket.listPullRequests({ - cwd: "/repo", - headSelector: "feature/all", - state: "all", - limit: 10, - }); - - assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [ - ["pagelen", "10"], - ["sort", "-updated_on"], - [ - "q", - 'source.branch.name = "feature/all" AND (state = "OPEN" OR state = "MERGED" OR state = "DECLINED" OR state = "SUPERSEDED")', - ], - ["state", "OPEN"], - ["state", "MERGED"], - ["state", "DECLINED"], - ["state", "SUPERSEDED"], - ]); - }).pipe(Effect.provide(layer)); -}); - -it.effect("reads repository clone URLs and default branch", () => { - const { layer } = makeLayer({ - response: (request) => - Response.json( - request.url.endsWith("/branching-model") - ? { - development: { - branch: { name: "main" }, - name: "main", - use_mainbranch: true, - }, - } - : repositoryJson, - ), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const cloneUrls = yield* bitbucket.getRepositoryCloneUrls({ - cwd: "/repo", - repository: "pingdotgg/t3code", - }); - const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" }); - - assert.deepStrictEqual(cloneUrls, { - nameWithOwner: "pingdotgg/t3code", - url: "https://bitbucket.org/pingdotgg/t3code.git", - sshUrl: "git@bitbucket.org:pingdotgg/t3code.git", - }); - assert.strictEqual(defaultBranch, "main"); - }).pipe(Effect.provide(layer)); -}); - -it.effect.each([false, true])( - "rejects invalid explicit repositories before fallback, context=%s", - (withContext) => { - const { execute, resolve, listRemotes, layer } = makeLayer({ - response: () => Response.json(repositoryJson), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - for (const repository of ["t3code", "", " \t "]) { - const error = yield* bitbucket - .getRepositoryCloneUrls({ - cwd: "/repo", - repository, - ...(withContext - ? { - context: { - provider: { - kind: SourceControlProviderKind.make("bitbucket"), - name: "Bitbucket", - baseUrl: "https://bitbucket.org", - }, - remoteName: "origin", - remoteUrl: "git@bitbucket.org:pingdotgg/t3code.git", - }, - } - : {}), - }) - .pipe(Effect.match({ onFailure: (error) => error, onSuccess: () => null })); - - assert.instanceOf(error, BitbucketApi.BitbucketRepositoryLocatorError); - assert.strictEqual( - isBitbucketRepositoryLocatorError(error) ? error.repository : null, - repository, - ); - assert.strictEqual(resolve.mock.calls.length, 0); - assert.strictEqual(listRemotes.mock.calls.length, 0); - assert.strictEqual(execute.mock.calls.length, 0); - } - }).pipe(Effect.provide(layer)); - }, -); - -it.effect("prefers an explicit repository and uses context when the repository is omitted", () => { - const { execute, resolve, listRemotes, layer } = makeLayer({ - response: (request) => - Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const context = { - provider: { - kind: SourceControlProviderKind.make("bitbucket"), - name: "Bitbucket", - baseUrl: "https://bitbucket.org", - }, - remoteName: "origin", - remoteUrl: "git@bitbucket.org:another/context.git", - }; - for (const repository of ["pingdotgg/t3code", "https://bitbucket.org/pingdotgg/t3code.git"]) { - yield* bitbucket.getRepositoryCloneUrls({ cwd: "/repo", context, repository }); - } - yield* bitbucket.getDefaultBranch({ cwd: "/repo", context }); - - assert.deepStrictEqual( - execute.mock.calls.map(([request]) => request.url).toSorted(), - [ - "https://api.test.local/2.0/repositories/pingdotgg/t3code", - "https://api.test.local/2.0/repositories/pingdotgg/t3code", - "https://api.test.local/2.0/repositories/another/context", - "https://api.test.local/2.0/repositories/another/context/branching-model", - ].toSorted(), - ); - assert.strictEqual(resolve.mock.calls.length, 0); - assert.strictEqual(listRemotes.mock.calls.length, 0); - }).pipe(Effect.provide(layer)); -}); - -it.effect("discovers the repository from cwd remotes when the repository is omitted", () => { - const { execute, resolve, listRemotes, layer } = makeLayer({ - response: (request) => - Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const branch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" }); - - assert.strictEqual(branch, "main"); - assert.deepStrictEqual(resolve.mock.calls, [[{ cwd: "/repo" }]]); - assert.deepStrictEqual(listRemotes.mock.calls, [["/repo"]]); - assert.isTrue( - execute.mock.calls.every(([request]) => - request.url.startsWith("https://api.test.local/2.0/repositories/pingdotgg/t3code"), - ), - ); - }).pipe(Effect.provide(layer)); -}); - -it.effect( - "prefers the Bitbucket branching model development branch as the default PR target", - () => { - const { execute, layer } = makeLayer({ - response: (request) => - Response.json( - request.url.endsWith("/branching-model") - ? { - development: { - branch: { name: "develop" }, - name: "develop", - use_mainbranch: false, - }, - } - : repositoryJson, - ), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" }); - - assert.strictEqual(defaultBranch, "develop"); - assert.deepStrictEqual( - execute.mock.calls.map((call) => call[0].url).toSorted(), - [ - "https://api.test.local/2.0/repositories/pingdotgg/t3code", - "https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model", - ].toSorted(), - ); - }).pipe(Effect.provide(layer)); - }, -); - -it.effect( - "falls back to the repository main branch when the Bitbucket development branch is invalid", - () => { - const { layer } = makeLayer({ - response: (request) => - Response.json( - request.url.endsWith("/branching-model") - ? { - development: { - name: "develop", - use_mainbranch: false, - is_valid: false, - }, - } - : repositoryJson, - ), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" }); - - assert.strictEqual(defaultBranch, "main"); - }).pipe(Effect.provide(layer)); - }, -); - -it.effect( - "falls back to the repository main branch when the Bitbucket branching model is unavailable", - () => { - const { layer } = makeLayer({ - response: (request) => - request.url.endsWith("/branching-model") - ? Response.json({ error: { message: "Not found" } }, { status: 404 }) - : Response.json(repositoryJson), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" }); - - assert.strictEqual(defaultBranch, "main"); - }).pipe(Effect.provide(layer)); - }, -); - -it.effect("creates repositories through the Bitbucket REST API", () => { - const { execute, layer } = makeLayer({ - response: () => Response.json(repositoryJson), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const cloneUrls = yield* bitbucket.createRepository({ - cwd: "/repo", - repository: "pingdotgg/t3code", - visibility: "private", - }); - - assert.deepStrictEqual(cloneUrls, { - nameWithOwner: "pingdotgg/t3code", - url: "https://bitbucket.org/pingdotgg/t3code.git", - sshUrl: "git@bitbucket.org:pingdotgg/t3code.git", - }); - - const request = execute.mock.calls[0]?.[0]; - assert.strictEqual(request?.url, "https://api.test.local/2.0/repositories/pingdotgg/t3code"); - assert.strictEqual(request?.method, "POST"); - assert.ok(request); - const rawBody = (request.body as { readonly body?: Uint8Array }).body; - assert.ok(rawBody); - assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), { - scm: "git", - is_private: true, - }); - }).pipe(Effect.provide(layer)); -}); - -it.effect("creates pull requests using the official REST payload shape", () => { - const { execute, layer } = makeLayer({ - response: () => Response.json(bitbucketPullRequest), - }); - - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "bitbucket-pr-body-" }); - yield* fileSystem.writeFileString(bodyFile, "PR body"); - - const bitbucket = yield* BitbucketApi.BitbucketApi; - yield* bitbucket.createPullRequest({ - cwd: "/repo", - baseBranch: "main", - headSelector: "owner:feature/provider", - title: "Provider PR", - bodyFile, - }); - - const request = execute.mock.calls[0]?.[0]; - assert.strictEqual( - request?.url, - "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests", - ); - assert.strictEqual(request?.method, "POST"); - assert.ok(request); - const rawBody = (request.body as { readonly body?: Uint8Array }).body; - assert.ok(rawBody); - assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), { - title: "Provider PR", - description: "PR body", - source: { - branch: { name: "feature/provider" }, - repository: { full_name: "owner/t3code" }, - }, - destination: { - branch: { name: "main" }, - }, - }); - }).pipe(Effect.provide(layer), Effect.scoped); -}); - -it.effect("reports auth status through the Bitbucket REST /user endpoint", () => { - const { layer } = makeLayer({ - response: () => Response.json({ username: "bitbucket-user" }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const auth = yield* bitbucket.probeAuth; - - assert.deepStrictEqual(auth, { - status: "authenticated", - account: Option.some("bitbucket-user"), - host: Option.some("bitbucket.org"), - detail: Option.none(), - }); - }).pipe(Effect.provide(layer)); -}); - -it.effect("prefers credentials saved in settings over the environment, without a restart", () => { - const { execute, layer } = makeLayer({ - response: () => Response.json({ username: "bitbucket-user" }), - }); - const lastAuthorization = () => execute.mock.calls.at(-1)?.[0].headers.authorization; - const basic = (user: string, password: string) => `Basic ${btoa(`${user}:${password}`)}`; - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const settings = yield* ServerSettings.ServerSettingsService; - - yield* bitbucket.probeAuth; - assert.strictEqual(lastAuthorization(), basic("user@example.com", "token")); - - yield* settings.updateSettings({ - sourceControlHosts: { - bitbucket: { email: "saved@example.com", apiToken: "saved-api-token" }, - }, - }); - yield* bitbucket.probeAuth; - assert.strictEqual(lastAuthorization(), basic("saved@example.com", "saved-api-token")); - - yield* settings.updateSettings({ - sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } }, - }); - yield* bitbucket.probeAuth; - assert.strictEqual(lastAuthorization(), "Bearer saved-access-token"); - - yield* settings.updateSettings({ - sourceControlHosts: { bitbucket: { accessToken: "", apiToken: "" } }, - }); - yield* bitbucket.probeAuth; - assert.strictEqual(lastAuthorization(), basic("user@example.com", "token")); - }).pipe(Effect.provide(layer)); -}); - -it.effect("never puts a saved token that is unsafe for an HTTP header on the wire", () => { - const { execute, layer } = makeLayer({ - response: () => Response.json({ username: "bitbucket-user" }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const settings = yield* ServerSettings.ServerSettingsService; - - // Fetch would reject this header with an error quoting the token, and that error reaches - // clients. The unusable token is ignored, so the environment credential is used instead. - yield* settings.updateSettings({ - sourceControlHosts: { bitbucket: { accessToken: "saved\ntoken" } }, - }); - yield* bitbucket.probeAuth; - assert.strictEqual( - execute.mock.calls.at(-1)?.[0].headers.authorization, - `Basic ${btoa("user@example.com:token")}`, - ); - }).pipe(Effect.provide(layer)); -}); - -it.effect("reports saved credentials as configured when Bitbucket cannot confirm them", () => { - const { layer } = makeLayer({ - response: () => new Response(null, { status: 401 }), - env: { T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0" }, - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const settings = yield* ServerSettings.ServerSettingsService; - - assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated"); - - yield* settings.updateSettings({ - sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } }, - }); - assert.deepStrictEqual(yield* bitbucket.probeAuth, { - status: "unknown", - account: Option.none(), - host: Option.some("bitbucket.org"), - detail: Option.some("An access token is configured."), - }); - }).pipe(Effect.provide(layer)); -}); - -it.effect("preserves the HTTP client failure without deriving the domain message from it", () => { - const transportCause = new Error("socket reset by peer"); - let requestFailure: HttpClientError.HttpClientError | undefined; - const { layer } = makeLayer({ - response: () => Response.json({}), - requestFailure: (request) => { - requestFailure = new HttpClientError.HttpClientError({ - reason: new HttpClientError.TransportError({ - request, - cause: transportCause, - }), - }); - return requestFailure; - }, - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const error = yield* Effect.flip( - bitbucket.getPullRequest({ - cwd: "/repo", - reference: "42", - }), - ); - - assert.instanceOf(error, BitbucketApi.BitbucketRequestError); - assert.strictEqual(error.operation, "getPullRequest"); - assert.strictEqual( - error.message, - "Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.", - ); - assert.strictEqual(error.cause, requestFailure); - assert.strictEqual(requestFailure?.cause, transportCause); - }).pipe(Effect.provide(layer)); -}); - -it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => { - const responseBody = '{"error":{"message":"credential=secret-value"}}'; - const { layer } = makeLayer({ - response: () => new Response(responseBody, { status: 403 }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const error = yield* bitbucket - .checkoutPullRequest({ cwd: "/repo", reference: "42" }) - .pipe(Effect.flip); - - assert.instanceOf(error, BitbucketApi.BitbucketResponseError); - assert.strictEqual(error.operation, "getPullRequest"); - assert.strictEqual(error.status, 403); - assert.strictEqual(error.responseBodyLength, responseBody.length); - assert.notProperty(error, "responseBody"); - assert.strictEqual( - error.message, - "Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.", - ); - assert.notInclude(error.message, "secret-value"); - }).pipe(Effect.provide(layer)); -}); - -it.effect("keeps a 429 Retry-After time on the response error", () => { - const { layer } = makeLayer({ - response: () => new Response("busy", { status: 429, headers: { "Retry-After": "120" } }), - }); - - return Effect.gen(function* () { - yield* TestClock.setTime(1_000); - const bitbucket = yield* BitbucketApi.BitbucketApi; - const error = yield* bitbucket - .request({ method: "GET", url: "/repositories/acme/web" }) - .pipe(Effect.flip); - - assert.instanceOf(error, BitbucketApi.BitbucketResponseError); - assert.strictEqual(error.status, 429); - assert.strictEqual(error.retryAt, 121_000); - }).pipe(Effect.provide(layer)); -}); - -it.effect("preserves Bitbucket response body read failures as their immediate cause", () => { - const cause = new Error("response stream failed"); - const { layer } = makeLayer({ - response: () => - new Response( - new ReadableStream({ - start: (controller) => controller.error(cause), - }), - { status: 502 }, - ), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const error = yield* bitbucket - .getPullRequest({ cwd: "/repo", reference: "42" }) - .pipe(Effect.flip); - - assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError); - assert.strictEqual(error.operation, "getPullRequest"); - assert.strictEqual(error.status, 502); - assert.instanceOf(error.cause, HttpClientError.HttpClientError); - assert.strictEqual(error.cause.cause, cause); - assert.strictEqual( - error.message, - "Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.", - ); - }).pipe(Effect.provide(layer)); -}); - -it.effect("keeps the 429 retry time when the response body cannot be read", () => { - const { layer } = makeLayer({ - response: () => - new Response( - new ReadableStream({ - start: (controller) => controller.error(new Error("response stream failed")), - }), - { status: 429, headers: { "Retry-After": "120" } }, - ), - }); - - return Effect.gen(function* () { - yield* TestClock.setTime(1_000); - const bitbucket = yield* BitbucketApi.BitbucketApi; - const error = yield* bitbucket - .request({ method: "GET", url: "/repositories/acme/web" }) - .pipe(Effect.flip); - - assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError); - assert.strictEqual(error.status, 429); - assert.strictEqual(error.retryAt, 121_000); - }).pipe(Effect.provide(layer)); -}); - -it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => { - const { git, layer } = makeLayer({ - response: () => - Response.json({ - ...bitbucketPullRequest, - source: { - branch: { name: "feature/source-control" }, - repository: { - full_name: "pingdotgg/t3code", - workspace: { slug: "pingdotgg" }, - }, - }, - }), - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - yield* bitbucket.checkoutPullRequest({ - cwd: "/repo", - context: { - provider: { - kind: SourceControlProviderKind.make("bitbucket"), - name: "Bitbucket", - baseUrl: "https://bitbucket.org", - }, - remoteName: "origin", - remoteUrl: "git@bitbucket.org:pingdotgg/t3code.git", - }, - reference: "42", - force: true, - }); - - assert.strictEqual(git.ensureRemote.mock.calls.length, 0); - assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], { - cwd: "/repo", - remoteName: "origin", - remoteBranch: "feature/source-control", - localBranch: "feature/source-control", - }); - assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], { - cwd: "/repo", - branch: "feature/source-control", - remoteName: "origin", - remoteBranch: "feature/source-control", - }); - assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], { - cwd: "/repo", - refName: "feature/source-control", - }); - }).pipe(Effect.provide(layer)); -}); - -it.effect("preserves Git checkout failures without deriving the domain message from them", () => { - const gitCause = new GitCommandError({ - operation: "fetchRemoteBranch", - command: "git fetch origin feature/source-control", - cwd: "/repo", - detail: "remote rejected the request", - }); - const { layer } = makeLayer({ - response: () => - Response.json({ - ...bitbucketPullRequest, - source: { - branch: { name: "feature/source-control" }, - repository: { - full_name: "pingdotgg/t3code", - workspace: { slug: "pingdotgg" }, - }, - }, - }), - git: { - fetchRemoteBranch: () => Effect.fail(gitCause), - }, - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - const error = yield* Effect.flip( - bitbucket.checkoutPullRequest({ - cwd: "/repo", - reference: "42", - force: true, - }), - ); - - assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError); - assert.strictEqual(error.cwd, "/repo"); - assert.strictEqual(error.reference, "42"); - assert.strictEqual( - error.message, - "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.", - ); - assert.strictEqual(error.cause, gitCause); - }).pipe(Effect.provide(layer)); -}); - -it.effect("checks out fork pull requests through an ensured fork remote", () => { - const { git, layer } = makeLayer({ - response: (request) => { - if (request.url.endsWith("/repositories/octocat/t3code")) { - return Response.json({ - ...repositoryJson, - full_name: "octocat/t3code", - links: { - html: { href: "https://bitbucket.org/octocat/t3code" }, - clone: [ - { name: "https", href: "https://bitbucket.org/octocat/t3code.git" }, - { name: "ssh", href: "git@bitbucket.org:octocat/t3code.git" }, - ], - }, - }); - } - return Response.json({ - ...bitbucketPullRequest, - source: { - branch: { name: "main" }, - repository: { - full_name: "octocat/t3code", - workspace: { slug: "octocat" }, - }, - }, - }); - }, - }); - - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - yield* bitbucket.checkoutPullRequest({ - cwd: "/repo", - reference: "42", - force: true, - }); - - assert.deepStrictEqual(git.ensureRemote.mock.calls[0]?.[0], { - cwd: "/repo", - preferredName: "octocat", - url: "git@bitbucket.org:octocat/t3code.git", - }); - assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], { - cwd: "/repo", - remoteName: "octocat", - remoteBranch: "main", - localBranch: "t3code/pr-42/main", - }); - assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], { - cwd: "/repo", - branch: "t3code/pr-42/main", - remoteName: "octocat", - remoteBranch: "main", - }); - assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], { - cwd: "/repo", - refName: "t3code/pr-42/main", - }); - }).pipe(Effect.provide(layer)); -}); - -it.effect("refuses a url that points away from the configured Bitbucket", () => { - const { layer, execute } = makeLayer({ response: () => new Response("{}", { status: 200 }) }); - return Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - - const error = yield* Effect.flip( - bitbucket.request({ method: "GET", url: "https://attacker.example/2.0/repositories" }), - ); - - assert.strictEqual(error._tag, "BitbucketUntrustedUrlError"); - assert.strictEqual(execute.mock.calls.length, 0); - }).pipe(Effect.provide(layer)); -}); - -it.effect("keeps only the host of a url it refuses, never its query", () => - Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - - const error = yield* Effect.flip( - bitbucket.request({ - method: "GET", - url: "https://attacker.example/asset?signature=secret-token", - }), - ); - - assert.strictEqual(error._tag, "BitbucketUntrustedUrlError"); - assert.strictEqual( - error._tag === "BitbucketUntrustedUrlError" ? error.host : "", - "https://attacker.example", - ); - assert.notInclude(error.message, "secret-token"); - }).pipe(Effect.provide(makeLayer({ response: () => new Response("{}", { status: 200 }) }).layer)), -); - -it.effect("does not follow a redirect off the configured Bitbucket", () => - Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - - const error = yield* Effect.flip( - bitbucket.request({ method: "GET", url: "/repositories/acme/web/pullrequests/1/diff" }), - ); - - // The client would carry every header to the new host, so the hop is checked here instead. - assert.strictEqual(error._tag, "BitbucketUntrustedUrlError"); - }).pipe( - Effect.provide( - makeLayer({ - response: () => - new Response(null, { - status: 302, - headers: { location: "https://attacker.example/stolen" }, - }), - }).layer, - ), - ), -); - -it.effect("follows a redirect that stays on the configured Bitbucket", () => - Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - - const result = yield* bitbucket.request({ - method: "GET", - url: "/repositories/acme/web/pullrequests/1/diff", - }); - - // Bitbucket serves a diff as a redirect to a commit range, so the hop has to be followed. - assert.strictEqual(result.body, "diff --git a/a.ts b/a.ts"); - assert.isFalse(result.truncated); - }).pipe( - Effect.provide( - makeLayer({ - response: (request) => - request.url.endsWith("/pullrequests/1/diff") - ? new Response(null, { - status: 302, - headers: { location: "https://api.test.local/2.0/repositories/acme/web/diff/abc" }, - }) - : new Response("diff --git a/a.ts b/a.ts", { status: 200 }), - }).layer, - ), - ), -); - -it.effect("cuts a response short rather than reading an unbounded diff into memory", () => - Effect.gen(function* () { - const bitbucket = yield* BitbucketApi.BitbucketApi; - - const result = yield* bitbucket.request({ - method: "GET", - url: "/repositories/acme/web/pullrequests/1/diff", - maxBytes: 8, - }); - - assert.strictEqual(result.body, "12345678"); - assert.isTrue(result.truncated); - }).pipe( - Effect.provide( - makeLayer({ response: () => new Response("1234567890", { status: 200 }) }).layer, - ), - ), -); - -const stalledResponseBody = (status: number): Response => - new Response( - new ReadableStream({ - start(controller) { - controller.enqueue(new TextEncoder().encode("{")); - }, - }), - { status, headers: { "content-type": "application/json" } }, - ); - -it.effect.each([200, 503])( - "times out a stalled Bitbucket JSON body after HTTP %s headers", - (status) => { - const { execute, layer } = makeLayer({ response: () => stalledResponseBody(status) }); - return Effect.gen(function* () { - const api = yield* BitbucketApi.BitbucketApi; - const fiber = yield* Effect.forkChild( - Effect.flip(api.getPullRequest({ cwd: "/repo", reference: "42" })), - ); - while (execute.mock.calls.length === 0) yield* Effect.yieldNow; - yield* TestClock.adjust("31 seconds"); - const error = yield* Fiber.join(fiber); - assert.instanceOf(error, BitbucketApi.BitbucketRequestError); - assert.strictEqual(error.operation, "getPullRequest"); - }).pipe(Effect.provide(layer)); - }, -); - -it.effect.each([200, 503])( - "times out a stalled Bitbucket raw body after HTTP %s headers", - (status) => { - const { execute, layer } = makeLayer({ response: () => stalledResponseBody(status) }); - return Effect.gen(function* () { - const api = yield* BitbucketApi.BitbucketApi; - const fiber = yield* Effect.forkChild( - Effect.flip(api.request({ method: "GET", url: "/user" })), - ); - while (execute.mock.calls.length === 0) yield* Effect.yieldNow; - yield* TestClock.adjust("31 seconds"); - const error = yield* Fiber.join(fiber); - assert.instanceOf(error, BitbucketApi.BitbucketRequestError); - assert.strictEqual(error.operation, "request"); - }).pipe(Effect.provide(layer)); - }, -); - -it.effect("times out before JSON headers arrive", () => { - const { execute, layer } = makeLayer({ response: () => Response.json({}), stall: true }); - return Effect.gen(function* () { - const api = yield* BitbucketApi.BitbucketApi; - const fiber = yield* Effect.forkChild( - Effect.flip(api.getPullRequest({ cwd: "/repo", reference: "42" })), - ); - while (execute.mock.calls.length === 0) yield* Effect.yieldNow; - yield* TestClock.adjust("31 seconds"); - const error = yield* Fiber.join(fiber); - assert.instanceOf(error, BitbucketApi.BitbucketRequestError); - assert.strictEqual(error.operation, "getPullRequest"); - }).pipe(Effect.provide(layer)); -}); - -it.effect("times out before raw response headers arrive", () => { - const { execute, layer } = makeLayer({ response: () => Response.json({}), stall: true }); - return Effect.gen(function* () { - const api = yield* BitbucketApi.BitbucketApi; - const fiber = yield* Effect.forkChild( - Effect.flip(api.request({ method: "GET", url: "/user" })), - ); - while (execute.mock.calls.length === 0) yield* Effect.yieldNow; - yield* TestClock.adjust("31 seconds"); - const error = yield* Fiber.join(fiber); - assert.instanceOf(error, BitbucketApi.BitbucketRequestError); - assert.strictEqual(error.operation, "request"); - }).pipe(Effect.provide(layer)); -}); diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts index eefa6534cbede..c82f5f3cad077 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts @@ -1,581 +1,131 @@ -import { SourceControlProviderKind } from "@t3tools/contracts"; +import { SourceControlProviderKind, VcsProcessSpawnError } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; -import type * as Context from "effect/Context"; -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"; -import { ChildProcessSpawner } from "effect/process"; -import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; -import { VcsProcessSpawnError } from "@t3tools/contracts"; +import { providerAuth } from "@t3tools/source-control-core/server/discovery"; +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import { + fakeDiscovery, + fakeSourceControlProvider, +} from "@t3tools/source-control-testing/fakeSourceControlDriver"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; -import * as ServerSettings from "../serverSettings.ts"; import * as ServerConfig from "../config.ts"; -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; import * as VcsProcess from "../vcs/VcsProcess.ts"; -import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli"; -import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi"; -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; -import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy"; -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; -import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli"; -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli"; -import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi"; -import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials"; -import * as ForgejoSourceControlProvider from "@t3tools/source-control-forgejo/server/ForgejoSourceControlProvider"; -import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider"; import * as SourceControlDiscovery from "./SourceControlDiscovery.ts"; import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts"; -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts"; -import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; -const layerSourceControlProviderRegistryTest = (input: { - readonly bitbucket: Partial; - readonly process: Partial; -}) => - SourceControlProviderRegistry.layer.pipe( - Layer.provide( - Layer.mergeAll( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-source-control-registry-test-", - }).pipe(Layer.provide(NodeServices.layer)), - Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}), - Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}), - Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket), - Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}), - ServerSettings.ServerSettingsService.layerTest(), - Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}), - Layer.mock(GitHubRest.GitHubRest)({}), - // The GitHub provider's GraphQL reads go through these; no test here makes one. - Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}), - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))), - ), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - Layer.mock(GitLabCli.GitLabCli)({}), - Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}), - Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }), - Layer.mock(GitCafeApi.GitCafeApi)({}), - Layer.mock(GitCafeCredentials.GitCafeCredentials)({ - cliEnv: () => Effect.succeed({}), - }), - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}), - Layer.mock(VcsProcess.VcsProcess)(input.process), - ServerSourceControlHost.layer.pipe( - Layer.provide( - Layer.mergeAll( - Layer.mock(VcsProcess.VcsProcess)(input.process), - ServerSettings.ServerSettingsService.layerTest(), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({}), - ), - ), - ), - ), - ), +const kind = SourceControlProviderKind.make; + +// Serves both the host's runs and the server's own VCS probes, whose inputs share these fields. +const run = ( + input: Pick< + SourceControlHost.SourceControlProcessInput, + "operation" | "command" | "args" | "cwd" + >, +): Effect.Effect => { + if (input.args[0] === "--version") { + return input.command === "missing-cli" + ? Effect.fail( + new VcsProcessSpawnError({ + operation: input.operation, + command: input.command, + cwd: input.cwd, + cause: new Error(`${input.command} not found`), + }), + ) + : Effect.succeed(TestSourceControlHost.processOutput(`${input.command} version test\n`)); + } + return Effect.succeed( + TestSourceControlHost.processOutput(`signed in as ${input.command}-user\n`), ); +}; -const processOutput = ( - stdout: string, - options?: { - readonly stderr?: string; - readonly exitCode?: ChildProcessSpawner.ExitCode; - }, -): VcsProcess.VcsProcessOutput => ({ - exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0), - stdout, - stderr: options?.stderr ?? "", - stdoutTruncated: false, - stderrTruncated: false, +const cliDiscovery = (name: string) => ({ + type: "cli" as const, + kind: kind(name), + label: name, + installHint: `Install ${name}.`, + executable: name === "beta" ? "missing-cli" : `${name}-cli`, + versionArgs: ["--version"], + authArgs: ["auth", "status"], + parseAuth: ({ stdout }: { readonly stdout: string }) => + providerAuth({ status: "authenticated", account: /as (\S+)/.exec(stdout)?.[1] }), }); -const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); -const encodeJsonEffect = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); - -it.effect("reports implemented tools separately from locally available executables", () => { - const processMock = { - run: (input: VcsProcess.VcsProcessInput) => { - if (input.command === "git") { - return Effect.succeed(processOutput("git version 2.51.0\n")); - } - if (input.command === "gh" && input.args[0] === "--version") { - return Effect.succeed(processOutput("gh version 2.83.0\n")); - } - if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") { - return Effect.succeed( - processOutput( - encodeJson({ - hosts: { - "github.com": [ - { - state: "success", - active: true, - host: "github.com", - login: "juliusmarminge", - tokenSource: "keyring", - gitProtocol: "ssh", - }, - ], - }, - }), - ), - ); - } - return Effect.fail( - new VcsProcessSpawnError({ - operation: input.operation, - command: input.command, - cwd: input.cwd, - cause: new Error(`${input.command} not found`), - }), - ); - }, - } satisfies Partial; - const layerTest = SourceControlDiscovery.layer.pipe( - Layer.provide( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-source-control-discovery-", +const layerDiscovery = Layer.effect( + SourceControlProviderRegistry.SourceControlProviderRegistry, + SourceControlProviderRegistry.makeWithProviders( + [ + cliDiscovery("alpha"), + cliDiscovery("beta"), + fakeDiscovery("gamma", { + probeAuth: Effect.succeed(providerAuth({ status: "authenticated", account: "api-user" })), }), - ), - Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)), - Layer.provide( - layerSourceControlProviderRegistryTest({ - process: processMock, - bitbucket: { - probeAuth: Effect.succeed({ - status: "unauthenticated", - account: Option.none(), - host: Option.some("bitbucket.org"), - detail: Option.some( - "Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.", - ), - }), - }, - }), - ), - Layer.provideMerge(NodeServices.layer), - ); + ].map((discovery) => ({ + kind: discovery.kind, + provider: fakeSourceControlProvider(discovery.kind), + discovery, + })), + ), +).pipe( + Layer.provideMerge(TestSourceControlHost.layer({ process: { run } })), + Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()), + Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})), + Layer.provideMerge(Layer.mock(VcsProcess.VcsProcess)({ run })), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-discovery-" }), + ), + Layer.provideMerge(NodeServices.layer), +); - return Effect.gen(function* () { +it.effect("reports every hosting integration in registry order with its sign-in", () => + Effect.gen(function* () { const discovery = yield* SourceControlDiscovery.SourceControlDiscovery; const result = yield* discovery.discover; - assert.deepStrictEqual( - result.versionControlSystems.map((item) => ({ - kind: item.kind, - implemented: item.implemented, - status: item.status, - })), - [ - { kind: "git", implemented: true, status: "available" }, - { kind: "jj", implemented: false, status: "missing" }, - ], - ); assert.deepStrictEqual( result.sourceControlProviders.map((item) => ({ kind: item.kind, status: item.status, + version: item.version, auth: item.auth.status, account: item.auth.account, })), [ { - kind: SourceControlProviderKind.make("github"), + kind: kind("alpha"), status: "available", + version: Option.some("alpha-cli version test"), auth: "authenticated", - account: Option.some("juliusmarminge"), + account: Option.some("alpha-cli-user"), }, { - kind: SourceControlProviderKind.make("gitlab"), + kind: kind("beta"), status: "missing", + version: Option.none(), auth: "unknown", account: Option.none(), }, { - kind: SourceControlProviderKind.make("azure-devops"), - status: "missing", - auth: "unknown", - account: Option.none(), - }, - { - kind: SourceControlProviderKind.make("bitbucket"), + kind: kind("gamma"), status: "available", - auth: "unauthenticated", - account: Option.none(), - }, - { - kind: SourceControlProviderKind.make("forgejo"), - status: "missing", - auth: "unknown", - account: Option.none(), - }, - { - kind: SourceControlProviderKind.make("gitcafe"), - status: "missing", - auth: "unknown", - account: Option.none(), + version: Option.none(), + auth: "authenticated", + account: Option.some("api-user"), }, ], ); - const bitbucket = result.sourceControlProviders.find((item) => item.kind === "bitbucket"); - assert.ok(bitbucket); - assert.strictEqual(bitbucket.executable, undefined); - }).pipe(Effect.provide(layerTest)); -}); - -it.effect("probes provider authentication without exposing token details", () => { - const processMock = { - run: (input: VcsProcess.VcsProcessInput) => { - if (input.args[0] === "--version") { - return Effect.succeed(processOutput(`${input.command} version test\n`)); - } - if (input.command === "gh" && input.args.join(" ") === "auth status --json hosts") { - return Effect.succeed( - processOutput( - encodeJson({ - hosts: { - "github.com": [ - { - state: "success", - active: true, - host: "github.com", - login: "octocat", - tokenSource: "keyring", - gitProtocol: "ssh", - }, - ], - }, - }), - ), - ); - } - if (input.command === "glab" && input.args.join(" ") === "auth status") { - return Effect.succeed( - processOutput(`gitlab.com -Logged in to gitlab.com as gitlab-user -`), - ); - } - if (input.command === "tea" && input.args[0] === "login") { - return Effect.succeed( - processOutput( - encodeJson([ - { - name: "forgejo", - url: "https://forgejo.example.com", - ssh_host: "forgejo.example.com", - user: "forgejo-user", - valid: "true", - default: "true", - }, - ]), - ), - ); - } - if ( - input.command === "az" && - input.args.join(" ") === "account show --query user.name -o tsv" - ) { - return Effect.succeed(processOutput("azure-user@example.com\n")); - } - if (input.command === "cafe" && input.args.slice(-3).join(" ") === "auth status --json") { - return Effect.succeed( - processOutput( - encodeJson({ schemaVersion: 1, data: { host: "git.cafe", username: "cafe-user" } }), - ), - ); - } - return Effect.fail( - new VcsProcessSpawnError({ - operation: input.operation, - command: input.command, - cwd: input.cwd, - cause: new Error(`${input.command} not found`), - }), - ); - }, - } satisfies Partial; - const layerTest = SourceControlDiscovery.layer.pipe( - Layer.provide( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-source-control-auth-discovery-", - }), - ), - Layer.provide(Layer.mock(VcsProcess.VcsProcess)(processMock)), - Layer.provide( - layerSourceControlProviderRegistryTest({ - process: processMock, - bitbucket: { - probeAuth: Effect.succeed({ - status: "authenticated", - account: Option.some("bitbucket-user"), - host: Option.some("bitbucket.org"), - detail: Option.none(), - }), - }, - }), - ), - Layer.provideMerge(NodeServices.layer), - ); - - return Effect.gen(function* () { - const discovery = yield* SourceControlDiscovery.SourceControlDiscovery; - const result = yield* discovery.discover; - assert.deepStrictEqual( - result.sourceControlProviders.map((item) => ({ - kind: item.kind, - auth: item.auth.status, - account: item.auth.account, - detail: item.auth.detail, - })), + result.versionControlSystems.map((item) => [item.kind, item.status]), [ - { - kind: SourceControlProviderKind.make("github"), - auth: "authenticated", - account: Option.some("octocat"), - detail: Option.none(), - }, - { - kind: SourceControlProviderKind.make("gitlab"), - auth: "authenticated", - account: Option.some("gitlab-user"), - detail: Option.none(), - }, - { - kind: SourceControlProviderKind.make("azure-devops"), - auth: "authenticated", - account: Option.some("azure-user@example.com"), - detail: Option.none(), - }, - { - kind: SourceControlProviderKind.make("bitbucket"), - auth: "authenticated", - account: Option.some("bitbucket-user"), - detail: Option.none(), - }, - { - kind: SourceControlProviderKind.make("forgejo"), - auth: "authenticated", - account: Option.some("forgejo-user"), - detail: Option.none(), - }, - { - kind: SourceControlProviderKind.make("gitcafe"), - auth: "authenticated", - account: Option.some("cafe-user"), - detail: Option.none(), - }, + ["git", "available"], + ["jj", "available"], ], ); - }).pipe(Effect.provide(layerTest)); -}); - -it.effect( - "checks out fj pull refs and preserves existing branches and dirty files until forced", - () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const git = yield* VcsProcess.VcsProcess; - const path = yield* Path.Path; - const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-fj-checkout-" }); - const source = path.join(root, "source"); - const cwd = path.join(root, "checkout"); - yield* fs.makeDirectory(source); - for (const args of [ - ["init", "-b", "main"], - ["config", "user.name", "Test"], - ["config", "user.email", "test@example.com"], - ]) - yield* git.run({ operation: "test.setup", command: "git", cwd: source, args }); - yield* fs.writeFileString(path.join(source, "base.txt"), "base\n"); - for (const args of [ - ["add", "base.txt"], - ["commit", "-m", "base"], - ]) - yield* git.run({ operation: "test.setup", command: "git", cwd: source, args }); - const base = (yield* git.run({ - operation: "test.setup", - command: "git", - cwd: source, - args: ["rev-parse", "HEAD"], - })).stdout.trim(); - yield* git.run({ - operation: "test.setup", - command: "git", - cwd: root, - args: ["clone", source, cwd], - }); - yield* fs.writeFileString(path.join(source, "feature.txt"), "pull request change\n"); - for (const args of [ - ["add", "feature.txt"], - ["commit", "-m", "feature"], - ["update-ref", "refs/pull/42/head", "HEAD"], - ]) - yield* git.run({ operation: "test.setup", command: "git", cwd: source, args }); - const head = (yield* git.run({ - operation: "test.setup", - command: "git", - cwd: source, - args: ["rev-parse", "HEAD"], - })).stdout.trim(); - const fetched: string[] = []; - const host = yield* SourceControlHost.SourceControlHost; - const provider = yield* ForgejoSourceControlProvider.make.pipe( - Effect.provideService( - SourceControlHost.SourceControlHost, - SourceControlHost.SourceControlHost.of({ - settings: host.settings, - git: host.git, - process: { - run: (input) => { - if (input.args[0] !== "fetch") return git.run(input); - const url = input.args[2]; - assert.isDefined(url); - fetched.push(url!); - return git.run({ - ...input, - args: input.args.map((arg) => - arg === "git@forgejo.test:reviewer/project.git" ? source : arg, - ), - }); - }, - }, - }), - ), - Effect.provide( - Layer.mock(ForgejoCli.ForgejoCli)({ - resolveRepository: () => - Effect.succeed({ - command: "fj", - login: "work", - repository: "reviewer/project", - baseUrl: "https://forgejo.test", - }), - api: (input) => { - assert.include( - ["repos/reviewer/project", "repos/reviewer/project/pulls/42"], - input.path, - ); - return Effect.succeed( - processOutput( - encodeJson( - input.path.endsWith("/pulls/42") - ? { - number: 42, - title: "Checkout", - html_url: "https://forgejo.test/reviewer/project/pulls/42", - state: "open", - merged: false, - base: { ref: "main", sha: base, repo: null }, - head: { ref: "feature", sha: head, repo: null }, - } - : { - full_name: "reviewer/project", - clone_url: source, - ssh_url: "git@forgejo.test:reviewer/project.git", - default_branch: "main", - }, - ), - ), - ); - }, - }), - ), - ); - yield* provider.checkoutChangeRequest({ - cwd, - reference: "https://forgejo.test/reviewer/project/pulls/42", - }); - assert.strictEqual( - (yield* git.run({ - operation: "test.verify", - command: "git", - cwd, - args: ["branch", "--show-current"], - })).stdout.trim(), - "pulls/42", - ); - assert.strictEqual( - (yield* git.run({ - operation: "test.verify", - command: "git", - cwd, - args: ["rev-parse", "HEAD"], - })).stdout.trim(), - head, - ); - assert.strictEqual( - yield* fs.readFileString(path.join(cwd, "feature.txt")), - "pull request change\n", - ); - for (const args of [ - ["checkout", "main"], - ["branch", "-f", "pulls/42", "main"], - ]) - yield* git.run({ operation: "test.setup", command: "git", cwd, args }); - yield* fs.writeFileString(path.join(cwd, "base.txt"), "uncommitted work\n"); - yield* provider.checkoutChangeRequest({ cwd, reference: "42" }); - assert.strictEqual( - (yield* git.run({ - operation: "test.verify", - command: "git", - cwd, - args: ["rev-parse", "HEAD"], - })).stdout.trim(), - base, - ); - assert.strictEqual(yield* fs.exists(path.join(cwd, "feature.txt")), false); - yield* provider.checkoutChangeRequest({ - cwd, - reference: "42", - force: true, - context: { - provider: { - kind: SourceControlProviderKind.make("forgejo"), - name: "Forgejo", - baseUrl: "https://forgejo.test", - }, - remoteName: "origin", - remoteUrl: "git@forgejo.test:maria/project.git", - }, - }); - assert.strictEqual( - (yield* git.run({ - operation: "test.verify", - command: "git", - cwd, - args: ["rev-parse", "HEAD"], - })).stdout.trim(), - head, - ); - assert.strictEqual( - yield* fs.readFileString(path.join(cwd, "base.txt")), - "uncommitted work\n", - ); - assert.strictEqual( - yield* fs.readFileString(path.join(cwd, "feature.txt")), - "pull request change\n", - ); - assert.deepStrictEqual(fetched, [source, source, "git@forgejo.test:reviewer/project.git"]); - }).pipe( - Effect.scoped, - Effect.provide( - ServerSourceControlHost.layer.pipe( - Layer.provideMerge(VcsProcess.layer), - Layer.provideMerge(ServerSettings.ServerSettingsService.layerTest()), - Layer.provideMerge(Layer.mock(GitVcsDriver.GitVcsDriver)({})), - Layer.provideMerge(Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({})), - Layer.provideMerge(NodeServices.layer), - ), - ), - ), + }).pipe(Effect.provide(SourceControlDiscovery.layer.pipe(Layer.provide(layerDiscovery)))), ); diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.ts b/apps/server/src/sourceControl/SourceControlDiscovery.ts index f56985fefd639..b6c8239f1705a 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.ts @@ -64,7 +64,7 @@ export class SourceControlDiscovery extends Context.Service< } >()("t3/sourceControl/SourceControlDiscovery") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const process = yield* VcsProcess.VcsProcess; diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts index dc5a6505170bd..249bc07b3ad3f 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts @@ -9,54 +9,78 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as PubSub from "effect/PubSub"; -import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; -import { HttpClient } from "effect/http"; -import { ChildProcessSpawner } from "effect/process"; import { DEFAULT_SERVER_SETTINGS, VcsProcessSpawnError, VcsProcessTimeoutError, - VcsRepositoryDetectionError, } from "@t3tools/contracts"; +import type { + SourceControlCliDiscoverySpec, + SourceControlManagedCliDiscoverySpec, + SourceControlProviderDiscoverySpec, +} from "@t3tools/source-control-core/server/discovery"; +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import { fakeSourceControlProvider } from "@t3tools/source-control-testing/fakeSourceControlDriver"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; import * as ServerSettings from "../serverSettings.ts"; import * as ServerConfig from "../config.ts"; import type * as VcsDriver from "../vcs/VcsDriver.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; -import * as VcsProcess from "../vcs/VcsProcess.ts"; -import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli"; -import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi"; -import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; -import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy"; -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; -import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials"; -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; -import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli"; -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli"; -import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi"; -import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials"; import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts"; -import * as ServerSourceControlHost from "./ServerSourceControlHost.ts"; const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); +const kind = SourceControlProviderKind.make; + +class NotAnswered extends Schema.TaggedError()("NotAnswered", {}) {} + +const linkSubject = (host: string) => () => + Effect.succeed({ title: `${host} subject`, body: null }); + +/** Only GitHub and GitLab read linked subjects, as in production. */ +const PROVIDERS = [ + fakeSourceControlProvider("github", { resolveLink: linkSubject("github") }), + fakeSourceControlProvider("gitlab", { resolveLink: linkSubject("gitlab") }), + fakeSourceControlProvider("forgejo"), + fakeSourceControlProvider("bitbucket"), + fakeSourceControlProvider("azure-devops"), +]; + +/** A host CLI that claims every server it is signed in to, as `glab` does. */ +const claimingCli = (claims: string): SourceControlCliDiscoverySpec => ({ + type: "cli", + kind: kind(claims), + label: claims, + installHint: `Install ${claims}.`, + executable: `${claims}-cli`, + versionArgs: ["--version"], + authArgs: ["auth", "status"], + remoteRefinementArgs: ({ provider }) => ["auth", "status", "--hostname", provider.name], + parseAuth: () => ({ + status: "unknown", + account: Option.none(), + host: Option.none(), + detail: Option.none(), + }), + refineUnknownRemote: ({ context, auth }) => + auth.stdout.includes(`Logged in to ${context.provider.name}`) + ? { kind: kind(claims), name: `${claims} Self-Hosted`, baseUrl: context.provider.baseUrl } + : null, +}); -const processOutput = ( - stdout: string, - options?: { - readonly stderr?: string; - readonly exitCode?: ChildProcessSpawner.ExitCode; - }, -): VcsProcess.VcsProcessOutput => ({ - exitCode: options?.exitCode ?? ChildProcessSpawner.ExitCode(0), - stdout, - stderr: options?.stderr ?? "", - stdoutTruncated: false, - stderrTruncated: false, +const managedCli = ( + claims: string, + refine: SourceControlManagedCliDiscoverySpec["refineUnknownRemote"], +): SourceControlManagedCliDiscoverySpec => ({ + type: "managed-cli", + kind: kind(claims), + label: claims, + installHint: `Install ${claims}.`, + probe: () => Effect.die("unused"), + refineUnknownRemote: refine, }); function makeRegistry(input: { @@ -64,12 +88,9 @@ function makeRegistry(input: { readonly name: string; readonly url: string; }>; - readonly process?: Partial; - readonly githubApi?: Partial; - readonly gitlab?: Partial; - readonly forgejo?: Partial; + readonly discovery?: ReadonlyArray; + readonly run?: SourceControlHost.SourceControlHost["Service"]["process"]["run"]; readonly settings?: Partial; - readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"]; }) { const driver = { listRemotes: () => @@ -87,78 +108,47 @@ function makeRegistry(input: { }), } satisfies Partial; - const layerRegistry = Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ - get: () => Effect.succeed(driver as unknown as VcsDriver.VcsDriver["Service"]), - resolve: - input.resolve ?? - (() => - Effect.succeed({ - kind: "git", - repository: { - kind: "git", - rootPath: "/repo", - metadataPath: null, - freshness: { - source: "live-local" as const, - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }, - driver: driver as unknown as VcsDriver.VcsDriver["Service"], - })), - }); - - const layerProcess = Layer.mock(VcsProcess.VcsProcess)({ - run: () => Effect.succeed(processOutput("")), - ...input.process, - }); - - return SourceControlProviderRegistry.make.pipe( + const discovery = input.discovery ?? [claimingCli("gitlab")]; + return SourceControlProviderRegistry.makeWithProviders( + PROVIDERS.map((provider) => ({ + kind: provider.kind, + provider, + discovery: discovery.find((spec) => spec.kind === provider.kind) ?? { + type: "api", + kind: provider.kind, + label: provider.kind, + installHint: "unused", + probeAuth: Effect.die("unused"), + }, + })), + ).pipe( Effect.provide( Layer.mergeAll( - NodeServices.layer, - layerRegistry, - layerProcess, - ServerSourceControlHost.layer.pipe( - Layer.provide( - Layer.mergeAll( - layerProcess, - layerRegistry, - ServerSettings.ServerSettingsService.layerTest(), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - ), - ), - ), - Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}), - Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}), - Layer.mock(BitbucketApi.BitbucketApi)({}), - Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}), + Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ + resolve: () => + Effect.succeed({ + kind: "git", + repository: { + kind: "git", + rootPath: "/repo", + metadataPath: null, + freshness: { + source: "live-local" as const, + observedAt: TEST_EPOCH, + expiresAt: Option.none(), + }, + }, + driver: driver as unknown as VcsDriver.VcsDriver["Service"], + }), + }), + TestSourceControlHost.layer({ + process: { + run: input.run ?? (() => Effect.succeed(TestSourceControlHost.processOutput(""))), + }, + }), input.settings ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings) : ServerSettings.ServerSettingsService.layerTest(), - Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}), - // The GitHub provider's GraphQL reads go through these; no test here makes one. - Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}), - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))), - ), - Layer.mock(GitHubRest.GitHubRest)({ - // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed. - credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })), - ...input.githubApi, - }), - Layer.mock(GitVcsDriver.GitVcsDriver)({}), - Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}), - Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}), - Layer.mock(ForgejoCli.ForgejoCli)({ - listLogins: () => Effect.succeed([]), - ...input.forgejo, - }), - Layer.mock(GitCafeApi.GitCafeApi)({}), - Layer.mock(GitCafeCredentials.GitCafeCredentials)({ - cliEnv: () => Effect.succeed({}), - }), ServerConfig.layerTest(process.cwd(), { prefix: "t3-source-control-registry-test-", }).pipe(Layer.provide(NodeServices.layer)), @@ -167,121 +157,40 @@ function makeRegistry(input: { ); } -it.effect("routes GitHub remotes to the GitHub provider", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "git@github.com:pingdotgg/t3code.git" }], - }); - - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "github"); - }), -); - -it.effect("routes directly by provider kind for remote-first workflows", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ - remotes: [], - }); - - const provider = yield* registry.get(SourceControlProviderKind.make("github")); - - assert.strictEqual(provider.kind, "github"); - }), -); - -it.effect("includes the request cwd when an unregistered provider is used", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ remotes: [] }); - const provider = yield* registry.get(SourceControlProviderKind.make("unknown")); - - const error = yield* provider - .getChangeRequest({ cwd: "/repo", reference: "#42" }) - .pipe(Effect.flip); - - assert.strictEqual(error.provider, "unknown"); - assert.strictEqual(error.operation, "getChangeRequest"); - assert.strictEqual(error.cwd, "/repo"); - assert.strictEqual(error.reference, "#42"); - }), -); +const signedIn = (host: string) => () => + Effect.succeed(TestSourceControlHost.processOutput(` ✓ Logged in to ${host} as user\n`)); -it.effect("lists no change requests for a repository on an unrecognized host", () => +it.effect("routes an unknown remote to the integration that claims its server", () => Effect.gen(function* () { + const asked: Array = []; const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "https://git.example.internal/team/repo.git" }], - }); - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "unknown"); - assert.deepStrictEqual( - yield* provider.listChangeRequests({ cwd: "/repo", headSelector: "master", state: "all" }), - [], - ); - }), -); - -it.effect("retains VCS detection failures with structured cwd context", () => - Effect.gen(function* () { - const cause = new VcsRepositoryDetectionError({ - operation: "resolve", - cwd: "/repo", - detail: "raw VCS detection failure", - cause: new Error("raw nested failure"), - }); - const registry = yield* makeRegistry({ - remotes: [], - resolve: () => Effect.fail(cause), + remotes: [{ name: "origin", url: "git@self-hosted.example.test:group/project.git" }], + run: (input) => { + asked.push([input.command, ...input.args].join(" ")); + return signedIn("self-hosted.example.test")(); + }, }); - const error = yield* registry.resolve({ cwd: "/repo" }).pipe(Effect.flip); - - assert.strictEqual(error.provider, "unknown"); - assert.strictEqual(error.operation, "detectProvider"); - assert.strictEqual(error.cwd, "/repo"); - assert.strictEqual(error.detail, "Failed to detect source control provider."); - assert.strictEqual(error.cause, cause); - assert.equal(error.message.includes(cause.message), false); - }), -); + const handle = yield* registry.resolveHandle({ cwd: "/repo" }); -it.effect("routes GitLab remotes to the GitLab provider", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "git@gitlab.com:group/project.git" }], + assert.strictEqual(handle.provider.kind, "gitlab"); + assert.deepStrictEqual(handle.context?.provider, { + kind: kind("gitlab"), + name: "gitlab Self-Hosted", + baseUrl: "https://self-hosted.example.test", }); - - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "gitlab"); + assert.deepStrictEqual(asked, ["gitlab-cli auth status --hostname self-hosted.example.test"]); }), ); -it.effect("routes authenticated self-hosted GitLab remotes without relying on host naming", () => +it.effect("leaves a remote no integration claims unknown, with its server's address", () => Effect.gen(function* () { const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "https://self-hosted.example.test/group/project.git" }], - process: { - run: () => - Effect.succeed( - processOutput( - `gitlab.com - x gitlab.com: API call failed: 401 Unauthorized - ! No token found -self-hosted.example.test - ✓ Logged in to self-hosted.example.test as gitlab-user - ✓ Token found: ****** -`, - { exitCode: ChildProcessSpawner.ExitCode(1) }, - ), - ), - }, + remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }], }); - - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "gitlab"); + const handle = yield* registry.resolveHandle({ cwd: "/repo" }); + assert.strictEqual(handle.provider.kind, kind("unknown")); + assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test"); }), ); @@ -289,21 +198,14 @@ it.effect("refines the caller-selected remote instead of choosing another config Effect.gen(function* () { const registry = yield* makeRegistry({ remotes: [{ name: "origin", url: "git@github.com:fork/project.git" }], - process: { - run: () => - Effect.succeed( - processOutput(`self-hosted.example.test - ✓ Logged in to self-hosted.example.test as gitlab-user -`), - ), - }, + run: signedIn("self-hosted.example.test"), }); const handle = yield* registry.resolveHandle({ cwd: "/repo", context: { provider: { - kind: SourceControlProviderKind.make("unknown"), + kind: kind("unknown"), name: "self-hosted.example.test", baseUrl: "https://self-hosted.example.test", }, @@ -317,53 +219,6 @@ it.effect("refines the caller-selected remote instead of choosing another config }), ); -it.effect("routes authenticated self-hosted GitLab remotes on non-standard ports", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "https://self-hosted.example.test:8443/group/project.git" }], - process: { - run: () => - Effect.succeed( - processOutput( - `self-hosted.example.test:8443 - ✓ Logged in to self-hosted.example.test:8443 as gitlab-user - ✓ Token found: ****** -`, - ), - ), - }, - }); - - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "gitlab"); - }), -); - -it.effect("routes Bitbucket remotes to the Bitbucket provider", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "git@bitbucket.org:pingdotgg/t3code.git" }], - }); - - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "bitbucket"); - }), -); - -it.effect("routes Azure DevOps remotes to the Azure DevOps provider", () => - Effect.gen(function* () { - const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "https://dev.azure.com/acme/project/_git/repo" }], - }); - - const provider = yield* registry.resolve({ cwd: "/repo" }); - - assert.strictEqual(provider.kind, "azure-devops"); - }), -); - it.effect("falls back to a non-origin remote when origin is not configured", () => Effect.gen(function* () { const registry = yield* makeRegistry({ @@ -377,44 +232,22 @@ it.effect("falls back to a non-origin remote when origin is not configured", () ); it.effect( - "routes linked subjects by URL independently of the checkout and skips unsupported links", + "routes linked subjects to the host that serves them, independently of the checkout", () => Effect.gen(function* () { const registry = yield* makeRegistry({ remotes: [{ name: "origin", url: "https://github.com/unrelated/checkout.git" }], - githubApi: { - rest: () => - Effect.succeed({ - status: 200, - headers: {}, - body: JSON.stringify({ title: "GitHub issue", body: null }), - truncated: false, - invalidUtf8: false, - }), - }, - gitlab: { - execute: () => - Effect.succeed( - processOutput(JSON.stringify({ title: "GitLab MR", description: "Nested project" })), - ), - }, }); - for (const [url, expected] of [ - ["https://github.com/team/project/issues/1", { title: "GitHub issue", body: null }], - [ - "https://gitlab.com/team/sub/project/-/merge_requests/2", - { title: "GitLab MR", body: "Nested project" }, - ], + for (const [url, host] of [ + ["https://github.com/team/project/issues/1", "github"], + ["https://gitlab.com/team/sub/project/-/merge_requests/2", "gitlab"], ] as const) { const lookup = registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }); assert.ok(lookup); - assert.deepStrictEqual(yield* lookup, expected); + assert.deepStrictEqual(yield* lookup, { title: `${host} subject`, body: null }); } for (const url of [ "https://example.test/team/project/issues/1", - "https://github.attacker.test/team/project/issues/1", - "https://gitlab.attacker.test/team/project/-/issues/1", - "https://github.com/team/project", "https://codeberg.org/team/project/issues/1", "https://bitbucket.org/team/project/pull-requests/1", "https://dev.azure.com/org/project/_git/repo/pullrequest/1", @@ -424,70 +257,38 @@ it.effect( assert.strictEqual( registry.resolveLink({ cwd: "/unrelated", url: new URL(url) }), undefined, + url, ); } }).pipe(Effect.scoped), ); -it.effect.each([ - { name: "a credential", credential: "found", expected: "github" }, - { name: "a host turned off in Settings", credential: "disabled", expected: "github" }, - { name: "no credential", credential: "missing", expected: "unknown" }, -] as const)("resolves custom-host remotes with $name", (scenario) => +it.effect("does not refine a context whose server address is empty", () => Effect.gen(function* () { - const hosts: Array = []; - const commands: Array = []; - const registry = yield* makeRegistry({ - remotes: [{ name: "origin", url: "git@code.example.test:team/project.git" }], - process: { - run: ({ command }) => { - commands.push(command); - return Effect.succeed(processOutput("")); - }, - }, - githubApi: { - credential: (host) => { - hosts.push(host); - return scenario.credential === "found" - ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` }) - : scenario.credential === "disabled" - ? Effect.fail(new GitHubCredentials.GitHubHostDisabledError({ host })) - : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })); - }, - }, - }); - const handle = yield* registry.resolveHandle({ cwd: "/repo" }); - assert.strictEqual(handle.provider.kind, SourceControlProviderKind.make(scenario.expected)); - assert.strictEqual(handle.context?.provider.baseUrl, "https://code.example.test"); - assert.deepStrictEqual(hosts, ["code.example.test"]); - assert.notInclude(commands, "gh"); - }), -); - -it.effect("skips GitHub discovery for the identity resolver's empty base URL", () => - Effect.gen(function* () { - const hosts: string[] = []; + let asked = 0; const remoteUrl = "git@githubenterprise.dev.example.com:team/workspace.git"; const registry = yield* makeRegistry({ remotes: [{ name: "origin", url: remoteUrl }], - githubApi: { - credential: (host) => { - hosts.push(host); - return Effect.succeed({ - token: Redacted.make("token"), - fingerprint: `${host}:fingerprint`, - }); - }, - }, + discovery: [ + managedCli("github", ({ context }) => { + asked += 1; + return Effect.succeed( + context.provider.baseUrl === "" + ? null + : { kind: kind("github"), name: "GitHub", baseUrl: context.provider.baseUrl }, + ); + }), + ], }); const context = { - provider: { kind: SourceControlProviderKind.make("unknown"), name: "Unknown", baseUrl: "" }, + provider: { kind: kind("unknown"), name: "Unknown", baseUrl: "" }, remoteName: "origin", remoteUrl, }; - const unresolved = yield* registry.resolveHandle({ cwd: "/repo", context }); - assert.deepStrictEqual(unresolved.context, context); - assert.deepStrictEqual(hosts, []); + assert.deepStrictEqual( + (yield* registry.resolveHandle({ cwd: "/repo", context })).context, + context, + ); const resolved = yield* registry.resolveHandle({ cwd: "/repo" }); assert.strictEqual(resolved.provider.kind, "github"); @@ -495,7 +296,7 @@ it.effect("skips GitHub discovery for the identity resolver's empty base URL", ( resolved.context?.provider.baseUrl, "https://githubenterprise.dev.example.com", ); - assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]); + assert.strictEqual(asked, 2); }), ); @@ -515,7 +316,7 @@ const resolveUnknown = ( cwd: `/${repository}`, context: { provider: { - kind: SourceControlProviderKind.make("unknown"), + kind: kind("unknown"), name: "git.example.internal", baseUrl: "https://git.example.internal", }, @@ -530,24 +331,16 @@ it.effect("asks once for every checkout of a server no integration claims", () = const release = yield* Deferred.make(); const registry = yield* makeRegistry({ remotes: [], - process: { - run: ({ command, args, cwd }) => { - asked.push([command, ...args].join(" ")); - return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd)))); - }, - }, - githubApi: { - credential: (host) => { - asked.push(`credential ${host}`); - return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })); - }, - }, - forgejo: { - listLogins: ({ command = "tea", cwd }) => { - asked.push(command); - const cause = notFound(command, cwd); - return Effect.fail(new ForgejoCli.ForgejoCliError({ command, cwd, detail: "", cause })); - }, + discovery: [ + claimingCli("gitlab"), + managedCli("github", ({ context }) => { + asked.push(`managed ${context.provider.name}`); + return Effect.succeed(null); + }), + ], + run: ({ command, args, cwd }) => { + asked.push([command, ...args].join(" ")); + return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd)))); }, }); @@ -570,10 +363,8 @@ it.effect("asks once for every checkout of a server no integration claims", () = ); const once = asked.slice(); assert.sameMembers(once, [ - "credential git.example.internal", - "glab auth status --hostname Git.Example.Internal", - "fj", - "tea", + "managed git.example.internal", + "gitlab-cli auth status --hostname git.example.internal", ]); yield* TestClock.adjust("5 minutes"); @@ -585,20 +376,27 @@ it.effect("asks once for every checkout of a server no integration claims", () = it.effect("asks again after a check that could not answer", () => Effect.gen(function* () { let asks = 0; + let managedAsks = 0; const registry = yield* makeRegistry({ remotes: [], - process: { - run: ({ command, cwd }) => { - asks += 1; - return Effect.fail( - new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }), - ); - }, + discovery: [ + claimingCli("gitlab"), + managedCli("github", () => { + managedAsks += 1; + return Effect.fail(new NotAnswered()); + }), + ], + run: ({ command, cwd }) => { + asks += 1; + return Effect.fail( + new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }), + ); }, }); yield* resolveUnknown(registry, "a"); yield* resolveUnknown(registry, "b"); assert.strictEqual(asks, 2); + assert.strictEqual(managedAsks, 2); }), ); @@ -606,7 +404,7 @@ it.effect("asks again once Settings change", () => Effect.gen(function* () { const changes = yield* PubSub.unbounded(); const handled = yield* Deferred.make(); - let signedIn = false; + let claims = false; const registry = yield* makeRegistry({ remotes: [], settings: { @@ -623,16 +421,18 @@ it.effect("asks again once Settings change", () => ), ), }, - process: { run: ({ command, cwd }) => Effect.fail(notFound(command, cwd)) }, - githubApi: { - credential: (host) => - signedIn - ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` }) - : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })), - }, + discovery: [ + managedCli("github", ({ context }) => + Effect.succeed( + claims + ? { kind: kind("github"), name: "GitHub", baseUrl: context.provider.baseUrl } + : null, + ), + ), + ], }); assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown"); - signedIn = true; + claims = true; assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown"); yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS); diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 6109fe43c19b5..ad83942f2afdf 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -13,9 +13,9 @@ import { type SourceControlProviderDiscoveryItem, } from "@t3tools/contracts"; import type {} from "@t3tools/contracts"; -import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl"; import * as BuiltInDrivers from "./builtInDrivers.ts"; +import { sourceControlDefinitions } from "./sourceControlDefinitions.ts"; import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; import { probeSourceControlProvider, @@ -74,9 +74,7 @@ function unsupportedProvider( ): SourceControlProvider.SourceControlProvider["Service"] { return SourceControlProvider.SourceControlProvider.of({ kind, - // A remote on a host no provider recognizes (or no remote at all) has no change - // requests T3 could know about. Answering with none keeps the status poller from - // failing, and warning, on every refresh of such a repository. + // Unknown hosts have no readable change requests; return none to avoid poll warnings on every refresh. listChangeRequests: (input) => kind === "unknown" ? Effect.succeed([]) @@ -144,7 +142,7 @@ function selectProviderContext( ): SourceControlProvider.SourceControlProviderContext | null { const candidates: Array = []; for (const remote of remotes) { - const provider = detectSourceControlProviderFromRemoteUrl(remote.url); + const provider = sourceControlDefinitions.recognizeRemote(remote.url); if (provider) { candidates.push({ provider, @@ -162,10 +160,7 @@ function selectProviderContext( ); } -/** - * `cwd` is left out because it only matters when a probe fails there, and a failed probe - * is not kept. Equality ignores `lookup`, so this is not a `Data.Class`. - */ +// Failed probes are not cached, so cwd is irrelevant; equality ignores lookup, unlike Data.Class. class UnknownRemoteLookup { readonly key: string; readonly lookup: Effect.Effect; @@ -235,7 +230,7 @@ function bindProviderContext( }); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWithProviders")( function* (registrations: ReadonlyArray) { const config = yield* ServerConfig.ServerConfig; @@ -337,7 +332,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit if (input.url.protocol !== "https:" || input.url.username || input.url.password) { return undefined; } - const kind = detectSourceControlProviderFromRemoteUrl(input.url.href)?.kind; + const kind = sourceControlDefinitions.recognizeRemote(input.url.href)?.kind; return kind ? providers.get(kind)?.resolveLink?.(input) : undefined; }, get, @@ -357,17 +352,15 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit }, ); -export const make = Effect.gen(function* () { - const drivers = yield* Effect.forEach(BuiltInDrivers.BUILT_IN_SOURCE_CONTROL_DRIVERS, (driver) => - driver.make.pipe( - Effect.map((instance): SourceControlProviderRegistration => ({ - kind: driver.kind, - provider: instance.sourceControl, - discovery: instance.discovery, - })), - ), +const make = Effect.gen(function* () { + const drivers = yield* BuiltInDrivers.SourceControlDrivers; + return yield* makeWithProviders( + drivers.map(({ driver, instance }): SourceControlProviderRegistration => ({ + kind: driver.kind, + provider: instance.sourceControl, + discovery: instance.discovery, + })), ); - return yield* makeWithProviders(drivers); }); export const layer = Layer.effect(SourceControlProviderRegistry, make); diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts index 7e6662f3e44cb..4a9105e9f5d9e 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts @@ -7,21 +7,20 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as PlatformError from "effect/PlatformError"; -import * as Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; -import { GitCommandError, SourceControlProviderError } from "@t3tools/contracts"; +import { + GitCommandError, + SourceControlProviderError, + type SourceControlCloneRepositoryInput, +} from "@t3tools/contracts"; import * as ServerConfig from "../config.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as BitbucketSourceControlProvider from "@t3tools/source-control-bitbucket/server/BitbucketSourceControlProvider"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts"; import * as SourceControlRepositoryService from "./SourceControlRepositoryService.ts"; -const isSourceControlProviderError = Schema.is(SourceControlProviderError); - const CLONE_URLS = { nameWithOwner: "octocat/t3code", url: "https://github.com/octocat/t3code", @@ -102,181 +101,59 @@ function layer(input: { : layerService.pipe(Layer.provideMerge(NodeServices.layer)); } -it.effect("looks up repositories through the requested provider without search", () => { - const calls: Array<{ cwd: string; repository: string }> = []; - const provider = makeProvider({ - getRepositoryCloneUrls: (input) => - Effect.sync(() => { - calls.push({ cwd: input.cwd, repository: input.repository }); - return CLONE_URLS; - }), - }); - - return Effect.gen(function* () { - const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; - const result = yield* service.lookupRepository({ - provider: SourceControlProviderKind.make("github"), - repository: "octocat/t3code", - cwd: "/workspace", - }); - - assert.deepStrictEqual(result, { - provider: SourceControlProviderKind.make("github"), - ...CLONE_URLS, - }); - assert.deepStrictEqual(calls, [{ cwd: "/workspace", repository: "octocat/t3code" }]); - }).pipe(Effect.provide(layer({ provider }))); -}); - -it.effect("preserves provider failures without deriving the repository message from them", () => { - const providerCause = new SourceControlProviderError({ - provider: SourceControlProviderKind.make("github"), - operation: "getRepositoryCloneUrls", - cwd: "/workspace", - repository: "octocat/t3code", - detail: "credential token abc123 was rejected", - }); - const provider = makeProvider({ - getRepositoryCloneUrls: () => Effect.fail(providerCause), - }); - - return Effect.gen(function* () { +const lookupFailingWith = (cause: unknown, detail: string) => + Effect.gen(function* () { const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; - const error = yield* Effect.flip( - service.lookupRepository({ - provider: SourceControlProviderKind.make("github"), - repository: "octocat/t3code", - cwd: "/workspace", + return yield* service + .lookupRepository({ provider: SourceControlProviderKind.make("bitbucket"), repository: "x" }) + .pipe(Effect.flip); + }).pipe( + Effect.provide( + layer({ + provider: makeProvider({ + getRepositoryCloneUrls: (input) => + Effect.fail( + new SourceControlProviderError({ + provider: SourceControlProviderKind.make("bitbucket"), + operation: "getRepositoryCloneUrls", + cwd: input.cwd, + detail, + cause, + }), + ), + }), }), - ); + ), + ); - assert.strictEqual(error.provider, "github"); - assert.strictEqual(error.operation, "lookupRepository"); - assert.strictEqual(error.detail, "The source control operation could not be completed."); - assert.strictEqual( - error.message, - "Source control repository operation lookupRepository failed for github: The source control operation could not be completed.", +it.effect("tells the user a host's fixed explanation of a failed repository lookup", () => + Effect.gen(function* () { + const error = yield* lookupFailingWith( + { userFacingDetail: "Repositories are named workspace/repository." }, + "Repositories are named workspace/repository.", ); - assert.strictEqual(error.cause, providerCause); - }).pipe(Effect.provide(layer({ provider }))); -}); - -it.effect( - "reports the safe Bitbucket locator detail through repository lookup and publishing", - () => - Effect.gen(function* () { - const locatorCause = new BitbucketApi.BitbucketRepositoryLocatorError({ - repository: "credential-token-abc123", - }); - const provider = yield* BitbucketSourceControlProvider.make.pipe( - Effect.provide( - Layer.mock(BitbucketApi.BitbucketApi)({ - getRepositoryCloneUrls: () => Effect.fail(locatorCause), - createRepository: () => Effect.fail(locatorCause), - }), - ), - ); - - yield* Effect.gen(function* () { - const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; - const input = { - provider: SourceControlProviderKind.make("bitbucket"), - repository: locatorCause.repository, - cwd: "/workspace", - }; - for (const operation of [ - service.lookupRepository(input).pipe(Effect.asVoid), - service.publishRepository({ ...input, visibility: "private" }).pipe(Effect.asVoid), - ]) { - const error = yield* Effect.flip(operation); - - assert.strictEqual(error.provider, "bitbucket"); - assert.strictEqual( - error.detail, - "Bitbucket repositories must be specified as workspace/repository.", - ); - assert.notInclude(error.message, locatorCause.repository); - assert.instanceOf(error.cause, SourceControlProviderError); - assert.strictEqual( - isSourceControlProviderError(error.cause) ? error.cause.cause : null, - locatorCause, - ); - } - }).pipe(Effect.provide(layer({ provider }))); - }), + assert.strictEqual(error.detail, "Repositories are named workspace/repository."); + }), ); -it.effect("keeps a plain Bitbucket locator lookalike out of the repository message", () => { - const provider = makeProvider({ - kind: SourceControlProviderKind.make("bitbucket"), - getRepositoryCloneUrls: () => - Effect.fail( - new SourceControlProviderError({ - provider: SourceControlProviderKind.make("bitbucket"), - operation: "getRepositoryCloneUrls", - cwd: "/workspace", - detail: "credential token abc123 was rejected", - cause: { - _tag: "BitbucketRepositoryLocatorError", - repository: "t3code", - detail: "credential token abc123 was rejected", - }, - }), - ), - }); - - return Effect.gen(function* () { - const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; - const error = yield* Effect.flip( - service.lookupRepository({ - provider: SourceControlProviderKind.make("bitbucket"), - repository: "t3code", - }), - ); - - assert.strictEqual(error.detail, "The source control operation could not be completed."); - assert.notInclude(error.message, "abc123"); - }).pipe(Effect.provide(layer({ provider }))); -}); - -it.effect("keeps arbitrary Bitbucket request failures out of the repository message", () => +it.effect("keeps a host's raw response text out of a failed repository lookup", () => Effect.gen(function* () { - const cause = new BitbucketApi.BitbucketRequestError({ - operation: "getRepository", - cause: new Error("credential token abc123 was rejected"), - }); - const provider = yield* BitbucketSourceControlProvider.make.pipe( - Effect.provide( - Layer.mock(BitbucketApi.BitbucketApi)({ - getRepositoryCloneUrls: () => Effect.fail(cause), - }), - ), + const error = yield* lookupFailingWith( + new Error("upstream"), + "internal token=abc", ); - - yield* Effect.gen(function* () { - const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; - const error = yield* Effect.flip( - service.lookupRepository({ - provider: SourceControlProviderKind.make("bitbucket"), - repository: "pingdotgg/t3code", - cwd: "/workspace", - }), - ); - - assert.strictEqual(error.detail, "The source control operation could not be completed."); - assert.notInclude(error.message, "abc123"); - assert.notInclude(error.message, cause.detail); - }).pipe(Effect.provide(layer({ provider }))); + assert.strictEqual(error.detail, "The source control operation could not be completed."); }), ); -it.effect("clones a looked-up repository into the requested destination", () => +it.effect("clones a looked-up repository after creating missing parent directories", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const parent = yield* fs.makeTempDirectoryScoped({ + const temporaryDirectory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-source-control-clone-parent-", }); + const parent = path.join(temporaryDirectory, "missing", "nested"); const destinationPath = path.join(parent, "t3code"); const cloneCalls: Array<{ cwd: string; args: ReadonlyArray }> = []; @@ -305,7 +182,8 @@ it.effect("clones a looked-up repository into the requested destination", () => layer({ git: { execute: (input) => - Effect.sync(() => { + Effect.gen(function* () { + assert.isTrue(yield* fs.exists(parent).pipe(Effect.orDie)); cloneCalls.push({ cwd: input.cwd, args: input.args }); return processOutput(); }), @@ -413,6 +291,98 @@ it.effect("reports clone progress from git's stderr and keeps its error text on }).pipe(Effect.provide(NodeServices.layer)), ); +function rejectingSsh( + urls: Array, + httpsFails: boolean, + reason: GitCommandError["reason"] = "authentication_failed", +) { + return { + execute: (input: GitVcsDriver.ExecuteGitInput) => + Effect.gen(function* () { + const url = input.args.at(-2)!; + urls.push(url); + if (url.startsWith("https://") && !httpsFails) return processOutput(); + yield* ( + input.progress?.onStderrLine?.( + url.startsWith("https://") + ? "fatal: could not read Username for 'https://github.com': terminal prompts disabled" + : "git@github.com: Permission denied (publickey).", + ) ?? Effect.void + ); + return yield* new GitCommandError({ + operation: input.operation, + command: "git", + cwd: input.cwd, + reason, + detail: "Git command exited with a non-zero status.", + }); + }), + } satisfies Partial; +} + +const cloneInTemporaryDirectory = ( + git: Partial, + input: Omit, +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fs + .makeTempDirectoryScoped({ prefix: "t3-clone-fallback-" }) + .pipe(Effect.orDie); + return yield* Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + return yield* service.cloneRepository({ + ...input, + destinationPath: path.join(parent, "t3code"), + }); + }).pipe(Effect.provide(layer({ git }).pipe(Layer.orDie))); + }).pipe(Effect.provide(NodeServices.layer)); + +it.effect("retries a clone over HTTPS when the SSH login is refused", () => + Effect.gen(function* () { + const urls: Array = []; + const result = yield* cloneInTemporaryDirectory(rejectingSsh(urls, false), { + remoteUrl: CLONE_URLS.sshUrl, + }); + + assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl, "https://github.com/octocat/t3code.git"]); + assert.strictEqual(result.remoteUrl, "https://github.com/octocat/t3code.git"); + }), +); + +it.effect("reports both failures when the HTTPS retry fails too", () => + Effect.gen(function* () { + const urls: Array = []; + const error = yield* Effect.flip( + cloneInTemporaryDirectory(rejectingSsh(urls, true), { remoteUrl: CLONE_URLS.sshUrl }), + ); + + assert.strictEqual(urls.length, 2); + assert.strictEqual( + error.detail, + "git@github.com: Permission denied (publickey). Cloning over HTTPS instead also failed: fatal: could not read Username for 'https://github.com': terminal prompts disabled", + ); + }), +); + +it.effect.each([ + ["the caller asked for SSH", "ssh", "authentication_failed"], + ["git failed for another reason", undefined, "remote_unreachable"], +] as const)("does not retry over HTTPS when %s", ([, protocol, reason]) => + Effect.gen(function* () { + const urls: Array = []; + yield* Effect.flip( + cloneInTemporaryDirectory(rejectingSsh(urls, false, reason), { + remoteUrl: CLONE_URLS.sshUrl, + ...(protocol === undefined ? {} : { protocol }), + }), + ); + + assert.deepStrictEqual(urls, [CLONE_URLS.sshUrl]); + }), +); + it.effect("strips embedded credentials from the remote URL it reports", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -528,74 +498,6 @@ it.effect("preserves destination probe failures instead of treating them as miss ); }); -it.effect("publishes by creating the repository, adding a remote, and pushing upstream", () => { - const createCalls: Array<{ cwd: string; repository: string; visibility: string }> = []; - const remoteCalls: Array<{ cwd: string; preferredName: string; url: string }> = []; - const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = []; - const provider = makeProvider({ - createRepository: (input) => - Effect.sync(() => { - createCalls.push({ - cwd: input.cwd, - repository: input.repository, - visibility: input.visibility, - }); - return CLONE_URLS; - }), - }); - - return Effect.gen(function* () { - const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; - const result = yield* service.publishRepository({ - cwd: "/workspace", - provider: SourceControlProviderKind.make("github"), - repository: "octocat/t3code", - visibility: "private", - remoteName: "origin", - protocol: "ssh", - }); - - assert.deepStrictEqual(result, { - repository: { provider: SourceControlProviderKind.make("github"), ...CLONE_URLS }, - remoteName: "origin", - remoteUrl: CLONE_URLS.sshUrl, - branch: "feature/remote-v1", - upstreamBranch: "origin/feature/remote-v1", - status: "pushed", - }); - assert.deepStrictEqual(createCalls, [ - { cwd: "/workspace", repository: "octocat/t3code", visibility: "private" }, - ]); - assert.deepStrictEqual(remoteCalls, [ - { cwd: "/workspace", preferredName: "origin", url: CLONE_URLS.sshUrl }, - ]); - assert.deepStrictEqual(pushCalls, [{ cwd: "/workspace", remoteName: "origin" }]); - }).pipe( - Effect.provide( - layer({ - provider, - git: { - ensureRemote: (input) => - Effect.sync(() => { - remoteCalls.push(input); - return "origin"; - }), - pushCurrentBranch: (cwd, _fallbackBranch, options) => - Effect.sync(() => { - pushCalls.push({ cwd, remoteName: options?.remoteName }); - return { - status: "pushed" as const, - branch: "feature/remote-v1", - upstreamBranch: "origin/feature/remote-v1", - setUpstream: true, - }; - }), - }, - }), - ), - ); -}); - it.effect("publishes to the remote name returned by ensureRemote", () => { const pushCalls: Array<{ cwd: string; remoteName: string | null | undefined }> = []; @@ -633,6 +535,64 @@ it.effect("publishes to the remote name returned by ensureRemote", () => { ); }); +function failingPush(reason?: GitCommandError["reason"]) { + return { + pushCurrentBranch: (cwd: string) => + Effect.fail( + new GitCommandError({ + operation: "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", + command: "git", + cwd, + ...(reason === undefined ? {} : { reason }), + detail: "Git command exited with a non-zero status.", + }), + ), + } satisfies Partial; +} + +it.effect("explains a rejected SSH push after creating the repository", () => + Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + const error = yield* Effect.flip( + service.publishRepository({ + cwd: "/workspace", + provider: SourceControlProviderKind.make("github"), + repository: "octocat/t3code", + visibility: "private", + protocol: "ssh", + }), + ); + + assert.strictEqual(error.operation, "publishRepository"); + assert.strictEqual( + error.detail, + 'Created octocat/t3code and added it as remote "origin", but the push failed because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "git remote set-url origin https://github.com/octocat/t3code", then push again.', + ); + assert.instanceOf(error.cause, GitCommandError); + }).pipe(Effect.provide(layer({ git: failingPush("authentication_failed") }))), +); + +// regression: #19219 publishing did not explain why the first push failed +it.effect("says the repository exists when an unclassified publish push fails", () => + Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + const error = yield* Effect.flip( + service.publishRepository({ + cwd: "/workspace", + provider: SourceControlProviderKind.make("github"), + repository: "octocat/t3code", + visibility: "private", + protocol: "https", + }), + ); + + assert.strictEqual( + error.detail, + 'Created octocat/t3code and added it as remote "origin", but the push failed. Fix the problem, then push again.', + ); + }).pipe(Effect.provide(layer({ git: failingPush() }))), +); + it.effect("publish succeeds with status remote_added when the local repo has no commits", () => { let pushCalls = 0; return Effect.gen(function* () { diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts index f3b46816b2300..e89a6330a69e4 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts @@ -7,8 +7,10 @@ import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import { + GitCommandError, SourceControlProviderError, SourceControlRepositoryError, + type GitCommandFailureReason, type SourceControlCloneRepositoryInput, type SourceControlCloneRepositoryResult, type SourceControlCloneProtocol, @@ -22,17 +24,19 @@ import { import * as ServerConfig from "../config.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import { parseGitCloneProgressLine, type GitCloneProgressLine, } from "../project/gitCloneProgress.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; +import * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { cloneUrlForProtocol, cloneUrlProtocol } from "@t3tools/shared/cloneUrl"; const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError); const isSourceControlProviderError = Schema.is(SourceControlProviderError); -const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError); +const isGitCommandError = Schema.is(GitCommandError); export class SourceControlRepositoryService extends Context.Service< SourceControlRepositoryService, @@ -69,14 +73,10 @@ export interface SourceControlCloneOptions { readonly timeoutMs?: number | null; } -// The synchronous RPC (older clients, mobile) keeps a deadline: nothing else -// tells the user a clone stalled. The tracked path passes null and relies on -// progress and Cancel instead. +// Older/mobile synchronous RPCs need deadlines; tracked clones use progress and Cancel instead. const CLONE_TIMEOUT_MS = 120_000; const CLONE_ENV = { - // `--progress` forces the transfer counters through the pipe; the delay env - // makes the checkout counter start immediately. No tty means a credential - // prompt would hang forever, so tell git to fail instead. + // Force piped progress immediately; refuse credential prompts that would hang without a tty. GIT_PROGRESS_DELAY: "0", GIT_TERMINAL_PROMPT: "0", LC_ALL: "C", @@ -90,11 +90,9 @@ function mapRepositoryError(operation: string, provider: SourceControlProviderKi operation, provider, detail: - isSourceControlProviderError(cause) && - cause.provider === "bitbucket" && - isBitbucketRepositoryLocatorError(cause.cause) - ? BitbucketApi.BitbucketRepositoryLocatorError.detail - : "The source control operation could not be completed.", + (isSourceControlProviderError(cause) + ? SourceControlProvider.userFacingSourceControlDetail(cause.cause) + : undefined) ?? "The source control operation could not be completed.", cause, }), ); @@ -112,11 +110,7 @@ function toRepositoryInfo( }; } -/** - * The URL clients see. A pasted `https://user:token@host/…` must not travel - * back over `subscribeProjectClones` to every reader; git still gets the - * original. - */ +// Redact credentials from client clone snapshots; git still receives the original URL. function redactRemoteUrl(remoteUrl: string): string { try { const url = new URL(remoteUrl); @@ -133,14 +127,53 @@ function redactRemoteUrl(remoteUrl: string): string { } } -// Userinfo may itself contain `@`; everything up to the last one before the -// host boundary goes. +// Userinfo can contain @; remove through the last one before the host boundary. const URL_WITH_USERINFO = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s/]+@/gi; function redactUrlCredentials(text: string): string { return text.replace(URL_WITH_USERINFO, "$1"); } +// The remote already exists after push failure; advise fixing access and pushing. +// Use fixed text and provider URLs because git stderr can expose credentials. +function publishPushFailureDetail(input: { + readonly urls: SourceControlRepositoryCloneUrls; + readonly remoteName: string; + readonly remoteUrl: string; + readonly reason: GitCommandFailureReason | undefined; +}): string { + const created = `Created ${input.urls.nameWithOwner} and added it as remote "${input.remoteName}", but the push failed`; + const switchToHttps = `git remote set-url ${input.remoteName} ${input.urls.url}`; + const usesSsh = input.remoteUrl === input.urls.sshUrl; + switch (input.reason) { + case "authentication_failed": + return usesSsh + ? `${created} because SSH authentication was rejected. Add an SSH key to your account, or switch the remote to HTTPS with "${switchToHttps}", then push again.` + : `${created} because Git could not authenticate. Check your Git credentials, then push again.`; + case "host_key_unverified": + return `${created} because the host's SSH key is not trusted yet. Verify it by connecting once with ssh, or switch the remote to HTTPS with "${switchToHttps}", then push again.`; + default: + return `${created}. Fix the problem, then push again.`; + } +} + +/** + * SSH rejection can be retried over HTTPS when the host's credential helper is available. + * Explicit SSH requests must not fall back; unknown URL shapes must not be guessed. + */ +function httpsFallbackUrl( + input: SourceControlCloneRepositoryInput, + prepared: SourceControlPreparedClone, +): string | null { + if (input.protocol === "ssh" || cloneUrlProtocol(prepared.cloneUrl) !== "ssh") return null; + if (prepared.repository?.sshUrl === prepared.cloneUrl) return prepared.repository.url; + return cloneUrlForProtocol(prepared.cloneUrl, "https"); +} + +const isSshRejection = (error: SourceControlRepositoryError) => + isGitCommandError(error.cause) && + (error.cause.reason === "authentication_failed" || error.cause.reason === "host_key_unverified"); + function selectRemoteUrl( urls: SourceControlRepositoryCloneUrls, protocol: SourceControlCloneProtocol | undefined, @@ -154,7 +187,7 @@ function selectRemoteUrl( } } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const fileSystem = yield* FileSystem.FileSystem; @@ -179,20 +212,23 @@ export const make = Effect.gen(function* () { ); }; - const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")(function* ( - input: SourceControlRepositoryLookupInput, - ) { - const providerKind = yield* ensureConcreteProvider({ - operation: "lookupRepository", - provider: input.provider, - }); - const provider = yield* providers.get(providerKind); - const urls = yield* provider.getRepositoryCloneUrls({ - cwd: input.cwd ?? config.cwd, - repository: input.repository.trim(), - }); - return toRepositoryInfo(providerKind, urls); - }); + const lookupRepository = Effect.fn("SourceControlRepositoryService.lookupRepository")( + function* (input: SourceControlRepositoryLookupInput) { + const providerKind = yield* ensureConcreteProvider({ + operation: "lookupRepository", + provider: input.provider, + }); + const provider = yield* providers.get(providerKind); + const urls = yield* provider.getRepositoryCloneUrls({ + cwd: input.cwd ?? config.cwd, + repository: input.repository.trim(), + }); + return toRepositoryInfo(providerKind, urls); + }, + // Someone adding or cloning a repository is waiting, so a background rate-limit pause must not + // refuse the lookup. + Effect.provideService(SourceControlRateLimit.Interactive, true), + ); const normalizeDestinationPath = Effect.fn("SourceControlRepositoryService.normalizeDestination")( function* (destinationPath: string) { @@ -234,7 +270,11 @@ export const make = Effect.gen(function* () { }); } } else { - yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true }); + // Skip existing parents: recursive mkdir on a Windows drive root fails with EPERM. + const parentPath = path.dirname(normalizedDestination); + if (!(yield* fileSystem.exists(parentPath))) { + yield* fileSystem.makeDirectory(parentPath, { recursive: true }); + } } return { @@ -280,15 +320,14 @@ export const make = Effect.gen(function* () { } satisfies SourceControlPreparedClone; }); - const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* ( + const runClone = Effect.fn("SourceControlRepositoryService.runClone")(function* ( input: SourceControlCloneRepositoryInput, + destinationPath: string, + cloneUrl: string, options?: SourceControlCloneOptions, ) { - const prepared = yield* prepareClone(input); const onProgress = options?.onProgress; - // Git interleaves progress redraws with its real messages on stderr. The - // last non-progress lines are what explain a failure ("Repository not - // found", "Permission denied"), so keep them for the error detail. + // Git mixes progress and diagnostics on stderr; retain non-progress tail lines for failure details. const stderrTail: Array = []; const onStderrLine = (line: string) => { const parsed = parseGitCloneProgressLine(line); @@ -304,18 +343,10 @@ export const make = Effect.gen(function* () { yield* git .execute({ operation: "SourceControlRepositoryService.cloneRepository", - cwd: path.dirname(prepared.destinationPath), - args: [ - "clone", - "--progress", - "--", - prepared.cloneUrl, - path.basename(prepared.destinationPath), - ], + cwd: path.dirname(destinationPath), + args: ["clone", "--progress", "--", cloneUrl, path.basename(destinationPath)], timeoutMs: options?.timeoutMs === undefined ? CLONE_TIMEOUT_MS : options.timeoutMs, - // Progress redraws add up on a slow multi-GB clone. The buffered copy - // is never read (the tail is kept by hand above), so keep it small - // and let the line callbacks keep flowing past the cap. + // Buffered output is unused and progress can be huge; cap it while retaining line callbacks. maxOutputBytes: 256 * 1024, appendTruncationMarker: true, keepLineCallbacksAfterTruncation: true, @@ -336,10 +367,42 @@ export const make = Effect.gen(function* () { }), ), ); + }); + + const cloneRepository = Effect.fn("SourceControlRepositoryService.cloneRepository")(function* ( + input: SourceControlCloneRepositoryInput, + options?: SourceControlCloneOptions, + ) { + const prepared = yield* prepareClone(input); + const httpsUrl = httpsFallbackUrl(input, prepared); + const remoteUrl = yield* runClone( + input, + prepared.destinationPath, + prepared.cloneUrl, + options, + ).pipe( + Effect.as(prepared.remoteUrl), + Effect.catch((sshError) => + httpsUrl === null || !isSshRejection(sshError) + ? Effect.fail(sshError) + : runClone(input, prepared.destinationPath, httpsUrl, options).pipe( + Effect.as(redactRemoteUrl(httpsUrl)), + Effect.mapError( + (httpsError) => + new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: sshError.provider, + detail: `${sshError.detail} Cloning over HTTPS instead also failed: ${httpsError.detail}`, + cause: httpsError.cause, + }), + ), + ), + ), + ); return { cwd: prepared.destinationPath, - remoteUrl: prepared.remoteUrl, + remoteUrl, repository: prepared.repository, }; }); @@ -348,11 +411,8 @@ export const make = Effect.gen(function* () { destinationPath: string, ) { const normalized = yield* normalizeDestinationPath(destinationPath); - // Only what git left behind may go. The destination was empty when the - // clone started, so anything without a `.git` inside was put there by - // someone else since; refuse rather than delete their files. - // A missing destination is already discarded; any other read failure - // (a file in its place, permissions) is not something to remove through. + // Only .git-bearing partial clones may be deleted; other files arrived after the empty-directory check. + // Missing destinations are already discarded; other read failures must refuse removal. const entries = yield* fileSystem.readDirectory(normalized).pipe( Effect.catchIf( (cause) => cause.reason._tag === "NotFound", @@ -375,9 +435,7 @@ export const make = Effect.gen(function* () { detail: "Destination path contains files that are not from the clone.", }); } - // The directory itself is the project's workspace root and must stay; - // only git's partial contents go. An interrupted git may still be closing - // files, so removal retries briefly. + // Preserve the workspace directory after removing partial contents; retry while interrupted git closes files. yield* fileSystem.remove(normalized, { recursive: true, force: true }).pipe( Effect.andThen(fileSystem.makeDirectory(normalized, { recursive: true })), Effect.retry({ schedule: Schedule.spaced("200 millis"), times: 5 }), @@ -412,10 +470,7 @@ export const make = Effect.gen(function* () { url: remoteUrl, }); - // An empty local repo (no commits) would make `git push HEAD:...` fail - // with an opaque "src refspec HEAD does not match any". Treat this as a - // partial success: the remote was created and wired up, but there is - // nothing to push yet. + // Empty repos cannot push HEAD; report partial success because the remote already exists. const hasCommits = yield* git .execute({ operation: "SourceControlRepositoryService.publishRepository.headCheck", @@ -437,7 +492,22 @@ export const make = Effect.gen(function* () { }; } - const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName }); + const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName }).pipe( + Effect.mapError( + (cause) => + new SourceControlRepositoryError({ + operation: "publishRepository", + provider: providerKind, + detail: publishPushFailureDetail({ + urls, + remoteName, + remoteUrl, + reason: cause.reason, + }), + cause, + }), + ), + ); return { repository: toRepositoryInfo(providerKind, urls), diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts index 9212122d195e5..0e994dcac4a7f 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -1,48 +1,31 @@ -import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli"; -import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli"; -import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; -import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi"; -import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; -import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli"; -import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; -import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi"; -import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials"; -import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; -import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; -import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; -import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; -import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; -import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli"; -import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; -import type { SourceControlDriver } from "@t3tools/source-control-core/server/driver"; +import type { + SourceControlDriver, + SourceControlDriverInstance, +} from "@t3tools/source-control-core/server/driver"; +import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as ServerSourceControlHost from "./ServerSourceControlHost.ts"; +import { BUILT_IN_SOURCE_CONTROL_DRIVER_LIST } from "./sourceControlDefinitions.ts"; -const drivers = [ - GitHubDriver.driver, - GitLabDriver.driver, - AzureDevOpsDriver.driver, - BitbucketDriver.driver, - ForgejoDriver.driver, - GitCafeDriver.driver, -]; +export interface SourceControlDriverEntry { + readonly driver: Pick; + readonly instance: SourceControlDriverInstance; +} -export type BuiltInSourceControlDriversEnv = - (typeof drivers)[number] extends SourceControlDriver ? R : never; +/** Every driver's instance, in registry order. Everything that reads a host reads it here. */ +export class SourceControlDrivers extends Context.Service< + SourceControlDrivers, + ReadonlyArray +>()("t3/sourceControl/builtInDrivers/SourceControlDrivers") {} -export const BUILT_IN_SOURCE_CONTROL_DRIVERS: ReadonlyArray< - SourceControlDriver -> = drivers; +const make = Effect.forEach(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, (driver) => + driver.make.pipe(Effect.map((instance) => ({ driver, instance }))), +); -export const layer = Layer.mergeAll( - // `GitHubRest.layerWithDependencies` carries the quota reserve and rate-limit pause every GitHub - // reader shares, so the server builds it once, here. - GitHubPullRequestApi.layer.pipe(Layer.provideMerge(GitHubRest.layerWithDependencies)), - AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer)), - BitbucketPullRequestApi.layer.pipe(Layer.provideMerge(BitbucketApi.layer)), - ForgejoCli.layer, - GitCafeApi.layer.pipe(Layer.provideMerge(GitCafeCredentials.layer)), - GitLabPullRequestCli.layer.pipe(Layer.provideMerge(GitLabCli.layer)), -).pipe(Layer.provideMerge(ServerSourceControlHost.layer)); +export const layer = Layer.effect(SourceControlDrivers, make).pipe( + Layer.provideMerge(ServerSourceControlHost.layer), + Layer.provideMerge(SourceControlRateLimit.layer), +); diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.test.ts b/apps/server/src/sourceControl/sourceControlDefinitions.test.ts new file mode 100644 index 0000000000000..e21efd8173a73 --- /dev/null +++ b/apps/server/src/sourceControl/sourceControlDefinitions.test.ts @@ -0,0 +1,12 @@ +import { expect, it } from "@effect/vitest"; + +import { + BUILT_IN_SOURCE_CONTROL_DRIVER_LIST, + sourceControlDefinitions, +} from "./sourceControlDefinitions.ts"; + +it("runs a driver for every host the server and clients read, in their order", () => { + expect(BUILT_IN_SOURCE_CONTROL_DRIVER_LIST.map((driver) => driver.definition)).toEqual( + sourceControlDefinitions.definitions, + ); +}); diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts new file mode 100644 index 0000000000000..eaeb8dd55f110 --- /dev/null +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -0,0 +1,19 @@ +import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; +import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; +import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; +import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; +import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; +import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; + +/** In the shared registry's order, which is the order hosts are listed and probed in. */ +export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ + GitHubDriver.driver, + GitLabDriver.driver, + GitCafeDriver.driver, + ForgejoDriver.driver, + BitbucketDriver.driver, + AzureDevOpsDriver.driver, +] as const; + +export const sourceControlDefinitions = builtInSourceControlDefinitions; diff --git a/apps/server/src/sourceControl/sourceControlHostSecrets.ts b/apps/server/src/sourceControl/sourceControlHostSecrets.ts index 8ac8046985ce6..46c96ca5b7f05 100644 --- a/apps/server/src/sourceControl/sourceControlHostSecrets.ts +++ b/apps/server/src/sourceControl/sourceControlHostSecrets.ts @@ -1,26 +1,12 @@ import { secretSettingsFields } from "@t3tools/contracts"; -import * as AzureDevOps from "@t3tools/source-control-azure-devops/client/definition"; -import * as Bitbucket from "@t3tools/source-control-bitbucket/client/definition"; -import type { SourceControlClientDefinition } from "@t3tools/source-control-core/client/definition"; -import * as Forgejo from "@t3tools/source-control-forgejo/client/definition"; -import * as GitCafe from "@t3tools/source-control-gitcafe/client/definition"; -import * as GitHub from "@t3tools/source-control-github/client/definition"; -import * as GitLab from "@t3tools/source-control-gitlab/client/definition"; -const definitions: ReadonlyArray = [ - GitHub.definition, - GitLab.definition, - AzureDevOps.definition, - Bitbucket.definition, - Forgejo.definition, - GitCafe.definition, -]; +import { sourceControlDefinitions } from "./sourceControlDefinitions.ts"; export const SOURCE_CONTROL_HOST_SECRET_FIELDS: ReadonlyMap< string, ReadonlyArray > = new Map( - definitions.flatMap((definition) => { + sourceControlDefinitions.definitions.flatMap((definition) => { const fields = definition.settings ? secretSettingsFields(definition.settings) : []; return fields.length > 0 ? [[definition.kind, fields] as const] : []; }), diff --git a/apps/server/src/sourceControl/threadPullRequests.ts b/apps/server/src/sourceControl/threadPullRequests.ts new file mode 100644 index 0000000000000..8d9c72b1c6cdf --- /dev/null +++ b/apps/server/src/sourceControl/threadPullRequests.ts @@ -0,0 +1,15 @@ +import { makeThreadPullRequests } from "@t3tools/source-control-core/shared/threadPullRequests"; + +import { sourceControlDefinitions } from "./sourceControlDefinitions.ts"; + +export { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; + +export const { + normalizeThreadPullRequestKey, + legacyThreadPullRequestKey, + threadPullRequestKeysEqual, + threadPullRequestKeyOf, + resolveThreadPullRequestChains, + threadPullRequestsOf, + applyThreadPullRequestLinkUpdate, +} = makeThreadPullRequests(sourceControlDefinitions); diff --git a/apps/server/src/speechToText/SpeechToText.test.ts b/apps/server/src/speechToText/SpeechToText.test.ts new file mode 100644 index 0000000000000..fb7d87de7d9ec --- /dev/null +++ b/apps/server/src/speechToText/SpeechToText.test.ts @@ -0,0 +1,254 @@ +import { describe, expect, it } from "@effect/vitest"; +import { SpeechToTextSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import { + parseSpeechToTextResponse, + resolveSpeechToTextRequest, + SpeechToTextFailure, + speechToTextFileName, + transcribeSpeech, +} from "./SpeechToText.ts"; + +const settings = Schema.decodeUnknownSync(SpeechToTextSettings); + +describe("resolveSpeechToTextRequest", () => { + it("sends OpenAI-style providers to /audio/transcriptions with their defaults", () => { + const request = resolveSpeechToTextRequest( + settings({ + provider: "groq", + language: "de", + prompt: "T3 Code, Effect", + providers: { groq: { apiKey: "gsk" } }, + }), + "audio/webm;codecs=opus", + ); + expect(request).toEqual({ + provider: "groq", + url: "https://api.groq.com/openai/v1/audio/transcriptions", + headers: { authorization: "Bearer gsk" }, + fields: [ + ["model", "whisper-large-v3-turbo"], + ["response_format", "json"], + ["language", "de"], + ["prompt", "T3 Code, Effect"], + ], + fileName: "dictation.webm", + }); + }); + + it("uses each service's own endpoint, auth header and field names", () => { + const elevenlabs = resolveSpeechToTextRequest( + settings({ + provider: "elevenlabs", + language: "en", + providers: { elevenlabs: { apiKey: "xi" } }, + }), + "audio/mp4", + ); + expect(elevenlabs).toMatchObject({ + url: "https://api.elevenlabs.io/v1/speech-to-text", + headers: { "xi-api-key": "xi" }, + fields: [ + ["model_id", "scribe_v2"], + ["tag_audio_events", "false"], + ["language_code", "en"], + ], + fileName: "dictation.m4a", + }); + + const xai = resolveSpeechToTextRequest( + settings({ provider: "xai", prompt: "ignored", providers: { xai: { apiKey: "xk" } } }), + "audio/webm", + ); + expect(xai).toMatchObject({ url: "https://api.x.ai/v1/stt", fields: [["format", "true"]] }); + + // Mistral ignores prompts; they must not be sent. + const mistral = resolveSpeechToTextRequest( + settings({ + provider: "mistral", + prompt: "ignored", + providers: { mistral: { apiKey: "mk" } }, + }), + "audio/webm", + ); + expect(mistral).toMatchObject({ + url: "https://api.mistral.ai/v1/audio/transcriptions", + fields: [ + ["model", "voxtral-mini-latest"], + ["response_format", "json"], + ], + }); + }); + + it("lets a self-hosted server run without a key", () => { + const request = resolveSpeechToTextRequest( + settings({ + provider: "openai-compatible", + providers: { + "openai-compatible": { + baseUrl: "http://127.0.0.1:8000/v1/", + model: "Systran/faster-whisper-small", + }, + }, + }), + "audio/wav", + ); + expect(request).toMatchObject({ + url: "http://127.0.0.1:8000/v1/audio/transcriptions", + headers: {}, + fileName: "dictation.wav", + }); + }); + + it("explains what is missing", () => { + const off = resolveSpeechToTextRequest(settings({}), "audio/webm"); + expect(off).toBeInstanceOf(SpeechToTextFailure); + const missingKey = resolveSpeechToTextRequest(settings({ provider: "openai" }), "audio/webm"); + expect((missingKey as SpeechToTextFailure).message).toBe( + "Add your OpenAI API key in Settings → Speech to text.", + ); + const missingUrl = resolveSpeechToTextRequest( + settings({ provider: "openai-compatible" }), + "audio/webm", + ); + expect((missingUrl as SpeechToTextFailure).message).toBe( + "Add the server URL in Settings → Speech to text.", + ); + }); +}); + +describe("parseSpeechToTextResponse", () => { + it("returns the trimmed transcript", () => { + expect(parseSpeechToTextResponse("openai", 200, '{"text":" Hallo Welt "}')).toBe("Hallo Welt"); + }); + + it("surfaces the provider's error message", () => { + const failure = parseSpeechToTextResponse( + "openai", + 401, + '{"error":{"message":"Incorrect API key provided."}}', + ); + expect((failure as SpeechToTextFailure).message).toBe( + "OpenAI rejected the recording (HTTP 401): Incorrect API key provided.", + ); + const elevenlabs = parseSpeechToTextResponse( + "elevenlabs", + 422, + '{"detail":{"message":"Unsupported audio."}}', + ); + expect((elevenlabs as SpeechToTextFailure).message).toContain("Unsupported audio."); + }); + + it("rejects a success without text", () => { + expect(parseSpeechToTextResponse("groq", 200, "{}")).toBeInstanceOf(SpeechToTextFailure); + }); +}); + +describe("speechToTextFileName", () => { + it("matches the container so the service picks the right decoder", () => { + expect(speechToTextFileName("audio/ogg;codecs=opus")).toBe("dictation.ogg"); + expect(speechToTextFileName("audio/x-m4a")).toBe("dictation.m4a"); + expect(speechToTextFileName("application/octet-stream")).toBe("dictation.webm"); + }); +}); + +describe("transcribeSpeech", () => { + it.effect("uploads the recording as multipart form data", () => + Effect.gen(function* () { + const seen: Array<{ url: string; auth: string | undefined; form: FormData }> = []; + const http = HttpClient.make((request) => + Effect.promise(async () => { + if (request.body._tag !== "FormData") throw new Error("expected multipart body"); + seen.push({ + url: request.url, + auth: request.headers.authorization, + form: request.body.formData, + }); + return HttpClientResponse.fromWeb(request, Response.json({ text: "Hello there." })); + }), + ); + const text = yield* transcribeSpeech( + settings({ + provider: "openai", + providers: { openai: { apiKey: "sk", model: "whisper-1" } }, + }), + { bytes: new Uint8Array([1, 2, 3]), mimeType: "audio/webm" }, + ).pipe(Effect.provideService(HttpClient.HttpClient, http)); + + expect(text).toBe("Hello there."); + expect(seen).toHaveLength(1); + expect(seen[0]!.url).toBe("https://api.openai.com/v1/audio/transcriptions"); + expect(seen[0]!.auth).toBe("Bearer sk"); + expect(seen[0]!.form.get("model")).toBe("whisper-1"); + const file = seen[0]!.form.get("file") as File; + expect(file.name).toBe("dictation.webm"); + expect(file.size).toBe(3); + }), + ); + + it.effect("never repeats the configured key from a provider error", () => + Effect.gen(function* () { + const http = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json( + { error: { message: "Invalid API key: gsk-secret-123" } }, + { status: 401 }, + ), + ), + ), + ); + const failure = yield* transcribeSpeech( + settings({ provider: "groq", providers: { groq: { apiKey: "gsk-secret-123" } } }), + { bytes: new Uint8Array([1]), mimeType: "audio/webm" }, + ).pipe(Effect.provideService(HttpClient.HttpClient, http), Effect.flip); + expect(failure.message).not.toContain("gsk-secret-123"); + expect(failure.message).not.toContain("gsk-secret-12"); + expect(failure.message).toBe( + "Groq rejected the recording (HTTP 401): Invalid API key: [redacted]", + ); + }), + ); + + it.effect("masks a key that straddles the error detail limit", () => + Effect.gen(function* () { + const message = `${"x".repeat(290)} gsk-secret-123`; + const http = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ error: { message } }, { status: 401 }), + ), + ), + ); + const failure = yield* transcribeSpeech( + settings({ provider: "groq", providers: { groq: { apiKey: "gsk-secret-123" } } }), + { bytes: new Uint8Array([1]), mimeType: "audio/webm" }, + ).pipe(Effect.provideService(HttpClient.HttpClient, http), Effect.flip); + expect(failure.message).not.toContain("gsk-secret"); + }), + ); + + it.effect("fails with the provider's message instead of an empty transcript", () => + Effect.gen(function* () { + const http = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ error: { message: "quota exceeded" } }, { status: 429 }), + ), + ), + ); + const failure = yield* transcribeSpeech( + settings({ provider: "groq", providers: { groq: { apiKey: "gsk" } } }), + { bytes: new Uint8Array([1]), mimeType: "audio/webm" }, + ).pipe(Effect.provideService(HttpClient.HttpClient, http), Effect.flip); + expect(failure.status).toBe(502); + expect(failure.message).toBe("Groq rejected the recording (HTTP 429): quota exceeded"); + }), + ); +}); diff --git a/apps/server/src/speechToText/SpeechToText.ts b/apps/server/src/speechToText/SpeechToText.ts new file mode 100644 index 0000000000000..a27fccf3c6357 --- /dev/null +++ b/apps/server/src/speechToText/SpeechToText.ts @@ -0,0 +1,241 @@ +import { + resolveSpeechToTextProviderSettings, + SPEECH_TO_TEXT_PROVIDERS, + type SpeechToTextProvider, + type SpeechToTextSettings, +} from "@t3tools/contracts"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import { HttpClient, HttpClientRequest } from "effect/http"; + +// Self-hosted Whisper servers can take a while to load a model on the first request. +const TRANSCRIPTION_TIMEOUT = "120 seconds"; +const ERROR_DETAIL_MAX_LENGTH = 300; + +export class SpeechToTextFailure extends Data.TaggedError("SpeechToTextFailure")<{ + /** HTTP status for the client: 4xx when the setup is wrong, 502 when the service failed. */ + readonly status: number; + readonly message: string; +}> {} + +export type SpeechToTextAudio = { + readonly bytes: Uint8Array; + readonly mimeType: string; +}; + +export type SpeechToTextRequest = { + readonly provider: SpeechToTextProvider; + readonly url: string; + readonly headers: Readonly>; + /** Multipart fields sent alongside the `file` part. */ + readonly fields: ReadonlyArray; + readonly fileName: string; +}; + +const AUDIO_EXTENSIONS: Readonly> = { + "audio/webm": "webm", + "audio/ogg": "ogg", + "audio/mp4": "m4a", + "audio/m4a": "m4a", + "audio/x-m4a": "m4a", + "audio/aac": "aac", + "audio/mpeg": "mp3", + "audio/wav": "wav", + "audio/x-wav": "wav", + "audio/flac": "flac", +}; + +/** Whisper-style APIs pick the decoder from the file name, so it must match the container. */ +export function speechToTextFileName(mimeType: string): string { + const essence = mimeType.split(";")[0]!.trim().toLowerCase(); + return `dictation.${AUDIO_EXTENSIONS[essence] ?? "webm"}`; +} + +/** Builds the provider request, or explains which setting is missing. */ +export function resolveSpeechToTextRequest( + settings: SpeechToTextSettings, + mimeType: string, +): SpeechToTextRequest | SpeechToTextFailure { + const provider = settings.provider; + if (provider === null) { + return new SpeechToTextFailure({ + status: 409, + message: "Speech to text is turned off for this environment.", + }); + } + const info = SPEECH_TO_TEXT_PROVIDERS[provider]; + const configured = resolveSpeechToTextProviderSettings(settings, provider); + const apiKey = configured.apiKey; + if (info.apiKeyRequired && apiKey.length === 0) { + return new SpeechToTextFailure({ + status: 409, + message: `Add your ${info.label} API key in Settings → Speech to text.`, + }); + } + const baseUrl = (configured.baseUrl || info.defaultBaseUrl).replace(/\/+$/, ""); + if (baseUrl.length === 0) { + return new SpeechToTextFailure({ + status: 409, + message: "Add the server URL in Settings → Speech to text.", + }); + } + const model = configured.model || info.defaultModel; + if (model.length === 0 && provider !== "xai") { + return new SpeechToTextFailure({ + status: 409, + message: "Choose a model in Settings → Speech to text.", + }); + } + const language = settings.language; + const prompt = info.supportsPrompt ? settings.prompt : ""; + const bearer: Record = apiKey ? { authorization: `Bearer ${apiKey}` } : {}; + const fileName = speechToTextFileName(mimeType); + + switch (provider) { + case "xai": + return { + provider, + url: `${baseUrl}/stt`, + headers: bearer, + fields: [["format", "true"], ...(language ? [["language", language] as const] : [])], + fileName, + }; + case "elevenlabs": + return { + provider, + url: `${baseUrl}/speech-to-text`, + headers: { "xi-api-key": apiKey }, + fields: [ + ["model_id", model], + ["tag_audio_events", "false"], + ...(language ? [["language_code", language] as const] : []), + ], + fileName, + }; + case "openai": + case "groq": + case "mistral": + case "deepinfra": + case "openai-compatible": + return { + provider, + url: `${baseUrl}/audio/transcriptions`, + headers: bearer, + fields: [ + ["model", model], + ["response_format", "json"], + ...(language ? [["language", language] as const] : []), + ...(prompt ? [["prompt", prompt] as const] : []), + ], + fileName, + }; + } +} + +/** + * Some services and proxies echo the submitted credential in authentication errors; their + * messages reach logs and clients, so the configured key is masked first. + */ +export function redactSpeechToTextSecret(message: string, apiKey: string): string { + return apiKey.length > 0 ? message.replaceAll(apiKey, "[redacted]") : message; +} + +function readErrorDetail(body: string): string { + try { + const parsed: unknown = JSON.parse(body); + if (parsed !== null && typeof parsed === "object") { + const record = parsed as Record; + for (const candidate of [record.error, record.detail, record]) { + if (typeof candidate === "string" && candidate.trim()) { + return candidate.trim().slice(0, ERROR_DETAIL_MAX_LENGTH); + } + if (candidate !== null && typeof candidate === "object") { + const message = (candidate as Record).message; + if (typeof message === "string" && message.trim()) { + return message.trim().slice(0, ERROR_DETAIL_MAX_LENGTH); + } + } + } + } + } catch {} + return body.trim().slice(0, ERROR_DETAIL_MAX_LENGTH); +} + +/** Every supported service answers with JSON carrying the transcript in `text`. */ +export function parseSpeechToTextResponse( + provider: SpeechToTextProvider, + status: number, + body: string, +): string | SpeechToTextFailure { + const label = SPEECH_TO_TEXT_PROVIDERS[provider].label; + if (status < 200 || status >= 300) { + const detail = readErrorDetail(body); + return new SpeechToTextFailure({ + status: 502, + message: `${label} rejected the recording (HTTP ${status})${detail ? `: ${detail}` : "."}`, + }); + } + try { + const parsed: unknown = JSON.parse(body); + const text = + parsed !== null && typeof parsed === "object" + ? (parsed as Record).text + : undefined; + if (typeof text === "string") return text.trim(); + } catch {} + return new SpeechToTextFailure({ + status: 502, + message: `${label} returned a response without a transcript.`, + }); +} + +export const transcribeSpeech = Effect.fn("SpeechToText.transcribe")(function* ( + settings: SpeechToTextSettings, + audio: SpeechToTextAudio, +) { + const request = resolveSpeechToTextRequest(settings, audio.mimeType); + if (request instanceof SpeechToTextFailure) return yield* request; + + const form = new FormData(); + for (const [name, value] of request.fields) form.append(name, value); + form.append( + "file", + new Blob([audio.bytes as Uint8Array], { type: audio.mimeType }), + request.fileName, + ); + + const label = SPEECH_TO_TEXT_PROVIDERS[request.provider].label; + const client = yield* HttpClient.HttpClient; + const response = yield* client + .execute( + HttpClientRequest.post(request.url).pipe( + HttpClientRequest.setHeaders(request.headers), + HttpClientRequest.bodyFormData(form), + ), + ) + .pipe( + Effect.flatMap((response) => + Effect.map(response.text, (body) => ({ status: response.status, body })), + ), + Effect.timeout(TRANSCRIPTION_TIMEOUT), + // Request spans would record the API key header and the provider URL. + Effect.withTracerEnabled(false), + Effect.mapError( + () => + new SpeechToTextFailure({ + status: 502, + message: `Could not reach ${label}. Check the server URL and network.`, + }), + ), + ); + + // Masked before parsing, which truncates details and could cut a key in half. + const apiKey = resolveSpeechToTextProviderSettings(settings, request.provider).apiKey; + const transcript = parseSpeechToTextResponse( + request.provider, + response.status, + redactSpeechToTextSecret(response.body, apiKey), + ); + if (transcript instanceof SpeechToTextFailure) return yield* transcript; + return transcript; +}); diff --git a/apps/server/src/speechToText/SpeechToTextRoute.test.ts b/apps/server/src/speechToText/SpeechToTextRoute.test.ts new file mode 100644 index 0000000000000..112de1a694243 --- /dev/null +++ b/apps/server/src/speechToText/SpeechToTextRoute.test.ts @@ -0,0 +1,103 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http"; + +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import * as ServerConfig from "../config.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { + issueSpeechToTextUploadUrl, + layerSpeechToTextRoute, + SPEECH_TO_TEXT_ROUTE_PREFIX, + validateSpeechToTextUploadToken, +} from "./SpeechToTextRoute.ts"; + +const layerWith = (speechToText: Parameters[0]) => + Layer.mergeAll(ServerSecretStore.layer, ServerSettingsService.layerTest(speechToText)).pipe( + Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-speech-to-text-" })), + Layer.provideMerge(NodeServices.layer), + ); + +const configured = layerWith({ + speechToText: { provider: "groq", providers: { groq: { apiKey: "gsk" } } }, +}); + +const input = { mimeType: "audio/webm", sizeBytes: 2048 } as const; + +describe("SpeechToTextRoute upload URLs", () => { + it.effect("signs the recording's type and size", () => + Effect.gen(function* () { + const issued = yield* issueSpeechToTextUploadUrl(input); + const token = issued.relativeUrl.slice(`${SPEECH_TO_TEXT_ROUTE_PREFIX}/`.length); + expect(yield* validateSpeechToTextUploadToken(token)).toMatchObject({ + kind: "speech-to-text-upload", + mimeType: "audio/webm", + sizeBytes: 2048, + }); + + const [payload, signature] = token.split("."); + expect(yield* validateSpeechToTextUploadToken(`${payload}x.${signature}`)).toBeNull(); + expect(yield* validateSpeechToTextUploadToken(`${token}.extra`)).toBeNull(); + }).pipe(Effect.provide(configured)), + ); + + it.effect("refuses to mint a URL until a provider is set up", () => + Effect.gen(function* () { + const failure = yield* issueSpeechToTextUploadUrl(input).pipe(Effect.flip); + expect(failure._tag).toBe("SpeechToTextUnavailableError"); + expect(failure.reason).toBe("not-configured"); + }).pipe(Effect.provide(layerWith({ speechToText: { provider: "openai", providers: {} } }))), + ); +}); + +describe("SpeechToTextRoute transcription", () => { + it.effect("transcribes an upload through the configured service", () => + Effect.gen(function* () { + const forwarded: Array<{ url: string; size: number }> = []; + const provider = HttpClient.make((request) => + Effect.sync(() => { + const file = + request.body._tag === "FormData" ? (request.body.formData.get("file") as File) : null; + forwarded.push({ url: request.url, size: file?.size ?? -1 }); + return HttpClientResponse.fromWeb(request, Response.json({ text: "Hallo Welt." })); + }), + ); + const issued = yield* issueSpeechToTextUploadUrl({ mimeType: "audio/webm", sizeBytes: 4 }); + const context = yield* Effect.context< + ServerSecretStore.ServerSecretStore | ServerSettingsService + >(); + const { handler, dispose } = HttpRouter.toWebHandler( + layerSpeechToTextRoute.pipe( + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, provider)), + ), + { disableLogger: true }, + ); + yield* Effect.addFinalizer(() => Effect.promise(dispose)); + const post = (body: Uint8Array) => + Effect.promise(() => + handler( + new Request(`http://t3.test${issued.relativeUrl}`, { + method: "POST", + headers: { "content-type": "audio/webm" }, + body: body as Uint8Array, + }), + ), + ); + + const response = yield* post(new Uint8Array([1, 2, 3, 4])); + expect(response.status).toBe(200); + expect(yield* Effect.promise(() => response.json())).toEqual({ text: "Hallo Welt." }); + expect(forwarded).toEqual([ + { url: "https://api.groq.com/openai/v1/audio/transcriptions", size: 4 }, + ]); + + // A body that does not match the signed size never reaches the service. + const mismatched = yield* post(new Uint8Array([1, 2])); + expect(mismatched.status).toBe(400); + expect(forwarded).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(configured)), + ); +}); diff --git a/apps/server/src/speechToText/SpeechToTextRoute.ts b/apps/server/src/speechToText/SpeechToTextRoute.ts new file mode 100644 index 0000000000000..76516b44c7dcb --- /dev/null +++ b/apps/server/src/speechToText/SpeechToTextRoute.ts @@ -0,0 +1,153 @@ +import { + isSpeechToTextConfigured, + SPEECH_TO_TEXT_UPLOAD_URL_TTL_MS, + type SpeechToTextCreateUploadUrlInput, + SpeechToTextUnavailableError, +} from "@t3tools/contracts"; +import * as ByteSize from "effect/ByteSize"; +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import { HttpMiddleware, HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; + +import { + base64UrlDecodeUtf8, + base64UrlEncode, + signPayload, + timingSafeEqualBase64Url, +} from "../auth/utils.ts"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { SpeechToTextFailure, transcribeSpeech } from "./SpeechToText.ts"; + +export const SPEECH_TO_TEXT_ROUTE_PREFIX = "/api/speech-to-text/transcriptions"; + +const SIGNING_SECRET_NAME = "speech-to-text-upload-signing-key"; + +// The URL is the credential, like attachment uploads, so every client and connection mode can +// POST the recording without building auth headers. The claims pin the size and type. +const UploadClaims = Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("speech-to-text-upload"), + mimeType: Schema.String, + sizeBytes: Schema.Number, + expiresAt: Schema.Number, +}); +type UploadClaims = typeof UploadClaims.Type; + +const uploadClaimsJson = Schema.fromJsonString(UploadClaims); +const decodeUploadClaims = Schema.decodeUnknownOption(uploadClaimsJson); +const encodeUploadClaims = Schema.encodeSync(uploadClaimsJson); + +const loadSigningSecret = Effect.gen(function* () { + const secretStore = yield* ServerSecretStore.ServerSecretStore; + return yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32); +}); + +export const issueSpeechToTextUploadUrl = Effect.fn("SpeechToText.issueUploadUrl")(function* ( + input: SpeechToTextCreateUploadUrlInput, +) { + const settingsService = yield* ServerSettingsService; + const settings = yield* settingsService.getSettings.pipe(Effect.orElseSucceed(() => null)); + if (!settings || !isSpeechToTextConfigured(settings.speechToText)) { + return yield* new SpeechToTextUnavailableError({ reason: "not-configured" }); + } + const secret = yield* loadSigningSecret.pipe( + Effect.mapError(() => new SpeechToTextUnavailableError({ reason: "signing-key" })), + ); + const expiresAt = (yield* Clock.currentTimeMillis) + SPEECH_TO_TEXT_UPLOAD_URL_TTL_MS; + const encodedPayload = base64UrlEncode( + encodeUploadClaims({ + version: 1, + kind: "speech-to-text-upload", + mimeType: input.mimeType, + sizeBytes: input.sizeBytes, + expiresAt, + }), + ); + return { + relativeUrl: `${SPEECH_TO_TEXT_ROUTE_PREFIX}/${encodedPayload}.${signPayload(encodedPayload, secret)}`, + expiresAt, + }; +}); + +export const validateSpeechToTextUploadToken = Effect.fn("SpeechToText.validateUploadToken")( + function* (token: string) { + const [encodedPayload, signature, unexpectedSegment] = token.split("."); + if (!encodedPayload || !signature || unexpectedSegment) return null; + const secret = yield* loadSigningSecret.pipe(Effect.orElseSucceed(() => null)); + if (!secret || !timingSafeEqualBase64Url(signature, signPayload(encodedPayload, secret))) { + return null; + } + let claims: UploadClaims | null; + try { + claims = Option.getOrNull(decodeUploadClaims(base64UrlDecodeUtf8(encodedPayload))); + } catch { + claims = null; + } + if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null; + return claims; + }, +); + +const jsonResponse = (status: number, body: Record) => + HttpServerResponse.jsonUnsafe(body, { + status, + headers: { "cache-control": "private, no-store" }, + }); + +export const layerSpeechToTextRoute = HttpRouter.add( + "POST", + `${SPEECH_TO_TEXT_ROUTE_PREFIX}/*`, + // The token in the path is the credential, so this request never reaches the access log. + HttpMiddleware.withLoggerDisabled( + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) return jsonResponse(400, { error: "Bad request." }); + + const token = url.value.pathname.slice(`${SPEECH_TO_TEXT_ROUTE_PREFIX}/`.length); + const claims = token ? yield* validateSpeechToTextUploadToken(token) : null; + if (!claims) { + return jsonResponse(404, { error: "This upload link expired. Record again." }); + } + const contentLength = request.headers["content-length"]; + if (contentLength !== undefined && Number(contentLength) !== claims.sizeBytes) { + return jsonResponse(400, { error: "Content-Length must match the upload size." }); + } + // Chunked requests carry no content-length, so the reader itself is capped. + const body = yield* request.arrayBuffer.pipe( + Effect.map((buffer) => new Uint8Array(buffer)), + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(claims.sizeBytes)), + Effect.option, + ); + if (Option.isNone(body) || body.value.byteLength !== claims.sizeBytes) { + return jsonResponse(400, { error: "The recording did not match its declared size." }); + } + + const settingsService = yield* ServerSettingsService; + const settings = yield* settingsService.getSettings.pipe(Effect.option); + if (Option.isNone(settings)) { + return jsonResponse(500, { error: "Could not read the speech-to-text settings." }); + } + return yield* transcribeSpeech(settings.value.speechToText, { + bytes: body.value, + mimeType: claims.mimeType, + }).pipe( + Effect.map((text) => jsonResponse(200, { text })), + Effect.catchTags({ + SpeechToTextFailure: (failure: SpeechToTextFailure) => + Effect.as( + Effect.logWarning("Speech-to-text transcription failed.", { + status: failure.status, + message: failure.message, + }), + jsonResponse(failure.status, { error: failure.message }), + ), + }), + ); + }), + ), +); diff --git a/apps/server/src/startupAccess.test.ts b/apps/server/src/startupAccess.test.ts index 03c01170f158e..fd56b4a4c86f3 100644 --- a/apps/server/src/startupAccess.test.ts +++ b/apps/server/src/startupAccess.test.ts @@ -1,79 +1,75 @@ -import { assert, expect, it } from "@effect/vitest"; +import type * as NodeOS from "node:os"; + +import { describe, expect, it } from "@effect/vitest"; import { - buildPairingUrl, - formatHeadlessServeOutput, - renderTerminalQrCode, - resolveHeadlessConnectionHost, + acceptsPrivateNetworkConnection, resolveHeadlessConnectionString, - resolveListeningPort, } from "./startupAccess.ts"; -it("prefers localhost when no explicit host is configured", () => { - expect(resolveHeadlessConnectionHost(undefined)).toBe("localhost"); - expect(resolveHeadlessConnectionString(undefined, 3773)).toBe("http://localhost:3773"); -}); - -it("keeps explicit bind hosts in the connection string", () => { - expect(resolveHeadlessConnectionString("127.0.0.1", 3773)).toBe("http://127.0.0.1:3773"); - expect(resolveHeadlessConnectionString("::1", 3773)).toBe("http://[::1]:3773"); +const ipv4 = (address: string, internal = false): NodeOS.NetworkInterfaceInfo => ({ + address, + netmask: "255.255.255.0", + family: "IPv4", + mac: "00:00:00:00:00:00", + internal, + cidr: `${address}/24`, }); it("resolves wildcard hosts to a concrete external interface when one is available", () => { const connectionString = resolveHeadlessConnectionString("0.0.0.0", 3773, { - en0: [ - { - address: "192.168.1.42", - netmask: "255.255.255.0", - family: "IPv4", - mac: "00:00:00:00:00:00", - internal: false, - cidr: "192.168.1.42/24", - }, - ], - lo0: [ - { - address: "127.0.0.1", - netmask: "255.0.0.0", - family: "IPv4", - mac: "00:00:00:00:00:00", - internal: true, - cidr: "127.0.0.1/8", - }, - ], + interfaces: { en0: [ipv4("192.168.1.42")], lo0: [ipv4("127.0.0.1", true)] }, }); expect(connectionString).toBe("http://192.168.1.42:3773"); }); -it("prefers the actual bound port when an http server address is available", () => { - expect(resolveListeningPort({ port: 4123 }, 3773)).toBe(4123); - expect(resolveListeningPort("pipe", 3773)).toBe(3773); - expect(resolveListeningPort(null, 3773)).toBe(3773); -}); +it("skips public and container addresses for a private-network listener", () => { + const interfaces = { + eth0: [ipv4("203.0.113.7")], + docker0: [ipv4("172.17.0.1")], + bridge200: [ipv4("192.168.64.1")], + eth1: [ipv4("10.0.0.5")], + }; -it("builds a pairing URL that embeds the token in the hash", () => { - expect(buildPairingUrl("http://192.168.1.42:3773", "PAIRCODE")).toBe( - "http://192.168.1.42:3773/pair#token=PAIRCODE", + expect(resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces })).toBe( + "http://203.0.113.7:3773", ); + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { interfaces, privateNetworkOnly: true }), + ).toBe("http://10.0.0.5:3773"); + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { eth0: [ipv4("203.0.113.7")] }, + privateNetworkOnly: true, + }), + ).toBe("http://localhost:3773"); }); -it("renders terminal QR codes as a multi-line unicode block grid", () => { - const qrCode = renderTerminalQrCode("http://192.168.1.42:3773/pair#token=PAIRCODE"); - - assert.isTrue(qrCode.includes("█")); - assert.isTrue(qrCode.split("\n").length > 10); +it("prefers a LAN address over a tailnet one for a private-network pairing URL", () => { + expect( + resolveHeadlessConnectionString("0.0.0.0", 3773, { + interfaces: { tailscale0: [ipv4("100.101.102.103")], en0: [ipv4("192.168.1.42")] }, + privateNetworkOnly: true, + }), + ).toBe("http://192.168.1.42:3773"); }); -it("formats headless serve output with the connection string, token, pairing url, and qr code", () => { - const output = formatHeadlessServeOutput({ - connectionString: "http://192.168.1.42:3773", - token: "PAIRCODE", - pairingUrl: "http://192.168.1.42:3773/pair#token=PAIRCODE", +describe("acceptsPrivateNetworkConnection", () => { + const accepts = (localAddress: string | undefined, remoteAddress: string | undefined) => + acceptsPrivateNetworkConnection({ localAddress, remoteAddress }); + + it("serves loopback, LAN, and tailnet clients", () => { + expect(accepts("127.0.0.1", "127.0.0.1")).toBe(true); + expect(accepts("::ffff:192.168.1.20", "::ffff:192.168.1.31")).toBe(true); + expect(accepts("100.101.102.103", "100.90.1.2")).toBe(true); }); - expect(output).toContain("Connection string: http://192.168.1.42:3773"); - expect(output).toContain("Token: PAIRCODE"); - expect(output).toContain("Pairing URL: http://192.168.1.42:3773/pair#token=PAIRCODE"); - assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄")); + it("closes connections from or to a public address", () => { + // A cloud VM's public address is NATed to a private interface address. + expect(accepts("172.31.4.10", "203.0.113.7")).toBe(false); + expect(accepts("203.0.113.7", "192.168.1.31")).toBe(false); + expect(accepts("169.254.10.1", "169.254.10.2")).toBe(false); + expect(accepts(undefined, "192.168.1.31")).toBe(false); + }); }); diff --git a/apps/server/src/startupAccess.ts b/apps/server/src/startupAccess.ts index 4bc2578eeca73..cd2815931e307 100644 --- a/apps/server/src/startupAccess.ts +++ b/apps/server/src/startupAccess.ts @@ -1,8 +1,11 @@ +import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; +import { isPrivateNetworkHost, isSharedAddressSpaceHost } from "@t3tools/shared/hostClassification"; import { QrCode } from "@t3tools/shared/qrCode"; import * as Effect from "effect/Effect"; import { HttpServer } from "effect/http"; +import * as NetAddress from "effect/net/NetAddress"; import * as ServerConfig from "./config.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; @@ -35,6 +38,43 @@ export const isWildcardHost = (host: string | undefined): boolean => export const formatHostForUrl = (host: string): string => host.includes(":") && !host.startsWith("[") ? `[${host}]` : host; +/** + * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and + * macOS's `bridge100`+) have private addresses only this machine reaches. A + * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so + * it stays listed. + */ +export const VIRTUAL_INTERFACE = + /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/; + +/** + * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in + * plain or IPv4-mapped IPv6 form. + */ +export const isPrivateNetworkAddress = (address: string): boolean => { + const ipv4 = address.replace(/^::ffff:/i, ""); + return NodeNet.isIPv4(ipv4) && !ipv4.startsWith("169.254.") && isPrivateNetworkHost(ipv4); +}; + +/** + * A private-network listener binds every interface but serves only + * connections that stay on loopback, a LAN, or the tailnet. Both ends must be + * private: a cloud VM or a router port forward hands public clients to a + * private local address. + */ +export const acceptsPrivateNetworkConnection = (socket: { + readonly localAddress?: string | undefined; + readonly remoteAddress?: string | undefined; +}): boolean => + [socket.localAddress, socket.remoteAddress].every( + (address) => address !== undefined && isPrivateNetworkAddress(address), + ); + +export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string => + address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address) + ? "[::1]" + : "127.0.0.1"; + const normalizeHost = (host: string): string => host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; @@ -42,9 +82,10 @@ const isIpv4Family = (family: string | number): boolean => family === "IPv4" || const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6; -export const resolveHeadlessConnectionHost = ( +const resolveHeadlessConnectionHost = ( host: string | undefined, - interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(), + interfaces: NetworkInterfacesMap, + privateNetworkOnly: boolean, ): string => { if (!host) { return "localhost"; @@ -54,13 +95,26 @@ export const resolveHeadlessConnectionHost = ( return normalizeHost(host); } - const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []); - const externalIpv4 = interfaceEntries.find( - (entry) => !entry.internal && isIpv4Family(entry.family), + const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) => + privateNetworkOnly && VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? []), ); + const externalIpv4Entries = interfaceEntries.filter( + (entry) => + !entry.internal && + isIpv4Family(entry.family) && + (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)), + ); + // A tailnet or other CGNAT address reaches fewer devices than the LAN one. + const externalIpv4 = privateNetworkOnly + ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ?? + externalIpv4Entries[0]) + : externalIpv4Entries[0]; if (externalIpv4) { return externalIpv4.address; } + if (privateNetworkOnly) { + return "localhost"; + } const externalIpv6 = interfaceEntries.find( (entry) => !entry.internal && isIpv6Family(entry.family), @@ -71,13 +125,20 @@ export const resolveHeadlessConnectionHost = ( export const resolveHeadlessConnectionString = ( host: string | undefined, port: number, - interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(), + options: { + readonly interfaces?: NetworkInterfacesMap; + readonly privateNetworkOnly?: boolean | undefined; + } = {}, ): string => { - const connectionHost = resolveHeadlessConnectionHost(host, interfaces); + const connectionHost = resolveHeadlessConnectionHost( + host, + options.interfaces ?? NodeOS.networkInterfaces(), + options.privateNetworkOnly === true, + ); return `http://${formatHostForUrl(connectionHost)}:${port}`; }; -export const resolveListeningPort = (address: unknown, fallbackPort: number): number => { +const resolveListeningPort = (address: unknown, fallbackPort: number): number => { if ( typeof address === "object" && address !== null && @@ -137,6 +198,7 @@ export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessI const connectionString = resolveHeadlessConnectionString( serverConfig.host, resolveListeningPort(httpServer.address, serverConfig.port), + { privateNetworkOnly: serverConfig.privateNetworkOnly }, ); const issued = yield* serverAuth.issueStartupPairingCredential(); diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index e3870f8af0c41..c05d4aed4cfbf 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -5,16 +5,15 @@ import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import type * as Path from "effect/Path"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; -import * as Schema from "effect/Schema"; import { SCAN_CACHE_FILE_NAME } from "./usage/usageScanCache.ts"; import { TestClock } from "effect/testing"; import * as SqlClient from "effect/sql/SqlClient"; import { DEFAULT_SERVER_SETTINGS, - StorageCleanupReport, type WorktreeKeepWhen, type StorageCleanupSettings, } from "@t3tools/contracts"; @@ -33,16 +32,12 @@ import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAd import { ServerActivation } from "./serverActivation.ts"; import { describe, expect, it } from "@effect/vitest"; import { - EventId, ProjectId, - ProviderDriverKind, ProviderInstanceId, - ProviderSessionId, RunId, RuntimeRequestId, ThreadId, type OrchestrationV2DomainEvent, - type OrchestrationV2ProviderSession, type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -54,7 +49,6 @@ import { const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z"); const DAY_MS = 24 * 60 * 60 * 1_000; -const decodeCleanupReport = Schema.decodeSync(StorageCleanupReport); function at(offsetMs: number): DateTime.Utc { return DateTime.makeUnsafe(NOW_MS + offsetMs); @@ -124,13 +118,6 @@ describe("V2 storage cleanup eligibility", () => { }, ); - it.each(["idle", "completed", "interrupted", "failed", "cancelled", "rolled_back"] as const)( - "allows cleanup once its thread is %s", - (status) => { - expect(storageCleanupThreadIdle(candidateWithStatus(status), NOW_MS)).toBe(true); - }, - ); - it.each(["completed", "interrupted", "cancelled", "rolled_back"] as const)( "retains %s while background work is pending", (status) => { @@ -236,6 +223,16 @@ describe("merged pull request cleanup", () => { }); }); +const allocatedBytes = (fs: FileSystem.FileSystem, file: string) => + fs.stat(file).pipe( + Effect.map((stat) => + Option.getOrElse( + Option.map(stat.blocks, (blocks) => Number(blocks) * 512), + () => Number(stat.size), + ), + ), + ); + const cleanupFixture = ( storageCleanup: StorageCleanupSettings = { ...DEFAULT_SERVER_SETTINGS.storageCleanup, @@ -247,7 +244,7 @@ const cleanupFixture = ( const fs = yield* FileSystem.FileSystem; const config = yield* ServerConfig.ServerConfig; const git = yield* GitVcsDriver.GitVcsDriver; - const repo = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" }); + const repo = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" })); const command = (cwd: string, args: string[]) => git.execute({ operation: "cleanup-test", cwd, args }); yield* command(repo, ["init", "-b", "main"]); @@ -265,6 +262,7 @@ const cleanupFixture = ( storageCleanup, }; let threads = [shell({ branch: "feature", worktreePath: worktree })]; + let deletedThreads: OrchestrationV2ThreadShell[] = []; let storedWorktreePaths: string[] = [worktree]; let projectRoots = [repo]; let editBeforeRemoval = false; @@ -279,7 +277,12 @@ const cleanupFixture = ( ...git, execute: (input) => Effect.gen(function* () { - if (editBeforeRemoval && input.args.includes("remove")) + // Before Git's own clean check: inside `git worktree remove`, or on + // Windows the same status check the removal makes before deleting. + if ( + editBeforeRemoval && + (input.args.includes("remove") || input.args.includes("--porcelain")) + ) yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n"); return yield* git.execute(input); }), @@ -306,14 +309,26 @@ const cleanupFixture = ( getShellSnapshot: (input?: { location?: string }) => Effect.sync(() => { snapshotReads++; - return { threads: input?.location === "archive" ? [] : threads }; + const visible = threads.filter((thread) => thread.deletedAt === null); + return { + threads: + input?.location === "archive" + ? [] + : visible.filter((thread) => thread.archivedAt === null), + archivedThreads: + input?.location === "active" + ? [] + : visible.filter((thread) => thread.archivedAt !== null), + }; }), - getThreadWorktreePaths: () => + getThreadWorktreePaths: (input?: { includeArchived?: boolean }) => Effect.sync(() => threads.flatMap((thread) => - thread.worktreePath === null - ? [] - : [{ threadId: thread.id, worktreePath: thread.worktreePath }], + thread.deletedAt === null && + (input?.includeArchived === true || thread.archivedAt === null) && + thread.worktreePath !== null + ? [{ threadId: thread.id, worktreePath: thread.worktreePath }] + : [], ), ), getThreadShell: (threadId: ThreadId) => @@ -344,12 +359,17 @@ const cleanupFixture = ( }), }, ] - : strings.join("").includes('AS "worktreePath"') - ? [ - ...threads.flatMap((thread) => thread.worktreePath ?? []), - ...storedWorktreePaths, - ].map((worktreePath) => ({ worktreePath })) - : [], + : strings.join("").includes("deleted_at IS NOT NULL") + ? deletedThreads.map((thread) => ({ + payload_json: JSON.stringify(thread), + workspaceRoot: repo, + })) + : strings.join("").includes('AS "worktreePath"') + ? [ + ...threads.flatMap((thread) => thread.worktreePath ?? []), + ...storedWorktreePaths, + ].map((worktreePath) => ({ worktreePath })) + : [], )) as unknown as SqlClient.SqlClient), Effect.provideService(GitManager.GitManager, { invalidateStatus: () => Effect.void, @@ -401,6 +421,9 @@ const cleanupFixture = ( setThreads: (next: typeof threads) => { threads = next; }, + setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => { + deletedThreads = next; + }, setStoredWorktreePaths: (paths: string[]) => { storedWorktreePaths = paths; }, @@ -443,27 +466,6 @@ const pausedMeasurementFixture = (storageCleanup?: StorageCleanupSettings) => measuredPath = yield* fs.realPath(fixture.worktree); return { ...fixture, measuring, resume }; }); -const sessionUpdated = ( - index: number, - status: OrchestrationV2ProviderSession["status"], -): OrchestrationV2DomainEvent => ({ - id: EventId.make(`event-${index}`), - type: "provider-session.updated", - threadId: ThreadId.make("thread-1"), - occurredAt: at(0), - payload: { - id: ProviderSessionId.make(`session-${index}`), - driver: ProviderDriverKind.make("codex"), - providerInstanceId: ProviderInstanceId.make("codex"), - status, - cwd: "/elsewhere", - model: null, - capabilities: CodexProviderCapabilitiesV2, - createdAt: at(0), - updatedAt: at(0), - lastError: null, - }, -}); const cleanupTestLayer = GitVcsDriver.layer.pipe( Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "storage-cleanup-" })), Layer.provideMerge(NodeServices.layer), @@ -480,6 +482,188 @@ const runCleanupTest = ( >, ) => effect.pipe(Effect.provide(cleanupTestLayer), Effect.scoped); +const submoduleCleanupFixture = () => + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const { command, repo, worktree } = fixture; + const submodule = `${worktree}/module`; + const child = `${submodule}/child`; + for (const [cwd, name] of [ + [worktree, "module"], + [submodule, "child"], + ] as const) { + yield* command(cwd, ["-c", "protocol.file.allow=always", "submodule", "add", repo, name]); + yield* command(`${cwd}/${name}`, ["config", "user.name", "Cleanup test"]); + yield* command(`${cwd}/${name}`, ["config", "user.email", "cleanup@example.test"]); + } + const recordSubmodules = () => + Effect.gen(function* () { + yield* command(submodule, ["commit", "-am", "record child"]); + yield* command(submodule, ["push", "origin", "HEAD:submodule"]); + yield* command(worktree, ["commit", "-am", "record module"]); + }); + yield* recordSubmodules(); + return { ...fixture, submodule, child, recordSubmodules }; + }); + +it.live("removes clean submodules recursively, including deinitialized repositories", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, repo, worktree, submodule, command, recordSubmodules } = + yield* submoduleCleanupFixture(); + yield* command(submodule, [ + "-c", + "protocol.file.allow=always", + "submodule", + "add", + repo, + "stored", + ]); + yield* recordSubmodules(); + yield* command(submodule, ["submodule", "deinit", "stored"]); + const admin = (yield* command(worktree, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); + const report = yield* service.runNow; + expect(report.entries.find((entry) => entry.path === worktree)).toMatchObject({ + outcome: "removed", + }); + expect(report.counts).toEqual({ removed: 1, kept: 0, failed: 0 }); + expect(yield* fs.exists(worktree)).toBe(false); + expect(yield* fs.exists(admin)).toBe(false); + }), + ), +); + +it.live("keeps nested submodule files protected by the current keep rule", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, submodule, child, command, setPolicy } = + yield* submoduleCleanupFixture(); + setPolicy("tracked-changes"); + yield* fs.writeFileString(`${child}/tracked.txt`, "local edit\n"); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept" }); + expect(yield* fs.readFileString(`${child}/tracked.txt`)).toBe("local edit\n"); + yield* fs.writeFileString(`${child}/tracked.txt`, "original\n"); + setPolicy("any-local-files"); + yield* fs.writeFileString(`${child}/.env`, "local secret\n"); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept" }); + expect(yield* fs.readFileString(`${child}/.env`)).toBe("local secret\n"); + + yield* fs.remove(`${child}/.env`); + yield* command(submodule, ["submodule", "deinit", "child"]); + yield* fs.writeFileString(`${child}/.env`, "secret after deinit\n"); + const report = yield* service.runNow; + expect({ + outcome: report.entries.find((entry) => entry.path === worktree)?.outcome, + contents: (yield* fs.exists(`${child}/.env`)) + ? yield* fs.readFileString(`${child}/.env`) + : null, + }).toEqual({ outcome: "kept", contents: "secret after deinit\n" }); + + yield* fs.remove(`${child}/.env`); + setPolicy("uncommitted-changes"); + yield* fs.writeFileString(`${child}/notes.txt`, "notes after deinit\n"); + const untrackedReport = yield* service.runNow; + expect({ + outcome: untrackedReport.entries.find((entry) => entry.path === worktree)?.outcome, + contents: (yield* fs.exists(`${child}/notes.txt`)) + ? yield* fs.readFileString(`${child}/notes.txt`) + : null, + }).toEqual({ outcome: "kept", contents: "notes after deinit\n" }); + }), + ), +); + +it.live("keeps unpushed submodule history after checkout and deinitialization", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, submodule, child, command, recordSubmodules } = + yield* submoduleCleanupFixture(); + yield* command(child, ["checkout", "-b", "local-only"]); + yield* fs.writeFileString(`${child}/tracked.txt`, "unpublished work\n"); + yield* command(child, ["commit", "-am", "local work"]); + const local = (yield* command(child, ["rev-parse", "HEAD"])).stdout.trim(); + yield* recordSubmodules(); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); + expect(yield* fs.readFileString(`${child}/tracked.txt`)).toBe("unpublished work\n"); + + yield* command(child, ["checkout", "main"]); + yield* recordSubmodules(); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); + const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); + yield* command(submodule, ["submodule", "deinit", "child"]); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); + expect( + (yield* command(worktree, [ + "--git-dir", + childGit, + "rev-parse", + "refs/heads/local-only", + ])).stdout.trim(), + ).toBe(local); + expect( + (yield* command(worktree, ["--git-dir", childGit, "show", "local-only:tracked.txt"])) + .stdout, + ).toBe("unpublished work\n"); + yield* command(worktree, ["--git-dir", childGit, "branch", "-D", "local-only"]); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("remote-tracking") }); + expect( + (yield* command(worktree, ["--git-dir", childGit, "show", `${local}:tracked.txt`])).stdout, + ).toBe("unpublished work\n"); + }), + ), +); + +it.live("keeps submodules when stored repository metadata is malformed", () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, worktree, submodule, child, command } = yield* submoduleCleanupFixture(); + const childGit = (yield* command(child, ["rev-parse", "--absolute-git-dir"])).stdout.trim(); + yield* command(submodule, ["submodule", "deinit", "child"]); + yield* fs.writeFileString(`${childGit}/HEAD`, "not a ref\n"); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "kept", reason: expect.stringContaining("inspected") }); + expect(yield* fs.exists(worktree)).toBe(true); + expect(yield* fs.readFileString(`${childGit}/HEAD`)).toBe("not a ref\n"); + }), + ), +); + +it.live("preserves late tracked edits when submodules were never initialized", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + const { service, fs, worktree, command } = fixture; + const head = (yield* command(worktree, ["rev-parse", "HEAD"])).stdout.trim(); + yield* fs.writeFileString( + `${worktree}/.gitmodules`, + '[submodule "module"]\n\tpath = module\n\turl = /unused\n', + ); + yield* command(worktree, ["add", ".gitmodules"]); + yield* command(worktree, ["update-index", "--add", "--cacheinfo", `160000,${head},module`]); + yield* command(worktree, ["commit", "-m", "record uninitialized module"]); + yield* fs.makeDirectory(`${worktree}/module`); + fixture.editBeforeRemoval(); + expect( + (yield* service.runNow).entries.find((entry) => entry.path === worktree), + ).toMatchObject({ outcome: "failed" }); + expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("late edit\n"); + }), + ), +); + describe("subagent worktree ownership", () => { it.effect.each([ "idle", @@ -566,7 +750,6 @@ describe("subagent worktree ownership", () => { id: ThreadId.make("grandchild"), lineage: { ...child.lineage, parentThreadId: child.id }, }; - // The worktree owner can follow its children in the snapshot. fixture.setThreads( scenario === "grandchild" ? [grandchild, child, root] @@ -673,6 +856,97 @@ describe("subagent worktree ownership", () => { ); }); +describe("deleted thread worktrees", () => { + const parent = (worktreePath: string) => + shell({ branch: "feature", worktreePath, deletedAt: at(-DAY_MS) }); + // Deleting the parent leaves its native subagent thread in the projection. + const subagent = ( + owner: OrchestrationV2ThreadShell, + overrides: Partial = {}, + ) => + shell({ + id: ThreadId.make("child"), + title: "Subagent", + branch: "feature", + worktreePath: owner.worktreePath, + status: "completed", + createdBy: "agent", + creationSource: "provider", + lineage: { + rootThreadId: owner.id, + parentThreadId: owner.id, + relationshipToParent: "subagent", + }, + ...overrides, + }); + + it.effect.each(["no subagents", "native subagent"] as const)( + "removes a deleted thread's worktree with %s", + (scenario) => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeAfterDays: null, + worktreeOnDelete: true, + }); + const owner = parent(fixture.worktree); + fixture.setDeletedThreads([owner]); + fixture.setThreads(scenario === "native subagent" ? [subagent(owner)] : []); + const report = yield* fixture.service.runNow; + expect(report.entries[0]).toMatchObject({ + threadId: owner.id, + outcome: "removed", + reason: "Thread was deleted", + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + ); + + it.effect("applies the remaining subagent's rules when deletion cleanup is off", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeAfterDays: 8, + worktreeOnDelete: false, + }); + const owner = parent(fixture.worktree); + const child = subagent(owner); + fixture.setDeletedThreads([owner]); + fixture.setThreads([child]); + const report = yield* fixture.service.runNow; + expect(report.entries[0]).toMatchObject({ + threadId: child.id, + outcome: "removed", + reason: "Inactive for 30 days", + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + ); + + it.effect("waits out the settle grace of a subagent that just settled", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeAfterDays: null, + worktreeOnDelete: true, + }); + const owner = parent(fixture.worktree); + fixture.setDeletedThreads([owner]); + fixture.setThreads([subagent(owner, { settledAt: at(0), updatedAt: at(0) })]); + const report = yield* fixture.service.runNow; + expect(report.entries[0]).toMatchObject({ + threadId: owner.id, + outcome: "kept", + reason: "Settled moments ago", + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + ); +}); + describe("orphan worktree reports", () => { it.live("keeps orphan results visible when thread results fill the report", () => runCleanupTest( @@ -740,27 +1014,6 @@ describe("orphan worktree reports", () => { ), ); - it.live("waits an hour before reporting a folder without a thread row", () => - runCleanupTest( - Effect.gen(function* () { - const fixture = yield* cleanupFixture(); - fixture.setThreads([]); - const folder = `${fixture.config.worktreesDir}/review-guide-123/checkout`; - yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "review", folder]); - expect((yield* fixture.service.runNow).entries).toEqual([]); - yield* fixture.fs.utimes(folder, 1, 1); - expect((yield* fixture.service.runNow).entries).toEqual([ - expect.objectContaining({ - path: folder, - outcome: "kept", - reason: "No thread uses this worktree", - }), - ]); - expect(yield* fixture.fs.exists(`${folder}/tracked.txt`)).toBe(true); - }), - ), - ); - it.live("continues reporting when a project root cannot be probed", () => runCleanupTest( Effect.gen(function* () { @@ -779,73 +1032,6 @@ describe("orphan worktree reports", () => { ), ); - it.effect.each(["walk-timeout", "sweep-budget"] as const)( - "caches walk timeouts and retries budget-cut orphan sizes (%s)", - (limit) => - runCleanupTest( - Effect.gen(function* () { - yield* TestClock.setTime(NOW_MS); - const fs = yield* FileSystem.FileSystem; - const measuring = yield* Deferred.make(); - let orphan = ""; - let walks = 0; - const fixture = yield* cleanupFixture().pipe( - Effect.provideService(FileSystem.FileSystem, { - ...fs, - readDirectory: (directory, options) => - Effect.gen(function* () { - if (directory.endsWith("/repository") && walks === 0) - yield* TestClock.adjust("1 second"); - if (directory === orphan) { - walks++; - if (limit === "walk-timeout" || walks === 1) { - yield* Deferred.succeed(measuring, undefined); - return yield* Effect.never; - } - } - return (yield* fs.readDirectory(directory, options)).sort(); - }), - }), - ); - fixture.setThreads([]); - orphan = `${fixture.config.worktreesDir}/repository/orphan`; - yield* fs.makeDirectory(orphan, { recursive: true }); - yield* fs.writeFileString(`${orphan}/file`, "x"); - yield* fs.utimes(orphan, 1, 1); - const later = `${fixture.config.worktreesDir}/repository/z-later`; - yield* fs.makeDirectory(later); - yield* fs.utimes(later, 1, 1); - if (limit === "sweep-budget") { - const first = `${fixture.config.worktreesDir}/repository/a-first`; - yield* fs.makeDirectory(first); - yield* fs.utimes(first, 1, 1); - } - const orphanEntry = (report: StorageCleanupReport) => - report.entries.find((entry) => entry.path === orphan); - const sweep = yield* fixture.service.runNow.pipe(Effect.forkChild); - yield* Deferred.await(measuring); - yield* TestClock.adjust(limit === "walk-timeout" ? "30 seconds" : "29 seconds"); - const firstReport = yield* Fiber.join(sweep); - expect(orphanEntry(firstReport)?.bytes).toBeNull(); - expect(firstReport.entries.find((entry) => entry.path === later)?.bytes).toBeNull(); - const nextReport = yield* fixture.service.runNow; - expect(orphanEntry(nextReport)?.bytes).toBe(limit === "walk-timeout" ? null : 1); - expect(nextReport.entries.find((entry) => entry.path === later)?.bytes).toBe(0); - yield* fs.writeFileString(`${orphan}/file`, "changed"); - expect(orphanEntry(yield* fixture.service.runNow)?.bytes).toBe( - limit === "walk-timeout" ? null : 1, - ); - expect(walks).toBe(limit === "walk-timeout" ? 1 : 2); - if (limit === "walk-timeout") return; - fixture.setStoredWorktreePaths([orphan]); - expect(orphanEntry(yield* fixture.service.runNow)).toBeUndefined(); - fixture.setStoredWorktreePaths([]); - expect(orphanEntry(yield* fixture.service.runNow)?.bytes).toBe(7); - expect(walks).toBe(3); - }), - ), - ); - it.live.each(["nested", "direct"] as const)( "reports a linked orphan's size without removing its files (%s)", (location) => @@ -856,7 +1042,7 @@ describe("orphan worktree reports", () => { const orphan = `${fixture.config.worktreesDir}/${location === "nested" ? "repository/" : ""}orphan`; yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); const sizes = yield* Effect.forEach(yield* fixture.fs.readDirectory(orphan), (name) => - fixture.fs.stat(`${orphan}/${name}`).pipe(Effect.map((stat) => Number(stat.size))), + allocatedBytes(fixture.fs, `${orphan}/${name}`), ); const outside = yield* fixture.fs.makeTempDirectoryScoped(); yield* fixture.fs.writeFileString(`${outside}/external`, "outside data"); @@ -870,6 +1056,7 @@ describe("orphan worktree reports", () => { outcome: "kept", reason: "No thread uses this worktree", path: orphan, + projectPath: null, threadId: null, threadTitle: null, bytes: sizes.reduce((sum, size) => sum + size, 0), @@ -965,96 +1152,6 @@ describe("orphan worktree reports", () => { ), ); - it.live.each(["direct", "symlink"] as const)( - "reports an orphan under a managed root inside a project (%s)", - (location) => - runCleanupTest( - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const walked: string[] = []; - const fixture = yield* cleanupFixture().pipe( - Effect.provideService(FileSystem.FileSystem, { - ...fs, - readDirectory: (directory, options) => { - walked.push(directory); - return fs.readDirectory(directory, options); - }, - }), - ); - fixture.setThreads([]); - const root = `${fixture.repo}/.worktrees`; - const orphan = `${root}/repository/orphan`; - const source = `${fixture.repo}/src`; - yield* fs.makeDirectory(`${source}/nested/deep`, { recursive: true }); - yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); - if (location === "symlink") { - const alias = `${fixture.config.worktreesDir}/project-alias`; - yield* fs.symlink(fixture.repo, alias); - fixture.setProjectRoots([alias]); - } - fixture.setSettings({ worktreesDirectory: root }); - yield* fs.utimes(orphan, 1, 1); - const report = yield* fixture.service.runNow; - expect(report.entries).toEqual([ - expect.objectContaining({ - path: orphan, - outcome: "kept", - reason: "No thread uses this worktree", - }), - ]); - expect(walked.some((directory) => directory.startsWith(source))).toBe(false); - expect(yield* fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n"); - }), - ), - ); - - it.live("reports an orphan containing a removed project checkout", () => - runCleanupTest( - Effect.gen(function* () { - const fixture = yield* cleanupFixture(); - fixture.setThreads([]); - const orphan = `${fixture.config.worktreesDir}/repository/orphan`; - const removed = `${orphan}/removed-checkout`; - yield* fixture.command(fixture.repo, ["worktree", "add", "-b", "orphan", orphan]); - yield* fixture.fs.makeDirectory(removed); - yield* fixture.fs.remove(removed, { recursive: true }); - fixture.setProjectRoots([fixture.repo, removed]); - yield* fixture.fs.utimes(orphan, 1, 1); - const report = yield* fixture.service.runNow; - expect(report.entries).toEqual([ - expect.objectContaining({ - path: orphan, - outcome: "kept", - reason: "No thread uses this worktree", - }), - ]); - expect(yield* fixture.fs.readFileString(`${orphan}/tracked.txt`)).toBe("original\n"); - }), - ), - ); - - it.live("skips project workspace internals while reporting a real orphan sibling", () => - runCleanupTest( - Effect.gen(function* () { - const fixture = yield* cleanupFixture(); - fixture.setThreads([]); - const project = `${fixture.config.worktreesDir}/project-checkout`; - const orphan = `${fixture.config.worktreesDir}/repository/orphan`; - yield* fixture.fs.makeDirectory(`${project}/src/nested`, { recursive: true }); - yield* fixture.fs.makeDirectory(orphan, { recursive: true }); - yield* fixture.fs.writeFileString(`${orphan}/file`, "x"); - fixture.setProjectRoots([fixture.repo, project]); - yield* fixture.fs.utimes(orphan, 1, 1); - const report = yield* fixture.service.runNow; - expect(report.entries).toEqual([ - expect.objectContaining({ path: orphan, outcome: "kept", bytes: 1 }), - ]); - expect(yield* fixture.fs.exists(`${project}/src/nested`)).toBe(true); - expect(yield* fixture.fs.exists(orphan)).toBe(true); - }), - ), - ); - it.live("skips symbolic links at both directory levels and disabled cleanup", () => runCleanupTest( Effect.gen(function* () { @@ -1091,7 +1188,7 @@ describe("orphan worktree reports", () => { expect.objectContaining({ path: folder, outcome: "kept", - bytes: 13, + bytes: yield* allocatedBytes(fixture.fs, `${folder}/payload`), reason: "No thread uses this folder, and it isn't a git worktree", }), ]); @@ -1119,7 +1216,11 @@ describe("orphan worktree reports", () => { Effect.ensuring(fixture.fs.chmod(blocked, 0o700).pipe(Effect.orDie)), ); expect(report.entries).toEqual([ - expect.objectContaining({ path: orphan, outcome: "kept", bytes: 1 }), + expect.objectContaining({ + path: orphan, + outcome: "kept", + bytes: yield* allocatedBytes(fixture.fs, `${orphan}/file`), + }), ]); expect(yield* fixture.fs.exists(orphan)).toBe(true); }), @@ -1152,30 +1253,44 @@ describe("orphan worktree reports", () => { }), ), ); +}); - it.live("caps orphan entries while preserving kept totals", () => +describe("storage cleanup reports and local file policies", () => { + it.effect("automatically removes an eligible archived thread checkout", () => runCleanupTest( Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); const fixture = yield* cleanupFixture(); - fixture.setThreads([]); - for (let i = 0; i < 205; i++) { - const orphan = `${fixture.config.worktreesDir}/repository/orphan-${i}`; - yield* fixture.fs.makeDirectory(orphan, { recursive: true }); - yield* fixture.fs.writeFileString(`${orphan}/file`, "x"); - yield* fixture.fs.utimes(orphan, 1, 1); - } - const report = yield* fixture.service.runNow; - expect(report.entries).toHaveLength(200); - expect(report.entries.every((entry) => entry.bytes === 1)).toBe(true); - expect(report.omittedCount).toBe(5); - expect(report.counts).toEqual({ removed: 0, kept: 205, failed: 0 }); - expect(report.bytesFreed).toBe(0); + fixture.setThreads([ + shell({ + branch: "feature", + worktreePath: fixture.worktree, + archivedAt: at(-DAY_MS), + }), + ]); + yield* fixture.activate(Stream.empty); + const [report] = yield* fixture.service.reports.pipe( + Stream.filter((report) => report !== null), + Stream.take(1), + Stream.runCollect, + ); + yield* fixture.service.drain; + expect(report).toMatchObject({ + trigger: "automatic", + counts: { removed: 1, kept: 0, failed: 0 }, + entries: [ + { + threadId: "thread-1", + path: fixture.worktree, + outcome: "removed", + reason: "Inactive for 30 days", + }, + ], + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(false); }), ), ); -}); - -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) => @@ -1202,26 +1317,114 @@ describe("storage cleanup reports and local file policies", () => { ), ); - it.live("measures nested regular files without following symlinks", () => + it.live("reports allocated bytes of single-link files without following symlinks", () => runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); setPolicy("tracked-changes"); const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => - fs.stat(`${worktree}/${name}`).pipe(Effect.map((stat) => Number(stat.size))), + allocatedBytes(fs, `${worktree}/${name}`), ); const outside = yield* fs.makeTempDirectoryScoped(); yield* fs.writeFileString(`${outside}/external`, "must not count"); + yield* fs.writeFileString(`${outside}/store-file`, "shared ".repeat(10_000)); yield* fs.makeDirectory(`${worktree}/node_modules/nested`, { recursive: true }); yield* fs.writeFileString(`${worktree}/node_modules/nested/file`, "count me"); + sizes.push(yield* allocatedBytes(fs, `${worktree}/node_modules/nested/file`)); + yield* fs.link(`${outside}/store-file`, `${worktree}/node_modules/hardlinked`); yield* fs.symlink(outside, `${worktree}/node_modules/directory-link`); yield* fs.symlink(`${outside}/external`, `${worktree}/node_modules/file-link`); yield* fs.symlink(`${outside}/missing`, `${worktree}/node_modules/dangling-link`); const report = yield* service.runNow; - const bytes = sizes.reduce((sum, size) => sum + size, 8); + const bytes = sizes.reduce((sum, size) => sum + size, 0); expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes, files: null }); expect(report.bytesFreed).toBe(bytes); expect(yield* fs.readFileString(`${outside}/external`)).toBe("must not count"); + expect(yield* fs.readFileString(`${outside}/store-file`)).toBe("shared ".repeat(10_000)); + expect(yield* fs.exists(worktree)).toBe(false); + }), + ), + ); + it.live.each(["same-device", "other-device", "no-manifest"] as const)( + "counts the pnpm virtual store only when its store forces copies (%s)", + (store) => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const storeDir = yield* fs.makeTempDirectoryScoped({ prefix: "pnpm-store-" }); + const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + stat: (target) => + fs + .stat(target) + .pipe( + Effect.map((info) => + store === "other-device" && target === storeDir + ? { ...info, dev: info.dev + 1n } + : info, + ), + ), + }), + ); + setPolicy("tracked-changes"); + const nodeModules = `${worktree}/node_modules`; + yield* fs.makeDirectory(`${nodeModules}/.pnpm/pkg@1.0.0`, { recursive: true }); + yield* fs.makeDirectory(`${nodeModules}/.vite`); + yield* fs.writeFileString( + `${nodeModules}/.pnpm/pkg@1.0.0/index.js`, + "clone ".repeat(10_000), + ); + yield* fs.writeFileString(`${nodeModules}/.vite/deps.js`, "cache"); + if (store !== "no-manifest") + yield* fs.writeFileString( + `${nodeModules}/.modules.yaml`, + JSON.stringify({ storeDir, virtualStoreDir: ".pnpm" }), + ); + const counted = [ + ...(yield* fs.readDirectory(worktree)).flatMap((name) => + name === "node_modules" ? [] : [`${worktree}/${name}`], + ), + `${nodeModules}/.vite/deps.js`, + ...(store === "no-manifest" ? [] : [`${nodeModules}/.modules.yaml`]), + ...(store === "same-device" ? [] : [`${nodeModules}/.pnpm/pkg@1.0.0/index.js`]), + ]; + const bytes = (yield* Effect.forEach(counted, (file) => allocatedBytes(fs, file))).reduce( + (sum, size) => sum + size, + 0, + ); + const report = yield* service.runNow; + expect(report.entries[0]).toMatchObject({ outcome: "removed", bytes }); + }), + ), + ); + // An agent can write this manifest. Statting its store sent the Windows + // user's NTLM credentials to attacker.test during a background sweep. + it.live.each([ + { storeDir: "\\\\attacker.test\\s" }, + { storeDir: "/local/store", virtualStoreDir: "//attacker.test/s" }, + ])("never stats a network pnpm store %o", (manifest) => + runCleanupTest( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const statted: Array = []; + const { service, worktree, setPolicy } = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + stat: (target) => { + statted.push(target); + return fs.stat(target); + }, + }), + ); + setPolicy("tracked-changes"); + yield* fs.makeDirectory(`${worktree}/node_modules`); + yield* fs.writeFileString( + `${worktree}/node_modules/.modules.yaml`, + JSON.stringify(manifest), + ); + expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); + expect(statted.filter((target) => target.includes("attacker.test"))).toEqual([]); }), ), ); @@ -1264,6 +1467,18 @@ describe("storage cleanup reports and local file policies", () => { shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }), ], ], + [ + "an archived thread starts using it", + (worktree: string) => [ + shell({ branch: "feature", worktreePath: worktree }), + shell({ + id: ThreadId.make("thread-2"), + branch: "feature", + worktreePath: worktree, + archivedAt: at(-DAY_MS), + }), + ], + ], ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) => runCleanupTest( Effect.gen(function* () { @@ -1287,41 +1502,6 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live("reads the thread snapshot once per sweep, not per worktree", () => - runCleanupTest( - Effect.gen(function* () { - const { service, snapshotReads } = yield* cleanupFixture(); - expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); - expect(snapshotReads()).toBe(1); - }), - ), - ); - it.live.each([ - ["running", "ready", 1], - ["stopped", "error", 2], - ] as const)( - "session updates to %s or %s during a sweep make %i sweep(s) in total", - ([first, second, sweeps]) => - runCleanupTest( - Effect.gen(function* () { - const fixture = yield* pausedMeasurementFixture(); - const handled = yield* Deferred.make(); - yield* fixture.activate( - Stream.fromEffect(Deferred.await(fixture.measuring)).pipe( - Stream.flatMap(() => Stream.range(0, 19)), - Stream.map((index) => sessionUpdated(index, index % 2 === 0 ? first : second)), - Stream.concat( - Stream.fromEffect(Deferred.succeed(handled, undefined)).pipe(Stream.drain), - ), - ), - ); - yield* Deferred.await(handled); - yield* Deferred.succeed(fixture.resume, undefined); - yield* fixture.service.drain; - expect(fixture.snapshotReads()).toBe(sweeps); - }), - ), - ); it.live("does not measure a worktree kept for an open provider session", () => runCleanupTest( Effect.gen(function* () { @@ -1356,7 +1536,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("compares the checked-out branch without a full status", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, worktree, command, setThreads, fullStatusCalls } = + const { service, fs, repo, worktree, command, setThreads, fullStatusCalls } = yield* cleanupFixture(); const changed = { outcome: "kept", reason: "Repository or branch changed" }; yield* command(worktree, ["checkout", "--detach"]); @@ -1374,8 +1554,15 @@ describe("storage cleanup reports and local file policies", () => { const index = (yield* command(worktree, ["rev-parse", "--git-path", "index"])).stdout; yield* fs.writeFileString(`${index.trim()}.lock`, ""); const locked = (yield* service.runNow).entries[0]; - expect(locked).toMatchObject({ outcome: "failed" }); + expect(locked).toMatchObject({ + outcome: "failed", + projectPath: repo, + path: worktree, + threadId: "thread-1", + threadTitle: "Thread", + }); expect(locked?.reason).toContain("Git index is locked"); + expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("original\n"); yield* fs.remove(`${index.trim()}.lock`); const gitFile = yield* fs.readFileString(`${worktree}/.git`); yield* fs.writeFileString(`${worktree}/.git`, "gitdir: /missing-git-directory\n"); @@ -1386,27 +1573,6 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it("decodes reports from servers without size fields", () => { - const report = decodeCleanupReport({ - trigger: "manual", - startedAt: "2026-06-10T12:00:00.000Z", - finishedAt: "2026-06-10T12:00:01.000Z", - entries: [ - { - kind: "worktree", - outcome: "removed", - reason: "Removed", - path: null, - threadId: null, - threadTitle: null, - }, - ], - counts: { removed: 1, kept: 0, failed: 0 }, - omittedCount: 0, - }); - expect(report.bytesFreed).toBe(0); - expect(report.entries[0]).toMatchObject({ bytes: null, files: null }); - }); it.live.each([ ["any-local-files", ".env", "kept"], ["uncommitted-changes", ".env", "removed"], @@ -1425,7 +1591,7 @@ describe("storage cleanup reports and local file policies", () => { expect(yield* service.latestReport).toBeNull(); yield* fs.writeFileString(`${worktree}/${file}`, "local data\n"); const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => - fs.stat(`${worktree}/${name}`).pipe(Effect.map((stat) => Number(stat.size))), + allocatedBytes(fs, `${worktree}/${name}`), ); const bytes = sizes.reduce((sum, size) => sum + size, 0); const report = yield* service.runNow; @@ -1451,6 +1617,83 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + 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({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeUnchanged: true, + }); + const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); + yield* command(remote, ["init", "--bare", "-b", "trunk"]); + yield* command(repo, ["remote", "add", "origin", remote]); + yield* command(repo, ["push", "origin", "main:trunk"]); + yield* command(repo, ["update-ref", "-d", "refs/remotes/origin/trunk"]); + expect((yield* command(repo, ["for-each-ref", "refs/remotes/origin"])).stdout).toBe(""); + + const report = yield* service.runNow; + expect(report.entries[0]).toMatchObject({ + outcome: "removed", + reason: "No commits beyond the default branch", + }); + expect(yield* fs.exists(worktree)).toBe(false); + }), + ), + ); + it.live( + "keeps worktree commits present on nondefault main but absent from advertised trunk", + () => + runCleanupTest( + Effect.gen(function* () { + const { service, fs, repo, worktree, command } = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeUnchanged: true, + }); + const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); + yield* command(remote, ["init", "--bare", "-b", "trunk"]); + yield* command(repo, ["remote", "add", "origin", remote]); + yield* command(repo, ["push", "origin", "main:trunk"]); + yield* fs.writeFileString(`${worktree}/tracked.txt`, "unmerged work\n"); + yield* command(worktree, ["commit", "-am", "unmerged work"]); + yield* command(repo, ["push", "origin", "feature:main"]); + expect( + (yield* command(repo, ["symbolic-ref", "refs/remotes/origin/HEAD"]).pipe(Effect.exit)) + ._tag, + ).toBe("Failure"); + + const report = yield* service.runNow; + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Has commits beyond the default branch", + }); + expect(yield* fs.readFileString(`${worktree}/tracked.txt`)).toBe("unmerged work\n"); + }), + ), + ); + 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({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeUnchanged: true, + }); + const remote = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-remote-" }); + yield* command(remote, ["init", "--bare", "-b", "trunk"]); + yield* command(repo, ["remote", "add", "origin", remote]); + // The remote HEAD names an unborn trunk; main exists but is not its default. + yield* command(repo, ["push", "origin", "main"]); + + const report = yield* service.runNow; + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Default branch is unavailable", + }); + expect(yield* fs.exists(worktree)).toBe(true); + }), + ), + ); it.live("preserves tracked edits written after the final status check", () => runCleanupTest( Effect.gen(function* () { @@ -1469,21 +1712,6 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live("streams the current report and subsequent runs", () => - runCleanupTest( - Effect.gen(function* () { - const { service } = yield* cleanupFixture(); - const reports = yield* service.reports.pipe( - Stream.take(2), - Stream.tap((report) => (report === null ? service.runNow : Effect.void)), - Stream.runCollect, - ); - expect(reports[0]).toBeNull(); - expect(reports[1]).toEqual(yield* service.latestReport); - expect(reports[1]?.counts).toEqual({ removed: 1, kept: 0, failed: 0 }); - }), - ), - ); it.live("caps entries while preserving totals and prioritizing removals", () => runCleanupTest( Effect.gen(function* () { @@ -1528,29 +1756,6 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); - it.live( - "reports shared and running worktrees but omits disabled rules and missing directories", - () => - runCleanupTest( - Effect.gen(function* () { - const fixture = yield* cleanupFixture(); - const { service, fs, worktree, setThreads } = fixture; - setThreads([shell({ branch: "feature", worktreePath: worktree, status: "running" })]); - expect((yield* service.runNow).entries[0]?.reason).toContain("Thread is running"); - setThreads([ - shell({ branch: "feature", worktreePath: worktree }), - shell({ id: ThreadId.make("thread-2"), branch: "feature", worktreePath: worktree }), - ]); - expect((yield* service.runNow).entries[0]?.reason).toBe("Shared by 2 threads"); - fixture.disable(); - expect((yield* service.runNow).entries).toEqual([]); - yield* fs.remove(worktree, { recursive: true }); - expect( - (yield* service.runNow).entries.filter((entry) => entry.kind === "worktree"), - ).toEqual([]); - }), - ), - ); it.live("serializes concurrent requests and returns each run's report", () => runCleanupTest( Effect.gen(function* () { @@ -1628,102 +1833,6 @@ describe("storage cleanup reports and local file policies", () => { ); }); -describe("settled worktree retention", () => { - it.effect.each([ - "immediate", - "settle-script", - "expired", - "boundary", - "wait", - "recent-update", - "active", - "dirty", - "project-off", - "project-custom", - "inactive-settling", - ] as const)("applies retention and safety checks (%s)", (scenario) => - Effect.gen(function* () { - yield* TestClock.setTime(NOW_MS); - const fixture = yield* cleanupFixture(); - const days = ["wait", "boundary", "expired", "recent-update"].includes(scenario) ? 8 : 0; - const rules = { - ...DEFAULT_SERVER_SETTINGS.storageCleanup, - worktreeSettledAfterDays: - scenario === "project-custom" || scenario === "inactive-settling" ? null : days, - worktreeAfterDays: scenario === "inactive-settling" ? 1 : null, - }; - fixture.setSettings({ - storageCleanup: rules, - projectSettingsOverrides: { - [ProjectId.make("project-1")]: - scenario === "project-off" - ? { worktreeCleanup: { mode: "off" } } - : scenario === "project-custom" - ? { - worktreeCleanup: { - mode: "custom", - rules: { ...rules, worktreeSettledAfterDays: 0 }, - }, - } - : {}, - }, - }); - const thread = shell({ - branch: "feature", - worktreePath: fixture.worktree, - settledAt: - scenario === "active" - ? null - : at( - scenario === "expired" || - scenario === "recent-update" || - scenario === "inactive-settling" - ? -20 * DAY_MS - : scenario === "boundary" - ? -8 * DAY_MS - : scenario === "wait" - ? -8 * DAY_MS + 1 - : scenario === "settle-script" - ? 0 - : -60_000, - ), - updatedAt: at( - scenario === "recent-update" || - scenario === "settle-script" || - scenario === "inactive-settling" - ? 0 - : -10 * DAY_MS, - ), - }); - fixture.setThreads([thread]); - if (scenario === "dirty") - yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "edit\n"); - const report = yield* fixture.service.runNow; - const removed = ["immediate", "expired", "boundary", "project-custom"].includes(scenario); - expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed); - expect(report.counts.removed).toBe(removed ? 1 : 0); - if (scenario !== "project-off") { - const reason = - scenario === "active" - ? "Not settled" - : scenario === "wait" - ? "Settled for 7 of 8 days" - : ["settle-script", "recent-update", "inactive-settling"].includes(scenario) - ? "Settled moments ago" - : scenario === "dirty" - ? "Has uncommitted changes (1 file)" - : `Settled for ${scenario === "expired" ? 20 : scenario === "boundary" ? 8 : 0} days`; - expect(report.entries[0]).toMatchObject({ outcome: removed ? "removed" : "kept", reason }); - } - expect(thread.branch).toBe("feature"); - expect( - (yield* fixture.command(fixture.repo, ["rev-parse", "--verify", "refs/heads/feature"])) - .exitCode, - ).toBe(0); - }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), - ); -}); - describe("settled worktree rechecks", () => { it.live.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( "keeps a checkout changed during measurement (%j)", @@ -1776,52 +1885,3 @@ it.live("keeps saved usage data when removing a settled checkout", () => }), ), ); - -it.live.each(["thread.settled", "stopped", "ready"] as const)( - "leaves settled cleanup to the regular sweeps after %s", - (trigger) => - runCleanupTest( - Effect.gen(function* () { - const fixture = yield* pausedMeasurementFixture({ - ...DEFAULT_SERVER_SETTINGS.storageCleanup, - worktreeSettledAfterDays: 0, - }); - fixture.setSettings({ - storageCleanup: { - ...DEFAULT_SERVER_SETTINGS.storageCleanup, - worktreeSettledAfterDays: 0, - }, - }); - const thread = shell({ - branch: "feature", - worktreePath: fixture.worktree, - settledAt: at(0), - }); - fixture.setThreads([thread]); - const handled = yield* Deferred.make(); - yield* fixture.activate( - Stream.fromEffect(Deferred.await(fixture.measuring)).pipe( - Stream.flatMap(() => Stream.range(0, 19)), - Stream.map((index): OrchestrationV2DomainEvent => - trigger === "thread.settled" - ? { - id: EventId.make(`settled-${index}`), - type: "thread.settled", - threadId: thread.id, - occurredAt: at(0), - payload: { ...thread, lastVisitedAt: null }, - } - : sessionUpdated(index, trigger), - ), - Stream.concat( - Stream.fromEffect(Deferred.succeed(handled, undefined)).pipe(Stream.drain), - ), - ), - ); - yield* Deferred.await(handled); - yield* Deferred.succeed(fixture.resume, undefined); - yield* fixture.service.drain; - expect(fixture.snapshotReads()).toBe(1); - }), - ), -); diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index d684448674282..0433aaf845e7e 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -32,6 +32,7 @@ import type { PlatformError } from "effect/PlatformError"; import * as Schedule from "effect/Schedule"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import { parse as parseYaml } from "yaml"; import * as ServerConfig from "./config.ts"; import * as GitManager from "./git/GitManager.ts"; @@ -45,9 +46,11 @@ import * as Settings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts"; import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; +import { removeLinkedWorktree } from "./vcs/worktreeRemoval.ts"; import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { isNetworkPath } from "@t3tools/shared/path"; const decodeCleanupThread = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationV2AppThreadJson), @@ -55,10 +58,16 @@ const decodeCleanupThread = Schema.decodeUnknownEffect( const decodeCleanupSession = Schema.decodeUnknownEffect( Schema.fromJsonString(OrchestrationV2ProviderSessionJson), ); +// pnpm 11 writes this file as JSON, older versions as YAML. +const decodePnpmModulesManifest = Schema.decodeUnknownEffect( + Schema.Struct({ + storeDir: Schema.String, + virtualStoreDir: Schema.optional(Schema.String), + }), +); const DAY_MS = 86_400_000; -// After a settle, the project's settle script needs time to open its -// terminal, which then protects the worktree. +// Give settle scripts time to open terminals that protect the worktree. const SETTLE_SCRIPT_GRACE_MS = 60_000; // Worktree creation can precede its thread row, including review-guide checkouts. const ORPHAN_WORKTREE_GRACE_MS = 60 * 60 * 1_000; @@ -136,7 +145,9 @@ export function storageCleanupActivityAt(thread: OrchestrationV2ThreadShell): nu } /** Only a complete subagent chain within this worktree shares ownership. */ -function worktreeOwner(threads: ReadonlyArray) { +function worktreeOwner>( + threads: ReadonlyArray, +) { if (threads.length === 1) return threads[0]; const byId = new Map(threads.map((thread) => [thread.id, thread])); const tops = threads.filter((thread) => !byId.has(thread.lineage.parentThreadId!)); @@ -161,11 +172,7 @@ function worktreeOwner(threads: ReadonlyArray) { return owner; } -/** - * Whether the host's pull request proves this worktree's head was merged. A - * squash or rebase merge leaves the head outside the default branch, so the - * merged pull request then has to name this exact commit. - */ +/** Squash/rebase merges require the merged PR to name this exact head commit. */ export function storageCleanupPullRequestMerged( pullRequest: Pick< GitManager.GitBranchPullRequest, @@ -247,14 +254,40 @@ const make = Effect.gen(function* () { ); }); - const measureWorktree = (worktreePath: string) => - Effect.gen(function* () { + // 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 + // forces real copies, which still count. + const sharedPnpmVirtualStore = Effect.fnUntraced( + function* (root: string) { + const nodeModules = path.join(root, "node_modules"); + const text = yield* fs.readFileString(path.join(nodeModules, ".modules.yaml")); + const manifest = yield* decodePnpmModulesManifest(yield* Effect.try(() => parseYaml(text))); + // An agent can write this manifest, and statting a network path makes + // Windows sign in to its host with the user's NTLM credentials. + if (isNetworkPath(manifest.storeDir) || isNetworkPath(manifest.virtualStoreDir ?? "")) { + return null; + } + const virtualStore = path.resolve(nodeModules, manifest.virtualStoreDir ?? ".pnpm"); + const [store, virtual] = yield* Effect.all([ + fs.stat(manifest.storeDir), + fs.stat(virtualStore), + ]); + return store.dev === virtual.dev ? virtualStore : null; + }, + Effect.orElseSucceed(() => null), + ); + + const measureWorktree = Effect.fn("storageCleanup.measureWorktree")( + function* (worktreePath: string) { const root = yield* fs.realPath(worktreePath); + const skipped = yield* sharedPnpmVirtualStore(root); const pending = [root]; let entries = 1; let bytes = 0; while (pending.length > 0) { const target = pending.pop()!; + if (target === skipped) continue; // Effect's stat follows links. Probe with readLink first to get lstat // semantics, including skipping dangling links and directory links. const isLink = yield* fs.readLink(target).pipe( @@ -270,8 +303,14 @@ const make = Effect.gen(function* () { if (isLink) continue; if ((yield* fs.realPath(target)) !== target) return null; const stat = yield* fs.stat(target); - if (stat.type === "File") bytes += Number(stat.size); - else if (stat.type === "Directory") { + if (stat.type === "File") { + // Removing a shared hardlink leaves its blocks allocated. + if (Option.getOrElse(stat.nlink, () => 1n) !== 1n) continue; + bytes += Option.match(stat.blocks, { + onNone: () => Number(stat.size), + onSome: (blocks) => Number(blocks * 512n), + }); + } else if (stat.type === "Directory") { const names = yield* fs.readDirectory(target); entries += names.length; if (entries > 2_000_000) return null; @@ -283,19 +322,16 @@ const make = Effect.gen(function* () { } } return bytes; - }).pipe( - Effect.timeout("30 seconds"), - Effect.orElseSucceed(() => null), - ); + }, + Effect.timeout("30 seconds"), + Effect.orElseSucceed(() => null), + ); - // The snapshot takes seconds on large databases, so it runs on the reader - // worker instead of the event loop. + // Large snapshots take seconds; use the reader worker instead of blocking the event loop. const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () { - const { threads } = yield* projections - .getShellSnapshot({ location: "active" }) - .pipe(NodeSqliteClient.readOnly); + const snapshot = yield* projections.getShellSnapshot().pipe(NodeSqliteClient.readOnly); const projects = yield* projectStore.listShells(); - return { projects, threads }; + return { projects, threads: [...snapshot.threads, ...snapshot.archivedThreads] }; }); const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* ( @@ -320,7 +356,6 @@ const make = Effect.gen(function* () { projects: ReadonlyArray<{ readonly workspaceRoot: string }>, entries: StorageCleanupReportEntry[], ) { - // Include deleted and archived threads, even those without a branch or project. const rows = yield* sql<{ worktreePath: string }>` SELECT DISTINCT json_extract(payload_json, '$.worktreePath') AS "worktreePath" FROM orchestration_v2_projection_threads @@ -372,9 +407,7 @@ const make = Effect.gen(function* () { } return result; }); - // Let the first walk reach its own limit so unmeasurable folders get cached. - // Later walks share the remaining sweep budget. - // Unmeasured folders still appear with an unknown size. + // Let the first walk time out and cache unmeasurable folders; later walks share the remaining budget. const now = yield* Clock.currentTimeMillis; const measurementDeadline = now + 30_000; let firstMeasurement = true; @@ -410,6 +443,7 @@ const make = Effect.gen(function* () { ? "No thread uses this worktree" : "No thread uses this folder, and it isn't a git worktree", path: worktreePath, + projectPath: null, threadId: null, threadTitle: null, bytes, @@ -439,9 +473,7 @@ const make = Effect.gen(function* () { } }); - // Whether cwd stopped being a checkout of this branch. Two small Git reads, - // since every worktree in a sweep is asked; statusDetailsLocal also diffs and - // counts. + // Use two small Git reads: statusDetailsLocal also diffs and counts for every worktree. const branchChanged = Effect.fn("StorageCleanup.branchChanged")(function* ( cwd: string, branch: string | null, @@ -453,8 +485,7 @@ const make = Effect.gen(function* () { cwd, detail, }); - // Null when cwd is not a repository, or is gone. Git's own messages are - // matched, so they must not be translated. + // Return null for missing/non-repository cwd; force untranslated git diagnostics for matching. const read = Effect.fnUntraced(function* (args: string[], allowedExitCode?: number) { const result = yield* git .execute({ @@ -484,8 +515,7 @@ const make = Effect.gen(function* () { return yield* failure( "Git index is locked. Status will resume when the index lock is removed.", ); - // Exits 1 for a detached HEAD. Reads the full ref name, which is never - // shortened to "heads/" when a tag shares the branch name. + // Detached HEAD exits 1; full refs avoid shortening when a tag shares the branch name. const head = yield* read(["symbolic-ref", "--quiet", "HEAD"], 1); if (head === null) return true; const ref = head.exitCode === 0 ? head.stdout.trim() : ""; @@ -533,6 +563,122 @@ const make = Effect.gen(function* () { return file === undefined ? null : `has ignored files (${file})`; }); + const submoduleRemoval = Effect.fn("StorageCleanup.submoduleRemoval")( + function* (cwd: string, rules: WorktreeCleanupRules) { + const inspect = (args: string[], maxOutputBytes = 64 * 1024) => + git.execute({ + operation: "StorageCleanup.submodules", + cwd, + args, + maxOutputBytes, + }); + const admin = yield* inspect(["rev-parse", "--absolute-git-dir"]); + if (admin.stdoutTruncated || admin.stderrTruncated) + return { force: false, reason: "submodule inspection exceeded the limit" }; + const modules = path.join(admin.stdout.replace(/\n$/, ""), "modules"); + const stored = yield* fs.exists(modules); + if (!stored && !(yield* fs.exists(path.join(cwd, ".gitmodules")))) + return { force: false, reason: null }; + const populated = yield* inspect([ + "submodule", + "foreach", + "--recursive", + "--quiet", + 'printf "%s\\0" "$toplevel/$sm_path"', + ]); + if (populated.stdoutTruncated || populated.stderrTruncated) + return { force: false, reason: "submodule inspection exceeded the limit" }; + const paths = populated.stdout.split("\0").filter(Boolean); + const pending = [modules]; + for (const submodule of paths) { + const directory = yield* inspect(["-C", submodule, "rev-parse", "--absolute-git-dir"]); + if (directory.stdoutTruncated || directory.stderrTruncated) + return { force: false, reason: "submodule inspection exceeded the limit" }; + pending.push(directory.stdout.replace(/\n$/, "")); + } + const visited = new Set(); + while (pending.length > 0) { + const directory = pending.pop()!; + if (!(yield* fs.exists(directory))) continue; + const canonical = yield* fs.realPath(directory); + if (visited.has(canonical)) continue; + visited.add(canonical); + if (visited.size > 10_000) + return { force: false, reason: "submodule inspection exceeded the limit" }; + if ((yield* fs.stat(directory)).type !== "Directory") + return { force: false, reason: "submodule repository could not be inspected" }; + if (yield* fs.exists(path.join(directory, "HEAD"))) { + const unpushed = yield* inspect([ + "--git-dir", + directory, + "--work-tree", + cwd, + "rev-list", + "--max-count=1", + "HEAD", + "--all", + "--reflog", + "--not", + "--remotes", + ]); + if (unpushed.stdoutTruncated || unpushed.stderrTruncated) + return { force: false, reason: "submodule inspection exceeded the limit" }; + if (unpushed.stdout.trim() !== "") + return { force: false, reason: "submodule has commits not on a remote-tracking ref" }; + pending.push(path.join(directory, "modules")); + } else { + for (const name of yield* fs.readDirectory(directory)) + pending.push(path.join(directory, name)); + } + } + // Check files after walking stored history to shorten the gap before forced removal. + for (const submodule of paths) { + const changes = yield* localChangesReason(submodule, rules); + if (changes !== null) return { force: false, reason: `submodule ${changes}` }; + } + const force = stored || paths.length > 0; + if (force && rules.worktreeKeepWhen !== "tracked-changes") { + const root = yield* fs.realPath(cwd); + // Git status and foreach omit files inside deinitialized gitlink directories. + const populatedPaths = new Set(paths.map(pathKey)); + const unchecked: string[] = []; + for (const repository of [root, ...paths]) { + const index = yield* inspect( + ["-C", repository, "ls-files", "--stage", "-z"], + 16 * 1024 * 1024, + ); + if (index.stdoutTruncated || index.stderrTruncated) + return { force: false, reason: "submodule inspection exceeded the limit" }; + for (const entry of index.stdout.split("\0")) { + if (!entry.startsWith("160000 ")) continue; + const submodule = path.resolve(repository, entry.slice(entry.indexOf("\t") + 1)); + if (!inside(root, submodule)) + return { force: false, reason: "submodules could not be inspected" }; + if (!populatedPaths.has(pathKey(submodule)) && (yield* fs.exists(submodule))) + unchecked.push(submodule); + } + } + let inspected = unchecked.length; + while (unchecked.length > 0) { + if (inspected > 10_000) + return { force: false, reason: "submodule inspection exceeded the limit" }; + const target = unchecked.pop()!; + if ( + (yield* fs.realPath(target)) !== path.resolve(target) || + (yield* fs.stat(target)).type !== "Directory" + ) + return { force: false, reason: "submodule has local files" }; + if (path.basename(target) === "node_modules") continue; + const names = yield* fs.readDirectory(target); + inspected += names.length; + for (const name of names) unchecked.push(path.join(target, name)); + } + } + return { force, reason: null }; + }, + Effect.orElseSucceed(() => ({ force: false, reason: "submodules could not be inspected" })), + ); + const cleanupGit = Effect.fn("StorageCleanup.cleanupGit")(function* ( cwd: string, args: string[], @@ -580,7 +726,7 @@ const make = Effect.gen(function* () { FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id WHERE t.deleted_at IS NOT NULL - `; + `.pipe(NodeSqliteClient.readOnly); const deletedThreads = (yield* Effect.forEach(deletedRows, (row) => decodeCleanupThread(row.payload_json).pipe( Effect.map((thread) => ({ ...thread, workspaceRoot: row.workspaceRoot })), @@ -588,12 +734,29 @@ const make = Effect.gen(function* () { )).filter((thread) => thread.worktreePath !== null && thread.branch !== null); const snapshot = yield* readThreads(); const refreshedDefaultRefs = new Map>(); + const defaultBranches = new Map(); const groups = Map.groupBy( snapshot.threads.filter((thread) => thread.worktreePath !== null), (thread) => path.resolve(thread.worktreePath!), ); + const deletedByPath = Map.groupBy(deletedThreads, (thread) => + path.resolve(thread.worktreePath!), + ); const candidates = [ - ...[...groups.values()].map((group) => worktreeOwner(group) ?? group[0]!), + ...[...groups].map( + ([worktreePath, 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) + ?.find( + (deleted) => + resolveWorktreeCleanup(serverSettings, deleted.projectId).worktreeOnDelete && + worktreeOwner([deleted, ...group]) === deleted, + ) ?? + worktreeOwner(group) ?? + group[0]!, + ), ...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath!))), ]; for (const thread of candidates) { @@ -603,6 +766,7 @@ const make = Effect.gen(function* () { const group = groups.get(worktreePath) ?? []; const activityAt = Math.max(...group.map(storageCleanupActivityAt)); const deleted = "workspaceRoot" in thread; + const members = deleted ? [thread, ...group] : group; const project = deleted ? { workspaceRoot: thread.workspaceRoot } : snapshot.projects.find((entry) => entry.id === thread.projectId); @@ -611,6 +775,7 @@ const make = Effect.gen(function* () { outcome: "kept", reason: "", path: worktreePath, + projectPath: project?.workspaceRoot ?? null, threadId: thread.id, threadTitle: thread.title, bytes: null, @@ -620,19 +785,18 @@ const make = Effect.gen(function* () { yield* Effect.gen(function* () { if (!(yield* fs.exists(worktreePath))) return; if (deleted && !settings.worktreeOnDelete) return keep("no rules apply"); - if (group.length > 1 && worktreeOwner(group) === undefined) - return keep(`shared by ${group.length} threads`); + if (members.length > 1 && worktreeOwner(members) === undefined) + return keep(`shared by ${members.length} threads`); if (project === undefined) return keep("project is unavailable"); if ( thread.branch === null || - (!deleted && !group.every((member) => storageCleanupThreadIdle(member, now))) + !group.every((member) => storageCleanupThreadIdle(member, now)) ) return keep("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("open terminal"); - // Roots are canonical, so compare canonical paths. A symlinked parent - // (a linked drive) is fine; a symlinked worktree directory is not. + // Compare canonical roots while allowing symlinked parents, never symlinked worktree directories. const realPath = yield* fs.realPath(worktreePath); const realParent = yield* fs.realPath(path.dirname(worktreePath)); if (realPath !== path.join(realParent, path.basename(worktreePath))) @@ -648,7 +812,6 @@ const make = Effect.gen(function* () { const changes = yield* localChangesReason(worktreePath, settings); if (changes !== null) return keep(changes); if ( - !deleted && group.some( (member) => member.settledAt !== null && @@ -680,7 +843,30 @@ const make = Effect.gen(function* () { if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) { const repositoryCwd = path.resolve(project.workspaceRoot); const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd); - const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote); + const defaultBranchKey = `${repositoryCwd}\0${remote}`; + let branch = defaultBranches.get(defaultBranchKey); + if (branch === undefined) { + branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote); + // Without a local HEAD ref, only the remote can identify its default; + // a conventional name may be a feature branch. + if (branch === null) { + branch = yield* git + .execute({ + operation: "StorageCleanup.resolveDefaultBranch", + cwd: repositoryCwd, + args: ["ls-remote", "--symref", "--", remote, "HEAD"], + timeoutMs: 20_000, + }) + .pipe( + Effect.map( + (result) => + /^ref: refs\/heads\/(.+)\tHEAD\r?$/m.exec(result.stdout)?.[1] ?? null, + ), + Effect.orElseSucceed(() => null), + ); + } + defaultBranches.set(defaultBranchKey, branch); + } if (branch === null) return keep("default branch is unavailable"); const defaultRef = `refs/remotes/${remote}/${branch}`; const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set(); @@ -732,68 +918,60 @@ const make = Effect.gen(function* () { ? "not merged" : "has commits beyond the default branch", ); - // Threads, queued deletion work and provider sessions as they are now, so a - // queued turn, resumed session or new thread sharing this path cancels - // the removal. Read only this path's threads: a full snapshot per - // worktree takes seconds on large databases. + // 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])) return "contains a project checkout"; - const latest = (yield* projections.getThreadWorktreePaths()).filter( - (entry) => path.resolve(entry.worktreePath) === worktreePath, - ); + const latest = (yield* projections.getThreadWorktreePaths({ + includeArchived: true, + })).filter((entry) => path.resolve(entry.worktreePath) === worktreePath); if (hasTerminal(worktreePath)) return "open terminal"; if (deleted) { if ( - latest.length > 0 || !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId) .worktreeOnDelete ) return "thread or cleanup settings changed since check"; - // V2 deletion queues durable cleanup. Do not remove its checkout until - // every effect has finished successfully or was explicitly cancelled. + // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout. const pendingCleanup = yield* sql` SELECT 1 FROM orchestration_v2_effect_outbox WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') LIMIT 1 - `; + `.pipe(NodeSqliteClient.readOnly); if (pendingCleanup.length > 0) return "thread deletion is still pending"; - } else { - const latestShells = yield* Effect.forEach(latest, (entry) => - projections.getThreadShell(entry.threadId), - ); - const latestGroup = latestShells.filter((shell) => shell !== null); - const latestOwner = worktreeOwner(latestGroup); - if ( - latestGroup.length !== group.length || - latestOwner?.id !== thread.id || - latestOwner?.branch !== thread.branch || - latestGroup.some((shell) => { - const previous = group.find((member) => member.id === shell.id); - return ( - previous === undefined || - shell.branch !== thread.branch || - !Equal.equals(shell.settledAt, previous.settledAt) || - (shell.settledAt !== null && - !Equal.equals(shell.updatedAt, previous.updatedAt)) || - !storageCleanupThreadIdle(shell, now) || - path.resolve(shell.worktreePath!) !== worktreePath || - storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) - ); - }) - ) - return "thread activity or shared worktree changed since check"; } + const latestShells = yield* Effect.forEach(latest, (entry) => + projections.getThreadShell(entry.threadId), + ); + const latestGroup = latestShells.filter((shell) => shell !== null); + const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup); + if ( + latestGroup.length !== group.length || + latestOwner?.id !== thread.id || + latestOwner?.branch !== thread.branch || + latestGroup.some((shell) => { + const previous = group.find((member) => member.id === shell.id); + return ( + previous === undefined || + shell.branch !== thread.branch || + !Equal.equals(shell.settledAt, previous.settledAt) || + (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) || + !storageCleanupThreadIdle(shell, now) || + path.resolve(shell.worktreePath!) !== worktreePath || + storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) + ); + }) + ) + return "thread activity or shared worktree changed since check"; // Sessions can outlive their run and can be shared across app threads. const sessionRows = yield* sql<{ payload_json: string }>` SELECT payload_json FROM orchestration_v2_projection_provider_sessions WHERE status != 'stopped' - `; + `.pipe(NodeSqliteClient.readOnly); const sessions = yield* Effect.forEach(sessionRows, (row) => decodeCleanupSession(row.payload_json), ); - // A stored session can stay ready after its runtime was released, - // for example once every thread detached; only a live one holds it. + // 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 ( @@ -829,19 +1007,27 @@ const make = Effect.gen(function* () { ) ) return keep("settings changed since check"); - // Clean only untracked files; Git must still refuse removal if a tracked - // edit arrives after our last status check. + // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check. if (settings.worktreeKeepWhen === "tracked-changes") yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); - yield* cleanupGit( - project.workspaceRoot, - ["-c", "status.showUntrackedFiles=normal", "worktree", "remove", "--", worktreePath], - "git worktree remove", - ); + const submodules = yield* submoduleRemoval(worktreePath, settings); + if (submodules.reason !== null) return keep(submodules.reason); + if (submodules.force) { + const changes = yield* localChangesReason(worktreePath, settings); + if (changes !== null) return keep(changes); + } + yield* removeLinkedWorktree({ + operation: "StorageCleanup.cleanupGit", + cwd: project.workspaceRoot, + worktreePath, + // Git requires force for submodules; recursive checks above cannot make removal atomic. + force: submodules.force, + execute: git.execute, + run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"), + }); entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes }); yield* gitManager.invalidateStatus(project.workspaceRoot); - // Preserve branch and path: ProviderTurnStartService recreates the checkout - // from that branch when the thread is resumed. + // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume. yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id }); }).pipe( (effect) => withWorkspaceLease(worktreePath, effect), @@ -919,6 +1105,7 @@ const make = Effect.gen(function* () { outcome: "failed", reason: cleanupFailureReason(error), path: null, + projectPath: null, threadId: null, threadTitle: null, bytes: null, @@ -951,6 +1138,7 @@ const make = Effect.gen(function* () { outcome: files > 0 ? "removed" : "kept", reason: files === 0 ? "No expired files" : `Removed ${files} ${category.label}`, path: null, + projectPath: null, threadId: null, threadTitle: null, bytes: files > 0 ? bytes : null, @@ -964,6 +1152,7 @@ const make = Effect.gen(function* () { outcome: "failed", reason: cleanupFailureReason(error), path: null, + projectPath: null, threadId: null, threadTitle: null, bytes: removed.files > 0 ? removed.bytes : null, diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts index e7f5889a5b500..1cc66be7b3dfe 100644 --- a/apps/server/src/telemetry/AnalyticsService.test.ts +++ b/apps/server/src/telemetry/AnalyticsService.test.ts @@ -8,13 +8,15 @@ import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; import * as HttpClient from "effect/http/HttpClient"; import * as HttpClientError from "effect/http/HttpClientError"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; import * as HttpServer from "effect/http/HttpServer"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as HttpServerResponse from "effect/http/HttpServerResponse"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ServerConfig from "../config.ts"; -import { getTelemetryIdentifier } from "./Identify.ts"; +import { getTelemetryIdentity } from "./Identify.ts"; import * as AnalyticsService from "./AnalyticsService.ts"; interface RecordedBatchRequest { @@ -52,75 +54,119 @@ interface RecordedBatchBody { const SentBatch = Schema.fromJsonString( Schema.Struct({ - batch: Schema.Array(Schema.Struct({ uuid: Schema.String })), + batch: Schema.Array( + Schema.Struct({ + uuid: Schema.String, + event: Schema.String, + distinct_id: Schema.String, + properties: Schema.Struct({ + telemetryChannel: Schema.String, + installId: Schema.optionalKey(Schema.String), + ownerSource: Schema.optionalKey(Schema.String), + observedBy: Schema.optionalKey(Schema.String), + }), + }), + ), }), ); +const decodeSentBatch = Schema.decodeEffect(SentBatch); +type SentEvent = (typeof SentBatch.Type)["batch"][number]; +type Respond = ( + request: HttpClientRequest.HttpClientRequest, +) => Effect.Effect; + +const respondWithStatus = + (status: number): Respond => + (request) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status }))); -const layerAcceptThenFailClient = (batches: Array>) => - Layer.succeed( - HttpClient.HttpClient, - HttpClient.make((request) => +const recordTwentyEvents = Effect.gen(function* () { + const analytics = yield* AnalyticsService.AnalyticsService; + for (let index = 0; index < 20; index += 1) { + yield* analytics.record("test.retry", { index }); + } +}); + +/** + * Runs `record` (20 events by default), then lets ten minutes of background + * flushes run against a client that answers every send with `respond`. + * Returns the sent batches. + */ +const sendForTenMinutes = ( + respond: Respond, + record: Effect.Effect< + void, + never, + AnalyticsService.AnalyticsService | Effect.Services + > = recordTwentyEvents, +) => + Effect.gen(function* () { + const batches: Array> = []; + const client = HttpClient.make((request) => Effect.gen(function* () { if (request.body._tag === "Uint8Array") { - const body = yield* Schema.decodeEffect(SentBatch)( - new TextDecoder().decode(request.body.body), - ).pipe(Effect.orDie); + const body = yield* decodeSentBatch(new TextDecoder().decode(request.body.body)).pipe( + Effect.orDie, + ); batches.push(body.batch); } - return yield* new HttpClientError.HttpClientError({ - reason: new HttpClientError.TransportError({ request, cause: "connection reset" }), - }); + return yield* respond(request); }), - ), - ); + ); + const runtimeLayer = AnalyticsService.layer.pipe( + Layer.provideMerge( + ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }), + ), + Layer.provide( + ConfigProvider.layer( + ConfigProvider.fromUnknown({ + T3CODE_TELEMETRY_ENABLED: true, + T3CODE_POSTHOG_KEY: "phc_test_key", + T3CODE_POSTHOG_HOST: "http://localhost", + }), + ), + ), + Layer.provide( + Layer.mergeAll( + Layer.succeed(HostProcess.Platform, "win32"), + Layer.succeed(HostProcess.Architecture, "x64"), + Layer.succeed(HttpClient.HttpClient, client), + ), + ), + ); -it("retryDelayMs doubles from 2s and stays under the 5 minute cap", () => { - assert.equal(AnalyticsService.retryDelayMs(1, 0), 1_000); - assert.equal(AnalyticsService.retryDelayMs(2, 0.999_999), 4_000); - assert.equal(AnalyticsService.retryDelayMs(30, 0), 150_000); - assert.equal(AnalyticsService.retryDelayMs(30, 0.999_999), 300_000); -}); + yield* Effect.gen(function* () { + yield* record; + for (let second = 0; second < 600; second += 1) { + yield* TestClock.adjust("1 second"); + } + }).pipe(Effect.provide(runtimeLayer)); + return batches; + }); it.layer(NodeServices.layer)("AnalyticsService test", (it) => { - it.effect("a batch that keeps failing is retried with backoff, then dropped", () => + it.effect("client owner reports cannot use up the server's owner cap", () => Effect.gen(function* () { - const batches: Array> = []; - const layerRuntime = AnalyticsService.layer.pipe( - Layer.provideMerge( - ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }), - ), - Layer.provide( - ConfigProvider.layer( - ConfigProvider.fromUnknown({ - T3CODE_TELEMETRY_ENABLED: true, - T3CODE_POSTHOG_KEY: "phc_test_key", - T3CODE_POSTHOG_HOST: "http://localhost", - }), - ), - ), - Layer.provide( - Layer.mergeAll( - Layer.succeed(HostProcess.Platform, "win32"), - Layer.succeed(HostProcess.Architecture, "x64"), - layerAcceptThenFailClient(batches), - ), - ), + const batches = yield* sendForTenMinutes( + respondWithStatus(204), + Effect.gen(function* () { + const analytics = yield* AnalyticsService.AnalyticsService; + yield* analytics.recordOwners( + Array.from({ length: 1_001 }, (_, index) => ({ + source: "device" as const, + ownerId: index.toString(16).padStart(64, "0"), + })), + "client", + ); + // The event buffer also holds 1,000, so send the client events first. + yield* analytics.flush; + yield* analytics.recordOwners([{ source: "connect", ownerId: "a".repeat(64) }], "server"); + }), ); + const owners = batches.flat().map((event) => event.properties.observedBy); - yield* Effect.gen(function* () { - const analytics = yield* AnalyticsService.AnalyticsService; - for (let index = 0; index < 20; index += 1) { - yield* analytics.record("test.retry", { index }); - } - for (let second = 0; second < 600; second += 1) { - yield* TestClock.adjust("1 second"); - } - }).pipe(Effect.provide(layerRuntime)); - - assert.equal(batches.length, 5); - const uuids = batches.map((batch) => batch.map((event) => event.uuid).join(",")); - assert.equal(new Set(uuids).size, 1, "every retry carries the same uuids"); - assert.equal(new Set(batches[0]?.map((event) => event.uuid)).size, 20); + assert.equal(owners.filter((observedBy) => observedBy === "client").length, 1_000); + assert.equal(owners.filter((observedBy) => observedBy === "server").length, 1); }), ); @@ -170,8 +216,8 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => { yield* Effect.gen(function* () { yield* Layer.launch(layerBatchServer).pipe(Effect.forkScoped); - const telemetryIdentifier = yield* getTelemetryIdentifier; - assert.equal(telemetryIdentifier !== null, true); + const { distinctId } = yield* getTelemetryIdentity; + assert.equal(distinctId !== null, true); const analytics = yield* AnalyticsService.AnalyticsService; for (let index = 0; index < 45; index += 1) { diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts index db627fdb92dc5..bc0a0ad562a4f 100644 --- a/apps/server/src/telemetry/AnalyticsService.ts +++ b/apps/server/src/telemetry/AnalyticsService.ts @@ -1,7 +1,4 @@ -/** - * Each event carries a uuid, so PostHog can tell a retried copy from a new - * event. - */ +// T3 ingest retains events and forwards to PostHog; UUIDs deduplicate retries there. import * as HostProcess from "@t3tools/shared/HostProcess"; import type { ClientOs } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; @@ -23,7 +20,7 @@ import * as HttpClientResponse from "effect/http/HttpClientResponse"; import packageJson from "../../package.json" with { type: "json" }; import * as ServerConfig from "../config.ts"; -import { getTelemetryIdentifier } from "./Identify.ts"; +import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts"; interface BufferedAnalyticsEvent { readonly uuid: string; @@ -39,15 +36,26 @@ interface DeliveryState { readonly retryAt: number; } -const FLUSH_INTERVAL_MS = 1_000; +// Retry delays shorter than this still wait for the next background check. +const FLUSH_INTERVAL_MS = 10_000; // A hung send would hold the flush lock, and with it the shutdown flush. const SEND_TIMEOUT = "10 seconds"; const MAX_BATCH_ATTEMPTS = 5; const RETRY_BASE_DELAY_MS = 2_000; +// Clients can report any number of owner ids; past this many per observer, new ones +// are not sent. Each observer has its own cap, so client reports never crowd out the +// server's own. +const MAX_RECORDED_OWNERS = 1_000; const RETRY_MAX_DELAY_MS = 300_000; +// These statuses reject the batch itself; unlike 408/429, retrying cannot help. +const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]); + +// Official release workflows set this telemetry channel; other builds report dev. +// Unlike __T3CODE_BUILD_CHANNEL__, this is not the sign-in page's latest/nightly channel. +declare const __T3CODE_TELEMETRY_CHANNEL__: "stable" | "nightly" | "preview" | "dev" | undefined; /** `random` is in [0, 1). */ -export function retryDelayMs(failures: number, random: number): number { +function retryDelayMs(failures: number, random: number): number { const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1)); return Math.round(ceiling / 2 + (ceiling / 2) * random); } @@ -57,7 +65,7 @@ const TelemetryEnvConfig = Config.all({ Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"), ), posthogHost: Config.String("T3CODE_POSTHOG_HOST").pipe( - Config.withDefault("https://us.i.posthog.com"), + Config.withDefault("https://ingest.t3.codes"), ), enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)), flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)), @@ -76,6 +84,16 @@ export class AnalyticsService extends Context.Service< ) => Effect.Effect; readonly flush: Effect.Effect; + + /** + * Records `install.owner_observed` for each owner of this install that the + * server read itself or a connecting client reported. Each owner is sent once + * per server process, so reconnects and repeated reads are free. + */ + readonly recordOwners: ( + owners: ReadonlyArray, + observedBy: "server" | "client", + ) => Effect.Effect; } >()("t3/telemetry/AnalyticsService") { static readonly layerTest = Layer.succeed( @@ -83,6 +101,7 @@ export class AnalyticsService extends Context.Service< AnalyticsService.of({ record: () => Effect.void, flush: Effect.void, + recordOwners: () => Effect.void, }), ); } @@ -103,12 +122,12 @@ function serverOsFromNodePlatform(platform: string): ClientOs { } /** @public */ -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const telemetryConfig = yield* TelemetryEnvConfig; const httpClient = yield* HttpClient.HttpClient; const serverConfig = yield* ServerConfig.ServerConfig; - const identifier = yield* getTelemetryIdentifier; + const { distinctId, installId } = yield* getTelemetryIdentity; const crypto = yield* Crypto.Crypto; const bufferRef = yield* Ref.make>([]); const deliveryRef = yield* Ref.make({ @@ -117,9 +136,14 @@ export const make = Effect.gen(function* () { failures: 0, retryAt: 0, }); + const recordedOwnersRef = yield* Ref.make< + Readonly>> + >({ server: new Set(), client: new Set() }); // The background flush and the shutdown flush must not send the same batch at once. const flushLock = yield* Semaphore.make(1); const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client"; + const telemetryChannel = + typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__; const hostPlatform = yield* HostProcess.Platform; const hostArchitecture = yield* HostProcess.Architecture; @@ -158,21 +182,23 @@ export const make = Effect.gen(function* () { const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* ( events: ReadonlyArray, ) { - if (!telemetryConfig.enabled || !identifier) return; + if (!telemetryConfig.enabled || !distinctId) return; const payload = { api_key: telemetryConfig.posthogKey, batch: events.map((event) => ({ uuid: event.uuid, event: event.event, - distinct_id: identifier, + distinct_id: distinctId, properties: { ...event.properties, + ...(installId === null ? {} : { installId }), $process_person_profile: false, platform: hostPlatform, wsl: Option.getOrUndefined(telemetryConfig.wslDistroName), arch: hostArchitecture, t3CodeVersion: packageJson.version, + telemetryChannel, clientType, serverOs: serverOsFromNodePlatform(hostPlatform), serverArch: hostArchitecture, @@ -197,6 +223,7 @@ export const make = Effect.gen(function* () { return [nextBatch, current.slice(nextBatch.length)] as const; }); + // Back off even after dropping rejected batches so bad API keys cannot drain the queue in a tight loop. const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () { while (true) { const delivery = yield* Ref.get(deliveryRef); @@ -214,20 +241,26 @@ export const make = Effect.gen(function* () { const failures = delivery.failures + 1; const batchAttempts = delivery.batchAttempts + 1; const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next); - if (batchAttempts < MAX_BATCH_ATTEMPTS) { + const error = sent.failure; + const rejected = + error._tag === "HttpClientError" && + error.reason._tag === "StatusCodeError" && + REJECTED_BATCH_STATUSES.has(error.reason.response.status); + if (!rejected && batchAttempts < MAX_BATCH_ATTEMPTS) { yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt }); yield* Effect.logDebug("Failed to send telemetry batch; will retry", { attempt: batchAttempts, - cause: sent.failure, + cause: error, }); return; } yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt }); - yield* Effect.logWarning("Dropped telemetry batch after repeated send failures", { - events: batch.length, - attempts: batchAttempts, - cause: sent.failure, - }); + yield* Effect.logWarning( + rejected + ? "Dropped telemetry batch the endpoint rejected" + : "Dropped telemetry batch after repeated send failures", + { events: batch.length, attempts: batchAttempts, cause: error }, + ); return; } }).pipe(flushLock.withPermit); @@ -241,10 +274,9 @@ export const make = Effect.gen(function* () { const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")( function* (event, properties) { - if (!telemetryConfig.enabled || !identifier) return; + if (!telemetryConfig.enabled || !distinctId) return; - // Telemetry is best effort: an event without a uuid is not sent. The - // Node implementation throws (a defect) rather than failing, so catch both. + // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs. const uuid = yield* Effect.exit(crypto.randomUUIDv7()); if (Exit.isFailure(uuid)) return; @@ -258,13 +290,36 @@ export const make = Effect.gen(function* () { }, ); + const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn( + "AnalyticsService.recordOwners", + )((owners, observedBy) => + Effect.forEach( + owners, + ({ source, ownerId }) => + Ref.modify(recordedOwnersRef, (recorded) => { + const key = `${source}:${ownerId}`; + const seen = recorded[observedBy]; + return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS + ? [false, recorded] + : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }]; + }).pipe( + Effect.flatMap((isNew) => + isNew + ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy }) + : Effect.void, + ), + ), + { discard: true }, + ), + ); + yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), { disableYield: true, }).pipe(Effect.forkScoped); yield* Effect.addFinalizer(() => flush); - return AnalyticsService.of({ record, flush }); + return AnalyticsService.of({ record, flush, recordOwners }); }); export const layer = Layer.effect(AnalyticsService, make); diff --git a/apps/server/src/telemetry/DelegatedTaskAnalytics.ts b/apps/server/src/telemetry/DelegatedTaskAnalytics.ts new file mode 100644 index 0000000000000..92a54ac8fcedb --- /dev/null +++ b/apps/server/src/telemetry/DelegatedTaskAnalytics.ts @@ -0,0 +1,93 @@ +/** + * Record one anonymous `mcp.delegated_task.finished` event per app-owned task reaching final status. + * + * @module DelegatedTaskAnalytics + */ +import type { OrchestrationV2DomainEvent } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as AnalyticsService from "./AnalyticsService.ts"; +import { crossProvider, providerDimensions } from "./ProviderDimensions.ts"; + +type SubagentEvent = Extract; + +const FINAL_STATUSES: ReadonlySet = new Set([ + "completed", + "failed", + "cancelled", + "interrupted", +]); + +export class DelegatedTaskAnalytics extends Context.Service< + DelegatedTaskAnalytics, + { readonly onSubagent: (event: SubagentEvent) => Effect.Effect } +>()("t3/telemetry/DelegatedTaskAnalytics") {} + +const make = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const analytics = yield* AnalyticsService.AnalyticsService; + const registry = yield* ProviderRegistry.ProviderRegistry; + // A task can be re-reported with the same final status; count it once per process. + const reported = new Set(); + + // Runs for every subagent update; most return early, so avoid a span per event. + const onSubagent = Effect.fnUntraced( + function* (event: SubagentEvent) { + const task = event.payload; + if (task.origin !== "app_owned" || !FINAL_STATUSES.has(task.status)) return; + if (reported.has(task.id)) return; + const parent = yield* orchestrator.getThreadShell(task.threadId); + const providers = yield* registry.getProviders; + const parentDimensions = + parent === null + ? { provider: "unknown" } + : providerDimensions(providers, parent.modelSelection); + const child = providerDimensions(providers, { + instanceId: task.providerInstanceId, + model: task.model ?? "", + }); + const cross = crossProvider(parentDimensions.provider, child.provider); + const durationSeconds = + task.startedAt !== null && task.completedAt !== null + ? Math.max( + 0, + Math.round( + (DateTime.toEpochMillis(task.completedAt) - + DateTime.toEpochMillis(task.startedAt)) / + 1000, + ), + ) + : undefined; + yield* analytics.record("mcp.delegated_task.finished", { + status: task.status, + callerProvider: parentDimensions.provider, + ...(parentDimensions.model === undefined ? {} : { callerModel: parentDimensions.model }), + targetProvider: child.provider, + ...(child.model === undefined ? {} : { targetModel: child.model }), + ...(cross === undefined ? {} : { crossProvider: cross }), + ...(task.completionWake === undefined ? {} : { completionWake: task.completionWake }), + ...(durationSeconds === undefined ? {} : { durationSeconds }), + }); + // Only after recording: a failed lookup leaves the next final update to report it. + reported.add(task.id); + }, + (effect) => effect.pipe(Effect.ignoreCause), + ); + + yield* forkParked( + Stream.runForEach(orchestrator.streamDomainEvents, (event) => + event.type === "subagent.updated" ? onSubagent(event) : Effect.void, + ), + ); + + return DelegatedTaskAnalytics.of({ onSubagent }); +}); + +export const layer = Layer.effect(DelegatedTaskAnalytics, make); diff --git a/apps/server/src/telemetry/FeatureUsage.test.ts b/apps/server/src/telemetry/FeatureUsage.test.ts new file mode 100644 index 0000000000000..784eb670a20e6 --- /dev/null +++ b/apps/server/src/telemetry/FeatureUsage.test.ts @@ -0,0 +1,69 @@ +import { + ORCHESTRATION_V2_WS_METHODS, + OrchestrationV2Command, + WS_METHODS, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import * as Schema from "effect/Schema"; + +import { commandFeatureUsage, featureUsage } from "./FeatureUsage.ts"; + +const command = Schema.decodeUnknownSync(OrchestrationV2Command); +const ids = { commandId: "command-private", threadId: "thread-private" }; + +it("ignores messages, housekeeping commands, and untracked RPCs", () => { + expect( + commandFeatureUsage( + command({ + ...ids, + type: "message.dispatch", + messageId: "message-private", + text: "secret prompt", + attachments: [], + createdBy: "user", + creationSource: "web", + dispatchMode: { type: "start_immediately" }, + }), + ), + ).toBe(undefined); + expect( + commandFeatureUsage( + command({ ...ids, type: "thread.visit", visitedAt: "2026-10-24T00:00:00.000Z" }), + ), + ).toBe(undefined); + expect(featureUsage(WS_METHODS.terminalWrite, { data: "rm -rf" })).toBe(undefined); +}); + +it("leaves thread launches to client.thread.started", () => { + expect( + featureUsage(ORCHESTRATION_V2_WS_METHODS.launchThread, { + title: "Private title", + workspaceStrategy: { type: "worktree", baseRef: "main", branch: "secret-branch" }, + }), + ).toBe(undefined); +}); + +it("tells watching a pull request apart from unwatching it", () => { + const watch = (watching: boolean) => + commandFeatureUsage( + command({ + ...ids, + type: "thread.pull-request.watch", + host: "github.com", + repository: "owner/private", + number: 7, + watching, + }), + ); + expect(watch(true)).toEqual({ feature: "thread.pull_request.watch", variant: "on" }); + expect(watch(false)).toEqual({ feature: "thread.pull_request.watch", variant: "off" }); +}); + +it("reads RPC variants from enums, never from paths or text", () => { + expect( + featureUsage(WS_METHODS.shellOpenInEditor, { cwd: "/Users/someone/secret", editor: "cursor" }), + ).toEqual({ feature: "editor.open", variant: "cursor" }); + expect(featureUsage(WS_METHODS.terminalOpen, { cwd: "/Users/someone/secret" })).toEqual({ + feature: "terminal.open", + }); +}); diff --git a/apps/server/src/telemetry/FeatureUsage.ts b/apps/server/src/telemetry/FeatureUsage.ts new file mode 100644 index 0000000000000..d8bcfc2e52d49 --- /dev/null +++ b/apps/server/src/telemetry/FeatureUsage.ts @@ -0,0 +1,85 @@ +import { type OrchestrationV2Command, WS_METHODS } from "@t3tools/contracts"; + +export interface FeatureUsage { + readonly feature: string; + readonly variant?: string; +} + +type Payload = Readonly>; + +const literal = (payload: Payload, key: string) => + typeof payload[key] === "string" ? (payload[key] as string) : undefined; + +const use = (feature: string, variant?: string): FeatureUsage => + variant === undefined ? { feature } : { feature, variant }; + +/** + * Exclude housekeeping and `message.dispatch`, which `client.turn.requested` already counts. + * Record at command dispatch so retries that commit no change do not count twice. + */ +const COMMAND_FEATURES: { + readonly [Type in OrchestrationV2Command["type"]]?: ( + command: Extract, + ) => FeatureUsage; +} = { + "checkpoint.rollback": (command) => ({ + feature: "checkpoint.rollback", + variant: command.restoreFiles === false ? "conversation_only" : "with_files", + }), + "thread.fork": () => ({ feature: "thread.fork" }), + "thread.merge_back": () => ({ feature: "thread.merge_back" }), + "provider.switch": () => ({ feature: "provider.switch" }), + "thread.archive": () => ({ feature: "thread.archive" }), + "thread.snooze": () => ({ feature: "thread.snooze" }), + "thread.pin": () => ({ feature: "thread.pin" }), + "thread.settle": () => ({ feature: "thread.settle" }), + "thread.pull-request.link": () => ({ feature: "thread.pull_request.link" }), + "thread.pull-request.watch": (command) => + use("thread.pull_request.watch", command.watching ? "on" : "off"), + "thread.runtime-mode.set": (command) => use("thread.runtime_mode.set", command.runtimeMode), + "thread.interaction-mode.set": (command) => + use("thread.interaction_mode.set", command.interactionMode), + "run.interrupt": () => ({ feature: "run.interrupt" }), + "queued-message.promote-to-steer": () => ({ feature: "queue.steer" }), + "queued-run.edit": () => ({ feature: "queue.edit" }), +}; + +/** + * RPCs that represent a user starting a feature. Variants come only from + * closed enums in the contracts, so no path, id, or free text can reach analytics. + * Thread launches are left out because `client.thread.started` counts them. + */ +const METHOD_FEATURES: Readonly FeatureUsage>> = { + [WS_METHODS.terminalOpen]: () => ({ feature: "terminal.open" }), + [WS_METHODS.previewOpen]: () => ({ feature: "preview.open" }), + [WS_METHODS.deviceOpen]: () => ({ feature: "device.open" }), + [WS_METHODS.shellOpenInEditor]: (payload) => use("editor.open", literal(payload, "editor")), + [WS_METHODS.vcsCreateWorktree]: () => ({ feature: "worktree.create" }), + [WS_METHODS.gitRunStackedAction]: (payload) => + use("git.stacked_action", literal(payload, "action")), + [WS_METHODS.pullRequestsRunAction]: (payload) => + use("pull_request.action", literal(payload, "action")), + [WS_METHODS.pullRequestsSubmitReview]: () => ({ feature: "pull_request.review" }), + [WS_METHODS.pullRequestsComment]: () => ({ feature: "pull_request.comment" }), + [WS_METHODS.scheduledTasksUpsert]: () => ({ feature: "scheduled_task.save" }), + [WS_METHODS.scheduledTasksRunNow]: () => ({ feature: "scheduled_task.run_now" }), + [WS_METHODS.agentSessionsImport]: () => ({ feature: "agent_session.import" }), + [WS_METHODS.projectCloneStart]: () => ({ feature: "project.clone" }), + [WS_METHODS.sourceControlPublishRepository]: () => ({ feature: "repository.publish" }), + [WS_METHODS.serverUpsertKeybinding]: () => ({ feature: "keybinding.customize" }), +}; + +/** The feature a dispatched command uses, or undefined when it is not a tracked feature. */ +export function commandFeatureUsage(command: OrchestrationV2Command): FeatureUsage | undefined { + // TypeScript cannot pair a union's tag with its own entry, so widen once here. + const mapping = COMMAND_FEATURES[command.type] as + | ((command: OrchestrationV2Command) => FeatureUsage) + | undefined; + return mapping?.(command); +} + +/** The feature a WebSocket request uses, or undefined when it is not a tracked feature. */ +export function featureUsage(method: string, payload: unknown): FeatureUsage | undefined { + if (typeof payload !== "object" || payload === null) return undefined; + return METHOD_FEATURES[method]?.(payload as Payload); +} diff --git a/apps/server/src/telemetry/Identify.test.ts b/apps/server/src/telemetry/Identify.test.ts index b556499547aad..6fa6c8500817e 100644 --- a/apps/server/src/telemetry/Identify.test.ts +++ b/apps/server/src/telemetry/Identify.test.ts @@ -10,6 +10,8 @@ import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as References from "effect/References"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts"; import * as ServerConfig from "../config.ts"; import * as Identify from "./Identify.ts"; @@ -39,28 +41,60 @@ const findIdentityLog = ( errorTag: string, ) => logs.find((log) => log.annotations.source === source && log.annotations.errorTag === errorTag); +const unsignedJwt = (claims: Readonly>) => + ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "signature"].join("."); + +const layerIdentity = (prefix: string, logs?: CapturedLog[]) => + Layer.provideMerge( + ServerSecretStore.layer, + ServerConfig.layerTest(process.cwd(), { prefix }), + ).pipe( + Layer.merge( + logs === undefined + ? Layer.empty + : Logger.layer([makeCaptureLogger(logs)], { mergeWithExisting: false }), + ), + ); + +const writeHomeFile = Effect.fn("test.writeHomeFile")(function* ( + homeDirectory: string, + relativePath: string, + contents: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const filePath = path.join(homeDirectory, relativePath); + yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true }); + yield* fileSystem.writeFileString(filePath, contents); + return filePath; +}); + it.layer(NodeServices.layer)("telemetry identity", (it) => { - it.effect("uses the persisted anonymous id when provider identities are absent", () => + it.effect("keeps the old distinct_id rule and a fixed install id as logins change", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const homeDirectory = path.join(config.baseDir, "home"); const anonymousId = "persisted-anonymous-id"; - yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId); + const installId = yield* sha256(anonymousId); + const identity = () => Identify.getTelemetryIdentityForHome(homeDirectory); - const identifier = yield* Identify.getTelemetryIdentifierForHome( - path.join(config.baseDir, "home"), - ); + assert.deepEqual(yield* identity(), { distinctId: installId, installId }); - assert.equal(identifier, yield* sha256(anonymousId)); - }).pipe( - Effect.provide( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-telemetry-identify-anonymous-", - }), - ), - ), + yield* writeHomeFile(homeDirectory, ".claude.json", `{"userID":"claude-machine"}`); + assert.deepEqual(yield* identity(), { + distinctId: yield* sha256("claude-machine"), + installId, + }); + + yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"auth_mode":"apikey"}`); + assert.equal((yield* identity()).distinctId, yield* sha256("claude-machine")); + + yield* writeHomeFile(homeDirectory, ".codex/auth.json", `{"tokens":{"account_id":"ws-1"}}`); + assert.deepEqual(yield* identity(), { distinctId: yield* sha256("ws-1"), installId }); + }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-install-"))), ); it.effect("leaves no torn anonymous id behind when its write fails midway", () => @@ -87,19 +121,77 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => { ), }); - const identifier = yield* Identify.getTelemetryIdentifierForHome( + const identity = yield* Identify.getTelemetryIdentityForHome( path.join(config.baseDir, "home"), ).pipe(Effect.provideService(FileSystem.FileSystem, tornWrites)); - assert.isNull(identifier); + assert.deepEqual(identity, { distinctId: null, installId: null }); assert.isFalse(yield* fileSystem.exists(config.anonymousIdPath)); - }).pipe( - Effect.provide( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-telemetry-identify-torn-", + }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-torn-"))), + ); + + it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => { + const logs: CapturedLog[] = []; + + return Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(config.anonymousIdPath); + + const identity = yield* Identify.getTelemetryIdentityForHome( + path.join(config.baseDir, "home"), + ); + assert.deepEqual(identity, { distinctId: null, installId: null }); + assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []); + + const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError"); + assert.equal(readLog?.annotations.filePath, config.anonymousIdPath); + assert.notEqual(readLog?.annotations.platformReason, "NotFound"); + assert.notProperty(readLog?.annotations ?? {}, "cause"); + assert.isUndefined( + findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"), + ); + }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-read-", logs))); + }); + + it.effect("reads the Connect account and each provider account as owners", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const secrets = yield* ServerSecretStore.ServerSecretStore; + const path = yield* Path.Path; + const homeDirectory = path.join(config.baseDir, "home"); + yield* secrets.set(CLOUD_LINKED_USER_ID, new TextEncoder().encode("user_connect")); + yield* writeHomeFile( + homeDirectory, + ".codex/auth.json", + JSON.stringify({ + tokens: { + account_id: "team-workspace", + id_token: unsignedJwt({ + sub: "google-oauth2|login-method", + "https://api.openai.com/auth": { user_id: "user-openai-person" }, + }), + }, }), - ), - ), + ); + yield* writeHomeFile( + homeDirectory, + ".claude.json", + JSON.stringify({ + userID: "claude-machine", + oauthAccount: { accountUuid: "claude-person" }, + }), + ); + + const owners = yield* Identify.getServerOwnersForHome(homeDirectory); + + assert.deepEqual(owners, [ + { source: "connect", ownerId: yield* sha256("user_connect") }, + { source: "openai", ownerId: yield* sha256("user-openai-person") }, + { source: "claude", ownerId: yield* sha256("claude-person") }, + ]); + }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-owners-"))), ); it.effect.each([ @@ -119,135 +211,60 @@ it.layer(NodeServices.layer)("telemetry identity", (it) => { secret: "private-personal-access-token", authJson: (secret: string) => `{"OPENAI_API_KEY":null,"personal_access_token":"${secret}"}`, }, - ])("falls back quietly when Codex authenticates with $login", ({ secret, authJson }) => { - const logs: CapturedLog[] = []; - const logger = makeCaptureLogger(logs); - - return Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const homeDirectory = path.join(config.baseDir, "home"); - const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json"); - const anonymousId = "tokenless-codex-anonymous-id"; - - yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true }); - yield* fileSystem.writeFileString(codexAuthPath, authJson(secret)); - yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId); - - const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory); - - assert.equal(identifier, yield* sha256(anonymousId)); - assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError")); - assert.isUndefined(findIdentityLog(logs, "codex", "TelemetryIdentityReadError")); - const allLogs = logs - .map((log) => - [String(log.message), ...Object.values(log.annotations).map(String)].join("\n"), - ) - .join("\n"); - assert.notInclude(allLogs, secret); - }).pipe( - Effect.provide( - Layer.merge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-telemetry-identify-tokenless-", - }), - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - ); - }); - - it.effect("logs structured decode context and falls back from malformed Codex auth", () => { - const logs: CapturedLog[] = []; - const logger = makeCaptureLogger(logs); - - return Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const homeDirectory = path.join(config.baseDir, "home"); - const codexAuthPath = path.join(homeDirectory, ".codex", "auth.json"); - const anonymousId = "decode-fallback-anonymous-id"; - const privateAccessToken = "private-codex-access-token"; - - yield* fileSystem.makeDirectory(path.dirname(codexAuthPath), { recursive: true }); - yield* fileSystem.writeFileString( - codexAuthPath, - `{"tokens":{"access_token":"${privateAccessToken}"}}`, - ); - yield* fileSystem.writeFileString(config.anonymousIdPath, anonymousId); - - const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory); - - assert.equal(identifier, yield* sha256(anonymousId)); - const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError"); - assert.isDefined(decodeLog); - assert.equal( - decodeLog?.message, - `Failed to decode codex telemetry identity at '${codexAuthPath}'.`, - ); + ])( + "adds no owner and logs nothing when Codex authenticates with $login", + ({ secret, authJson }) => { + const logs: CapturedLog[] = []; - assert.equal(decodeLog?.annotations.filePath, codexAuthPath); - assert.equal(decodeLog?.annotations.causeKind, "schema"); - assert.notProperty(decodeLog?.annotations ?? {}, "cause"); - const errorStack = decodeLog?.annotations.errorStack; - assert.isString(errorStack); - assert.include(errorStack, "Failed to decode codex telemetry identity"); - const annotations = Object.values(decodeLog?.annotations ?? {}) - .map(String) - .join("\n"); - assert.notInclude(annotations, privateAccessToken); - }).pipe( - Effect.provide( - Layer.merge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-telemetry-identify-decode-", - }), - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - ); - }); - - it.effect("does not overwrite the anonymous id path after a non-NotFound read failure", () => { - const logs: CapturedLog[] = []; - const logger = makeCaptureLogger(logs); - - return Effect.gen(function* () { - const config = yield* ServerConfig.ServerConfig; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const homeDirectory = path.join(config.baseDir, "home"); + return Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const path = yield* Path.Path; + const homeDirectory = path.join(config.baseDir, "home"); + yield* writeHomeFile(homeDirectory, ".codex/auth.json", authJson(secret)); - yield* fileSystem.makeDirectory(config.anonymousIdPath); + assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), []); + assert.deepEqual(logs, []); + }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-tokenless-", logs))); + }, + ); - const identifier = yield* Identify.getTelemetryIdentifierForHome(homeDirectory); + it.effect( + "warns about malformed Codex auth without its tokens and keeps the other owners", + () => { + const logs: CapturedLog[] = []; - assert.isNull(identifier); - assert.deepEqual(yield* fileSystem.readDirectory(config.anonymousIdPath), []); + return Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const path = yield* Path.Path; + const homeDirectory = path.join(config.baseDir, "home"); + const privateAccessToken = "private-codex-access-token"; + const codexAuthPath = yield* writeHomeFile( + homeDirectory, + ".codex/auth.json", + `{"tokens":{"access_token":"${privateAccessToken}"}}`, + ); + yield* writeHomeFile( + homeDirectory, + ".claude.json", + `{"oauthAccount":{"accountUuid":"claude-person"}}`, + ); - const readLog = findIdentityLog(logs, "anonymous", "TelemetryIdentityReadError"); - assert.isDefined(readLog); - assert.equal(readLog?.annotations.filePath, config.anonymousIdPath); - assert.equal(readLog?.annotations.causeKind, "platform"); - assert.notEqual(readLog?.annotations.platformReason, "NotFound"); - assert.notProperty(readLog?.annotations ?? {}, "cause"); - const errorStack = readLog?.annotations.errorStack; - assert.isString(errorStack); - assert.include(errorStack, "Failed to read anonymous telemetry identity"); - assert.isUndefined( - findIdentityLog(logs, "anonymous", "TelemetryAnonymousIdPersistenceError"), - ); - }).pipe( - Effect.provide( - Layer.merge( - ServerConfig.layerTest(process.cwd(), { - prefix: "t3-telemetry-identify-read-", - }), - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - ); - }); + assert.deepEqual(yield* Identify.getServerOwnersForHome(homeDirectory), [ + { source: "claude", ownerId: yield* sha256("claude-person") }, + ]); + const decodeLog = findIdentityLog(logs, "codex", "TelemetryIdentityDecodeError"); + assert.equal( + decodeLog?.message, + `Failed to decode codex telemetry identity at '${codexAuthPath}'.`, + ); + assert.equal(decodeLog?.annotations.causeKind, "schema"); + assert.notInclude( + Object.values(decodeLog?.annotations ?? {}) + .map(String) + .join("\n"), + privateAccessToken, + ); + }).pipe(Effect.provide(layerIdentity("t3-telemetry-identify-decode-", logs))); + }, + ); }); diff --git a/apps/server/src/telemetry/Identify.ts b/apps/server/src/telemetry/Identify.ts index 61c4d35359152..0baebc1e1803d 100644 --- a/apps/server/src/telemetry/Identify.ts +++ b/apps/server/src/telemetry/Identify.ts @@ -1,33 +1,66 @@ import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; -import * as Hex from "effect/encoding/Hex"; +import * as Base64Url from "effect/encoding/Base64Url"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; -import * as ServerConfig from "../config.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { hashTelemetryId } from "@t3tools/shared/telemetryId"; +import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; +import { CLOUD_LINKED_USER_ID } from "../cloud/config.ts"; +import * as ServerConfig from "../config.ts"; /** * Codex writes `tokens` only for ChatGPT logins and omits the key for API-key, * agent-identity, and personal-access-token logins, so its absence is a - * supported install and not a malformed file. + * supported install and not a malformed file. `account_id` is the ChatGPT + * workspace, which a whole Team shares; the `id_token` names the person. */ const CodexAuthJsonSchema = Schema.Struct({ tokens: Schema.optionalKey( Schema.Struct({ account_id: Schema.String, + id_token: Schema.optionalKey(Schema.String), }), ), }); +/** `userID` is random per machine. `oauthAccount` is present only while Claude Code is logged in. */ const ClaudeJsonSchema = Schema.Struct({ - userID: Schema.String, + userID: Schema.optionalKey(Schema.String), + oauthAccount: Schema.optionalKey( + Schema.Struct({ + accountUuid: Schema.optionalKey(Schema.String), + }), + ), }); +// `sub` names the login method (`google-oauth2|…`), so one person can have several. +// `user_id` (`user-…`) is the OpenAI account and is the same for every login. +const IdTokenClaims = Schema.Struct({ + "https://api.openai.com/auth": Schema.Struct({ user_id: Schema.NonEmptyString }), +}); +const decodeIdTokenClaims = Schema.decodeUnknownOption(Schema.fromJsonString(IdTokenClaims)); + +/** + * Who an install belongs to, from strongest to weakest. `connect` is the T3 + * Connect account. `openai` and `claude` are provider accounts. `device` is a + * client device that connected. + */ +export const TelemetryOwnerSource = Schema.Literals(["connect", "openai", "claude", "device"]); +export type TelemetryOwnerSource = typeof TelemetryOwnerSource.Type; + +export interface TelemetryOwner { + readonly source: TelemetryOwnerSource; + /** `hashTelemetryId` of the source's raw id. */ + readonly ownerId: string; +} + export const TelemetryIdentitySource = Schema.Literals(["codex", "claude", "anonymous"]); export type TelemetryIdentitySource = typeof TelemetryIdentitySource.Type; @@ -83,25 +116,11 @@ export class TelemetryAnonymousIdPersistenceError extends Schema.TaggedError()( - "TelemetryIdentityHashError", - { - source: TelemetryIdentitySource, - algorithm: Schema.Literal("SHA-256"), - cause: Schema.Defect(), - }, -) { - override get message(): string { - return `Failed to hash ${this.source} telemetry identity with ${this.algorithm}.`; - } -} - type TelemetryIdentityError = | TelemetryIdentityReadError | TelemetryIdentityDecodeError | TelemetryAnonymousIdGenerationError - | TelemetryAnonymousIdPersistenceError - | TelemetryIdentityHashError; + | TelemetryAnonymousIdPersistenceError; const decodeCodexAuthJson = Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema)); const decodeClaudeJson = Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema)); @@ -155,72 +174,48 @@ const readIdentityFile = ( }), ); -const hash = (source: TelemetryIdentitySource, value: string) => - Crypto.Crypto.pipe( - Effect.flatMap((crypto) => crypto.digest("SHA-256", new TextEncoder().encode(value))), - Effect.map(Hex.encode), - Effect.mapError( - (cause) => - new TelemetryIdentityHashError({ - source, - algorithm: "SHA-256", - cause, - }), - ), - ); +/** + * The OpenAI account id in a ChatGPT id_token, read without verifying it: + * analytics needs only a stable id. Codex CLI and T3's own sign-in both use it. + */ +export const openAiUserId = (idToken: string) => { + const payload = Base64Url.decodeString(idToken.split(".")[1] ?? ""); + return Result.isSuccess(payload) + ? Option.map( + decodeIdTokenClaims(payload.success), + (claims) => claims["https://api.openai.com/auth"].user_id, + ) + : Option.none(); +}; -const getCodexAccountId = Effect.fn("TelemetryIdentity.getCodexAccountId")(function* ( - homeDirectory: string, +const readJsonIdentityFile = Effect.fn("TelemetryIdentity.readJsonIdentityFile")(function* ( + source: "codex" | "claude", + filePath: string, + decode: (encoded: string) => Effect.Effect, ) { const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - - const authJsonPath = path.join(homeDirectory, ".codex", "auth.json"); - const encoded = yield* readIdentityFile(fileSystem, "codex", authJsonPath); + const encoded = yield* readIdentityFile(fileSystem, source, filePath); if (Option.isNone(encoded)) { - return Option.none(); + return Option.none(); } - const authJson = yield* decodeCodexAuthJson(encoded.value).pipe( - Effect.mapError( - (cause) => - new TelemetryIdentityDecodeError({ - source: "codex", - filePath: authJsonPath, - cause, - }), - ), + return yield* decode(encoded.value).pipe( + Effect.asSome, + Effect.mapError((cause) => new TelemetryIdentityDecodeError({ source, filePath, cause })), ); - - return authJson.tokens === undefined - ? Option.none() - : Option.some(authJson.tokens.account_id); }); -const getClaudeUserId = Effect.fn("TelemetryIdentity.getClaudeUserId")(function* ( - homeDirectory: string, -) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - - const claudeJsonPath = path.join(homeDirectory, ".claude.json"); - const encoded = yield* readIdentityFile(fileSystem, "claude", claudeJsonPath); - if (Option.isNone(encoded)) { - return Option.none(); - } - const claudeJson = yield* decodeClaudeJson(encoded.value).pipe( - Effect.mapError( - (cause) => - new TelemetryIdentityDecodeError({ - source: "claude", - filePath: claudeJsonPath, - cause, - }), - ), +// A missing or unreadable file only removes that owner; it never blocks the others. +const skipOnError = ( + effect: Effect.Effect< + Option.Option, + TelemetryIdentityReadError | TelemetryIdentityDecodeError, + R + >, +) => + effect.pipe( + Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(Option.none()))), ); - return Option.some(claudeJson.userID); -}); - const upsertAnonymousId = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const { anonymousIdPath } = yield* ServerConfig.ServerConfig; @@ -255,54 +250,92 @@ const upsertAnonymousId = Effect.gen(function* () { return anonymousId; }); -export const getTelemetryIdentifierForHome = Effect.fn("getTelemetryIdentifierForHome")( - function* (homeDirectory: string) { - const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe( - Effect.catchTags({ - TelemetryIdentityReadError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - TelemetryIdentityDecodeError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - }), - ); - if (Option.isSome(codexAccountId)) { - return yield* hash("codex", codexAccountId.value); - } - - const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe( - Effect.catchTags({ - TelemetryIdentityReadError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - TelemetryIdentityDecodeError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - }), - ); - if (Option.isSome(claudeUserId)) { - return yield* hash("claude", claudeUserId.value); - } - - const anonymousId = yield* upsertAnonymousId.pipe( - Effect.asSome, - Effect.catchTags({ - TelemetryIdentityReadError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - TelemetryAnonymousIdGenerationError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - TelemetryAnonymousIdPersistenceError: (error) => - logTelemetryIdentityError(error).pipe(Effect.as(Option.none())), - }), - ); - if (Option.isSome(anonymousId)) { - return yield* hash("anonymous", anonymousId.value); - } +const readProviderLogins = Effect.fn("TelemetryIdentity.readProviderLogins")(function* ( + homeDirectory: string, +) { + const path = yield* Path.Path; + const codexTokens = yield* readJsonIdentityFile( + "codex", + path.join(homeDirectory, ".codex", "auth.json"), + decodeCodexAuthJson, + ).pipe( + skipOnError, + Effect.map(Option.flatMap((authJson) => Option.fromUndefinedOr(authJson.tokens))), + ); + const claudeJson = yield* readJsonIdentityFile( + "claude", + path.join(homeDirectory, ".claude.json"), + decodeClaudeJson, + ).pipe(skipOnError); + return { codexTokens, claudeJson }; +}); - return null; - }, - Effect.tapError(logTelemetryIdentityError), - Effect.orElseSucceed(() => null), -); +/** + * `distinctId` preserves legacy priority: hashed Codex account_id, Claude userID, then anonymous id. + * It can change on login or be shared by a Codex Team; hashed `installId` stays stable per install. + * A null `distinctId` disables telemetry. Missing files and API-key-only Codex auth fall through; + * only unreadable or malformed files warn. + */ +export const getTelemetryIdentityForHome = Effect.fn("getTelemetryIdentityForHome")(function* ( + homeDirectory: string, +) { + const { codexTokens, claudeJson } = yield* readProviderLogins(homeDirectory); + const installId = yield* upsertAnonymousId.pipe( + Effect.map(hashTelemetryId), + Effect.catch((error) => logTelemetryIdentityError(error).pipe(Effect.as(null))), + ); + const providerId = Option.orElse( + Option.map(codexTokens, (tokens) => tokens.account_id), + () => Option.flatMap(claudeJson, (json) => Option.fromUndefinedOr(json.userID)), + ); + return { + distinctId: Option.isSome(providerId) ? hashTelemetryId(providerId.value) : installId, + installId, + }; +}); -export const getTelemetryIdentifier = Effect.flatMap( +export const getTelemetryIdentity = Effect.flatMap( HostProcess.HomeDirectory, - getTelemetryIdentifierForHome, + getTelemetryIdentityForHome, ); + +/** + * Owners the server can read without a client: the linked T3 Connect account + * and the provider logins under `homeDirectory`. Clients add `connect` and + * `device` owners when they connect. + */ +export const getServerOwnersForHome = Effect.fn("getServerOwnersForHome")(function* ( + homeDirectory: string, +) { + const secrets = yield* ServerSecretStore.ServerSecretStore; + const connectUser = yield* secrets.get(CLOUD_LINKED_USER_ID).pipe( + Effect.map(Option.map((bytes) => new TextDecoder().decode(bytes))), + Effect.catch((cause) => + Effect.logWarning("Failed to read the linked T3 Connect account for telemetry", { + errorTag: cause._tag, + }).pipe(Effect.as(Option.none())), + ), + ); + const { codexTokens, claudeJson } = yield* readProviderLogins(homeDirectory); + + const raw: ReadonlyArray]> = [ + ["connect", connectUser], + [ + "openai", + Option.flatMap(codexTokens, (tokens) => + Option.flatMap(Option.fromUndefinedOr(tokens.id_token), openAiUserId), + ), + ], + [ + "claude", + Option.flatMap(claudeJson, (json) => Option.fromUndefinedOr(json.oauthAccount?.accountUuid)), + ], + ]; + return raw.flatMap(([source, value]): ReadonlyArray => + Option.isSome(value) && value.value.trim() !== "" + ? [{ source, ownerId: hashTelemetryId(value.value) }] + : [], + ); +}); + +export const getServerOwners = Effect.flatMap(HostProcess.HomeDirectory, getServerOwnersForHome); diff --git a/apps/server/src/telemetry/ProviderDimensions.test.ts b/apps/server/src/telemetry/ProviderDimensions.test.ts new file mode 100644 index 0000000000000..d88010f600e35 --- /dev/null +++ b/apps/server/src/telemetry/ProviderDimensions.test.ts @@ -0,0 +1,78 @@ +import { ProviderInstanceId, ThreadId, type ServerProvider } from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; + +import { type AgentThread, agentToolProperties, handoffSettings } from "./ProviderDimensions.ts"; + +const provider = ( + instanceId: string, + driver: string, + models: ReadonlyArray<{ slug: string; isCustom: boolean }>, +) => + ({ + instanceId: ProviderInstanceId.make(instanceId), + driver, + models, + }) as unknown as ServerProvider; + +const providers = [ + provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]), + provider("claudeAgent", "claudeAgent", [ + { slug: "claude-opus-5-5", isCustom: false }, + { slug: "my-private-finetune", isCustom: true }, + ]), + provider("opencode", "opencode", [{ slug: "ollama/acme-internal", isCustom: false }]), +]; + +const thread = ( + instanceId: string, + model: string, + overrides: Partial = {}, +): AgentThread => ({ + modelSelection: { instanceId: ProviderInstanceId.make(instanceId), model }, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "user", + creationSource: "web", + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: ThreadId.make("t") }, + ...overrides, +}); + +it("omits custom, user-configured, and unknown models and instance names", () => { + expect( + agentToolProperties({ + tool: "t3_thread_send", + providers, + caller: thread("claudeAgent", "my-private-finetune"), + targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")], + outcome: { outcome: "ok" }, + }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({ + callerProvider, + callerModel, + targetProvider, + targetModel, + })), + ).toEqual([ + { + callerProvider: "claudeAgent", + callerModel: undefined, + targetProvider: "opencode", + targetModel: undefined, + }, + { + callerProvider: "claudeAgent", + callerModel: undefined, + targetProvider: "unknown", + targetModel: undefined, + }, + ]); +}); + +it("drops input strings outside the schema's literals, since rejected calls are recorded too", () => { + expect(handoffSettings("delegate_task", { mode: "/home/me/secret" }, undefined)).toEqual({ + targetChosen: false, + mode: "async", + }); + expect( + handoffSettings("t3_thread_launch", { workspaceStrategy: { type: "/home/me/secret" } }, {}), + ).toEqual({ targetChosen: false, workspace: "root" }); +}); diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.ts new file mode 100644 index 0000000000000..4e0447a1e2c44 --- /dev/null +++ b/apps/server/src/telemetry/ProviderDimensions.ts @@ -0,0 +1,210 @@ +import type { + ModelSelection, + OrchestrationV2ThreadShell, + ServerProvider, +} from "@t3tools/contracts"; + +/** + * Drivers whose model catalogs are published by the vendor. Other drivers + * (OpenCode, Pi, ACP agents) list models from the user's own configuration, + * such as local Ollama tags, so their model names stay out of analytics. + */ +const VENDOR_CATALOG_DRIVERS: ReadonlySet = new Set([ + "codex", + "claudeAgent", + "cursor", + "grok", + "antigravity", +]); + +export interface ProviderDimensions { + readonly provider: string; + readonly model?: string; +} + +/** + * Anonymous provider and model for a model selection. Instance ids are + * user-defined, so only the driver kind is reported. The model is reported + * only when it comes from a vendor catalog and is not a user-added custom model. + */ +export function providerDimensions( + providers: ReadonlyArray, + selection: Pick, +): ProviderDimensions { + const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId); + if (provider === undefined) return { provider: "unknown" }; + const model = provider.models.find((candidate) => candidate.slug === selection.model); + return VENDOR_CATALOG_DRIVERS.has(provider.driver) && model !== undefined && !model.isCustom + ? { provider: provider.driver, model: model.slug } + : { provider: provider.driver }; +} + +/** The thread fields agent analytics reads. Ids are used for lookups, never reported. */ +export type AgentThread = Pick< + OrchestrationV2ThreadShell, + "modelSelection" | "runtimeMode" | "interactionMode" | "createdBy" | "creationSource" | "lineage" +>; + +type Fields = Readonly>; + +const asFields = (value: unknown): Fields => + typeof value === "object" && value !== null ? (value as Fields) : {}; + +const stringField = (fields: Fields, key: string) => + typeof fields[key] === "string" ? (fields[key] as string) : undefined; + +/** A string from the tool input only when it is one of the schema's literals. */ +const oneOf = (value: string | undefined, allowed: ReadonlyArray) => + value !== undefined && allowed.includes(value) ? value : undefined; + +/** + * Whether two resolved providers differ. Unresolved selections compare as + * unknown rather than as a cross-provider handoff. + */ +export const crossProvider = (caller: string, target: string) => + caller === "unknown" || target === "unknown" ? undefined : caller !== target; + +const defined = (entries: Readonly>) => + Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined)); + +/** + * How deep a thread sits in a delegation tree: 0 for a top-level thread, 1 for + * its subagent, and so on. Forks are top-level threads of their own. Depth is + * counted by walking parents, capped so a corrupt lineage cannot loop. + */ +export const MAX_REPORTED_DEPTH = 5; + +/** + * Who started the work that made this call. Scheduled runs keep the task + * creator's provenance, so the run's message marks them instead. + */ +function callerOrigin(input: { + readonly thread: Pick; + readonly scheduledRun: boolean; +}) { + if (input.scheduledRun) return "scheduler"; + if (input.thread.createdBy === "agent") return "agent"; + return input.thread.createdBy === "system" ? "system" : "user"; +} + +/** + * Settings the agent chose for a handoff, read only from closed enums and + * booleans in the tool's arguments and result. Prompts, titles, and ids are + * never read. + */ +export function handoffSettings(tool: string, args: unknown, result: unknown): Fields { + const input = asFields(args); + const output = asFields(result); + switch (tool) { + case "delegate_task": + return defined({ + targetChosen: input.target !== undefined, + // Rejected calls are recorded too, so input strings must match a literal. + mode: oneOf(stringField(input, "mode"), ["async", "wait"]) ?? "async", + ...(output.waitTimedOut === true ? { waitTimedOut: true } : {}), + }); + case "create_threads": { + const threads = Array.isArray(input.threads) ? input.threads : []; + return { + batchSize: threads.length, + targetChosen: threads.some((thread) => asFields(thread).target !== undefined), + }; + } + case "t3_thread_launch": + return defined({ + targetChosen: input.modelSelection !== undefined, + workspace: + input.scratch === true + ? "scratch" + : (oneOf(stringField(asFields(input.workspaceStrategy), "type"), [ + "root", + "worktree", + "existing_worktree", + ]) ?? "root"), + }); + case "t3_thread_send": + return defined({ delivery: stringField(output, "delivery") }); + case "t3_thread_send_attachments": + return { delivery: "auto" }; + case "schedule_task": + return { bindToCurrentThread: input.bindToCurrentThread !== false }; + default: + return {}; + } +} + +/** Outcome of a tool call, with the stable failure code when the call failed. */ +export function toolOutcome( + result: + | { readonly isError?: boolean | undefined; readonly structuredContent?: unknown } + | undefined, +) { + if (result === undefined) return { outcome: "error", errorCode: "exception" }; + const content = asFields(result.structuredContent); + // T3 tool failures are declared errors whose structured content carries a + // closed `code`; the MCP layer does not always set isError for them. + const code = stringField(content, "code") ?? stringField(asFields(content.error), "_tag"); + if (result.isError === true || (content._tag !== undefined && code !== undefined)) { + return { outcome: "error", errorCode: code ?? "unknown" }; + } + return { outcome: "ok" }; +} + +/** + * Event properties for an agent tool call: the calling agent, and when the call + * handed work to other threads, the agents running them. Each target counts + * once, so a create_threads batch on two providers reports both. + */ +export function agentToolProperties(input: { + readonly tool: string; + readonly providers: ReadonlyArray; + readonly caller: AgentThread | undefined; + readonly callerProviderInstanceId?: ModelSelection["instanceId"]; + readonly callerDepth?: number; + readonly callerScheduledRun?: boolean; + readonly targets: ReadonlyArray; + readonly outcome: Fields; + readonly settings?: Fields; + readonly durationMs?: number; +}): ReadonlyArray>> { + const caller = + input.caller !== undefined + ? providerDimensions(input.providers, input.caller.modelSelection) + : input.callerProviderInstanceId !== undefined + ? { + provider: providerDimensions(input.providers, { + instanceId: input.callerProviderInstanceId, + model: "", + }).provider, + } + : { provider: "unknown" }; + const base = defined({ + tool: input.tool, + callerProvider: caller.provider, + callerModel: caller.model, + callerOrigin: + input.caller === undefined + ? undefined + : callerOrigin({ + thread: input.caller, + scheduledRun: input.callerScheduledRun === true, + }), + callerDepth: + input.callerDepth === undefined ? undefined : Math.min(input.callerDepth, MAX_REPORTED_DEPTH), + durationMs: input.durationMs, + ...input.outcome, + ...input.settings, + }); + if (input.targets.length === 0) return [base]; + return input.targets.map((thread) => { + const target = providerDimensions(input.providers, thread.modelSelection); + return defined({ + ...base, + targetProvider: target.provider, + targetModel: target.model, + targetRuntimeMode: thread.runtimeMode, + targetInteractionMode: thread.interactionMode, + crossProvider: crossProvider(caller.provider, target.provider), + }); + }); +} diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 65197ab61fa95..acff38ef00c37 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -4,38 +4,27 @@ import { DEFAULT_TERMINAL_ID, type TerminalAttachStreamEvent, type TerminalEvent, - type TerminalMetadataStreamEvent, type TerminalOpenInput, type TerminalRestartInput, ProviderDriverKind, ProviderInstanceId, - ServerSettingsError, TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Data from "effect/Data"; -import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Base64Url from "effect/encoding/Base64Url"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as PlatformError from "effect/PlatformError"; import * as Path from "effect/Path"; -import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as References from "effect/References"; -import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; -import * as TestClock from "effect/testing/TestClock"; -import { ChildProcessSpawner } from "effect/process"; import { expect, vi } from "vite-plus/test"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; @@ -44,6 +33,7 @@ import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as TerminalManager from "./Manager.ts"; +import { terminalOutputStream } from "./OutputProtocol.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; vi.mock("effect/SynchronizedRef", async (importOriginal) => { @@ -51,11 +41,9 @@ vi.mock("effect/SynchronizedRef", async (importOriginal) => { return { ...original, make: vi.fn(original.make) }; }); -const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); +// The server omits DOM types, which include TypeScript's WebAssembly declarations. -class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{ - readonly message: string; -}> {} +const encodeUnknownJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); class FakePtyProcess implements PtyAdapter.PtyProcess { readonly writes: string[] = []; @@ -170,25 +158,43 @@ class FakePtyAdapter { } } -const waitFor = ( - predicate: Effect.Effect, - timeout: Duration.Input = 800, -): Effect.Effect => - predicate.pipe( - Effect.filterOrFail( - (done) => done, - () => new WaitForConditionError({ message: "Condition not met" }), - ), - Effect.retry(Schedule.spaced("15 millis")), - Effect.timeoutOption(timeout), - Effect.flatMap((result) => - Option.match(result, { - onNone: () => - Effect.fail(new WaitForConditionError({ message: "Timed out waiting for condition" })), - onSome: () => Effect.void, - }), - ), - ); +// Publishes 9 MiB of output, past a stream's 8 MiB budget, while nothing pulls. +const publishPastOutputBudget = ( + manager: TerminalManager.TerminalManager["Service"], + process: FakePtyProcess, +) => + Effect.gen(function* () { + const published = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" && event.data === "last\n" + ? Deferred.succeed(published, undefined).pipe(Effect.asVoid) + : Effect.void, + ); + for (let index = 0; index < 9; index++) process.emitData("x".repeat(1024 * 1024)); + process.emitData("last\n"); + yield* Deferred.await(published); + unsubscribe(); + }); + +// Holds the next spawn, and with it the thread lock, until `release` succeeds. +class GatedPtyAdapter extends FakePtyAdapter { + gate: { + readonly spawning: Deferred.Deferred; + readonly release: Deferred.Deferred; + } | null = null; + + override spawn( + input: PtyAdapter.PtySpawnInput, + ): Effect.Effect { + const gate = this.gate; + this.gate = null; + if (!gate) return super.spawn(input); + return Deferred.succeed(gate.spawning, undefined).pipe( + Effect.andThen(Deferred.await(gate.release)), + Effect.andThen(super.spawn(input)), + ); + } +} function openInput(overrides: Partial = {}): TerminalOpenInput { return { @@ -217,23 +223,6 @@ const historyLogPath = (logsDir: string, threadId = "thread-1") => Effect.map(({ join }) => join(logsDir, `terminal_${Base64Url.encode(threadId)}.log`)), ); -const multiTerminalHistoryLogPath = ( - logsDir: string, - threadId = "thread-1", - terminalId = DEFAULT_TERMINAL_ID, -) => - Effect.service(Path.Path).pipe( - Effect.map(({ join }) => { - const threadPart = `terminal_${Base64Url.encode(threadId)}`; - return join( - logsDir, - terminalId === DEFAULT_TERMINAL_ID - ? `${threadPart}.log` - : `${threadPart}_${Base64Url.encode(terminalId)}.log`, - ); - }), - ); - interface CreateManagerOptions { shellResolver?: () => string; env?: NodeJS.ProcessEnv; @@ -248,6 +237,9 @@ interface CreateManagerOptions { >; subprocessPollIntervalMs?: number; processKillGraceMs?: number; + registerTerminalProcesses?: Parameters< + typeof TerminalManager.makeWithOptions + >[0]["registerTerminalProcesses"]; maxRetainedInactiveSessions?: number; historyByteLimit?: number; ptyAdapter?: FakePtyAdapter; @@ -298,6 +290,9 @@ const createManager = ( ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } : {}), processKillGraceMs: options.processKillGraceMs ?? 1, + ...(options.registerTerminalProcesses !== undefined + ? { registerTerminalProcesses: options.registerTerminalProcesses } + : {}), ...(options.maxRetainedInactiveSessions !== undefined ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions } : {}), @@ -416,19 +411,6 @@ it("bounds long partial lines and joins surrogate pairs across chunk boundaries" } }); -it("preserves retained lines as older storage is compacted", () => { - for (const maxLines of [3, 5_000]) { - let expected = ""; - const history = new TerminalManager.BoundedTerminalHistory(maxLines, expected); - for (let batch = 0; batch < 40; batch += 1) { - const chunk = Array.from({ length: 300 }, (_, line) => `${batch}:${line}\n`).join(""); - history.append(chunk); - expected = retainedHistory(expected + chunk, maxLines); - expect(history.value()).toBe(expected); - } - } -}); - it.layer( Layer.merge(NodeServices.layer, ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer))), { excludeTestServices: true }, @@ -450,32 +432,6 @@ it.layer( }), ); - it.effect("attaches to running sessions without restarting them", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - - yield* manager.open(openInput()); - const attachEvents = yield* Ref.make>([]); - const unsubscribe = yield* manager.attachStream( - { - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - cols: 100, - rows: 40, - }, - (event) => Ref.update(attachEvents, (events) => [...events, event]), - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot"); - expect(snapshot).toBeDefined(); - if (!snapshot || snapshot.type !== "snapshot") return; - assert.equal(snapshot.snapshot.threadId, "thread-1"); - assert.equal(snapshot.snapshot.terminalId, DEFAULT_TERMINAL_ID); - expect(ptyAdapter.spawnInputs).toHaveLength(1); - }), - ); - it.effect("keeps attach streams live when a terminal id is closed and reopened", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); @@ -501,90 +457,108 @@ it.layer( }), ); - it.effect("attaches to exited sessions without restarting them", () => + it.effect("resumed attaches after close never respawn until the terminal is reopened", () => Effect.gen(function* () { - const { manager, ptyAdapter, getEvents } = yield* createManager(); - + const { manager, ptyAdapter } = yield* createManager(); yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitExit({ exitCode: 0, signal: 0 }); - - yield* waitFor( - Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), - "1200 millis", - ); + yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); const attachEvents = yield* Ref.make>([]); const unsubscribe = yield* manager.attachStream( - openInput({ - env: { - T3CODE_WORKTREE_PATH: "/tmp/should-not-restart", - }, - worktreePath: "/tmp/should-not-restart", - }), + { ...openInput(), restartIfNotRunning: true, resume: true }, (event) => Ref.update(attachEvents, (events) => [...events, event]), ); yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot"); - expect(snapshot).toBeDefined(); - if (!snapshot || snapshot.type !== "snapshot") return; - assert.equal(snapshot.snapshot.status, "exited"); - assert.equal(snapshot.snapshot.worktreePath, null); + expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]); expect(ptyAdapter.spawnInputs).toHaveLength(1); + + yield* manager.open(openInput()); + const events = yield* Ref.get(attachEvents); + expect(events.map((event) => event.type)).toEqual(["closed", "snapshot"]); + expect(ptyAdapter.spawnInputs).toHaveLength(2); }), ); - it.effect("restarts inactive sessions from attach only when requested", () => + it.effect("resumed attaches respect closes before this server has seen a terminal", () => Effect.gen(function* () { - const { manager, ptyAdapter, getEvents } = yield* createManager(); + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.close({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + const attachEvents = yield* Ref.make>([]); + const unsubscribe = yield* manager.attachStream( + { ...openInput(), restartIfNotRunning: true, resume: true }, + (event) => Ref.update(attachEvents, (events) => [...events, event]), + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual(["closed"]); + expect(ptyAdapter.spawnInputs).toHaveLength(0); - process.emitExit({ exitCode: 0, signal: 0 }); + const restarted = yield* manager.restart(restartInput()); + expect(restarted.status).toBe("running"); + expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([ + "closed", + "restarted", + ]); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); - yield* waitFor( - Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), - "1200 millis", + it.effect("resumed attaches leave exited and evicted terminals stopped", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + maxRetainedInactiveSessions: 1, + }); + const exited = yield* Deferred.make(); + const unsubscribeEvents = yield* manager.subscribe((event) => + event.type === "exited" + ? Deferred.succeed(exited, undefined).pipe(Effect.asVoid) + : Effect.void, ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvents)); + yield* manager.open(openInput()); + ptyAdapter.processes[0]?.emitExit({ exitCode: 0, signal: 0 }); + yield* Deferred.await(exited); const attachEvents = yield* Ref.make>([]); const unsubscribe = yield* manager.attachStream( - { - ...openInput({ - env: { - T3CODE_WORKTREE_PATH: "/tmp/restart-requested", - }, - worktreePath: "/tmp/restart-requested", - }), - restartIfNotRunning: true, - }, + { ...openInput(), restartIfNotRunning: true, resume: true }, (event) => Ref.update(attachEvents, (events) => [...events, event]), ); yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + expect(yield* Ref.get(attachEvents)).toEqual([ + { type: "snapshot", snapshot: expect.objectContaining({ status: "exited" }) }, + ]); + expect(ptyAdapter.spawnInputs).toHaveLength(1); - const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot"); - expect(snapshot).toBeDefined(); - if (!snapshot || snapshot.type !== "snapshot") return; - assert.equal(snapshot.snapshot.status, "running"); - assert.equal(snapshot.snapshot.worktreePath, "/tmp/restart-requested"); + // Opening another terminal completes eviction before the next resumed attach. + yield* manager.open(openInput({ threadId: "thread-2" })); + const unsubscribeEvicted = yield* manager.attachStream( + { ...openInput(), restartIfNotRunning: true, resume: true }, + (event) => Ref.update(attachEvents, (events) => [...events, event]), + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribeEvicted)); + expect((yield* Ref.get(attachEvents)).map((event) => event.type)).toEqual([ + "snapshot", + "closed", + ]); expect(ptyAdapter.spawnInputs).toHaveLength(2); }), ); - const makeDirectory = (filePath: string) => - Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => - fs.makeDirectory(filePath, { recursive: true }), - ); - - const chmod = (filePath: string, mode: number) => - Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.chmod(filePath, mode)); + it.effect("resumed attaches recreate terminals this server has never seen", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const attachEvents = yield* Ref.make>([]); + const unsubscribe = yield* manager.attachStream({ ...openInput(), resume: true }, (event) => + Ref.update(attachEvents, (events) => [...events, event]), + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + expect(yield* Ref.get(attachEvents)).toEqual([ + { type: "snapshot", snapshot: expect.objectContaining({ status: "running" }) }, + ]); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); const pathExists = (filePath: string) => Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.exists(filePath)); @@ -597,65 +571,6 @@ it.layer( fs.writeFileString(filePath, contents), ); - it.effect("reports a missing cwd without an artificial cause", () => - Effect.gen(function* () { - const path = yield* Path.Path; - - const { manager, baseDir } = yield* createManager(); - const cwd = path.join(baseDir, "missing-cwd"); - const error = yield* Effect.flip(manager.open(openInput({ cwd }))); - - expect(error).toMatchObject({ - _tag: "TerminalCwdNotFoundError", - cwd, - }); - expect("cause" in error).toBe(false); - }), - ); - - it.effect("reports a cwd that is not a directory", () => - Effect.gen(function* () { - const path = yield* Path.Path; - - const { manager, baseDir } = yield* createManager(); - const cwd = path.join(baseDir, "cwd-file"); - yield* writeFileString(cwd, "not a directory"); - const error = yield* Effect.flip(manager.open(openInput({ cwd }))); - - expect(error).toMatchObject({ - _tag: "TerminalCwdNotDirectoryError", - cwd, - }); - expect("cause" in error).toBe(false); - }), - ); - - it.effect("preserves non-notFound cwd stat failures", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) === "win32") return; - - const path = yield* Path.Path; - - const { manager, baseDir } = yield* createManager(); - const blockedRoot = path.join(baseDir, "blocked-root"); - const blockedCwd = path.join(blockedRoot, "cwd"); - yield* makeDirectory(blockedCwd); - yield* chmod(blockedRoot, 0o000); - - const error = yield* Effect.flip(manager.open(openInput({ cwd: blockedCwd }))).pipe( - Effect.ensuring(chmod(blockedRoot, 0o755).pipe(Effect.ignore)), - ); - - expect(error).toMatchObject({ - _tag: "TerminalCwdStatError", - cwd: blockedCwd, - cause: { - _tag: "PlatformError", - }, - }); - }), - ); - it.effect("handles an exit replayed during subscription after publishing startup", () => Effect.gen(function* () { const ptyAdapter = new FakePtyAdapter(); @@ -686,801 +601,115 @@ it.layer( }), ); - it.effect("supports asynchronous PTY spawn effects", () => + it.effect("supports multiple terminals per thread independently", () => Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - ptyAdapter: new FakePtyAdapter("async"), - }); + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "term-2" })); - const snapshot = yield* manager.open(openInput()); + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; - assert.equal(snapshot.status, "running"); - expect(ptyAdapter.spawnInputs).toHaveLength(1); - expect(ptyAdapter.processes).toHaveLength(1); + yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); + yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); + + expect(first.writes).toEqual(["pwd\n"]); + expect(second.writes).toEqual(["ls\n"]); + expect(ptyAdapter.spawnInputs).toHaveLength(2); }), ); - it.effect("forwards write and resize to active pty process", () => + it.effect("closes only a thread's idle shells, ignoring a helper forked from the shell", () => Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + const { manager, ptyAdapter } = yield* createManager(5, { + processTable: Effect.succeed([ + { pid: 9000, ppid: 1, name: "zsh" }, + { pid: 100, ppid: 9000, name: "zsh" }, + { pid: 9001, ppid: 1, name: "zsh" }, + { pid: 200, ppid: 9001, name: "node" }, + { pid: 9002, ppid: 1, name: "zsh" }, + { pid: 300, ppid: 9002, name: "zsh" }, + { pid: 301, ppid: 300, name: "sleep" }, + { pid: 9003, ppid: 1, name: "zsh" }, + ]), + }).pipe(Effect.provide(layerWithHostPlatform("linux"))); + yield* manager.open(openInput({ terminalId: "idle" })); + yield* manager.open(openInput({ terminalId: "dev-server" })); + yield* manager.open(openInput({ terminalId: "subshell" })); + yield* manager.open(openInput({ threadId: "thread-2" })); - yield* manager.write({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - data: "ls\n", - }); - yield* manager.resize({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - cols: 120, - rows: 30, - }); + yield* manager.closeIdle({ threadId: "thread-1" }); - expect(process.writes).toEqual(["ls\n"]); - expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([ + true, + false, + false, + false, + ]); }), ); - it.effect("preserves structured context and causes for PTY I/O failures", () => + it.effect("keeps terminals that get input or output while closeIdle checks them", () => Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - const writeCause = new Error("PTY input handle is unavailable"); - process.writeFailure = writeCause; - const writeError = yield* Effect.flip( - manager.write({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - data: "secret input that must not be attached to the error", - }), - ); - - expect(writeError).toMatchObject({ - _tag: "TerminalWriteError", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - terminalPid: process.pid, + const ptyAdapter = new FakePtyAdapter(); + let duringCheck: (pid: number) => Effect.Effect = () => Effect.void; + const { manager } = yield* createManager(5, { + ptyAdapter, + subprocessPollIntervalMs: 60_000, + subprocessInspector: (pid) => + duringCheck(pid).pipe( + Effect.as({ hasRunningSubprocess: false, childCommand: null, processIds: [] }), + ), }); - expect(writeError.cause).toBe(writeCause); - expect(writeError).not.toHaveProperty("data"); - - const resizeCause = new Error("PTY resize handle is unavailable"); - process.resizeFailure = resizeCause; - const resizeError = yield* Effect.flip( - manager.resize({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - cols: 132, - rows: 40, - }), + const outputSeen = yield* Deferred.make(); + const unsubscribeOutput = yield* manager.subscribe((event) => + event.type === "output" + ? Deferred.succeed(outputSeen, undefined).pipe(Effect.asVoid) + : Effect.void, ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribeOutput)); + yield* manager.open(openInput({ terminalId: "typed" })); + yield* manager.open(openInput({ terminalId: "echoed" })); + const [typed, echoed] = ptyAdapter.processes; + duringCheck = (pid) => + pid === typed!.pid + ? manager + .write({ threadId: "thread-1", terminalId: "typed", data: "make build\r" }) + .pipe(Effect.orDie) + : Effect.gen(function* () { + echoed!.emitData("make build\r\n"); + yield* Deferred.await(outputSeen); + }).pipe(Effect.orDie); - expect(resizeError).toMatchObject({ - _tag: "TerminalResizeError", - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - terminalPid: process.pid, - cols: 132, - rows: 40, - }); - expect(resizeError.cause).toBe(resizeCause); + yield* manager.closeIdle({ threadId: "thread-1" }); - process.resizeFailure = undefined; - yield* manager.open(openInput({ cols: 132, rows: 40 })); - expect(process.resizeCalls).toEqual([{ cols: 132, rows: 40 }]); + expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([false, false]); }), ); - it.effect("ignores delayed resize requests after a terminal closes", () => + it.effect("caps incrementally appended history without losing partial or empty lines", () => Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); + const { manager, ptyAdapter } = yield* createManager(3); yield* manager.open(openInput()); const process = ptyAdapter.processes[0]; expect(process).toBeDefined(); if (!process) return; - yield* manager.close({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - deleteHistory: true, - }); - yield* manager.resize({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - cols: 120, - rows: 30, - }); + process.emitData("line1\n"); + process.emitData("\n"); + process.emitData("line3"); + process.emitData("-continued\nline4"); + yield* manager.close({ threadId: "thread-1" }); - expect(process.resizeCalls).toEqual([]); + const reopened = yield* manager.open(openInput()); + expect(reopened.history).toBe("\nline3-continued\nline4"); }), ); - it.effect("resizes running terminal on open when a different size is requested", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput({ cols: 100, rows: 24 })); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - const reopened = yield* manager.open(openInput({ cols: 120, rows: 30 })); - - assert.equal(reopened.status, "running"); - expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); - }), - ); - - it.effect("supports multiple terminals per thread independently", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput({ terminalId: "default" })); - yield* manager.open(openInput({ terminalId: "term-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); - yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); - - expect(first.writes).toEqual(["pwd\n"]); - expect(second.writes).toEqual(["ls\n"]); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - }), - ); - - it.effect("clears transcript and emits cleared event", () => - Effect.gen(function* () { - const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); - const path = yield* Path.Path; - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("hello\n"); - yield* waitFor( - historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); - yield* waitFor( - historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(readFileString), - Effect.map((text) => text === ""), - ), - ); - - const events = yield* getEvents; - expect(events.some((event) => event.type === "cleared")).toBe(true); - expect( - events.some( - (event) => - event.type === "cleared" && - event.threadId === "thread-1" && - event.terminalId === DEFAULT_TERMINAL_ID, - ), - ).toBe(true); - }), - ); - - it.effect("restarts terminal with empty transcript and respawns pty", () => - Effect.gen(function* () { - const { manager, ptyAdapter, logsDir } = yield* createManager(); - yield* manager.open(openInput()); - const firstProcess = ptyAdapter.processes[0]; - expect(firstProcess).toBeDefined(); - if (!firstProcess) return; - firstProcess.emitData("before restart\n"); - const path = yield* Path.Path; - yield* waitFor( - historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - - const snapshot = yield* manager.restart(restartInput()); - assert.equal(snapshot.history, ""); - assert.equal(snapshot.status, "running"); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - yield* waitFor( - historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(readFileString), - Effect.map((text) => text === ""), - ), - ); - }), - ); - - it.effect("restarts a running session when open is called with a different cwd", () => - Effect.gen(function* () { - const { manager, ptyAdapter, logsDir, baseDir } = yield* createManager(); - const path = yield* Path.Path; - const originalCwd = path.join(baseDir, "original"); - const differentCwd = path.join(baseDir, "different"); - yield* makeDirectory(originalCwd); - yield* makeDirectory(differentCwd); - - yield* manager.open(openInput({ cwd: originalCwd })); - const firstProcess = ptyAdapter.processes[0]; - expect(firstProcess).toBeDefined(); - if (!firstProcess) return; - - firstProcess.emitData("before reopen\n"); - const logPath = yield* historyLogPath(logsDir); - yield* waitFor(pathExists(logPath)); - - const reopened = yield* manager.open(openInput({ cwd: differentCwd })); - - expect(ptyAdapter.spawnInputs).toHaveLength(2); - assert.equal(firstProcess.killed, true); - assert.equal(reopened.cwd, differentCwd); - assert.equal(reopened.history, ""); - yield* waitFor(Effect.map(readFileString(logPath), (text) => text === "")); - }), - ); - - it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () => - Effect.gen(function* () { - const { manager, getEvents, baseDir } = yield* createManager(); - const path = yield* Path.Path; - const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a"); - const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b"); - yield* makeDirectory(firstWorktreePath); - yield* makeDirectory(secondWorktreePath); - const startedSnapshot = yield* manager.open( - openInput({ - cwd: firstWorktreePath, - worktreePath: firstWorktreePath, - }), - ); - const restartedSnapshot = yield* manager.restart( - restartInput({ - cwd: secondWorktreePath, - worktreePath: secondWorktreePath, - }), - ); - - assert.equal(startedSnapshot.worktreePath, firstWorktreePath); - assert.equal(restartedSnapshot.worktreePath, secondWorktreePath); - - const events = yield* getEvents; - const startedEvent = events.find( - (event): event is Extract => event.type === "started", - ); - const restartedEvent = events.find( - (event): event is Extract => - event.type === "restarted", - ); - - assert.equal(startedEvent?.snapshot.worktreePath, firstWorktreePath); - assert.equal(restartedEvent?.snapshot.worktreePath, secondWorktreePath); - }), - ); - - it.effect("preserves worktree metadata when reopening an exited session", () => - Effect.gen(function* () { - const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager(); - const path = yield* Path.Path; - const worktreePath = path.join(baseDir, "worktrees", "feature-a"); - yield* makeDirectory(worktreePath); - - yield* manager.open( - openInput({ - cwd: worktreePath, - worktreePath, - }), - ); - - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitExit({ exitCode: 0, signal: 0 }); - - yield* waitFor( - Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), - ); - - const reopenedSnapshot = yield* manager.open( - openInput({ - cwd: worktreePath, - worktreePath, - }), - ); - - assert.equal(reopenedSnapshot.worktreePath, worktreePath); - - const events = yield* getEvents; - const reopenedEvent = events - .toReversed() - .find( - (event): event is Extract => event.type === "started", - ); - - assert.equal(reopenedEvent?.snapshot.worktreePath, worktreePath); - }), - ); - - it.effect("emits exited event and reopens with clean transcript after exit", () => - Effect.gen(function* () { - const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); - const path = yield* Path.Path; - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("old data\n"); - yield* waitFor( - historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - process.emitExit({ exitCode: 0, signal: 0 }); - - yield* waitFor( - Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), - ); - const reopened = yield* manager.open(openInput()); - - assert.equal(reopened.history, ""); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - expect( - yield* historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(readFileString), - ), - ).toBe(""); - }), - ); - - it.effect("ignores trailing writes after terminal exit", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitExit({ exitCode: 0, signal: 0 }); - - yield* manager.write({ - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - data: "\r", - }); - expect(process.writes).toEqual([]); - }), - ); - - it.effect("emits subprocess activity events when child-process state changes", () => - Effect.gen(function* () { - let inspect: { - readonly hasRunningSubprocess: boolean; - readonly childCommand: string | null; - readonly processIds: ReadonlyArray; - } = { hasRunningSubprocess: false, childCommand: null, processIds: [] }; - const { manager, getEvents } = yield* createManager(5, { - subprocessInspector: () => Effect.succeed(inspect), - subprocessPollIntervalMs: 20, - }); - - yield* manager.open(openInput()); - expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false); - - inspect = { hasRunningSubprocess: true, childCommand: "vim", processIds: [100, 101] }; - yield* waitFor( - Effect.map(getEvents, (events) => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.label === "vim", - ), - ), - "1200 millis", - ); - - inspect = { hasRunningSubprocess: false, childCommand: null, processIds: [] }; - yield* waitFor( - Effect.map(getEvents, (events) => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === false && - event.label === "Terminal 1", - ), - ), - "1200 millis", - ); - }), - ); - - it.effect("does not invoke subprocess polling until a terminal session is running", () => - Effect.gen(function* () { - let checks = 0; - const { manager } = yield* createManager(5, { - subprocessInspector: () => { - checks += 1; - return Effect.succeed({ - hasRunningSubprocess: false, - childCommand: null, - processIds: [], - }); - }, - subprocessPollIntervalMs: 20, - }); - - yield* Effect.sleep("80 millis"); - assert.equal(checks, 0); - - yield* manager.open(openInput()); - yield* waitFor( - Effect.sync(() => checks > 0), - "1200 millis", - ); - }), - ); - - it.effect("derives subprocess activity for every terminal from one shared process snapshot", () => - Effect.gen(function* () { - const runCalls: Array<{ command: string; args: ReadonlyArray }> = []; - const psStdout = [" 100 9000 vim", " 101 100 git", " 200 9001 /usr/bin/python3"].join( - "\n", - ); - const processRunner: ProcessRunner.ProcessRunner["Service"] = { - run: (input) => - Effect.sync(() => { - runCalls.push({ command: input.command, args: input.args }); - return { - stdout: psStdout, - stderr: "", - code: ChildProcessSpawner.ExitCode(0), - timedOut: false, - stdoutTruncated: false, - stderrTruncated: false, - stdoutInvalidUtf8: false, - stderrInvalidUtf8: false, - }; - }), - }; - - const { manager, getEvents } = yield* createManager(5, { - subprocessPollIntervalMs: 20, - }).pipe( - Effect.provideService(ProcessRunner.ProcessRunner, processRunner), - Effect.provide(layerWithHostPlatform("linux")), - ); - - yield* manager.open(openInput()); - yield* manager.open(openInput({ threadId: "thread-2" })); - - yield* waitFor( - Effect.map( - getEvents, - (events) => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.label === "vim", - ) && - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.label === "python3", - ), - ), - "1200 millis", - ); - yield* waitFor( - Effect.sync(() => runCalls.length >= 3), - "1200 millis", - ); - - expect(runCalls.every((call) => call.args.join(" ") === "-eo pid=,ppid=,comm=")).toBe(true); - }), - ); - - it.effect("keeps last known subprocess state when the process snapshot fails", () => - Effect.gen(function* () { - let failSnapshots = false; - let failedCalls = 0; - const processRunner: ProcessRunner.ProcessRunner["Service"] = { - run: () => - Effect.sync(() => { - if (failSnapshots) failedCalls += 1; - return { - stdout: failSnapshots ? "" : " 100 9000 vim", - stderr: "", - code: ChildProcessSpawner.ExitCode(failSnapshots ? 1 : 0), - timedOut: false, - stdoutTruncated: false, - stderrTruncated: false, - stdoutInvalidUtf8: false, - stderrInvalidUtf8: false, - }; - }), - }; - - const { manager, getEvents } = yield* createManager(5, { - subprocessPollIntervalMs: 20, - }).pipe( - Effect.provideService(ProcessRunner.ProcessRunner, processRunner), - Effect.provide(layerWithHostPlatform("linux")), - ); - - yield* manager.open(openInput()); - yield* waitFor( - Effect.map(getEvents, (events) => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.label === "vim", - ), - ), - "1200 millis", - ); - - failSnapshots = true; - yield* waitFor( - Effect.sync(() => failedCalls >= 3), - "1200 millis", - ); - - const activityEvents = (yield* getEvents).filter((event) => event.type === "activity"); - expect(activityEvents.length).toBeGreaterThan(0); - expect(activityEvents.every((event) => event.hasRunningSubprocess === true)).toBe(true); - }), - ); - - it("calculates snapshot failure backoff and success reset delays", () => { - assert.equal(TerminalManager.subprocessSnapshotPollDelayMs(1_000, 0), 1_000); - assert.equal(TerminalManager.subprocessSnapshotPollDelayMs(1_000, 1), 2_000); - assert.equal(TerminalManager.subprocessSnapshotPollDelayMs(1_000, 2), 4_000); - assert.equal(TerminalManager.subprocessSnapshotPollDelayMs(1_000, 30), 60_000); - }); - - it.effect("uses process snapshots from the resource monitor", () => - Effect.gen(function* () { - let snapshotCalls = 0; - const { manager, getEvents } = yield* createManager(5, { - subprocessPollIntervalMs: 20, - processTable: Effect.sync(() => { - snapshotCalls += 1; - return [{ pid: 100, ppid: 9000, name: "ping.exe" }]; - }), - }).pipe(Effect.provide(layerWithHostPlatform("win32"))); - - yield* manager.open(openInput()); - yield* waitFor( - Effect.map(getEvents, (events) => - events.some( - (event) => - event.type === "activity" && event.hasRunningSubprocess && event.label === "ping", - ), - ), - "1200 millis", - ); - expect(snapshotCalls).toBeGreaterThan(0); - }), - ); - - it.effect("closes only a thread's idle shells, ignoring a helper forked from the shell", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - processTable: Effect.succeed([ - { pid: 9000, ppid: 1, name: "zsh" }, - { pid: 100, ppid: 9000, name: "zsh" }, - { pid: 9001, ppid: 1, name: "zsh" }, - { pid: 200, ppid: 9001, name: "node" }, - { pid: 9002, ppid: 1, name: "zsh" }, - { pid: 300, ppid: 9002, name: "zsh" }, - { pid: 301, ppid: 300, name: "sleep" }, - { pid: 9003, ppid: 1, name: "zsh" }, - ]), - }).pipe(Effect.provide(layerWithHostPlatform("linux"))); - yield* manager.open(openInput({ terminalId: "idle" })); - yield* manager.open(openInput({ terminalId: "dev-server" })); - yield* manager.open(openInput({ terminalId: "subshell" })); - yield* manager.open(openInput({ threadId: "thread-2" })); - - yield* manager.closeIdle({ threadId: "thread-1" }); - - expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([ - true, - false, - false, - false, - ]); - }), - ); - - it.effect("keeps terminals that get input or output while closeIdle checks them", () => - Effect.gen(function* () { - const ptyAdapter = new FakePtyAdapter(); - let duringCheck: (pid: number) => Effect.Effect = () => Effect.void; - const { manager, getEvents } = yield* createManager(5, { - ptyAdapter, - subprocessPollIntervalMs: 60_000, - subprocessInspector: (pid) => - duringCheck(pid).pipe( - Effect.as({ hasRunningSubprocess: false, childCommand: null, processIds: [] }), - ), - }); - yield* manager.open(openInput({ terminalId: "typed" })); - yield* manager.open(openInput({ terminalId: "echoed" })); - const [typed, echoed] = ptyAdapter.processes; - duringCheck = (pid) => - pid === typed!.pid - ? manager - .write({ threadId: "thread-1", terminalId: "typed", data: "make build\r" }) - .pipe(Effect.orDie) - : Effect.gen(function* () { - echoed!.emitData("make build\r\n"); - yield* waitFor( - Effect.map(getEvents, (events) => events.some((event) => event.type === "output")), - ); - }).pipe(Effect.orDie); - - yield* manager.closeIdle({ threadId: "thread-1" }); - - expect(ptyAdapter.processes.map((process) => process.killed)).toEqual([false, false]); - }), - ); - - it.effect("backs off the spawned fallback when the resource monitor snapshot fails", () => - Effect.gen(function* () { - const fallbackCalls: Array = []; - const processRunner: ProcessRunner.ProcessRunner["Service"] = { - run: () => - Clock.currentTimeMillis.pipe( - Effect.map((now) => { - fallbackCalls.push(now); - return { - stdout: " 100 9000 vim", - stderr: "", - code: ChildProcessSpawner.ExitCode(0), - timedOut: false, - stdoutTruncated: false, - stderrInvalidUtf8: false, - stdoutInvalidUtf8: false, - stderrTruncated: false, - }; - }), - ), - }; - - const { manager, getEvents } = yield* createManager(5, { - subprocessPollIntervalMs: 20, - processTable: Effect.fail("sidecar unavailable").pipe( - Effect.mapError((cause) => cause as never), - ), - }).pipe( - Effect.provideService(ProcessRunner.ProcessRunner, processRunner), - Effect.provide(layerWithHostPlatform("linux")), - ); - - yield* manager.open(openInput()); - yield* waitFor( - Effect.map(getEvents, (events) => - events.some( - (event) => - event.type === "activity" && - event.hasRunningSubprocess === true && - event.label === "vim", - ), - ), - "1200 millis", - ); - - yield* waitFor( - Effect.sync(() => fallbackCalls.length >= 4), - "2000 millis", - ); - const spanMs = fallbackCalls[3]! - fallbackCalls[0]!; - expect(spanMs).toBeGreaterThan(150); - }), - ); - - it.effect("coalesces live history writes while retaining the latest output on close", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const writes = yield* Queue.unbounded(); - const output = yield* Queue.unbounded(); - const trackedFileSystem = FileSystem.FileSystem.of({ - ...fs, - writeFileString: (filePath, contents, options) => - fs - .writeFileString(filePath, contents, options) - .pipe( - Effect.tap(() => (contents.length > 0 ? Queue.offer(writes, contents) : Effect.void)), - ), - }); - const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 0 }).pipe( - Effect.provideService(FileSystem.FileSystem, trackedFileSystem), - ); - yield* manager.open(openInput()); - const unsubscribe = yield* manager.subscribe((event) => - event.type === "output" ? Queue.offer(output, event.data).pipe(Effect.asVoid) : Effect.void, - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - const process = ptyAdapter.processes[0]!; - - process.emitData("first"); - yield* Queue.take(output); - yield* TestClock.adjust("200 millis"); - expect(yield* Queue.size(writes)).toBe(0); - - process.emitData(" second"); - yield* Queue.take(output); - yield* TestClock.adjust("50 millis"); - expect(yield* Queue.take(writes)).toBe("first second"); - - process.emitData(" third"); - yield* Queue.take(output); - const close = yield* manager.close({ threadId: "thread-1" }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* TestClock.adjust("250 millis"); - yield* Fiber.join(close); - expect((yield* manager.open(openInput())).history).toBe("first second third"); - }).pipe(Effect.provide(TestClock.layer())), - ); - - it.effect("caps persisted history to configured line limit", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(3); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("line1\nline2\nline3\nline4\n"); - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); - expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); - }), - ); - - it.effect("caps incrementally appended history without losing partial or empty lines", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(3); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("line1\n"); - process.emitData("\n"); - process.emitData("line3"); - process.emitData("-continued\nline4"); - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - expect(reopened.history).toBe("\nline3-continued\nline4"); - }), - ); - - it.effect("bounds persisted and attached history without truncating live output", () => + it.effect("bounds persisted and attached history without truncating live output", () => Effect.gen(function* () { const { manager, ptyAdapter, logsDir } = yield* createManager(5, { historyByteLimit: 10 }); const attachEvents = yield* Ref.make>([]); @@ -1505,61 +734,6 @@ it.layer( }), ); - it.effect.each(["current", "legacy"] as const)( - "reads only a Unicode-safe tail from oversized %s history", - (source) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - let sourcePath: string | undefined; - let closedReads = 0; - const readRequests: number[] = []; - const trackedFileSystem = FileSystem.FileSystem.of({ - ...fs, - readFileString: (candidate, encoding) => - candidate === sourcePath - ? Effect.die("History restoration must not read the whole file") - : fs.readFileString(candidate, encoding), - open: (candidate, options) => - Effect.gen(function* () { - if (candidate !== sourcePath) return yield* fs.open(candidate, options); - yield* Effect.addFinalizer(() => - Effect.sync(() => { - closedReads += 1; - }), - ); - const file = yield* fs.open(candidate, options); - return new Proxy(file, { - get(target, key) { - if (key === "read") { - return (buffer: Uint8Array) => { - readRequests.push(buffer.byteLength); - return target.read(buffer.subarray(0, 5)); - }; - } - return Reflect.get(target, key, target); - }, - }); - }), - }); - const { manager, logsDir } = yield* createManager(5, { historyByteLimit: 15 }).pipe( - Effect.provideService(FileSystem.FileSystem, trackedFileSystem), - ); - const nextPath = yield* historyLogPath(logsDir); - sourcePath = source === "current" ? nextPath : path.join(logsDir, "thread-1.log"); - yield* fs.writeFileString(sourcePath, "old".repeat(32_768) + "😀\uFEFFnewest\ré"); - - const snapshot = yield* manager.open(openInput()); - expect(snapshot.history).toBe("\uFEFFnewest\ré"); - expect(readRequests).toEqual([15, 10, 5]); - expect(closedReads).toBe(1); - expect(Buffer.from(yield* fs.readFile(nextPath)).toString()).toBe("\uFEFFnewest\ré"); - if (source === "legacy") expect(yield* fs.exists(sourcePath)).toBe(false); - yield* manager.close({ threadId: "thread-1" }); - expect((yield* manager.open(openInput())).history).toBe("\uFEFFnewest\ré"); - }), - ); - it.effect("retains plain Unicode and control characters around a split query", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); @@ -1577,27 +751,6 @@ it.layer( }), ); - it.effect("strips replay-unsafe terminal query and reply sequences from persisted history", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("prompt "); - process.emitData("\u001b[32mok\u001b[0m "); - process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007"); - process.emitData("\u001b[1;1R"); - process.emitData("done\n"); - - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - assert.equal(reopened.history, "prompt \u001b[32mok\u001b[0m done\n"); - }), - ); - it.effect("strips replayable CSI and DCS traffic while preserving setters", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); @@ -1606,348 +759,171 @@ it.layer( expect(process).toBeDefined(); if (!process) return; - process.emitData("prompt "); - process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u"); - process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\"); - process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\"); - process.emitData("\u0090$q m\u009c\u00901$r0m\u009c"); - process.emitData("\u0090+q544e\u009c\u00901+r544e=1b\u009c"); - process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u'); - process.emitData("done\n"); - - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - assert.equal(reopened.history, 'prompt \u001b[!p\u001b["p\u001b[4 q\u001b[udone\n'); - }), - ); - - it.effect("handles CSI and DCS query sequences split across output chunks", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("before "); - process.emitData("\u001b[?2026$"); - process.emitData("pafter "); - process.emitData("\u001bP$q "); - process.emitData("m\u001b"); - process.emitData("\\after "); - process.emitData("\u009b?3"); - process.emitData("1uafter "); - process.emitData("\u0090+q544e"); - process.emitData("\u009cafter\n"); - - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - assert.equal(reopened.history, "before after after after after\n"); - }), - ); - - it.effect( - "preserves clear and style control sequences while dropping chunk-split query traffic", - () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("before clear\n"); - process.emitData("\u001b[H\u001b[2J"); - process.emitData("prompt "); - process.emitData("\u001b]11;"); - process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1"); - process.emitData("R\u001b[36mdone\u001b[0m\n"); - - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - assert.equal( - reopened.history, - "before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n", - ); - }), - ); - - it.effect("does not leak final bytes from ESC sequences with intermediate bytes", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("before "); - process.emitData("\u001b(B"); - process.emitData("after\n"); - - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - assert.equal(reopened.history, "before \u001b(Bafter\n"); - }), - ); - - it.effect( - "preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", - () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("before "); - process.emitData("\u001b("); - process.emitData("Bafter\n"); - - yield* manager.close({ threadId: "thread-1" }); - - const reopened = yield* manager.open(openInput()); - assert.equal(reopened.history, "before \u001b(Bafter\n"); - }), - ); - - it.effect("deletes history file when close(deleteHistory=true)", () => - Effect.gen(function* () { - const { manager, ptyAdapter, logsDir } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("bye\n"); - const path = yield* Path.Path; - yield* waitFor( - historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - - yield* manager.close({ threadId: "thread-1", deleteHistory: true }); - expect( - yield* historyLogPath(logsDir).pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ).toBe(false); - }), - ); - - it.effect("closes all terminals for a thread when close omits terminalId", () => - Effect.gen(function* () { - const { manager, ptyAdapter, logsDir } = yield* createManager(); - yield* manager.open(openInput({ terminalId: "default" })); - yield* manager.open(openInput({ terminalId: "sidecar" })); - const defaultProcess = ptyAdapter.processes[0]; - const sidecarProcess = ptyAdapter.processes[1]; - expect(defaultProcess).toBeDefined(); - expect(sidecarProcess).toBeDefined(); - if (!defaultProcess || !sidecarProcess) return; - - defaultProcess.emitData("default\n"); - sidecarProcess.emitData("sidecar\n"); - const path = yield* Path.Path; - yield* waitFor( - multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - yield* waitFor( - multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - - yield* manager.close({ threadId: "thread-1", deleteHistory: true }); - - assert.equal(defaultProcess.killed, true); - assert.equal(sidecarProcess.killed, true); - expect( - yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ).toBe(false); - expect( - yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ).toBe(false); - }), - ); - - it.effect("escalates terminal shutdown to SIGKILL when process does not exit in time", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10 }); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + process.emitData("prompt "); + process.emitData("\u001b[?2026$p\u001b[?2026;2$y\u001b[>q\u001b[?u\u001b[?31u"); + process.emitData("\u001bP$q m\u001b\\\u001bP1$r0m\u001b\\"); + process.emitData("\u001bP+q544e\u001b\\\u001bP1+r544e=1b\u001b\\"); + process.emitData("\u0090$q m\u009c\u00901$r0m\u009c"); + process.emitData("\u0090+q544e\u009c\u00901+r544e=1b\u009c"); + process.emitData('\u001b[!p\u001b["p\u001b[4 q\u001b[u'); + process.emitData("done\n"); - const closeFiber = yield* manager.close({ threadId: "thread-1" }).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* TestClock.adjust("10 millis"); - yield* Fiber.join(closeFiber); + yield* manager.close({ threadId: "thread-1" }); - assert.equal(process.killSignals[0], "SIGTERM"); - expect(process.killSignals).toContain("SIGKILL"); - }).pipe(Effect.provide(TestClock.layer())), + const reopened = yield* manager.open(openInput()); + expect(reopened.history.startsWith('prompt \u001b[!p\u001b["p\u001b[4 q\u001b[udone\n')).toBe( + true, + ); + }), ); - it.effect("skips SIGKILL when the process exits during the grace period", () => + it.effect("handles CSI and DCS query sequences split across output chunks", () => Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10_000 }); + const { manager, ptyAdapter } = yield* createManager(); yield* manager.open(openInput()); const process = ptyAdapter.processes[0]; expect(process).toBeDefined(); if (!process) return; - const sigterm = yield* Deferred.make(); - process.onKill = (signal) => { - if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void); - }; + process.emitData("before "); + process.emitData("\u001b[?2026$"); + process.emitData("pafter "); + process.emitData("\u001bP$q "); + process.emitData("m\u001b"); + process.emitData("\\after "); + process.emitData("\u009b?3"); + process.emitData("1uafter "); + process.emitData("\u0090+q544e"); + process.emitData("\u009cafter\n"); yield* manager.close({ threadId: "thread-1" }); - yield* Deferred.await(sigterm); - process.emitExit({ exitCode: 0, signal: 15 }); - yield* TestClock.adjust("10 seconds"); - assert.deepEqual(process.killSignals, ["SIGTERM"]); - }).pipe(Effect.provide(TestClock.layer())), + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before after after after after\n"); + }), ); - it.effect("does not retain a kill fiber that finishes before registration", () => + it.effect("preserves large chunked OSC 52 and DCS strings across reopen", () => Effect.gen(function* () { - let managerState: - | SynchronizedRef.SynchronizedRef<{ - killFibers: Map>; - }> - | undefined; - const originalMake = (value: A) => Effect.sync(() => SynchronizedRef.makeUnsafe(value)); - const makeSpy = vi.spyOn(SynchronizedRef, "make").mockImplementation((value) => - originalMake(value).pipe( - Effect.map((ref) => { - if (typeof value === "object" && value !== null && "killFibers" in value) { - managerState = ref as typeof managerState; - } - return ref; + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]!; + const outputSeen = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" && event.data === "done\n" + ? Deferred.succeed(outputSeen, undefined).pipe(Effect.asVoid) + : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + const sequences = [ + { prefix: `\u001b]52;c;${"YWJj".repeat(16_384)}\u001b`, terminator: "\\" }, + { prefix: `\u0090q${"?".repeat(65_536)}`, terminator: "\u009c" }, + ]; + const stripped = "\u001b]11;?\u0007\u0090$q m\u009c"; + const preserved = "\u001b[31m\u009d52;c;YWJj\u009c"; + const expected = + sequences.map(({ prefix, terminator }) => prefix + terminator + preserved).join("") + + "done\n"; + + // Counts reads of strings larger than one emitted chunk, so rescanning the + // pending prefix on every chunk shows up as quadratic work. + const charCodeAt = String.prototype.charCodeAt; + let largeStringReads = 0; + yield* Effect.gen(function* () { + // eslint-disable-next-line no-extend-native -- Count reads without retaining millions of spy call records. + String.prototype.charCodeAt = function (this: string, index: number) { + if (this.length > 4_096) largeStringReads += 1; + return charCodeAt.call(this, index); + }; + for (const { prefix, terminator } of sequences) { + for (let offset = 0; offset < prefix.length; offset += 4_096) { + process.emitData(prefix.slice(offset, offset + 4_096)); + } + process.emitData(terminator + stripped + preserved); + } + process.emitData("done\n"); + yield* Deferred.await(outputSeen); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + // eslint-disable-next-line no-extend-native -- Restore the counting hook even when the test fails. + String.prototype.charCodeAt = charCodeAt; }), ), ); - yield* Effect.addFinalizer(() => Effect.sync(() => makeSpy.mockRestore())); - for (const budget of [10, 15, 20, 25, 30, 40, 50, 75, 100, 150, 200, 500]) { - const { manager, ptyAdapter } = yield* createManager(); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]!; - process.onKill = () => process.emitExit({ exitCode: 0, signal: 15 }); - // Vary the caller's operation budget to cover child completion before - // and after the parent resumes its registration step. - yield* manager - .close({ threadId: "thread-1" }) - .pipe(Effect.provideService(References.MaxOpsBeforeYield, budget)); - yield* Effect.yieldNow; - expect(managerState).toBeDefined(); - yield* Fiber.awaitAll(SynchronizedRef.getUnsafe(managerState!).killFibers.values()); - expect(SynchronizedRef.getUnsafe(managerState!).killFibers.size, `budget ${budget}`).toBe( - 0, - ); - expect(process.killSignals).toEqual(["SIGTERM"]); - } + yield* manager.close({ threadId: "thread-1" }); + + expect(largeStringReads).toBeLessThan(2 * expected.length); + expect(yield* readFileString(yield* historyLogPath(logsDir))).toBe(expected); + expect((yield* manager.open(openInput())).history.startsWith(expected)).toBe(true); }), ); - it.effect("releases the exit listener when kill escalation is interrupted", () => - Effect.gen(function* () { - const scope = yield* Scope.make("sequential"); - const { manager, ptyAdapter } = yield* createManager(5, { - processKillGraceMs: 10_000, - }).pipe(Effect.provideService(Scope.Scope, scope)); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + it.effect( + "preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - const sigterm = yield* Deferred.make(); - process.onKill = (signal) => { - if (signal === "SIGTERM") Deferred.doneUnsafe(sigterm, Effect.void); - }; - yield* manager.close({ threadId: "thread-1" }); - yield* Deferred.await(sigterm); - assert.isAbove(process.exitListenerCount, 0); + process.emitData("before "); + process.emitData("\u001b("); + process.emitData("Bafter\n"); - yield* Scope.close(scope, Exit.void); + yield* manager.close({ threadId: "thread-1" }); - assert.equal(process.exitListenerCount, 0); - assert.deepEqual(process.killSignals, ["SIGTERM"]); - }).pipe(Effect.provide(TestClock.layer())), + const reopened = yield* manager.open(openInput()); + expect(reopened.history.startsWith("before \u001b(Bafter\n")).toBe(true); + }), ); - it.effect("publishes closed events when terminals are explicitly closed", () => + it.effect.each([ + { + label: "subagent", + threadId: + "thread:provider:claudeAgent:native-thread:provider-thread%3Aprovider%3AclaudeAgent%3Anative-thread%3Apending%253Arun%253Athread%253A9175fb53-52d7-4d4d-9be7-25a76cf84b91%253Aordinal%253A7%3Aad899ae84c7a131b0", + }, + // Also too long for the legacy `.log` lookup. + { label: "300-character", threadId: "x".repeat(300) }, + ])("persists history for a $label thread id too long to encode into a filename", ({ threadId }) => Effect.gen(function* () { - const { manager, getEvents } = yield* createManager(); - yield* manager.open(openInput({ terminalId: "default" })); - yield* manager.open(openInput({ terminalId: "sidecar" })); + const terminalId = "t".repeat(128); + const { manager, ptyAdapter, logsDir } = yield* createManager(); + const fs = yield* FileSystem.FileSystem; + yield* manager.open(openInput({ threadId })); + yield* manager.open(openInput({ threadId, terminalId })); + ptyAdapter.processes[0]!.emitData("default\n"); + ptyAdapter.processes[1]!.emitData("long\n"); + yield* manager.close({ threadId }); - yield* manager.close({ threadId: "thread-1" }); + expect((yield* manager.open(openInput({ threadId }))).history).toBe("default\n"); + expect((yield* manager.open(openInput({ threadId, terminalId }))).history).toBe("long\n"); - const closedEvents = (yield* getEvents).filter( - (event): event is Extract => event.type === "closed", - ); - expect(closedEvents.map((event) => event.terminalId).sort()).toEqual(["default", "sidecar"]); + yield* manager.close({ threadId, deleteHistory: true }); + expect(yield* fs.readDirectory(logsDir)).toEqual([]); }), ); - it.effect("evicts oldest inactive terminal sessions when retention limit is exceeded", () => + it.effect("keeps reading and deleting history at an encoded path that already fit", () => Effect.gen(function* () { - const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(5, { - maxRetainedInactiveSessions: 1, - }); - - yield* manager.open(openInput({ threadId: "thread-1" })); - yield* manager.open(openInput({ threadId: "thread-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - first.emitData("first-history\n"); - second.emitData("second-history\n"); - const path = yield* Path.Path; - yield* waitFor( - historyLogPath(logsDir, "thread-1").pipe( - Effect.provideService(Path.Path, path), - Effect.flatMap(pathExists), - ), - ); - first.emitExit({ exitCode: 0, signal: 0 }); - yield* Effect.sleep(Duration.millis(5)); - second.emitExit({ exitCode: 0, signal: 0 }); - - yield* waitFor( - Effect.map( - getEvents, - (events) => events.filter((event) => event.type === "exited").length === 2, - ), - ); + const threadId = "x".repeat(120); + const { manager, logsDir } = yield* createManager(); + const fs = yield* FileSystem.FileSystem; + const logPath = yield* historyLogPath(logsDir, threadId); + yield* fs.makeDirectory(logsDir, { recursive: true }); + yield* fs.writeFileString(logPath, "before upgrade\n"); - const reopenedSecond = yield* manager.open(openInput({ threadId: "thread-2" })); - const reopenedFirst = yield* manager.open(openInput({ threadId: "thread-1" })); + expect((yield* manager.open(openInput({ threadId }))).history).toBe("before upgrade\n"); + // A long terminal id pushes only this terminal's name past the limit, so the thread's + // history is split across both forms and deleting the thread must remove both. + yield* manager.open(openInput({ threadId, terminalId: "t".repeat(128) })); - assert.equal(reopenedFirst.history, "first-history\n"); - assert.equal(reopenedSecond.history, ""); + yield* manager.close({ threadId, deleteHistory: true }); + expect(yield* fs.exists(logPath)).toBe(false); + expect(yield* fs.readDirectory(logsDir)).toEqual([]); }), ); @@ -2005,27 +981,6 @@ it.layer( }), ); - it.effect("prefers PowerShell over ComSpec for Windows terminals", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - env: { - ComSpec: "C:\\Windows\\System32\\cmd.exe", - PATH: "C:\\Windows\\System32", - SystemRoot: "C:\\Windows", - }, - }).pipe(Effect.provide(layerWithHostPlatform("win32"))); - - yield* manager.open(openInput()); - - expect(ptyAdapter.spawnInputs[0]).toEqual( - expect.objectContaining({ - shell: "pwsh.exe", - args: ["-NoLogo"], - }), - ); - }), - ); - it.effect("preserves Windows Path casing when appending managed ACP binaries", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -2119,30 +1074,77 @@ it.layer( }), ); - it.effect.each(["linux", "darwin", "win32"] as const)( - "advertises truecolor before the PTY backend on %s without replacing explicit values", - (platform) => - Effect.gen(function* () { - for (const [parentColor, runtimeColor, expected] of [ - [undefined, undefined, "truecolor"], - ["", undefined, "truecolor"], - ["24bit", undefined, "24bit"], - ["24bit", "", ""], - [undefined, "", ""], - ["24bit", "custom", "custom"], - ] as const) { - const env = Object.freeze({ COLORTERM: parentColor }); - const { manager, ptyAdapter } = yield* createManager(5, { - shellResolver: () => "/bin/sh", - env, - }).pipe(Effect.provide(layerWithHostPlatform(platform))); - yield* manager.open( - openInput({ env: runtimeColor === undefined ? {} : { COLORTERM: runtimeColor } }), - ); - expect(ptyAdapter.spawnInputs[0]?.env.COLORTERM).toBe(expected); - expect(env.COLORTERM).toBe(parentColor); - } - }), + it.effect("turns off fish terminal queries unless the user chose query-term", () => + Effect.gen(function* () { + for (const [platform, env, runtimeEnv, expected] of [ + ["linux", {}, {}, { fish_features: "no-query-term" }], + [ + "linux", + { fish_features: "qmark-noglob" }, + {}, + { fish_features: "qmark-noglob,no-query-term" }, + ], + [ + "linux", + { fish_features: "qmark-noglob,query-term" }, + {}, + { fish_features: "qmark-noglob,query-term" }, + ], + [ + "linux", + { fish_features: "qmark-noglob,no-query-term" }, + {}, + { fish_features: "qmark-noglob,no-query-term" }, + ], + [ + "linux", + { fish_features: "query-term" }, + { fish_features: "qmark-noglob" }, + { fish_features: "qmark-noglob,no-query-term" }, + ], + [ + "win32", + { FISH_FEATURES: "qmark-noglob" }, + {}, + { FISH_FEATURES: "qmark-noglob,no-query-term" }, + ], + [ + "win32", + { Fish_Features: "qmark-noglob,query-term" }, + {}, + { Fish_Features: "qmark-noglob,query-term" }, + ], + [ + "win32", + { FISH_FEATURES: "qmark-noglob,no-query-term" }, + {}, + { FISH_FEATURES: "qmark-noglob,no-query-term" }, + ], + [ + "win32", + { Fish_Features: "query-term" }, + { fish_features: "qmark-noglob" }, + { Fish_Features: "qmark-noglob,no-query-term" }, + ], + [ + "win32", + { FISH_FEATURES: "no-query-term" }, + { fish_features: "qmark-noglob,query-term" }, + { FISH_FEATURES: "qmark-noglob,query-term" }, + ], + ] as const) { + const { manager, ptyAdapter } = yield* createManager(5, { + env, + }).pipe(Effect.provide(layerWithHostPlatform(platform))); + yield* manager.open(openInput({ env: runtimeEnv })); + const fishFeatures = Object.fromEntries( + Object.entries(ptyAdapter.spawnInputs[0]!.env).filter( + ([key]) => key.toLowerCase() === "fish_features", + ), + ); + expect.soft(fishFeatures, JSON.stringify({ platform, env, runtimeEnv })).toEqual(expected); + } + }), ); it.effect("filters app runtime env variables from terminal sessions", () => @@ -2153,9 +1155,14 @@ it.layer( T3CODE_PORT: "3773", VITE_DEV_SERVER_URL: "http://localhost:5173", TEST_TERMINAL_KEEP: "keep-me", + TMUX: "/tmp/tmux-1000/default,1234,0", + TMUX_PANE: "%3", + ZELLIJ_SESSION_NAME: "work", + ZELLIJ_CONFIG_DIR: "/home/user/.config/zellij", }, }); yield* manager.open(openInput()); + yield* manager.open(openInput({ terminalId: "explicit", env: { TMUX_PANE: "%9" } })); const spawnInput = ptyAdapter.spawnInputs[0]; expect(spawnInput).toBeDefined(); if (!spawnInput) return; @@ -2164,26 +1171,11 @@ it.layer( expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); - }), - ); - - it.effect("expands provider home paths passed to setup terminals", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5); - - yield* manager.open({ - ...openInput(), - env: { - CODEX_HOME: "~/.codex-work", - CLAUDE_CONFIG_DIR: "~/.claude-work", - CUSTOM_ACCOUNT: "~/leave-this-value-alone", - }, - }); - - const environment = ptyAdapter.spawnInputs[0]?.env; - expect(environment?.CODEX_HOME).toMatch(/[\\/][.]codex-work$/); - expect(environment?.CLAUDE_CONFIG_DIR).toMatch(/[\\/][.]claude-work$/); - expect(environment?.CUSTOM_ACCOUNT).toBe("~/leave-this-value-alone"); + expect(spawnInput.env.TMUX).toBeUndefined(); + expect(spawnInput.env.TMUX_PANE).toBeUndefined(); + expect(spawnInput.env.ZELLIJ_SESSION_NAME).toBeUndefined(); + expect(spawnInput.env.ZELLIJ_CONFIG_DIR).toBe("/home/user/.config/zellij"); + expect(ptyAdapter.spawnInputs[1]?.env.TMUX_PANE).toBe("%9"); }), ); @@ -2220,52 +1212,6 @@ it.layer( }), ); - it.effect("leaves the environment untouched when not launched from an AppImage", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - env: { - PATH: "/usr/local/bin:/usr/bin:/bin", - LD_LIBRARY_PATH: "/home/user/.local/lib", - OWD: "/home/user/keep-this", - }, - }); - yield* manager.open(openInput()); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; - - expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin"); - expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib"); - expect(spawnInput.env.OWD).toBe("/home/user/keep-this"); - }), - ); - - it.effect("injects runtime env overrides into spawned terminals", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { env: { FORCE_COLOR: "3" } }); - yield* manager.open( - openInput({ - env: { - T3CODE_PROJECT_ROOT: "/repo", - T3CODE_WORKTREE_PATH: "/repo/worktree-a", - CUSTOM_FLAG: "1", - NO_COLOR: "1", - FORCE_COLOR: "0", - }, - }), - ); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; - - assert.equal(spawnInput.env.T3CODE_PROJECT_ROOT, "/repo"); - assert.equal(spawnInput.env.T3CODE_WORKTREE_PATH, "/repo/worktree-a"); - assert.equal(spawnInput.env.CUSTOM_FLAG, "1"); - assert.equal(spawnInput.env.NO_COLOR, "1"); - assert.equal(spawnInput.env.FORCE_COLOR, "0"); - }), - ); - it.effect("resolves a provider instance environment before spawning", () => Effect.gen(function* () { const providerInstanceId = ProviderInstanceId.make("codex_work"); @@ -2306,148 +1252,56 @@ it.layer( const error = yield* manager.open(openInput({ providerInstanceId })).pipe(Effect.flip); - assert.deepStrictEqual( - error, - new TerminalProviderInstanceNotFoundError({ providerInstanceId }), - ); - expect(ptyAdapter.spawnInputs).toHaveLength(0); - }), - ); - - it.effect("preserves the settings failure when provider environment resolution fails", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const providerInstanceId = ProviderInstanceId.make("codex_work"); - const settingsCause = new Error("secret store read failed"); - const settingsError = new ServerSettingsError({ - settingsPath: "/test/settings.json", - operation: "read-secret", - providerInstanceId, - environmentVariable: "OPENROUTER_API_KEY", - cause: settingsCause, - }); - const serverSettings = ServerSettings.ServerSettingsService.of({ - start: Effect.void, - ready: Effect.void, - getSettings: Effect.fail(settingsError), - updateSettings: () => Effect.fail(settingsError), - updateProviderInstance: () => Effect.fail(settingsError), - withSettingsSnapshot: () => Effect.fail(settingsError), - streamChanges: Stream.empty, - subscribeChanges: Effect.succeed(Stream.empty), - }); - - const error = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ - serverSettings, - path, - rawProviderInstanceId: providerInstanceId, - env: undefined, - }).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "TerminalProviderEnvironmentError", - providerInstanceId, - }); - expect(error.cause).toBe(settingsError); - expect(error.message).not.toContain(settingsError.message); - expect(error.message).not.toContain("OPENROUTER_API_KEY"); - }), - ); - - it.effect.each([ - { - name: "Codex home", - driver: "codex", - variable: "CODEX_HOME", - config: { homePath: "/configured/codex" }, - expectedHome: "/configured/codex", - }, - { - name: "Codex shadow home", - driver: "codex", - variable: "CODEX_HOME", - config: { homePath: "/configured/codex", shadowHomePath: "/configured/codex-shadow" }, - expectedHome: "/configured/codex-shadow", - }, - { - name: "Claude home", - driver: "claudeAgent", - variable: "CLAUDE_CONFIG_DIR", - config: { homePath: "/configured/claude" }, - expectedHome: "/configured/claude", - }, - ])("prefers $name over the instance environment", ({ driver, variable, config, expectedHome }) => - Effect.gen(function* () { - const path = yield* Path.Path; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ - serverSettings, - path, - rawProviderInstanceId: "configured_home", - env: undefined, - }); - - expect(environment[variable]).toBe(path.resolve(expectedHome)); - }).pipe( - Effect.provide( - ServerSettings.layerTest({ - providerInstances: { - [ProviderInstanceId.make("configured_home")]: { - driver: ProviderDriverKind.make(driver), - environment: [{ name: variable, value: "~/.environment-account", sensitive: false }], - config, - }, - }, - }), - ), - ), - ); - - it.effect("resolves the Codex default slot", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ - serverSettings, - path, - rawProviderInstanceId: "codex", - env: undefined, - }); - - expect(environment.CODEX_HOME).toMatch(/[\\/][.]codex-default$/); - }).pipe( - Effect.provide( - ServerSettings.ServerSettingsService.layerTest({ - providerInstances: { - [ProviderInstanceId.make("codex")]: { - driver: ProviderDriverKind.make("codex"), - config: { homePath: "~/.codex-default" }, - }, - }, - }), - ), - ), + assert.deepStrictEqual( + error, + new TerminalProviderInstanceNotFoundError({ providerInstanceId }), + ); + expect(ptyAdapter.spawnInputs).toHaveLength(0); + }), ); - it.effect("resolves the Claude default slot", () => + it.effect.each([ + { + name: "Codex home", + driver: "codex", + variable: "CODEX_HOME", + config: { homePath: "/configured/codex" }, + expectedHome: "/configured/codex", + }, + { + name: "Codex shadow home", + driver: "codex", + variable: "CODEX_HOME", + config: { homePath: "/configured/codex", shadowHomePath: "/configured/codex-shadow" }, + expectedHome: "/configured/codex-shadow", + }, + { + name: "Claude home", + driver: "claudeAgent", + variable: "CLAUDE_CONFIG_DIR", + config: { homePath: "/configured/claude" }, + expectedHome: "/configured/claude", + }, + ])("prefers $name over the instance environment", ({ driver, variable, config, expectedHome }) => Effect.gen(function* () { const path = yield* Path.Path; const serverSettings = yield* ServerSettings.ServerSettingsService; const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ serverSettings, path, - rawProviderInstanceId: "claudeAgent", + rawProviderInstanceId: "configured_home", env: undefined, }); - expect(environment.CLAUDE_CONFIG_DIR).toMatch(/[\\/][.]claude-default$/); + expect(environment[variable]).toBe(path.resolve(expectedHome)); }).pipe( Effect.provide( - ServerSettings.ServerSettingsService.layerTest({ + ServerSettings.layerTest({ providerInstances: { - [ProviderInstanceId.make("claudeAgent")]: { - driver: ProviderDriverKind.make("claudeAgent"), - config: { homePath: "~/.claude-default" }, + [ProviderInstanceId.make("configured_home")]: { + driver: ProviderDriverKind.make(driver), + environment: [{ name: variable, value: "~/.environment-account", sensitive: false }], + config, }, }, }), @@ -2455,41 +1309,6 @@ it.layer( ), ); - it.effect("resolves an empty Codex default slot with default config", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const environment = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ - serverSettings, - path, - rawProviderInstanceId: "codex", - env: { CODEX_HOME: "/inherited/codex-home" }, - }); - - expect(environment.CODEX_HOME).toBe("/inherited/codex-home"); - }).pipe( - Effect.provide(ServerSettings.ServerSettingsService.layerTest({ providerInstances: {} })), - ), - ); - - it.effect("keeps unknown provider instance ids unavailable after default-slot hydration", () => - Effect.gen(function* () { - const path = yield* Path.Path; - const serverSettings = yield* ServerSettings.ServerSettingsService; - const error = yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ - serverSettings, - path, - rawProviderInstanceId: "codex_unknown", - env: undefined, - }).pipe(Effect.flip); - - expect(error).toMatchObject({ - _tag: "TerminalProviderInstanceNotFoundError", - providerInstanceId: "codex_unknown", - }); - }).pipe(Effect.provide(ServerSettings.ServerSettingsService.layerTest())), - ); - it.effect("restarts a running terminal when the resolved provider environment changes", () => Effect.gen(function* () { const providerInstanceId = ProviderInstanceId.make("codex_work"); @@ -2618,148 +1437,6 @@ it.layer( }), ); - it.effect("fails closed when attaching would create a missing provider terminal", () => - Effect.gen(function* () { - const providerInstanceId = ProviderInstanceId.make("deleted_instance"); - const { manager, ptyAdapter } = yield* createManager(5, { - resolveProviderInstanceEnvironment: (requestedId) => - Effect.fail( - new TerminalProviderInstanceNotFoundError({ - providerInstanceId: ProviderInstanceId.make(requestedId), - }), - ), - }); - - const error = yield* manager - .attachStream(openInput({ providerInstanceId }), () => Effect.void) - .pipe(Effect.flip); - - assert.deepStrictEqual( - error, - new TerminalProviderInstanceNotFoundError({ providerInstanceId }), - ); - expect(ptyAdapter.spawnInputs).toHaveLength(0); - }), - ); - - it.effect("starts zsh with prompt spacer disabled to avoid `%` end markers", () => - Effect.gen(function* () { - if ((yield* HostProcess.Platform) === "win32") return; - const { manager, ptyAdapter } = yield* createManager(5, { - shellResolver: () => "/bin/zsh", - }); - yield* manager.open(openInput()); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; - - expect(spawnInput.args).toEqual(["-o", "nopromptsp"]); - }), - ); - - it.effect("bridges PTY callbacks back into Effect-managed event streaming", () => - Effect.gen(function* () { - const { manager, ptyAdapter, getEvents } = yield* createManager(5, { - ptyAdapter: new FakePtyAdapter("async"), - }); - - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("hello from callback\n"); - - yield* waitFor( - Effect.map(getEvents, (events) => - events.some((event) => event.type === "output" && event.data === "hello from callback\n"), - ), - "1200 millis", - ); - }), - ); - - it.effect("pushes PTY callbacks to direct event subscribers", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - ptyAdapter: new FakePtyAdapter("async"), - }); - const subscriberEvents = yield* Ref.make>([]); - const unsubscribe = yield* manager.subscribe((event) => - Ref.update(subscriberEvents, (events) => [...events, event]), - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("hello from subscriber\n"); - - yield* waitFor( - Effect.map(Ref.get(subscriberEvents), (events) => - events.some( - (event) => event.type === "output" && event.data === "hello from subscriber\n", - ), - ), - "1200 millis", - ); - }), - ); - - it.effect("subscribes terminal metadata with an initial snapshot and live deltas", () => - Effect.gen(function* () { - const { manager } = yield* createManager(); - yield* manager.open(openInput({ threadId: "existing-thread" })); - - const metadataEvents = yield* Ref.make>([]); - const unsubscribe = yield* manager.subscribeMetadata((event) => - Ref.update(metadataEvents, (events) => [...events, event]), - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - const initialEvents = yield* Ref.get(metadataEvents); - expect(initialEvents[0]).toMatchObject({ - type: "snapshot", - terminals: [ - { - threadId: "existing-thread", - terminalId: DEFAULT_TERMINAL_ID, - }, - ], - }); - - yield* manager.open(openInput({ threadId: "new-thread" })); - - yield* waitFor( - Effect.map(Ref.get(metadataEvents), (events) => - events.some( - (event) => - event.type === "upsert" && - event.terminal.threadId === "new-thread" && - event.terminal.terminalId === DEFAULT_TERMINAL_ID, - ), - ), - "1200 millis", - ); - - yield* manager.close({ threadId: "new-thread", terminalId: DEFAULT_TERMINAL_ID }); - - yield* waitFor( - Effect.map(Ref.get(metadataEvents), (events) => - events.some( - (event) => - event.type === "remove" && - event.threadId === "new-thread" && - event.terminalId === DEFAULT_TERMINAL_ID, - ), - ), - "1200 millis", - ); - }), - ); - it.effect("removes terminal metadata subscriptions when initial delivery fails", () => Effect.gen(function* () { const { manager } = yield* createManager(); @@ -2781,45 +1458,152 @@ it.layer( }), ); - it.effect( - "streams attach snapshots followed by live events without duplicate start snapshots", - () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - ptyAdapter: new FakePtyAdapter("async"), - }); - const attachEvents = yield* Ref.make>([]); - const unsubscribe = yield* manager.attachStream(openInput(), (event) => - Ref.update(attachEvents, (events) => [...events, event]), - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + it.effect("finishes shell startup when its creating attachment is cancelled", () => + Effect.gen(function* () { + const ptyAdapter = new GatedPtyAdapter(); + const { manager } = yield* createManager(5, { ptyAdapter }); + const input = openInput(); + const gate = { + spawning: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + ptyAdapter.gate = gate; + const consumer = yield* Stream.runDrain( + terminalOutputStream( + (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup), + (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup), + ), + ).pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(gate.spawning); + const cancelled = yield* Fiber.interrupt(consumer).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.succeed(gate.release, undefined); + yield* Fiber.join(cancelled); - expect(yield* Ref.get(attachEvents)).toMatchObject([ - { - type: "snapshot", - snapshot: { - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - }, - }, - ]); + const snapshots: TerminalAttachStreamEvent[] = []; + const stop = yield* manager.attachStream(input, (event) => + Effect.sync(() => { + snapshots.push(event); + }), + ); + stop(); + expect(snapshots).toMatchObject([ + { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[0]?.pid } }, + ]); + expect(ptyAdapter.processes).toHaveLength(1); + }).pipe(Effect.scoped), + ); - process.emitData("hello from attach\n"); + it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () => + Effect.gen(function* () { + const ptyAdapter = new GatedPtyAdapter(); + const historyByteLimit = 64 * 1024; + const { manager } = yield* createManager(5, { ptyAdapter, historyByteLimit }); + const input = openInput(); + const pull = yield* Stream.toPull( + terminalOutputStream( + (listener, registerCleanup) => manager.attachStream(input, listener, registerCleanup), + (listener, registerCleanup) => manager.resyncStream(input, listener, registerCleanup), + ), + ); + expect(yield* pull).toMatchObject([{ type: "snapshot", snapshot: { history: "" } }]); + const process = ptyAdapter.processes[0]!; + yield* publishPastOutputBudget(manager, process); + + const resumed = yield* pull; + expect(resumed).toHaveLength(1); + expect(resumed[0]?.type).toBe("snapshot"); + if (resumed[0]?.type !== "snapshot") throw new Error("Expected a recovery snapshot"); + expect(Buffer.byteLength(resumed[0].snapshot.history)).toBeLessThanOrEqual(historyByteLimit); + expect(resumed[0].snapshot.history.endsWith("last\n")).toBe(true); + process.emitData("after recovery\n"); + expect(yield* pull).toMatchObject([{ type: "output", data: "after recovery\n" }]); + expect(ptyAdapter.spawnInputs).toHaveLength(1); - yield* waitFor( - Effect.map(Ref.get(attachEvents), (events) => - events.some((event) => event.type === "output" && event.data === "hello from attach\n"), - ), - "1200 millis", - ); + yield* publishPastOutputBudget(manager, process); + yield* manager.close(input); + expect(yield* pull).toEqual([ + { type: "closed", threadId: input.threadId, terminalId: input.terminalId }, + ]); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + yield* manager.open(input); + expect(yield* pull).toMatchObject([ + { type: "snapshot", snapshot: { status: "running", pid: ptyAdapter.processes[1]!.pid } }, + ]); + const reopenedProcess = ptyAdapter.processes[1]!; + reopenedProcess.emitData("after reopen\n"); + expect(yield* pull).toMatchObject([{ type: "output", data: "after reopen\n" }]); + + yield* publishPastOutputBudget(manager, reopenedProcess); + // Queue close/reopen ahead of recovery while another spawn owns the thread lock. + const gate = { + spawning: yield* Deferred.make(), + release: yield* Deferred.make(), + }; + ptyAdapter.gate = gate; + const holder = yield* manager + .open(openInput({ terminalId: "other" })) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(gate.spawning); + const closed = yield* manager.close(input).pipe(Effect.forkChild({ startImmediately: true })); + const reopened = yield* manager + .open(input) + .pipe(Effect.forkChild({ startImmediately: true })); + const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + reopenedProcess.emitData("old session\n"); + yield* Deferred.succeed(gate.release, undefined); + yield* Fiber.join(holder); + yield* Fiber.join(closed); + yield* Fiber.join(reopened); + + const batch = yield* Fiber.join(recovery); + expect(batch).toHaveLength(1); + expect(batch[0]).toMatchObject({ + type: "snapshot", + snapshot: { status: "running", pid: ptyAdapter.processes.at(-1)!.pid }, + }); + 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), + ); - const events = yield* Ref.get(attachEvents); - expect(events.filter((event) => event.type === "snapshot")).toHaveLength(1); - }), + it.effect("does not replay in-flight output already included in an observer snapshot", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const input = openInput(); + yield* manager.open(input); + const reached = yield* Deferred.make(); + const release = yield* Deferred.make(); + const delivered = yield* Deferred.make(); + // The snapshot sees history before this earlier fanout listener releases it. + const unsubscribe = yield* manager.subscribe((event) => + event.type === "output" && event.data === "in flight\n" + ? Deferred.succeed(reached, undefined).pipe(Effect.andThen(Deferred.await(release))) + : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + ptyAdapter.processes[0]!.emitData("in flight\n"); + yield* Deferred.await(reached); + const observed: TerminalAttachStreamEvent[] = []; + const stopObserving = yield* manager.observeStream(input, (event) => + Effect.gen(function* () { + observed.push(event); + if (event.type === "output" && event.data === "after\n") { + yield* Deferred.succeed(delivered, undefined); + } + }), + ); + yield* Effect.addFinalizer(() => Effect.sync(stopObserving)); + expect(observed).toMatchObject([{ type: "snapshot", snapshot: { history: "in flight\n" } }]); + yield* Deferred.succeed(release, undefined); + ptyAdapter.processes[0]!.emitData("after\n"); + yield* Deferred.await(delivered); + 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", () => @@ -2919,113 +1703,4 @@ it.layer( expect(missingEvents).toEqual([]); }), ); - - it.effect("buffers attach output delivered during the initial snapshot callback", () => - Effect.gen(function* () { - const { manager, ptyAdapter } = yield* createManager(5, { - ptyAdapter: new FakePtyAdapter("async"), - }); - yield* manager.open(openInput()); - - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - const attachEvents = yield* Ref.make>([]); - const unsubscribe = yield* manager.attachStream(openInput(), (event) => - Effect.gen(function* () { - yield* Ref.update(attachEvents, (events) => [...events, event]); - if (event.type === "snapshot") { - yield* Effect.sync(() => process.emitData("during snapshot\n")); - yield* Effect.yieldNow; - } - }), - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - yield* waitFor( - Effect.map(Ref.get(attachEvents), (events) => - events.some((event) => event.type === "output" && event.data === "during snapshot\n"), - ), - "1200 millis", - ); - - expect(yield* Ref.get(attachEvents)).toMatchObject([ - { type: "snapshot" }, - { type: "output", data: "during snapshot\n" }, - ]); - }), - ); - - it.effect("preserves queued PTY output ordering through exit callbacks", () => - Effect.gen(function* () { - const { manager, ptyAdapter, getEvents } = yield* createManager(5, { - ptyAdapter: new FakePtyAdapter("async"), - }); - - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("first\n"); - process.emitData("second\n"); - process.emitExit({ exitCode: 0, signal: 0 }); - - yield* waitFor( - Effect.map(getEvents, (events) => { - const relevant = events.filter( - (event) => event.type === "output" || event.type === "exited", - ); - return relevant.length >= 3; - }), - "1200 millis", - ); - - const relevant = (yield* getEvents).filter( - (event) => event.type === "output" || event.type === "exited", - ); - expect(relevant).toEqual([ - expect.objectContaining({ type: "output", data: "first\n", sequence: 2 }), - expect.objectContaining({ type: "output", data: "second\n", sequence: 3 }), - expect.objectContaining({ type: "exited", exitCode: 0, exitSignal: 0, sequence: 4 }), - ]); - - const attachEvents = yield* Ref.make>([]); - const unsubscribe = yield* manager.attachStream( - { - threadId: "thread-1", - terminalId: DEFAULT_TERMINAL_ID, - }, - (event) => Ref.update(attachEvents, (events) => [...events, event]), - ); - yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); - - const snapshot = (yield* Ref.get(attachEvents)).find((event) => event.type === "snapshot"); - expect(snapshot).toBeDefined(); - if (!snapshot || snapshot.type !== "snapshot") return; - expect(snapshot.snapshot.sequence).toBe(4); - }), - ); - - it.effect("scoped runtime shutdown stops active terminals cleanly", () => - Effect.gen(function* () { - const scope = yield* Scope.make("sequential"); - const { manager, ptyAdapter } = yield* createManager(5, { - processKillGraceMs: 10, - }).pipe(Effect.provideService(Scope.Scope, scope)); - yield* manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - const closeScope = yield* Scope.close(scope, Exit.void).pipe(Effect.forkScoped); - yield* Effect.yieldNow; - yield* TestClock.adjust("10 millis"); - yield* Fiber.join(closeScope); - - assert.equal(process.killSignals[0], "SIGTERM"); - expect(process.killSignals).toContain("SIGKILL"); - }).pipe(Effect.provide(TestClock.layer())), - ); }); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 3bb561aef2537..3abfed846c49f 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1,6 +1,10 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto digest is effectful; a sync hash keeps historyPath a plain function. +import * as NodeCrypto from "node:crypto"; + import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { DEFAULT_TERMINAL_ID, + DEFAULT_MAX_TERMINAL_BUFFER_BYTES, TerminalCwdError, TerminalCwdNotDirectoryError, TerminalCwdNotFoundError, @@ -94,11 +98,26 @@ const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024; const DEFAULT_PERSIST_DEBOUNCE_MS = 250; const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000; const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000; +// Discover children started without terminal input or output. +const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; -const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); +// The tmux/screen/Zellij keys name the multiplexer pane that launched the server, +// so inheriting them points multiplexer-aware tools at that unrelated pane. +const TERMINAL_ENV_BLOCKLIST = new Set([ + "PORT", + "ELECTRON_RENDERER_PORT", + "ELECTRON_RUN_AS_NODE", + "TMUX", + "TMUX_PANE", + "STY", + "WINDOW", + "ZELLIJ", + "ZELLIJ_SESSION_NAME", + "ZELLIJ_PANE_ID", +]); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); const MAX_TERMINAL_LABEL_LENGTH = 128; const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings); @@ -149,11 +168,19 @@ export class TerminalManager extends Context.Service< readonly attachStream: ( input: TerminalAttachInput, listener: (event: TerminalAttachStreamEvent) => Effect.Effect, + registerCleanup?: (stop: () => void) => void, ) => Effect.Effect<() => void, TerminalError>; readonly observeStream: ( input: TerminalObserveInput, listener: (event: TerminalAttachStreamEvent) => Effect.Effect, + registerCleanup?: (stop: () => void) => void, + ) => Effect.Effect<() => void, TerminalError>; + + readonly resyncStream: ( + input: TerminalObserveInput, + listener: (event: TerminalAttachStreamEvent) => Effect.Effect, + registerCleanup?: (stop: () => void) => void, ) => Effect.Effect<() => void, TerminalError>; readonly write: (input: TerminalWriteInput) => Effect.Effect; @@ -162,16 +189,12 @@ export class TerminalManager extends Context.Service< readonly clear: (input: TerminalClearInput) => Effect.Effect; - /** - * Always resets history before spawning the new process. - */ + /** Resets history before spawning. */ readonly restart: ( input: TerminalRestartInput, ) => Effect.Effect; - /** - * When `terminalId` is omitted, closes all sessions for the thread. - */ + /** Omit terminalId to close all sessions for the thread. */ readonly close: (input: TerminalCloseInput) => Effect.Effect; readonly closeIdle: (input: { @@ -181,6 +204,7 @@ export class TerminalManager extends Context.Service< readonly subscribe: ( listener: (event: TerminalEvent) => Effect.Effect, + registerCleanup?: (stop: () => void) => void, ) => Effect.Effect<() => void>; readonly subscribeMetadata: ( @@ -412,6 +436,16 @@ function advanceEventSequence(session: TerminalSessionState): { return { updatedAt, sequence: session.eventSequence }; } +function terminalActivityMark(session: TerminalSessionState): number { + return session.eventSequence + session.inputCount; +} + +interface QuietTerminalSession { + readonly process: PtyAdapter.PtyProcess | null; + readonly mark: number; + readonly idleSnapshots: number; +} + function cleanupProcessHandles(session: TerminalSessionState): void { session.unsubscribeData?.(); session.unsubscribeData = null; @@ -616,10 +650,7 @@ interface TerminalProcessTableSnapshot { readonly commandById: ReadonlyMap; } -export function subprocessSnapshotPollDelayMs( - pollIntervalMs: number, - failureCount: number, -): number { +function subprocessSnapshotPollDelayMs(pollIntervalMs: number, failureCount: number): number { return Math.min(pollIntervalMs * 2 ** failureCount, MAX_SUBPROCESS_POLL_INTERVAL_MS); } @@ -627,8 +658,7 @@ function parsePosixProcessTable(stdout: string): TerminalProcessTableSnapshot { const childrenByParent = new Map(); const commandById = new Map(); for (const line of stdout.split(/\r?\n/g)) { - // `comm=` is the final column and may itself contain spaces, so only the - // first two tokens are structural. + // The final comm column can contain spaces; only the first two tokens are structural. const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line); if (!match) continue; const pid = Number(match[1]); @@ -666,8 +696,7 @@ function deriveSubprocessInspectResult( const commandName = (pid: number) => normalizeChildCommandName(snapshot.commandById.get(pid) ?? "", platform); const shellName = commandName(terminalPid); - // Async prompt themes fork the shell into a helper that waits with no - // children of its own. That copy is not a command the user started. + // Async prompt themes fork childless shell helpers that are not user commands. const childPid = (snapshot.childrenByParent.get(terminalPid) ?? []).find( (pid) => shellName === null || @@ -698,9 +727,7 @@ function deriveSubprocessInspectResult( const POSIX_PS_ABSOLUTE_PATHS = ["/bin/ps", "/usr/bin/ps"] as const; -// Resolve `ps` to an absolute path once at startup. Spawning by bare name -// walks every PATH entry per spawn (one failed posix_spawn per directory -// until the hit), which is measurable at a 1s poll cadence on long PATHs. +// Resolve ps once; bare-name spawns repeatedly probe long PATHs during one-second polling. const resolvePosixPsCommand = Effect.fn("terminal.resolvePosixPsCommand")(function* () { const fileSystem = yield* FileSystem.FileSystem; for (const candidate of POSIX_PS_ABSOLUTE_PATHS) { @@ -737,8 +764,7 @@ const posixProcessTableSnapshot = Effect.fn("terminal.posixProcessTableSnapshot" ), ); if (result.code !== 0 || result.timedOut || result.stdoutTruncated) { - // Not authoritative: an empty or partial table would mark every terminal - // idle and clear its registered process ids. Failing skips the tick. + // Reject partial tables; treating them as authoritative would clear process ids and mark terminals idle. return yield* new TerminalSubprocessCheckError({ command: "ps", exitCode: result.code, @@ -973,6 +999,46 @@ export class BoundedTerminalHistory { } } +// Pop beyond Ghostty's eight-entry Kitty stacks on both screens before clearing +// flags. A 1049 round trip preserves the main cursor, text, and scrollback. +const INHERITED_INPUT_RESET = + "\u001b[?1049h\u001b[<100u\u001b[=0;1u\u001b[?1049l" + + "\u001b[?1;9;66;67;1000;1002;1003;1004;1005;1006;1015;2004l" + + "\u001b[?25;1035;1036h\u001b[<100u\u001b[=0;1u\u001b[>4m"; + +function neutralizeInheritedHistory(history: string, maxLines: number, maxBytes: number): string { + // Scan exactly the cold replay window, reserving the entire longest reset so + // neither the server nor the client can trim away the entry after we choose its exit. + const resetBytes = history.includes("\u001b") + ? Buffer.byteLength(INHERITED_INPUT_RESET + "\u001b7\u001b[?1049l") + : 0; + history = new BoundedTerminalHistory( + // The suffix occupies the empty line after a trailing newline, too. + resetBytes > 0 && history.endsWith("\n") ? maxLines - 1 : maxLines, + history, + Math.max(0, maxBytes - resetBytes), + ).value(); + if (!history.includes("\u001b")) return history; + // An unconditional 1049 reset restores a stale saved cursor on the main + // screen. The exit must match the inherited screen's cursor-save behavior. + let alternateScreen: number | undefined; + // eslint-disable-next-line no-control-regex -- Match replayed alternate-screen controls. + for (const match of history.matchAll(/\u001b(?:\[\?([0-9;]+)([hl])|(c))/gu)) { + if (match[3]) alternateScreen = undefined; + for (const parameter of (match[1] ?? "").split(";")) { + const mode = Number(parameter); + if (mode === 47 || mode === 1047 || mode === 1049) { + alternateScreen = match[2] === "h" ? (alternateScreen ?? mode) : undefined; + } + } + } + // A client may trim away the entry, leaving us on main: save its current + // cursor before exiting. On alternate this saves only the alternate cursor. + const leaveAlternateScreen = + alternateScreen === undefined ? "" : `\u001b7\u001b[?${alternateScreen}l`; + return history + leaveAlternateScreen + INHERITED_INPUT_RESET; +} + function isCsiFinalByte(codePoint: number): boolean { return codePoint >= 0x40 && codePoint <= 0x7e; } @@ -987,10 +1053,7 @@ function shouldStripCsiSequence(body: string, finalByte: string): boolean { if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) { return true; } - // DECRQM mode queries (…$p) and DECRPM replies (…$y): replaying a stored - // query makes the terminal answer again, and the shell echoes the answer as - // junk at the prompt. The `$` guard keeps setters like DECSTR (!p) and - // DECSCL ("p) intact. + // Strip DECRQM/DECRPM query traffic to prevent echoed replies during replay; $ guards preserve setters. if ((finalByte === "p" || finalByte === "y") && /^[0-9;?]*\$$/.test(body)) { return true; } @@ -1005,9 +1068,7 @@ function shouldStripCsiSequence(body: string, finalByte: string): boolean { return false; } -// DECRQSS ($q) and XTGETTCAP (+q) queries plus their replies ([01]$r / [01]+r): -// pure request/response traffic with no visual value, and replaying a stored -// query triggers a fresh reply. +// Strip DECRQSS/XTGETTCAP query traffic; replaying queries triggers fresh replies without visual value. function shouldStripDcsSequence(content: string): boolean { return /^[01]?[$+][qr]/.test(content); } @@ -1072,6 +1133,8 @@ function sanitizeTerminalHistoryChunk( } const input = `${pendingControlSequence}${data}`; + // Only the pending prefix's final ESC can begin a terminator split across chunks. + const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); let visibleText = ""; let index = 0; @@ -1114,7 +1177,10 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5e || nextCodePoint === 0x5f ) { - const terminatorIndex = findStringTerminatorIndex(input, index + 2); + const terminatorIndex = findStringTerminatorIndex( + input, + Math.max(index + 2, pendingScanStart), + ); if (terminatorIndex === null) { return { visibleText, pendingControlSequence: input.slice(index) }; } @@ -1160,7 +1226,10 @@ function sanitizeTerminalHistoryChunk( } if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) { - const terminatorIndex = findStringTerminatorIndex(input, index + 1); + const terminatorIndex = findStringTerminatorIndex( + input, + Math.max(index + 1, pendingScanStart), + ); if (terminatorIndex === null) { return { visibleText, pendingControlSequence: input.slice(index) }; } @@ -1190,12 +1259,23 @@ function legacySafeThreadId(threadId: string): string { return threadId.replace(/[^a-zA-Z0-9._-]/g, "_"); } -function toSafeThreadId(threadId: string): string { +const MAX_FILE_NAME_BYTES = 255; + +function encodedHistoryThreadPart(threadId: string): string { return `terminal_${Base64Url.encode(threadId)}`; } -function toSafeTerminalId(terminalId: string): string { - return Base64Url.encode(terminalId); +function hashId(id: string): string { + return NodeCrypto.createHash("sha256").update(id).digest("base64url"); +} + +// "." is outside the base64url alphabet, so a hashed name can never collide with an encoded one. +function hashedHistoryThreadPart(threadId: string): string { + return `terminal_sha256.${hashId(threadId)}`; +} + +function joinHistoryFileName(threadPart: string, terminalPart: string | null): string { + return terminalPart === null ? `${threadPart}.log` : `${threadPart}_${terminalPart}.log`; } function toSessionKey(threadId: string, terminalId: string): string { @@ -1225,12 +1305,7 @@ function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean { return segment === appDir || segment.startsWith(`${appDir}/`); } -// On Linux AppImage builds the runtime mounts the app under a temporary dir and -// injects APPIMAGE/APPDIR/ARGV0/OWD plus mount entries on PATH/LD_LIBRARY_PATH. -// The integrated terminal inherits the server process environment, so without -// this scrub those leak into the PTY and tools resolve against the AppImage -// mount instead of the user's real environment (e.g. `php` reporting PHP_BINARY -// as the AppImage path). See issue #1699. +// AppImage mount paths would make PTY tools resolve against the mount instead of the user's system. function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv { if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env; @@ -1283,6 +1358,17 @@ function createTerminalSpawnEnv( if (!spawnEnv.COLORTERM && runtimeEnv?.COLORTERM === undefined) { spawnEnv.COLORTERM = "truecolor"; } + // fish 4.1+ can wait 10s at startup for a DA1 reply before a renderer can answer. + // Skip the query unless the user or provider already chose `query-term` or `no-query-term`. + const fishFeaturesKey = + platform === "win32" + ? (Object.keys(spawnEnv).find((candidate) => candidate.toLowerCase() === "fish_features") ?? + "fish_features") + : "fish_features"; + const fishFeatures = spawnEnv[fishFeaturesKey]; + if (!fishFeatures?.includes("query-term")) { + spawnEnv[fishFeaturesKey] = fishFeatures ? `${fishFeatures},no-query-term` : "no-query-term"; + } return stripAppImageRuntimeEnv(spawnEnv); } @@ -1371,7 +1457,7 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( ); }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("TerminalManager.make")(function* () { const { terminalLogsDir, providerStatusCacheDir, baseDir } = yield* ServerConfig.ServerConfig; const ptyAdapter = yield* PtyAdapter.PtyAdapter; @@ -1419,9 +1505,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const agentScope = yield* AgentScope; - // Terminals must inherit the user's full environment (minus the blocklist - // applied in createTerminalSpawnEnv) — an allowlist here silently strips - // things like PSModulePath, DISPLAY, proxies, and toolchain variables. + // Inherit the full environment minus createTerminalSpawnEnv's blocklist; allowlists silently drop user tooling variables. const baseEnv = options.env ?? process.env; const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv)); const processRunner = yield* ProcessRunner.ProcessRunner; @@ -1443,9 +1527,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return { ...input, env }; }, ); - // One process-table snapshot per poll tick, shared across every terminal. - // Per-terminal `pgrep`/`ps` calls multiply spawn load by terminal count and - // can exhaust the PID space on hosts with many sessions (#6332). + // Share one process table per poll; per-terminal scans can exhaust PIDs on busy hosts. const fallbackProcessTableSnapshot = ( platform === "win32" ? windowsProcessTableSnapshot() @@ -1510,28 +1592,43 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func sessions: new Map(), killFibers: new Map(), }); + // Keep close markers in memory so unknown IDs recover after a server restart. + const closedSessionKeys = new Set(); const threadLocks = yield* KeyedLock.make(); const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect>(); const workerScope = yield* Scope.make("sequential"); yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void)); - const publishEvent = (event: TerminalEvent) => - Effect.gen(function* () { + const publishEvent = + /* Provider events include streaming deltas; avoid a span for each update. */ + Effect.fnUntraced(function* (event: TerminalEvent) { for (const listener of terminalEventListeners) { yield* listener(event).pipe(Effect.ignoreCause({ log: true })); } }); + // Nested subagent thread ids can encode past the filename limit. Only names that would not fit + // switch to hashed ids, so every history file that already exists keeps its path. const historyPath = (threadId: string, terminalId: string) => { - const threadPart = toSafeThreadId(threadId); - if (terminalId === DEFAULT_TERMINAL_ID) { - return path.join(logsDir, `${threadPart}.log`); + const isDefault = terminalId === DEFAULT_TERMINAL_ID; + const encodedName = joinHistoryFileName( + encodedHistoryThreadPart(threadId), + isDefault ? null : Base64Url.encode(terminalId), + ); + if (encodedName.length <= MAX_FILE_NAME_BYTES) { + return path.join(logsDir, encodedName); } - return path.join(logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); + return path.join( + logsDir, + joinHistoryFileName(hashedHistoryThreadPart(threadId), isDefault ? null : hashId(terminalId)), + ); }; - const legacyHistoryPath = (threadId: string) => - path.join(logsDir, `${legacySafeThreadId(threadId)}.log`); + const legacyHistoryName = (threadId: string) => `${legacySafeThreadId(threadId)}.log`; + const legacyHistoryPath = (threadId: string) => path.join(logsDir, legacyHistoryName(threadId)); + // Ids this long could never have been written under the legacy name. + const hasLegacyHistoryPath = (threadId: string) => + Buffer.byteLength(legacyHistoryName(threadId)) <= MAX_FILE_NAME_BYTES; const readManagerState = SynchronizedRef.get(managerStateRef); @@ -1571,8 +1668,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func fiber: Fiber.Fiber, ) { yield* modifyManagerState((state) => { - // The child may finish (and run its finalizer) before this registration. - // Check inside the synchronized update so completed fibers are not retained. + // Children may finalize before registration; check inside the synchronized update to avoid retaining finished fibers. if (fiber.pollUnsafe() !== undefined) { return [undefined, state] as const; } @@ -1587,8 +1683,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func threadId: string, terminalId: string, ) { - // Subscribe before SIGTERM so an immediate exit is not missed. Released with - // Effect.ensuring because a JS `finally` does not run when the fiber is interrupted. + // Subscribe before SIGTERM to catch immediate exits; Effect.ensuring releases even on interruption, unlike JS finally. const exited = Deferred.makeUnsafe(); const unsubscribeExit = process.onExit(() => { Deferred.doneUnsafe(exited, Effect.void); @@ -1794,7 +1889,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return history; } - if (terminalId !== DEFAULT_TERMINAL_ID) { + if (terminalId !== DEFAULT_TERMINAL_ID || !hasLegacyHistoryPath(threadId)) { return new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit); } @@ -1852,7 +1947,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }), ), ); - if (terminalId === DEFAULT_TERMINAL_ID) { + if (terminalId === DEFAULT_TERMINAL_ID && hasLegacyHistoryPath(threadId)) { yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe( Effect.catch((error) => Effect.logWarning("failed to delete terminal history", { @@ -1868,16 +1963,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* ( threadId: string, ) { - const threadPrefix = `${toSafeThreadId(threadId)}_`; + const threadParts = [encodedHistoryThreadPart(threadId), hashedHistoryThreadPart(threadId)]; const entries = yield* fileSystem .readDirectory(logsDir, { recursive: false }) .pipe(Effect.orElseSucceed(() => [] as Array)); yield* Effect.forEach( entries.filter( (name) => - name === `${toSafeThreadId(threadId)}.log` || name === `${legacySafeThreadId(threadId)}.log` || - name.startsWith(threadPrefix), + threadParts.some((part) => name === `${part}.log` || name.startsWith(`${part}_`)), ), (name) => fileSystem.remove(path.join(logsDir, name), { force: true }).pipe( @@ -1955,6 +2049,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func for (const session of inactiveSessions.slice(0, toEvict)) { const key = toSessionKey(session.threadId, session.terminalId); sessions.delete(key); + closedSessionKeys.add(key); } return [undefined, { ...state, sessions }] as const; @@ -2213,9 +2308,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func platform, yield* HostProcess.HomeDirectory, ); - // Append (never prepend) managed ACP agent install directories so - // `kimi login` and friends resolve by name without shadowing any - // system or user tool of the same name. + // Append managed install directories so agent commands resolve without shadowing user/system tools. if ( options.managedBinaryCacheDir !== undefined && options.managedBinaryToolsDir !== undefined @@ -2359,6 +2452,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* flushPersist(threadId, terminalId); const removed = yield* modifyManagerState((state) => { + closedSessionKeys.add(key); if (!state.sessions.has(key)) { return [false, state] as const; } @@ -2381,16 +2475,46 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } }); + // Two unchanged snapshots cover children forked just after the first snapshot. + // Process identity prevents a restarted shell from inheriting quiet state. + let quietSessions = new WeakMap(); + let skippedQuietTicks = 0; + const isQuiet = (session: TerminalSessionState & { pid: number }) => { + const quiet = quietSessions.get(session); + return ( + quiet !== undefined && + quiet.idleSnapshots === 2 && + quiet.process === session.process && + quiet.mark === terminalActivityMark(session) && + !session.hasRunningSubprocess + ); + }; + const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { const state = yield* readManagerState; - const runningSessions = [...state.sessions.values()].filter( - (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), - ); + const runningSessions = [...state.sessions.values()] + .filter( + (session): session is TerminalSessionState & { pid: number } => + session.status === "running" && Number.isInteger(session.pid), + ) + .map((session) => ({ + session, + terminalPid: session.pid, + process: session.process, + mark: terminalActivityMark(session), + })); if (runningSessions.length === 0) { return true; } + if ( + runningSessions.every(({ session }) => isQuiet(session)) && + skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1 + ) { + skippedQuietTicks += 1; + return true; + } + skippedQuietTicks = 0; const inspectorOption = yield* acquireSubprocessInspector.pipe( Effect.asSome, @@ -2409,15 +2533,18 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); if (Option.isNone(inspectorOption)) { + quietSessions = new WeakMap(); return false; } const { inspector: subprocessInspector, snapshotSucceeded } = inspectorOption.value; - const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( - session: TerminalSessionState & { pid: number }, + candidate: (typeof runningSessions)[number], ) { - const terminalPid = session.pid; + const { session, terminalPid, process } = candidate; + let mark = candidate.mark; + const previous = quietSessions.get(session); + quietSessions.delete(session); const inspectResult = yield* subprocessInspector(terminalPid).pipe( Effect.asSome, Effect.catch((reason) => @@ -2430,7 +2557,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ), ); - if (Option.isNone(inspectResult)) { + if ( + Option.isNone(inspectResult) || + session.status !== "running" || + session.pid !== terminalPid || + session.process !== process + ) { return; } @@ -2447,8 +2579,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); if ( Option.isNone(liveSession) || + liveSession.value !== session || liveSession.value.status !== "running" || liveSession.value.pid !== terminalPid || + liveSession.value.process !== process || (liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess && liveSession.value.childCommandLabel === nextChildLabel) ) { @@ -2458,6 +2592,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess; liveSession.value.childCommandLabel = nextChildLabel; const eventStamp = advanceEventSequence(liveSession.value); + // Only this poll's own event may advance the mark without waking it. + mark += 1; return [ Option.some({ @@ -2475,12 +2611,28 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (Option.isSome(event)) { yield* publishEvent(event.value); } + + if ( + snapshotSucceeded && + !next.hasRunningSubprocess && + session.status === "running" && + session.pid === terminalPid && + session.process === process && + terminalActivityMark(session) === mark + ) { + quietSessions.set(session, { + process, + mark, + idleSnapshots: previous?.process === process && previous.mark === mark ? 2 : 1, + }); + } }); yield* Effect.forEach(runningSessions, checkSubprocessActivity, { concurrency: "unbounded", discard: true, }); + return snapshotSucceeded; }); @@ -2553,7 +2705,16 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const existing = yield* getSession(input.threadId, terminalId); if (Option.isNone(existing)) { yield* flushPersist(input.threadId, terminalId); - const history = yield* readHistory(input.threadId, terminalId); + const inherited = yield* readHistory(input.threadId, terminalId); + const history = new BoundedTerminalHistory( + historyLineLimit, + neutralizeInheritedHistory( + inherited.value(), + historyLineLimit, + Math.min(historyByteLimit, DEFAULT_MAX_TERMINAL_BUFFER_BYTES), + ), + historyByteLimit, + ); const cols = input.cols ?? DEFAULT_OPEN_COLS; const rows = input.rows ?? DEFAULT_OPEN_ROWS; const session: TerminalSessionState = { @@ -2587,6 +2748,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* modifyManagerState((state) => { const sessions = new Map(state.sessions); sessions.set(sessionKey, createdSession); + closedSessionKeys.delete(sessionKey); return [undefined, { ...state, sessions }] as const; }); @@ -2681,57 +2843,56 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)), ); - const openOrAttachForStream = (input: TerminalAttachInput) => - withThreadLock( - input.threadId, - Effect.gen(function* () { - const terminalId = input.terminalId; - const existing = yield* getSession(input.threadId, terminalId); + const openOrAttachForStream = Effect.fnUntraced(function* (input: TerminalAttachInput) { + const terminalId = input.terminalId; + const existing = yield* getSession(input.threadId, terminalId); - if (Option.isNone(existing)) { - if (!input.cwd) { - return yield* new TerminalSessionLookupError({ - threadId: input.threadId, - terminalId, - }); - } + if (Option.isNone(existing)) { + if (input.resume && closedSessionKeys.has(toSessionKey(input.threadId, terminalId))) { + return null; + } + if (!input.cwd) { + return yield* new TerminalSessionLookupError({ + threadId: input.threadId, + terminalId, + }); + } - const resolvedInput = yield* resolveLaunchInputEnvironment({ - ...input, - terminalId, - cwd: input.cwd, - }); - return yield* openLocked(resolvedInput); - } + const resolvedInput = yield* resolveLaunchInputEnvironment({ + ...input, + terminalId, + cwd: input.cwd, + }); + return yield* Effect.uninterruptible(openLocked(resolvedInput)); + } - const session = existing.value; - const targetCols = input.cols ?? session.cols; - const targetRows = input.rows ?? session.rows; + const session = existing.value; + const targetCols = input.cols ?? session.cols; + const targetRows = input.rows ?? session.rows; - if (!session.process && input.cwd && input.restartIfNotRunning === true) { - const resolvedInput = yield* resolveLaunchInputEnvironment({ - ...input, - terminalId, - cwd: input.cwd, - }); - return yield* openLocked(resolvedInput); - } + if (!input.resume && !session.process && input.cwd && input.restartIfNotRunning === true) { + const resolvedInput = yield* resolveLaunchInputEnvironment({ + ...input, + terminalId, + cwd: input.cwd, + }); + return yield* Effect.uninterruptible(openLocked(resolvedInput)); + } - if ( - session.process && - session.status === "running" && - (session.cols !== targetCols || session.rows !== targetRows) - ) { - const process = session.process; - yield* resizePtyProcess(session, process, targetCols, targetRows); - session.cols = targetCols; - session.rows = targetRows; - session.updatedAt = yield* nowIso; - } + if ( + session.process && + session.status === "running" && + (session.cols !== targetCols || session.rows !== targetRows) + ) { + const process = session.process; + yield* resizePtyProcess(session, process, targetCols, targetRows); + session.cols = targetCols; + session.rows = targetRows; + session.updatedAt = yield* nowIso; + } - return snapshot(session); - }), - ); + return snapshot(session); + }); const readAllTerminalMetadata = () => readManagerState.pipe( @@ -2755,48 +2916,81 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func Effect.map((session) => (Option.isSome(session) ? summary(session.value) : null)), ); - const subscribe: TerminalManager["Service"]["subscribe"] = (listener) => + const subscribe: TerminalManager["Service"]["subscribe"] = (listener, registerCleanup) => Effect.sync(() => { terminalEventListeners.add(listener); - return () => { + const stop = () => { terminalEventListeners.delete(listener); }; + // Transfer ownership before an interrupt can discard the returned handle. + registerCleanup?.(stop); + return stop; }); + // Subscribe after taking the lock so contention cannot accumulate an unbounded replay. + // Snapshot listeners run under that lock and must not block. const streamSession = ( input: TerminalObserveInput, - initial: Effect.Effect, + initial: Effect.Effect, listener: (event: TerminalAttachStreamEvent) => Effect.Effect, + registerCleanup?: (stop: () => void) => void, ) => { let unsubscribe: (() => void) | null = null; + const stop = () => { + unsubscribe?.(); + unsubscribe = null; + }; return Effect.gen(function* () { const bufferedEvents: TerminalEvent[] = []; let deliverLive = false; + let snapshotFloor: number | null = null; - unsubscribe = yield* subscribe((event) => { - if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) { - return Effect.void; - } + yield* subscribe( + (event) => { + if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) { + return Effect.void; + } - if (!deliverLive) { - bufferedEvents.push(event); - return Effect.void; - } + if (!deliverLive) { + bufferedEvents.push(event); + return Effect.void; + } - const attachEvent = terminalEventToAttachEvent(event); - return attachEvent ? listener(attachEvent) : Effect.void; - }); + // Fanout can finish after a snapshot that already includes the event. + // Keep only its sequence, not its history, until the session changes. + if (snapshotFloor !== null) { + if ( + event.type === "started" || + event.type === "restarted" || + event.type === "error" || + event.type === "closed" + ) { + snapshotFloor = null; + } else if (typeof event.sequence === "number" && event.sequence <= snapshotFloor) { + return Effect.void; + } + } + + const attachEvent = terminalEventToAttachEvent(event); + return attachEvent ? listener(attachEvent) : Effect.void; + }, + (cleanup) => { + unsubscribe = cleanup; + registerCleanup?.(stop); + }, + ); const initialSnapshot = yield* initial; - yield* listener({ - type: "snapshot", - snapshot: initialSnapshot, - }); + yield* listener( + initialSnapshot === null + ? { type: "closed", threadId: input.threadId, terminalId: input.terminalId } + : { type: "snapshot", snapshot: initialSnapshot }, + ); for (const event of bufferedEvents) { - if (isDuplicateAttachSnapshotEvent(event, initialSnapshot)) { + if (initialSnapshot !== null && isDuplicateAttachSnapshotEvent(event, initialSnapshot)) { continue; } @@ -2805,36 +2999,48 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* listener(attachEvent); } } + // The live listener keeps this closure, so release replayed output. + bufferedEvents.length = 0; + snapshotFloor = initialSnapshot?.sequence ?? null; deliverLive = true; - return () => { - unsubscribe?.(); - unsubscribe = null; - }; + return stop; }).pipe( - Effect.catchCause((cause) => - Effect.flatMap( - Effect.sync(() => { - unsubscribe?.(); - unsubscribe = null; - }), - () => Effect.failCause(cause), - ), - ), + (effect) => withThreadLock(input.threadId, effect), + Effect.onError(() => Effect.sync(stop)), ); }; - const attachStream: TerminalManager["Service"]["attachStream"] = (input, listener) => - streamSession(input, openOrAttachForStream(input), listener); + const attachStream: TerminalManager["Service"]["attachStream"] = ( + input, + listener, + registerCleanup, + ) => streamSession(input, openOrAttachForStream(input), listener, registerCleanup); - const observeStream: TerminalManager["Service"]["observeStream"] = (input, listener) => + const observeStream: TerminalManager["Service"]["observeStream"] = ( + input, + listener, + registerCleanup, + ) => streamSession( input, - withThreadLock( - input.threadId, - requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)), + requireSession(input.threadId, input.terminalId).pipe(Effect.map(snapshot)), + listener, + registerCleanup, + ); + + const resyncStream: TerminalManager["Service"]["resyncStream"] = ( + input, + listener, + registerCleanup, + ) => + streamSession( + input, + getSession(input.threadId, input.terminalId).pipe( + Effect.map((session) => (Option.isSome(session) ? snapshot(session.value) : null)), ), listener, + registerCleanup, ); const metadataEventFromTerminalEvent = ( @@ -2983,83 +3189,85 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }), ); - const restartResolved = (input: TerminalRestartInput) => - Effect.gen(function* () { - yield* increment(terminalRestartsTotal, { scope: "thread" }); - const terminalId = input.terminalId; - yield* assertValidCwd(input.cwd); - - const sessionKey = toSessionKey(input.threadId, terminalId); - const existingSession = yield* getSession(input.threadId, terminalId); - let session: TerminalSessionState; - if (Option.isNone(existingSession)) { - const cols = input.cols ?? DEFAULT_OPEN_COLS; - const rows = input.rows ?? DEFAULT_OPEN_ROWS; - session = { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - worktreePath: input.worktreePath ?? null, - status: "starting", - pid: null, - history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit), - pendingHistoryControlSequence: "", - pendingProcessEvents: [], - pendingProcessEventIndex: 0, - processEventDrainRunning: false, - exitCode: null, - exitSignal: null, - updatedAt: yield* nowIso, - eventSequence: 0, - inputCount: 0, - cols, - rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - childCommandLabel: null, - runtimeEnv: normalizedRuntimeEnv(input.env), - }; - const createdSession = session; - yield* modifyManagerState((state) => { - const sessions = new Map(state.sessions); - sessions.set(sessionKey, createdSession); - return [undefined, { ...state, sessions }] as const; - }); - yield* evictInactiveSessionsIfNeeded(); - } else { - session = existingSession.value; - yield* stopProcess(session); - session.cwd = input.cwd; - session.worktreePath = input.worktreePath ?? null; - session.runtimeEnv = normalizedRuntimeEnv(input.env); - } + const restartResolved = Effect.fn("Manager.restartResolved")(function* ( + input: TerminalRestartInput, + ) { + yield* increment(terminalRestartsTotal, { scope: "thread" }); + const terminalId = input.terminalId; + yield* assertValidCwd(input.cwd); - const cols = input.cols ?? session.cols; - const rows = input.rows ?? session.rows; + const sessionKey = toSessionKey(input.threadId, terminalId); + const existingSession = yield* getSession(input.threadId, terminalId); + let session: TerminalSessionState; + if (Option.isNone(existingSession)) { + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + session = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + worktreePath: input.worktreePath ?? null, + status: "starting", + pid: null, + history: new BoundedTerminalHistory(historyLineLimit, "", historyByteLimit), + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: yield* nowIso, + eventSequence: 0, + inputCount: 0, + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + childCommandLabel: null, + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + closedSessionKeys.delete(sessionKey); + return [undefined, { ...state, sessions }] as const; + }); + yield* evictInactiveSessionsIfNeeded(); + } else { + session = existingSession.value; + yield* stopProcess(session); + session.cwd = input.cwd; + session.worktreePath = input.worktreePath ?? null; + session.runtimeEnv = normalizedRuntimeEnv(input.env); + } - session.history.clear(); - session.pendingHistoryControlSequence = ""; - session.pendingProcessEvents = []; - session.pendingProcessEventIndex = 0; - session.processEventDrainRunning = false; - yield* persistHistory(input.threadId, terminalId, session.history); - yield* startSession( - session, - { - threadId: input.threadId, - terminalId, - cwd: input.cwd, - ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), - cols, - rows, - ...(input.env ? { env: input.env } : {}), - }, - "restarted", - ); - return snapshot(session); - }); + const cols = input.cols ?? session.cols; + const rows = input.rows ?? session.rows; + + session.history.clear(); + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + yield* persistHistory(input.threadId, terminalId, session.history); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}), + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "restarted", + ); + return snapshot(session); + }); const restart: TerminalManager["Service"]["restart"] = (input) => withThreadLock( @@ -3107,13 +3315,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func (input.terminalId === undefined || session.terminalId === input.terminalId), ); if (running.length === 0) return; - const activityMark = (session: TerminalSessionState) => - session.eventSequence + session.inputCount; const marks = new Map( - running.map((session) => [session.terminalId, activityMark(session)]), + running.map((session) => [session.terminalId, terminalActivityMark(session)]), ); - // Inspect now instead of trusting the last poll, so a command started - // since then keeps its terminal. + // Inspect now so commands started after the last poll still protect their terminals. const { inspector } = yield* acquireSubprocessInspector; yield* Effect.forEach( running, @@ -3121,7 +3326,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func inspector(session.pid).pipe( Effect.flatMap((result) => result.hasRunningSubprocess || - activityMark(session) !== marks.get(session.terminalId) + terminalActivityMark(session) !== marks.get(session.terminalId) ? Effect.void : closeSession(input.threadId, session.terminalId, false), ), @@ -3142,6 +3347,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func open, attachStream, observeStream, + resyncStream, write, resize, clear, diff --git a/apps/server/src/terminal/NodePtyAdapter.test.ts b/apps/server/src/terminal/NodePtyAdapter.test.ts index 79f73c2e9060c..66704396e9e76 100644 --- a/apps/server/src/terminal/NodePtyAdapter.test.ts +++ b/apps/server/src/terminal/NodePtyAdapter.test.ts @@ -4,14 +4,11 @@ import * as NodeNet from "node:net"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import * as Logger from "effect/Logger"; import * as Scheduler from "effect/Scheduler"; -import { expect, vi } from "vite-plus/test"; +import { vi } from "vite-plus/test"; import * as NodePtyAdapter from "./NodePtyAdapter.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; @@ -160,125 +157,6 @@ it.effect("reports an incompatible Windows readiness API instead of hanging", () }).pipe(Effect.provide(layerTest)), ); -it.effect.each(["win32", "linux", "darwin"] as const)( - "terminates through node-pty using %s semantics", - (platform) => - Effect.gen(function* () { - const adapter = yield* PtyAdapter.PtyAdapter; - const process = yield* adapter.spawn({ - shell: "test-shell", - cwd: ".", - cols: 80, - rows: 24, - env: {}, - }); - const nativeProcess = spawn.mock.results.at(-1)!.value; - nativeProcess.kill.mockImplementation((signal?: string) => { - if (platform === "win32" && signal) { - throw new Error("Signals not supported on windows."); - } - }); - - process.kill("SIGTERM"); - process.kill("SIGKILL"); - process.kill(); - - assert.deepEqual( - nativeProcess.kill.mock.calls, - platform === "win32" - ? [[undefined], [undefined], [undefined]] - : [["SIGTERM"], ["SIGKILL"], [undefined]], - ); - }).pipe(Effect.provide(layerTestFor(platform))), -); - -it.effect("spawns through the public adapter with the provided host references", () => - Effect.gen(function* () { - spawn.mockClear(); - const adapter = yield* PtyAdapter.PtyAdapter; - const process = yield* adapter.spawn({ - shell: "powershell.exe", - args: ["-NoLogo"], - cwd: "C:\\workspace", - cols: 120, - rows: 40, - env: {}, - }); - - assert.equal(process.pid, 42); - assert.equal(spawn.mock.calls.length, 1); - assert.deepEqual(spawn.mock.calls[0], [ - "powershell.exe", - ["-NoLogo"], - { - cwd: "C:\\workspace", - cols: 120, - rows: 40, - env: { TERM: "xterm-256color" }, - name: "xterm-256color", - }, - ]); - }).pipe(Effect.provide(layerTest)), -); - -it.effect("preserves a caller-provided TERM in the spawn env on win32", () => - Effect.gen(function* () { - spawn.mockClear(); - const adapter = yield* PtyAdapter.PtyAdapter; - yield* adapter.spawn({ - shell: "powershell.exe", - cwd: "C:\\workspace", - cols: 80, - rows: 24, - env: { TERM: "xterm-direct" }, - }); - - assert.equal(spawn.mock.calls.length, 1); - assert.deepEqual(spawn.mock.calls[0], [ - "powershell.exe", - [], - { - cwd: "C:\\workspace", - cols: 80, - rows: 24, - env: { TERM: "xterm-direct" }, - name: "xterm-256color", - }, - ]); - }).pipe(Effect.provide(layerTest)), -); - -it.effect("reports native module load failures as structured startup defects", () => - Effect.gen(function* () { - const cause = new Error("native binding could not be loaded"); - const exit = yield* NodePtyAdapter.make().pipe( - Effect.provideService(NodePtyAdapter.NodePtyModuleLoaderRef, () => Promise.reject(cause)), - Effect.exit, - ); - - assert.isTrue(Exit.isFailure(exit)); - if (Exit.isFailure(exit)) { - assert.isTrue(Cause.hasDies(exit.cause)); - const error = Cause.squash(exit.cause); - assert.instanceOf(error, NodePtyAdapter.NodePtyModuleLoadError); - assert.deepInclude(error, { - _tag: "NodePtyModuleLoadError", - platform: "win32", - architecture: "x64", - }); - assert.equal(error.message, "Failed to load node-pty for win32-x64."); - } - }).pipe( - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - Layer.succeed(HostProcess.Platform, "win32"), - Layer.succeed(HostProcess.Architecture, "x64"), - ), - ), - ), -); - it.effect.each([2048, 8])( "preserves an exit during readiness handoff with scheduler budget %s", (budget) => @@ -319,47 +197,3 @@ it.effect("replays an exit to late subscribers and respects unsubscription", () assert.equal(nativeProcess.events.listenerCount("exit"), 0); }).pipe(Effect.provide(layerTest)), ); - -it.effect.each(["spawn", "interrupt"] as const)( - "logs cleanup failures without replacing %s", - (failure) => - Effect.gen(function* () { - const { nativeProcess, subscribed } = preparePendingProcess(); - const killError = new Error("native kill failed"); - nativeProcess._agent.kill.mockImplementation(() => { - throw killError; - }); - const messages: unknown[] = []; - const logger = Logger.make(({ message }) => { - messages.push(message); - }); - const adapter = yield* PtyAdapter.PtyAdapter; - const fiber = yield* adapter - .spawn(spawnInput) - .pipe( - Effect.provide(Logger.layer([logger], { mergeWithExisting: false })), - Effect.forkChild, - ); - yield* subscribed; - const spawnError = new Error("pipe failed"); - if (failure === "interrupt") yield* Fiber.interrupt(fiber); - else nativeProcess._socket.emit("error", spawnError); - const exit = yield* Fiber.await(fiber); - assert.isTrue(Exit.isFailure(exit)); - if (Exit.isFailure(exit)) { - if (failure === "interrupt") assert.isTrue(Cause.hasInterrupts(exit.cause)); - else { - const error = Cause.squash(exit.cause); - assert.instanceOf(error, PtyAdapter.PtySpawnError); - assert.equal(error.cause, spawnError); - } - } - assert.equal(messages.length, 1); - expect(messages[0]).toMatchObject([ - "failed to cancel Windows terminal startup", - { terminalPid: 0, cause: { cause: killError } }, - ]); - assert.equal(nativeProcess.events.listenerCount("exit"), 0); - assert.equal(nativeProcess._socket.listenerCount("ready_datapipe"), 0); - }).pipe(Effect.provide(layerTest)), -); diff --git a/apps/server/src/terminal/NodePtyAdapter.ts b/apps/server/src/terminal/NodePtyAdapter.ts index e9b1fe5d4b91c..4b83ddf6697e6 100644 --- a/apps/server/src/terminal/NodePtyAdapter.ts +++ b/apps/server/src/terminal/NodePtyAdapter.ts @@ -26,10 +26,7 @@ export class NodePtyModuleLoadError extends Schema.TaggedError Promise; -// node-pty stays external to the CLI bundle because it dlopens a native -// addon. Inside a Node single-executable, `import()` cannot load files from -// disk (only built-ins resolve), while `require` always reads the real -// filesystem, so both the module and its spawn-helper resolve through it. +// node-pty's native addon stays external; single-executables need require to resolve disk modules and spawn helpers. const requireForNodePty = NodeModule.createRequire(import.meta.url); const loadNodePty: NodePtyModuleLoader = () => @@ -81,12 +78,8 @@ const ensureNodePtySpawnHelperExecutable = Effect.fn(function* () { yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined)); }); -/** - * node-pty defers creation to avoid blocking on named pipes: - * https://github.com/microsoft/node-pty/pull/885 Its public API has no - * readiness event. The private ready_datapipe handler sets pid before our - * listener runs. - */ +// node-pty has no public readiness event; ready_datapipe sets pid before our listener. +// Deferred pipe creation: https://github.com/microsoft/node-pty/pull/885 const waitForWindowsPid = ( process: import("node-pty").IPty, trackedProcess: NodePtyProcess, @@ -139,10 +132,7 @@ const waitForWindowsPid = ( return Effect.sync(cleanup); }); -/** - * Cancels Windows startup without waiting for the first output, unlike public kill(). - * The private agent can cancel the pending connection before a child exists. - */ +// The private agent cancels pending connections before a child exists; public kill waits for first output. const killStartingWindowsPty = (process: import("node-pty").IPty) => Effect.try(() => { if ( @@ -225,7 +215,7 @@ class NodePtyProcess implements PtyAdapter.PtyProcess { } } -export const make = Effect.fn("NodePtyAdapter.make")(function* () { +const make = Effect.fn("NodePtyAdapter.make")(function* () { const loadNodePtyModule = yield* NodePtyModuleLoaderRef; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -255,9 +245,7 @@ export const make = Effect.fn("NodePtyAdapter.make")(function* () { return PtyAdapter.PtyAdapter.of({ spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) { yield* ensureNodePtySpawnHelperExecutableCached; - // node-pty only writes `name` into the child's TERM on the Unix path; - // the ConPTY path leaves the environment untouched, so Windows children - // inherit a missing or 16-color TERM unless it is set here. + // ConPTY ignores node-pty's name option for TERM; set it explicitly to avoid missing/16-color values. const env = platform === "win32" && input.env["TERM"] === undefined ? { ...input.env, TERM: "xterm-256color" } diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts index a12f9d6ecbf85..a05d635361b81 100644 --- a/apps/server/src/terminal/OutputProtocol.test.ts +++ b/apps/server/src/terminal/OutputProtocol.test.ts @@ -1,14 +1,20 @@ import { assert, describe, it } from "@effect/vitest"; -import { WS_METHODS } from "@t3tools/contracts"; +import { + type TerminalAttachStreamEvent, + TerminalAttachStreamEvent as TerminalAttachStreamEventSchema, + TerminalEvent as TerminalEventSchema, + WS_METHODS, +} from "@t3tools/contracts"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc"; -import { withTerminalOutputWindow } from "./OutputProtocol.ts"; +import { terminalOutputStream, withTerminalOutputWindow } from "./OutputProtocol.ts"; describe("terminal output window", () => { it.effect.each([ @@ -77,3 +83,279 @@ describe("terminal output window", () => { }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), ); }); + +const output = (data: string): TerminalAttachStreamEvent => ({ + type: "output", + threadId: "thread-1", + terminalId: "default", + data, +}); + +const snapshot = (history: string): TerminalAttachStreamEvent => ({ + type: "snapshot", + snapshot: { + threadId: "thread-1", + terminalId: "default", + cwd: "/repo", + worktreePath: null, + status: "running", + pid: 1, + history, + exitCode: null, + exitSignal: null, + label: "bash", + updatedAt: "2026-01-01T00:00:00.000Z", + }, +}); + +// Stands in for TerminalManager's fanout: listeners run in publish order and +// may release themselves while it iterates. +const makePublisher = () => { + const listeners = new Set<(event: TerminalAttachStreamEvent) => Effect.Effect>(); + return { + listeners, + subscribe: ( + listener: (event: TerminalAttachStreamEvent) => Effect.Effect, + registerCleanup?: (stop: () => void) => void, + ) => + Effect.sync(() => { + listeners.add(listener); + const stop = () => { + listeners.delete(listener); + }; + registerCleanup?.(stop); + return stop; + }), + publish: (event: TerminalAttachStreamEvent) => + Effect.forEach(listeners, (listener) => listener(event), { discard: true }), + }; +}; + +// Like TerminalManager.attachStream: a snapshot, then live events. +const attach = + (publisher: ReturnType, history: string) => + ( + listener: (event: TerminalAttachStreamEvent) => Effect.Effect, + registerCleanup: (stop: () => void) => void, + ) => + publisher + .subscribe(listener, registerCleanup) + .pipe(Effect.tap(() => listener(snapshot(history)))); + +const chunkBytes = (message: RpcMessage.FromServerEncoded) => + Buffer.byteLength(JSON.stringify(message)); + +describe("terminal output stream", () => { + it.effect.each([ + WS_METHODS.terminalAttach, + WS_METHODS.terminalObserve, + WS_METHODS.subscribeTerminalEvents, + ])("releases only the ACK-stalled subscriber on %s and resumes safely", (tag) => + Effect.gen(function* () { + const legacy = tag === WS_METHODS.subscribeTerminalEvents; + const group = RpcGroup.make( + Rpc.make(tag, { + success: legacy ? TerminalEventSchema : TerminalAttachStreamEventSchema, + stream: true, + }), + ); + const publisher = makePublisher(); + const stalled = yield* Queue.unbounded(); + const healthy = yield* Queue.unbounded(); + const receive = yield* Deferred.make[0]>(); + const protocol = yield* RpcServer.Protocol.make((write) => + Effect.gen(function* () { + yield* Deferred.succeed(receive, write); + const serialization = yield* RpcSerialization.RpcSerialization; + return { + disconnects: yield* Queue.unbounded(), + send: (clientId, response) => Queue.offer(clientId === 0 ? stalled : healthy, response), + end: () => Effect.void, + clientIds: Effect.succeed(new Set([0, 1])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: false, + supportsNotifications: true, + codecFor: serialization.codecFor, + }; + }), + ); + const initial = legacy ? output("ready") : snapshot(""); + yield* RpcServer.make(group).pipe( + Effect.provide( + group.toLayerHandler(tag, () => + terminalOutputStream( + (listener, registerCleanup) => + publisher + .subscribe(listener, registerCleanup) + .pipe(Effect.tap(() => listener(initial))), + legacy ? undefined : attach(publisher, "fresh history"), + 256 * 1024, + ), + ), + ), + Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)), + Effect.forkScoped, + ); + const write = yield* Deferred.await(receive); + const takeChunk = Effect.fnUntraced(function* (queue: typeof stalled) { + const response = yield* Queue.take(queue); + assert.equal(response._tag, "Chunk"); + if (response._tag !== "Chunk") throw new Error("Expected an RPC chunk"); + assert.isAtMost(chunkBytes(response), 70 * 1024); + return response.values; + }); + yield* write(0, { _tag: "Request", id: "1", tag, payload: null, headers: [] }); + assert.deepEqual(yield* takeChunk(stalled), [initial]); + yield* write(1, { _tag: "Request", id: "2", tag, payload: null, headers: [] }); + assert.deepEqual(yield* takeChunk(healthy), [initial]); + yield* write(1, { _tag: "Ack", requestId: "2" }); + + // Eight unacknowledged chunks fill only client 0's output window. + for (let index = 0; index < 7; index++) { + const event = output("before-stall-" + index); + yield* publisher.publish(event); + assert.deepEqual(yield* takeChunk(stalled), [event]); + assert.deepEqual(yield* takeChunk(healthy), [event]); + yield* write(1, { _tag: "Ack", requestId: "2" }); + } + assert.equal(publisher.listeners.size, 2); + for (let index = 0; index < 100; index++) { + const event = output(index + ":" + "界".repeat(1365)); + yield* publisher.publish(event); + assert.deepEqual(yield* takeChunk(healthy), [event]); + yield* write(1, { _tag: "Ack", requestId: "2" }); + if (index === 31) assert.equal(publisher.listeners.size, 2); + } + assert.equal(yield* Queue.size(stalled), 0); + assert.equal(publisher.listeners.size, 1); + + yield* write(0, { _tag: "Ack", requestId: "1" }); + if (legacy) { + assert.deepEqual(yield* Queue.take(stalled), { + _tag: "Exit", + requestId: "1", + exit: { _tag: "Success", value: null }, + }); + } else { + assert.deepEqual(yield* takeChunk(stalled), [snapshot("fresh history")]); + assert.equal(publisher.listeners.size, 2); + for (let index = 0; index < 7; index++) { + yield* write(0, { _tag: "Ack", requestId: "1" }); + } + } + const after = output("unique output after recovery"); + yield* publisher.publish(after); + assert.deepEqual(yield* takeChunk(healthy), [after]); + if (!legacy) assert.deepEqual(yield* takeChunk(stalled), [after]); + assert.equal(yield* Queue.size(stalled), 0); + }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), + ); + + it.effect("interrupts recovery while its subscription is still waiting", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const recovering = yield* Deferred.make(); + const interrupted = yield* Deferred.make(); + const pull = yield* Stream.toPull( + terminalOutputStream( + attach(publisher, ""), + () => + Deferred.succeed(recovering, undefined).pipe( + Effect.andThen(Effect.never), + Effect.onInterrupt(() => Deferred.succeed(interrupted, undefined)), + ), + 1024, + ), + ); + yield* pull; + yield* publisher.publish(output("x".repeat(1024))); + yield* publisher.publish(output("x".repeat(1024))); + assert.equal(publisher.listeners.size, 0); + + const recovery = yield* pull.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(recovering); + 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", () => + Effect.gen(function* () { + const publisher = makePublisher(); + for (const recovering of [false, true, false, true]) { + const handoff = yield* Deferred.make(); + const complete = yield* Deferred.make(); + const acquire: ReturnType = (listener, registerCleanup) => + attach(publisher, "")(listener, registerCleanup).pipe( + // Hold the successful exit before its cleanup handle reaches the caller. + Effect.onExit(() => + Deferred.succeed(handoff, undefined).pipe(Effect.andThen(Deferred.await(complete))), + ), + ); + const consumer = yield* Effect.gen(function* () { + const pull = yield* Stream.toPull( + terminalOutputStream(recovering ? attach(publisher, "") : acquire, acquire, 1024), + ); + yield* pull; + yield* publisher.publish(output("x".repeat(1024))); + yield* publisher.publish(output("x".repeat(1024))); + yield* pull; + }).pipe(Effect.scoped, Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(handoff); + assert.equal(publisher.listeners.size, 1); + const cancellation = yield* Fiber.interrupt(consumer).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.succeed(complete, undefined); + 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", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const pull = yield* Stream.toPull(terminalOutputStream(attach(publisher, ""))); + assert.deepEqual(yield* pull, [snapshot("")]); + // 1,024 code units but 3 KiB of UTF-8. + const data = "界".repeat(1024); + for (let index = 0; index < 1024; index++) yield* publisher.publish(output(data)); + + let delivered = 0; + while (delivered < 1024) { + const batch = yield* pull; + assert.isAtMost( + batch.reduce( + (bytes, event) => bytes + (event.type === "output" ? Buffer.byteLength(event.data) : 0), + 0, + ), + 64 * 1024, + ); + delivered += batch.length; + } + assert.equal(delivered, 1024); + }).pipe(Effect.scoped), + ); + + it.effect("charges snapshot history but never overflows on one snapshot", () => + Effect.gen(function* () { + const publisher = makePublisher(); + const history = "界".repeat(16 * 1024); + const events = terminalOutputStream(attach(publisher, history), undefined, 32 * 1024); + const pull = yield* Stream.toPull(events); + // A snapshot larger than the budget is still delivered. + assert.deepEqual(yield* pull, [snapshot(history)]); + assert.equal(publisher.listeners.size, 1); + + // Queued snapshots count their history: a second one overflows. + yield* publisher.publish(snapshot(history)); + 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/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts index 402ed32c022ae..5a0f596e84784 100644 --- a/apps/server/src/terminal/OutputProtocol.ts +++ b/apps/server/src/terminal/OutputProtocol.ts @@ -1,5 +1,9 @@ -import { WS_METHODS } from "@t3tools/contracts"; +import { type TerminalAttachStreamEvent, type TerminalEvent, WS_METHODS } from "@t3tools/contracts"; +import type * as Arr from "effect/Array"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as Latch from "effect/Latch"; +import * as Stream from "effect/Stream"; import type { RpcServer } from "effect/rpc"; const MAX_PENDING_CHUNKS = 8; @@ -66,3 +70,117 @@ export function withTerminalOutputWindow( }), }; } + +const MAX_QUEUED_OUTPUT = 8 * 1024 * 1024; +// Charge an envelope so tiny events cannot bypass the byte budget. +const EVENT_OVERHEAD = 128; + +type Listener = (event: A) => Effect.Effect; +// Acquisition must register cleanup synchronously with installing the listener. +type Subscribe = ( + listener: Listener, + registerCleanup: (stop: () => void) => void, +) => Effect.Effect<() => void, E>; + +const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) => + EVENT_OVERHEAD + + (event.type === "output" + ? Buffer.byteLength(event.data) + : "snapshot" in event + ? Buffer.byteLength(event.snapshot.history) + : 0); + +export function terminalOutputStream( + subscribe: Subscribe, + resync?: Subscribe, + maxQueued = MAX_QUEUED_OUTPUT, +): Stream.Stream { + return Stream.unwrap( + Effect.gen(function* () { + const ready = yield* Latch.make(); + let pending: Array = []; + let sizes: number[] = []; + let head = 0; + let queued = 0; + let overflowed = false; + let subscription = 0; + let unsubscribe: (() => void) | null = null; + const release = () => { + subscription += 1; + unsubscribe?.(); + unsubscribe = null; + pending = []; + sizes = []; + head = 0; + queued = 0; + }; + yield* Effect.addFinalizer(() => Effect.sync(release)); + + const listen = (from: Subscribe) => + Effect.suspend(() => { + const id = ++subscription; + return from( + (event) => + Effect.sync(() => { + if (id !== subscription) return; + const size = queuedSize(event); + pending.push(event); + sizes.push(size); + queued += size; + // A single snapshot must fit even when history fills the budget. + if (queued - sizes[head]! > maxQueued) { + release(); + overflowed = true; + } + ready.openUnsafe(); + }), + (stop) => { + // Overflow or cancellation may invalidate acquisition before registration. + if (id === subscription) unsubscribe = stop; + else stop(); + }, + ).pipe( + Effect.asVoid, + Effect.onError(() => Effect.sync(release)), + ); + }); + + const take = () => { + const event = pending[head]!; + pending[head] = undefined; + head += 1; + return event; + }; + const takeBatch = (): Arr.NonEmptyReadonlyArray => { + let bytes = sizes[head]!; + const batch: [A, ...A[]] = [take()]; + while (head < pending.length && bytes + sizes[head]! <= MAX_PENDING_BYTES) { + bytes += sizes[head]!; + batch.push(take()); + } + queued -= bytes; + if (head * 2 >= pending.length) { + pending = pending.slice(head); + sizes = sizes.slice(head); + head = 0; + } + return batch; + }; + + const pull: Effect.Effect, E | Cause.Done> = Effect.suspend( + () => { + if (overflowed) { + overflowed = false; + return resync ? listen(resync).pipe(Effect.andThen(pull)) : Cause.done(); + } + if (head < pending.length) return Effect.succeed(takeBatch()); + ready.closeUnsafe(); + return ready.await.pipe(Effect.andThen(pull)); + }, + ); + + yield* listen(subscribe); + return Stream.fromPull(Effect.succeed(pull)); + }), + ); +} diff --git a/apps/server/src/terminal/nodePtyConsoleList.test.ts b/apps/server/src/terminal/nodePtyConsoleList.test.ts index b412f3c8502a7..bcc8313089f43 100644 --- a/apps/server/src/terminal/nodePtyConsoleList.test.ts +++ b/apps/server/src/terminal/nodePtyConsoleList.test.ts @@ -3,9 +3,7 @@ import * as NodeModule from "node:module"; import { afterEach, describe, expect, it } from "vite-plus/test"; -// Exercises the patched console-list helper in patches/node-pty@1.2.0-beta.15.patch. -// The agent calls `require("child_process").fork` at call time, so replacing it on -// the shared CJS module stands in for the forked helper on every platform. +// The agent forks via the shared CJS module at call time; replace it to stub the helper on every platform. const requireCjs = NodeModule.createRequire(import.meta.url); const childProcess: typeof import("node:child_process") = requireCjs("child_process"); const { @@ -61,6 +59,7 @@ describe("node-pty console process list helper", () => { expect(list).toEqual([SHELL_PID]); }); + // regression: #18519 Windows terminal kill waited on timeouts it("falls back to the shell PID when the helper fails to spawn", async () => { const list = await getConsoleProcessList((helper) => { helper.emit("error", Object.assign(new Error("spawn ENOENT"), { code: "ENOENT" })); diff --git a/apps/server/src/testUtils/gitConfig.setup.ts b/apps/server/src/testUtils/gitConfig.setup.ts index a8139563ff3bf..f2ad4a83e2d54 100644 --- a/apps/server/src/testUtils/gitConfig.setup.ts +++ b/apps/server/src/testUtils/gitConfig.setup.ts @@ -1,8 +1,4 @@ -// Git for Windows installs with core.autocrlf=true, which checks committed LF -// files out as CRLF and breaks every byte-exact content assertion; a signing -// key or a non-default init branch on the developer's machine breaks fixtures -// the same way. Set as environment so each git child the driver spawns sees it -// without touching the fixtures. +// Override inherited autocrlf, signing and init-branch settings through env so every git child gets stable fixtures. const entries: ReadonlyArray = [ ["core.autocrlf", "false"], ["core.filemode", "false"], diff --git a/apps/server/src/testUtils/processProbe.ts b/apps/server/src/testUtils/processProbe.ts new file mode 100644 index 0000000000000..9970359244be3 --- /dev/null +++ b/apps/server/src/testUtils/processProbe.ts @@ -0,0 +1,73 @@ +// @effect-diagnostics nodeBuiltinImport:off - a socket observes fixture processes after their parent exits. +import * as NodeNet from "node:net"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as TestClock from "effect/testing/TestClock"; + +export const makeProcessProbe = Effect.gen(function* () { + const started = yield* Deferred.make(); + const exited = yield* Deferred.make(); + const sockets = new Set(); + const server = NodeNet.createServer((socket) => { + sockets.add(socket); + let output = ""; + socket.on("data", (chunk) => { + output += chunk.toString(); + if (output.includes("\n")) { + const pid = Number(output.trim()); + if (Number.isSafeInteger(pid) && pid > 0) { + Deferred.doneUnsafe(started, Effect.succeed(pid)); + } + } + }); + socket.on("close", () => { + sockets.delete(socket); + Deferred.doneUnsafe(exited, Effect.void); + }); + }); + yield* Effect.acquireRelease( + Effect.callback((resume) => { + server.once("error", (error) => resume(Effect.fail(error))); + server.listen(0, "127.0.0.1", () => resume(Effect.void)); + }), + () => + Effect.sync(() => { + for (const socket of sockets) socket.destroy(); + server.close(); + }), + ); + const address = server.address(); + if (address === null || typeof address === "string") { + return yield* Effect.die("Missing process probe port"); + } + return { + port: address.port, + started: Deferred.await(started).pipe( + Effect.timeout("4 seconds"), + TestClock.withLive, + Effect.tap((pid) => + Effect.addFinalizer(() => + Effect.gen(function* () { + if (yield* Deferred.isDone(exited)) return; + // Only a PID reported by this fixture is eligible for failure cleanup. + yield* Effect.sync(() => { + try { + process.kill(pid, "SIGKILL"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } + }); + }), + ), + ), + ), + exited: Deferred.await(exited).pipe(Effect.timeout("4 seconds"), TestClock.withLive), + }; +}); + +export const processProbeSource = (port: number) => ` + const { createConnection } = await import("node:net"); + const probe = createConnection(${port}, "127.0.0.1", () => { + probe.write(process.pid + "\\n"); + }); +`; diff --git a/apps/server/src/testUtils/shardWeights.json b/apps/server/src/testUtils/shardWeights.json index 54e1203030ad8..d0f1fafc69687 100644 --- a/apps/server/src/testUtils/shardWeights.json +++ b/apps/server/src/testUtils/shardWeights.json @@ -1,429 +1,216 @@ { "integration/transferBudgetV2.integration.test.ts": 3.1, - "src/assets/AssetAccess.test.ts": 1.7, - "src/assets/AttachmentUpload.test.ts": 0.4, - "src/assets/NativeAppIconResolver.test.ts": 1.0, - "src/assets/icns.test.ts": 0.1, - "src/attachmentStore.test.ts": 0.3, - "src/auth/EnvironmentAuth.test.ts": 0.9, + "src/assets/AssetAccess.test.ts": 1.3, + "src/auth/EnvironmentAuth.test.ts": 0.8, "src/auth/EnvironmentAuthAdmin.test.ts": 1.6, - "src/auth/EnvironmentAuthPolicy.test.ts": 0.4, "src/auth/McpOAuth.test.ts": 1.5, - "src/auth/PairingGrantStore.test.ts": 0.6, - "src/auth/RpcAuthorization.test.ts": 0.4, - "src/auth/ServerSecretStore.test.ts": 0.4, - "src/auth/SessionStore.test.ts": 1.4, + "src/auth/SessionStore.test.ts": 0.9, "src/auth/dpop.test.ts": 0.5, "src/auth/http.test.ts": 0.5, "src/auth/replayMarkers.test.ts": 3.7, - "src/auth/utils.test.ts": 0.1, - "src/background/BackgroundPolicy.test.ts": 0.3, - "src/background/HostPowerMonitor.test.ts": 0.4, - "src/bootstrap.test.ts": 0.4, - "src/checkpointing/CheckpointDiffQuery.test.ts": 1.3, - "src/checkpointing/CheckpointStore.test.ts": 1.7, - "src/checkpointing/Diffs.test.ts": 0.1, - "src/claudeModelOptions.test.ts": 0.4, + "src/checkpointing/CheckpointDiffQuery.test.ts": 1.1, + "src/checkpointing/CheckpointStore.test.ts": 0.9, "src/cli/app.test.ts": 2.4, "src/cli/config.test.ts": 0.6, - "src/cli/connect.test.ts": 0.4, - "src/cli/invocation.test.ts": 0.2, - "src/cli/pair.test.ts": 3.2, - "src/cli/project.test.ts": 3.1, + "src/cli/pair.test.ts": 2.4, + "src/cli/project.test.ts": 2.4, "src/cli/service.test.ts": 0.5, - "src/cli/sshHelper.test.ts": 2.4, "src/cli/theme.test.ts": 2.1, "src/cli/trace.test.ts": 1.2, "src/cli/triage.test.ts": 0.5, - "src/cli/triagePrompt.test.ts": 0.1, "src/cli/uninstall.test.ts": 0.5, "src/cli/update.test.ts": 1.7, - "src/cli/updateProgress.test.ts": 0.1, - "src/cliAuthFormat.test.ts": 0.2, - "src/cloud/CliState.test.ts": 0.3, "src/cloud/CliTokenManager.test.ts": 0.7, - "src/cloud/CloudLink.lifecycle.test.ts": 1.9, + "src/cloud/CloudLink.lifecycle.test.ts": 0.9, "src/cloud/CloudLink.test.ts": 1.1, - "src/cloud/ManagedEndpointRuntime.test.ts": 0.4, - "src/cloud/bootService.test.ts": 0.6, - "src/cloud/environmentKeys.test.ts": 0.4, + "src/cloud/bootService.test.ts": 0.5, "src/cloud/http.test.ts": 1.2, - "src/cloud/linkChecks.test.ts": 0.2, "src/cloud/managedTunnelStartup.test.ts": 0.5, - "src/cloud/pinnedRuntime.test.ts": 0.4, - "src/cloud/publicConfig.test.ts": 0.2, - "src/cloud/relayResponse.test.ts": 0.3, "src/cloud/selfUpdate.test.ts": 0.6, - "src/cloud/serviceLauncherClient.test.ts": 0.2, - "src/cloud/servicePreflight.test.ts": 0.1, - "src/cloud/traceRelayRequest.test.ts": 0.2, "src/codexModelOptions.test.ts": 0.6, - "src/compileCache.test.ts": 0.3, - "src/desktopUpdate/DesktopAppUpdate.test.ts": 0.3, - "src/device/AgentDeviceTarget.test.ts": 0.3, "src/device/DeviceActions.test.ts": 0.7, "src/device/DeviceHubProxy.stream.test.ts": 0.6, - "src/device/DeviceHubProxy.test.ts": 0.4, "src/device/DeviceMultiHost.test.ts": 0.5, "src/device/DeviceService.test.ts": 0.5, - "src/device/DeviceToolchain.test.ts": 0.4, - "src/device/LocalDeviceHost.test.ts": 0.4, "src/device/SshDeviceHost.test.ts": 0.5, - "src/device/deviceToolMaintenance.test.ts": 1.7, - "src/device/localSshDeviceHost.test.ts": 0.2, - "src/device/sshDeviceScript.test.ts": 3.3, - "src/diagnostics/ProcessDiagnostics.test.ts": 0.3, - "src/diagnostics/ProcessResourceMonitor.test.ts": 0.4, - "src/diagnostics/TraceDiagnostics.test.ts": 0.4, - "src/entrypoint.test.ts": 0.1, - "src/environment/DirectEndpoints.test.ts": 0.4, - "src/environment/RemoteOpenTargets.test.ts": 0.4, + "src/device/deviceToolMaintenance.test.ts": 1.3, "src/environment/ServerEnvironment.test.ts": 0.7, - "src/environment/ServerEnvironmentLabel.test.ts": 0.3, - "src/environment/ServerEnvironmentMachine.test.ts": 0.3, - "src/environmentTheme.test.ts": 0.6, - "src/git/GitManager.test.ts": 46.5, + "src/git/GitManager.test.ts": 13.7, "src/git/GitWorkflowService.test.ts": 2.7, - "src/git/detachStackFrame.memory.test.ts": 0.8, "src/git/linkCreatedPullRequest.test.ts": 1.2, - "src/htmlRender/HtmlRender.test.ts": 0.4, - "src/htmlRender/publicProxy.test.ts": 0.2, - "src/http.test.ts": 2.0, - "src/httpResponseErrorGuard.test.ts": 0.2, - "src/imageMime.test.ts": 0.1, - "src/keybindings.test.ts": 0.4, - "src/mcp/AcpMcpStdioBridge.test.ts": 0.3, + "src/http.test.ts": 2, "src/mcp/McpDeviceToolkit.test.ts": 1.5, - "src/mcp/McpHttpServer.test.ts": 2.2, - "src/mcp/McpInvocationContext.test.ts": 0.3, + "src/mcp/McpHttpServer.test.ts": 1.3, "src/mcp/McpSessionRegistry.test.ts": 1.1, "src/mcp/McpToolAccess.race.test.ts": 1.4, "src/mcp/McpToolAccess.test.ts": 1.2, "src/mcp/OrchestratorMcpService.activity.test.ts": 1.1, "src/mcp/OrchestratorMcpService.test.ts": 1.2, - "src/mcp/OrchestratorMcpToolkit.integration.test.ts": 14.4, + "src/mcp/OrchestratorMcpToolkit.integration.test.ts": 1.2, "src/mcp/PreviewAutomationBroker.test.ts": 0.5, - "src/mcp/TaskCancelNativeSubagent.integration.test.ts": 1.4, - "src/mcp/ThreadMetadataMcpService.test.ts": 1.2, - "src/mcp/WorktreeMcpService.test.ts": 1.2, + "src/mcp/TaskCancelNativeSubagent.integration.test.ts": 1, + "src/mcp/WorktreeMcpService.test.ts": 0.9, "src/mcp/toolkits/core.test.ts": 1.7, "src/mcp/toolkits/device/handlers.test.ts": 1.4, "src/mcp/toolkits/environment/handlers.test.ts": 1.1, - "src/mcp/toolkits/orchestrator/tools.test.ts": 1.1, "src/mcp/toolkits/preview/handlers.test.ts": 1.4, "src/mcp/toolkits/preview/tools.test.ts": 3.6, "src/mcp/toolkits/previewControls/handlers.test.ts": 1.6, "src/mcp/toolkits/project/handlers.test.ts": 1.3, "src/mcp/toolkits/pullRequests/handlers.test.ts": 1.3, - "src/mcp/toolkits/worktree/registration.test.ts": 1.5, - "src/mcpApps/McpAppModelContext.test.ts": 1.0, + "src/mcpApps/McpAppModelContext.test.ts": 1, "src/mcpApps/McpAppRequests.test.ts": 1.3, "src/observability/DefectReporter.test.ts": 1.2, - "src/observability/EventLoopMonitor.test.ts": 0.3, - "src/observability/HeapSnapshot.test.ts": 0.4, - "src/observability/Metrics.test.ts": 1.0, "src/observability/OtlpEndpointCheck.test.ts": 0.5, - "src/observability/RpcInstrumentation.test.ts": 0.3, - "src/orchestration-v2/AcpRegistryOrchestratorV2.live.test.ts": 1.3, - "src/orchestration-v2/Adapters/AcpAdapterV2.test.ts": 55.1, - "src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts": 2.6, - "src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts": 1.3, - "src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts": 9.5, + "src/orchestration-v2/Adapters/AcpAdapterV2.test.ts": 25.5, + "src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts": 1.3, + "src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts": 1.1, "src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts": 0.6, - "src/orchestration-v2/Adapters/CodexAdapterV2.test.ts": 7.2, - "src/orchestration-v2/Adapters/GrokAdapterV2.test.ts": 0.5, - "src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts": 4.8, - "src/orchestration-v2/Adapters/claudeWorkflowProgress.test.ts": 0.2, - "src/orchestration-v2/AttachmentClaims.test.ts": 0.4, - "src/orchestration-v2/BackgroundWorkStop.integration.test.ts": 5.7, + "src/orchestration-v2/Adapters/CodexAdapterV2.test.ts": 4.5, + "src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts": 2.8, + "src/orchestration-v2/BackgroundWorkStop.integration.test.ts": 4.3, "src/orchestration-v2/CheckpointCaptureService.test.ts": 0.5, "src/orchestration-v2/CheckpointRestoreSafety.test.ts": 0.6, "src/orchestration-v2/CheckpointRollbackService.test.ts": 0.6, "src/orchestration-v2/CheckpointScopeOwnership.test.ts": 2.6, - "src/orchestration-v2/CheckpointService.test.ts": 0.4, - "src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts": 2.1, + "src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts": 1.6, "src/orchestration-v2/CommandPolicy.test.ts": 0.6, - "src/orchestration-v2/ContextHandoffBudget.test.ts": 0.4, - "src/orchestration-v2/ContextHandoffService.test.ts": 0.3, - "src/orchestration-v2/CursorOrchestratorV2.live.test.ts": 2.0, "src/orchestration-v2/DelegatedCompletionDelivery.test.ts": 2.1, "src/orchestration-v2/DispatchModeLimit.test.ts": 1.1, "src/orchestration-v2/EffectWorker.test.ts": 1.2, - "src/orchestration-v2/FoundationPersistence.test.ts": 4.7, - "src/orchestration-v2/GrokOrchestratorV2.live.test.ts": 1.2, - "src/orchestration-v2/LiveStreamBudget.test.ts": 0.2, - "src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts": 6.3, - "src/orchestration-v2/OpenCode2OrchestratorV2.live.test.ts": 1.7, + "src/orchestration-v2/FoundationPersistence.test.ts": 3.2, + "src/orchestration-v2/OpenCode2OrchestratorV2.integration.test.ts": 4, "src/orchestration-v2/Orchestrator.control-reads.test.ts": 1.4, "src/orchestration-v2/Orchestrator.migration.test.ts": 1.5, - "src/orchestration-v2/ProjectCommands.test.ts": 0.3, "src/orchestration-v2/ProjectSettingsUpgrade.integration.test.ts": 1.4, - "src/orchestration-v2/ProjectStore.test.ts": 0.4, "src/orchestration-v2/ProjectionControlReads.test.ts": 5.3, "src/orchestration-v2/ProjectionRecovery.test.ts": 1.7, "src/orchestration-v2/ProjectionSettlement.test.ts": 1.3, - "src/orchestration-v2/ProjectionStore.test.ts": 2.6, - "src/orchestration-v2/ProviderAdapterRegistry.test.ts": 0.4, + "src/orchestration-v2/ProjectionStore.test.ts": 1.5, "src/orchestration-v2/ProviderContinuationService.test.ts": 1.2, - "src/orchestration-v2/ProviderEventIngestor.test.ts": 4.6, - "src/orchestration-v2/ProviderRuntimeRecoveryPerformance.test.ts": 2.5, + "src/orchestration-v2/ProviderEventIngestor.test.ts": 2.1, "src/orchestration-v2/ProviderRuntimeRecoveryService.regression.test.ts": 1.4, "src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts": 1.2, - "src/orchestration-v2/ProviderSelectionTransition.test.ts": 0.4, - "src/orchestration-v2/ProviderSessionManager.test.ts": 2.6, + "src/orchestration-v2/ProviderSessionManager.test.ts": 1.8, "src/orchestration-v2/ProviderSessionTransitionPolicy.test.ts": 0.5, "src/orchestration-v2/ProviderSwitchService.test.ts": 0.6, "src/orchestration-v2/ProviderTurnControlService.test.ts": 1.3, - "src/orchestration-v2/ProviderTurnStartService.memory.test.ts": 8.0, "src/orchestration-v2/ProviderTurnStartService.test.ts": 1.4, "src/orchestration-v2/ProviderTurnTokenUsage.test.ts": 0.6, "src/orchestration-v2/PullRequestSyncReactor.test.ts": 2.3, - "src/orchestration-v2/QueuedRunOrder.test.ts": 0.1, - "src/orchestration-v2/RestartBackgroundNote.test.ts": 0.3, "src/orchestration-v2/RestartContinuation.test.ts": 1.5, "src/orchestration-v2/RunCompletionReads.test.ts": 0.5, "src/orchestration-v2/RunExecutionService.test.ts": 1.4, "src/orchestration-v2/RunFinalizationService.test.ts": 1.1, - "src/orchestration-v2/RuntimePolicy.test.ts": 0.3, "src/orchestration-v2/RuntimeRequestService.test.ts": 0.6, - "src/orchestration-v2/SelectionRestart.integration.test.ts": 3.7, + "src/orchestration-v2/SelectionRestart.integration.test.ts": 2.4, "src/orchestration-v2/ShellStream.test.ts": 0.5, - "src/orchestration-v2/SteeringCompletion.integration.test.ts": 5.5, - "src/orchestration-v2/SubagentProjection.test.ts": 0.4, + "src/orchestration-v2/SteeringCompletion.integration.test.ts": 4.5, "src/orchestration-v2/ThreadDeletion.test.ts": 0.5, - "src/orchestration-v2/ThreadFind.test.ts": 1.6, + "src/orchestration-v2/ThreadFind.test.ts": 1, "src/orchestration-v2/ThreadFork.execution.test.ts": 1.4, - "src/orchestration-v2/ThreadForkService.test.ts": 0.4, - "src/orchestration-v2/ThreadLaunchService.test.ts": 4.5, - "src/orchestration-v2/ThreadLifecycleService.test.ts": 1.9, - "src/orchestration-v2/ThreadLiveEventCoalescer.test.ts": 0.3, - "src/orchestration-v2/ThreadManagementService.test.ts": 2.0, + "src/orchestration-v2/ThreadLaunchService.test.ts": 2.1, + "src/orchestration-v2/ThreadManagementService.test.ts": 0.7, "src/orchestration-v2/ThreadMessageIntake.test.ts": 1.1, "src/orchestration-v2/ThreadPullRequestService.test.ts": 1.2, "src/orchestration-v2/ThreadSearch.test.ts": 0.6, - "src/orchestration-v2/ThreadSettlementService.test.ts": 2.0, - "src/orchestration-v2/ThreadStop.test.ts": 2.5, - "src/orchestration-v2/ThreadStream.test.ts": 0.3, - "src/orchestration-v2/ThreadTitleRegenerationService.test.ts": 1.8, - "src/orchestration-v2/ThreadTransportPerformance.test.ts": 0.4, + "src/orchestration-v2/ThreadSettlementService.test.ts": 2, + "src/orchestration-v2/ThreadStop.test.ts": 2.1, + "src/orchestration-v2/ThreadTitleRegenerationService.test.ts": 1.2, "src/orchestration-v2/TurnItemPositionStore.test.ts": 0.5, "src/orchestration-v2/TurnStartReads.test.ts": 0.6, - "src/orchestration-v2/UserFacingErrors.test.ts": 0.4, - "src/orchestration-v2/V1ImportBoundary.test.ts": 0.3, - "src/orchestration-v2/WireProjection.test.ts": 0.4, - "src/orchestration-v2/assistantStreaming.test.ts": 0.3, "src/orchestration-v2/boundedSnapshotTransport.test.ts": 2.2, - "src/orchestration-v2/legacy/LegacyV1Cutover.integration.test.ts": 1.8, + "src/orchestration-v2/legacy/LegacyV1Cutover.integration.test.ts": 1.4, "src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts": 0.5, - "src/orchestration-v2/pullRequestWatch.test.ts": 0.4, - "src/orchestration-v2/runtimeLayer.test.ts": 3.1, - "src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts": 2.7, - "src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts": 1.7, - "src/orchestration-v2/testkit/OrchestratorReplayFixtures.contract.test.ts": 1.3, - "src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts": 60.3, - "src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts": 2.7, - "src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts": 2.4, - "src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts": 27.3, - "src/orchestration-v2/testkit/ThreadFork.integration.test.ts": 4.3, - "src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts": 6.6, - "src/orchestration-v2/threadHistoryPaging.test.ts": 0.3, - "src/orchestration-v2/toolOutputImageBytes.test.ts": 0.3, - "src/orchestration-v2/workflowAgentAnswers.test.ts": 0.3, + "src/orchestration-v2/runtimeLayer.test.ts": 2.8, + "src/orchestration-v2/testkit/AcpRegistryReplayFixtures.integration.test.ts": 4.8, + "src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts": 13.7, + "src/orchestration-v2/testkit/CodexReplayFixtures.integration.test.ts": 6.4, + "src/orchestration-v2/testkit/CursorReplayFixtures.integration.test.ts": 4.8, + "src/orchestration-v2/testkit/GrokReplayFixtures.integration.test.ts": 5.1, + "src/orchestration-v2/testkit/MuseReplayFixtures.integration.test.ts": 2.4, + "src/orchestration-v2/testkit/OpenCodeReplayFixtures.integration.test.ts": 5.8, + "src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts": 2.2, + "src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts": 2.1, + "src/orchestration-v2/testkit/PiReplayFixtures.integration.test.ts": 4.3, + "src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts": 16.1, + "src/orchestration-v2/testkit/ThreadFork.integration.test.ts": 2.9, + "src/orchestration-v2/testkit/ThreadMergeBack.integration.test.ts": 5.1, "src/orchestration-v2/workflowScriptQuery.test.ts": 0.9, - "src/os-jank.test.ts": 0.2, - "src/persistence/Errors.test.ts": 0.2, "src/persistence/Migrations.test.ts": 0.5, - "src/persistence/Migrations/016_CanonicalizeModelSelections.test.ts": 0.4, - "src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.test.ts": 0.4, "src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.test.ts": 1.1, - "src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.test.ts": 0.4, - "src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts": 0.3, - "src/persistence/Migrations/027_028_ProviderInstanceIdColumns.test.ts": 0.3, - "src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.test.ts": 0.4, - "src/persistence/Migrations/031_AuthAuthorizationScopes.test.ts": 0.4, - "src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.test.ts": 0.8, - "src/persistence/Migrations/040_ProjectionProjectFaviconPath.test.ts": 0.4, - "src/persistence/Migrations/041_AuthSessionClientConnection.test.ts": 0.4, - "src/persistence/Migrations/042_ProjectionThreadLinkedPullRequest.test.ts": 0.3, - "src/persistence/Migrations/046_RepairAutomaticSettlementTimestamps.test.ts": 0.4, - "src/persistence/Migrations/047_ProjectionProjectIcon.test.ts": 0.4, "src/persistence/Migrations/049_ProjectionThreadsActiveOrderKey.test.ts": 0.6, - "src/persistence/Migrations/050_ProjectionThreadPullRequests.test.ts": 0.4, "src/persistence/Migrations/051_ProjectionThreadMessageContext.test.ts": 0.5, - "src/persistence/Migrations/054_ProjectionThreadsAutoSettleDisabledAt.test.ts": 0.3, - "src/persistence/Migrations/055_OrchestrationV2.application-event-source.test.ts": 0.4, - "src/persistence/Migrations/055_OrchestrationV2.effect-cancellation.test.ts": 0.4, - "src/persistence/Migrations/055_OrchestrationV2.test.ts": 1.4, - "src/persistence/Migrations/056_RemoveRedundantProjectionIndexes.test.ts": 0.5, "src/persistence/Migrations/057_ScheduledTaskWebhooks.test.ts": 0.5, - "src/persistence/OrchestrationEventStore.sequence.test.ts": 0.6, - "src/persistence/OrchestrationEventStore.test.ts": 2.5, - "src/persistence/RepositoryErrorCorrelation.test.ts": 0.4, - "src/persistence/Sqlite.test.ts": 1.0, + "src/persistence/OrchestrationEventStore.test.ts": 0.5, "src/persistence/initializeV2Database.test.ts": 0.6, "src/persistence/reconcileV2PreviewMigration.test.ts": 1.1, - "src/preview/DesktopBrowserChannel.test.ts": 0.5, - "src/preview/Manager.test.ts": 0.3, - "src/preview/PortScanner.test.ts": 0.4, - "src/preview/PreviewBrowser.test.ts": 0.4, - "src/preview/PreviewBrowserHost.test.ts": 0.2, - "src/preview/ServerBrowser.test.ts": 0.9, "src/preview/ServerBrowserContexts.test.ts": 0.6, - "src/preview/ServerBrowserPage.test.ts": 2.7, + "src/preview/ServerBrowserPage.test.ts": 1.2, "src/preview/ServerBrowserStream.test.ts": 1.5, - "src/preview/SessionControl.test.ts": 0.1, - "src/process/agentScope.test.ts": 0.4, - "src/process/externalLauncher.test.ts": 2.7, - "src/processRunner.test.ts": 0.7, "src/project/AgentSessionImporter.test.ts": 1.5, - "src/project/AgentSessionJson.test.ts": 0.2, - "src/project/AgentSessionScanner.test.ts": 5.9, - "src/project/ManagedProjectFolders.test.ts": 2.2, + "src/project/AgentSessionScanner.test.ts": 0.8, + "src/project/ManagedProjectFolders.test.ts": 1.7, "src/project/ProjectCloneTracker.test.ts": 0.5, - "src/project/ProjectEnrichmentService.test.ts": 0.4, - "src/project/ProjectFaviconResolver.test.ts": 0.4, - "src/project/ProjectMutation.test.ts": 1.0, "src/project/ProjectService.deletion.test.ts": 0.7, "src/project/ProjectService.test.ts": 1.5, - "src/project/ProjectSetupScriptRunner.test.ts": 1.1, - "src/project/RepositoryIdentityResolver.test.ts": 0.5, - "src/project/T3ProjectFileLoader.test.ts": 0.3, "src/project/WorktreeSetupTracker.test.ts": 0.6, - "src/project/http.test.ts": 1.5, - "src/provider/AcpRegistryProbe.test.ts": 1.4, - "src/provider/AntigravityAuth.test.ts": 0.4, - "src/provider/AntigravityInstallation.test.ts": 0.5, - "src/provider/AntigravityProvider.test.ts": 0.4, + "src/provider/AcpRegistryProbe.test.ts": 0.9, "src/provider/ClaudeCapabilitiesProbe.test.ts": 0.7, - "src/provider/ClaudeModelCatalog.test.ts": 0.3, - "src/provider/CodexAuthCallback.test.ts": 0.3, - "src/provider/CodexChatGptAuth.test.ts": 7.1, - "src/provider/CodexChatGptModels.test.ts": 0.2, + "src/provider/CodexChatGptAuth.test.ts": 3.6, "src/provider/CodexChatGptSessionLock.test.ts": 0.5, - "src/provider/CodexDeveloperInstructions.test.ts": 0.1, - "src/provider/CodexInstallation.test.ts": 0.9, - "src/provider/CodexManagedErrors.test.ts": 0.2, - "src/provider/CodexManagedRuntime.test.ts": 0.4, - "src/provider/CodexMcpElicitation.test.ts": 0.1, - "src/provider/CodexProvider.catalog.test.ts": 1.1, "src/provider/CodexProvider.test.ts": 0.5, "src/provider/CodexThreadRevert.test.ts": 0.6, - "src/provider/Drivers/AntigravityDriver.test.ts": 3.0, - "src/provider/Drivers/AntigravitySkills.test.ts": 0.3, - "src/provider/Drivers/ClaudeExecutable.test.ts": 0.2, - "src/provider/Drivers/ClaudeHome.test.ts": 0.2, - "src/provider/Drivers/ClaudeSkillDispatch.test.ts": 0.1, - "src/provider/Drivers/ClaudeSkills.test.ts": 0.2, + "src/provider/Drivers/AntigravityDriver.test.ts": 1.2, "src/provider/Drivers/CodexDriver.test.ts": 0.8, - "src/provider/Drivers/CodexHomeLayout.test.ts": 0.4, - "src/provider/Drivers/antigravityUsageReader.test.ts": 0.3, - "src/provider/Drivers/claudeUsage.test.ts": 0.1, - "src/provider/Drivers/codexUsage.test.ts": 0.3, - "src/provider/EventNdjsonLogger.test.ts": 0.4, - "src/provider/GrokProvider.test.ts": 1.8, + "src/provider/GrokProvider.test.ts": 1.2, "src/provider/ModelManifest.test.ts": 0.6, - "src/provider/OpenCode2Client.events.test.ts": 0.4, - "src/provider/ProjectSettingsOverrideSweep.test.ts": 0.4, "src/provider/ProviderAuthService.test.ts": 0.5, - "src/provider/ProviderCredentialStore.test.ts": 0.4, - "src/provider/ProviderInstanceRegistry.test.ts": 10.7, + "src/provider/ProviderInstanceRegistry.test.ts": 1, "src/provider/ProviderInstanceRegistryHydration.test.ts": 1.1, - "src/provider/ProviderRegistry.test.ts": 1.3, - "src/provider/TurnTokenUsage.test.ts": 0.2, - "src/provider/acp/AcpJsonRpcConnection.test.ts": 11.1, - "src/provider/acp/AcpSessionRuntime.processTree.test.ts": 3.7, - "src/provider/acp/AntigravityAcpSupport.test.ts": 0.4, - "src/provider/acp/AntigravityProtocol.test.ts": 0.2, - "src/provider/antigravityAuthSupport.test.ts": 0.7, - "src/provider/antigravityCallback.test.ts": 0.3, + "src/provider/ProviderRegistry.test.ts": 0.7, + "src/provider/acp/AcpJsonRpcConnection.test.ts": 6.1, + "src/provider/acp/AcpSessionRuntime.processTree.test.ts": 1, "src/provider/antigravityUsageLimits.test.ts": 0.6, - "src/provider/claudeResetCredits.test.ts": 0.2, - "src/provider/claudeUsageLimits.test.ts": 0.1, - "src/provider/codexLaunchArgs.test.ts": 0.1, - "src/provider/codexModelCatalog.test.ts": 0.3, - "src/provider/codexUsageLimits.test.ts": 0.2, "src/provider/providerCompatibility.test.ts": 1.6, "src/provider/providerInstallation.test.ts": 1.1, "src/provider/providerMaintenanceRunner.test.ts": 0.5, - "src/provider/providerStatusCache.test.ts": 0.3, - "src/provider/resetCreditCoordinator.test.ts": 0.1, - "src/provider/userInputAttachments.test.ts": 0.3, - "src/pullRequest/PullRequestProviderRateLimit.test.ts": 0.4, - "src/pullRequest/PullRequestReadCache.test.ts": 0.4, - "src/pullRequest/PullRequestReviewGuideService.test.ts": 4.0, - "src/pullRequest/PullRequestService.test.ts": 8.7, - "src/pullRequest/linkedThreads.test.ts": 0.4, - "src/pullRequest/pullRequestReviewGuideInput.test.ts": 0.1, - "src/pullRequest/pullRequestReviewGuideNormalize.test.ts": 0.1, + "src/pullRequest/PullRequestReviewGuideService.test.ts": 0.7, + "src/pullRequest/PullRequestService.test.ts": 4.6, "src/pullRequest/pullRequestSyncKey.test.ts": 0.7, "src/relay/AgentAwarenessRelay.test.ts": 1.6, - "src/resourceTelemetry/DesktopTelemetryReceiver.test.ts": 0.3, - "src/resourceTelemetry/Model.test.ts": 0.3, - "src/resourceTelemetry/NativeTelemetryClient.test.ts": 0.4, - "src/resourceTelemetry/ResourceMonitorBinary.test.ts": 0.3, "src/resourceTelemetry/ResourceTelemetry.test.ts": 0.5, - "src/resourceTelemetry/ResourceTelemetryHistory.test.ts": 0.2, - "src/review/ReviewService.test.ts": 0.4, - "src/rpcInitialItems.memory.test.ts": 8.1, - "src/scheduledTasks/Schedule.test.ts": 0.3, "src/scheduledTasks/ScheduledTaskService.schedule.test.ts": 1.5, "src/scheduledTasks/ScheduledTaskService.test.ts": 1.5, - "src/scheduledTasks/ScheduledTaskService.webhook.test.ts": 2.6, + "src/scheduledTasks/ScheduledTaskService.webhook.test.ts": 1.5, "src/scheduledTasks/webhookRoute.test.ts": 1.4, - "src/scheduledTasks/webhookTemplate.test.ts": 0.1, - "src/scheduledTasks/webhookVerification.test.ts": 0.2, - "src/scheduling/Scheduler.integration.test.ts": 1.5, - "src/scheduling/Scheduler.test.ts": 0.2, "src/secrets/SecretRequests.test.ts": 2.6, - "src/serverActivation.test.ts": 0.2, - "src/serverLifecycleEvents.test.ts": 0.4, - "src/serverLogger.test.ts": 0.3, "src/serverRuntimeStartup.autoPull.test.ts": 1.3, "src/serverRuntimeStartup.test.ts": 1.3, "src/serverRuntimeState.test.ts": 1.1, - "src/serverSettings.test.ts": 3.0, + "src/serverSettings.test.ts": 1.6, "src/serviceLauncher.test.ts": 11.2, "src/sourceControl/BitbucketApi.test.ts": 0.6, - "src/sourceControl/SourceControlDiscovery.test.ts": 0.6, "src/sourceControl/SourceControlProviderRegistry.test.ts": 0.5, - "src/sourceControl/SourceControlRepositoryService.test.ts": 0.4, - "src/sourceControl/gitHubChangeRequestTemplate.test.ts": 1.0, - "src/sourceControl/githubStackRebase.test.ts": 2.9, + "src/sourceControl/githubStackRebase.test.ts": 1.5, "src/startupAccess.test.ts": 0.5, - "src/storageCleanup.test.ts": 2.8, - "src/telemetry/AnalyticsService.test.ts": 0.4, - "src/telemetry/Identify.test.ts": 0.4, - "src/terminal/Manager.test.ts": 4.7, - "src/terminal/NodePtyAdapter.test.ts": 0.2, + "src/storageCleanup.test.ts": 1.4, + "src/terminal/Manager.test.ts": 0.9, "src/terminal/OutputProtocol.test.ts": 0.9, - "src/testUtils/weightedShardSequencer.test.ts": 0.3, "src/textGeneration/AntigravityTextGeneration.test.ts": 0.5, - "src/textGeneration/ClaudeTextGeneration.test.ts": 0.9, - "src/textGeneration/CodexTextGeneration.test.ts": 1.6, - "src/textGeneration/GrokTextGeneration.test.ts": 1.3, + "src/textGeneration/CodexTextGeneration.test.ts": 1, + "src/textGeneration/GrokTextGeneration.test.ts": 0.5, "src/textGeneration/OpenCode2TextGeneration.test.ts": 1.4, "src/textGeneration/TextGeneration.test.ts": 1.2, "src/textGeneration/ThreadTitleLinks.test.ts": 0.5, "src/usage/UsageLimitSources.test.ts": 0.6, - "src/usage/UsageService.test.ts": 2.8, + "src/usage/UsageService.test.ts": 2.2, "src/usage/cliproxyApi.test.ts": 0.5, - "src/usage/usageAggregation.test.ts": 0.2, - "src/usage/usagePricing.test.ts": 0.4, - "src/usage/usageScanCache.test.ts": 0.3, - "src/usage/usageTranscriptReader.test.ts": 0.3, "src/usage/usageTranscriptStreaming.test.ts": 1.1, - "src/utils/subscribeBeforeSnapshot.test.ts": 0.1, - "src/vcs/GitVcsDriver.test.ts": 6.5, - "src/vcs/GitVcsDriverCore.test.ts": 13.6, - "src/vcs/VcsDriverRegistry.test.ts": 0.3, - "src/vcs/VcsProcess.test.ts": 0.5, + "src/vcs/GitVcsDriver.test.ts": 2.8, + "src/vcs/GitVcsDriverCore.test.ts": 7.2, "src/vcs/VcsProjectConfig.test.ts": 0.7, - "src/vcs/VcsProvisioningService.test.ts": 0.4, "src/vcs/VcsStatusBroadcaster.test.ts": 1.3, - "src/workspace/WorkspaceEntries.test.ts": 2.5, - "src/workspace/WorkspaceFileSystem.test.ts": 0.4, - "src/workspace/WorkspacePaths.test.ts": 0.2, - "src/workspace/WorkspaceSearchIndex.test.ts": 0.2, - "src/workspace/fileHeaderMimeType.test.ts": 0.1, + "src/workspace/WorkspaceEntries.test.ts": 0.8, "src/ws.test.ts": 1.9 } diff --git a/apps/server/src/testUtils/weightedShardSequencer.test.ts b/apps/server/src/testUtils/weightedShardSequencer.test.ts deleted file mode 100644 index 4d898a1bb9d90..0000000000000 --- a/apps/server/src/testUtils/weightedShardSequencer.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import type { TestSpecification, Vitest } from "vite-plus/test/node"; - -import shardWeights from "./shardWeights.json" with { type: "json" }; -import { WeightedShardSequencer } from "./weightedShardSequencer.ts"; - -const root = "/repo/apps/server"; -const recordedSeconds: Readonly> = shardWeights; -const recorded = Object.keys(recordedSeconds); -const files = [...recorded, ...Array.from({ length: 300 }, (_, i) => `src/fast${i}.test.ts`)]; -const specs = files.map((file) => ({ moduleId: `${root}/${file}` }) as TestSpecification); - -const shardModuleIds = (count: number) => - Promise.all( - Array.from({ length: count }, async (_, i) => { - const ctx = { config: { root, shard: { index: i + 1, count } } } as unknown as Vitest; - const shard = await new WeightedShardSequencer(ctx).shard(specs); - return shard.map((spec) => spec.moduleId); - }), - ); - -describe("WeightedShardSequencer", () => { - it("runs every file in exactly one shard", async () => { - const shards = await shardModuleIds(6); - - expect(shards.flat().toSorted()).toEqual(specs.map((spec) => spec.moduleId).toSorted()); - }); - - it("puts each of the slowest files in a different shard", async () => { - const slowest = new Set( - recorded - .toSorted((a, b) => (recordedSeconds[b] ?? 0) - (recordedSeconds[a] ?? 0)) - .slice(0, 6) - .map((file) => `${root}/${file}`), - ); - const shards = await shardModuleIds(6); - - for (const shard of shards) { - expect(shard.filter((moduleId) => slowest.has(moduleId))).toHaveLength(1); - } - }); -}); diff --git a/apps/server/src/testUtils/weightedShardSequencer.ts b/apps/server/src/testUtils/weightedShardSequencer.ts index 6aed9892443d5..51c5130b3a5c4 100644 --- a/apps/server/src/testUtils/weightedShardSequencer.ts +++ b/apps/server/src/testUtils/weightedShardSequencer.ts @@ -6,21 +6,12 @@ import { BaseSequencer, type TestSpecification } from "vite-plus/test/node"; import shardWeights from "./shardWeights.json" with { type: "json" }; -// The median recorded file, for files added since the weights were recorded. +// Use the recorded median for new files. const UNRECORDED_FILE_SECONDS = 0.6; const recordedSeconds: Readonly> = shardWeights; -/** - * Splits server test files across `--shard` runs by recorded duration. Vitest's - * default split hashes file paths into equal-count shards, which can put the - * slowest files on one runner. Here the longest file goes to the lightest shard - * first. Every shard derives the same split from the same file list, so each - * file still runs in exactly one shard. Weights are each file's wall time in a - * CI shard, imports included: the gaps between consecutive file results in the - * `Test Server` logs. Imports are about a third of a shard, so test time alone - * leaves the shards with many small files slowest. - */ +// Include import time (~1/3 of CI shards) in weights; derive identical splits so each file runs once. export class WeightedShardSequencer extends BaseSequencer { override async shard(files: TestSpecification[]) { const { index, count } = this.ctx.config.shard ?? { index: 1, count: 1 }; diff --git a/apps/server/src/testkit/RpcInitialMemory.fixture.mjs b/apps/server/src/testkit/RpcInitialMemory.fixture.mjs deleted file mode 100644 index a9648abf67155..0000000000000 --- a/apps/server/src/testkit/RpcInitialMemory.fixture.mjs +++ /dev/null @@ -1,130 +0,0 @@ -import * as NodeModule from "node:module"; -import * as NodeURL from "node:url"; -import * as NodeCrypto from "node:crypto"; -import * as NodeAssert from "node:assert/strict"; - -const root = process.argv[2]; -const mode = process.argv[3]; -const count = Number(process.argv[4] ?? 4); -const bytes = Number(process.argv[5] ?? 32768); -const require = NodeModule.createRequire(root + "/apps/server/package.json"); -const load = (name) => import(NodeURL.pathToFileURL(require.resolve("effect/" + name))); -const [Effect, Stream, Layer, Deferred, Fiber] = await Promise.all( - ["Effect", "Stream", "Layer", "Deferred", "Fiber"].map(load), -); -const app = (file) => import(NodeURL.pathToFileURL(root + "/apps/server/src/" + file + ".ts")); -const [Prefix, Ws, Threads, Events] = await Promise.all([ - app("rpcInitialItems"), - app("ws"), - app("orchestration-v2/ThreadManagementService"), - app("persistence/OrchestrationEventStore"), -]); -const refs = []; -const fibers = []; -const checkpoints = []; -const deliveredCounts = []; - -function history() { - const value = JSON.parse(JSON.stringify({ text: NodeCrypto.randomBytes(bytes).toString("hex") })); - refs.push(new WeakRef(value)); - return value; -} - -function start(ready) { - const index = deliveredCounts.push(0) - 1; - const live = Stream.fromEffect(Deferred.succeed(ready, undefined)).pipe( - Stream.drain, - Stream.concat(Stream.never), - ); - const dependencies = Layer.mergeAll( - Layer.mock(Threads.ThreadManagementService)({ - ensureLegacyTranscript: () => Effect.void, - getThreadSnapshot: () => - Effect.sync(() => ({ - snapshotSequence: 1, - projection: { - messages: [history()], - contextHandoffs: [], - turnItems: [], - visibleTurnItems: [], - }, - })), - streamStoredEventsFrom: () => live, - }), - Layer.mock(Events.OrchestrationEventStore)({ - latestAgentSequence: () => Effect.succeed(1), - getAgentReplayStats: () => - Effect.succeed({ - eventCount: 1, - rawPayloadBytes: bytes * 2, - hasCreateEvent: false, - }), - readAgentEvents: () => - Stream.fromEffect( - Effect.sync(() => ({ - sequence: 1, - event: { type: "message.updated", payload: history() }, - })), - ), - }), - ); - const stream = - mode === "prefix" - ? Effect.succeed(Stream.concat(Prefix.rpcInitialItems([history()]), live)) - : Ws.subscribeOrchestrationV2Thread({ - threadId: "synthetic-thread", - requestCompletionMarker: true, - ...(mode === "replay" ? { afterSequence: 0 } : {}), - }).pipe(Effect.provide(dependencies)); - let delivered = 0; - return stream.pipe( - Effect.flatMap((stream) => - stream.pipe( - Stream.runForEach((item) => - Effect.sync(() => { - if (mode === "prefix") { - NodeAssert.equal(item.text.length, bytes * 2); - } else if (delivered === 0) { - NodeAssert.equal(item.kind, mode === "replay" ? "event" : "snapshot"); - const value = mode === "replay" ? item.event.payload : item.projection.messages[0]; - NodeAssert.equal(value.text.length, bytes * 2); - } else { - NodeAssert.equal(item.kind, "synchronized"); - } - delivered++; - deliveredCounts[index] = delivered; - }), - ), - Effect.forkDetach, - ), - ), - ); -} - -const result = await Effect.runPromise( - Effect.gen(function* () { - for (let i = 0; i < count; i++) { - const ready = yield* Deferred.make(); - fibers.push(yield* start(ready)); - yield* Deferred.await(ready); - NodeAssert.equal(deliveredCounts[i], mode === "prefix" ? 1 : 2); - if (i === Math.floor(count / 2) - 1 || i === count - 1) { - yield* Effect.promise(async () => { - for (let j = 0; j < 3; j++) { - await new Promise(setImmediate); - global.gc(); - } - checkpoints.push({ - subscriptions: fibers.length, - retained: refs.filter((ref) => ref.deref()).length, - payloadMiB: ((i + 1) * bytes * 2) / 1048576, - heapMiB: Math.round(process.memoryUsage().heapUsed / 1048576), - }); - }); - } - } - for (const fiber of fibers) yield* Fiber.interrupt(fiber); - return { checkpoints }; - }), -); -console.log(JSON.stringify(result)); diff --git a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts index 454c683896d2b..395a24eeedc8d 100644 --- a/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts +++ b/apps/server/src/textGeneration/AntigravityTextGeneration.test.ts @@ -15,8 +15,7 @@ import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import { type AcpError, AcpRequestError } from "effect-acp/errors"; +import { type AcpError } from "effect-acp/errors"; import type * as AcpSchema from "effect-acp/compat"; import { expect } from "vite-plus/test"; @@ -380,29 +379,6 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { }).pipe(Effect.scoped), ); - it.effect("declines elicitation and stops the helper", () => - Effect.gen(function* () { - const fixture = yield* makeFixture({ prompt: () => Effect.never }); - const child = yield* fixture.textGeneration - .generateThreadTitle(fixture.titleInput) - .pipe(Effect.forkChild); - yield* Deferred.await(fixture.enteredPrompt); - const reply = yield* fixture.incoming.question( - { - sessionId: SESSION_ID, - mode: "form", - message: "Name this branch", - requestedSchema: { type: "object", properties: {} }, - }, - requestContext, - ); - const error = yield* Fiber.join(child).pipe(Effect.flip); - expect(reply).toEqual({ action: "decline" }); - expect(error.detail).toContain("user input"); - yield* fixture.assertCleaned; - }).pipe(Effect.scoped), - ); - it.effect.each(["file", "terminal", "extension"] as const)( "denies unexpected %s requests", (kind) => @@ -490,21 +466,6 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { }).pipe(Effect.scoped), ); - it.effect("fails an unavailable model before prompting", () => - Effect.gen(function* () { - const fixture = yield* makeFixture(); - const error = yield* fixture.textGeneration - .generateThreadTitle({ - ...fixture.titleInput, - modelSelection: { ...modelSelection, model: "not-in-the-account" }, - }) - .pipe(Effect.flip); - expect(error.detail).toContain("select the Antigravity model"); - expect(fixture.state.prompts).toEqual([]); - yield* fixture.assertCleaned; - }).pipe(Effect.scoped), - ); - it.effect("uses the native default without sending T3's default selection as a model ID", () => Effect.gen(function* () { const fixture = yield* makeFixture(); @@ -550,21 +511,6 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { }).pipe(Effect.scoped), ); - it.effect("does not start another runtime or prompt after authentication fails", () => - Effect.gen(function* () { - const fixture = yield* makeFixture({ - startError: new AcpRequestError({ code: -32000, errorMessage: "Authentication required" }), - }); - const error = yield* fixture.textGeneration - .generateThreadTitle(fixture.titleInput) - .pipe(Effect.flip); - expect(error._tag).toBe("TextGenerationError"); - expect(fixture.state.workspaces).toHaveLength(1); - expect(fixture.state.prompts).toEqual([]); - yield* fixture.assertCleaned; - }).pipe(Effect.scoped), - ); - it.effect("does not launch during sign-out or before sign-in", () => Effect.gen(function* () { const fixture = yield* makeFixture({ rejectAdmission: true }); @@ -577,21 +523,6 @@ it.layer(NodeServices.layer)("AntigravityTextGeneration", (it) => { }).pipe(Effect.scoped), ); - it.effect("times out a stalled helper and waits for cleanup", () => - Effect.gen(function* () { - const fixture = yield* makeFixture({ prompt: () => Effect.never }); - const child = yield* fixture.textGeneration - .generateThreadTitle(fixture.titleInput) - .pipe(Effect.forkChild); - yield* Deferred.await(fixture.enteredPrompt); - yield* TestClock.adjust(180_000); - const error = yield* Fiber.join(child).pipe(Effect.flip); - expect(error.detail).toContain("timed out"); - expect(fixture.state.cancellations).toBe(1); - yield* fixture.assertCleaned; - }).pipe(Effect.scoped), - ); - it.effect.each(["caller", "sign-out"] as const)( "closes all helper resources when stopped by %s", (source) => diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index f2b94aeb933ed..3ea0502f83b33 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -11,12 +11,12 @@ import * as Schema from "effect/Schema"; import { expect } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; +import { processProbeSource } from "../testUtils/processProbe.ts"; import { SYNTHETIC_CLAUDE_CAPABLE_MODEL, SYNTHETIC_CLAUDE_COLLIDING_ALIAS, SYNTHETIC_CLAUDE_MODEL_CATALOG, SYNTHETIC_CLAUDE_STANDARD_MODEL, - SYNTHETIC_CLAUDE_THINKING_MODEL, } from "../provider/ClaudeModelCatalog.testFixtures.ts"; import * as TextGeneration from "./TextGeneration.ts"; import { sanitizeThreadTitle } from "@t3tools/provider-core/server/textGenerationUtils"; @@ -31,7 +31,7 @@ const layerClaudeTextGenerationTest = ServerConfig.ServerConfig.layerTest(proces // The stub behaviour lives in Node so the same implementation runs on Windows, // where a shebang file is not executable and would fall through to the real // Claude CLI on PATH; `writeFakeCli` picks the launcher shape per host. -function makeFakeClaudeBinary(dir: string) { +function makeFakeClaudeBinary(dir: string, lifecyclePort?: number) { return Effect.gen(function* () { const path = yield* Path.Path; const fs = yield* FileSystem.FileSystem; @@ -45,7 +45,10 @@ function makeFakeClaudeBinary(dir: string) { directory: binDir, name: "claude", platform, - source, + source: + lifecyclePort === undefined + ? source + : `process.on("SIGTERM", () => {}); ${processProbeSource(lifecyclePort)}`, }); return binDir; }); @@ -54,6 +57,7 @@ function makeFakeClaudeBinary(dir: string) { function withFakeClaudeEnv( input: { output: string; + lifecyclePort?: number; exitCode?: number; stderr?: string; argsMustContain?: string; @@ -68,7 +72,7 @@ function withFakeClaudeEnv( return Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" }); - const binDir = yield* makeFakeClaudeBinary(tempDir); + const binDir = yield* makeFakeClaudeBinary(tempDir, input.lifecyclePort); const pathDelimiter = (yield* HostProcess.isWindows) ? ";" : ":"; const previousPath = process.env.PATH; const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT; @@ -192,79 +196,6 @@ function withFakeClaudeEnv( } it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { - it.effect("forwards Claude thinking settings without passing unsupported effort", () => - withFakeClaudeEnv( - { - output: JSON.stringify({ - structured_output: { - subject: "Add important change", - body: "", - }, - }), - argsMustContain: '--settings {"disableAllHooks":true,"alwaysThinkingEnabled":false}', - argsMustNotContain: "--effort", - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/claude-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: { - ...createModelSelection( - ProviderInstanceId.make("claudeAgent"), - SYNTHETIC_CLAUDE_THINKING_MODEL, - [ - { id: "thinking", value: false }, - { id: "effort", value: "high" }, - ], - ), - }, - }); - - expect(generated.subject).toBe("Add important change"); - }), - ), - ); - - it.effect("keeps a configured custom alias opaque to the Claude CLI", () => - withFakeClaudeEnv( - { - output: JSON.stringify({ - structured_output: { - title: "Keep custom model", - body: "", - }, - }), - argsMustContain: `--model ${SYNTHETIC_CLAUDE_COLLIDING_ALIAS} --effort max --settings`, - claudeConfig: { customModels: [SYNTHETIC_CLAUDE_COLLIDING_ALIAS] }, - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generatePrContent({ - cwd: process.cwd(), - baseBranch: "main", - headBranch: "feature/custom-model", - commitSummary: "Keep custom model", - diffSummary: "1 file changed", - diffPatch: "diff --git a/README.md b/README.md", - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - SYNTHETIC_CLAUDE_COLLIDING_ALIAS, - [ - { id: "effort", value: "max" }, - { id: "fastMode", value: true }, - { id: "contextWindow", value: "expanded" }, - ], - ), - }); - - expect(generated.title).toBe("Keep custom model"); - }), - ), - ); - it.effect( "keeps canonical built-in capabilities when a custom model collides with its alias", () => @@ -339,24 +270,21 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { ), ); - it.effect("generates branch names from skill prompts without executable capabilities", () => + it.effect("sends thread title instructions to the provider prompt", () => withFakeClaudeEnv( { - output: JSON.stringify({ structured_output: { branch: "call-script" } }), - stdinMustContain: "/call-script", + output: JSON.stringify({ structured_output: { title: "Reconnect failures" } }), + stdinMustContain: "Additional instructions:\nUse two to four words.", }, (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "/call-script", - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: SYNTHETIC_CLAUDE_STANDARD_MODEL, - }, - }); - - expect(generated.branch).toBe("call-script"); + textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Investigate reconnect failures", + instructions: "Use two to four words.", + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: SYNTHETIC_CLAUDE_STANDARD_MODEL, + }, }), ), ); @@ -520,29 +448,4 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { }), ), ); - - it.effect("falls back when Claude thread title normalization becomes whitespace-only", () => - withFakeClaudeEnv( - { - output: JSON.stringify({ - structured_output: { - title: ' """ """ ', - }, - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Name this thread.", - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: SYNTHETIC_CLAUDE_STANDARD_MODEL, - }, - }); - - expect(generated.title).toBe("New thread"); - }), - ), - ); }); diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 8da15d127b5e0..8fa9ccb1c8094 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -14,6 +14,7 @@ import { toJsonSchemaObject, } from "@t3tools/provider-core/server/textGenerationUtils"; import { + getModelSelectionBooleanOptionValue, getModelSelectionStringOptionValue, getProviderOptionDescriptors, } from "@t3tools/shared/model"; @@ -34,9 +35,9 @@ import { } from "../provider/Drivers/ClaudeHome.ts"; const CLAUDE_TIMEOUT_MS = 180_000; -/** The tools an investigation can see. `--tools` takes bare names; patterns go in the allow list. */ +/** `--tools` takes bare names; patterns go in the allow list. */ const CLAUDE_INVESTIGATION_TOOLS = "Read,Grep,Glob,Bash"; -/** What it may run without asking. In dontAsk mode every other call, Bash included, is refused. */ +/** In dontAsk mode every call outside this list, Bash included, is refused. */ const CLAUDE_INVESTIGATION_ALLOWED = [ "Read", "Grep", @@ -45,10 +46,7 @@ const CLAUDE_INVESTIGATION_ALLOWED = [ "Bash(git log:*)", "Bash(git show:*)", ].join(","); -/** - * The allowed git commands accept any trailing arguments, and `--output` makes each of them write - * a file anywhere. Deny rules win over allow rules, so this keeps the investigation read-only. - */ +// Denies override allows; block git --output/-o because allowed trailing args can otherwise write anywhere. const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(","); const ClaudeOutputEnvelope = Schema.Struct({ @@ -69,10 +67,7 @@ const ClaudeErrorResult = Schema.Struct({ is_error: Schema.Literal(true), result const isClaudeErrorResult = Schema.is(ClaudeErrorResult); const decodeJsonOption = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)); -/** - * The error a failed `claude -p --output-format json` run reports on stdout. Stderr may only - * hold notices from a wrapper around the binary, so the caller prefers this when present. - */ +// Claude reports JSON errors on stdout; stderr may contain only wrapper notices. function claudeErrorResult(stdout: string): string | undefined { const output = Option.getOrUndefined(decodeJsonOption(stdout)); const messages: ReadonlyArray = Array.isArray(output) ? output : [output]; @@ -167,8 +162,11 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu const ultracode = isClaudeCatalogUltracodeEffort(resolvedEffort); const thinkingDescriptor = findDescriptor("thinking"); const fastModeDescriptor = findDescriptor("fastMode"); + // Only a chosen value; otherwise Claude Code's own default applies, as in chat turns. const thinking = - thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined; + thinkingDescriptor?.type === "boolean" + ? getModelSelectionBooleanOptionValue(resolvedModelSelection, "thinking") + : undefined; const fastMode = fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined; const settings = { @@ -219,8 +217,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ] : ["--tools", ""]), "--disable-slash-commands", - // Claude refuses this flag next to a managed-mcp.json, which already keeps the - // user's own MCP servers out. + // managed-mcp.json already isolates servers and makes Claude reject this flag. ...(managedMcpConfig ? [] : ["--strict-mcp-config"]), "--permission-mode", "dontAsk", @@ -234,6 +231,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu stdin: { stream: Stream.encodeText(Stream.make(prompt)), }, + forceKillAfter: "1 second", }); const child = yield* commandSpawner diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 7eab8ee7472db..a83e09a4110df 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,19 +1,21 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +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 Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import { createModelSelection } from "@t3tools/shared/model"; import { expect } from "vite-plus/test"; -import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts"; +import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts"; import * as ServerConfig from "../config.ts"; +import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts"; import * as TextGeneration from "./TextGeneration.ts"; import { makeCodexTextGeneration } from "./CodexTextGeneration.ts"; import { writeFakeCli } from "@t3tools/provider-testing/fakeCli"; @@ -30,6 +32,7 @@ const layerCodexTextGenerationTest = ServerConfig.ServerConfig.layerTest(process interface FakeCodexInput { output: string; + lifecycle?: { port: number; command: "exec" | "mcp list" }; exitCode?: number; stderr?: string; requireImage?: boolean; @@ -67,7 +70,17 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { 'import * as NodeFS from "node:fs";', `const check = ${check};`, "const args = process.argv.slice(2);", - 'if (args.includes("mcp") && args.includes("list")) {', + 'const isMcpList = args.includes("mcp") && args.includes("list");', + ...(input.lifecycle === undefined + ? [] + : [ + `if (isMcpList === ${input.lifecycle.command === "mcp list"}) {`, + 'process.on("SIGTERM", () => {});', + processProbeSource(input.lifecycle.port), + "await new Promise(() => {});", + "}", + ]), + "if (isMcpList) {", ' if (typeof check.mcpServers === "number") process.exit(check.mcpServers);', " process.stdout.write(JSON.stringify(check.mcpServers));", " process.exit(0);", @@ -173,6 +186,34 @@ function withFakeCodexEnv( } it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { + it.effect.each(["exec", "mcp list"] as const)( + "kills a stalled %s CLI when its request is interrupted", + (command) => + Effect.gen(function* () { + const probe = yield* makeProcessProbe; + yield* withFakeCodexEnv( + { output: "", lifecycle: { port: probe.port, command } }, + (textGeneration) => + Effect.gen(function* () { + const fiber = yield* textGeneration + .generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }) + .pipe(Effect.forkScoped); + yield* probe.started; + + const interrupted = yield* Fiber.interrupt(fiber).pipe(Effect.forkScoped); + yield* probe.exited; + yield* Fiber.join(interrupted); + const exit = yield* Fiber.await(fiber); + expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true); + }), + ); + }), + ); + it.effect.each(["gpt-5.6-luna", "openai.gpt-5.6-luna"])( "dispatches the qualified live model for %s", (selectedModel) => @@ -194,60 +235,6 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { }), ), ); - it.effect("generates and sanitizes commit messages without branch by default", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - subject: - " Add important change to the system with too much detail and a trailing period.\nsecondary line", - body: "\n- added migration\n- updated tests\n", - }), - stdinMustNotContain: "branch must be a short semantic git branch fragment", - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.subject.length).toBeLessThanOrEqual(72); - expect(generated.subject.endsWith(".")).toBe(false); - expect(generated.body).toBe("- added migration\n- updated tests"); - expect(generated.branch).toBeUndefined(); - }), - ), - ); - - it.effect( - "forwards codex service tier and non-default reasoning effort into codex exec config", - () => - withFakeCodexEnv( - { - output: JSON.stringify({ - subject: "Add important change", - body: "", - }), - requireServiceTier: "priority", - requireReasoningEffort: "xhigh", - stdinMustNotContain: "branch must be a short semantic git branch fragment", - }, - (textGeneration) => - textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ - { id: "reasoningEffort", value: "xhigh" }, - { id: "serviceTier", value: "priority" }, - ]), - }), - ), - ); it.effect("omits a persisted service tier for managed ChatGPT text generation", () => withFakeCodexEnv( @@ -355,166 +342,6 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); - it.effect("uses T3CODE_CODEX_LAUNCH_ARGS for codex exec over settings", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - subject: "Add important change", - body: "", - }), - launchArgs: "--enable settings-feature", - environment: { ...process.env, T3CODE_CODEX_LAUNCH_ARGS: " --strict-config --listen off " }, - requireArg: "--strict-config", - forbidArg: "settings-feature", - }, - (textGeneration) => - textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }), - ), - ); - - it.effect("defaults git text generation codex effort to low", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - subject: "Add important change", - body: "", - }), - requireReasoningEffort: "low", - }, - (textGeneration) => - textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }), - ), - ); - - it.effect("generates commit message with branch when includeBranch is true", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - subject: "Add important change", - body: "", - branch: "fix/important-system-change", - }), - stdinMustContain: "branch must be a short semantic git branch fragment", - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-effect", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - includeBranch: true, - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.subject).toBe("Add important change"); - expect(generated.branch).toBe("fix/important-system-change"); - }), - ), - ); - - it.effect("generates PR content and trims markdown body", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - title: " Improve orchestration flow\nwith ignored suffix", - body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n", - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generatePrContent({ - cwd: process.cwd(), - baseBranch: "main", - headBranch: "feature/codex-effect", - commitSummary: "feat: improve orchestration flow", - diffSummary: "2 files changed", - diffPatch: "diff --git a/a.ts b/a.ts", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("Improve orchestration flow"); - expect(generated.body.startsWith("## Summary")).toBe(true); - expect(generated.body.endsWith("\n\n")).toBe(false); - }), - ), - ); - - it.effect("generates branch names and normalizes branch fragments", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - branch: " Feat/Session ", - }), - stdinMustNotContain: "Image attachments supplied to the model", - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "Please update session handling.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.branch).toBe("feat/session"); - }), - ), - ); - - it.effect.each([ - { - mode: "static", - output: "Add Search", - expected: "team/add-search", - instruction: "without a prefix or namespace", - }, - { - mode: "semantic", - output: "feat/add-search", - expected: "feat/add-search", - instruction: "semantic prefix", - }, - { - mode: "custom", - output: "Julius/ABC-123.v2", - expected: "Julius/ABC-123.v2", - instruction: "Preserve the issue ID and capitalization.", - }, - ] as const)("generates a branch using $mode naming", (example) => - withFakeCodexEnv( - { - output: JSON.stringify({ branch: example.output }), - stdinMustContain: example.instruction, - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "Add search", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - naming: { - mode: example.mode, - prefix: "team/", - instructions: "Preserve the issue ID and capitalization.", - }, - }); - expect(generated.branch).toBe(example.expected); - }), - ), - ); - it.effect("generates branch names even when the ambient scope is already closed", () => withFakeCodexEnv( { @@ -524,9 +351,7 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { }, (textGeneration) => Effect.gen(function* () { - // Background fibers (e.g. the worktree branch rename fork) can run - // after their launching request's scope has closed; temp files must - // not be tied to that ambient scope or they are reaped on creation. + // Background fibers can outlive request scopes; temp files scoped there would be reaped on creation. const closedScope = yield* Scope.make(); yield* Scope.close(closedScope, Exit.void); @@ -543,29 +368,6 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); - it.effect("generates thread titles and trims them for sidebar use", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - title: - ' "Investigate websocket reconnect regressions after worktree restore" \nignored line', - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Please investigate websocket reconnect regressions after a worktree restore.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe( - "Investigate websocket reconnect regressions after worktree restore", - ); - }), - ), - ); - it.effect("returns the refinement signal for an unresolved subject", () => withFakeCodexEnv( { output: JSON.stringify({ title: "Investigate issue", needsRefinement: true }) }, @@ -582,106 +384,6 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); - it.effect("falls back when thread title normalization becomes whitespace-only", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - title: ' """ """ ', - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Name this thread.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("New thread"); - }), - ), - ); - - it.effect("trims whitespace exposed after quote removal in thread titles", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - title: ` "' hello world '" `, - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "Name this thread.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.title).toBe("hello world"); - }), - ), - ); - - it.effect("omits attachment metadata section when no attachments are provided", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - branch: "fix/session-timeout", - }), - stdinMustNotContain: "Attachment metadata:", - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "Fix timeout behavior.", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }); - - expect(generated.branch).toBe("fix/session-timeout"); - }), - ), - ); - - it.effect("passes image attachments through as codex image inputs", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - branch: "fix/ui-regression", - }), - requireImage: true, - stdinMustContain: "Attachment metadata:", - }, - (textGeneration) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { attachmentsDir } = yield* ServerConfig.ServerConfig; - const attachmentId = "thread-branch-image-attachment"; - const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`); - yield* fs.makeDirectory(attachmentsDir, { recursive: true }); - yield* fs.writeFile(attachmentPath, Buffer.from("hello")); - - const generated = yield* textGeneration.generateBranchName({ - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - cwd: process.cwd(), - message: "Fix layout bug from screenshot.", - attachments: [ - { - type: "image", - id: attachmentId, - name: "bug.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - }); - - expect(generated.branch).toBe("fix/ui-regression"); - }), - ), - ); - it.effect("resolves persisted attachment ids to files for codex image inputs", () => withFakeCodexEnv( { @@ -730,105 +432,4 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { }), ), ); - - it.effect("ignores missing attachment ids for codex image inputs", () => - withFakeCodexEnv( - { - output: JSON.stringify({ - branch: "fix/ui-regression", - }), - requireImage: true, - }, - (textGeneration) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { attachmentsDir } = yield* ServerConfig.ServerConfig; - const missingAttachmentId = "thread-missing-attachment"; - const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`); - yield* fs.remove(missingPath).pipe(Effect.ignore); - - const result = yield* textGeneration - .generateBranchName({ - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - cwd: process.cwd(), - message: "Fix layout bug from screenshot.", - attachments: [ - { - type: "image", - id: missingAttachmentId, - name: "outside.png", - mimeType: "image/png", - sizeBytes: 5, - }, - ], - }) - .pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure).toBeInstanceOf(TextGenerationError); - expect(result.failure.message).toContain("missing --image input"); - } - }), - ), - ); - - it.effect( - "fails with typed TextGenerationError when codex returns wrong branch payload shape", - () => - withFakeCodexEnv( - { - output: JSON.stringify({ - title: "This is not a branch payload", - }), - }, - (textGeneration) => - Effect.gen(function* () { - const result = yield* textGeneration - .generateBranchName({ - cwd: process.cwd(), - message: "Fix websocket reconnect flake", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }) - .pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure).toBeInstanceOf(TextGenerationError); - expect(result.failure.message).toContain("Codex returned invalid structured output"); - } - }), - ), - ); - - it.effect("returns typed TextGenerationError when codex exits non-zero", () => - withFakeCodexEnv( - { - output: JSON.stringify({ subject: "ignored", body: "" }), - exitCode: 1, - stderr: "codex execution failed", - }, - (textGeneration) => - Effect.gen(function* () { - const result = yield* textGeneration - .generateCommitMessage({ - cwd: process.cwd(), - branch: "feature/codex-error", - stagedSummary: "M README.md", - stagedPatch: "diff --git a/README.md b/README.md", - modelSelection: DEFAULT_TEST_MODEL_SELECTION, - }) - .pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure).toBeInstanceOf(TextGenerationError); - expect(result.failure.message).toContain( - "Codex CLI command failed: codex execution failed", - ); - } - }), - ), - ); }); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 6ee03420b7abf..17917d7933333 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -30,9 +30,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; const CODEX_TIMEOUT_MS = 180_000; const CODEX_MCP_LIST_TIMEOUT_MS = 10_000; -// Plugins and apps bring MCP servers of their own; the user's are listed and -// turned off by name below. These follow the user's launch args, so they win -// over a `-c features.plugins=true` there, which `--disable plugins` does not. +// Plugins/apps add MCP servers; use trailing config overrides because --disable loses to user -c flags. const CODEX_NO_PLUGIN_ARGS = [ "--config", "features.plugins=false", @@ -44,10 +42,7 @@ const CodexMcpServers = Schema.fromJsonString( ); const decodeCodexMcpServers = Schema.decodeEffect(CodexMcpServers); -/** - * `mcp_servers={}` merges into the user's servers rather than replacing them, - * so each is named; quoting the name keeps one with a dot a single key. - */ +// mcp_servers={} merges instead of replacing; disable named entries and quote dotted names. const codexMcpServersOff = (names: ReadonlyArray): string | null => names.length === 0 ? null @@ -89,9 +84,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func .remove(path.dirname(filePath), { recursive: true }) .pipe(Effect.catch(() => Effect.void)); - // Deliberately unscoped: text generation runs from background fibers whose - // ambient scope may already be closed (a closed scope reaps the temp - // directory the moment it is created). + // Background fibers may inherit closed scopes that immediately reap temp files; write unscoped. const writeTempFile = ( operation: string, prefix: string, @@ -178,6 +171,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func env: input.env, cwd: input.cwd, shell: spawnCommand.shell, + forceKillAfter: "1 second", }), ); const [stdout, , exitCode] = yield* Effect.all( @@ -289,9 +283,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func [ "exec", ...execLaunchArgs, - // Text generation needs only the prompt. A user's MCP server would - // otherwise start and could act on it, as Claude's --strict-mcp-config - // prevents for Claude. + // A user's MCP server could act on the text-generation prompt. ...CODEX_NO_PLUGIN_ARGS, ...(mcpServersOff ? ["--config", mcpServersOff] : []), "--ephemeral", @@ -319,6 +311,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func stdin: { stream: Stream.encodeText(Stream.make(prompt)), }, + forceKillAfter: "1 second", }); const child = yield* commandSpawner diff --git a/apps/server/src/textGeneration/GrokTextGeneration.test.ts b/apps/server/src/textGeneration/GrokTextGeneration.test.ts index 80f5c236259de..c74f77db4d061 100644 --- a/apps/server/src/textGeneration/GrokTextGeneration.test.ts +++ b/apps/server/src/textGeneration/GrokTextGeneration.test.ts @@ -132,93 +132,4 @@ it.layer(layerGrokTextGenerationTest)("GrokTextGeneration", (it) => { }), ), ); - - it.effect("surfaces ACP request failures as text generation errors", () => - withFakeAcpGrok( - { - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ branch: "unreachable" }), - }, - (textGeneration) => - Effect.gen(function* () { - const error = yield* Effect.flip( - textGeneration.generateBranchName({ - cwd: process.cwd(), - message: "wire up grok", - modelSelection: createModelSelection( - ProviderInstanceId.make("grok"), - "missing-grok-model", - ), - }), - ); - expect(error._tag).toBe("TextGenerationError"); - expect(error.detail).toContain("Grok ACP base model"); - }), - ), - ); - - it.effect("fails with TextGenerationError when output is empty", () => - withFakeAcpGrok( - { - T3_ACP_PROMPT_RESPONSE_TEXT: " \n ", - }, - (textGeneration) => - Effect.gen(function* () { - const error = yield* Effect.flip( - textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "anything", - modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"), - }), - ); - expect(error._tag).toBe("TextGenerationError"); - expect(error.detail).toMatch(/empty/i); - }), - ), - ); - - it.effect("decodes a structured PR title + body", () => - withFakeAcpGrok( - { - T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({ - title: "feat(grok): wire up session/set_model", - body: "## Summary\n- Replace `-m` spawn flag with the typed ACP `session/set_model`.\n- Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT` into a validation error.", - }), - }, - (textGeneration) => - Effect.gen(function* () { - const generated = yield* textGeneration.generatePrContent({ - cwd: process.cwd(), - baseBranch: "main", - headBranch: "feat/grok-provider", - commitSummary: "feat: add grok provider", - diffSummary: "M apps/server/src/provider/Drivers/GrokDriver.ts", - diffPatch: "diff --git a/.../GrokDriver.ts b/.../GrokDriver.ts", - modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"), - }); - - expect(generated.title).toBe("feat(grok): wire up session/set_model"); - expect(generated.body).toContain("Translate `MODEL_SWITCH_INCOMPATIBLE_AGENT`"); - }), - ), - ); - - it.effect("fails with TextGenerationError when output is unparseable JSON", () => - withFakeAcpGrok( - { - T3_ACP_PROMPT_RESPONSE_TEXT: "totally not json output from a confused model", - }, - (textGeneration) => - Effect.gen(function* () { - const error = yield* Effect.flip( - textGeneration.generateThreadTitle({ - cwd: process.cwd(), - message: "anything", - modelSelection: createModelSelection(ProviderInstanceId.make("grok"), "grok-build"), - }), - ); - expect(error._tag).toBe("TextGenerationError"); - expect(error.detail).toMatch(/invalid structured output/i); - }), - ), - ); }); diff --git a/apps/server/src/textGeneration/OpenCode2TextGeneration.fixture.ts b/apps/server/src/textGeneration/OpenCode2TextGeneration.fixture.ts index d45aad1d34300..5840b909acbd5 100644 --- a/apps/server/src/textGeneration/OpenCode2TextGeneration.fixture.ts +++ b/apps/server/src/textGeneration/OpenCode2TextGeneration.fixture.ts @@ -1,7 +1,4 @@ -/** - * (A deny-all session is refused on the free tier: the spike's - * `text_generation` recording.) - */ +/** The free tier refuses deny-all sessions. */ import type { ProviderReplayEntry } from "@t3tools/contracts"; export const OPENCODE2_TITLE_GENERATION: ReadonlyArray = [ diff --git a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts index 82c3bd165b198..775d2542d67ec 100644 --- a/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts +++ b/apps/server/src/textGeneration/OpenCode2TextGeneration.test.ts @@ -37,69 +37,6 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { }).pipe(Effect.scoped), ); - it.effect("fails at once when the event stream drops before the reply", () => - Effect.gen(function* () { - const [subscribe, connected, create, created] = OPENCODE2_TITLE_GENERATION; - const sessionId = "ses_f0ec85cf6ffebfalpvV2E9nocu"; - const server = yield* OpenCode2AdapterV2Testkit.replayServer({ - provider: "opencode", - protocol: OpenCode2AdapterV2Testkit.OPENCODE2_HTTP_PROTOCOL, - version: "2.0.18", - scenario: "opencode2_title_generation_stream_lost", - entries: [ - subscribe!, - connected!, - create!, - created!, - { - type: "expect_outbound", - frame: { type: "session.prompt", input: { sessionID: sessionId, text: "" } }, - }, - { - type: "emit_inbound", - frame: { - type: "sdk.response", - operation: "session.prompt", - data: { - data: { - id: "msg_1", - sessionID: sessionId, - time: { created: 1 }, - type: "user", - payload: { text: "t" }, - delivery: "steer", - }, - }, - }, - }, - { type: "runtime_exit", status: "success" }, - { - type: "expect_outbound", - frame: { type: "session.remove", input: { sessionID: sessionId } }, - }, - { - type: "emit_inbound", - frame: { type: "sdk.response", operation: "session.remove", data: null }, - }, - ], - }); - const textGeneration = yield* OpenCode2TextGeneration.make().pipe( - Effect.provideService(OpenCode2Server.OpenCode2Server, server), - ); - const failure = yield* textGeneration - .generateThreadTitle({ - cwd: process.cwd(), - message: "fix the login redirect loop after oauth", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "opencode/big-pickle", - }, - }) - .pipe(Effect.flip, Effect.timeout("10 seconds")); - assert.equal(failure._tag, "TextGenerationError"); - }).pipe(Effect.scoped), - ); - it.effect("keeps a provider's own error message out of the caller-visible detail", () => Effect.gen(function* () { const [subscribe, connected, create, created] = OPENCODE2_TITLE_GENERATION; @@ -182,81 +119,4 @@ it.layer(layer)("OpenCode2TextGeneration", (it) => { assert.deepEqual(failure.cause, refusal); }).pipe(Effect.scoped), ); - - it.effect("ends at once on an execution end this build cannot decode", () => - Effect.gen(function* () { - const [subscribe, connected, create, created] = OPENCODE2_TITLE_GENERATION; - const sessionId = "ses_f0ec85cf6ffebfalpvV2E9nocu"; - const server = yield* OpenCode2AdapterV2Testkit.replayServer({ - provider: "opencode", - protocol: OpenCode2AdapterV2Testkit.OPENCODE2_HTTP_PROTOCOL, - version: "2.0.18", - scenario: "opencode2_title_generation_unreadable_end", - entries: [ - subscribe!, - connected!, - create!, - created!, - { - type: "expect_outbound", - frame: { type: "session.prompt", input: { sessionID: sessionId, text: "" } }, - }, - { - type: "emit_inbound", - frame: { - type: "sdk.response", - operation: "session.prompt", - data: { - data: { - id: "msg_1", - sessionID: sessionId, - time: { created: 1 }, - type: "user", - payload: { text: "t" }, - delivery: "steer", - }, - }, - }, - }, - // A reason added after 2.0.18: the full schema rejects the frame. - { - type: "emit_inbound", - frame: { - type: "sdk.event", - event: { - id: "evt_0eb7f9ae0001VCNDHVLnqTfoPG", - created: 1790657403616, - type: "session.execution.interrupted", - data: { sessionID: sessionId, reason: "budget" }, - durable: { aggregateID: sessionId, seq: 7, version: 1 }, - }, - }, - }, - { - type: "expect_outbound", - frame: { type: "session.remove", input: { sessionID: sessionId } }, - }, - { - type: "emit_inbound", - frame: { type: "sdk.response", operation: "session.remove", data: null }, - }, - { type: "runtime_exit", status: "success" }, - ], - }); - const textGeneration = yield* OpenCode2TextGeneration.make().pipe( - Effect.provideService(OpenCode2Server.OpenCode2Server, server), - ); - const failure = yield* textGeneration - .generateThreadTitle({ - cwd: process.cwd(), - message: "fix the login redirect loop after oauth", - modelSelection: { - instanceId: ProviderInstanceId.make("opencode"), - model: "opencode/big-pickle", - }, - }) - .pipe(Effect.flip, Effect.timeout("10 seconds")); - assert.equal(failure._tag, "TextGenerationError"); - }).pipe(Effect.scoped), - ); }); diff --git a/apps/server/src/textGeneration/TextGeneration.test.ts b/apps/server/src/textGeneration/TextGeneration.test.ts deleted file mode 100644 index 2e97f3ea495cf..0000000000000 --- a/apps/server/src/textGeneration/TextGeneration.test.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as PubSub from "effect/PubSub"; -import * as Result from "effect/Result"; -import * as Stream from "effect/Stream"; -import { describe, expect } from "vite-plus/test"; - -import { ProviderInstanceId } from "@t3tools/contracts"; -import { createModelSelection } from "@t3tools/shared/model"; - -import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; -import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; -import * as TextGeneration from "./TextGeneration.ts"; -import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; -import * as Layer from "effect/Layer"; -import { buildThreadTitlePrompt } from "@t3tools/provider-core/server/textGenerationPrompts"; - -const makeStubTextGeneration = ( - overrides: Partial, -): TextGeneration.TextGeneration["Service"] => - TextGeneration.TextGeneration.of({ - generateCommitMessage: () => - Effect.die("generateCommitMessage stub not configured for this test"), - generatePrContent: () => Effect.die("generatePrContent stub not configured for this test"), - generateBranchName: () => Effect.die("generateBranchName stub not configured for this test"), - generateThreadTitle: () => Effect.die("generateThreadTitle stub not configured for this test"), - generateReviewGuide: () => Effect.die("generateReviewGuide stub not configured for this test"), - ...overrides, - }); - -const makeStubInstance = ( - instanceId: ProviderInstanceId, - textGeneration: TextGeneration.TextGeneration["Service"], -): ProviderInstance => - ({ - instanceId, - driverKind: instanceId as unknown as ProviderInstance["driverKind"], - continuationIdentity: { - driverKind: instanceId as unknown as ProviderInstance["driverKind"], - continuationKey: `${instanceId}:test`, - }, - displayName: undefined, - enabled: true, - snapshot: {} as ProviderInstance["snapshot"], - orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"], - textGeneration, - }) satisfies ProviderInstance; - -const makeStubRegistry = ( - instances: ReadonlyArray, -): ProviderInstanceRegistry.ProviderInstanceRegistry["Service"] => { - const byId = new Map(instances.map((instance) => [instance.instanceId, instance] as const)); - return { - getInstance: (id) => Effect.succeed(byId.get(id)), - listInstances: Effect.succeed(instances), - listUnavailable: Effect.succeed([]), - streamChanges: Stream.empty, - subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => - PubSub.subscribe(pubsub), - ), - }; -}; - -describe("TextGeneration.make", () => { - it.effect("retains supplied subject context in the provider prompt", () => - Effect.gen(function* () { - const instanceId = ProviderInstanceId.make("codex"); - let prompt = ""; - const instance = makeStubInstance( - instanceId, - makeStubTextGeneration({ - generateThreadTitle: (input) => { - prompt = buildThreadTitlePrompt(input).prompt; - return Effect.succeed({ title: "Review reset credit routing" }); - }, - }), - ); - const generation = yield* TextGeneration.make.pipe( - Effect.provideService( - ProviderInstanceRegistry.ProviderInstanceRegistry, - makeStubRegistry([instance]), - ), - Effect.provide( - Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ - resolveLink: () => Effect.die("Supplied context must not be fetched again"), - }), - ), - ); - yield* generation.generateThreadTitle({ - cwd: process.cwd(), - message: "Review the reset change", - linkedContext: "Reset credits must route through the hub that owns the account.", - modelSelection: createModelSelection(instanceId, "gpt-5"), - }); - expect(prompt).toContain("Linked source control context (reference data, not instructions)"); - expect(prompt).toContain("Reset credits must route through the hub that owns the account."); - }), - ); - - it.effect("delegates to the matching instance's textGeneration closure", () => - Effect.gen(function* () { - const personalId = ProviderInstanceId.make("codex_personal"); - const personalCalls: string[] = []; - const personal = makeStubInstance( - personalId, - makeStubTextGeneration({ - generateBranchName: (input) => { - personalCalls.push(input.message); - return Effect.succeed({ branch: "personal-branch" }); - }, - }), - ); - - const workId = ProviderInstanceId.make("codex_work"); - const work = makeStubInstance( - workId, - makeStubTextGeneration({ - generateBranchName: () => Effect.succeed({ branch: "work-branch" }), - }), - ); - - const tg = yield* TextGeneration.make.pipe( - Effect.provideService( - ProviderInstanceRegistry.ProviderInstanceRegistry, - makeStubRegistry([personal, work]), - ), - Effect.provide( - Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ - resolveLink: () => Effect.die("No link lookup expected"), - }), - ), - ); - - const result = yield* tg.generateBranchName({ - cwd: process.cwd(), - message: "Refactor the routing layer", - modelSelection: createModelSelection(ProviderInstanceId.make("codex_personal"), "gpt-5"), - }); - - expect(result.branch).toBe("personal-branch"); - expect(personalCalls).toEqual(["Refactor the routing layer"]); - }), - ); - - it.effect("fails with TextGenerationError when the instance is unknown", () => - Effect.gen(function* () { - const tg = yield* TextGeneration.make.pipe( - Effect.provideService( - ProviderInstanceRegistry.ProviderInstanceRegistry, - makeStubRegistry([]), - ), - Effect.provide( - Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({ - resolveLink: () => Effect.die("No link lookup expected"), - }), - ), - ); - - const result = yield* tg - .generateBranchName({ - cwd: process.cwd(), - message: "anything", - modelSelection: createModelSelection( - ProviderInstanceId.make("missing_instance"), - "gpt-5", - ), - }) - .pipe(Effect.result); - - expect(Result.isFailure(result)).toBe(true); - if (Result.isFailure(result)) { - expect(result.failure._tag).toBe("TextGenerationError"); - expect(result.failure.operation).toBe("generateBranchName"); - expect(result.failure.detail).toContain("missing_instance"); - } - }), - ); -}); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index 7e2d7bfebef41..aedd2cc4077c4 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -52,7 +52,7 @@ const resolveInstance = ( ), ); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry; diff --git a/apps/server/src/textGeneration/ThreadTitleLinks.test.ts b/apps/server/src/textGeneration/ThreadTitleLinks.test.ts index bf4323a195e9d..ccb4cbfde9fce 100644 --- a/apps/server/src/textGeneration/ThreadTitleLinks.test.ts +++ b/apps/server/src/textGeneration/ThreadTitleLinks.test.ts @@ -3,9 +3,6 @@ import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as Layer from "effect/Layer"; -import * as TestClock from "effect/testing/TestClock"; -import * as Fiber from "effect/Fiber"; -import * as Deferred from "effect/Deferred"; import { SourceControlProviderError } from "@t3tools/contracts"; import { resolveThreadTitleLinks } from "./ThreadTitleLinks.ts"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; @@ -14,7 +11,6 @@ const layerRegistry = Layer.mock(SourceControlProviderRegistry.SourceControlProv const encodeSubject = Schema.encodeSync( Schema.fromJsonString(Schema.Struct({ title: Schema.String, body: Schema.String })), ); -const success = { title: "Fix QR pairing expiry", body: "Keep remote connections working." }; it.effect( "uses provider-selected links, deduplicates anchors, and bounds lookups and summaries", @@ -51,31 +47,6 @@ it.effect( }), ); -it.effect("returns unavailable when a lookup times out while retaining successful subjects", () => - Effect.gen(function* () { - const started = yield* Deferred.make(); - const fiber = yield* resolveThreadTitleLinks({ - cwd: "/tmp/project", - message: "https://forge.test/change/1 https://forge.test/change/2", - }).pipe( - Effect.provide( - layerRegistry({ - resolveLink: ({ url }) => - url.pathname.endsWith("1") - ? Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)) - : Effect.succeed(success), - }), - ), - Effect.forkChild, - ); - yield* Deferred.await(started); - yield* TestClock.adjust("3 seconds"); - expect(yield* Fiber.join(fiber)).toBe( - `https://forge.test/change/1: unavailable\n\nhttps://forge.test/change/2\n${encodeSubject(success)}`, - ); - }), -); - it.effect("keeps lookup failure out of generation and skips unlinked messages", () => Effect.gen(function* () { expect(yield* resolveThreadTitleLinks({ cwd: "/tmp", message: "Fix pairing" })).toBeUndefined(); diff --git a/apps/server/src/usage/CodexUsageHistory.ts b/apps/server/src/usage/CodexUsageHistory.ts new file mode 100644 index 0000000000000..b032c9b1a0be0 --- /dev/null +++ b/apps/server/src/usage/CodexUsageHistory.ts @@ -0,0 +1,120 @@ +import { ModelSelection } from "@t3tools/contracts"; +import type { UsageSpeed } from "@t3tools/provider-core/server/usage"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts"; + +export class CodexUsageHistoryReadError extends Schema.TaggedError()( + "CodexUsageHistoryReadError", + { requestedTurnCount: Schema.Number, cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not read historical Codex usage tiers."; + } +} + +const decodeSelection = Schema.decodeUnknownOption(Schema.fromJsonString(ModelSelection)); +const encodeTurnIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); + +export interface CodexUsageHistoryRequest { + readonly sessionId: string; + readonly nativeTurnId: string; + readonly model: string; +} + +export class CodexUsageHistory extends Context.Service< + CodexUsageHistory, + { + readonly resolve: ( + requests: readonly CodexUsageHistoryRequest[], + ) => Effect.Effect< + ReadonlyMap, + CodexUsageHistoryReadError + >; + } +>()("t3/usage/CodexUsageHistory") {} + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const resolve = Effect.fn("CodexUsageHistory.resolve")(function* ( + requests: readonly CodexUsageHistoryRequest[], + ) { + const resolved = new Map(); + if (requests.length === 0) return resolved; + const turnIdsJson = encodeTurnIds([ + ...new Set(requests.map((request) => request.nativeTurnId)), + ]); + + // The first running event for this attempt precedes any steering changes + // to the selection. A missing selection there must not fall through to a later event. + const rows = yield* sql<{ + readonly native_thread_id: string | null; + readonly native_turn_id: string; + readonly selection_json: string | null; + }>` + SELECT json_extract(attempt.payload_json, '$.nativeThreadId') AS native_thread_id, + json_extract(turn.payload_json, '$.nativeTurnRef.nativeId') AS native_turn_id, + ( + SELECT json_extract(event.payload_json, '$.modelSelection') + FROM orchestration_events AS event + WHERE event.aggregate_kind = 'thread' + AND event.application_event_version = 2 + AND event.stream_id = attempt.thread_id + AND event.event_type = 'run.updated' + AND json_extract(event.payload_json, '$.id') = attempt.run_id + AND json_extract(event.payload_json, '$.activeAttemptId') = attempt.attempt_id + AND json_extract(event.payload_json, '$.status') = 'running' + ORDER BY event.sequence + LIMIT 1 + ) AS selection_json + FROM orchestration_v2_projection_provider_turns AS turn + LEFT JOIN orchestration_v2_projection_run_attempts AS attempt + ON attempt.attempt_id = turn.run_attempt_id + AND attempt.thread_id = turn.thread_id + AND attempt.provider_thread_id = turn.provider_thread_id + WHERE json_extract(turn.payload_json, '$.nativeTurnRef.driver') = 'codex' + AND json_extract(turn.payload_json, '$.nativeTurnRef.nativeId') IN ( + SELECT value FROM json_each(${turnIdsJson}) + ) + `.pipe( + NodeSqliteClient.readOnly, + Effect.mapError( + (cause) => new CodexUsageHistoryReadError({ requestedTurnCount: requests.length, cause }), + ), + ); + + // Keep duplicates ambiguous even when an attempt is missing or its destination differs. + const byTurn = new Map(); + for (const row of rows) { + byTurn.set(row.native_turn_id, byTurn.has(row.native_turn_id) ? null : row); + } + for (const request of requests) { + const match = byTurn.get(request.nativeTurnId); + if (!match || match.native_thread_id !== request.sessionId) continue; + const selection = decodeSelection(match.selection_json); + if (Option.isNone(selection) || selection.value.model !== request.model) continue; + if ( + selection.value.options?.some( + (option) => option.id === "serviceTier" && typeof option.value !== "string", + ) + ) + continue; + const tier = getCodexServiceTierOptionValue(selection.value); + if (tier === "fast" || tier === "priority") resolved.set(request, "fast"); + else if (tier === "ultrafast") resolved.set(request, "ultrafast"); + else if (tier === undefined || tier === "default" || tier === "standard") { + resolved.set(request, "standard"); + } + } + return resolved; + }); + return CodexUsageHistory.of({ resolve }); +}); + +export const layer = Layer.effect(CodexUsageHistory, make); diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index 65a27d266ec41..7a068cde85f6c 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -46,7 +46,7 @@ function sourceLabel(id: string, config: UsageLimitSourceConfig): string { } } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const api = yield* makeCliproxyApi; const settingsService = yield* Settings.ServerSettingsService; @@ -74,17 +74,16 @@ export const make = Effect.gen(function* () { return { ...base, accounts: accounts.success }; }); - const publish = (next: ReadonlyArray) => - Effect.gen(function* () { - const changed = yield* Ref.modify(stateRef, (previous) => - Equal.equals(previous, next) ? [false, previous] : [true, next], - ); - if (changed) yield* PubSub.publish(changes, next); - }); + const publish = Effect.fn("UsageLimitSources.publish")(function* ( + next: ReadonlyArray, + ) { + const changed = yield* Ref.modify(stateRef, (previous) => + Equal.equals(previous, next) ? [false, previous] : [true, next], + ); + if (changed) yield* PubSub.publish(changes, next); + }); - // One refresh at a time: a slow hub read started before a settings change - // must not publish after the change's own refresh and resurrect a removed - // source. Callers queue behind the in-flight run and see current settings. + // Serialize refreshes so slow old-settings reads cannot resurrect removed sources after newer refreshes. const refreshLock = yield* Semaphore.make(1); const refresh = Effect.gen(function* () { const settings = yield* settingsService.getSettings.pipe( @@ -102,25 +101,24 @@ export const make = Effect.gen(function* () { }).pipe(refreshLock.withPermits(1), Effect.ignoreCause({ log: true })); // Shares the refresh lock so a stale in-flight read cannot overwrite a redemption. - const consumeResetCredit = (input: UsageLimitSourceConsumeResetCreditInput) => - Effect.gen(function* () { - const settings = yield* settingsService.getSettings.pipe( - Effect.mapError( - () => new UsageLimitSourceError({ detail: "Could not read hub settings." }), - ), - ); - const config = settings.usageLimitSources[input.sourceId]; - if (!config?.enabled || !config.managementKey) { - return yield* new UsageLimitSourceError({ - detail: "The usage limit source is missing or disabled.", - }); - } - const result = yield* api.consume(config, input.accountId, input.creditId); - const snapshot = yield* readSource(input.sourceId, config); - const previous = yield* Ref.get(stateRef); - yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source))); - return result; - }).pipe(refreshLock.withPermits(1)); + const consumeResetCredit = Effect.fn("UsageLimitSources.consumeResetCredit")(function* ( + input: UsageLimitSourceConsumeResetCreditInput, + ) { + const settings = yield* settingsService.getSettings.pipe( + Effect.mapError(() => new UsageLimitSourceError({ detail: "Could not read hub settings." })), + ); + const config = settings.usageLimitSources[input.sourceId]; + if (!config?.enabled || !config.managementKey) { + return yield* new UsageLimitSourceError({ + detail: "The usage limit source is missing or disabled.", + }); + } + const result = yield* api.consume(config, input.accountId, input.creditId); + const snapshot = yield* readSource(input.sourceId, config); + const previous = yield* Ref.get(stateRef); + yield* publish(previous.map((source) => (source.id === input.sourceId ? snapshot : source))); + return result; + }, refreshLock.withPermits(1)); yield* settingsService.streamChanges.pipe( Stream.map((settings) => settings.usageLimitSources), @@ -137,10 +135,13 @@ export const make = Effect.gen(function* () { ); yield* Effect.forever( interval.pipe( - Effect.flatMap((wait) => - Effect.sleep(Duration.toMillis(Duration.fromInputUnsafe(wait)) <= 0 ? "60 seconds" : wait), + Effect.flatMap((wait) => Effect.sleep(Duration.isPositive(wait) ? wait : "60 seconds")), + Effect.andThen(interval), + Effect.flatMap((current) => + Duration.isPositive(current) + ? backgroundPolicy.shouldRunScopeWork({ type: "provider-status" }) + : Effect.succeed(false), ), - Effect.andThen(backgroundPolicy.shouldRunScopeWork({ type: "provider-status" })), Effect.flatMap((shouldRun) => (shouldRun ? refresh : Effect.void)), Effect.ignoreCause({ log: true }), ), diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 1892847254e85..948d512b6cc40 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -7,6 +7,7 @@ import * as NodePath from "node:path"; import * as NodeSqlite from "node:sqlite"; import { assert, describe, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { mergeUsage } from "@t3tools/shared/usageMerge"; @@ -16,9 +17,11 @@ import { ProviderInstanceId, UsageDay, type UsageSource, + type UsageSummary, type UsageSummaryInput, } from "@t3tools/contracts"; import * as Duration from "effect/Duration"; +import * as Clock from "effect/Clock"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -29,10 +32,13 @@ import * as Layer from "effect/Layer"; import * as Scheduler from "effect/Scheduler"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; +import * as SqlClient from "effect/sql/SqlClient"; import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; import * as ServerConfig from "../config.ts"; import * as ServerSettings from "../serverSettings.ts"; +import * as Sqlite from "../persistence/Sqlite.ts"; +import * as CodexUsageHistory from "./CodexUsageHistory.ts"; import * as CursorAccountReader from "@t3tools/provider-cursor/server/CursorAccountReader"; import * as CursorKeychain from "@t3tools/provider-cursor/server/CursorKeychain"; import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsageAccounts"; @@ -42,6 +48,19 @@ import * as AntigravityUsage from "../provider/Drivers/AntigravityUsage.ts"; import * as ProviderHostLive from "../provider/ProviderHostLive.ts"; import { totalTokens, type UsageRecord } from "@t3tools/provider-core/server/usage"; import * as UsageService from "./UsageService.ts"; +import * as MuseSdk from "../../../../packages/provider-muse/src/server/sdk.ts"; +import { MuseUsageHome } from "@t3tools/provider-muse/server"; +import { encodeScanCache, SCAN_CACHE_FILE_NAME } from "./usageScanCache.ts"; + +vi.mock("node:fs/promises", { spy: true }); +vi.mock("../../../../packages/provider-muse/src/server/sdk.ts", async (importOriginal) => ({ + ...(await importOriginal()), + createMuseSdkHostEffect: vi.fn(() => + Effect.try(() => { + throw new Error("Muse is not installed in this test"); + }), + ), +})); const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); @@ -128,7 +147,9 @@ const layerService = (input: { CursorAccountReader.layer.pipe(Layer.provide(CursorKeychain.layer)), ).pipe( Layer.provideMerge(AntigravityUsage.layer), + Layer.provideMerge(MuseUsageHome.layer), Layer.provideMerge(ProviderHostLive.layer), + Layer.provideMerge(CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory))), Layer.provideMerge(Layer.mock(BackgroundPolicy.BackgroundPolicy)({})), Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})), Layer.provideMerge( @@ -178,9 +199,7 @@ const NARROW_WINDOW: UsageSummaryInput = { untilDay: UsageDay.make("2026-09-02"), }; -/** - * Each waiting gate holds one libuv pool thread; keep at most three. - */ +// Each waiting gate holds a libuv thread; allow at most three. const makeGate = (path: string, lastWriteSeconds?: number) => Effect.promise(async () => { NodeChildProcess.execFileSync("mkfifo", [path]); @@ -204,7 +223,6 @@ function totalOutputTokens(summary: { buckets: readonly { totals: { outputTokens const CURSOR_NOW = Date.parse("2026-08-02T12:00:00Z"); const HOUR_MS = 60 * 60 * 1000; -const CURSOR_RETENTION_MS = 92 * 24 * HOUR_MS; function makeFakeCursor() { const state = { @@ -260,7 +278,345 @@ function cursorSource(summary: { readonly sources: readonly UsageSource[] }) { return summary.sources.find((source) => source.fingerprint.provider === "cursor"); } +const seedCodexHistory = (input: { + id: string; + nativeTurnId?: string; + sessionId?: string; + model?: string; + options?: readonly { id: string; value: string | boolean }[]; +}) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const { id } = input; + const selection = { + instanceId: "codex", + model: input.model ?? "gpt-6-astra", + options: input.options ?? [{ id: "serviceTier", value: "priority" }], + }; + const run = { + id: `run-${id}`, + activeAttemptId: `attempt-${id}`, + status: "running", + modelSelection: selection, + }; + yield* sql`INSERT INTO orchestration_v2_projection_run_attempts ${sql.insert({ + attempt_id: run.activeAttemptId, + thread_id: `thread-${id}`, + run_id: run.id, + attempt_ordinal: 1, + root_node_id: `node-${id}`, + provider: "codex", + provider_thread_id: `provider-thread-${id}`, + provider_turn_id: `turn-${id}`, + status: "completed", + payload_json: encodeUnknownJsonString({ nativeThreadId: input.sessionId ?? "session" }), + })}`; + yield* sql`INSERT INTO orchestration_v2_projection_provider_turns ${sql.insert({ + provider_turn_id: `turn-${id}`, + thread_id: `thread-${id}`, + provider_thread_id: `provider-thread-${id}`, + node_id: `node-${id}`, + run_attempt_id: run.activeAttemptId, + ordinal: 1, + status: "completed", + payload_json: encodeUnknownJsonString({ + nativeTurnRef: { driver: "codex", nativeId: input.nativeTurnId ?? id, strength: "strong" }, + }), + })}`; + const changedSelection = { + ...selection, + options: [{ id: "serviceTier", value: "ultrafast" }], + }; + // These selections disagree so reading the current projection or the wrong event is visible. + yield* sql`INSERT INTO orchestration_v2_projection_runs ${sql.insert({ + run_id: run.id, + thread_id: `thread-${id}`, + ordinal: 1, + provider: "codex", + provider_thread_id: `provider-thread-${id}`, + status: "completed", + requested_at: "2026-08-01T10:00:00Z", + payload_json: encodeUnknownJsonString({ + ...run, + status: "completed", + modelSelection: { ...selection, options: [] }, + }), + })}`; + for (const [index, payload] of [ + { ...run, activeAttemptId: "earlier-attempt", modelSelection: changedSelection }, + { ...run, status: "queued", modelSelection: changedSelection }, + run, + { ...run, modelSelection: changedSelection }, + ].entries()) { + yield* sql`INSERT INTO orchestration_events ${sql.insert({ + event_id: `event-${id}-${index}`, + aggregate_kind: "thread", + stream_id: `thread-${id}`, + stream_version: index + 1, + event_type: "run.updated", + occurred_at: "2026-08-01T10:00:00Z", + actor_kind: "system", + metadata_json: "{}", + application_event_version: 2, + payload_json: encodeUnknownJsonString(payload), + })}`; + } + }); + +describe("Codex usage history", () => { + const historyLayer = CodexUsageHistory.layer.pipe(Layer.provideMerge(Sqlite.layerMemory)); + const request = (nativeTurnId: string) => ({ + sessionId: "session", + nativeTurnId, + model: "gpt-6-astra", + }); + + it.effect("resolves a batch from each attempt's first running selection", () => + Effect.gen(function* () { + yield* seedCodexHistory({ id: "fast" }); + yield* seedCodexHistory({ + id: "ultrafast", + options: [{ id: "serviceTier", value: "ultrafast" }], + }); + yield* seedCodexHistory({ id: "legacy-option", options: [{ id: "fastMode", value: true }] }); + yield* seedCodexHistory({ id: "standard", options: [] }); + const requests = ["fast", "ultrafast", "legacy-option", "standard", "fast"].map(request); + const history = yield* CodexUsageHistory.CodexUsageHistory; + const resolved = yield* history.resolve(requests); + assert.strictEqual(resolved.size, requests.length); + assert.deepStrictEqual( + requests.map((item) => resolved.get(item)), + ["fast", "ultrafast", "fast", "standard", "fast"], + ); + }).pipe(Effect.provide(historyLayer)), + ); + + it.effect("leaves ambiguous, mismatched, and missing V2 evidence unresolved", () => + Effect.gen(function* () { + for (const id of [ + "valid", + "duplicate-model", + "duplicate-session", + "imported", + "v1-event", + "queued", + "missing-selection", + ]) { + yield* seedCodexHistory({ id }); + } + yield* seedCodexHistory({ + id: "second-model", + nativeTurnId: "duplicate-model", + model: "other-model", + }); + yield* seedCodexHistory({ + id: "second-session", + nativeTurnId: "duplicate-session", + sessionId: "other-session", + }); + yield* seedCodexHistory({ id: "wrong-model", model: "other-model" }); + yield* seedCodexHistory({ id: "wrong-session", sessionId: "other-session" }); + const sql = yield* SqlClient.SqlClient; + yield* sql`UPDATE orchestration_v2_projection_provider_turns + SET run_attempt_id = NULL WHERE provider_turn_id = 'turn-imported'`; + yield* sql`DELETE FROM orchestration_v2_projection_run_attempts WHERE attempt_id = 'attempt-imported'`; + yield* sql`UPDATE orchestration_events SET application_event_version = 1 + WHERE stream_id = 'thread-v1-event'`; + yield* sql`UPDATE orchestration_events + SET payload_json = json_set(payload_json, '$.status', 'queued') + WHERE stream_id = 'thread-queued'`; + yield* sql`UPDATE orchestration_events + SET payload_json = json_remove(payload_json, '$.modelSelection') + WHERE event_id = 'event-missing-selection-2'`; + const requests = [ + "valid", + "duplicate-model", + "duplicate-session", + "wrong-model", + "wrong-session", + "missing-turn", + "imported", + "v1-event", + "queued", + "missing-selection", + ].map(request); + const history = yield* CodexUsageHistory.CodexUsageHistory; + const resolved = yield* history.resolve(requests); + assert.deepStrictEqual([...resolved], [[requests[0], "fast"]]); + }).pipe(Effect.provide(historyLayer)), + ); + + it.effect( + "reports SQL failures through the typed channel and can resolve again after repair", + () => + Effect.gen(function* () { + yield* seedCodexHistory({ id: "retry" }); + const history = yield* CodexUsageHistory.CodexUsageHistory; + const sql = yield* SqlClient.SqlClient; + const input = request("retry"); + yield* sql`ALTER TABLE orchestration_events RENAME TO unavailable_events`; + const error = yield* Effect.flip(history.resolve([input])); + assert.instanceOf(error, CodexUsageHistory.CodexUsageHistoryReadError); + assert.strictEqual(error.requestedTurnCount, 1); + yield* sql`ALTER TABLE unavailable_events RENAME TO orchestration_events`; + assert.strictEqual((yield* history.resolve([input])).get(input), "fast"); + }).pipe(Effect.provide(historyLayer)), + ); +}); + describe("UsageService", () => { + it.live( + "repairs initial Codex prices after unchanged-file retries, persists evidence and corrections, and honors later native tiers", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const sessions = NodePath.join(home, "codex", "sessions"); + const fastPath = NodePath.join(sessions, "fast.jsonl"); + const ultraPath = NodePath.join(sessions, "ultra.jsonl"); + const meta = (id: string) => ({ + type: "session_meta", + payload: { id, model_provider: "openai" }, + }); + const context = (turn_id?: string) => ({ + type: "turn_context", + payload: { model: "gpt-6-astra", turn_id }, + }); + const usage = (output_tokens: number) => ({ + type: "event_msg", + timestamp: "2026-08-01T10:00:00Z", + payload: { + type: "token_count", + info: { last_token_usage: { input_tokens: 0, output_tokens } }, + }, + }); + const tier = (service_tier?: string) => ({ + type: "event_msg", + payload: { type: "thread_settings_applied", thread_settings: { service_tier } }, + }); + const lines = (records: readonly unknown[]) => + records.map((record) => encodeUnknownJsonString(record)).join("\n") + "\n"; + const verify = (summary: UsageSummary, output: number, cost: number) => { + assert.strictEqual(totalOutputTokens(summary), output); + assert.strictEqual( + summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0), + cost, + ); + }; + yield* Effect.promise(async () => { + await NodeFSP.mkdir(sessions, { recursive: true }); + await NodeFSP.writeFile( + fastPath, + lines([meta("fast-session"), context("fast-turn"), usage(1)]) + + encodeUnknownJsonString(usage(2)), + ); + await NodeFSP.writeFile( + ultraPath, + lines([meta("ultra-session"), context("ultra-turn"), usage(4)]), + ); + }); + yield* Effect.gen(function* () { + const first = yield* UsageService.make; + verify(yield* first.readSummary(WINDOW), 7, 7); + yield* first.awaitPersisted; + const pending = yield* UsageService.make; + verify(yield* pending.readSummary(WINDOW), 7, 7); + yield* seedCodexHistory({ id: "fast-turn", sessionId: "fast-session" }); + yield* seedCodexHistory({ + id: "ultra-turn", + sessionId: "ultra-session", + options: [{ id: "serviceTier", value: "ultrafast" }], + }); + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE orchestration_events RENAME TO unavailable_events`; + verify(yield* pending.readSummary(WINDOW), 7, 7); + yield* pending.awaitPersisted; + const retry = yield* UsageService.make; + verify(yield* retry.readSummary(WINDOW), 7, 7); + yield* sql`ALTER TABLE unavailable_events RENAME TO orchestration_events`; + // History repair must touch both the committed record and tentative tail. + verify(yield* retry.readSummary(WINDOW), 7, 30); + yield* retry.awaitPersisted; + yield* sql`ALTER TABLE orchestration_events RENAME TO resolved_events`; + verify(yield* retry.readSummary(WINDOW), 7, 30); + const resolved = yield* UsageService.make; + verify(yield* resolved.readSummary(WINDOW), 7, 30); + yield* sql`ALTER TABLE resolved_events RENAME TO orchestration_events`; + + // Completing the tail reparses it; neither an absent turn ID nor a new + // turn with no retained attempt may inherit the inferred Fast speed. + yield* Effect.promise(() => + NodeFSP.appendFile( + fastPath, + "\n" + lines([context(), usage(3), context("unretained-turn"), usage(4)]), + ), + ); + verify(yield* resolved.readSummary(WINDOW), 14, 37); + yield* seedCodexHistory({ + id: "native-turn", + sessionId: "fast-session", + options: [{ id: "serviceTier", value: "ultrafast" }], + }); + yield* seedCodexHistory({ id: "later-native-turn", sessionId: "fast-session" }); + yield* Effect.promise(() => + NodeFSP.appendFile( + fastPath, + lines([ + context("native-turn"), + tier(), + usage(5), + context("later-native-turn"), + usage(6), + tier("priority"), + ]) + encodeUnknownJsonString(usage(7)), + ), + ); + verify(yield* resolved.readSummary(WINDOW), 32, 62); + yield* resolved.awaitPersisted; + const native = yield* UsageService.make; + verify(yield* native.readSummary(WINDOW), 32, 62); + yield* seedCodexHistory({ + id: "after-restart-native", + sessionId: "fast-session", + options: [{ id: "serviceTier", value: "ultrafast" }], + }); + yield* Effect.promise(() => + NodeFSP.appendFile( + fastPath, + "\n" + + lines([context("after-restart-native"), usage(8), tier("ultrafast"), usage(9)]), + ), + ); + verify(yield* native.readSummary(WINDOW), 49, 132); + yield* native.awaitPersisted; + yield* Effect.promise(async () => { + await NodeFSP.rm(fastPath); + await NodeFSP.rm(ultraPath); + }); + yield* sql`DELETE FROM orchestration_events`; + const deleted = yield* UsageService.make; + verify(yield* deleted.readSummary(WINDOW), 49, 132); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-initial-tier", + home, + settings, + ratesDocument: { + "gpt-6-astra": { + input_cost_per_token: 0, + output_cost_per_token: 1, + input_cost_per_token_priority: 0, + output_cost_per_token_priority: 2, + input_cost_per_token_ultrafast: 0, + output_cost_per_token_ultrafast: 6, + }, + }, + }), + ), + ); + }).pipe(Effect.scoped), + ); + it.live( "reads Pi per-model usage and auxiliary costs once across forks and repeated entries", () => @@ -450,6 +806,227 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live( + "reads Muse inference history once, persists appended usage, and reprices unknown models", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const museHome = NodePath.join(home, "configured-data", "muse"); + const dir = NodePath.join(museHome, "sessions", "2026", "08", "01", "parent"); + const child = NodePath.join(dir, "subagent", "child"); + const entry = ( + id: string, + sessionId = "parent", + timestamp = "2026-08-01T00:00:00Z", + model = "muse-unknown", + ) => ({ + schema_version: 1, + record_type: "event", + payload_type: "runtime.session", + payload_schema_version: 1, + id, + recorded_at: Date.parse(timestamp) * 1000 + 999, + stream: { kind: "session", id: sessionId }, + payload: { + source_run_record_id: id, + event: { + kind: "model_completed", + model, + usage: { + input_tokens: 100, + cached_tokens: 60, + cache_read_tokens: 60, + cache_write_tokens: 10, + output_tokens: 20, + reasoning_tokens: 8, + }, + }, + }, + }); + const parent = entry("inference-1"); + const review = { + ...entry("review", "child"), + payload_schema_version: 3, + payload: { + event: { + ...parent.payload.event, + kind: "automated_review_completed", + model: { model_id: "priced-model" }, + usage: { + input_tokens: 100, + cached_input_tokens: 60, + output_tokens: 20, + reasoning_tokens: 8, + }, + }, + }, + }; + yield* Effect.promise(async () => { + await NodeFSP.mkdir(child, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(dir, "session.jsonl"), + [ + parent, + parent, + { + ...parent, + payload: { event: { ...parent.payload.event, kind: "workflow_completed" } }, + }, + { ...parent, payload_type: "goal_usage_attribution" }, + entry("before", "parent", "2026-07-31T23:59:59.999Z"), + entry("after", "parent", "2026-08-02T00:00:00Z"), + ] + .map((line) => encodeUnknownJsonString(line)) + .join("\n") + "\n{broken}\n", + ); + await NodeFSP.writeFile( + NodePath.join(child, "session.jsonl"), + [ + { ...parent, id: "copied-envelope", stream: { kind: "session", id: "child" } }, + entry("child-inference", "child"), + review, + ] + .map((line) => encodeUnknownJsonString(line)) + .join("\n") + "\n", + ); + await NodeFSP.writeFile( + NodePath.join(child, "telemetry.jsonl"), + encodeUnknownJsonString(entry("not-a-session")) + "\n", + ); + }); + using _create = vi.spyOn(MuseSdk, "createMuseSdkHostEffect").mockImplementation((options) => + Effect.succeed({ + initializeResult: { + grantedCapabilities: [], + museHome: NodePath.join(options.environment?.XDG_DATA_HOME ?? home, "muse"), + }, + close: async () => {}, + } as unknown as MuseSdk.MuseSdkHost), + ); + yield* Effect.gen(function* () { + const service = yield* UsageService.make; + const window = { + timeZone: "UTC", + sinceDay: UsageDay.make("2026-08-01"), + untilDay: UsageDay.make("2026-08-01"), + }; + const muse = (summary: UsageSummary) => + summary.buckets.filter((bucket) => bucket.provider === "muse"); + const first = yield* service.readSummary(window); + const buckets = muse(first); + assert.strictEqual( + buckets.reduce((sum, b) => sum + b.records, 0), + 3, + ); + assert.strictEqual( + buckets.reduce((sum, b) => sum + totalTokens(b.totals), 0), + 360, + ); + const unknown = buckets.find((b) => b.model === "muse-unknown"); + assert.strictEqual(unknown?.costSource, "unpriced"); + assert.strictEqual(unknown?.unpricedRecords, 2); + assert.deepStrictEqual(unknown?.totals, { + uncachedInputTokens: 60, + cachedInputTokens: 120, + cacheCreationTokens: 20, + outputTokens: 40, + reasoningTokens: 16, + }); + const priced = buckets.find((b) => b.model === "priced-model"); + assert.strictEqual(priced?.costSource, "modelPriced"); + assert.closeTo(priced?.costUsd ?? NaN, 0.000172, 1e-12); + assert.closeTo(priced?.cacheSavingsUsd ?? NaN, 0.000108, 1e-12); + const sources = first.sources.filter((source) => source.fingerprint.provider === "muse"); + assert.strictEqual(sources.length, 1); + assert.strictEqual(sources[0]?.scannedFiles, 2); + assert.strictEqual(sources[0]?.distinctSessions, 2); + const local = muse( + yield* service.readSummary({ ...window, timeZone: "America/Los_Angeles" }), + ); + assert.strictEqual( + local.reduce((sum, b) => sum + b.records, 0), + 1, + ); + assert.strictEqual(local[0]?.day, "2026-08-01"); + const hourly = muse( + yield* service.readSummary({ + ...window, + resolution: "hour", + sinceTime: "2026-08-01T00:00:00.000Z", + untilTime: "2026-08-02T00:00:00.000Z", + }), + ); + assert.strictEqual( + hourly.reduce((sum, b) => sum + b.records, 0), + 3, + ); + const appended = encodeUnknownJsonString(entry("appended", "child")); + const file = NodePath.join(child, "session.jsonl"); + yield* Effect.promise(() => NodeFSP.appendFile(file, appended.slice(0, -10))); + assert.deepStrictEqual(muse(yield* service.readSummary(window)), buckets); + yield* service.awaitPersisted; + const restarted = yield* UsageService.make; + yield* Effect.promise(() => NodeFSP.appendFile(file, appended.slice(-10) + "\n")); + const grown = muse(yield* restarted.readSummary(window)); + assert.strictEqual( + grown.reduce((sum, b) => sum + b.records, 0), + 4, + ); + assert.strictEqual( + grown.reduce((sum, b) => sum + totalTokens(b.totals), 0), + 480, + ); + const settingsService = yield* ServerSettings.ServerSettingsService; + yield* settingsService.updateSettings({ + usagePriceOverrides: { + "muse-unknown": { + inputCostPerMillionTokens: 2, + outputCostPerMillionTokens: 4, + cacheReadCostPerMillionTokens: 0.2, + cacheWriteCostPerMillionTokens: 1, + }, + }, + }); + const repriced = muse(yield* restarted.readSummary(window)).find( + (b) => b.model === "muse-unknown", + ); + assert.strictEqual(repriced?.unpricedRecords, 0); + assert.closeTo(repriced?.costUsd ?? NaN, 0.000486, 1e-12); + }).pipe( + Effect.scoped, + Effect.provide( + layerService({ + prefix: "usage-muse", + home, + environment: { XDG_DATA_HOME: NodePath.dirname(museHome) }, + settings: { + ...settings, + providerInstances: { + ...settings.providerInstances, + [ProviderInstanceId.make("muse")]: { + driver: ProviderDriverKind.make("muse"), + enabled: false, + }, + [ProviderInstanceId.make("muse-alias")]: { + driver: ProviderDriverKind.make("muse"), + enabled: false, + }, + }, + }, + ratesDocument: { + "priced-model": { + input_cost_per_token: 0.000002, + output_cost_per_token: 0.000004, + cache_read_input_token_cost: 0.0000002, + cache_creation_input_token_cost: 0.0000002, + }, + }, + }), + ), + ); + }).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; @@ -651,26 +1228,6 @@ describe("UsageService", () => { ); }).pipe(Effect.scoped), ); - it.live("omits Cursor account usage when no file login is saved", () => - Effect.gen(function* () { - const { settings, home } = yield* setup; - for (const platform of ["linux", "win32", "darwin"] as const) { - const service = yield* UsageService.make.pipe( - Effect.provide( - layerService({ - prefix: `usage-service-cursor-no-login-${platform}`, - home, - settings, - platform, - environment: { AGENT_CLI_CREDENTIAL_STORE: "file" }, - }), - ), - ); - const summary = yield* service.readSummary(WINDOW); - assert.isFalse(summary.sources.some((source) => source.fingerprint.provider === "cursor")); - } - }).pipe(Effect.scoped), - ); it.live("keeps Cursor credential errors visible when a saved login cannot be read", () => Effect.gen(function* () { @@ -691,138 +1248,6 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live("answers Cursor from its cache while one shared refresh runs", () => - Effect.gen(function* () { - const { settings, home } = yield* setup; - yield* writeCursorLogin(home); - yield* TestClock.setTime(CURSOR_NOW); - const cursor = makeFakeCursor(); - cursor.state.events = [{ timestampMs: CURSOR_NOW - 2 * HOUR_MS, outputTokens: 5 }]; - const gate = yield* Deferred.make(); - cursor.state.gate = gate; - yield* Effect.gen(function* () { - const service = yield* makeWithCursor(cursor.read); - const cold = yield* service.readSummary(WINDOW); - assert.strictEqual(cursorSource(cold)?.refreshing, true); - assert.strictEqual(cursorSource(cold)?.status, "ok"); - assert.strictEqual(totalOutputTokens(cold), 0); - const joined = yield* service.readSummary(WINDOW); - assert.strictEqual(cursorSource(joined)?.refreshing, true); - - const waited = yield* service - .readSummary({ ...WINDOW, awaitRefresh: true }) - .pipe(Effect.forkChild); - yield* Deferred.succeed(gate, undefined); - const refreshed = yield* Fiber.join(waited); - assert.isFalse(refreshed.sources.some((source) => source.refreshing)); - assert.strictEqual(cursorSource(refreshed)?.status, "ok"); - assert.strictEqual(totalOutputTokens(refreshed), 5); - assert.strictEqual(cursor.state.calls.length, 1); - - yield* TestClock.adjust(Duration.seconds(30)); - const cached = yield* service.readSummary(WINDOW); - assert.isUndefined(cursorSource(cached)?.refreshing); - assert.strictEqual(totalOutputTokens(cached), 5); - assert.strictEqual(cursor.state.calls.length, 1); - - yield* TestClock.adjust(Duration.seconds(31)); - cursor.state.events.push({ timestampMs: CURSOR_NOW, outputTokens: 7 }); - const stale = yield* service.readSummary(WINDOW); - assert.strictEqual(cursorSource(stale)?.refreshing, true); - assert.strictEqual(totalOutputTokens(stale), 5); - const fresh = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); - assert.isUndefined(cursorSource(fresh)?.refreshing); - assert.strictEqual(totalOutputTokens(fresh), 12); - assert.strictEqual(cursor.state.calls.length, 2); - }).pipe(Effect.provide(layerService({ prefix: "usage-service-cursor-swr", home, settings }))); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - - it.live("caches Cursor's whole retention and then refetches only the newest edge", () => - Effect.gen(function* () { - const { settings, home } = yield* setup; - yield* writeCursorLogin(home); - yield* TestClock.setTime(CURSOR_NOW); - const cursor = makeFakeCursor(); - cursor.state.events = [ - { timestampMs: Date.parse("2026-07-10T10:00:00Z"), outputTokens: 17 }, - { timestampMs: CURSOR_NOW - 24 * HOUR_MS, outputTokens: 5 }, - { timestampMs: CURSOR_NOW - HOUR_MS / 2, outputTokens: 7 }, - { timestampMs: CURSOR_NOW - HOUR_MS / 2, outputTokens: 7 }, - ]; - yield* Effect.gen(function* () { - const service = yield* makeWithCursor(cursor.read); - const read = (input: UsageSummaryInput) => - service.readSummary({ ...input, awaitRefresh: true }); - assert.strictEqual(totalOutputTokens(yield* read(WINDOW)), 19); - assert.deepStrictEqual(cursor.state.calls, [ - { sinceMs: CURSOR_NOW - CURSOR_RETENTION_MS, untilMs: CURSOR_NOW }, - ]); - - const wide = { ...WINDOW, sinceDay: UsageDay.make("2026-07-01") }; - assert.strictEqual(totalOutputTokens(yield* read(wide)), 36); - assert.strictEqual(cursor.state.calls.length, 1); - - cursor.state.events.push( - { timestampMs: CURSOR_NOW - HOUR_MS / 6, outputTokens: 11 }, - { timestampMs: CURSOR_NOW + HOUR_MS, outputTokens: 13 }, - ); - yield* TestClock.adjust(Duration.hours(2)); - assert.strictEqual(totalOutputTokens(yield* read(WINDOW)), 43); - assert.deepStrictEqual(cursor.state.calls[1], { - sinceMs: CURSOR_NOW - HOUR_MS, - untilMs: CURSOR_NOW + 2 * HOUR_MS, - }); - - cursor.state.accountKey = "account-b"; - yield* TestClock.adjust(Duration.minutes(2)); - assert.strictEqual(totalOutputTokens(yield* read(wide)), 60); - assert.strictEqual(cursor.state.calls.length, 4); - assert.strictEqual(cursorSource(yield* read(wide))?.fingerprint.volumeId, "account-b"); - }).pipe( - Effect.provide( - layerService({ prefix: "usage-service-cursor-incremental", home, settings }), - ), - ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - - it.live("reports a failed Cursor refresh from its cache without refreshing", () => - Effect.gen(function* () { - const { settings, home } = yield* setup; - yield* writeCursorLogin(home); - yield* TestClock.setTime(CURSOR_NOW); - const cursor = makeFakeCursor(); - cursor.state.events = [{ timestampMs: CURSOR_NOW - HOUR_MS * 3, outputTokens: 5 }]; - yield* Effect.gen(function* () { - const service = yield* makeWithCursor(cursor.read); - yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); - - yield* TestClock.adjust(Duration.minutes(2)); - cursor.state.error = "Sign in to Cursor again to read account usage."; - const failed = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); - assert.strictEqual(cursorSource(failed)?.status, "partial"); - assert.strictEqual(cursorSource(failed)?.message, cursor.state.error); - assert.isUndefined(cursorSource(failed)?.refreshing); - assert.strictEqual(totalOutputTokens(failed), 5); - - const again = yield* service.readSummary(WINDOW); - assert.strictEqual(cursorSource(again)?.status, "partial"); - assert.isUndefined(cursorSource(again)?.refreshing); - assert.strictEqual(cursor.state.calls.length, 2); - - yield* TestClock.adjust(Duration.minutes(2)); - cursor.state.accountKey = "account-b"; - const switched = yield* service.readSummary({ ...WINDOW, awaitRefresh: true }); - assert.strictEqual(cursorSource(switched)?.status, "missing"); - assert.strictEqual(cursorSource(switched)?.message, cursor.state.error); - assert.strictEqual(totalOutputTokens(switched), 0); - }).pipe( - Effect.provide(layerService({ prefix: "usage-service-cursor-failure", home, settings })), - ); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - it.live("restores the Cursor account cache after a restart", () => Effect.gen(function* () { const { settings, home } = yield* setup; @@ -985,6 +1410,85 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("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"); + const instanceRoot = NodePath.join(home, "opencode-work"); + const alias = NodePath.join(home, "opencode-alias"); + const dataHome = NodePath.join(home, "data"); + const xdgRoot = NodePath.join(dataHome, "opencode"); + const histories = [ + { root: hostRoot, id: "host", output: 5 }, + { root: instanceRoot, id: "work", output: 7 }, + { root: xdgRoot, id: "xdg", output: 11 }, + ]; + yield* Effect.promise(async () => { + for (const { root, id, output } of histories) { + const directory = NodePath.join(root, "storage", "message", "session-1"); + await NodeFSP.mkdir(directory, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(directory, `${id}.json`), + encodeUnknownJsonString({ + role: "assistant", + modelID: "example-model", + time: { created: Date.parse("2026-08-01T10:00:00Z") }, + tokens: { input: 10, output }, + }), + ); + } + await NodeFSP.symlink(instanceRoot, alias, "junction"); + }); + const service = yield* UsageService.make.pipe( + Effect.provide( + layerService({ + prefix: "usage-service-opencode-instances", + home, + environment: { XDG_DATA_HOME: dataHome }, + settings: { + ...settings, + providerInstances: { + ...settings.providerInstances, + [ProviderInstanceId.make("opencode-work")]: { + driver: ProviderDriverKind.make("opencode"), + environment: [ + { + name: "OPENCODE_DATA_DIR", + value: ` ${instanceRoot}, ${alias} `, + sensitive: false, + }, + ], + }, + [ProviderInstanceId.make("opencode-xdg")]: { + driver: ProviderDriverKind.make("opencode"), + environment: [{ name: "OPENCODE_DATA_DIR", value: "", sensitive: false }], + }, + }, + }, + }), + ), + ); + const summary = yield* service.readSummary(WINDOW); + const sources = summary.sources.filter( + (source) => source.fingerprint.provider === "opencode", + ); + const expectedRoots = yield* Effect.promise(() => + Promise.all(histories.map(({ root }) => NodeFSP.realpath(root))), + ); + assert.deepStrictEqual( + sources.map((source) => source.fingerprint.resolvedHomePath).sort(), + expectedRoots.sort(), + ); + assert.deepStrictEqual( + summary.buckets + .filter((bucket) => bucket.provider === "opencode") + .map((bucket) => bucket.totals.outputTokens) + .sort((a, b) => a - b), + [5, 7, 11], + ); + }).pipe(Effect.scoped), + ); + it.live("counts aliased OpenCode and Antigravity directories once", () => Effect.gen(function* () { const { settings, home } = yield* setup; @@ -1039,6 +1543,77 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); + it.live("reads Antigravity history from each instance's data directory", () => + Effect.gen(function* () { + const { settings, home } = yield* setup; + const first = NodePath.join(home, "antigravity-first"); + const second = NodePath.join(home, "antigravity-second"); + yield* Effect.promise(async () => { + for (const [dir, outputTokens] of [ + [first, 7], + [second, 11], + ] as const) { + await NodeFSP.mkdir(dir); + const db = new NodeSqlite.DatabaseSync( + NodePath.join(dir, `${NodePath.basename(dir)}.db`), + ); + try { + db.exec("CREATE TABLE steps (idx INTEGER, metadata BLOB)"); + // Step protobuf: 100 input tokens, distinct output tokens, and 2026-08-01T10:00Z. + const metadata = new Uint8Array([ + 0x4a, + 4, + 0x10, + 100, + 0x18, + outputTokens, + ...Buffer.from("420608a087b7d306", "hex"), + ]); + db.prepare("INSERT INTO steps VALUES (?, ?)").run(0, metadata); + } finally { + db.close(); + } + } + }); + const instance = (dataDir: string) => ({ + driver: ProviderDriverKind.make("antigravity"), + environment: [{ name: "ANTIGRAVITY_DATA_DIR", value: dataDir, sensitive: false }], + }); + const service = yield* UsageService.make.pipe( + Effect.provide( + layerService({ + prefix: "usage-service-antigravity-instances-test", + home, + settings: { + providerInstances: { + ...settings.providerInstances, + [ProviderInstanceId.make("antigravity-first")]: instance(first), + [ProviderInstanceId.make("antigravity-second")]: instance(` ${second}, `), + }, + }, + }), + ), + ); + const summary = yield* service.readSummary(WINDOW); + const roots = summary.sources + .filter((source) => source.fingerprint.provider === "antigravity") + .map((source) => source.fingerprint.resolvedHomePath); + for (const [dir, outputTokens] of [ + [first, 7], + [second, 11], + ] as const) { + const root = yield* Effect.promise(() => NodeFSP.realpath(dir)); + assert.include(roots, root); + assert.strictEqual( + summary.buckets + .filter((bucket) => bucket.provider === "antigravity" && bucket.sourcePath === root) + .reduce((sum, bucket) => sum + bucket.totals.outputTokens, 0), + outputTokens, + ); + } + }).pipe(Effect.scoped), + ); + it.live("reads configured and disabled accounts once across shared and aliased homes", () => Effect.gen(function* () { const { transcript, settings, home } = yield* setup; @@ -1358,22 +1933,127 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live("counts appended usage on a rescan of a grown transcript", () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); - - const service = yield* UsageService.make.pipe( - Effect.provide(layerService({ prefix: "usage-service-grow-test", home, settings })), - ); - - const first = yield* service.readSummary(WINDOW); - assert.strictEqual(totalOutputTokens(first), 5); - - yield* Effect.promise(() => NodeFSP.appendFile(transcript, claudeLine(2, 7))); - const second = yield* service.readSummary(WINDOW); - assert.strictEqual(totalOutputTokens(second), 12); - }).pipe(Effect.scoped), + it.live( + "retains Codex reconciliation and partial coverage through persisted restart, append and repair", + () => + Effect.gen(function* () { + const { home, settings } = yield* setup; + const dir = NodePath.join(home, "codex", "sessions"); + const transcript = NodePath.join(dir, "rollout.jsonl"); + const usage = (input: number, output: number) => ({ + input_tokens: input, + output_tokens: output, + total_tokens: input + output, + }); + const counted = (input: number, output: number, totalInput: number, totalOutput: number) => + encodeUnknownJsonString({ + type: "event_msg", + timestamp: "2026-08-01T10:00:00Z", + payload: { + type: "token_count", + info: { + last_token_usage: usage(input, output), + total_token_usage: usage(totalInput, totalOutput), + }, + }, + }); + const tier = (service_tier: string) => + encodeUnknownJsonString({ + type: "event_msg", + payload: { type: "thread_settings_applied", thread_settings: { service_tier } }, + }); + const bad = counted(10, 2, 130, 28); + // Cross the reader's projection threshold so cumulative fields must survive selection. + const stale = counted(20, 5, 100, 20).replace( + '"payload":', + '"padding":' + encodeUnknownJsonString("x".repeat(9 * 1024 * 1024)) + ',"payload":', + ); + let content = [ + encodeUnknownJsonString({ type: "turn_context", payload: { model: "gpt-6-astra" } }), + counted(100, 20, 100, 20), + stale, + tier("priority"), + bad, + ].join("\n"); + yield* Effect.promise(async () => { + await NodeFSP.mkdir(dir, { recursive: true }); + await NodeFSP.writeFile(transcript, content); + }); + yield* Effect.gen(function* () { + const verify = ( + summary: UsageSummary, + output: number, + cost: number, + malformed: number, + ) => { + assert.strictEqual(totalOutputTokens(summary), output); + assert.strictEqual( + summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0), + cost, + ); + const source = summary.sources.find( + (source) => source.fingerprint.provider === "codex", + ); + assert.strictEqual(source?.status, malformed === 0 ? "ok" : "partial"); + assert.strictEqual(source?.malformedRecords, malformed); + if (malformed > 0) assert.match(source?.message ?? "", /1 malformed or inconsistent/); + else assert.notMatch(source?.message ?? "", /malformed|inconsistent/); + }; + const open = vi.spyOn(NodeFSP, "open"); + open.mockClear(); + yield* Effect.addFinalizer(() => Effect.sync(() => open.mockRestore())); + const first = yield* UsageService.make; + const cold = yield* first.readSummary(WINDOW); + assert.isTrue(open.mock.calls.some(([path]) => path === transcript)); + verify(cold, 20, 20, 1); + yield* first.awaitPersisted; + const restarted = yield* UsageService.make; + open.mockClear(); + verify(yield* first.readSummary(WINDOW), 20, 20, 1); + verify(yield* restarted.readSummary(WINDOW), 20, 20, 1); + assert.isFalse(open.mock.calls.some(([path]) => path === transcript)); + open.mockRestore(); + + const append = "\n" + counted(10, 2, 140, 30) + "\n"; + content += append; + yield* Effect.promise(() => NodeFSP.appendFile(transcript, append)); + verify(yield* restarted.readSummary(WINDOW), 22, 24, 1); + yield* restarted.awaitPersisted; + const resumed = yield* UsageService.make; + verify(yield* resumed.readSummary(WINDOW), 22, 24, 1); + const next = tier("ultrafast") + "\n" + counted(10, 2, 150, 32) + "\n"; + content += next; + yield* Effect.promise(() => NodeFSP.appendFile(transcript, next)); + verify(yield* resumed.readSummary(WINDOW), 24, 36, 1); + + const repaired = content.replace(bad, counted(30, 8, 130, 28)); + assert.strictEqual(Buffer.byteLength(repaired), Buffer.byteLength(content)); + yield* Effect.promise(async () => { + const stat = await NodeFSP.stat(transcript); + await NodeFSP.writeFile(transcript, repaired); + await NodeFSP.utimes(transcript, stat.atime, stat.mtimeMs / 1000 + 1); + }); + verify(yield* resumed.readSummary(WINDOW), 32, 52, 0); + }).pipe( + Effect.provide( + layerService({ + prefix: "usage-codex-reconciliation", + home, + settings, + ratesDocument: { + "gpt-6-astra": { + input_cost_per_token: 0, + output_cost_per_token: 1, + input_cost_per_token_priority: 0, + output_cost_per_token_priority: 2, + input_cost_per_token_ultrafast: 0, + output_cost_per_token_ultrafast: 6, + }, + }, + }), + ), + ); + }).pipe(Effect.scoped), ); it.live( @@ -1431,9 +2111,9 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live( - "upgrades a v4 cache: reprices live Codex tiers, keeps deleted rollouts, leaves v4 intact", - () => + it.live.each([4, 5, 6, 7, 8])( + "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts and the old file", + (version) => Effect.gen(function* () { const { home, settings } = yield* setup; const sessions = NodePath.join(home, "codex", "sessions"); @@ -1453,7 +2133,10 @@ describe("UsageService", () => { timestamp: "2026-08-01T10:00:00Z", payload: { type: "token_count", - info: { last_token_usage: { input_tokens: 0, output_tokens: outputTokens } }, + info: { + last_token_usage: { input_tokens: 0, output_tokens: outputTokens }, + total_token_usage: { input_tokens: 100, output_tokens: outputTokens + 30 }, + }, }, }, ] @@ -1469,33 +2152,65 @@ describe("UsageService", () => { yield* Effect.gen(function* () { const { stateDir } = yield* ServerConfig.ServerConfig; - const cachePath = NodePath.join(stateDir, "usage-scan-cache-v5.json"); - const legacyPath = NodePath.join(stateDir, "usage-scan-cache.json"); + const cachePath = NodePath.join(stateDir, SCAN_CACHE_FILE_NAME); + const legacyPath = NodePath.join( + stateDir, + version === 4 ? "usage-scan-cache.json" : `usage-scan-cache-v${version}.json`, + ); const first = yield* UsageService.make; yield* first.readSummary(WINDOW); yield* first.awaitPersisted; const legacy = yield* Effect.promise(async () => { + const livePath = await NodeFSP.realpath(live); const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { - files: Record; + files: Record }>; }; - for (const file of Object.values(document.files)) { - file.r = file.r.map((row) => [...row.slice(0, 10), 0]); - delete file.cs.speed; + for (const [path, file] of Object.entries(document.files)) { + file.r = file.r.map((row) => [ + ...row.slice(0, 6), + path === livePath ? 99 : row[6], + ...row.slice(7, 10), + version === 4 ? 0 : 1, + ]); + if (version === 4) delete file.cs.speed; + if (version < 6) { + delete file.cs.lastCumulativeUsage; + delete file.cs.malformedRecords; + } + if (version === 8 && path === livePath) { + file.r = []; + file.mr = 1; + file.cs.malformedRecords = 1; + } } - const text = encodeUnknownJsonString({ ...document, version: 4 }); - await NodeFSP.writeFile(legacyPath, text); + const text = encodeUnknownJsonString({ ...document, version }); await NodeFSP.rm(cachePath); + await NodeFSP.writeFile(legacyPath, text); + if (version === 6) { + for (const [name, olderVersion] of [ + ["usage-scan-cache-v5.json", 5], + ["usage-scan-cache.json", 4], + ] as const) { + await NodeFSP.writeFile( + NodePath.join(stateDir, name), + encodeUnknownJsonString({ ...document, version: olderVersion, files: {} }), + ); + } + } await NodeFSP.rm(deleted); return text; }); - const summary = yield* (yield* UsageService.make).readSummary(WINDOW); + const upgraded = yield* UsageService.make; + const summary = yield* upgraded.readSummary(WINDOW); assert.strictEqual(totalOutputTokens(summary), 30); assert.strictEqual( summary.buckets.reduce((sum, bucket) => sum + bucket.costUsd, 0), - 80, + 60 + 20 * (version === 4 ? 1 : 2), ); + yield* upgraded.awaitPersisted; + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v9.json"); assert.strictEqual( yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")), legacy, @@ -1503,13 +2218,15 @@ describe("UsageService", () => { }).pipe( Effect.provide( layerService({ - prefix: "usage-service-v4-upgrade-test", + prefix: "usage-service-cache-upgrade-test", home, settings, ratesDocument: { "gpt-6-astra": { input_cost_per_token: 0, output_cost_per_token: 1, + input_cost_per_token_priority: 0, + output_cost_per_token_priority: 2, input_cost_per_token_ultrafast: 0, output_cost_per_token_ultrafast: 6, }, @@ -1689,46 +2406,49 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( - "keeps the later read when a scan that read earlier finishes first", - () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - const dir = NodePath.dirname(transcript); - const gate = (name: string) => NodePath.join(dir, `${name}.jsonl`); - const wideProbe = gate("wide-probe"); - const wideHold = gate("wide-hold"); - const narrowProbe = gate("narrow-probe"); - const narrowHold = gate("narrow-hold"); - yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); - yield* makeGate(wideProbe, BEFORE_NARROW_WINDOW); - yield* makeGate(wideHold, BEFORE_NARROW_WINDOW); - yield* Effect.gen(function* () { - const service = yield* UsageService.make; - const wide = yield* service.readSummary(WINDOW).pipe(Effect.forkChild); - yield* openGate(wideProbe); - yield* replaceFile(transcript, claudeLine(1, 5) + claudeLine(2, 7)); - yield* makeGate(narrowProbe); - yield* makeGate(narrowHold); - const narrow = yield* service.readSummary(NARROW_WINDOW).pipe(Effect.forkChild); - yield* openGate(narrowProbe); - yield* openGate(wideHold); - yield* Fiber.join(wide); - yield* openGate(narrowHold); - yield* Fiber.join(narrow); - - yield* Effect.promise(() => - Promise.all( - [transcript, wideProbe, wideHold, narrowProbe, narrowHold].map((path) => - NodeFSP.rm(path), - ), - ), - ); - assert.strictEqual(totalOutputTokens(yield* service.readSummary(WINDOW)), 12); - }).pipe( - Effect.provide(layerService({ prefix: "usage-service-late-read-test", home, settings })), + 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 = encodeScanCache( + new Map([ + [ + transcript, + { + size: 0, + mtimeMs, + provider: "claude" as const, + records: [], + tailRecords: [], + malformedRecords: 2, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }, + ], + ]), ); - }).pipe(Effect.scoped), + yield* Effect.promise(async () => { + await NodeFSP.mkdir(stateDir, { recursive: true }); + await NodeFSP.writeFile( + NodePath.join(stateDir, SCAN_CACHE_FILE_NAME), + encodeUnknownJsonString(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), ); it.live("reports saved usage of a removed directory only for windows it reaches", () => @@ -1823,119 +2543,6 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live("shares one scan between concurrent identical requests", () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); - - let ratesFetches = 0; - const service = yield* UsageService.make.pipe( - Effect.provide( - layerService({ - prefix: "usage-service-flight-test", - home, - settings, - onRatesFetch: () => { - ratesFetches += 1; - }, - }), - ), - ); - - const [first, second] = yield* Effect.all( - [service.readSummary(WINDOW), service.readSummary(WINDOW)], - { concurrency: 2 }, - ); - assert.deepStrictEqual(first, second); - assert.strictEqual(ratesFetches, 2); - - yield* service.readSummary(WINDOW); - assert.strictEqual(ratesFetches, 2); - }).pipe(Effect.scoped), - ); - - it.live("refetches a rate table inside its TTL only when the client asks", () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); - - let ratesFetches = 0; - const service = yield* UsageService.make.pipe( - Effect.provide( - layerService({ - prefix: "usage-service-rates-refresh-test", - home, - settings, - ratesDocument: { - "claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 }, - }, - onRatesFetch: () => { - ratesFetches += 1; - }, - }), - ), - ); - - const first = yield* service.readSummary(WINDOW); - assert.strictEqual(ratesFetches, 1); - assert.strictEqual(first.pricing.status, "fresh"); - - yield* TestClock.adjust(Duration.minutes(2)); - yield* service.readSummary(WINDOW); - assert.strictEqual(ratesFetches, 1); - - const [refreshed] = yield* Effect.all([service.refreshRates, service.refreshRates], { - concurrency: 2, - }); - assert.strictEqual(ratesFetches, 2); - assert.strictEqual(refreshed.status, "fresh"); - assert.strictEqual(refreshed.knownModels, 1); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - - it.live("preserves cached estimates when both pricing downloads fail and recovers", () => - Effect.gen(function* () { - const { transcript, settings, home } = yield* setup; - yield* Effect.promise(() => NodeFSP.writeFile(transcript, claudeLine(1, 5))); - let status = 200; - const requests: string[] = []; - const service = yield* UsageService.make.pipe( - Effect.provide( - layerService({ - prefix: "usage-service-rates-failure-test", - home, - settings, - ratesDocument: { - "claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 }, - }, - ratesStatus: () => status, - onRatesFetch: (request) => requests.push(request.url), - }), - ), - ); - const first = yield* service.readSummary(WINDOW); - yield* TestClock.adjust(Duration.minutes(2)); - status = 503; - - const failed = yield* service.refreshRates; - assert.strictEqual(failed.status, "cached"); - assert.strictEqual(failed.fetchedAt, first.pricing.fetchedAt); - assert.strictEqual(requests.length, 3); - assert.strictEqual( - requests[2], - "https://api.github.com/repos/BerriAI/litellm/contents/model_prices_and_context_window.json?ref=main", - ); - const cached = yield* service.readSummary(WINDOW); - assert.deepStrictEqual(cached.buckets, first.buckets); - - status = 200; - yield* TestClock.adjust(Duration.minutes(1)); - const recovered = yield* service.refreshRates; - assert.strictEqual(recovered.status, "fresh"); - assert.notStrictEqual(recovered.fetchedAt, first.pricing.fetchedAt); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - it.live.each(["network", "http", "invalidJson", "empty"] as const)( "recovers pricing through the GitHub API after a %s failure", (failure) => @@ -1995,126 +2602,6 @@ describe("UsageService", () => { }).pipe(Effect.scoped), ); - it.live("tries the GitHub API after the primary pricing request times out", () => - Effect.gen(function* () { - const { settings, home } = yield* setup; - const primaryStarted = yield* Deferred.make(); - const service = yield* UsageService.make.pipe( - Effect.provide( - layerService({ - prefix: "usage-service-rates-timeout-test", - home, - settings, - ratesResponse: (request) => - request.url.startsWith("https://api.github.com/") - ? Effect.succeed( - Response.json({ - "claude-fable-5": { input_cost_per_token: 1e-5, output_cost_per_token: 5e-5 }, - }), - ) - : Deferred.succeed(primaryStarted, undefined).pipe(Effect.andThen(Effect.never)), - }), - ), - ); - const refresh = yield* service.refreshRates.pipe(Effect.forkChild); - yield* Deferred.await(primaryStarted); - yield* TestClock.adjust(Duration.seconds(10)); - const pricing = yield* Fiber.join(refresh); - assert.strictEqual(pricing.status, "fresh"); - assert.strictEqual(pricing.knownModels, 1); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - - it.live("keeps pricing unavailable when neither download has usable rates", () => - Effect.gen(function* () { - const { settings, home } = yield* setup; - const service = yield* UsageService.make.pipe( - Effect.provide(layerService({ prefix: "usage-service-rates-empty-test", home, settings })), - ); - const pricing = yield* service.refreshRates; - assert.strictEqual(pricing.status, "unavailable"); - assert.isNull(pricing.fetchedAt); - }).pipe(Effect.scoped), - ); - - it.live.each([false, true])( - "throttles failed pricing loads from completion with cached rates: %s", - (hasCachedRates) => - Effect.gen(function* () { - const { settings, home } = yield* setup; - const primaryStarted = yield* Deferred.make(); - const fallbackStarted = yield* Deferred.make(); - let responding = true; - let requests = 0; - const service = yield* UsageService.make.pipe( - Effect.provide( - layerService({ - prefix: "usage-service-rates-retry-floor-test", - home, - settings, - onRatesFetch: () => { - requests += 1; - }, - ratesResponse: (request) => - responding - ? Effect.succeed( - Response.json({ - "claude-fable-5": { - input_cost_per_token: 1e-5, - output_cost_per_token: 5e-5, - }, - }), - ) - : Deferred.succeed( - request.url.startsWith("https://api.github.com/") - ? fallbackStarted - : primaryStarted, - undefined, - ).pipe(Effect.andThen(Effect.never)), - }), - ), - ); - let fetchedAt: string | null = null; - if (hasCachedRates) { - fetchedAt = (yield* service.refreshRates).fetchedAt; - yield* TestClock.adjust(Duration.hours(24)); - } - responding = false; - const refresh = yield* service.refreshRates.pipe(Effect.forkChild); - yield* Deferred.await(primaryStarted); - yield* TestClock.adjust(Duration.seconds(10)); - yield* Deferred.await(fallbackStarted); - yield* TestClock.adjust(Duration.seconds(10)); - const failed = yield* Fiber.join(refresh); - const expectedStatus = hasCachedRates ? "cached" : "unavailable"; - assert.strictEqual(failed.status, expectedStatus); - assert.strictEqual(failed.fetchedAt, fetchedAt); - const requestsAfterFailure = requests; - assert.strictEqual(requestsAfterFailure, hasCachedRates ? 3 : 2); - - responding = true; - const [immediate, summary] = yield* Effect.all( - [service.refreshRates, service.readSummary(WINDOW)], - { concurrency: 2 }, - ); - assert.strictEqual(immediate.status, expectedStatus); - assert.strictEqual(summary.pricing.status, expectedStatus); - assert.strictEqual(requests, requestsAfterFailure); - yield* TestClock.adjust(Duration.seconds(59)); - const coolingDown = yield* service.refreshRates; - assert.strictEqual(coolingDown.status, expectedStatus); - assert.strictEqual(coolingDown.fetchedAt, fetchedAt); - assert.strictEqual(requests, requestsAfterFailure); - - yield* TestClock.adjust(Duration.seconds(1)); - const recovered = yield* service.refreshRates; - assert.strictEqual(recovered.status, "fresh"); - assert.strictEqual(recovered.knownModels, 1); - assert.notStrictEqual(recovered.fetchedAt, fetchedAt); - assert.strictEqual(requests, requestsAfterFailure + 1); - }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), - ); - it.live("does not orphan an in-flight scan when its first caller is interrupted", () => Effect.gen(function* () { const { settings, home } = yield* setup; diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 49d8d179664bb..356eb1f5fd912 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -50,7 +50,7 @@ import { import { decodeScanCache, dedupeWithinFile, - LEGACY_SCAN_CACHE_FILE_NAME, + LEGACY_SCAN_CACHE_FILE_NAMES, makeScanCacheWriter, pruneScanCache, SCAN_CACHE_FILE_NAME, @@ -67,10 +67,7 @@ const RATES_TTL_MS = 24 * 60 * 60 * 1000; const RATES_REFRESH_FLOOR_MS = 60 * 1000; -/** - * Files are filtered by mtime before opening. The slack covers a session whose - * last write lands just before local midnight on the window's first day. - */ +// mtime slack includes writes just before local midnight on the window's first day. const MTIME_SLACK_MS = 36 * 60 * 60 * 1000; const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000; @@ -124,11 +121,7 @@ const sharedSessionProviders: ReadonlySet = new Set( ), ); -/** - * Only these need cross-file dedupe keys: within one file the occurrence count - * already keeps every key unique, so keying the rest would only build and hash - * a string for each of their records. - */ +// Only shared sessions need cross-file dedupe; per-file occurrence counts make other keys unique. function sharedSessions( files: readonly { readonly records: readonly UsageRecord[] }[], ): ReadonlySet { @@ -195,6 +188,11 @@ export const make = Effect.gen(function* () { const readerContext = yield* Effect.context(); const fileCache: ScanCache = new Map(); + // Reads from concurrent windows can still hold the original record after it is corrected. + const resolvedRecords = new WeakMap(); + const correctedRecord = (record: UsageRecord) => resolvedRecords.get(record) ?? record; + const correctedBatch = (records: readonly UsageRecord[]) => + records.some((record) => resolvedRecords.has(record)) ? records.map(correctedRecord) : records; const sourceCache = new Map(); let cacheDirty = false; const isWithinDirectory = (filePath: string, dir: string) => { @@ -204,7 +202,6 @@ export const make = Effect.gen(function* () { const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json"); const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME); - const legacyScanCachePath = path.join(config.stateDir, LEGACY_SCAN_CACHE_FILE_NAME); const writeCacheFile = (filePath: string, contents: string) => writeFileStringAtomically({ filePath, contents }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), @@ -353,7 +350,7 @@ export const make = Effect.gen(function* () { ([filePath, entry]) => entry.provider === provider && entry.mtimeMs >= retentionCutoffMs && - entry.records.length + entry.tailRecords.length > 0 && + (entry.records.length + entry.tailRecords.length > 0 || entry.malformedRecords > 0) && isWithinDirectory(filePath, dir), ); const volumeId = @@ -379,11 +376,7 @@ export const make = Effect.gen(function* () { return dirs; }); - /** - * `Effect.cached` makes concurrent first readers await the same load rather - * than each seeing a "loaded" flag set before the read finished and cold - * scanning against an empty cache. - */ + // Share first loads so concurrent readers cannot scan against a still-empty cache. const ensureScanCacheLoaded = yield* Effect.cached( Effect.gen(function* () { const readDocument = (filePath: string) => @@ -392,8 +385,9 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); let document = yield* readDocument(scanCachePath); - if (document === null) { - document = yield* readDocument(legacyScanCachePath); + for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) { + if (document !== null) break; + document = yield* readDocument(path.join(config.stateDir, fileName)); cacheDirty = document !== null; } if (document === null) return; @@ -409,13 +403,10 @@ export const make = Effect.gen(function* () { ); const writeScanCache = makeScanCacheWriter(); - // Scans with different windows can finish together; serializing the writes - // keeps an older snapshot from landing after a newer one. + // Serialize writes so concurrently finished window scans cannot overwrite newer snapshots. const persistLock = yield* Semaphore.make(1); - // The dirty flag is cleared before encoding, so a change while the write is - // in flight marks it dirty again. A failed write restores the flag, so the - // next persist retries instead of leaving disk stale. + // Clear dirty before encoding to retain concurrent changes; restore it on failure for retry. const persistCaches = Effect.gen(function* () { if (cacheDirty) { cacheDirty = false; @@ -442,8 +433,6 @@ export const make = Effect.gen(function* () { const awaitPersisted = Effect.suspend(() => Fiber.awaitAll([...pendingPersists])).pipe( Effect.asVoid, ); - // A write still running when the service shuts down finishes first, so the - // next start does not lose the last scan. yield* Effect.addFinalizer(() => awaitPersisted); /** @@ -451,66 +440,102 @@ export const make = Effect.gen(function* () { * than completion order: saved records of deleted transcripts aggregate in * cache order, where the first copy of a duplicate wins. */ - const readFileRecords = ( + const readFileRecords = Effect.fn("UsageService.readFileRecords")(function* ( filePath: string, size: number, mtimeMs: number, provider: UsageProviderKind, format: TranscriptUsageFormat, - ): Effect.Effect<{ + ): Effect.fn.Return<{ readonly records: readonly UsageRecord[]; + readonly malformedRecords: number; readonly failed?: true; readonly update?: { readonly entry: CachedFile; readonly replaces: CachedFile | undefined }; - }> => - Effect.gen(function* () { - const cached = fileCache.get(filePath); - // Provider is part of the identity: if both providers were ever pointed - // at one directory, a hit parsed by the other parser must not be reused. - if ( - cached && - cached.size === size && - cached.mtimeMs === mtimeMs && - cached.provider === provider - ) { - return { - records: - cached.tailRecords.length === 0 - ? cached.records - : [...cached.records, ...cached.tailRecords], - }; - } - - // Only a strictly grown file may resume. Same size with a new mtime, or - // a shrunken file, means rewritten content; re-parse it whole. - const resumeFrom = - cached !== undefined && cached.provider === provider && size > cached.size - ? cached.position - : undefined; + }> { + const cached = fileCache.get(filePath); + // Provider is part of the identity: if both providers were ever pointed + // at one directory, a hit parsed by the other parser must not be reused. + if ( + cached && + cached.size === size && + cached.mtimeMs === mtimeMs && + cached.provider === provider + ) { + return { + records: + cached.tailRecords.length === 0 + ? cached.records + : [...cached.records, ...cached.tailRecords], + malformedRecords: cached.malformedRecords, + }; + } - const parsed = yield* Effect.promise(() => - readTranscriptRecords(filePath, format, resumeFrom), - ); - // A read failure is not an empty transcript: caching it under this - // (size, mtime) would silently drop the file's usage until it changes. - if (parsed === null) - return { - records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [], - failed: true, - }; + // Only a strictly grown file may resume. Same size with a new mtime, or + // a shrunken file, means rewritten content; re-parse it whole. + const resumeFrom = + cached !== undefined && cached.provider === provider && size > cached.size + ? cached.position + : undefined; + + const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, format, resumeFrom)); + // A read failure is not an empty transcript: caching it under this + // (size, mtime) would silently drop the file's usage until it changes. + if (parsed === null) + return { + records: cached?.provider === provider ? [...cached.records, ...cached.tailRecords] : [], + malformedRecords: cached?.provider === provider ? cached.malformedRecords : 0, + failed: true, + }; - const base = parsed.resumed && cached !== undefined ? cached.records : []; - const seen = new Set(); - const records = dedupeWithinFile([...base, ...parsed.records], seen); - const tailRecords = dedupeWithinFile(parsed.tailRecords, seen); + if (parsed.resumed && cached !== undefined && cached.tailRecords.length > 0) { + // Completing a tentative line reparses it. Reuse its saved correction only when the + // same usage is emitted again, without putting inferred tiers in the parser state. + const reparsed = [...parsed.records, ...parsed.tailRecords]; + const identity = (record: UsageRecord) => + encodeUsageRecordKey([ + record.provider, + record.sessionId, + record.timestampMs, + record.model, + record.rateModel, + record.totals, + record.reportedCostUsd, + record.dedupeKey, + ]); + for (const [index, previous] of cached.tailRecords.entries()) { + const record = reparsed[index]; + const corrected = correctedRecord(previous); + if ( + record?.unresolvedServiceTierTurnId !== undefined && + corrected.unresolvedServiceTierTurnId === undefined && + identity(record) === identity(corrected) + ) { + resolvedRecords.set(record, corrected); + } + } + } + const base = parsed.resumed && cached !== undefined ? cached.records : []; + const seen = new Set(); + const records = dedupeWithinFile([...base, ...parsed.records], seen); + const tailRecords = dedupeWithinFile(parsed.tailRecords, seen); - return { - records: tailRecords.length === 0 ? records : [...records, ...tailRecords], - update: { - entry: { size, mtimeMs, provider, records, tailRecords, position: parsed.position }, - replaces: cached, + return { + records: tailRecords.length === 0 ? records : [...records, ...tailRecords], + malformedRecords: parsed.malformedRecords, + update: { + entry: { + size, + mtimeMs, + provider, + records, + tailRecords, + malformedRecords: parsed.malformedRecords, + position: parsed.position, }, - }; - }); + replaces: cached, + }, + }; + }); interface ScannedDir { readonly provider: UsageProviderKind; @@ -521,7 +546,11 @@ export const make = Effect.gen(function* () { readonly message?: string; readonly action?: UsageSource["action"]; readonly files: - | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[] + | readonly { + readonly path: string; + readonly records: readonly UsageRecord[]; + readonly malformedRecords: number; + }[] | null; readonly refreshing?: true; } @@ -546,8 +575,8 @@ export const make = Effect.gen(function* () { ), { concurrency: TRANSCRIPT_READ_CONCURRENCY }, ); - const parsedFiles = read.map(({ path, records, update }) => { - if (update === undefined) return { path, records }; + const parsedFiles = read.map(({ path, records, malformedRecords, update }) => { + if (update === undefined) return { path, records, malformedRecords }; // A scan of another window may have cached its own read of this file // meanwhile. Then keep whichever read saw the later file, so a slower // scan never replaces newer usage with older. @@ -555,12 +584,16 @@ export const make = Effect.gen(function* () { if ( current === update.replaces || current === undefined || - !isLaterRead(current, update.entry) + isLaterRead(update.entry, current) ) { - fileCache.set(path, update.entry); + fileCache.set(path, { + ...update.entry, + records: correctedBatch(update.entry.records), + tailRecords: correctedBatch(update.entry.tailRecords), + }); cacheDirty = true; } - return { path, records }; + return { path, records, malformedRecords }; }); const unread = failedPaths + read.filter((file) => file.failed).length; return { @@ -605,6 +638,7 @@ export const make = Effect.gen(function* () { : Effect.succeed(volumeId), (resolved): ScannedDir => ({ ...source, + files: source.files?.map((file) => ({ ...file, malformedRecords: 0 })) ?? null, provider: reader.provider, volumeId: resolved, }), @@ -616,9 +650,7 @@ export const make = Effect.gen(function* () { { concurrency: "unbounded" }, ); - // Independent sources scan together. Transcript directories go one at a - // time, so open files stay at `TRANSCRIPT_READ_CONCURRENCY`. The result - // keeps this order, since aggregation keeps the first copy of a duplicate. + // Scan independent sources together, directories sequentially to bound open files; preserve order for first-copy dedupe. const [transcripts, scanDirs] = yield* Effect.all( [Effect.forEach(dirs, (dir) => scanTranscriptDir(dir, windowStartMs)), scans], { concurrency: "unbounded" }, @@ -699,8 +731,7 @@ export const make = Effect.gen(function* () { const sources: UsageSource[] = []; - // Cleanup may remove transcripts, but the usage we already saved still - // contributes to its source through the normal aggregation and dedupe path. + // Deleted transcripts' saved usage still aggregates and deduplicates normally. const retainedSinceMs = Math.max(windowStartMs, retentionCutoffMs); const filesByDir = scannedDirs.map(({ provider, dir, files }) => { const retainedFiles = [...(files ?? [])]; @@ -713,10 +744,57 @@ export const make = Effect.gen(function* () { !isWithinDirectory(filePath, dir) ) continue; - retainedFiles.push({ path: filePath, records: [...entry.records, ...entry.tailRecords] }); + retainedFiles.push({ + path: filePath, + records: [...entry.records, ...entry.tailRecords], + malformedRecords: entry.malformedRecords, + }); } return retainedFiles; }); + const windowEndMs = + hourlyWindow?.untilTimeMs ?? + Date.parse(`${input.untilDay}T00:00:00Z`) + 86400000 + MTIME_SLACK_MS; + let resolvedAny = false; + for (const { reader } of transcriptReaders) { + if (reader.resolveServiceTiers === undefined) continue; + const pending = new Set(); + for (const [index, files] of filesByDir.entries()) { + if (scannedDirs[index]?.provider !== reader.provider) continue; + for (const file of files) { + for (const raw of file.records) { + const record = correctedRecord(raw); + if ( + record.provider === reader.provider && + record.unresolvedServiceTierTurnId !== undefined && + record.timestampMs >= windowStartMs && + record.timestampMs < windowEndMs + ) { + pending.add(record); + } + } + } + } + if (pending.size === 0) continue; + const resolved = yield* reader + .resolveServiceTiers([...pending]) + .pipe(Effect.provideContext(readerContext)); + for (const [record, speed] of resolved) { + const { unresolvedServiceTierTurnId: _turnId, ...rest } = record; + resolvedRecords.set(record, { ...rest, speed }); + resolvedAny = true; + } + } + if (resolvedAny) { + for (const [filePath, entry] of fileCache) { + const records = correctedBatch(entry.records); + const tailRecords = correctedBatch(entry.tailRecords); + if (records === entry.records && tailRecords === entry.tailRecords) continue; + // Update the current entry by identity; a slow resolver cannot restore an older file. + fileCache.set(filePath, { ...entry, records, tailRecords }); + cacheDirty = true; + } + } const crossFileSessions = sharedSessions(filesByDir.flat()); for (const [ @@ -725,25 +803,27 @@ export const make = Effect.gen(function* () { ] of scannedDirs.entries()) { let scannedFiles = 0; let skippedFiles = 0; + let malformedRecords = 0; // Distinct per directory. Buckets carry per-cell session counts, but a // session spans days and models, so clients total this figure instead. const sessionIds = new Set(); for (const file of filesByDir[index] ?? []) { + malformedRecords += file.malformedRecords; if (file.records.length === 0) { skippedFiles += 1; continue; } scannedFiles += 1; const eventOccurrences = new Map(); - for (const record of file.records) { + for (const rawRecord of file.records) { + const record = correctedRecord(rawRecord); let usageRecord = record; if ( sharedSessionProviders.has(record.provider) && crossFileSessions.has(record.sessionId) ) { - // Match moved copies without collapsing repeated equal events - // within one file (timestamps can have only second precision). + // Dedupe moved copies but retain repeated equal events within a file, including second-precision timestamps. const key = encodeUsageRecordKey([ record.provider, record.sessionId, @@ -761,15 +841,31 @@ export const make = Effect.gen(function* () { } } + const sourceMessage = + message ?? (files === null ? "No transcript directory on this environment." : null); sources.push({ fingerprint: { hostId: sourceHostId ?? hostId, provider, resolvedHomePath: dir, volumeId }, - status: files === null && scannedFiles === 0 ? "missing" : (status ?? "ok"), + status: + files === null && scannedFiles === 0 + ? "missing" + : malformedRecords > 0 + ? status === undefined || status === "ok" + ? "partial" + : status + : (status ?? "ok"), scannedFiles, skippedFiles, - malformedRecords: 0, + malformedRecords, distinctSessions: sessionIds.size, message: - message ?? (files === null ? "No transcript directory on this environment." : null), + malformedRecords > 0 + ? [ + sourceMessage, + `${malformedRecords} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.`, + ] + .filter(Boolean) + .join(" ") + : sourceMessage, ...(action ? { action } : {}), ...(refreshing ? { refreshing } : {}), }); @@ -817,14 +913,11 @@ export const make = Effect.gen(function* () { const existing = inflightScans.get(key); if (existing !== undefined) return existing; - // Enrollment and detached-fiber creation must be atomic. Otherwise a - // canceled first caller can leave a Deferred with no scan to finish it. + // Register and fork atomically so cancellation cannot leave a Deferred without a scan. const created = Deferred.makeUnsafe(); inflightScans.set(key, created); - // Detached so one departing client cannot tear the scan out from under - // the fibers awaiting it; a finished scan warms the cache either way. - // The cache write is registered before the waiters resume, so they - // can await it, but its fiber starts after they have the summary. + // Detach so caller departure cannot cancel shared scans; finished scans warm the cache. + // Register writes before releasing waiters, but start writing after delivering their summary. yield* scanSummary(input, settings).pipe( Effect.onExit((exit) => Effect.sync(() => inflightScans.delete(key)).pipe( diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts index 459363e5fe81e..0119adfd940f3 100644 --- a/apps/server/src/usage/cliproxyApi.test.ts +++ b/apps/server/src/usage/cliproxyApi.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as TestClock from "effect/testing/TestClock"; -import { HttpClient, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import { makeCliproxyApi } from "./cliproxyApi.ts"; @@ -48,7 +48,12 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); function fixture( options: { - accounts?: Array<(typeof accounts)[number] & { disabled?: boolean }>; + accounts?: Array< + (typeof accounts)[number] & { + disabled?: boolean; + id_token: { chatgpt_account_id: string; plan_type?: string; chatgpt_plan_type?: string }; + } + >; upstream?: (request: RequestBody) => { status: number; body: unknown }; cooldownStatus?: number; } = {}, @@ -73,7 +78,7 @@ function fixture( request, Response.json({}, { status: options.cooldownStatus ?? 200 }), ); - expect(path).toBe("/v0/management/api-call"); + expect(path).toMatch(/\/v0\/management\/api-call$/); expect(body?.header?.Authorization).toBe("Bearer $TOKEN$"); const upstream = options.upstream?.(body!) ?? { status: 200, @@ -114,6 +119,80 @@ function fixture( }; } +const unreachableHub = ( + fail: ( + request: Parameters[0]>[0], + ) => HttpClientError.HttpClientError, +) => + makeCliproxyApi.pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => Effect.fail(fail(request))), + ), + Effect.provide(NodeCrypto.layer), + ); + +describe("CLIProxyAPI hub failures", () => { + it.effect("names the TLS code when the hub's certificate is not trusted", () => + Effect.gen(function* () { + const api = yield* unreachableHub( + (request) => + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + // Node's fetch wraps the TLS error, which carries the code, in a generic TypeError. + cause: new TypeError("fetch failed", { + cause: Object.assign(new Error("unable to get local issuer certificate"), { + code: "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", + }), + }), + }), + }), + ); + const error = yield* Effect.flip(api.readAccounts(config)); + expect(error.detail).toContain("UNABLE_TO_GET_ISSUER_CERT_LOCALLY"); + expect(error.detail).toContain("NODE_EXTRA_CA_CERTS"); + }), + ); + + // regression: #18168 Limits hub failures name their TLS, HTTP, or timeout cause + it.effect("ignores a transport code that is not a short Node error code", () => + Effect.gen(function* () { + const api = yield* unreachableHub( + (request) => + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + cause: Object.assign(new Error("odd"), { code: "X".repeat(200) }), + }), + }), + ); + const error = yield* Effect.flip(api.readAccounts(config)); + expect(error.detail).toBe("The hub management request failed."); + }), + ); + + it.effect("names the status, not the body, when the hub rejects the request", () => + Effect.gen(function* () { + const test = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ error: "management-secret is wrong" }, { status: 401 }), + ), + ), + ); + const api = yield* makeCliproxyApi.pipe( + Effect.provideService(HttpClient.HttpClient, test), + Effect.provide(NodeCrypto.layer), + ); + const error = yield* Effect.flip(api.readAccounts(config)); + expect(error.detail).toContain("401"); + expect(error.detail).not.toContain("management-secret"); + }), + ); +}); + describe("CLIProxyAPI built-in management API", () => { it.effect( "reads both accounts and their earliest unexpired credits without plugin endpoints", @@ -145,6 +224,58 @@ describe("CLIProxyAPI built-in management API", () => { }), ); + it.effect("resolves a missing usage plan from current, then legacy, token plans", () => + Effect.gen(function* () { + const test = fixture({ + accounts: [ + { ...accounts[0]!, id_token: { chatgpt_account_id: "account-a", plan_type: "free" } }, + { + ...accounts[1]!, + id_token: { + chatgpt_account_id: "account-b", + plan_type: "go", + chatgpt_plan_type: "plus", + }, + }, + { + ...accounts[1]!, + id: "third.json", + auth_index: "c", + id_token: { chatgpt_account_id: "account-c", chatgpt_plan_type: "free" }, + }, + ], + upstream: (request) => ({ + status: 200, + body: { + ...(request.auth_index === "a" ? { plan_type: "plus" } : {}), + rate_limit: { primary_window: { used_percent: 12 } }, + }, + }), + }); + const api = yield* test.api; + const result = yield* api.readAccounts(config); + expect(result.map((account) => [account.plan, account.usageLimits.windows[0]?.kind])).toEqual( + [ + ["ChatGPT Plus Subscription", "session"], + ["ChatGPT Go Subscription", "monthly"], + ["ChatGPT Free Subscription", "monthly"], + ], + ); + }), + ); + + it.effect("keeps the path of a hub served under a prefix", () => + Effect.gen(function* () { + const test = fixture(); + const api = yield* test.api; + yield* api.readAccounts({ ...config, url: "https://tools.test/cliproxy" }); + expect(test.requests.length).toBeGreaterThan(0); + expect( + test.requests.every((request) => request.path.startsWith("/cliproxy/v0/management/")), + ).toBe(true); + }), + ); + it.effect("keeps usage when the credits endpoint fails", () => Effect.gen(function* () { const test = fixture({ @@ -185,8 +316,9 @@ describe("CLIProxyAPI built-in management API", () => { Effect.gen(function* () { const test = fixture({ accounts: [{ ...accounts[0]!, provider: "claude" }], - upstream: () => ({ - status: 200, + // The usage endpoint answers 429 to requests without a Claude Code user agent. + upstream: (request) => ({ + status: request.header?.["User-Agent"]?.startsWith("claude-code/") ? 200 : 429, body: { five_hour: { utilization: 10, resets_at: null }, seven_day: { utilization: 50, resets_at: "2099-01-01T00:00:00Z" }, @@ -238,21 +370,6 @@ describe("CLIProxyAPI built-in management API", () => { }), ); - it.effect.each([ - ["nothing_to_reset", "nothingToReset"], - ["no_credit", "noCredit"], - ["already_redeemed", "alreadyRedeemed"], - ] as const)("reports %s accurately", ([code, outcome]) => - Effect.gen(function* () { - const test = fixture({ upstream: () => ({ status: 200, body: { code } }) }); - const api = yield* test.api; - expect(yield* api.consume(config, "first.json", "credit")).toEqual({ outcome }); - expect(test.requests.some((request) => request.path.endsWith("/reset-quota"))).toBe( - code === "already_redeemed", - ); - }), - ); - it.effect("reports redemption success even if cooldown clearing fails", () => Effect.gen(function* () { const api = yield* fixture({ cooldownStatus: 404 }).api; diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts index b6404fce42aed..91504d8002295 100644 --- a/apps/server/src/usage/cliproxyApi.ts +++ b/apps/server/src/usage/cliproxyApi.ts @@ -5,12 +5,13 @@ import { type UsageLimitSourceAccount, type UsageLimitSourceConfig, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Schema from "effect/Schema"; -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; import { codexPlanLabel } from "../provider/CodexProvider.ts"; import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts"; @@ -27,6 +28,7 @@ const AuthFile = Schema.Struct({ Schema.Struct({ chatgpt_account_id: Schema.optional(Schema.String), chatgpt_plan_type: Schema.optional(Schema.String), + plan_type: Schema.optional(Schema.String), }), ), }); @@ -88,6 +90,41 @@ const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(Credit const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage)); const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage)); const isUsageLimitSourceError = Schema.is(UsageLimitSourceError); + +// Extra CAs can fix untrusted chains; expiry/hostname failures report codes only. +const UNTRUSTED_CERTIFICATE_CODES = new Set([ + "DEPTH_ZERO_SELF_SIGNED_CERT", + "SELF_SIGNED_CERT_IN_CHAIN", + "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", + "UNABLE_TO_VERIFY_LEAF_SIGNATURE", +]); + +// fetch wraps Node error codes in generic TypeErrors. +const nodeErrorCode = (cause: unknown) => { + for (let error = cause, depth = 0; error instanceof Error && depth < 3; depth += 1) { + const code = (error as { readonly code?: unknown }).code; + if (typeof code === "string" && /^[A-Z0-9_]{1,64}$/.test(code)) return code; + error = error.cause; + } + return undefined; +}; + +// Hub responses can contain credentials; expose only failure kind, HTTP status or Node code. +const describeManagementFailure = (error: unknown) => { + if (Cause.isTimeoutError(error)) return "The hub did not answer within 15 seconds."; + if (HttpClientError.isHttpClientError(error)) { + const reason = error.reason; + if (reason._tag === "StatusCodeError") { + return `The hub answered with HTTP ${reason.response.status}.`; + } + const code = reason._tag === "TransportError" ? nodeErrorCode(reason.cause) : undefined; + if (code !== undefined && UNTRUSTED_CERTIFICATE_CODES.has(code)) { + return `The hub's TLS certificate is not trusted (${code}). If it comes from a private CA, add that CA to NODE_EXTRA_CA_CERTS.`; + } + if (code !== undefined) return `The hub request failed (${code}).`; + } + return "The hub management request failed."; +}; const decodeConsumeResponse = Schema.decodeUnknownEffect( Schema.fromJsonString( Schema.Struct({ @@ -130,7 +167,11 @@ export const makeCliproxyApi = Effect.gen(function* () { body?: unknown, ) { const url = yield* Effect.try({ - try: () => new URL(`/v0/management/${path}`, config.url).toString(), + try: () => + new URL( + `v0/management/${path}`, + config.url.endsWith("/") ? config.url : `${config.url}/`, + ).toString(), catch: () => new UsageLimitSourceError({ detail: "The hub URL is not valid." }), }); const request = ( @@ -143,7 +184,7 @@ export const makeCliproxyApi = Effect.gen(function* () { Effect.flatMap((response) => response.json), Effect.timeout("15 seconds"), Effect.mapError( - () => new UsageLimitSourceError({ detail: "The hub management request failed." }), + (error) => new UsageLimitSourceError({ detail: describeManagementFailure(error) }), ), ); return response; @@ -171,7 +212,12 @@ export const makeCliproxyApi = Effect.gen(function* () { ? { "Chatgpt-Account-Id": account.id_token.chatgpt_account_id } : {}), } - : { Authorization: "Bearer $TOKEN$", "anthropic-beta": "oauth-2025-04-20" }; + : { + Authorization: "Bearer $TOKEN$", + "anthropic-beta": "oauth-2025-04-20", + // The OAuth usage endpoint can return 429 without a Claude Code user agent. + "User-Agent": "claude-code/2.1.273", + }; const raw = yield* management(config, "api-call", { auth_index: account.auth_index, method: data === undefined ? "GET" : "POST", @@ -263,14 +309,16 @@ export const makeCliproxyApi = Effect.gen(function* () { : null; const available = yield* credits(config, account).pipe(Effect.orElseSucceed(() => undefined)); const next = available?.[0]; + const planType = + usage.plan_type ?? account.id_token?.plan_type ?? account.id_token?.chatgpt_plan_type; return { ...base, - plan: codexPlanLabel(usage.plan_type ?? account.id_token?.chatgpt_plan_type), + plan: codexPlanLabel(planType), usageLimits: { ...codexRateLimitsToLimits({ checkedAt, snapshot: { - planType: usage.plan_type ?? null, + planType: planType ?? null, primary: toWindow(usage.rate_limit?.primary_window), secondary: toWindow(usage.rate_limit?.secondary_window), }, @@ -307,8 +355,10 @@ export const makeCliproxyApi = Effect.gen(function* () { config: UsageLimitSourceConfig, ): Effect.fn.Return, UsageLimitSourceError> { const accounts = yield* authFiles(config).pipe( - Effect.mapError( - () => new UsageLimitSourceError({ detail: "The hub could not list accounts." }), + Effect.mapError((error) => + isUsageLimitSourceError(error) + ? error + : new UsageLimitSourceError({ detail: "The hub could not list accounts." }), ), ); return yield* Effect.forEach( diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts index b89c1fe702234..08b3f3ae1b8c8 100644 --- a/apps/server/src/usage/usageAggregation.test.ts +++ b/apps/server/src/usage/usageAggregation.test.ts @@ -68,19 +68,6 @@ function aggregate( } describe("UsageAggregator", () => { - it("requires exact bounds for hourly aggregation", () => { - expect( - () => - new UsageAggregator({ - timeZone: "UTC", - sinceDay: "2026-08-01", - untilDay: "2026-08-31", - resolution: "hour", - rates, - }), - ).toThrow("requires exact time bounds"); - }); - it("splits a bucket's cost by category and speed", () => { const [bucket] = aggregate([record(), record({ speed: "fast" })]).buckets; @@ -111,13 +98,6 @@ describe("UsageAggregator", () => { expect(result.buckets[0]?.totals.outputTokens).toBe(50); }); - it("still sums records that carry no dedupe key", () => { - const result = aggregate([record(), record()]); - - expect(result.duplicatesDropped).toBe(0); - expect(result.buckets[0]?.totals.outputTokens).toBe(100); - }); - it("buckets by the day in the requested time zone", () => { const utc = aggregate([record()], "UTC"); const losAngeles = aggregate([record()], "America/Los_Angeles"); @@ -194,24 +174,6 @@ describe("UsageAggregator", () => { ]); }); - it("keeps daily payloads collapsed when hourly resolution is not requested", () => { - const result = aggregate([ - record({ timestampMs: Date.parse("2026-08-07T04:05:13.944Z") }), - record({ timestampMs: Date.parse("2026-08-07T05:05:13.944Z") }), - ]); - - expect(result.buckets).toHaveLength(1); - expect(result.buckets[0]?.hourStart).toBeUndefined(); - expect(result.buckets[0]?.records).toBe(2); - }); - - it("prices against the rate table", () => { - const result = aggregate([record()]); - - expect(result.buckets[0]?.costUsd).toBeCloseTo(0.004625, 9); - expect(result.buckets[0]?.costSource).toBe("modelPriced"); - }); - it("counts tokens but not cost for a model with no rate", () => { const result = aggregate([record({ model: "kimi-k3" })]); @@ -228,26 +190,6 @@ describe("UsageAggregator", () => { expect(result.buckets[0]?.costSource).toBe("providerReported"); }); - it("drops records outside the window", () => { - const result = aggregate([record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") })]); - - expect(result.outOfWindow).toBe(1); - expect(result.buckets).toHaveLength(0); - }); - - it("reports whether a record contributed", () => { - const aggregator = new UsageAggregator({ - timeZone: "UTC", - sinceDay: "2026-08-01", - untilDay: "2026-08-31", - rates, - }); - - expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(true); - expect(aggregator.add(record({ dedupeKey: "msg_1:" }))).toBe(false); - expect(aggregator.add(record({ timestampMs: Date.parse("2026-07-01T12:00:00Z") }))).toBe(false); - }); - it("folds a mapped model into its target and prices it there", () => { const aggregator = new UsageAggregator({ timeZone: "UTC", @@ -266,16 +208,6 @@ describe("UsageAggregator", () => { expect(result.buckets[0]?.costUsd).toBeCloseTo(0.00925, 9); expect(result.buckets[0]?.unpricedRecords).toBe(0); }); - - it("separates providers and models into their own buckets", () => { - const result = aggregate([ - record(), - record({ provider: "codex", model: "gpt-5.6-sol" }), - record({ model: "claude-opus-5" }), - ]); - - expect(result.buckets).toHaveLength(3); - }); }); describe("resolveModelAliases", () => { diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index 65e28d4845a72..17903cd062eae 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -10,10 +10,7 @@ import type { import { EMPTY_TOTALS, type UsageRecord } from "@t3tools/provider-core/server/usage"; import { cacheSavingsUsd, priceUsage, type RateTable } from "./usagePricing.ts"; -/** - * `en-CA` yields ISO-ordered parts, which is why it is used here rather than - * assembling the day from `Date` getters (those are host-local only). - */ +// en-CA gives ISO-ordered parts in the requested zone; Date getters are host-local. function makeDayFormatter(timeZone: string): (timestampMs: number) => string { let format: Intl.DateTimeFormat; try { @@ -31,10 +28,7 @@ function makeDayFormatter(timeZone: string): (timestampMs: number) => string { day: "2-digit", }); } - // Formatting once per quarter-hour slot keeps `Intl` (about 2µs a call) off - // the per-record path. Named zones put midnight on a quarter hour, so their - // slots never split; a fixed offset such as `+00:01` can, and records in a - // split slot are formatted exactly. + // Cache quarter-hour slots to avoid per-record Intl calls; fixed-offset midnight can split slots and needs exact formatting. const days = new Map(); return (timestampMs) => { const slot = Math.floor(timestampMs / QUARTER_HOUR_MS); @@ -100,11 +94,7 @@ export interface AggregateResult { readonly outOfWindow: number; } -/** - * De-duplication is global across the whole scan, not per file: Claude Code - * copies a message's records forward when a session is resumed or forked, so - * the same `dedupeKey` legitimately appears in several transcripts. - */ +/** Deduplicates across the whole scan; Claude copies records into resumed/forked transcripts. */ export class UsageAggregator { readonly #buckets = new Map(); readonly #seen = new Set(); @@ -209,7 +199,7 @@ export class UsageAggregator { return true; } - /** The target's own rate applies, so a provider-specific `rateModel` is dropped. */ + // Aliases use the target's rate, replacing provider-specific rateModel. #mapModel(record: UsageRecord): UsageRecord { const model = this.#options.modelAliases?.get(record.model); if (model === undefined) return record; @@ -217,11 +207,7 @@ export class UsageAggregator { return { ...rest, model }; } - /** - * Records arrive file by file in time order, so most land in the bucket the - * previous record used. Checking that first skips building and hashing a - * key string per record. - */ + // Time-ordered records usually reuse the previous bucket; avoid rebuilding its key. #bucketFor( day: string, hourIndex: number, diff --git a/apps/server/src/usage/usagePricing.test.ts b/apps/server/src/usage/usagePricing.test.ts index 3b8b62d48a6ee..2ce6d6f74eff7 100644 --- a/apps/server/src/usage/usagePricing.test.ts +++ b/apps/server/src/usage/usagePricing.test.ts @@ -233,6 +233,21 @@ describe("usage pricing", () => { ); }); + it("keeps a bare alias when a reseller entry omits the fast tier", () => { + const table = parseRateTable({ + "provider-a/example-model": { + ...rate(1), + input_cost_per_token_priority: 2, + output_cost_per_token_priority: 10, + }, + "provider-b/example-model": rate(1), + }); + + expect(lookupRate(table, "example-model")).toEqual( + lookupRate(table, "provider-a/example-model"), + ); + }); + it("leaves an ambiguous bare name unpriced", () => { const table = parseRateTable({ "provider-a/example-model": rate(1), diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 50d839f8175c4..fa512218d7c0c 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -14,10 +14,7 @@ export interface TokenRates { readonly cacheCreationCostPerToken: number; } -/** - * LiteLLM also publishes `*_above_272k_tokens`, `*_flex`, and `*_batches` variants. Transcripts - * don't record those, so we don't price them. - */ +/** Omits LiteLLM's above_272k_tokens, flex and batches variants, which transcripts do not record. */ export interface ModelRate extends TokenRates { readonly fast: TokenRates | null; readonly ultrafast: TokenRates | null; @@ -51,10 +48,7 @@ function finiteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } -/** - * Anthropic bills cache reads at a discount and cache writes at a premium. When the standard - * tier omits them, cached input is priced as plain input rather than as free. - */ +// Missing cache rates fall back to input pricing; Anthropic normally discounts reads and charges extra for writes. function readTokenRates( entry: LiteLlmEntry, suffix: string, @@ -95,10 +89,7 @@ function fastMultiplier(entry: LiteLlmEntry): number | null { return fast !== null && fast > 0 ? fast : null; } -/** - * Entries without both an input and an output rate are dropped: a half-priced model would - * silently under-report cost, which is worse than reporting the model as unpriced. - */ +/** Drops models missing input or output rates to avoid understating cost. */ export function parseRateTable(document: unknown): RateTable { const table = new Map(); if (typeof document !== "object" || document === null) return table; @@ -129,8 +120,8 @@ export function parseRateTable(document: unknown): RateTable { const held = aliasCandidates.get(alias); if (held === undefined) { aliasCandidates.set(alias, rate); - } else if (held !== null && !sameRate(held, rate)) { - aliasCandidates.set(alias, null); + } else if (held !== null) { + aliasCandidates.set(alias, mergeAliasRate(held, rate)); } } for (const [alias, rate] of aliasCandidates) { @@ -150,12 +141,18 @@ function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean { ); } -function sameRate(a: ModelRate, b: ModelRate): boolean { - return ( - sameTokenRates(a, b) && - sameTokenRates(a.fast, b.fast) && - sameTokenRates(a.ultrafast, b.ultrafast) - ); +// Resellers often omit speed tiers, so a missing tier fills from the other entry instead of conflicting. +function mergeAliasRate(a: ModelRate, b: ModelRate): ModelRate | null { + const fast = a.fast ?? b.fast; + const ultrafast = a.ultrafast ?? b.ultrafast; + if ( + !sameTokenRates(a, b) || + !sameTokenRates(fast, b.fast ?? fast) || + !sameTokenRates(ultrafast, b.ultrafast ?? ultrafast) + ) { + return null; + } + return { ...a, fast, ultrafast }; } function ratesAt(rate: ModelRate, speed: UsageSpeed): TokenRates { @@ -171,21 +168,13 @@ function bareModelName(key: string): string { return slash === -1 ? key : key.slice(slash + 1); } -/** - * Drops a bracketed variant suffix such as `claude-fable-5-1[1m]`, which - * Claude Code writes for the 1M context tier. The rate table only knows the - * base name, and we price at the base tier anyway. - */ +// Price Claude's bracketed context variants at the base tier, the only name the rate table knows. function stripVariantSuffix(key: string): string { const bracket = key.indexOf("["); return bracket === -1 ? key : key.slice(0, bracket); } -/** - * `` marks locally generated messages that were never billed. Bare family names - * ("opus", "sonnet") are genuinely ambiguous across generations, so we report them as unpriced - * instead of guessing a generation. - */ +// Synthetic messages are unbilled; bare family names are generation-ambiguous and remain unpriced. const UNPRICEABLE_MODELS = new Set([ "", "synthetic", @@ -195,10 +184,7 @@ const UNPRICEABLE_MODELS = new Set([ "fable", ]); -/** - * A scan prices every record twice against a few dozen models, and tables are - * never mutated once built. - */ +// Immutable tables permit caching rates across twice-per-record pricing lookups. const resolvedRates = new WeakMap>(); export function lookupRate(table: RateTable, model: string): ModelRate | null { @@ -247,10 +233,7 @@ function sumCategories(cost: UsageCategoryCost): number { return cost.input + cost.cacheRead + cost.cacheWrite + cost.output; } -/** - * `reasoningTokens` is intentionally not charged separately: it is already - * counted inside `outputTokens`. - */ +/** Reasoning tokens are already included in outputTokens; do not charge twice. */ export function priceUsage( table: RateTable, record: PricedRecord, diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index fac9cc3e0341e..22eec143d8c79 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -2,16 +2,15 @@ import { describe, expect, it } from "@effect/vitest"; import { decodeScanCache, - dedupeWithinFile, encodeScanCache, makeScanCacheWriter, - pruneScanCache, type CachedFile, type ScanCache, } from "./usageScanCache.ts"; import type { UsageRecord } from "@t3tools/provider-core/server/usage"; import { TEST_FORMAT_MAP } from "./usageTestFormats.ts"; +import { initialCodexScanState, parseCodexLine } from "../provider/Drivers/codexUsage.ts"; function record(overrides: Partial = {}): UsageRecord { return { @@ -52,6 +51,7 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]) provider: "claude", records, tailRecords: [], + malformedRecords: 0, position: position(), }); } @@ -59,103 +59,192 @@ function cacheWith(entries: readonly [string, number, readonly UsageRecord[]][]) } describe("scan cache round trip", () => { - it("restores records unchanged", () => { + it("restores cached history unchanged except for Claude local placeholders", () => { const original = cacheWith([ [ "/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })], ], - ["/b.jsonl", 200, [record({ sessionId: "session-b", reportedCostUsd: 1.5 })]], + [ + "/b.jsonl", + 200, + [ + record({ + sessionId: "session-b", + reportedCostUsd: 1.5, + totals: { + uncachedInputTokens: 0, + cachedInputTokens: 0, + cacheCreationTokens: 0, + outputTokens: 0, + reasoningTokens: 0, + }, + }), + ], + ], ]); original.set("/grok.jsonl", { size: 40, + malformedRecords: 2, mtimeMs: 300, provider: "grok", records: [ record({ provider: "grok", model: "grok-4.5-build", dedupeKey: "s:p:grok-4.5-build" }), + record({ provider: "grok", model: "", dedupeKey: "s:p:" }), ], - tailRecords: [record({ provider: "grok", model: "grok-4.5-build", dedupeKey: null })], + tailRecords: [record({ provider: "grok", model: "", dedupeKey: null })], position: position({ resumeOffset: 30, guardLength: 30, guardHash: 123 }), }); + const state = initialCodexScanState(); + for (const line of [ + { type: "session_meta", payload: { id: "session-c", model_provider: "openai" } }, + { type: "turn_context", payload: { model: "gpt-6-astra", turn_id: "native-turn" } }, + { + type: "event_msg", + timestamp: "2026-08-01T10:00:00Z", + payload: { + type: "token_count", + info: { last_token_usage: { input_tokens: 1, output_tokens: 2 } }, + }, + }, + ]) + parseCodexLine(JSON.stringify(line), state); + const pending = { + ...record({ + provider: "codex", + model: "gpt-6-astra", + sessionId: "session-c", + dedupeKey: null, + }), + unresolvedServiceTierTurnId: "native-turn", + }; + const pendingTail = { ...pending, unresolvedServiceTierTurnId: "native-tail" }; original.set("/codex.jsonl", { size: 80, + malformedRecords: 3, mtimeMs: 400, provider: "codex", records: [ - record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null, speed: "ultrafast" }), - ], - tailRecords: [], - position: position({ - state: { + record({ + provider: "codex", model: "gpt-6-astra", + rateModel: "gpt-6", + dedupeKey: null, speed: "ultrafast", - sessionId: "session-c", - lastUsageSignature: '{"input_tokens":1}', - sawSessionMeta: true, - suppressingForkCopies: false, - forkCopyAnchorMs: 0, - }, - }), + }), + pending, + ], + tailRecords: [pendingTail], + position: position({ state }), }); + original.set("/a.jsonl", { + ...original.get("/a.jsonl")!, + tailRecords: [record({ dedupeKey: "msg_tail:" })], + }); + const claude = original.get("/a.jsonl")!; + const cached = new Map(original); + cached.set("/a.jsonl", { + ...claude, + records: [...claude.records, record({ model: "" })], + tailRecords: [ + ...claude.tailRecords, + record({ model: "", dedupeKey: "msg_tail:" }), + ], + }); const restored = decodeScanCache( - JSON.parse(JSON.stringify(encodeScanCache(original))), + JSON.parse(JSON.stringify(encodeScanCache(cached))), TEST_FORMAT_MAP, ); expect(restored.size).toBe(4); - expect(restored.get("/a.jsonl")).toEqual(original.get("/a.jsonl")); - expect(restored.get("/b.jsonl")).toEqual(original.get("/b.jsonl")); - expect(restored.get("/grok.jsonl")).toEqual(original.get("/grok.jsonl")); - expect(restored.get("/codex.jsonl")).toEqual(original.get("/codex.jsonl")); - }); - - it("drops an entry whose persisted parse state is corrupt", () => { - const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]])); - const poisoned = { - ...encoded, - files: { - "/a.jsonl": { ...encoded.files["/a.jsonl"]!, cs: { model: 42 } }, - }, - }; - - expect( - decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"), - ).toBe(false); + expect(restored).toEqual(original); }); - it("drops an entry whose guard length is outside the supported range", () => { - const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]])); - const poisoned = { - ...encoded, - files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, gl: 1e20 } }, - }; - - expect( - decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"), - ).toBe(false); - }); - - it("drops an entry whose speed is not a known index", () => { - const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record({ speed: "fast" })]]])); - const row = encoded.files["/a.jsonl"]!.r[0]!; - const poisoned = { - ...encoded, - files: { "/a.jsonl": { ...encoded.files["/a.jsonl"]!, r: [[...row.slice(0, 10), true]] } }, - }; - - expect( - decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).has("/a.jsonl"), - ).toBe(false); - }); - - it("rejects a document from before records carried a speed", () => { - const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]])); - const previous = { ...encoded, version: 3 }; - - expect(decodeScanCache(JSON.parse(JSON.stringify(previous)), TEST_FORMAT_MAP).size).toBe(0); - }); + it.each([5, 6, 7, 8])( + "retains v%s history and compatible positions but invalidates obsolete state", + (version) => { + const original = cacheWith([["/gone.jsonl", 100, [record({ speed: "fast" })]]]); + original.set("/gone-codex.jsonl", { + ...original.get("/gone.jsonl")!, + provider: "codex", + malformedRecords: 1, + records: [record({ provider: "codex", speed: "fast", dedupeKey: null })], + position: position({ + state: { + ...(version >= 6 ? initialCodexScanState() : {}), + model: "gpt-6-astra", + speed: "fast", + sessionId: "session-a", + lastUsageSignature: null, + sawSessionMeta: true, + suppressingForkCopies: false, + forkCopyAnchorMs: 0, + }, + }), + }); + original.set("/gone-pi.jsonl", { + ...original.get("/gone.jsonl")!, + size: 256, + provider: "pi", + records: [record({ provider: "pi", model: "anthropic/claude-fable-5" })], + malformedRecords: 3, + position: position({ state: { sessionId: "session-a" } }), + }); + const cleanCodex = { + ...original.get("/gone-codex.jsonl")!, + malformedRecords: 0, + }; + original.set("/clean-codex.jsonl", cleanCodex); + const encoded = encodeScanCache(original); + const entry = encoded.files["/gone.jsonl"]!; + const legacy = { + ...encoded, + version, + files: { + ...encoded.files, + "/gone.jsonl": { + s: entry.s, + m: entry.m, + p: entry.p, + r: entry.r, + t: entry.t, + o: entry.o, + gl: entry.gl, + gh: entry.gh, + cs: entry.cs, + }, + }, + }; + + const restored = decodeScanCache(JSON.parse(JSON.stringify(legacy)), TEST_FORMAT_MAP); + expect(restored.get("/gone.jsonl")).toEqual(original.get("/gone.jsonl")); + expect(restored.get("/gone-codex.jsonl")).toEqual({ + ...original.get("/gone-codex.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + expect(restored.get("/clean-codex.jsonl")).toEqual( + version >= 8 + ? cleanCodex + : { + ...cleanCodex, + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }, + ); + expect(restored.get("/gone-pi.jsonl")).toEqual( + version >= 6 + ? original.get("/gone-pi.jsonl") + : { + ...original.get("/gone-pi.jsonl"), + size: -1, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }, + ); + }, + ); it("rewrites only changed entries and still restores the whole cache", () => { const write = makeScanCacheWriter(); @@ -163,12 +252,14 @@ describe("scan cache round trip", () => { ["/a.jsonl", 100, [record()]], ["/b.jsonl", 200, [record({ sessionId: "session-b" })]], ]); + cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 }); const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } }; expect(decodeScanCache(JSON.parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache); cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, size: 30, + malformedRecords: 4, records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })], }); const document = JSON.parse(write(cache, { sources })); @@ -176,15 +267,6 @@ describe("scan cache round trip", () => { expect(document.sources).toEqual(sources); }); - it("interns repeated model and session strings", () => { - const encoded = encodeScanCache( - cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" }), record()]]]), - ); - - expect(encoded.models).toEqual(["claude-fable-5"]); - expect(encoded.sessions).toEqual(["session-a"]); - }); - it("treats a corrupt or foreign document as an empty cache", () => { expect(decodeScanCache(null, TEST_FORMAT_MAP).size).toBe(0); expect(decodeScanCache("nonsense", TEST_FORMAT_MAP).size).toBe(0); @@ -204,13 +286,6 @@ describe("scan cache round trip", () => { expect([...restored.keys()]).toEqual(["/good.jsonl"]); }); - it("rejects the whole cache when an intern table holds a non-string", () => { - const encoded = encodeScanCache(cacheWith([["/a.jsonl", 100, [record()]]])); - const poisoned = { ...encoded, models: [1] }; - - expect(decodeScanCache(JSON.parse(JSON.stringify(poisoned)), TEST_FORMAT_MAP).size).toBe(0); - }); - it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => { const encoded = encodeScanCache( cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]), @@ -230,43 +305,3 @@ describe("scan cache round trip", () => { expect(restored.has("/a.jsonl")).toBe(false); }); }); - -describe("pruneScanCache", () => { - const retentionCutoffMs = 1000; - - it("drops entries older than retention", () => { - const cache = cacheWith([["/old.jsonl", 500, [record()]]]); - - const removed = pruneScanCache(cache, retentionCutoffMs); - - expect(removed).toBe(1); - expect(cache.size).toBe(0); - }); - - it("keeps entries whose file has disappeared", () => { - const cache = cacheWith([["/gone.jsonl", 5000, [record()]]]); - - pruneScanCache(cache, retentionCutoffMs); - - expect(cache.size).toBe(1); - }); -}); - -describe("dedupeWithinFile", () => { - it("keeps the first record per dedupe key", () => { - const kept = dedupeWithinFile([ - record({ totals: { ...record().totals, outputTokens: 1 } }), - record({ totals: { ...record().totals, outputTokens: 999 } }), - record({ dedupeKey: "msg_2:" }), - ]); - - expect(kept).toHaveLength(2); - expect(kept[0]?.totals.outputTokens).toBe(1); - }); - - it("keeps every record that has no dedupe key", () => { - expect( - dedupeWithinFile([record({ dedupeKey: null }), record({ dedupeKey: null })]), - ).toHaveLength(2); - }); -}); diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 2288ffafa74ff..ce8752a867b33 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -6,9 +6,10 @@ import type { } from "@t3tools/provider-core/server/usage"; import * as Schema from "effect/Schema"; +import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 5 as const; +const USAGE_SCAN_CACHE_VERSION = 9 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -16,8 +17,14 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * both. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v5.json"; -export const LEGACY_SCAN_CACHE_FILE_NAME = "usage-scan-cache.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v9.json"; +export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v8.json", + "usage-scan-cache-v7.json", + "usage-scan-cache-v6.json", + "usage-scan-cache-v5.json", + "usage-scan-cache.json", +] as const; const SPEEDS: readonly UsageSpeed[] = ["standard", "fast", "ultrafast"]; @@ -26,12 +33,10 @@ export interface CachedFile { readonly mtimeMs: number; readonly provider: UsageProviderKind; readonly records: readonly UsageRecord[]; - /** - * Records from a trailing segment the writer had not newline-terminated at - * parse time. Kept apart from `records` because an incremental parse - * re-reads that segment and would otherwise double count it. - */ + /** Unterminated tail records stay separate because incremental parsing rereads them. */ readonly tailRecords: readonly UsageRecord[]; + /** Whole-file count, including diagnostics from the tentative tail. */ + readonly malformedRecords: number; readonly position: TranscriptParsePosition; } @@ -50,6 +55,7 @@ type SerializedRecord = readonly [ reportedCostUsd: number | null, speed: number, rateModelIndex?: number | null, + unresolvedServiceTierTurnId?: string, ]; interface SerializedFile { @@ -58,6 +64,7 @@ interface SerializedFile { readonly p: UsageProviderKind; readonly r: readonly SerializedRecord[]; readonly t: readonly SerializedRecord[]; + readonly mr: number; readonly o: number; readonly gl: number; readonly gh: number; @@ -107,6 +114,9 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile record.rateModel === undefined ? null : intern(tables.models, tables.modelIndex, record.rateModel), + ...(record.unresolvedServiceTierTurnId === undefined + ? ([] as const) + : ([record.unresolvedServiceTierTurnId] as const)), ]; return { s: entry.size, @@ -114,6 +124,7 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile p: entry.provider, r: entry.records.map(serializeRecord), t: entry.tailRecords.map(serializeRecord), + mr: entry.malformedRecords, o: entry.position.resumeOffset, gl: entry.position.guardLength, gh: entry.position.guardHash, @@ -133,11 +144,7 @@ export function encodeScanCache(cache: ScanCache): SerializedCache { }; } -/** - * Entries are replaced, never mutated, when their file changes, so an entry's JSON is memoised by - * identity. The intern tables only grow, so a memoised entry's indexes stay valid; a pruned entry - * can leave an unused string behind until the next process start. - */ +/** Memoizes immutable entries by identity; growing intern tables preserve indexes, retaining unused strings until restart. */ export function makeScanCacheWriter(): ( cache: ScanCache, extra: Readonly>, @@ -194,9 +201,7 @@ export function decodeScanCache( const models = root.models as readonly string[]; const sessions = root.sessions as readonly string[]; - // Any corrupt row disqualifies the whole entry. Keeping the survivors - // under the original (size, mtime) would read as a valid warm hit and the - // file would never be re-parsed, silently losing the dropped rows' usage. + // Reject entire corrupt entries; partial survivors would appear warm and hide usage until the file changes. const decodeRecords = ( rows: readonly unknown[], provider: UsageProviderKind, @@ -217,6 +222,7 @@ export function decodeScanCache( reportedCostUsd, speedIndex, rateModelIndex, + unresolvedServiceTierTurnId, ] = row as SerializedRecord; const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined; @@ -226,6 +232,8 @@ export function decodeScanCache( typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || model === undefined || + (unresolvedServiceTierTurnId !== undefined && + typeof unresolvedServiceTierTurnId !== "string") || (rateModelIndex != null && rateModel === undefined) || !Number.isFinite(uncached) || !Number.isFinite(cached) || @@ -237,6 +245,10 @@ export function decodeScanCache( return null; } + // Unchanged and deleted transcripts may only exist in the cache, so the + // parser cannot remove their previously saved local placeholders. + if (provider === "claude" && model === CLAUDE_SYNTHETIC_MODEL) continue; + records.push({ provider, timestampMs, @@ -252,6 +264,9 @@ export function decodeScanCache( }, reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null, speed, + ...(version >= 7 && unresolvedServiceTierTurnId !== undefined + ? { unresolvedServiceTierTurnId } + : {}), dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null, }); } @@ -266,6 +281,8 @@ export function decodeScanCache( const format = formats.get(entry.p); if (format === undefined) continue; if (!isRecordArray(entry.r) || !isRecordArray(entry.t)) continue; + const malformedRecords = entry.mr === undefined ? 0 : entry.mr; + if (!Number.isSafeInteger(malformedRecords) || malformedRecords < 0) continue; // Position fields feed byte offsets and a Buffer allocation in the reader, // so anything outside their real ranges must reject the entry: a bogus // guard length would otherwise fail every parse of the file, silently @@ -284,11 +301,12 @@ export function decodeScanCache( ) { continue; } - // v4 records of stateful formats (Codex) predate service tiers, so they - // all priced as standard. Keep them, because the rollout may be gone, but - // make a live rollout re-parse whole: no file has size -1, and a zero - // position cannot resume. - const legacy = format.state !== undefined && version < USAGE_SCAN_CACHE_VERSION; + // Keep history for deleted rollouts, but re-parse incompatible reducer state. + // v9 repairs skipped initial Codex requests; clean v8 entries can still resume. + const legacy = + format.state !== undefined && + (version < 6 || + (entry.p === "codex" && (version < 8 || (version < 9 && malformedRecords > 0)))); // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; @@ -304,6 +322,7 @@ export function decodeScanCache( provider, records, tailRecords, + malformedRecords, position: legacy ? { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null } : { @@ -343,10 +362,7 @@ export function pruneScanCache(cache: ScanCache, retentionCutoffMs: number): num return removed; } -/** - * Callers stitching an incremental parse together pass one `seen` set across the line and tail - * record batches so the whole file stays deduplicated as a unit; the set is mutated in place. - */ +/** Mutates seen; share it across incremental line/tail batches to deduplicate the whole file. */ export function dedupeWithinFile( records: readonly UsageRecord[], seen: Set = new Set(), diff --git a/apps/server/src/usage/usageTestFormats.ts b/apps/server/src/usage/usageTestFormats.ts index 8c5bca3bb0d48..ecc4ede6efd3c 100644 --- a/apps/server/src/usage/usageTestFormats.ts +++ b/apps/server/src/usage/usageTestFormats.ts @@ -2,18 +2,20 @@ import type { UsageProviderKind } from "@t3tools/contracts"; import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage"; import { piUsageFormat } from "@t3tools/provider-pi/server/usage"; import { grokUsageFormat } from "@t3tools/provider-grok/server/usage"; +import { museUsageFormat } from "@t3tools/provider-muse/server/usage"; import { claudeUsageFormat } from "../provider/Drivers/claudeUsage.ts"; import { codexUsageFormat } from "../provider/Drivers/codexUsage.ts"; export const TEST_FORMATS: Record< - "claude" | "codex" | "grok" | "pi", + "claude" | "codex" | "grok" | "pi" | "muse", TranscriptUsageFormat > = { claude: claudeUsageFormat, codex: codexUsageFormat, grok: grokUsageFormat, pi: piUsageFormat, + muse: museUsageFormat, }; export const TEST_FORMAT_MAP = new Map>( diff --git a/apps/server/src/usage/usageTranscriptReader.test.ts b/apps/server/src/usage/usageTranscriptReader.test.ts index 3cd49d1cd1c98..e7fa7067916c9 100644 --- a/apps/server/src/usage/usageTranscriptReader.test.ts +++ b/apps/server/src/usage/usageTranscriptReader.test.ts @@ -6,6 +6,8 @@ import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import { afterEach, assert, beforeEach, describe, it } from "@effect/vitest"; +import type { TranscriptUsageFormat } from "@t3tools/provider-core/server/usage"; +import * as Schema from "effect/Schema"; import { TEST_FORMATS } from "./usageTestFormats.ts"; import { readTranscriptRecords, transcriptLineGate } from "./usageTranscriptReader.ts"; @@ -70,6 +72,71 @@ function codexUsageLine(outputTokens: number, secondsOffset: number): string { } describe("readTranscriptRecords resume", () => { + it.each([ + { mode: "buffered", streamingThresholdBytes: Infinity }, + { mode: "streaming", streamingThresholdBytes: 0 }, + ])("counts malformed tails once across $mode reads and resume", async (options) => { + const format: TranscriptUsageFormat<{ errors: number }> = { + ...TEST_FORMATS.claude, + selectFields: { ...TEST_FORMATS.claude.selectFields, usage: true }, + state: { + initial: () => ({ errors: 0 }), + schema: Schema.Struct({ errors: Schema.Number }), + }, + parseLine(line, state) { + return this.parseProjected(JSON.parse(line), state); + }, + parseProjected(value, state) { + if ( + typeof value === "object" && + value !== null && + "usage" in value && + value.usage === "malformed" + ) { + state.errors += 1; + return []; + } + return TEST_FORMATS.claude.parseProjected(value, undefined); + }, + readMalformedRecords: (state: { errors: number }) => state.errors, + }; + const path = NodePath.join(dir, "diagnostics.jsonl"); + const malformed = JSON.stringify({ usage: "malformed" }); + // Completed lines enter the projected parser only when they cross a stream chunk. + const committed = `${JSON.stringify({ usage: "malformed", padding: "x".repeat(256 * 1024) })}\n${claudeLine(1, 5)}`; + await NodeFSP.writeFile(path, committed + malformed); + + const first = await readTranscriptRecords(path, format, undefined, options); + assert.isNotNull(first); + assert.deepStrictEqual( + first.records.map((record) => record.totals.outputTokens), + [5], + ); + assert.deepStrictEqual(first.tailRecords, []); + assert.strictEqual(first.position.resumeOffset, Buffer.byteLength(committed)); + assert.deepStrictEqual(first.position.state, { errors: 1 }); + assert.strictEqual(first.malformedRecords, 2); + + const savedPosition = JSON.parse(JSON.stringify(first.position)); + await NodeFSP.appendFile(path, `\n${claudeLine(2, 7)}${malformed}\n`); + const resumed = await readTranscriptRecords(path, format, savedPosition, options); + assert.isNotNull(resumed); + assert.isTrue(resumed.resumed); + assert.deepStrictEqual( + resumed.records.map((record) => record.totals.outputTokens), + [7], + ); + assert.deepStrictEqual(resumed.position.state, { errors: 3 }); + assert.strictEqual(resumed.malformedRecords, 3); + + const full = await readTranscriptRecords(path, format, undefined, options); + assert.isNotNull(full); + assert.deepStrictEqual([...first.records, ...resumed.records], full.records); + assert.deepStrictEqual(resumed.tailRecords, full.tailRecords); + assert.deepStrictEqual(resumed.position, full.position); + assert.strictEqual(resumed.malformedRecords, full.malformedRecords); + }); + it("parses only appended lines when resuming a grown file", async () => { const path = NodePath.join(dir, "claude.jsonl"); await NodeFSP.writeFile(path, claudeLine(1, 5) + claudeLine(2, 7)); @@ -77,6 +144,7 @@ describe("readTranscriptRecords resume", () => { assert.isNotNull(first); assert.strictEqual(first.records.length, 2); assert.isFalse(first.resumed); + assert.strictEqual(first.malformedRecords, 0); await NodeFSP.appendFile(path, claudeLine(3, 11)); const second = await readTranscriptRecords(path, TEST_FORMATS.claude, first.position); @@ -120,8 +188,7 @@ describe("readTranscriptRecords resume", () => { assert.isNotNull(first); assert.strictEqual(first.records.length, 1); - // Codex re-emits an unchanged token_count on stream boundaries; the copy - // lands after the resume point and must still be dropped. + // Codex duplicates token_count at stream boundaries, including after resume points. await NodeFSP.appendFile(path, codexUsageLine(9, 5) + codexUsageLine(21, 8)); const second = await readTranscriptRecords(path, TEST_FORMATS.codex, first.position); assert.isNotNull(second); @@ -153,6 +220,65 @@ describe("readTranscriptRecords resume", () => { assert.strictEqual(second.tailRecords.length, 0); }); + it.each([ + { mode: "buffered", streamingThresholdBytes: Infinity }, + { mode: "streaming", streamingThresholdBytes: 0 }, + ])( + "resumes an initial Codex carried-total tail without rebilling it ($mode)", + async (options) => { + const path = NodePath.join(dir, "continuation.jsonl"); + const usage = (input: number, output: number) => ({ + input_tokens: input, + output_tokens: output, + }); + const event = (last: unknown, cumulative: unknown) => + JSON.stringify({ + type: "event_msg", + timestamp: "2026-08-01T10:00:05Z", + payload: { + type: "token_count", + info: { last_token_usage: last, total_token_usage: cumulative }, + }, + }); + const firstLine = event(usage(100, 20), usage(500, 60)); + await NodeFSP.writeFile( + path, + codexMetaLine() + codexModelLine("gpt-6-astra") + codexTierLine("ultrafast") + firstLine, + ); + const first = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options); + assert.isNotNull(first); + assert.strictEqual(first.records.length, 0); + assert.deepStrictEqual( + first.tailRecords.map((r) => [r.totals.outputTokens, r.speed]), + [[20, "ultrafast"]], + ); + assert.strictEqual(first.malformedRecords, 0); + + await NodeFSP.appendFile(path, `\n${firstLine}\n${event(usage(10, 2), usage(510, 62))}\n`); + const resumed = await readTranscriptRecords( + path, + TEST_FORMATS.codex, + JSON.parse(JSON.stringify(first.position)), + options, + ); + const full = await readTranscriptRecords(path, TEST_FORMATS.codex, undefined, options); + assert.isNotNull(resumed); + assert.isNotNull(full); + assert.isTrue(resumed.resumed); + assert.deepStrictEqual(resumed.records, full.records); + assert.deepStrictEqual( + resumed.records.map((r) => [r.totals.outputTokens, r.speed]), + [ + [20, "ultrafast"], + [2, "ultrafast"], + ], + ); + assert.deepStrictEqual(resumed.tailRecords, []); + assert.strictEqual(resumed.malformedRecords, 0); + assert.deepStrictEqual(resumed.position, full.position); + }, + ); + it("re-parses from the start when the guard bytes no longer match", async () => { const path = NodePath.join(dir, "claude.jsonl"); await NodeFSP.writeFile(path, claudeLine(1, 5)); @@ -229,12 +355,6 @@ describe("readTranscriptRecords resume", () => { assert.strictEqual(result.records[0]?.sessionId, "codex-session-1"); assert.strictEqual(result.position.resumeOffset, Buffer.byteLength(content)); }); - - it("returns null for an unreadable file", async () => { - assert.isNull( - await readTranscriptRecords(NodePath.join(dir, "missing.jsonl"), TEST_FORMATS.claude), - ); - }); }); describe("transcriptLineGate", () => { @@ -244,17 +364,6 @@ describe("transcriptLineGate", () => { }; const markers = { one: ['"usage"'], several: ['"token_count"', '"session_meta"', '"a.b(c)"'] }; - it("passes only lines containing one of its markers", () => { - for (const kind of ["one", "several"] as const) { - for (const marker of markers[kind]) { - assert.isTrue(gates[kind](Buffer.from(`{"payload":{${marker}:1}}`))); - assert.isFalse(gates[kind](Buffer.from(`{"text":"see ${marker.slice(1, -1)} here"}`))); - assert.isFalse(gates[kind](Buffer.from(`{${marker.replace(/[._]|usage/, "x")}:1}`))); - } - assert.isFalse(gates[kind](Buffer.alloc(0))); - } - }); - it("matches markers beside multi-byte and malformed UTF-8", () => { const invalid = Buffer.from([0xff, 0xc3]); for (const kind of ["one", "several"] as const) { diff --git a/apps/server/src/usage/usageTranscriptReader.ts b/apps/server/src/usage/usageTranscriptReader.ts index d3f19afd20a94..4f131f310f418 100644 --- a/apps/server/src/usage/usageTranscriptReader.ts +++ b/apps/server/src/usage/usageTranscriptReader.ts @@ -1,9 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -/** - * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB - * across ~1,500 files, and buffer-level streaming is roughly an order of - * magnitude cheaper than materialising each file. - */ +// Cold windows span ~1.4 GB/1,500 files; node:fs buffer streaming is ~10x cheaper than materializing files. import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import * as NodeStringDecoder from "node:string_decoder"; @@ -24,12 +20,7 @@ export interface TranscriptFile { readonly mtimeMs: number; } -/** - * The guard hash fingerprints the bytes immediately before `resumeOffset`. A - * resume only proceeds when those bytes still match: transcripts are - * append-only by design, but a rotated or rewritten file silently mis-parsed - * from the middle would corrupt usage totals. - */ +/** Resume only if bytes before resumeOffset match the guard hash; rewritten files would corrupt totals. */ export interface TranscriptParsePosition { readonly resumeOffset: number; readonly guardLength: number; @@ -39,12 +30,10 @@ export interface TranscriptParsePosition { export interface TranscriptParseResult { readonly records: readonly UsageRecord[]; - /** - * Records from a trailing segment the writer has not newline-terminated yet. - * Kept out of `records` because `position` deliberately excludes that - * segment: the next scan re-reads it once the writer finishes the line. - */ + /** Unterminated tail records stay outside records/position so the next scan rereads them. */ readonly tailRecords: readonly UsageRecord[]; + /** Includes tentative tail diagnostics; position.state only includes committed lines. */ + readonly malformedRecords: number; readonly position: TranscriptParsePosition; readonly resumed: boolean; } @@ -76,12 +65,7 @@ function fnv1a(buffer: Buffer): number { return hash >>> 0; } -/** - * Grok sessions also ship multi-megabyte `chat_history` and `events` logs that - * never carry usage, so the basename filter keeps a cold scan off those files. - * Results keep `readdir` order, which the aggregator's first-seen dedupe relies - * on. - */ +/** Skips Grok logs without usage; preserves readdir order for first-seen deduplication. */ export async function listTranscriptFiles( root: string, sinceMs: number, @@ -158,12 +142,7 @@ async function guardMatches( } } -/** - * Several would be one pass over the line each, so they are matched together as - * one alternation over the line's latin1 view instead: latin1 maps every byte - * to one character without validating it, so an ASCII marker matches exactly - * where its bytes do. - */ +// 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) { const marker = Buffer.from(markers[0]); @@ -175,15 +154,7 @@ export function transcriptLineGate(markers: readonly [string, ...string[]]) { return (line: Buffer) => pattern.test(line.toString("latin1")); } -/** - * Streams one transcript and returns the usage records it contains, or `null` - * when the file could not be read. - * - * The distinction matters to the caller's cache: a genuinely empty transcript - * is a stable fact worth memoising, while a transient read failure memoised - * under the same `(size, mtime)` key would silently drop that file's usage - * until the file next changes. - */ +/** Returns null on read failure; caching it as empty would hide usage until size/mtime changes. */ export async function readTranscriptRecords( filePath: string, format: TranscriptUsageFormat, @@ -250,8 +221,7 @@ export async function readTranscriptRecords( return; } if (!streaming) { - // Usage has no import-history budget: retain all selected usage fields, - // regardless of the size of the surrounding unselected tool content. + // Usage has no import-history budget; retain selected fields regardless of surrounding tool payload size. streaming = createTranscriptJsonReader(() => {}, selectPath, { maxDepth: Infinity }); decoder = new NodeStringDecoder.StringDecoder("utf8"); for (const pending of pendingChunks) streaming.write(decoder.write(pending)); @@ -302,14 +272,12 @@ export async function readTranscriptRecords( scanOffset += chunk.length; } - // The unfinished tail parses against a copy, so the saved state stays at - // `resumeOffset` and the next scan replays the tail from it. + // Parse unfinished tails against copied state so the next scan can replay from resumeOffset. const encodedState = encodeState === undefined ? null : encodeState(state); const tailRecords: UsageRecord[] = []; - finish( - decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)), - tailRecords, - ); + const tailState = + decodeState === undefined ? state : Option.getOrThrow(decodeState(encodedState)); + finish(tailState, tailRecords); const guardLength = Math.min(GUARD_LENGTH, resumeOffset); let guardHash = 0; @@ -322,6 +290,7 @@ export async function readTranscriptRecords( return { records, tailRecords, + malformedRecords: format.readMalformedRecords?.(tailState) ?? 0, position: { resumeOffset, guardLength, diff --git a/apps/server/src/usage/usageTranscriptStreaming.test.ts b/apps/server/src/usage/usageTranscriptStreaming.test.ts index e088c8bb20922..856ba2ac5b9d7 100644 --- a/apps/server/src/usage/usageTranscriptStreaming.test.ts +++ b/apps/server/src/usage/usageTranscriptStreaming.test.ts @@ -50,8 +50,8 @@ const claude = (id = "m1", output = 99) => ({ }, }); const codex = [ - { type: "session_meta", timestamp, payload: { id: "s1" } }, - { type: "turn_context", timestamp, payload: { model: "gpt-5.6-sol" } }, + { type: "session_meta", timestamp, payload: { id: "s1", model_provider: "openai" } }, + { type: "turn_context", timestamp, payload: { model: "gpt-5.6-sol", turn_id: "initial-turn" } }, { type: "event_msg", timestamp, @@ -108,6 +108,53 @@ async function scan( } describe("large usage records", () => { + it("streams Muse completion envelopes and resumes a partial appended event", async () => { + const entry = { + schema_version: 1, + record_type: "event", + payload_type: "runtime.session", + payload_schema_version: 3, + id: "envelope-1", + recorded_at: 1_785_578_400_123_456, + stream: { kind: "session", id: "parent" }, + payload: { + source_run_record_id: "inference-1", + event: { + kind: "automated_review_completed", + model: { model_id: "review-model" }, + usage: { + input_tokens: 100, + cached_input_tokens: 60, + output_tokens: 20, + reasoning_tokens: 8, + }, + }, + }, + }; + const small = await scan([entry], "muse", "small-muse"); + expect(small.records[0]?.totals).toMatchObject({ + uncachedInputTokens: 40, + cachedInputTokens: 60, + }); + const path = NodePath.join(dir, "large-muse.jsonl"); + await NodeFSP.writeFile(path, JSON.stringify({ ...entry, discarded: { content } }) + "\n"); + const large = await readTranscriptRecords(path, "muse"); + expect(large?.records).toEqual(small.records); + const appended = JSON.stringify({ + ...entry, + id: "envelope-2", + payload: { ...entry.payload, source_run_record_id: "inference-2" }, + }); + await NodeFSP.appendFile(path, appended.slice(0, -7)); + const partial = await readTranscriptRecords(path, "muse", large!.position); + expect(partial?.records).toEqual([]); + await NodeFSP.appendFile(path, appended.slice(-7) + "\n"); + const completed = await readTranscriptRecords(path, "muse", partial!.position); + expect(completed?.records).toHaveLength(1); + expect(completed?.records[0]?.dedupeKey).not.toBe(large?.records[0]?.dedupeKey); + expect(completed?.records[0]?.totals).toEqual(small.records[0]?.totals); + }); + it("keeps Pi model, cost, and fork identity after large assistant content", async () => { const entry = { type: "message", @@ -252,9 +299,14 @@ describe("large usage records", () => { it("preserves Codex model switches and duplicate suppression across streaming resumes", async () => { const path = NodePath.join(dir, "history.jsonl"); const first = await scan( - codex.map((record) => ({ padding: content, ...record })), + codex.map((record) => ({ padding: "x".repeat(9 * 1024 * 1024), ...record })), "codex", ); + expect(first.records[0]).toMatchObject({ + sessionId: "s1", + model: "gpt-5.6-sol", + unresolvedServiceTierTurnId: "initial-turn", + }); await NodeFSP.appendFile( path, [ @@ -281,6 +333,7 @@ describe("large usage records", () => { sessionId: "s1", totals: { outputTokens: 101 }, }); + expect(result?.records[0]).not.toHaveProperty("unresolvedServiceTierTurnId"); const full = await readTranscriptRecords(path, "codex"); expect([...first.records, ...result!.records]).toEqual(full?.records); }); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 3a7a16f95d4cc..0e3d2b5063ed2 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -9,13 +9,18 @@ import * as Fiber from "effect/Fiber"; import * as TestClock from "effect/testing/TestClock"; 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 { ChildProcessSpawner } from "effect/process"; +import * as Metric from "effect/Metric"; import { assert, it } from "@effect/vitest"; import { CheckpointRef, GitCommandError, VcsProcessExitError } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as ServerConfig from "../config.ts"; +import { gitCommandDuration, gitCommandsTotal } from "../observability/Metrics.ts"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; @@ -96,6 +101,37 @@ runVcsDriverContractSuite({ }, }); +it.effect("lists the fetch and push URLs of a partial clone remote", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-partial-clone-remotes-", + }); + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + yield* runGit(cwd, ["init"]); + yield* runGit(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]); + yield* runGit(cwd, [ + "remote", + "set-url", + "--push", + "origin", + "git@github.com:octocat/t3code.git", + ]); + yield* runGit(cwd, ["config", "remote.origin.promisor", "true"]); + yield* runGit(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]); + + const result = yield* driver.listRemotes(cwd); + assert.deepEqual(result.remotes, [ + { + name: "origin", + url: "https://github.com/pingdotgg/t3code.git", + pushUrl: Option.some("git@github.com:octocat/t3code.git"), + isPrimary: true, + }, + ]); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + const makeCheckpointFixture = Effect.fn("makeCheckpointFixture")(function* ( driver: Effect.Success>, cwd: string, @@ -163,6 +199,74 @@ it.effect("checkpoint capture skips untracked nested repositories without a comm }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.skipIf(!symlinksSupported)( + "checkpoint capture writes its index into the real git dir when cwd is a symlinked subdirectory", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveRunner = yield* ProcessRunner.ProcessRunner; + const indexFiles: string[] = []; + const captureProcess = yield* VcsProcess.make.pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: (input) => { + const indexFile = input.env?.GIT_INDEX_FILE; + if (indexFile !== undefined) indexFiles.push(indexFile); + return liveRunner.run(input); + }, + }), + ); + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, captureProcess), + ); + const sandbox = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-checkpoint-symlink-", + }); + const repo = path.join(sandbox, "repo"); + const subdir = path.join(repo, "sub", "dir"); + const link = path.join(sandbox, "nest", "link"); + yield* fileSystem.makeDirectory(subdir, { recursive: true }); + yield* fileSystem.makeDirectory(path.dirname(link), { recursive: true }); + yield* fileSystem.symlink(subdir, link); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, repo); + // Git returns ../../.git from the target; resolving it against the link reaches the decoy. + yield* git(["-C", sandbox, "init"]); + yield* fileSystem.writeFileString(path.join(subdir, "nested.txt"), "from-link\n"); + const realCommonDir = yield* fileSystem.realPath(path.join(repo, ".git")); + + yield* driver.checkpoints.captureCheckpoint({ cwd: link, checkpointRef }); + + assert.isTrue(indexFiles.length > 0); + for (const indexFile of indexFiles) { + assert.strictEqual(yield* fileSystem.realPath(path.dirname(indexFile)), realCommonDir); + } + assert.strictEqual( + (yield* git(["show", `${checkpointRef}:sub/dir/nested.txt`])).stdout, + "from-link\n", + ); + }).pipe(Effect.scoped, Effect.provide(layerGitCaptureContract)), +); + +it.effect("checkpoint capture keeps the shared index a split index still uses", () => + 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-checkpoint-split-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + yield* git(["config", "core.splitIndex", "true"]); + yield* git(["config", "splitIndex.sharedIndexExpire", "now"]); + yield* git(["update-index", "--split-index"]); + yield* fileSystem.writeFileString(path.join(cwd, "untracked.txt"), "new\n"); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + assert.strictEqual((yield* git(["show", `${checkpointRef}:untracked.txt`])).stdout, "new\n"); + assert.strictEqual((yield* git(["ls-files", "--cached"])).stdout, "file.txt\n"); + assert.strictEqual((yield* git(["diff", "--cached", "--name-only"])).stdout, "file.txt\n"); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint recovery discovers nested HEAD independently of inherited GIT_DIR", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -210,6 +314,9 @@ it.effect("checkpoint capture still fails when a clean filter rejects a file", ( ); assert.strictEqual(result._tag, "Failure"); + if (result._tag === "Failure") { + assert.strictEqual(result.failure._tag, "VcsProcessExitError"); + } assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex); assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef })); }).pipe(Effect.scoped, Effect.provide(layerGitContract)), @@ -245,47 +352,98 @@ it.effect("checkpoint capture refuses a truncated nested repository listing", () }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect("checkpoint recovery refuses excessive candidates before probing", () => +it.effect("checkpoint capture skips an ignored project while keeping its allowed sibling", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const liveProcess = yield* VcsProcess.VcsProcess; const driver = yield* GitVcsDriver.makeVcsDriverShape(); - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-cap-" }); - const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); - yield* git(["init", "empty0"]); - for (let i = 1; i < 65; i++) - yield* fs.copy(path.join(cwd, "empty0"), path.join(cwd, `empty${i}`)); - const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index")); - let stageError: VcsProcessExitError | undefined; - let nestedProbes = 0; - let stageAttempts = 0; - const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( - Effect.provideService(VcsProcess.VcsProcess, { - run: (input) => { - if (input.cwd !== cwd && input.args.includes("rev-parse")) nestedProbes++; - if (input.args.includes("add") && input.args.includes("-A")) stageAttempts++; - return liveProcess.run(input).pipe( - Effect.tapError((error) => { - if (error._tag === "VcsProcessExitError") stageError = error; - return Effect.void; - }), - ); - }, - }), + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ignored-" }); + const { git } = yield* makeCheckpointFixture(driver, parent); + yield* fs.writeFileString( + path.join(parent, ".gitignore"), + "*\n!.gitignore\n!file.txt\n!keep/\n!keep/**\n", ); - const result = yield* Effect.result( - captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }), + const ignoredCwd = path.join(parent, "ignored"); + const keepCwd = path.join(parent, "keep"); + yield* fs.makeDirectory(ignoredCwd); + yield* fs.makeDirectory(keepCwd); + yield* fs.writeFileString(path.join(ignoredCwd, "secret.txt"), "private\n"); + yield* fs.writeFileString(path.join(keepCwd, "new.txt"), "new\n"); + const originalIndex = yield* fs.readFile(path.join(parent, ".git", "index")); + const ignoredRef = CheckpointRef.make("refs/t3/checkpoints/ignored"); + const keepRef = CheckpointRef.make("refs/t3/checkpoints/keep"); + + const ignored = yield* Effect.result( + driver.checkpoints.captureCheckpoint({ cwd: ignoredCwd, checkpointRef: ignoredRef }), ); - assert.strictEqual(nestedProbes, 0); - assert.strictEqual(stageAttempts, 1); - assert.strictEqual(result._tag, "Failure"); - if (result._tag === "Failure") assert.strictEqual(result.failure, stageError); - assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef })); - assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex); + yield* driver.checkpoints.captureCheckpoint({ cwd: keepCwd, checkpointRef: keepRef }); + + assert.strictEqual((yield* git(["show", `${keepRef}:keep/new.txt`])).stdout, "new\n"); + assert.strictEqual((yield* git(["ls-tree", "-r", keepRef, "--", "ignored"])).stdout, ""); + assert.isFalse( + yield* driver.checkpoints.hasCheckpointRef({ cwd: parent, checkpointRef: ignoredRef }), + ); + assert.deepEqual(yield* fs.readFile(path.join(parent, ".git", "index")), originalIndex); + assert.strictEqual(ignored._tag, "Failure"); + if (ignored._tag === "Failure") { + assert.strictEqual(ignored.failure._tag, "VcsUnsupportedOperationError"); + } }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect.each([ + { tracking: "committed-only", committed: ["committed.txt"], staged: [] }, + { tracking: "staged-only", committed: [], staged: ["staged.txt"] }, + { tracking: "mixed", committed: ["committed.txt"], staged: ["staged.txt"] }, +])( + "checkpoint capture keeps $tracking tracked edits but excludes new files in a project ignored later", + ({ committed, staged }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-ignored-later-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, parent); + const cwd = path.join(parent, "sub"); + yield* fs.makeDirectory(cwd); + for (const file of committed) { + yield* fs.writeFileString(path.join(cwd, file), "committed\n"); + yield* git(["add", `sub/${file}`]); + } + if (committed.length > 0) { + yield* git(["commit", "-m", "track project"]); + } + for (const file of staged) { + yield* fs.writeFileString(path.join(cwd, file), "staged\n"); + yield* git(["add", `sub/${file}`]); + } + const tracked = [...committed, ...staged]; + yield* fs.writeFileString(path.join(parent, ".gitignore"), "sub/\n"); + for (const file of tracked) { + yield* fs.writeFileString(path.join(cwd, file), `${file} working\n`); + } + yield* fs.writeFileString(path.join(cwd, "secret.txt"), "private\n"); + const originalIndex = yield* fs.readFile(path.join(parent, ".git", "index")); + + const captured = yield* Effect.result( + driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }), + ); + + assert.deepEqual(yield* fs.readFile(path.join(parent, ".git", "index")), originalIndex); + if (captured._tag === "Failure") return yield* captured.failure; + assert.strictEqual( + (yield* git(["ls-tree", "-r", "--name-only", checkpointRef, "--", "sub"])).stdout, + tracked.map((file) => `sub/${file}\n`).join(""), + ); + for (const file of tracked) { + assert.strictEqual( + (yield* git(["show", `${checkpointRef}:sub/${file}`])).stdout, + `${file} working\n`, + ); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect.each([ { phase: "add", nestedRecovery: false, expireRecovery: false }, { phase: "update-ref", nestedRecovery: false, expireRecovery: false }, @@ -392,95 +550,6 @@ it.effect.each([ }).pipe(Effect.scoped, Effect.provide(layerGitCaptureContract)), ); -it.effect.each(["discovery", "probe", "retry"] as const)( - "checkpoint recovery has one deadline including %s", - (blockedPhase) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const liveProcess = yield* VcsProcess.VcsProcess; - const driver = yield* GitVcsDriver.makeVcsDriverShape(); - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-recovery-timeout-" }); - const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); - yield* git(["init", "empty"]); - const originalIndex = yield* fs.readFile(path.join(cwd, ".git", "index")); - const entered = yield* Deferred.make(); - const discovered = yield* Deferred.make(); - let stageError: VcsProcessExitError | undefined; - let privateIndex: string | undefined; - let interrupted = false; - let stagingAttempts = 0; - const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( - Effect.provideService(VcsProcess.VcsProcess, { - run: (input) => { - const staging = input.args.includes("add") && input.args.includes("-A"); - if (staging) { - privateIndex = input.env?.GIT_INDEX_FILE; - stagingAttempts += 1; - } - const block = - (blockedPhase === "discovery" && input.args.includes("--others")) || - (blockedPhase === "probe" && input.cwd !== cwd && input.args.includes("rev-parse")) || - (blockedPhase === "retry" && - staging && - input.args.some((arg) => arg.startsWith(":(exclude,literal)"))); - if (block) - return ( - blockedPhase === "retry" - ? fs - .writeFileString( - `${input.env!.GIT_INDEX_FILE!}.lock`, - "interrupted index write", - ) - .pipe(Effect.orDie) - : Effect.void - ).pipe( - Effect.andThen(Deferred.succeed(entered, undefined)), - Effect.andThen(Effect.never), - Effect.onInterrupt(() => - Effect.sync(() => { - interrupted = true; - }), - ), - ); - return liveProcess.run(input).pipe( - Effect.tap(() => - blockedPhase === "probe" && input.args.includes("--others") - ? Deferred.succeed(discovered, undefined).pipe( - Effect.andThen(Effect.sleep("3 seconds")), - ) - : Effect.void, - ), - Effect.tapError((error) => { - if (staging && error._tag === "VcsProcessExitError") stageError = error; - return Effect.void; - }), - ); - }, - }), - ); - const captureStore = yield* makeCaptureStore(captureDriver, cwd); - const fiber = yield* captureStore - .captureCheckpoint({ cwd, checkpointRef }) - .pipe(Effect.flip, Effect.forkScoped); - if (blockedPhase === "probe") { - yield* Deferred.await(discovered); - yield* TestClock.adjust("3 seconds"); - } - yield* Deferred.await(entered); - yield* TestClock.adjust(blockedPhase === "probe" ? "2 seconds" : "5 seconds"); - const error = yield* Fiber.join(fiber); - assert.strictEqual(error, stageError); - assert.strictEqual(stagingAttempts, blockedPhase === "retry" ? 2 : 1); - assert.isTrue(interrupted); - assert.isDefined(privateIndex); - assert.isFalse(yield* fs.exists(privateIndex!)); - assert.isFalse(yield* fs.exists(`${privateIndex!}.lock`)); - assert.isFalse(yield* driver.checkpoints.hasCheckpointRef({ cwd, checkpointRef })); - assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git", "index")), originalIndex); - }).pipe(Effect.scoped, Effect.provide(layerGitContract)), -); - it.effect("checkpoint recovery preserves interruption and removes the private index", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -515,39 +584,6 @@ it.effect("checkpoint recovery preserves interruption and removes the private in }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect("checkpoint capture does not rerun clean filters for unchanged indexed files", () => - 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-checkpoint-cache-" }); - const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); - yield* fileSystem.writeFileString( - path.join(cwd, ".gitattributes"), - "stable.txt filter=probe\n", - ); - yield* fileSystem.writeFileString(path.join(cwd, "stable.txt"), "unchanged\n"); - yield* fileSystem.writeFileString( - path.join(cwd, ".git", "filter.cjs"), - 'require("node:fs").appendFileSync(".git/filter-runs", "read\\n"); process.stdin.pipe(process.stdout);', - ); - yield* git(["config", "filter.probe.clean", "node .git/filter.cjs"]); - yield* fileSystem.utimes(path.join(cwd, "stable.txt"), 1_700_000_000, 1_700_000_000); - yield* git(["add", "."]); - yield* git(["commit", "-m", "record stable file"]); - yield* fileSystem.writeFileString(path.join(cwd, ".git", "filter-runs"), ""); - yield* fileSystem.writeFileString(path.join(cwd, "file.txt"), "changed\n"); - const originalIndex = yield* fileSystem.readFile(path.join(cwd, ".git", "index")); - - yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); - - assert.strictEqual(yield* fileSystem.readFileString(path.join(cwd, ".git", "filter-runs")), ""); - assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "changed\n"); - assert.strictEqual((yield* git(["show", `${checkpointRef}:stable.txt`])).stdout, "unchanged\n"); - assert.deepEqual(yield* fileSystem.readFile(path.join(cwd, ".git", "index")), originalIndex); - }).pipe(Effect.scoped, Effect.provide(layerGitContract)), -); - it.effect.each( [false, true].flatMap((nested) => (["sparse", "flags", "manual-skip", "missing", "non-cone-missing"] as const).map( @@ -646,46 +682,6 @@ it.effect.each( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect("checkpoint capture keeps the legacy path when Git lacks add --sparse", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const liveProcess = yield* VcsProcess.VcsProcess; - const driver = yield* GitVcsDriver.makeVcsDriverShape(); - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-legacy-" }); - const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); - yield* git(["sparse-checkout", "set", "--cone", "included"]); - const originalIndex = yield* fs.readFile(path.join(cwd, ".git/index")); - const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( - Effect.provideService(VcsProcess.VcsProcess, { - run: (input) => { - if (input.args.includes("-h")) - return Effect.succeed({ - exitCode: ChildProcessSpawner.ExitCode(129), - stdout: "usage: git add", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }); - return liveProcess.run( - input.args.includes("--sparse") - ? { - ...input, - args: input.args.map((arg) => - arg === "--sparse" ? "--unsupported-sparse" : arg, - ), - } - : input, - ); - }, - }), - ); - yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); - assert.strictEqual((yield* git(["show", `${checkpointRef}:file.txt`])).stdout, "unstaged\n"); - assert.deepEqual(yield* fs.readFile(path.join(cwd, ".git/index")), originalIndex); - }).pipe(Effect.scoped, Effect.provide(layerGitContract)), -); - it.effect.each(["normal", "flags", "sparse"] as const)( "checkpoint index inspection handles entries beyond the output cap (index=%s)", (indexMode) => @@ -769,103 +765,6 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])( assert.deepEqual((yield* fileSystem.stat(indexPath)).mtime, originalIndexMtime); }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect.each( - [false, true].flatMap((nested) => - (["sparse", "flags", "manual-skip", "missing", "non-cone-missing"] as const).map( - (indexState) => ({ nested, indexState }), - ), - ), -)( - "sparse checkpoint preserves two captures (nested=$nested, index=$indexState)", - ({ nested, indexState }) => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const driver = yield* GitVcsDriver.makeVcsDriverShape(); - const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-checkpoint-sparse-" }); - const { git } = yield* makeCheckpointFixture(driver, cwd); - const write = Effect.fn(function* (name: string, contents: string) { - yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true }); - yield* fs.writeFileString(path.join(cwd, name), contents); - }); - for (const name of [ - "scope/in/edit", - "scope/in/delete", - "scope/out/deep/absent", - "scope/out/present", - "elsewhere/file", - ]) { - yield* write(name, "original\n"); - } - yield* git(["add", "."]); - yield* git(["commit", "-m", "sparse fixture"]); - yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "scope/in", "elsewhere"]); - if (indexState === "non-cone-missing") - yield* git(["sparse-checkout", "set", "--no-cone", "/scope/in/", "/elsewhere/"]); - yield* write("scope/in/edit", "staged\n"); - yield* write("elsewhere/file", "staged outside\n"); - yield* git(["add", "."]); - if (indexState === "flags") - yield* git(["update-index", "--assume-unchanged", "scope/in/delete"]); - if (indexState === "manual-skip") - yield* git(["update-index", "--skip-worktree", "scope/in/delete"]); - yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]); - yield* write("scope/in/edit", "working\n"); - yield* write("scope/out/present", "modified skipped\n"); - yield* write("scope/out/new file", "new outside cone\n"); - yield* write("elsewhere/file", "working outside\n"); - yield* fs.remove(path.join(cwd, "scope/in/delete")); - const indexPath = path.join(cwd, ".git/index"); - if (indexState.endsWith("missing")) yield* fs.remove(indexPath); - const originalIndex = yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)); - const captureCwd = nested ? path.join(cwd, "scope") : cwd; - for (const turn of [1, 2]) { - const ref = CheckpointRef.make(`refs/t3/checkpoints/sparse/${turn}`); - if (turn === 2) { - yield* write("scope/in/edit", "second\n"); - yield* fs.remove(path.join(cwd, "scope/out/new file")); - yield* write("scope/out/second", "second addition\n"); - } - const capture = driver.checkpoints.captureCheckpoint({ - cwd: captureCwd, - checkpointRef: ref, - }); - if (indexState === "non-cone-missing") { - assert.strictEqual((yield* capture.pipe(Effect.flip))._tag, "VcsProcessExitError"); - assert.isFalse( - yield* driver.checkpoints.hasCheckpointRef({ cwd: captureCwd, checkpointRef: ref }), - ); - assert.isFalse(yield* fs.exists(indexPath)); - break; - } - yield* capture; - for (const [name, content] of [ - ["scope/out/deep/absent", "original\n"], - ["scope/out/present", "modified skipped\n"], - ["scope/in/edit", turn === 1 ? "working\n" : "second\n"], - ["elsewhere/file", nested ? "original\n" : "working outside\n"], - [ - turn === 1 ? "scope/out/new file" : "scope/out/second", - turn === 1 ? "new outside cone\n" : "second addition\n", - ], - ]) { - assert.strictEqual((yield* git(["show", `${ref}:${name}`])).stdout, content); - } - const files = (yield* git(["ls-tree", "-rz", "--name-only", ref])).stdout.split("\0"); - assert.notInclude(files, "scope/in/delete"); - if (turn === 2) assert.notInclude(files, "scope/out/new file"); - assert.deepEqual( - yield* fs.readFile(indexPath).pipe(Effect.orElseSucceed(() => null)), - originalIndex, - ); - assert.isFalse(yield* fs.exists(path.join(cwd, "scope/out/deep/absent"))); - assert.strictEqual( - yield* fs.readFileString(path.join(cwd, "elsewhere/file")), - "working outside\n", - ); - } - }).pipe(Effect.scoped, Effect.provide(layerGitContract)), -); it.effect("checkpoint capture preserves racy edits made after resetting the index", () => Effect.gen(function* () { @@ -1080,114 +979,264 @@ it.effect("restores empty checkpoints without changing paths outside the workspa }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); -it.effect("GitVcsDriver forwards execute env to the VCS process", () => { - let observedEnv: NodeJS.ProcessEnv | undefined; - let observedAppendTruncationMarker: boolean | undefined; - let observedOutputMode: VcsProcess.VcsProcessInput["outputMode"]; +// The real VCS process, spawning `command` wherever the driver runs git. +const vcsProcessSpawning = (command: string) => + Layer.effect( + VcsProcess.VcsProcess, + Effect.map(VcsProcess.make, (vcsProcess) => + VcsProcess.VcsProcess.of({ run: (input) => vcsProcess.run({ ...input, command }) }), + ), + ).pipe(Layer.provide(ProcessRunner.layer), Layer.provideMerge(NodeServices.layer)); - return Effect.gen(function* () { - const driver = yield* GitVcsDriver.makeVcsDriverShape(); +it.effect("GitVcsDriver treats a missing git executable as outside any repository", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-missing-git-" }); + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provide(vcsProcessSpawning(path.join(cwd, "git"))), + ); - yield* driver.execute({ - operation: "GitVcsDriver.test.env", - cwd: "/repo", - args: ["status"], - env: { - GIT_INDEX_FILE: "/tmp/t3-index", - }, - appendTruncationMarker: true, - outputMode: "error", - }); + assert.strictEqual(yield* driver.isInsideWorkTree(cwd), false); + assert.strictEqual(yield* driver.detectRepository(cwd), null); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); - assert.deepStrictEqual(observedEnv, { - GIT_INDEX_FILE: "/tmp/t3-index", - }); - assert.strictEqual(observedAppendTruncationMarker, true); - assert.strictEqual(observedOutputMode, "error"); - }).pipe( - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - Layer.mock(VcsProcess.VcsProcess)({ - run: (input) => - Effect.sync(() => { - observedEnv = input.env; - observedAppendTruncationMarker = input.appendTruncationMarker; - observedOutputMode = input.outputMode; - return { - exitCode: ChildProcessSpawner.ExitCode(0), - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }; - }), - }), - ), - ), +it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "GitVcsDriver still fails detection when git exists but cannot be spawned", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + // A file without the execute bit fails to spawn with a permission error. + const notExecutable = yield* fileSystem.makeTempFileScoped({ prefix: "t3-git-" }); + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provide(vcsProcessSpawning(notExecutable)), + ); + + const error = yield* driver.isInsideWorkTree(process.cwd()).pipe(Effect.flip); + assert.strictEqual(error._tag, "VcsProcessSpawnError"); + const detectionError = yield* driver.detectRepository(process.cwd()).pipe(Effect.flip); + assert.strictEqual(detectionError._tag, "VcsProcessSpawnError"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +const gitCommandCount = (operation: string, outcome: string) => + Metric.value( + Metric.withAttributes(gitCommandsTotal, [ + ["operation", operation], + ["outcome", outcome], + ]), + ).pipe(Effect.map((state) => state.count)); + +const gitCommandTiming = (operation: string) => + Metric.value(Metric.withAttributes(gitCommandDuration, [["operation", operation]])); + +// Keep VcsProcess's exit classification; replace only the subprocess and its clock. +const makeMeteredDriver = Effect.fn("test.makeMeteredDriver")(function* (exitCode: number) { + const process = yield* VcsProcess.make.pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: () => + TestClock.adjust("250 millis").pipe( + Effect.as({ + code: ChildProcessSpawner.ExitCode(exitCode), + stdout: "git output", + stderr: exitCode === 0 ? "" : "fatal: test failure", + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }), + ), + }), + ); + return yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, process), ); }); -it.effect("GitVcsDriver flushes checkpoint objects and refs to disk before publishing them", () => { - const observedArgs: ReadonlyArray[] = []; +it.effect("GitVcsDriver meters each git command once under its operation", () => + Effect.gen(function* () { + const operation = "GitVcsDriver.checkpoints.resolveHeadCommit"; + const driver = yield* makeMeteredDriver(0); - return Effect.gen(function* () { - const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const result = yield* driver.execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] }); + yield* driver.execute({ operation, cwd: "/another-repo", args: ["rev-parse", "other-ref"] }); + + assert.strictEqual(result.stdout, "git output"); + assert.strictEqual(yield* gitCommandCount(operation, "success"), 2); + assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0); + const timing = yield* gitCommandTiming(operation); + assert.strictEqual(timing.count, 2); + assert.strictEqual(timing.sum, 500); + }).pipe( + Effect.provide(NodeServices.layer), + Effect.provideService(Metric.MetricRegistry, new Map()), + ), +); - yield* driver.checkpoints.captureCheckpoint({ +it.effect("GitVcsDriver counts an allowed non-zero exit as a success", () => + Effect.gen(function* () { + const operation = "GitVcsDriver.checkpoints.hasHeadCommit"; + const driver = yield* makeMeteredDriver(1); + + const result = yield* driver.execute({ + operation, cwd: "/repo", - checkpointRef: CheckpointRef.make("refs/t3/checkpoints/thread/turn/1"), + args: ["rev-parse", "--verify", "HEAD"], + allowNonZeroExit: true, }); - const writeCommands = ["add", "write-tree", "commit-tree", "update-ref"]; - const writes = observedArgs.filter((args) => - writeCommands.some((command) => args.includes(command)), + assert.strictEqual(result.exitCode, 1); + assert.strictEqual(yield* gitCommandCount(operation, "success"), 1); + assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0); + const timing = yield* gitCommandTiming(operation); + assert.strictEqual(timing.count, 1); + assert.strictEqual(timing.sum, 250); + }).pipe( + Effect.provide(NodeServices.layer), + Effect.provideService(Metric.MetricRegistry, new Map()), + ), +); + +it.effect("GitVcsDriver counts a failed git command as a failure", () => + Effect.gen(function* () { + const operation = "GitVcsDriver.checkpoints.resolveHeadCommit"; + const driver = yield* makeMeteredDriver(128); + + const error = yield* driver + .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] }) + .pipe(Effect.flip); + + assert.strictEqual(error._tag, "VcsProcessExitError"); + assert.strictEqual(yield* gitCommandCount(operation, "failure"), 1); + assert.strictEqual(yield* gitCommandCount(operation, "success"), 0); + const timing = yield* gitCommandTiming(operation); + assert.strictEqual(timing.count, 1); + assert.strictEqual(timing.sum, 250); + }).pipe( + Effect.provide(NodeServices.layer), + Effect.provideService(Metric.MetricRegistry, new Map()), + ), +); + +it.effect("checkpoint capture meters every git process it starts, including streamed ones", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const liveProcess = yield* VcsProcess.VcsProcess; + const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + let started = 0; + let streamed = 0; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const captureDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + if (input.operation === operation) { + started++; + if (input.onStdoutChunk !== undefined) streamed++; + } + return liveProcess.run(input); + }, + }), ); - assert.strictEqual(writes.length, 4); - for (const args of writes) { - const command = args.findIndex((arg) => writeCommands.includes(arg)); - for (const setting of ["core.fsync=objects,reference", "core.fsyncMethod=fsync"]) { - const index = args.indexOf(setting); - assert.strictEqual(args[index - 1], "-c", args.join(" ")); - assert.isBelow(index, command); - } - } - assert.deepStrictEqual(observedArgs.at(-1), [ - "-C", - "/repo", - "-c", - "core.fsync=objects,reference", - "-c", - "core.fsyncMethod=fsync", - "update-ref", - "refs/t3/checkpoints/thread/turn/1", - "commit0000", - ]); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-metrics-" }); + const { checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + + yield* captureDriver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + + assert.isAbove(streamed, 0); + assert.strictEqual(yield* gitCommandCount(operation, "success"), started); + assert.strictEqual(yield* gitCommandCount(operation, "failure"), 0); + assert.strictEqual((yield* gitCommandTiming(operation)).count, started); }).pipe( - Effect.provide( - Layer.mergeAll( - NodeServices.layer, - Layer.mock(VcsProcess.VcsProcess)({ - run: (input) => - Effect.sync(() => { - observedArgs.push(input.args); - const stdout = input.args.includes("write-tree") - ? "tree0000\n" - : input.args.includes("commit-tree") - ? "commit0000\n" - : input.args.includes("--git-common-dir") - ? ".git\n" - : ""; - return { - exitCode: ChildProcessSpawner.ExitCode(0), - stdout, - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }; - }), - }), - ), - ), - ); -}); + Effect.scoped, + Effect.provide(layerGitContract), + Effect.provideService(Metric.MetricRegistry, new Map()), + ), +); + +it.effect("git metrics finalize cancellation without exposing arbitrary operation labels", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const process = yield* VcsProcess.make.pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)), + }), + ); + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, process), + ); + const operation = "arbitrary operation /private/path"; + const fiber = yield* driver + .execute({ operation, cwd: "/repo", args: ["rev-parse", "HEAD"] }) + .pipe(Effect.forkChild); + yield* Deferred.await(started); + yield* TestClock.adjust("250 millis"); + yield* Fiber.interrupt(fiber); + + assert.strictEqual(yield* gitCommandCount("other", "interrupt"), 1); + assert.strictEqual(yield* gitCommandCount(operation, "interrupt"), 0); + const timing = yield* gitCommandTiming("other"); + assert.strictEqual(timing.count, 1); + assert.strictEqual(timing.sum, 250); + }).pipe( + Effect.provide(NodeServices.layer), + Effect.provideService(Metric.MetricRegistry, new Map()), + ), +); + +it.effect("git metrics count fsync fallback and transient retry subprocesses separately", () => + Effect.gen(function* () { + const retryReady = yield* Deferred.make(); + const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + let attempts = 0; + const process = yield* VcsProcess.make.pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(ProcessRunner.ProcessRunner, { + run: (input) => + Effect.gen(function* () { + attempts++; + yield* TestClock.adjust("250 millis"); + if (attempts === 2) { + assert.include(input.args, "core.fsyncMethod=writeout-only"); + yield* Deferred.succeed(retryReady, undefined); + } + return { + code: ChildProcessSpawner.ExitCode(attempts < 3 ? 128 : 0), + stdout: "", + stderr: + attempts === 1 + ? "fatal: fsync error on '.git/objects/test': Operation not supported" + : attempts === 2 + ? "fatal: Unable to create '/repo/.git/index.lock': File exists." + : "", + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }; + }), + }), + ); + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, process), + ); + const fiber = yield* driver + .execute({ operation, cwd: "/repo", args: ["-c", "core.fsyncMethod=batch", "add"] }) + .pipe(Effect.forkChild); + yield* Deferred.await(retryReady); + yield* TestClock.adjust("75 millis"); + yield* Fiber.join(fiber); + + assert.strictEqual(attempts, 3); + assert.strictEqual(yield* gitCommandCount(operation, "failure"), 2); + assert.strictEqual(yield* gitCommandCount(operation, "success"), 1); + const timing = yield* gitCommandTiming(operation); + assert.strictEqual(timing.count, 3); + assert.strictEqual(timing.sum, 750); + }).pipe( + Effect.provide(NodeServices.layer), + Effect.provideService(Metric.MetricRegistry, new Map()), + ), +); diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 098b1ebcf6499..aaa4c382ac7c9 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -13,6 +13,7 @@ import { ChildProcessSpawner } from "effect/process"; import { GitCommandError, VcsProcessExitError, + VcsUnsupportedOperationError, type VcsSwitchRefInput, type VcsSwitchRefResult, type VcsCreateRefInput, @@ -32,6 +33,8 @@ import { type VcsStatusResult, type WorktreeSubmodules, } from "@t3tools/contracts"; +import { isMissingExecutable } from "@t3tools/source-control-core/server/discovery"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { makeGitVcsDriverCore, PATCH_RENDER_PREFIX_ARGS, @@ -48,13 +51,10 @@ export interface ExecuteGitInput { readonly env?: NodeJS.ProcessEnv; readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number | null; + readonly forceKillAfterMs?: number; readonly maxOutputBytes?: number; readonly appendTruncationMarker?: boolean; - /** - * With `appendTruncationMarker`, keep invoking the line callbacks after the - * buffered copy is full. For long-running commands whose output is only - * consumed through `progress`. - */ + /** With appendTruncationMarker, line callbacks continue beyond the buffer cap for progress-only consumers. */ readonly keepLineCallbacksAfterTruncation?: boolean; readonly progress?: ExecuteGitProgress; } @@ -117,10 +117,7 @@ export interface ExecuteGitProgress { } export interface CreateWorktreeProgress { - /** - * Git refuses an existing path, so a path reported here belongs to this call and is safe to - * remove on cancel. - */ + /** Git refuses existing paths; claimed paths belong to this call and can be removed on cancel. */ readonly onWorktreeClaimed?: (path: string) => Effect.Effect; readonly onCheckoutProgress?: (input: { percent: number; @@ -140,10 +137,7 @@ export interface CreateWorktreeProgress { export interface CreateWorktreeOptions { readonly progress?: CreateWorktreeProgress; - /** - * Null (or omitted, for callers without settings access) defers to the - * checkout's own t3.json. - */ + /** Null or omitted defers to the checkout's t3.json. */ readonly submodules?: WorktreeSubmodules | null; readonly worktreesDirectory?: string; } @@ -197,15 +191,10 @@ export interface GitRenameBranchResult { branch: string; } -export interface GitFetchPullRequestBranchInput { +export interface GitFetchRefInput { cwd: string; - prNumber: number; - branch: string; -} - -export interface GitFetchPullRequestHeadCommitInput { - cwd: string; - prNumber: number; + /** A ref on the primary remote, such as a host's change request head ref. */ + ref: string; } export interface GitResolveCommitInput { @@ -220,10 +209,7 @@ export interface GitResolveCommitResult { export interface GitRefreshCheckedOutBranchInput { cwd: string; targetCommit: string; - /** - * Commit the checkout is allowed to be hard-reset away from: the upstream commit read before - * the fetch. HEAD sitting there means the checkout holds no work of its own. - */ + /** Pre-fetch upstream commit; resetting away is safe only if HEAD stayed here. */ resetWhenHeadCommit?: string | null | undefined; } @@ -278,6 +264,11 @@ export interface GitResolveRemoteTrackingCommitResult { remoteRefName: string; } +export interface GitFetchWorktreeBaseCommitInput { + cwd: string; + refName: string; +} + export interface GitSetBranchUpstreamInput { cwd: string; branch: string; @@ -306,6 +297,7 @@ export class GitVcsDriver extends Context.Service< readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], + options?: { readonly includePatch?: boolean }, ) => Effect.Effect; readonly commit: ( cwd: string, @@ -332,6 +324,14 @@ export class GitVcsDriver extends Context.Service< cwd: string, key: string, ) => Effect.Effect; + /** + * The branch, named as on the host, that T3 recorded `branch` was cut from. Null when none + * was recorded. + */ + readonly readBranchBase: ( + cwd: string, + branch: string, + ) => Effect.Effect; readonly resolveBranchName: ( cwd: string, refName: string, @@ -344,11 +344,12 @@ export class GitVcsDriver extends Context.Service< input: VcsCreateWorktreeInput, options?: CreateWorktreeOptions, ) => Effect.Effect; - readonly fetchPullRequestBranch: ( - input: GitFetchPullRequestBranchInput, + /** Force-updates local `branch` to the primary remote's `ref`. */ + readonly fetchRefIntoBranch: ( + input: GitFetchRefInput & { readonly branch: string }, ) => Effect.Effect; - readonly fetchPullRequestHeadCommit: ( - input: GitFetchPullRequestHeadCommitInput, + readonly fetchRefCommit: ( + input: GitFetchRefInput, ) => Effect.Effect; readonly resolveCommit: ( input: GitResolveCommitInput, @@ -370,6 +371,13 @@ export class GitVcsDriver extends Context.Service< readonly resolveRemoteTrackingCommit: ( input: GitResolveRemoteTrackingCommitInput, ) => Effect.Effect; + readonly resolveWorktreeBaseRemote: ( + input: GitFetchWorktreeBaseCommitInput, + ) => Effect.Effect<{ remoteName: string; branchName: string } | null, GitCommandError>; + /** Fetches the configured upstream, explicit remote ref, or origin; null uses the local base. */ + readonly fetchWorktreeBaseCommit: ( + input: GitFetchWorktreeBaseCommitInput, + ) => Effect.Effect; readonly fetchRemoteBranch: ( input: GitFetchRemoteBranchInput, ) => Effect.Effect; @@ -407,7 +415,6 @@ const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; const CHECKPOINT_RECOVERY_MAX_CANDIDATES = 64; const CHECKPOINT_RECOVERY_TIMEOUT = "5 seconds"; const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; -const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000; const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ "-c", "core.fsmonitor=false", @@ -464,7 +471,8 @@ function parseGitRemoteVerboseOutput( continue; } - const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed); + // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. + const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed); if (!match) { continue; } @@ -486,45 +494,48 @@ function parseGitRemoteVerboseOutput( return remotes; } -const gitCommand = ( - process: VcsProcess.VcsProcess["Service"], - operation: string, - cwd: string, - args: ReadonlyArray, - options?: { - readonly stdin?: string; - readonly env?: NodeJS.ProcessEnv; - readonly allowNonZeroExit?: boolean; - readonly timeoutMs?: number; - readonly maxOutputBytes?: number; - readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"]; - readonly appendTruncationMarker?: boolean; - }, -) => - process.run({ - operation, - command: "git", - args: ["-C", cwd, ...args], - cwd, - spawnCwd: globalThis.process.cwd(), - ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}), - ...(options?.env !== undefined ? { env: options.env } : {}), - ...(options?.allowNonZeroExit !== undefined - ? { allowNonZeroExit: options.allowNonZeroExit } - : {}), - ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), - ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), - ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}), - ...(options?.appendTruncationMarker !== undefined - ? { appendTruncationMarker: options.appendTruncationMarker } - : {}), - }); +const gitCommand = Effect.fn("GitVcsDriver.gitCommand")( + ( + process: VcsProcess.VcsProcess["Service"], + operation: string, + cwd: string, + args: ReadonlyArray, + options?: { + readonly stdin?: string; + readonly env?: NodeJS.ProcessEnv; + readonly allowNonZeroExit?: boolean; + readonly timeoutMs?: number; + readonly maxOutputBytes?: number; + readonly outputMode?: VcsProcess.VcsProcessInput["outputMode"]; + readonly appendTruncationMarker?: boolean; + }, + ) => + process.run({ + operation, + command: "git", + args: ["-C", cwd, ...args], + cwd, + spawnCwd: globalThis.process.cwd(), + ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}), + ...(options?.env !== undefined ? { env: options.env } : {}), + ...(options?.allowNonZeroExit !== undefined + ? { allowNonZeroExit: options.allowNonZeroExit } + : {}), + ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), + ...(options?.outputMode !== undefined ? { outputMode: options.outputMode } : {}), + ...(options?.appendTruncationMarker !== undefined + ? { appendTruncationMarker: options.appendTruncationMarker } + : {}), + }), +); export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const vcsProcess = yield* VcsProcess.VcsProcess; const crypto = yield* Crypto.Crypto; + const hostPlatform = yield* HostProcess.Platform; const capabilities = { kind: "git" as const, supportsWorktrees: true, @@ -545,7 +556,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( timeoutMs: 5_000, maxOutputBytes: 4_096, }, - ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true")); + ).pipe( + Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"), + Effect.catchIf(isMissingExecutable, () => Effect.succeed(false)), + ); const execute: VcsDriver.VcsDriver["Service"]["execute"] = (input) => gitCommand(vcsProcess, input.operation, input.cwd, input.args, { @@ -768,36 +782,52 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }), ); - const resolveGitCommonDir = (cwd: string) => - Effect.gen(function* () { - const result = yield* execute({ - operation: "GitVcsDriver.checkpoints.resolveGitCommonDir", - cwd, - args: ["rev-parse", "--git-common-dir"], - }); - const gitCommonDir = result.stdout.trim(); - return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir); + // Git reports relative paths from the physical cwd, which can differ from a symlink. + const resolveGitCommonDir = Effect.fn("GitVcsDriver.resolveGitCommonDir")(function* ( + cwd: string, + ) { + const result = yield* execute({ + operation: "GitVcsDriver.checkpoints.resolveGitCommonDir", + cwd, + args: ["rev-parse", "--git-common-dir"], }); + const gitCommonDir = result.stdout.trim(); + if (path.isAbsolute(gitCommonDir)) return gitCommonDir; + const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + return path.resolve(physicalCwd, gitCommonDir); + }); - // Git renames loose objects and refs into place without fsync by default, so - // an unclean restart can leave 0-byte files under refs/t3/** that break every - // later fetch and push. Checkpoint writes flush before they are published; - // macOS defaults to writeout-only, which does not reach the disk either. + // Git defaults and macOS writeout-only can leave empty refs after crashes; flush before publication. + // Set fsync first: Git 2.36 ignores unknown batch without resetting the method. + // Batch fully flushes refs and equals fsync on macOS HFS+/APFS and Windows NTFS/ReFS. + // Keep per-object fsync elsewhere; VcsProcess retries unsupported macOS full flushes with plain fsync. const durableWrite = [ "-c", "core.fsync=objects,reference", "-c", "core.fsyncMethod=fsync", + ...(hostPlatform === "darwin" || hostPlatform === "win32" + ? ["-c", "core.fsyncMethod=batch"] + : []), ] as const; + // Checkpoints must handle existing paths beyond Windows MAX_PATH, even when + // core.longpaths is disabled in the user's Git configuration. + const longPaths = hostPlatform === "win32" ? ["-c", "core.longpaths=true"] : []; + const checkpoints: VcsDriver.VcsCheckpointOps = { captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) { const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; + // Scratch split-index writes can expire sharedindex files still used by the real index. const indexConfig = [ "-c", "core.fsmonitor=false", "-c", "sparse.expectFilesOutsideOfPatterns=false", + "-c", + "core.splitIndex=false", + "-c", + "splitIndex.sharedIndexExpire=never", ]; const gitCommonDir = yield* resolveGitCommonDir(input.cwd); const indexId = yield* crypto.randomUUIDv4().pipe(Effect.orDie); @@ -933,12 +963,70 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( cwd: input.cwd, args: sparseCheckout ? [...indexConfig, "-c", "index.sparse=true", "read-tree", "--reset", "HEAD"] - : ["read-tree", "HEAD"], + : [...indexConfig, "read-tree", "HEAD"], env: commitEnv, }); } } + const workspaceIgnored = (yield* filterIgnoredPaths(input.cwd, ["."])).length === 0; + if (workspaceIgnored) { + // HEAD omits staged-only paths. Seed just this workspace's additions, keeping + // unrelated staged changes and the scratch index's sparse flags untouched. + const additions = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "-c", + "core.quotePath=true", + "diff", + "--cached", + "--raw", + "--no-abbrev", + "--no-renames", + "--no-relative", + "--ignore-submodules=none", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--ita-visible-in-index", + "--diff-filter=A", + "--", + ".", + ], + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + if (additions.stdout.length > 0) { + // Git's quoted paths round-trip through index-info, including non-UTF-8 names. + yield* execute({ + operation, + cwd: input.cwd, + args: [...indexConfig, "-c", "index.sparse=false", "update-index", "--index-info"], + stdin: additions.stdout.replace( + /^:000000 ([0-7]{6}) 0+ ([0-9a-f]+) A\t/gm, + "$1 $2\t", + ), + env: commitEnv, + }); + } + const tracked = yield* execute({ + operation, + cwd: input.cwd, + args: [...indexConfig, "ls-files", "--cached", "-z", "--", "."], + env: commitEnv, + maxOutputBytes: 1, + outputMode: "truncate", + }); + if (tracked.stdout.length === 0) { + return yield* new VcsUnsupportedOperationError({ + operation, + kind: "git", + detail: "The workspace directory is ignored by its Git repository.", + }); + } + } + const stageFiles = (exclusions: ReadonlyArray) => execute({ operation, @@ -946,9 +1034,11 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( args: [ ...indexConfig, ...durableWrite, + ...longPaths, "add", ...(sparseCheckout ? ["--sparse"] : []), - "-A", + // add -A rejects ignored directories even when they contain tracked files. + workspaceIgnored ? "-u" : "-A", "--", ".", ...exclusions, @@ -959,12 +1049,19 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( Effect.catchTags({ VcsProcessExitError: (error) => Effect.gen(function* () { - // Git cannot stage an embedded repository until it has a commit. Discover these - // only after staging fails so ordinary checkpoints do not need another file scan. + // Git cannot stage uncommitted embedded repos; scan for them only after staging fails. const untracked = yield* execute({ operation, cwd: input.cwd, - args: ["ls-files", "--others", "--exclude-standard", "-z", "--", "."], + args: [ + ...longPaths, + "ls-files", + "--others", + "--exclude-standard", + "-z", + "--", + ".", + ], env: commitEnv, maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, }); @@ -1084,7 +1181,16 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( yield* execute({ operation, cwd: input.cwd, - args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."], + args: [ + ...longPaths, + "restore", + "--source", + commitOid, + "--worktree", + "--staged", + "--", + ".", + ], }); } // Restoring away the last tracked file can remove a nested workspace directory. @@ -1104,7 +1210,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const cleaned = yield* execute({ operation, cwd: input.cwd, - args: ["clean", "-fd", "--", "."], + args: [...longPaths, "clean", "-fd", "--", "."], allowNonZeroExit: true, }); if (cleaned.exitCode !== 0) { @@ -1133,7 +1239,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( yield* execute({ operation, cwd: input.cwd, - args: ["reset", "--quiet", "--", "."], + args: [...longPaths, "reset", "--quiet", "--", "."], }); } @@ -1194,7 +1300,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( : []), ], allowNonZeroExit: true, - maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + maxOutputBytes: input.maxOutputBytes ?? VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, outputMode: input.format === "numstat" ? "error" : "truncate", }); @@ -1236,11 +1342,10 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( operation, cwd: input.cwd, args: [...args, "--name-only", "-z", "--no-renames", "--no-ext-diff"], - maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, outputMode: "error", }).pipe(Effect.map((result) => result.stdout.split("\0"))); - // Remerge diff lists a merge's paths only where the result differs from Git's - // automatic merge, so a merge keeps its conflict fixes and drops clean upstream changes. + // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. const pathLists = yield* Effect.all( [ listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]), diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 0cb7beb361b7c..5853d44edb170 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -8,29 +8,27 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import * as Logger from "effect/Logger"; -import * as Metric from "effect/Metric"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; -import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { GitCommandError, ReviewDiffPreviewInput, + VcsRef, + VcsListRefsResult, type ReviewDiffFileContentsInput, type ReviewDiffPreviewResult, type WorktreeSubmodules, } from "@t3tools/contracts"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as ServerConfig from "../config.ts"; -import { gitCommandDuration } from "../observability/Metrics.ts"; import { makeGitVcsDriverCore, parseGitCheckoutProgressLine, @@ -41,6 +39,8 @@ import * as GitVcsDriver from "./GitVcsDriver.ts"; import { gitConfigEnv } from "./VcsProcess.ts"; const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError)); +const decodeVcsRef = Schema.decodeUnknownSync(VcsRef); +const decodeVcsListRefsResult = Schema.decodeUnknownSync(VcsListRefsResult); const layerServerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-vcs-driver-test-", @@ -80,6 +80,86 @@ const makeSuccessfulHandle = (stdout: string) => getOutputFd: () => Stream.empty, }); +const makeFailedHandle = (stderr: string) => + ChildProcessSpawner.makeHandle({ + ...makeNonRepositoryHandle(), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + stderr: Stream.encodeText(Stream.make(stderr)), + }); + +describe("Git output collection", () => { + // Git writes in arbitrary chunk sizes; one byte per chunk splits every + // multibyte character across reads. + const byteChunks = (text: string) => + Stream.fromIterable(Array.from(new TextEncoder().encode(text), (byte) => Uint8Array.of(byte))); + const makeDriver = (output: { stdout?: string; stderr?: string }) => + makeGitVcsDriverCore().pipe( + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + ...makeSuccessfulHandle(""), + stdout: byteChunks(output.stdout ?? ""), + stderr: byteChunks(output.stderr ?? ""), + }), + ), + ), + ), + ); + + it.effect("returns the same split UTF-8 and NUL output with and without line callbacks", () => + Effect.gen(function* () { + const stdout = "a\\b\0雪\nlast "; + const stderr = "Receiving é\r\nUpdating 雪\rdone"; + const driver = yield* makeDriver({ stdout, stderr }); + const input = { operation: "test.chunkedGitOutput", cwd: "/repo", args: ["status"] }; + const expected = { + exitCode: 0, + stdout, + stderr, + stdoutTruncated: false, + stderrTruncated: false, + }; + + assert.deepEqual(yield* driver.execute(input), expected); + + const stdoutLines: string[] = []; + const stderrLines: string[] = []; + const withCallbacks = yield* driver.execute({ + ...input, + progress: { + onStdoutLine: (line) => Effect.sync(() => void stdoutLines.push(line)), + onStderrLine: (line) => Effect.sync(() => void stderrLines.push(line)), + }, + }); + assert.deepEqual(withCallbacks, expected); + assert.deepEqual(stdoutLines, ["a\\b\0雪", "last "]); + assert.deepEqual(stderrLines, ["Receiving é", "Updating 雪", "done"]); + }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), + ); + + it.effect("caps output without line callbacks", () => + Effect.gen(function* () { + const driver = yield* makeDriver({ stderr: "é雪\rdone" }); + const input = { + operation: "test.cappedGitOutput", + cwd: "/repo", + args: ["status"], + maxOutputBytes: 3, + }; + + const truncated = yield* driver.execute({ ...input, appendTruncationMarker: true }); + assert.equal(truncated.stderr, "é\uFFFD"); + assert.isTrue(truncated.stderrTruncated); + + const error = yield* driver.execute(input).pipe(Effect.flip); + assert.equal(error.outputLength, 4); + assert.include(error.detail, "exceeded 3 bytes"); + }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), + ); +}); + const makeTmpDir = ( prefix = "git-vcs-driver-test-", ): Effect.Effect => @@ -151,112 +231,6 @@ const initRepoWithCommit = ( return { initialBranch }; }); -it.effect("bounds Git bursts across drivers without timing out queued commands", () => - Effect.gen(function* () { - const gate = yield* Deferred.make(); - const starts = yield* Queue.unbounded(); - let active = 0; - let peak = 0; - const spawner = ChildProcessSpawner.make(() => - Effect.acquireRelease( - Effect.gen(function* () { - peak = Math.max(peak, ++active); - yield* Queue.offer(starts, active); - return ChildProcessSpawner.makeHandle({ - ...makeSuccessfulHandle("ok"), - exitCode: Deferred.await(gate).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }); - }), - () => Effect.sync(() => active--), - ), - ); - const drivers = yield* Effect.all( - Array.from({ length: 16 }, () => - makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ), - ), - ); - const burst = yield* Effect.forEach( - drivers, - (driver, index) => - driver.execute({ - operation: "test.gitBurst", - cwd: "/repo", - args: ["rev-parse", "HEAD"], - ...(index < 4 ? {} : { timeoutMs: index < 8 ? 30_000 : 1_000 }), - }), - { concurrency: "unbounded" }, - ).pipe(Effect.forkChild); - - yield* TestClock.adjust("2 seconds"); - assert.equal(yield* Queue.size(starts), 8); - assert.equal(peak, 8); - yield* Deferred.succeed(gate, undefined); - const results = yield* Fiber.join(burst); - assert.equal(results.length, 16); - assert.isTrue(results.every((result) => result.stdout === "ok" && result.exitCode === 0)); - assert.equal(peak, 8); - assert.equal(active, 0); - const duration = yield* Metric.value( - Metric.withAttributes(gitCommandDuration, [["operation", "test.gitBurst"]]), - ); - assert.equal(duration.count, 16); - assert.equal(duration.sum, 16_000); - }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), -); - -it.effect.each([{ timeoutMs: null }, { timeoutMs: 30_001 }])( - "keeps all Git slots available with a pending command whose timeout is $timeoutMs", - ({ timeoutMs }) => - Effect.gen(function* () { - const slowGate = yield* Deferred.make(); - const fastGate = yield* Deferred.make(); - const starts = yield* Queue.unbounded(); - let active = 0; - const spawner = ChildProcessSpawner.make((command) => - Effect.acquireRelease( - Effect.gen(function* () { - active++; - yield* Queue.offer(starts, undefined); - const gate = - ChildProcess.isStandardCommand(command) && command.args[0] === "push" - ? slowGate - : fastGate; - return ChildProcessSpawner.makeHandle({ - ...makeSuccessfulHandle("ok"), - exitCode: Deferred.await(gate).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), - }); - }), - () => Effect.sync(() => active--), - ), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - const slow = yield* driver - .execute({ operation: "test.slowGit", cwd: "/repo", args: ["push"], timeoutMs }) - .pipe(Effect.forkChild); - yield* Queue.take(starts); - const burst = yield* Effect.all( - Array.from({ length: 8 }, () => - driver.execute({ operation: "test.fastGit", cwd: "/repo", args: ["status"] }), - ), - { concurrency: "unbounded" }, - ).pipe(Effect.forkChild); - - yield* TestClock.adjust("0 seconds"); - assert.equal(yield* Queue.size(starts), 8); - assert.equal(active, 9); - yield* Deferred.succeed(fastGate, undefined); - assert.equal((yield* Fiber.join(burst)).length, 8); - assert.equal(active, 1); - yield* Deferred.succeed(slowGate, undefined); - assert.equal((yield* Fiber.join(slow)).stdout, "ok"); - assert.equal(active, 0); - }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), -); - it.effect.each(["root", "nested", "worktree"] as const)( "skips clean filters while the %s index is locked and resumes after unlock", (location) => @@ -300,46 +274,6 @@ it.effect.each(["root", "nested", "worktree"] as const)( }).pipe(Effect.provide(layerTest)), ); -it.effect("uses stable diagnostics for every parsed non-repository command", () => { - const commands: Array<{ readonly args: ReadonlyArray; readonly lcAll?: string }> = []; - const spawner = ChildProcessSpawner.make((command) => - Effect.sync(() => { - if (!ChildProcess.isStandardCommand(command)) { - return assert.fail("expected a standard Git command"); - } - commands.push({ - args: command.args, - ...(command.options.env?.LC_ALL ? { lcAll: command.options.env.LC_ALL } : {}), - }); - return makeNonRepositoryHandle(); - }), - ); - const layerNodeServices = Layer.merge( - NodeServices.layer, - Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), - ); - const layer = GitVcsDriver.layer.pipe( - Layer.provide(layerServerConfig), - Layer.provideMerge(layerNodeServices), - ); - - return Effect.gen(function* () { - const driver = yield* GitVcsDriver.GitVcsDriver; - const cwd = "/repo"; - - yield* driver.statusDetailsLocal(cwd); - yield* driver.statusDetailsRemote(cwd, { refreshUpstream: false }); - yield* driver.listRefs({ cwd }); - - assert.deepStrictEqual(commands, [ - { args: ["rev-parse", "--git-path", "index"], lcAll: "C" }, - { args: ["status", "--porcelain=2", "--branch"], lcAll: "C" }, - { args: ["rev-parse", "--abbrev-ref", "HEAD"], lcAll: "C" }, - { args: ["rev-parse", "--git-common-dir"], lcAll: "C" }, - ]); - }).pipe(Effect.provide(layer)); -}); - it.effect("invalidates origin remote cache when a driver mutation adds origin", () => Effect.gen(function* () { const driver = yield* GitVcsDriver.GitVcsDriver; @@ -358,144 +292,13 @@ it.effect("invalidates origin remote cache when a driver mutation adds origin", }).pipe(Effect.provide(layerTest)), ); -it.effect("re-reads origin remote status after cache TTL expiry and bypassed invalidation", () => - Effect.gen(function* () { - const driver = yield* GitVcsDriver.GitVcsDriver; - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - - assert.equal((yield* driver.statusDetailsLocal(cwd)).hasOriginRemote, false); - - yield* git(cwd, ["remote", "add", "origin", remote]); - - const stillCached = yield* driver.statusDetailsLocal(cwd); - assert.equal(stillCached.hasOriginRemote, false); - - yield* TestClock.adjust("6 minutes"); - - const afterExpiry = yield* driver.statusDetailsLocal(cwd); - assert.equal(afterExpiry.hasOriginRemote, true); - }).pipe(Effect.provide(layerTest)), -); - -it.effect("coalesces concurrent ref pages into one repository snapshot", () => - Effect.scoped( - Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const spawnedArgs = yield* Ref.make>>([]); - const firstWorktreeScanStarted = yield* Deferred.make(); - const remoteNamesScanCompleted = yield* Deferred.make(); - const delayFirstWorktreeScan = yield* Ref.make(true); - const countingSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - yield* Ref.update(spawnedArgs, (current) => [...current, command.args]); - const isWorktreeScan = - command.args.includes("worktree") && command.args.includes("--porcelain"); - const shouldDelay = - isWorktreeScan && (yield* Ref.getAndSet(delayFirstWorktreeScan, false)); - if (shouldDelay) { - yield* Deferred.succeed(firstWorktreeScanStarted, undefined); - yield* Effect.sleep("8 seconds"); - } - const handle = yield* delegate.spawn(command); - const isRemoteNamesScan = - command.args.length === 3 && - command.args[0] === "--git-dir" && - command.args[2] === "remote"; - return isRemoteNamesScan - ? ChildProcessSpawner.makeHandle({ - ...handle, - exitCode: handle.exitCode.pipe( - Effect.tap(() => Deferred.succeed(remoteNamesScanCompleted, undefined)), - ), - }) - : handle; - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, countingSpawner), - ); - const cwd = yield* makeTmpDir(); - const runGit = (args: ReadonlyArray) => - driver.execute({ - operation: "GitVcsDriver.test.coalescedListRefs", - cwd, - args, - timeoutMs: 10_000, - }); - - yield* driver.initRepo({ cwd }); - yield* runGit(["config", "user.email", "test@test.com"]); - yield* runGit(["config", "user.name", "Test"]); - yield* writeTextFile(cwd, "README.md", "# test\n"); - yield* runGit(["add", "."]); - yield* runGit(["commit", "-m", "initial commit"]); - yield* Ref.set(spawnedArgs, []); - - const initialRequest = yield* driver - .listRefs({ cwd, refresh: true, limit: 100 }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(firstWorktreeScanStarted); - yield* Deferred.await(remoteNamesScanCompleted); - yield* TestClock.adjust("6 seconds"); - const laterRequests = yield* Effect.all( - Array.from({ length: 30 }, (_, index) => - driver.listRefs({ - cwd, - refresh: true, - query: `missing-${index}`, - limit: 100, - }), - ), - { concurrency: "unbounded" }, - ).pipe(Effect.forkChild({ startImmediately: true })); - yield* TestClock.adjust("2 seconds"); - yield* Fiber.join(initialRequest); - yield* Fiber.join(laterRequests); - yield* driver.listRefs({ cwd, cursor: 1, limit: 100 }); - - const firstSnapshotCommands = yield* Ref.get(spawnedArgs); - const snapshotRefScans = firstSnapshotCommands.filter( - (args) => - args.includes("for-each-ref") && - args.includes("refs/heads") && - args.includes("refs/remotes"), - ); - const worktreeScans = firstSnapshotCommands.filter( - (args) => args.includes("worktree") && args.includes("--porcelain"), - ); - assert.equal(snapshotRefScans.length, 1); - assert.equal(worktreeScans.length, 1); - - yield* driver.createRef({ cwd, refName: "feature/cache-invalidation" }); - const refreshed = yield* driver.listRefs({ cwd, limit: 100 }); - assert.equal( - refreshed.refs.some((ref) => ref.name === "feature/cache-invalidation"), - true, - ); - const allCommands = yield* Ref.get(spawnedArgs); - assert.equal( - allCommands.filter( - (args) => - args.includes("for-each-ref") && - args.includes("refs/heads") && - args.includes("refs/remotes"), - ).length, - 2, - ); - }), - ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), -); - -describe("pull output beyond the output cap", () => { +describe("pullCurrentBranch", () => { // A fast-forward that prints over 1 MB takes thousands of files, so the real pull's output is // padded past the cap instead. - const withPaddedPull = (stream: "stdout" | "stderr") => + const withPaddedPull = ( + stream: "stdout" | "stderr", + onPull?: (args: ReadonlyArray) => void, + ) => Effect.gen(function* () { const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; const padding = new Uint8Array(1_000_001).fill(0x20); @@ -506,6 +309,7 @@ describe("pull output beyond the output cap", () => { ChildProcess.isStandardCommand(command) && command.args.includes("pull") && command.args.includes("--ff-only"); + if (isPull) onPull?.(command.args); return isPull ? ChildProcessSpawner.makeHandle({ ...handle, @@ -534,9 +338,122 @@ describe("pull output beyond the output cap", () => { yield* git(updater, ["add", "remote.txt"]); yield* git(updater, ["commit", "-m", "remote commit"]); yield* git(updater, ["push", "origin", initialBranch]); - return { cwd, remoteHead: yield* git(updater, ["rev-parse", "HEAD"]) }; + return { + cwd, + remote, + updater, + initialBranch, + remoteHead: yield* git(updater, ["rev-parse", "HEAD"]), + }; }); + it.effect("still fetches other branches on the first pull", () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const { cwd, updater, remoteHead } = yield* cloneBehindRemote; + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.equal(result.status, "pulled"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + assert.equal(yield* git(cwd, ["rev-parse", "refs/remotes/origin/other"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each([false, true])( + "pulls past an unrelated lock with custom fetch mapping=%s", + (customMapping) => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const fs = yield* FileSystem.FileSystem; + const { cwd, updater, initialBranch, remoteHead } = yield* cloneBehindRemote; + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); + const remoteName = customMapping ? "team/upstream" : "origin"; + const refPrefix = customMapping + ? `refs/remotes/${remoteName}/mapped` + : "refs/remotes/origin"; + if (customMapping) { + yield* git(cwd, ["remote", "rename", "origin", remoteName]); + yield* git(cwd, ["config", `remote.${remoteName}.fetch`, `+refs/heads/*:${refPrefix}/*`]); + yield* git(cwd, ["update-ref", `${refPrefix}/${initialBranch}`, "HEAD"]); + } + const lock = `.git/${refPrefix}/other.lock`; + yield* writeTextFile(cwd, lock, ""); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.equal(result.status, "pulled"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + assert.equal(yield* git(cwd, ["rev-parse", `${refPrefix}/${initialBranch}`]), remoteHead); + assert.isTrue(yield* fs.exists(`${cwd}/${lock}`)); + assert.equal(yield* fs.readFileString(`${cwd}/${lock}`), ""); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("reports an upstream lock after the fallback without removing it", () => + Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + const fs = yield* FileSystem.FileSystem; + const { cwd, initialBranch } = yield* cloneBehindRemote; + const before = yield* git(cwd, ["rev-parse", "HEAD"]); + const lock = `.git/refs/remotes/origin/${initialBranch}.lock`; + yield* writeTextFile(cwd, lock, ""); + + const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); + + assert.include(error.detail, "could not update a local reference"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), before); + assert.isTrue(yield* fs.exists(`${cwd}/${lock}`)); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect.each(["branch", "HEAD"] as const)( + "does not retry a failed fetch if another operation moved %s", + (moved) => + Effect.gen(function* () { + const fixtureDriver = yield* GitVcsDriver.GitVcsDriver; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const { cwd, updater } = yield* cloneBehindRemote; + yield* git(updater, ["push", "origin", "HEAD:refs/heads/other"]); + yield* writeTextFile(cwd, ".git/refs/remotes/origin/other.lock", ""); + let pulls = 0; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const handle = yield* delegate.spawn(command); + if (!ChildProcess.isStandardCommand(command) || !command.args.includes("pull")) { + return handle; + } + pulls += 1; + return ChildProcessSpawner.makeHandle({ + ...handle, + exitCode: handle.exitCode.pipe( + Effect.tap(() => + git( + cwd, + moved === "branch" + ? ["checkout", "-b", "moved"] + : ["commit", "--allow-empty", "-m", "concurrent commit"], + ).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, fixtureDriver), + Effect.orDie, + ), + ), + ), + }); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const error = yield* Effect.flip(driver.pullCurrentBranch(cwd)); + + assert.include(error.detail, "could not update a local reference"); + assert.equal(pulls, 1); + }).pipe(Effect.scoped, Effect.provide(layerServerConfig.pipe(Layer.provideMerge(layerTest)))), + ); + it.effect.each(["stdout", "stderr"] as const)( "reports a fast-forward whose %s passes the cap as pulled", (stream) => @@ -558,7 +475,8 @@ describe("pull output beyond the output cap", () => { it.effect("still fails a pull that Git rejects, whatever its output size", () => Effect.scoped( Effect.gen(function* () { - const driver = yield* withPaddedPull("stderr"); + const pulls: ReadonlyArray[] = []; + const driver = yield* withPaddedPull("stderr", (args) => pulls.push(args)); yield* Effect.gen(function* () { const { cwd } = yield* cloneBehindRemote; yield* writeTextFile(cwd, "local.txt", "local\n"); @@ -570,6 +488,7 @@ describe("pull output beyond the output cap", () => { assert.equal(error.operation, "GitVcsDriver.pullCurrentBranch.pull"); assert.equal(error.exitCode, 128); assert.notInclude(error.detail, "exceeded"); + assert.lengthOf(pulls, 1); }).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); }), ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), @@ -667,42 +586,6 @@ it.effect("invalidates a ref snapshot when a mutation fails after changing Git", ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), ); -it.effect("fails a ref snapshot when for-each-ref exits unsuccessfully", () => - Effect.scoped( - Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const snapshotAttempts = yield* Ref.make(0); - const failingSnapshotSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - if (command.args.includes("for-each-ref")) { - yield* Ref.update(snapshotAttempts, (count) => count + 1); - return makeNonRepositoryHandle(); - } - return yield* delegate.spawn(command); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingSnapshotSpawner), - ); - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd).pipe(Effect.provideService(GitVcsDriver.GitVcsDriver, driver)); - - const error = yield* driver.listRefs({ cwd, refresh: true }).pipe(Effect.flip); - - assert.deepInclude(error, { - _tag: "GitCommandError", - operation: "GitVcsDriver.listRefs.snapshotRefs", - detail: "Git ref snapshot enumeration failed.", - exitCode: 128, - }); - assert.equal(yield* Ref.get(snapshotAttempts), 1); - }), - ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), -); - it.effect("marks the current branch when worktree metadata is unavailable", () => Effect.scoped( Effect.gen(function* () { @@ -825,130 +708,26 @@ it.effect("reads worktrees from git that rejects worktree list -z", () => ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), ); -it.effect("refreshes the current branch after an external checkout", () => +it.effect("does not report a separate git dir as the worktree of its branch", () => Effect.scoped( Effect.gen(function* () { const driver = yield* GitVcsDriver.GitVcsDriver; const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(cwd, ["branch", "external-checkout"]); - - const initialRefs = yield* driver.listRefs({ cwd, refresh: true }); - assert.isTrue(initialRefs.refs.find((ref) => ref.name === initialBranch)?.current); - - yield* driver.execute({ - operation: "GitVcsDriver.test.externalCheckout", - cwd, - args: ["checkout", "external-checkout"], - timeoutMs: 10_000, - }); - yield* TestClock.adjust("6 seconds"); - - const refreshedRefs = yield* driver.listRefs({ cwd, refresh: true }); - assert.isTrue(refreshedRefs.refs.find((ref) => ref.name === "external-checkout")?.current); - assert.isFalse(refreshedRefs.refs.find((ref) => ref.name === initialBranch)?.current); - }), - ).pipe(Effect.provide(layerTest)), -); + const gitDir = yield* makeTmpDir(); + yield* git(cwd, ["init", `--separate-git-dir=${gitDir}`]); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "init"]); -it.effect("backs off and logs failed fetch attempts across linked worktrees", () => - Effect.scoped( - Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const fetchAttempts = yield* Ref.make(0); - const failingFetchSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - if (command.args.includes("fetch") && command.args.includes("--quiet")) { - yield* Ref.update(fetchAttempts, (count) => count + 1); - return makeNonRepositoryHandle(); - } - return yield* delegate.spawn(command); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingFetchSpawner), - ); - const warnings: string[] = []; - const logger = Logger.make(({ message }) => { - warnings.push(String(message)); - }); - const readRemoteStatus = (workingDirectory: string) => - driver - .statusDetailsRemote(workingDirectory) - .pipe(Effect.provideService(Logger.CurrentLoggers, new Set([logger]))); - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const worktreesRoot = yield* makeTmpDir("git-vcs-driver-worktrees-"); - const pathService = yield* Path.Path; - const worktreePath = pathService.join(worktreesRoot, "linked"); - const runGit = (workingDirectory: string, args: ReadonlyArray) => - driver.execute({ - operation: "GitVcsDriver.test.upstreamRefreshBackoff", - cwd: workingDirectory, - args, - timeoutMs: 10_000, - }); + const refs = yield* driver.listRefs({ cwd, refresh: true }); + const worktreePath = refs.refs.find((ref) => ref.current)?.worktreePath; - yield* driver.initRepo({ cwd }); - yield* runGit(cwd, ["config", "user.email", "test@test.com"]); - yield* runGit(cwd, ["config", "user.name", "Test"]); - yield* writeTextFile(cwd, "README.md", "# test\n"); - yield* runGit(cwd, ["add", "."]); - yield* runGit(cwd, ["commit", "-m", "initial commit"]); - const initialBranch = (yield* runGit(cwd, ["branch", "--show-current"])).stdout.trim(); - yield* runGit(remote, ["init", "--bare"]); - yield* runGit(cwd, ["remote", "add", "origin", remote]); - yield* runGit(cwd, ["push", "-u", "origin", initialBranch]); - yield* runGit(cwd, ["worktree", "add", "-b", "feature/linked", worktreePath]); - yield* runGit(worktreePath, [ - "branch", - "--set-upstream-to", - `origin/${initialBranch}`, - "feature/linked", - ]); - const rootCommonDir = (yield* runGit(cwd, ["rev-parse", "--git-common-dir"])).stdout.trim(); - const linkedCommonDir = (yield* runGit(worktreePath, [ - "rev-parse", - "--git-common-dir", - ])).stdout.trim(); - // Native realpath, since git reports the long form of a directory the - // temp dir may name by its 8.3 short form on Windows. assert.equal( - NodeFS.realpathSync.native(pathService.resolve(cwd, rootCommonDir)), - NodeFS.realpathSync.native(pathService.resolve(worktreePath, linkedCommonDir)), + worktreePath && NodeFS.realpathSync.native(worktreePath), + NodeFS.realpathSync.native(cwd), ); - yield* Ref.set(fetchAttempts, 0); - - yield* readRemoteStatus(cwd); - yield* readRemoteStatus(worktreePath); - assert.equal(yield* Ref.get(fetchAttempts), 1); - assert.lengthOf(warnings, 1); - assert.include(warnings[0], "Background Git fetch failed"); - - yield* TestClock.adjust("29 seconds"); - yield* readRemoteStatus(worktreePath); - assert.equal(yield* Ref.get(fetchAttempts), 1); - assert.lengthOf(warnings, 1); - - yield* TestClock.adjust("1 second"); - yield* readRemoteStatus(cwd); - assert.equal(yield* Ref.get(fetchAttempts), 2); - assert.lengthOf(warnings, 2); - - yield* TestClock.adjust("59 seconds"); - yield* readRemoteStatus(worktreePath); - assert.equal(yield* Ref.get(fetchAttempts), 2); - assert.lengthOf(warnings, 2); - - yield* TestClock.adjust("1 second"); - yield* readRemoteStatus(cwd); - assert.equal(yield* Ref.get(fetchAttempts), 3); - assert.lengthOf(warnings, 3); }), - ).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), + ).pipe(Effect.provide(layerTest)), ); it.effect.each([ @@ -1104,73 +883,108 @@ it.effect("retries a fetch that lost a ref update to another Git process", () => }).pipe(Effect.provide(layerServerConfig.pipe(Layer.provideMerge(NodeServices.layer)))), ); -it.layer(layerTest)("GitVcsDriver core integration", (it) => { - describe("process environment", () => { - it.effect("preserves the caller locale for general Git subprocesses", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); +describe("rejected git refs", () => { + const remoteUrl = "https://user:token-123@git.example.invalid/org/secret-repo.git"; + const failedPush = `error: failed to push some refs to '${remoteUrl}'`; + const leakedText = [ + "token-123", + "secret-repo", + "git.example.invalid", + "private-branch", + "workflow scope", + ]; + + const failWith = (stderr: string) => { + const spawner = ChildProcessSpawner.make(() => Effect.succeed(makeFailedHandle(stderr))); + const layer = GitVcsDriver.layer.pipe( + Layer.provide(layerServerConfig), + Layer.provideMerge( + Layer.merge( + NodeServices.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ), + ); + return Effect.gen(function* () { + const driver = yield* GitVcsDriver.GitVcsDriver; + return yield* driver + .execute({ + operation: "GitVcsDriver.test.rejectedRef", + cwd: "/repo", + args: ["push", "origin", "HEAD"], + }) + .pipe(Effect.flip); + }).pipe(Effect.provide(layer)); + }; + + it.effect.each([ + { + label: "a ref the remote refused", + stderr: [ + "remote: Unable to determine if workflow can be created; workflow scope may be required.", + `To ${remoteUrl}`, + " ! [remote rejected] private-branch -> private-branch (workflow scope may be required.)", + failedPush, + ], + reason: "push_rejected_by_remote" as const, + detail: "The remote rejected the push.", + }, + { + label: "a non-fast-forward push", + stderr: [ + `To ${remoteUrl}`, + " ! [rejected] private-branch -> private-branch (non-fast-forward)", + failedPush, + ], + reason: "push_rejected_non_fast_forward" as const, + detail: "Pull or rebase", + }, + ])("names $label without quoting stderr", ({ stderr, reason, detail }) => + Effect.gen(function* () { + const error = yield* failWith(stderr.join("\n")); - const locale = yield* git( - cwd, - ["-c", 'alias.print-locale=!printf "%s" "$LC_ALL"', "print-locale"], - { LC_ALL: "zh_CN.UTF-8" }, - ); + assert.deepInclude(error, { reason }); + assert.include(error.detail, detail); + for (const text of leakedText) assert.notInclude(error.message, text); + }), + ); - assert.equal(locale, "zh_CN.UTF-8"); - }), - ); - }); + // A fetch into a diverged local branch prints the same rejected line, but + // never "failed to push some refs". + it.effect("leaves a rejected fetch unclassified", () => + Effect.gen(function* () { + const error = yield* failWith( + [`From ${remoteUrl}`, " ! [rejected] main -> side (non-fast-forward)"].join( + "\n", + ), + ); + + assert.equal(error.reason, undefined); + assert.equal(error.detail, "Git command exited with a non-zero status."); + }), + ); +}); +it.layer(layerTest)("GitVcsDriver core integration", (it) => { describe("structured errors", () => { - it.effect("preserves structured spawn context and the platform cause", () => + it.effect("does not retain git arguments or stderr in command failures", () => Effect.gen(function* () { - const parent = yield* makeTmpDir(); - const pathService = yield* Path.Path; - const cwd = pathService.join(parent, "missing"); + const cwd = yield* makeTmpDir(); const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.initRepo({ cwd }); + const secret = "secret-token-value"; const error = yield* driver .execute({ - operation: "GitVcsDriver.test.missingCwd", + operation: "GitVcsDriver.test.redactedFailure", cwd, - args: ["status", "--short"], + args: ["status", `--unknown-option=${secret}`], }) .pipe(Effect.flip); assert.deepInclude(error, { _tag: "GitCommandError", - operation: "GitVcsDriver.test.missingCwd", - command: "git", - argumentCount: 2, - cwd, - detail: "Failed to spawn Git process.", - }); - if (!(error.cause instanceof PlatformError.PlatformError)) { - return assert.fail("expected the original platform error cause"); - } - assert.equal(error.cause.reason._tag, "NotFound"); - assert.notInclude(error.detail, error.cause.message); - }), - ); - - it.effect("does not retain git arguments or stderr in command failures", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* driver.initRepo({ cwd }); - - const secret = "secret-token-value"; - const error = yield* driver - .execute({ - operation: "GitVcsDriver.test.redactedFailure", - cwd, - args: ["status", `--unknown-option=${secret}`], - }) - .pipe(Effect.flip); - - assert.deepInclude(error, { - _tag: "GitCommandError", - operation: "GitVcsDriver.test.redactedFailure", + operation: "GitVcsDriver.test.redactedFailure", command: "git", argumentCount: 2, cwd, @@ -1185,6 +999,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + // regression: #8645 name the cause of a failed git command it.effect("names the branch conflict behind a failed worktree add", () => Effect.gen(function* () { const parent = yield* makeTmpDir(); @@ -1216,6 +1031,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + // regression: #8645 name the cause of a failed git command it.effect("names a missing repository behind a failed command", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -1239,33 +1055,85 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("appends the reason tag to a caller-supplied detail", () => + it.effect.each([ + { action: "worktree add", detail: "git worktree add failed" }, + { action: "switch", detail: "git checkout failed" }, + ])( + "reports a missing ref during $action with stable, redacted diagnostics", + ({ action, detail }) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const path = yield* Path.Path; + const refName = "private/deleted-base"; + const locales: Array = []; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => { + if ( + ChildProcess.isStandardCommand(command) && + (command.args.includes("worktree") || command.args[0] === "checkout") + ) { + locales.push(command.options.env?.LC_ALL); + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const error = + action === "switch" + ? yield* driver.switchRef({ cwd, refName }).pipe(Effect.flip) + : yield* driver + .createWorktree({ + cwd, + refName, + newRefName: "t3/new-thread", + path: path.join(cwd, "worktree"), + }) + .pipe(Effect.flip); + + assert.deepInclude(error, { _tag: "GitCommandError", detail, reason: "ref_not_found" }); + assert.include(error.message, `${detail} (ref_not_found)`); + assert.notInclude(error.message, refName); + assert.notInclude(yield* encodeGitCommandError(error), refName); + assert.deepEqual(locales, ["C"]); + assert.notProperty(error, "stderr"); + assert.notProperty(error, "args"); + }), + ); + + it.effect.each([ + // Git cannot tell a missing revision from a missing file in these. + { label: "an argument that may be a path", args: ["log", "-1", "missing"] }, + { + label: "a pathspec worded like a diagnostic", + args: ["checkout", "HEAD", "--", "fatal: invalid reference: missing"], + }, + // The tag exists; it names a tree, which git reports in the same words. + { + label: "a worktree from a non-commit", + args: ["worktree", "add", "tree-worktree", "tree-tag"], + }, + ])("leaves $label unclassified rather than calling it a missing ref", ({ args }) => Effect.gen(function* () { - const parent = yield* makeTmpDir(); - const pathService = yield* Path.Path; - const cwd = pathService.join(parent, "repo"); - const fileSystem = yield* FileSystem.FileSystem; - yield* fileSystem.makeDirectory(cwd); + const cwd = yield* makeTmpDir(); const driver = yield* GitVcsDriver.GitVcsDriver; yield* initRepoWithCommit(cwd); - yield* git(cwd, [ - "worktree", - "add", - pathService.join(parent, "taken"), - "-b", - "taken-branch", - ]); + if (args.includes("tree-tag")) { + yield* git(cwd, ["tag", "tree-tag", "HEAD^{tree}"]); + } const error = yield* driver - .createWorktree({ + .execute({ + operation: "GitVcsDriver.test.ambiguousMissingName", cwd, - refName: "taken-branch", - path: pathService.join(parent, "second"), + args, + env: { LC_ALL: "C" }, }) .pipe(Effect.flip); - assert.equal(error.detail, "git worktree add failed"); - assert.include(error.message, "git worktree add failed (branch_checked_out_in_worktree)"); + assert.notProperty(error, "reason"); }), ); @@ -1365,7 +1233,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("does not read remote hook output as a git failure reason", () => + it.effect("reads a hook-declined push from git's rejection line, not the hook's output", () => Effect.gen(function* () { const parent = yield* makeTmpDir(); const pathService = yield* Path.Path; @@ -1394,40 +1262,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }) .pipe(Effect.flip); - assert.notProperty(error, "reason"); - assert.notInclude(error.message, "(authentication_failed)"); - }), - ); - - it.effect("does not read hook output as a git failure reason", () => - Effect.gen(function* () { - const parent = yield* makeTmpDir(); - const pathService = yield* Path.Path; - const remote = pathService.join(parent, "origin.git"); - const cwd = pathService.join(parent, "work"); - const fileSystem = yield* FileSystem.FileSystem; - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* fileSystem.makeDirectory(cwd); - yield* initRepoWithCommit(cwd); - yield* git(cwd, ["init", "--bare", remote]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* writeTextFile( - cwd, - ".git/hooks/pre-push", - '#!/bin/sh\necho "authentication failed" >&2\nexit 1\n', - ); - yield* fileSystem.chmod(pathService.join(cwd, ".git/hooks/pre-push"), 0o755); - - const error = yield* driver - .execute({ - operation: "GitVcsDriver.test.hookOutput", - cwd, - args: ["push", "origin", "HEAD"], - env: { LC_ALL: "C" }, - }) - .pipe(Effect.flip); - - assert.notProperty(error, "reason"); + assert.deepInclude(error, { reason: "push_rejected_by_remote" }); assert.notInclude(error.message, "(authentication_failed)"); }), ); @@ -1501,31 +1336,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.deepStrictEqual(refs.refs, []); }), ); - - it.effect("does not wrap a remove-worktree command failure in a synthetic error", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const pathService = yield* Path.Path; - const fileSystem = yield* FileSystem.FileSystem; - const notAWorktree = pathService.join(cwd, "not-a-worktree"); - yield* fileSystem.makeDirectory(notAWorktree); - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* driver.initRepo({ cwd }); - - const error = yield* driver.removeWorktree({ cwd, path: notAWorktree }).pipe(Effect.flip); - - assert.deepInclude(error, { - _tag: "GitCommandError", - operation: "GitVcsDriver.removeWorktree", - command: "git", - argumentCount: 6, - cwd, - }); - assert.notProperty(error, "cause"); - assert.notProperty(error, "stderr"); - assert.notInclude(error.detail, "Git command failed in"); - }), - ); }); describe("review diff previews", () => { @@ -1651,60 +1461,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("keeps the final path when NUL-separated git output is complete", () => - Effect.sync(() => { - const paths = splitNullSeparatedGitStdoutPaths({ - stdout: "complete.txt\0final.txt", - stdoutTruncated: false, - }); - - assert.deepStrictEqual(paths, ["complete.txt", "final.txt"]); - }), - ); - - it.effect("honors whitespace filtering for worktree and branch previews", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* git(cwd, ["checkout", "-b", "feature/whitespace"]); - yield* writeTextFile(cwd, "README.md", "# test\n"); - yield* git(cwd, ["add", "README.md"]); - yield* git(cwd, ["commit", "-m", "change whitespace"]); - yield* writeTextFile(cwd, "README.md", "# test\n"); - - const included = yield* driver.getReviewDiffPreview({ - cwd, - baseRef: initialBranch, - ignoreWhitespace: false, - }); - const ignored = yield* driver.getReviewDiffPreview({ - cwd, - baseRef: initialBranch, - ignoreWhitespace: true, - }); - - assert.isNotEmpty(included.sources.find((source) => source.kind === "working-tree")?.diff); - assert.isNotEmpty(included.sources.find((source) => source.kind === "branch-range")?.diff); - assert.strictEqual( - ignored.sources.find((source) => source.kind === "working-tree")?.diff, - "", - ); - assert.deepStrictEqual( - ignored.sources.find((source) => source.kind === "working-tree")?.files, - [], - ); - assert.deepStrictEqual( - ignored.sources.find((source) => source.kind === "branch-range")?.files, - [], - ); - assert.strictEqual( - ignored.sources.find((source) => source.kind === "branch-range")?.diff, - "", - ); - }), - ); - it.effect("keeps a/ and b/ patch prefixes when the repository disables them", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -1869,21 +1625,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("keeps untracked files visible before the first commit", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* driver.initRepo({ cwd }); - yield* writeTextFile(cwd, "untracked.txt", "visible before HEAD\n"); - - const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); - const source = preview.sources.find((candidate) => candidate.kind === "working-tree"); - - assert.include(source?.diff, "visible before HEAD"); - assert.equal(source?.truncated, false); - }), - ); - it.effect.each([false, true])( "keeps the preceding second cached in review previews (split: %s)", (splitIndex) => @@ -2139,32 +1880,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("attributes working-tree filesystem failures to the failing operation", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - - const error = yield* driver - .getReviewDiffFileContents( - makeReviewDiffFileContentsInput(cwd, { - changeType: "new", - oldPath: "missing.ts", - newPath: "missing.ts", - }), - ) - .pipe(Effect.flip); - - assert.deepInclude(error, { - _tag: "GitCommandError", - operation: "GitVcsDriver.getReviewDiffFileContents.workingTree.fs.realPath", - command: "fs.realPath", - cwd, - detail: "Could not resolve diff file 'missing.ts'.", - }); - }), - ); - it.effect("loads new and deleted files without reading their missing side", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -2288,6 +2003,159 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("honors configured remote-qualified bases for Changes and ahead counts", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fork = yield* makeTmpDir(); + const upstream = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(fork, ["init", "--bare"]); + yield* git(upstream, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", fork]); + yield* git(cwd, ["remote", "add", "upstream", upstream]); + yield* git(cwd, ["remote", "add", "canonical/team", upstream]); + yield* git(cwd, ["push", "origin", "main"]); + yield* writeTextFile(cwd, "upstream.txt", "unrelated upstream work\n"); + yield* git(cwd, ["add", "upstream.txt"]); + yield* git(cwd, ["commit", "-m", "upstream work"]); + yield* git(cwd, ["push", "upstream", "main"]); + yield* git(cwd, ["fetch", "canonical/team"]); + yield* git(cwd, ["branch", "release/v2"]); + yield* git(cwd, ["checkout", "-b", "feature/configured-base"]); + yield* writeTextFile(cwd, "feature.txt", "intended branch change\n"); + yield* git(cwd, ["add", "feature.txt"]); + yield* git(cwd, ["commit", "-m", "feature work"]); + + for (const baseRef of ["upstream/main", "canonical/team/main", "release/v2"]) { + yield* git(cwd, ["config", "branch.feature/configured-base.gh-merge-base", baseRef]); + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { baseRef, insertions: 1, deletions: 0 }); + assert.strictEqual(status.aheadCount, 1); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.strictEqual(changes.baseRef, baseRef); + assert.deepStrictEqual(changes.files, [ + { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, + ]); + } + + for (const baseRef of ["origin/main", "upstream/missing", "main"]) { + yield* git(cwd, ["config", "branch.feature/configured-base.gh-merge-base", baseRef]); + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "origin/main", + insertions: 2, + deletions: 0, + }); + assert.strictEqual(status.aheadCount, 2); + } + + yield* git(cwd, [ + "config", + "branch.feature/configured-base.gh-merge-base", + "refs/remotes/upstream/main", + ]); + yield* writeTextFile(cwd, "upstream.txt", "feature edits upstream file\n"); + for (const shadowRef of ["refs/heads/upstream/main", "refs/tags/upstream/main"]) { + yield* git(cwd, ["update-ref", shadowRef, "HEAD~2"]); + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "refs/remotes/upstream/main", + insertions: 2, + deletions: 1, + }); + assert.strictEqual(status.aheadCount, 1); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.strictEqual(changes.baseRef, "refs/remotes/upstream/main"); + assert.deepStrictEqual(changes.files, [ + { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, + { path: "upstream.txt", previousPath: null, additions: 1, deletions: 1 }, + ]); + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { + sourceKind: "branch-range", + baseRef: changes.baseRef, + headRef: "feature/configured-base", + oldPath: "upstream.txt", + newPath: "upstream.txt", + }), + ); + assert.deepStrictEqual(contents, { + oldContents: "unrelated upstream work\n", + newContents: "feature edits upstream file\n", + }); + yield* git(cwd, ["update-ref", "-d", shadowRef]); + } + }), + ); + + it.effect("keeps local branch bases consistent when tags share their names", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + const initialCommit = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["update-ref", "refs/tags/main", initialCommit]); + yield* git(cwd, ["update-ref", "refs/tags/release/v2", initialCommit]); + yield* writeTextFile(cwd, "README.md", "# test\nbase work\n"); + yield* git(cwd, ["commit", "-am", "base work"]); + yield* git(cwd, ["branch", "release/v2", "HEAD"]); + yield* git(cwd, ["checkout", "-b", "feature/local-base", "HEAD"]); + yield* writeTextFile(cwd, "README.md", "# test\nbase work\nfeature work\n"); + yield* git(cwd, ["commit", "-am", "feature work"]); + + for (const configuredBase of [undefined, "main", "release/v2"]) { + if (configuredBase !== undefined) { + yield* git(cwd, ["config", "branch.feature/local-base.gh-merge-base", configuredBase]); + } + const baseRef = configuredBase ?? "main"; + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { baseRef, insertions: 1, deletions: 0 }); + assert.strictEqual(status.aheadCount, 1); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.strictEqual(changes.baseRef, baseRef); + assert.deepStrictEqual(changes.files, [ + { path: "README.md", previousPath: null, additions: 1, deletions: 0 }, + ]); + const scoped = yield* driver.getReviewDiffPreview({ + cwd, + baseRef, + file: { path: "README.md", previousPath: null, sourceKind: "branch-range" }, + }); + const scopedChanges = scoped.sources.find((source) => source.kind === "branch-range")!; + assert.deepStrictEqual(scopedChanges.files, changes.files); + assert.strictEqual(scopedChanges.diff, changes.diff); + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { + sourceKind: "branch-range", + baseRef: changes.baseRef, + headRef: "feature/local-base", + }), + ); + assert.deepStrictEqual(contents, { + oldContents: "# test\nbase work\n", + newContents: "# test\nbase work\nfeature work\n", + }); + } + + for (const baseRef of ["refs/tags/main", initialCommit, "HEAD~2"]) { + const contents = yield* driver.getReviewDiffFileContents( + makeReviewDiffFileContentsInput(cwd, { + sourceKind: "branch-range", + baseRef, + headRef: "feature/local-base", + }), + ); + assert.strictEqual(contents.oldContents, "# test\n"); + } + }), + ); + it.effect("Changes accepts an explicit base on a detached HEAD and rejects a bad one", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -2342,28 +2210,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("skips Changes totals instead of indexing thousands of untracked files", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - yield* Effect.forEach( - Array.from({ length: 5_001 }, (_, index) => `bulk/${index}.txt`), - (file) => writeTextFile(cwd, file, "x\n"), - { concurrency: 32, discard: true }, - ); - yield* writeTextFile(cwd, "README.md", "changed\n"); - - const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); - assert.isTrue(status.hasWorkingTreeChanges); - assert.isUndefined(status.branchChanges); - - const preview = yield* driver.getReviewDiffPreview({ cwd }); - assert.isNotEmpty(preview.sources); - assert.isTrue(preview.sources.every((source) => source.truncated)); - }), - ); - it.effect("Changes does not show newer base commits as deletions", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -2416,6 +2262,94 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reads Changes totals without minimizing and keeps review diffs minimal", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["config", "diff.algorithm", "myers"]); + // Repeated lines make the default and minimal algorithms choose different edits. + const lines = Array.from({ length: 2000 }, (_, index) => index); + yield* writeTextFile( + cwd, + "repeated.txt", + lines.map((index) => `${(index ^ (index >> 3)) % 16}\n`).join(""), + ); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "repeated lines"]); + yield* git(cwd, ["checkout", "-b", "feature/totals"]); + yield* writeTextFile( + cwd, + "repeated.txt", + lines.map((index) => `${(index ^ (index >> 5)) % 16}\n`).join(""), + ); + const defaultStat = yield* git(cwd, ["diff", "--numstat", "HEAD", "--"]); + const minimalStat = yield* git(cwd, ["diff", "--minimal", "--numstat", "HEAD", "--"]); + assert.notEqual(defaultStat, minimalStat); + const [insertions, deletions] = defaultStat.split("\t"); + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: initialBranch, + insertions: Number(insertions), + deletions: Number(deletions), + }); + + const [additions, removals] = minimalStat.split("\t"); + const minimalPatch = yield* git(cwd, [ + "diff", + "--minimal", + "--patch", + "--no-color", + "--no-ext-diff", + "--no-textconv", + "--src-prefix=a/", + "--dst-prefix=b/", + "HEAD", + "--", + ]); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + for (const source of preview.sources) { + assert.deepStrictEqual(source.files, [ + { + path: "repeated.txt", + previousPath: null, + additions: Number(additions), + deletions: Number(removals), + }, + ]); + assert.strictEqual(source.diff.trim(), minimalPatch); + } + }), + ); + + it.effect.skipIf(!symlinksSupported)( + "lists the real repository through a symlink when a decoy repo occupies the lexical common dir", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const sandbox = yield* makeTmpDir("git-symlink-subdir-"); + yield* initRepoWithCommit(sandbox); + yield* git(sandbox, ["branch", "-M", "decoy-only"]); + const repo = pathService.join(sandbox, "repo"); + const link = pathService.join(sandbox, "nest", "link"); + yield* fileSystem.makeDirectory(pathService.join(repo, "sub", "dir"), { + recursive: true, + }); + yield* fileSystem.makeDirectory(pathService.dirname(link), { recursive: true }); + yield* fileSystem.symlink(pathService.join(repo, "sub", "dir"), link); + + yield* initRepoWithCommit(repo); + yield* git(repo, ["checkout", "-b", "real-only"]); + + // The decoy must exist before the first lookup, which caches repository paths. + const refs = yield* (yield* GitVcsDriver.GitVcsDriver).listRefs({ cwd: link }); + assert.isTrue(refs.isRepo); + assert.isFalse(refs.refs.some((ref) => ref.name === "decoy-only")); + assert.isTrue(refs.refs.some((ref) => ref.name === "real-only")); + }), + ); + it.effect("reads Changes totals with untracked files when requested", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -2440,33 +2374,76 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reports non-repository directories without failing", () => + it.effect("Changes compares the default branch with its tracking upstream, not origin", () => Effect.gen(function* () { + // `origin` is a fork whose main is behind; the checkout tracks the + // canonical repository through a second remote. + const canonical = yield* makeTmpDir(); + yield* initRepoWithCommit(canonical); + yield* git(canonical, ["branch", "-M", "main"]); + const fork = yield* makeTmpDir(); + yield* git(fork, ["clone", "--quiet", canonical, "."]); + yield* writeTextFile(canonical, "canonical.txt", "one\ntwo\nthree\n"); + yield* git(canonical, ["add", "canonical.txt"]); + yield* git(canonical, ["commit", "-m", "canonical moves ahead"]); + const cwd = yield* makeTmpDir(); const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["init", "-b", "main"]); + yield* git(cwd, ["remote", "add", "origin", fork]); + yield* git(cwd, ["remote", "add", "upstream", canonical]); + yield* git(cwd, ["fetch", "--quiet", "--all"]); + yield* git(cwd, ["reset", "--hard", "--quiet", "upstream/main"]); + yield* git(cwd, ["branch", "--set-upstream-to=upstream/main", "main"]); - const refs = yield* driver.listRefs({ cwd }); - assert.equal(refs.isRepo, false); - assert.deepStrictEqual(refs.refs, []); + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "upstream/main", + insertions: 0, + deletions: 0, + }); + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.strictEqual(changes.baseRef, "upstream/main"); + assert.deepStrictEqual(changes.files, []); + + // Without an upstream the primary remote's copy stays the base. + yield* git(cwd, ["branch", "--unset-upstream", "main"]); + const untracked = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(untracked.branchChanges, { + baseRef: "origin/main", + insertions: 3, + deletions: 0, + }); }), ); - it.effect("reports refName and dirty state for a repository", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* writeTextFile(cwd, "feature.ts", "export const value = 1;\n"); - - const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd); + it.effect( + "counts many untracked files exactly while collapsing their directory in status", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(cwd, ["checkout", "-b", "feature/many-untracked"]); + yield* Effect.forEach( + Array.from({ length: 1_001 }, (_, index) => `bulk/${index}.txt`), + (file) => writeTextFile(cwd, file, "one\ntwo\n"), + { concurrency: 32, discard: true }, + ); - assert.equal(status.isRepo, true); - assert.equal(status.branch, initialBranch); - assert.equal(status.hasWorkingTreeChanges, true); - assert.include( - status.workingTree.files.map((file) => file.path), - "feature.ts", - ); - }), + const status = yield* driver.statusDetailsLocal(cwd, { includeBranchChanges: true }); + assert.deepStrictEqual(status.branchChanges, { + baseRef: "main", + insertions: 2_002, + deletions: 0, + }); + assert.deepStrictEqual( + status.workingTree.files.map((file) => file.path), + ["bulk/"], + ); + }), ); it.effect("reports changes to a file named HEAD", () => @@ -2490,91 +2467,98 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reports default-branch delta separately from upstream delta", () => + it.effect("reports renamed and non-ASCII files by paths that can be committed", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/synced"]); - yield* writeTextFile(cwd, "feature.txt", "feature\n"); - yield* git(cwd, ["add", "feature.txt"]); - yield* git(cwd, ["commit", "-m", "feature commit"]); - yield* git(cwd, ["push", "-u", "origin", "feature/synced"]); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "src/old.ts", "one\ntwo\nthree\n"); + yield* writeTextFile(cwd, "café notes.md", "draft\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "add files"]); + yield* git(cwd, ["mv", "src/old.ts", "src/new.ts"]); + yield* writeTextFile(cwd, "src/new.ts", "one\ntwo\nthree\nfour\n"); + yield* writeTextFile(cwd, "café notes.md", "draft\nedit\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; - const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd); + const status = yield* driver.statusDetails(cwd); - assert.equal(status.hasUpstream, true); - assert.equal(status.aheadCount, 0); - assert.equal(status.behindCount, 0); - assert.equal(status.aheadOfDefaultCount, 1); + assert.deepEqual(status.workingTree.files, [ + { path: "café notes.md", insertions: 1, deletions: 0 }, + { path: "src/new.ts", insertions: 1, deletions: 0 }, + { path: "src/old.ts", insertions: 0, deletions: 0 }, + ]); + yield* driver.commit(cwd, "Commit selection", "", { + stage: { filePaths: status.workingTree.files.map((file) => file.path) }, + }); + assert.equal(yield* git(cwd, ["status", "--porcelain"]), ""); }), ); - it.effect("can read local files without traversing revision history", () => + it.effect("commits selected files from a nested project directory", () => Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-vcs-driver-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/local-only"]); - yield* writeTextFile(cwd, "feature.txt", "feature\n"); - yield* git(cwd, ["add", "feature.txt"]); - yield* git(cwd, ["commit", "-m", "feature commit"]); - yield* writeTextFile(cwd, "feature.txt", "feature\nlocal edit\n"); - yield* writeTextFile(cwd, "untracked.txt", "untracked\n"); + const path = yield* Path.Path; + // A root basename ending in whitespace catches a root lookup that trims Git's output. + const cwd = path.join(yield* makeTmpDir(), "repo "); + yield* (yield* FileSystem.FileSystem).makeDirectory(cwd); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "nested/tracked.txt", "one\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "add nested file"]); + yield* writeTextFile(cwd, "nested/tracked.txt", "one\ntwo\n"); + yield* writeTextFile(cwd, "nested/new.txt", "new\n"); + yield* writeTextFile(cwd, "README.md", "# test\nleft out\n"); + const nestedCwd = path.join(cwd, "nested"); + const driver = yield* GitVcsDriver.GitVcsDriver; - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const commands: ReadonlyArray[] = []; - const spawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) { - return yield* Effect.die("expected a standard Git command"); - } - commands.push(command.args); - return yield* delegate.spawn(command); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provide(layerServerConfig), + const status = yield* driver.statusDetails(nestedCwd); + + assert.deepEqual(status.workingTree.files, [ + { path: "nested/new.txt", insertions: 0, deletions: 0 }, + { path: "nested/tracked.txt", insertions: 1, deletions: 0 }, + { path: "README.md", insertions: 1, deletions: 0 }, + ]); + // The root is what the paths above are relative to, not the nested cwd, and it keeps + // the trailing space so the resolved editor target is the file that exists. + assert.equal(status.workingTree.rootPath, NodeFS.realpathSync.native(cwd)); + assert.equal( + NodeFS.existsSync(path.join(status.workingTree.rootPath!, "nested", "new.txt")), + true, ); + yield* driver.commit(nestedCwd, "Commit nested selection", "", { + stage: { filePaths: ["nested/new.txt", "nested/tracked.txt"] }, + }); + assert.equal(yield* git(cwd, ["status", "--porcelain"]), "M README.md"); + }), + ); - for (const hasUpstream of [false, true]) { - if (hasUpstream) { - yield* git(cwd, ["push", "-u", "origin", "feature/local-only"]); - } - commands.length = 0; - const local = yield* driver.statusDetailsLocal(cwd, { includeDivergence: false }); - assert.isFalse(commands.some((args) => args.includes("rev-list"))); - assert.isTrue(commands.some((args) => args.includes("--no-ahead-behind"))); - assert.equal(local.hasUpstream, hasUpstream); - assert.isTrue(local.hasWorkingTreeChanges); - assert.deepEqual(local.workingTree.files, [ - { path: "feature.txt", insertions: 1, deletions: 0 }, - { path: "untracked.txt", insertions: 0, deletions: 0 }, - ]); + it.effect("reports the linked worktree as the root of a nested directory in it", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const worktreePath = yield* makeTmpDir("git-vcs-driver-linked-"); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "nested/tracked.txt", "one\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "add nested file"]); + yield* git(cwd, ["worktree", "add", "-b", "feature/linked", worktreePath]); + yield* writeTextFile(worktreePath, "nested/tracked.txt", "one\ntwo\n"); + yield* writeTextFile(worktreePath, "nested/new.txt", "new\n"); + const nestedCwd = (yield* Path.Path).join(worktreePath, "nested"); + const driver = yield* GitVcsDriver.GitVcsDriver; - commands.length = 0; - const full = yield* driver.statusDetailsLocal(cwd); - assert.isTrue(commands.some((args) => args.includes("rev-list"))); - assert.equal(full.aheadCount, hasUpstream ? 0 : 1); - assert.equal(full.aheadOfDefaultCount, 1); - assert.deepEqual(local, { - ...full, - aheadCount: 0, - behindCount: 0, - aheadOfDefaultCount: 0, - }); - } + const status = yield* driver.statusDetails(nestedCwd); + + assert.deepEqual(status.workingTree.files, [ + { path: "nested/new.txt", insertions: 0, deletions: 0 }, + { path: "nested/tracked.txt", insertions: 1, deletions: 0 }, + ]); + assert.equal( + NodeFS.realpathSync.native(status.workingTree.rootPath!), + NodeFS.realpathSync.native(worktreePath), + ); }), ); - it.effect("reports remote divergence without reading working-tree details", () => + it.effect("reports default-branch delta separately from upstream delta", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-vcs-driver-remote-"); @@ -2582,23 +2566,18 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(remote, ["init", "--bare"]); yield* git(cwd, ["remote", "add", "origin", remote]); yield* git(cwd, ["push", "-u", "origin", initialBranch]); - yield* git(cwd, ["checkout", "-b", "feature/remote-status"]); + yield* git(cwd, ["checkout", "-b", "feature/synced"]); yield* writeTextFile(cwd, "feature.txt", "feature\n"); yield* git(cwd, ["add", "feature.txt"]); yield* git(cwd, ["commit", "-m", "feature commit"]); - yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]); - yield* writeTextFile(cwd, "untracked.txt", "local-only\n"); + yield* git(cwd, ["push", "-u", "origin", "feature/synced"]); - const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd); + const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd); - assert.equal(status.isRepo, true); - assert.equal(status.branch, "feature/remote-status"); assert.equal(status.hasUpstream, true); assert.equal(status.aheadCount, 0); assert.equal(status.behindCount, 0); assert.equal(status.aheadOfDefaultCount, 1); - assert.notProperty(status, "workingTree"); - assert.notProperty(status, "hasWorkingTreeChanges"); }), ); @@ -2838,7 +2817,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("refName operations", () => { - it.effect("optionally includes remote refs that match local branches", () => + it.effect("lists root and upstream metadata and optionally includes matching remote refs", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-vcs-driver-remote-"); @@ -2846,6 +2825,10 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(remote, ["init", "--bare"]); yield* git(cwd, ["remote", "add", "origin", remote]); yield* git(cwd, ["push", "-u", "origin", initialBranch]); + yield* git(cwd, ["remote", "add", "team/upstream", remote]); + yield* git(cwd, ["push", "team/upstream", "HEAD:refs/heads/feature/a"]); + yield* git(cwd, ["branch", "--track", "feature/a", "team/upstream/feature/a"]); + yield* git(cwd, ["branch", "--no-track", "local-only"]); const driver = yield* GitVcsDriver.GitVcsDriver; const deduplicated = yield* driver.listRefs({ cwd }); @@ -2854,7 +2837,19 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { false, ); - const complete = yield* driver.listRefs({ cwd, includeMatchingRemoteRefs: true }); + const worktreePath = yield* makeTmpDir("git-vcs-driver-worktree-"); + yield* git(cwd, ["worktree", "add", worktreePath, "feature/a"]); + yield* writeTextFile(worktreePath, "packages/app/file.txt", "nested project\n"); + const pathService = yield* Path.Path; + const nestedCwd = pathService.join(worktreePath, "packages", "app"); + const complete = yield* driver.listRefs({ + cwd: nestedCwd, + includeMatchingRemoteRefs: true, + }); + const untracked = complete.refs.find((ref) => ref.name === "local-only"); + assert.ok(untracked); + assert.equal("upstreamRef" in untracked, false); + assert.deepEqual(decodeVcsRef(untracked), untracked); assert.equal( complete.refs.some((ref) => ref.name === initialBranch), true, @@ -2873,6 +2868,25 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.equal(remoteOnly.refs.length, 1); assert.equal(remoteOnly.refs[0]?.name, `origin/${initialBranch}`); assert.equal(remoteOnly.refs[0]?.isRemote, true); + + const tracked = complete.refs.find((ref) => ref.name === "feature/a"); + assert.ok(tracked); + assert.deepEqual(decodeVcsRef(tracked), { + ...tracked, + upstreamRef: "refs/remotes/team/upstream/feature/a", + }); + const aliasCwd = pathService.join(cwd, "worktree-alias"); + NodeFS.symlinkSync(worktreePath, aliasCwd, "junction"); + const aliased = yield* driver.listRefs({ cwd: aliasCwd }); + const expected = [ + { ...complete, isAtRepositoryRoot: false }, + { ...aliased, isAtRepositoryRoot: true }, + ]; + assert.deepEqual([complete, aliased], expected); + assert.deepEqual( + [decodeVcsListRefsResult(complete), decodeVcsListRefsResult(aliased)], + expected, + ); }), ); @@ -2896,32 +2910,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("creates, checks out, renames, and lists refs", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - - yield* driver.createRef({ cwd, refName: "feature/original" }); - const switchRef = yield* driver.switchRef({ cwd, refName: "feature/original" }); - assert.equal(switchRef.refName, "feature/original"); - - const renamed = yield* driver.renameBranch({ - cwd, - oldBranch: "feature/original", - newBranch: "feature/renamed", - }); - assert.equal(renamed.branch, "feature/renamed"); - assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/renamed"); - - const refs = yield* driver.listRefs({ cwd }); - assert.equal( - refs.refs.find((refName) => refName.name === "feature/renamed")?.current, - true, - ); - }), - ); - it.effect("preserves exact custom names and refuses collisions without a suffix", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -2948,23 +2936,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("returns the existing refName when rename source and target match", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - - const current = yield* git(cwd, ["branch", "--show-current"]); - const result = yield* driver.renameBranch({ - cwd, - oldBranch: current, - newBranch: current, - }); - - assert.equal(result.branch, current); - }), - ); - it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3041,89 +3012,18 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.deepEqual(yield* driver.listLocalBranchNames(cwd), branches); assert.isFalse(yield* fileSystem.exists(pathService.join(worktrees, "wt"))); - // A lone "-" is still the previous checkout. yield* git(cwd, ["checkout", "-q", "keep"]); yield* git(cwd, ["checkout", "-q", initialBranch]); assert.equal((yield* driver.switchRef({ cwd, refName: "-" })).refName, "keep"); const previous = yield* driver.createWorktree({ cwd, path: pathService.join(worktrees, "previous"), - refName: "-", - }); - assert.equal( - yield* git(previous.worktree.path, ["branch", "--show-current"]), - initialBranch, - ); - }), - ); - - it.effect("still creates and reuses remote tracking branches and allows detached refs", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-remote-"); - const { initialBranch } = yield* initRepoWithCommit(cwd); - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const commands: Array> = []; - const spawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (ChildProcess.isStandardCommand(command)) commands.push(command.args); - return yield* delegate.spawn(command); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provide(layerServerConfig), - ); - const assertCheckout = ( - checkoutArgs: ReadonlyArray, - existenceReads: number, - trackingReads: number, - ) => { - assert.deepEqual( - commands.filter((args) => args[0] === "checkout"), - [checkoutArgs], - ); - assert.equal(commands.filter((args) => args[0] === "show-ref").length, existenceReads); - assert.equal(commands.filter((args) => args[0] === "for-each-ref").length, trackingReads); - assert.deepEqual( - commands.filter((args) => args[0] === "branch"), - [["branch", "--show-current"]], - ); - }; - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", "HEAD:refs/heads/remote-only"]); - - for (let attempt = 0; attempt < 2; attempt += 1) { - commands.length = 0; - const result = yield* driver.switchRef({ cwd, refName: "origin/remote-only" }); - assert.equal(result.refName, attempt === 0 ? "remote-only" : "review/renamed"); - assertCheckout( - attempt === 0 - ? ["checkout", "--track", "origin/remote-only", "--"] - : ["checkout", "review/renamed", "--"], - attempt === 0 ? 3 : 2, - 1, - ); - assert.equal( - yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), - "origin/remote-only", - ); - if (attempt === 0) yield* git(cwd, ["branch", "-m", "review/renamed"]); - yield* driver.switchRef({ cwd, refName: initialBranch }); - } - yield* git(cwd, ["branch", "origin/remote-only"]); - commands.length = 0; - const shadowed = yield* driver.switchRef({ cwd, refName: "origin/remote-only" }); - assert.equal(shadowed.refName, "origin/remote-only"); - assertCheckout(["checkout", "origin/remote-only", "--"], 2, 0); - - const commit = yield* git(cwd, ["rev-parse", "HEAD"]); - commands.length = 0; - const detached = yield* driver.switchRef({ cwd, refName: commit }); - assert.equal(detached.refName, null); - assertCheckout(["checkout", commit, "--"], 2, 0); - assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), commit); + refName: "-", + }); + assert.equal( + yield* git(previous.worktree.path, ["branch", "--show-current"]), + initialBranch, + ); }), ); }); @@ -3165,7 +3065,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["rev-parse", "HEAD"]), ); assert.equal( - yield* git(cwd, ["config", "branch.feature/parallel.gh-merge-base"]), + yield* git(cwd, ["config", "branch.feature/parallel.t3-merge-base"]), initialBranch, ); for (const [configured, expected] of [ @@ -3216,7 +3116,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), commit); assert.equal( - yield* driver.readConfigValue(cwd, "branch.feature/revision.gh-merge-base"), + yield* driver.readConfigValue(cwd, "branch.feature/revision.t3-merge-base"), null, ); }), @@ -3241,7 +3141,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); assert.equal( - yield* driver.readConfigValue(cwd, "branch.feature/branch.gh-merge-base"), + yield* driver.readConfigValue(cwd, "branch.feature/branch.t3-merge-base"), baseBranch, ); }), @@ -3260,17 +3160,22 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const commit = yield* git(cwd, ["rev-parse", "origin/release/v2"]); const path = yield* Path.Path; const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "remote"); yield* driver.createWorktree({ cwd, - path: path.join(yield* makeTmpDir("git-worktrees-"), "remote"), + path: worktreePath, refName: commit, newRefName: "feature/remote", baseRefName: baseRef, }); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; assert.equal( - yield* driver.readConfigValue(cwd, "branch.feature/remote.gh-merge-base"), - "release/v2", + yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), + commit, ); }), ); @@ -3322,9 +3227,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const fileSystem = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; - // Git refuses `file:` submodule transports by default (CVE-2022-39253) - // and ignores repo-level config for it, so a local fixture needs the - // env allowance. Real submodules are https/ssh and need none of this. + // Git blocks file submodule transports (CVE-2022-39253) despite repo config; local fixtures need env permission. const previousAllowedProtocol = process.env.GIT_ALLOW_PROTOCOL; process.env.GIT_ALLOW_PROTOCOL = "file"; yield* Effect.addFinalizer(() => @@ -3528,84 +3431,95 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reports checkout progress during parallel worktree creation", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - for (let index = 0; index < 200; index += 1) { - yield* writeTextFile(cwd, `file-${index}.txt`, `${index}\n`); - } - yield* git(cwd, ["add", "."]); - yield* git(cwd, ["commit", "-m", "add files"]); - const pathService = yield* Path.Path; - const worktreePath = pathService.join( - yield* makeTmpDir("git-worktrees-"), - "progress-worktree", - ); - const driver = yield* GitVcsDriver.GitVcsDriver; - const seen = yield* Ref.make>( - [], - ); - const claimed = yield* Ref.make<{ path: string; existed: boolean } | null>(null); - - yield* driver.createWorktree( - { cwd, path: worktreePath, refName: initialBranch, newRefName: "feature/progress" }, - { - progress: { - onWorktreeClaimed: (path) => - Ref.set(claimed, { path, existed: NodeFS.existsSync(path) }), - onCheckoutProgress: (update) => Ref.update(seen, (all) => [...all, update]), - }, - }, - ); - assert.deepEqual(yield* Ref.get(claimed), { path: worktreePath, existed: true }); - - const updates = yield* Ref.get(seen); - assert.isAbove(updates.length, 1); - assert.equal(updates.at(-1)?.percent, 100); - assert.equal(updates.at(-1)?.total, 201); - const completed = updates.map((update) => update.completed); - assert.deepEqual( - completed, - completed.toSorted((a, b) => a - b), - ); - }), - ); - - it.effect("creates and removes a worktree and its new local branch", () => + it.effect("still creates the worktree when the base-ref config is locked", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); const pathService = yield* Path.Path; - const worktreePath = pathService.join( - yield* makeTmpDir("git-worktrees-"), - "feature-worktree", - ); + const fileSystem = yield* FileSystem.FileSystem; + const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "locked-config"); + yield* writeTextFile(cwd, ".git/config.lock", ""); const driver = yield* GitVcsDriver.GitVcsDriver; const created = yield* driver.createWorktree({ cwd, path: worktreePath, refName: initialBranch, - newRefName: "feature/worktree", + newRefName: "feature/locked-config", + baseRefName: initialBranch, }); - assert.equal(created.worktree.path, worktreePath); - assert.equal(created.worktree.refName, "feature/worktree"); - assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "feature/worktree"); - - yield* driver.removeWorktree({ cwd, path: worktreePath }); - yield* driver.deleteLocalBranch({ - cwd, - refName: "feature/worktree", - force: true, + assert.deepEqual(created.worktree, { + path: worktreePath, + refName: "feature/locked-config", }); - const fileSystem = yield* FileSystem.FileSystem; - assert.equal(yield* fileSystem.exists(worktreePath), false); - assert.notInclude(yield* driver.listLocalBranchNames(cwd), "feature/worktree"); + assert.equal( + yield* git(worktreePath, ["branch", "--show-current"]), + "feature/locked-config", + ); + assert.equal( + yield* fileSystem.readFileString(pathService.join(worktreePath, "README.md")), + "# test\n", + ); + assert.equal( + yield* driver.readConfigValue(worktreePath, "branch.feature/locked-config.t3-merge-base"), + null, + ); + assert.equal(yield* fileSystem.exists(pathService.join(cwd, ".git/config.lock")), true); }), ); + it.effect.each([false, true])( + "cleans up links left by successful worktree removal, preserving ordinary files: %s", + (keepFile) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const outside = yield* makeTmpDir("git-worktree-link-target-"); + yield* writeTextFile(outside, "keep.txt", "external target\n"); + const worktreePath = pathService.join(cwd, "leftover"); + const nested = pathService.join(worktreePath, "node_modules"); + yield* fileSystem.makeDirectory(nested, { recursive: true }); + yield* fileSystem.makeDirectory(pathService.join(worktreePath, "empty")); + NodeFS.symlinkSync(outside, pathService.join(worktreePath, "linked"), "junction"); + NodeFS.symlinkSync(outside, pathService.join(nested, "pkg"), "junction"); + if (keepFile) { + yield* writeTextFile(worktreePath, "notes/draft.txt", "new work\n"); + } + + // Git removes symlinks on Unix; simulate its successful Windows removal + // leaving junctions behind so the cleanup is exercised on every platform. + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawner = ChildProcessSpawner.make((command) => + ChildProcess.isStandardCommand(command) && + command.args.join(" ").includes("worktree remove") + ? Effect.succeed(makeSuccessfulHandle("")) + : delegate.spawn(command), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + + yield* driver.removeWorktree({ cwd, path: worktreePath }); + + assert.equal( + yield* fileSystem.readFileString(pathService.join(outside, "keep.txt")), + "external target\n", + ); + if (keepFile) { + assert.deepEqual(yield* fileSystem.readDirectory(worktreePath), ["notes"]); + assert.equal( + yield* fileSystem.readFileString(pathService.join(worktreePath, "notes/draft.txt")), + "new work\n", + ); + } else { + assert.equal(yield* fileSystem.exists(worktreePath), false); + } + }), + ); + it.effect("keeps a worktree whose untracked files status is configured to hide", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3634,67 +3548,97 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("allows worktree removal to run longer than the default command timeout", () => + it.effect("leaves a folder alone that only shares the worktree's short name", () => Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const removalStarted = yield* Deferred.make(); - const delayedRemovalSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if ( - ChildProcess.isStandardCommand(command) && - command.args.join(" ").includes("worktree remove") - ) { - yield* Deferred.succeed(removalStarted, undefined); - yield* Effect.sleep("31 seconds"); - } - return yield* delegate.spawn(command); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, delayedRemovalSpawner), - Effect.provide(layerServerConfig), - ); const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); - const fileSystem = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; - const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "slow-removal"); - + const fileSystem = yield* FileSystem.FileSystem; + const driver = yield* GitVcsDriver.GitVcsDriver; + const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "short"); yield* driver.createWorktree({ cwd, path: worktreePath, refName: initialBranch, - newRefName: "feature/slow-removal", + newRefName: "feature/short", }); + // Unrelated to the worktree, but resolving "short" against cwd lands here. + const outside = yield* makeTmpDir("git-worktree-link-target-"); + const unrelated = pathService.join(cwd, "short"); + NodeFS.mkdirSync(unrelated); + NodeFS.symlinkSync(outside, pathService.join(unrelated, "linked"), "junction"); - const removal = yield* driver - .removeWorktree({ cwd, path: worktreePath, force: true }) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(removalStarted); - yield* TestClock.adjust("31 seconds"); - yield* Fiber.join(removal); + yield* Effect.result(driver.removeWorktree({ cwd, path: "short" })); - assert.equal(yield* fileSystem.exists(worktreePath), false); + assert.isTrue(NodeFS.lstatSync(pathService.join(unrelated, "linked")).isSymbolicLink()); + assert.equal(yield* fileSystem.exists(worktreePath), true); }), ); - it.effect("removes the same worktree path twice without failing", () => + it.effect("force-removes a worktree without deleting what its junctions point to", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, ".gitignore", "node_modules\n"); + yield* git(cwd, ["add", ".gitignore"]); + yield* git(cwd, ["commit", "-m", "ignore node_modules"]); + const fileSystem = yield* FileSystem.FileSystem; const pathService = yield* Path.Path; - const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "shared"); + const outside = yield* makeTmpDir("git-worktree-link-target-"); + yield* writeTextFile(outside, "keep.txt", "keep\n"); + const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked"); const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: initialBranch, + newRefName: "feature/linked", + }); + // Junctions on Windows, the way pnpm links packages; symlinks elsewhere. + NodeFS.mkdirSync(pathService.join(worktreePath, "node_modules")); + NodeFS.symlinkSync( + outside, + pathService.join(worktreePath, "node_modules", "dep"), + "junction", + ); + NodeFS.symlinkSync(outside, pathService.join(worktreePath, "shared"), "junction"); + + yield* driver.removeWorktree({ cwd, path: worktreePath, force: true }); + + assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), []); + assert.equal( + yield* fileSystem.readFileString(pathService.join(outside, "keep.txt")), + "keep\n", + ); + }), + ); + it.effect("keeps the junctions of a worktree that git refuses to remove", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, ".gitignore", "node_modules\n"); + yield* git(cwd, ["add", ".gitignore"]); + yield* git(cwd, ["commit", "-m", "ignore node_modules"]); + const pathService = yield* Path.Path; + const outside = yield* makeTmpDir("git-worktree-link-target-"); + const worktreePath = pathService.join(yield* makeTmpDir("git-worktrees-"), "linked"); + const driver = yield* GitVcsDriver.GitVcsDriver; yield* driver.createWorktree({ cwd, path: worktreePath, refName: initialBranch, - newRefName: "feature/shared", + newRefName: "feature/linked", }); + const link = pathService.join(worktreePath, "node_modules"); + NodeFS.symlinkSync(outside, link, "junction"); + yield* writeTextFile(worktreePath, "notes.txt", "draft\n"); + + const result = yield* Effect.result(driver.removeWorktree({ cwd, path: worktreePath })); - yield* driver.removeWorktree({ cwd, path: worktreePath }); - yield* driver.removeWorktree({ cwd, path: worktreePath }); + assert.isTrue(Result.isFailure(result)); + assert.isTrue(NodeFS.lstatSync(link).isSymbolicLink()); + assert.deepEqual(NodeFS.readdirSync(pathService.dirname(worktreePath)), ["linked"]); }), ); @@ -3728,6 +3672,31 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("remote operations", () => { + it.effect("ensureRemote reuses a partial clone remote and avoids its name", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init"]); + yield* git(cwd, ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"]); + yield* git(cwd, ["config", "remote.origin.promisor", "true"]); + yield* git(cwd, ["config", "remote.origin.partialclonefilter", "blob:none"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const reused = yield* driver.ensureRemote({ + cwd, + preferredName: "origin", + url: "git@github.com:pingdotgg/t3code.git", + }); + assert.equal(reused, "origin"); + const added = yield* driver.ensureRemote({ + cwd, + preferredName: "origin", + url: "https://github.com/another-owner/t3code.git", + }); + assert.equal(added, "origin-1"); + }), + ); + + // regression: #12485 explain fetch failures without exposing remote output it.effect("explains a real fetch failure for a missing local remote", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3765,7 +3734,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.equal(yield* driver.resolvePrimaryRemoteName(cwd), remoteName); yield* driver.fetchRemoteTrackingBranch({ cwd, remoteName, remoteBranch: initialBranch }); yield* driver.fetchRemote({ cwd, remoteName }); - const head = yield* driver.fetchPullRequestHeadCommit({ cwd, prNumber: 7 }); + const head = yield* driver.fetchRefCommit({ cwd, ref: "refs/pull/7/head" }); assert.isFalse(yield* fileSystem.exists((yield* Path.Path).join(cwd, "t3-marker"))); assert.equal(head.commitSha, yield* git(cwd, ["rev-parse", "HEAD"])); @@ -3831,6 +3800,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("commit context", () => { + it.effect("can omit the patch while preserving change detection and the real index", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + assert.isNull(yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false })); + yield* writeTextFile(cwd, "selected.txt", "selected content\n"); + yield* writeTextFile(cwd, "other.txt", "other content\n"); + yield* git(cwd, ["add", "other.txt"]); + const before = yield* git(cwd, ["diff", "--cached"]); + const summaryOnly = yield* driver.prepareCommitContext(cwd, ["selected.txt"], { + includePatch: false, + }); + assert.include(summaryOnly?.stagedSummary ?? "", "selected.txt"); + assert.notInclude(summaryOnly?.stagedSummary ?? "", "other.txt"); + assert.equal(summaryOnly?.stagedPatch, ""); + const full = yield* driver.prepareCommitContext(cwd, ["selected.txt"]); + assert.equal(full?.stagedSummary, summaryOnly?.stagedSummary); + assert.include(full?.stagedPatch ?? "", "+selected content"); + assert.equal(yield* git(cwd, ["diff", "--cached"]), before); + }), + ); + it.effect("prepares selected files without staging and commits only those files", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3957,65 +3949,6 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("remote operations", () => { - it.effect.each(["offline", "auth", "timeout"] as const)( - "does not retry a scoped fetch after %s", - (failure) => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const started = yield* Deferred.make(); - const attempts: Array> = []; - const spawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (!ChildProcess.isStandardCommand(command)) - return yield* Effect.die("unexpected command"); - if (command.args[0] !== "fetch") return yield* delegate.spawn(command); - attempts.push(command.args); - yield* Deferred.succeed(started, undefined); - return ChildProcessSpawner.makeHandle({ - ...makeNonRepositoryHandle(), - exitCode: - failure === "timeout" - ? Effect.never - : Effect.succeed(ChildProcessSpawner.ExitCode(128)), - stderr: Stream.encodeText( - Stream.make( - failure === "auth" - ? "fatal: Authentication failed" - : "fatal: Could not resolve host", - ), - ), - }); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provide(layerServerConfig), - ); - const fetching = yield* driver - .fetchRemote({ cwd, remoteName: "origin", refName: "main" }) - .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(started); - if (failure === "timeout") { - yield* TestClock.adjust("31 seconds"); - yield* TestClock.adjust("31 seconds"); - } - const result = yield* Fiber.join(fetching); - assert.isTrue(Result.isFailure(result)); - assert.equal(attempts.length, 1); - if (Result.isFailure(result)) { - assert.equal( - result.failure.detail, - failure === "timeout" - ? "Git command timed out." - : failure === "offline" - ? "Git could not reach the remote. Check the server's network connection and remote host, then retry." - : "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.", - ); - } - }), - ); - it.effect("creates a worktree from the latest fetched remote commit", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4098,9 +4031,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead); + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const comparisonBase = preview.sources.find( + (source) => source.kind === "branch-range", + )!.baseRef; assert.equal( - yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.gh-merge-base"), - initialBranch, + yield* git(worktreePath, ["rev-parse", `${comparisonBase}^{commit}`]), + remoteHead, ); assert.equal( yield* driver.readConfigValue(worktreePath, "branch.t3code/fetched-origin.remote"), @@ -4117,6 +4054,123 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("fetches the selected worktree base for Changes", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const fork = yield* makeTmpDir("git-fork-"); + const source = yield* makeTmpDir("git-source-"); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "-M", "stable"]); + yield* git(fork, ["init", "--bare"]); + yield* git(source, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", fork]); + yield* git(cwd, ["remote", "add", "upstream", source]); + yield* git(cwd, ["push", "origin", "stable"]); + yield* git(cwd, ["push", "-u", "upstream", "stable:release"]); + const localHead = yield* git(cwd, ["rev-parse", "HEAD"]); + + yield* writeTextFile(cwd, "fork.txt", "fork-only work\n"); + yield* git(cwd, ["add", "fork.txt"]); + yield* git(cwd, ["commit", "-m", "fork work"]); + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/release"]); + yield* git(cwd, ["reset", "--hard", localHead]); + + // Advance the source without updating this checkout's tracking refs. + yield* writeTextFile(cwd, "upstream.txt", "upstream-only work\n"); + yield* git(cwd, ["add", "upstream.txt"]); + yield* git(cwd, ["commit", "-m", "source advance"]); + const remoteHead = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(source, ["--git-dir=.", "fetch", cwd, "stable:refs/heads/release"]); + yield* git(cwd, ["reset", "--hard", localHead]); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const fetched = yield* driver.fetchWorktreeBaseCommit({ cwd, refName: "stable" }); + assert.deepEqual(fetched, { + commitSha: remoteHead, + remoteRefName: "upstream/release", + }); + yield* git(cwd, ["update-ref", "-d", "refs/remotes/upstream/release"]); + assert.deepEqual( + yield* driver.fetchWorktreeBaseCommit({ cwd, refName: "upstream/release" }), + { commitSha: remoteHead, remoteRefName: "upstream/release" }, + ); + yield* git(cwd, ["branch", "--unset-upstream", "stable"]); + assert.deepEqual(yield* driver.fetchWorktreeBaseCommit({ cwd, refName: "stable" }), { + commitSha: localHead, + remoteRefName: "origin/stable", + }); + assert.equal(yield* git(cwd, ["rev-parse", "stable"]), localHead); + + const path = yield* Path.Path; + const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "feature"); + yield* driver.createWorktree({ + cwd, + path: worktreePath, + refName: fetched!.commitSha, + newRefName: "feature/from-upstream", + baseRefName: `refs/remotes/${fetched!.remoteRefName}`, + }); + assert.equal(yield* git(worktreePath, ["rev-parse", "HEAD"]), remoteHead); + yield* writeTextFile(worktreePath, "feature.txt", "feature work\n"); + yield* git(worktreePath, ["add", "feature.txt"]); + yield* git(worktreePath, ["commit", "-m", "feature work"]); + + const preview = yield* driver.getReviewDiffPreview({ cwd: worktreePath }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.deepStrictEqual(changes.files, [ + { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, + ]); + assert.include(changes.diff, "+feature work"); + assert.notInclude(changes.diff, "upstream-only work"); + const status = yield* driver.statusDetailsLocal(worktreePath, { + includeBranchChanges: true, + }); + assert.strictEqual(status.aheadCount, 1); + assert.strictEqual(status.branchChanges?.insertions, 1); + assert.strictEqual(status.branchChanges?.deletions, 0); + // gh pr create consumes this setting verbatim as the hosted target branch. + assert.equal( + yield* driver.readConfigValue(worktreePath, "branch.feature/from-upstream.t3-merge-base"), + "release", + ); + assert.equal(changes.baseRef, "upstream/release"); + }), + ); + + it.effect("does not use a deleted remote worktree base's stale tracking commit", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-remote-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", `${initialBranch}:release`]); + yield* git(remote, ["--git-dir=.", "update-ref", "-d", "refs/heads/release"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + + assert.equal( + yield* git(cwd, ["rev-parse", "refs/remotes/origin/release"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + assert.isNull(yield* driver.fetchWorktreeBaseCommit({ cwd, refName: initialBranch })); + yield* git(cwd, ["remote", "remove", "origin"]); + assert.isNull(yield* driver.fetchWorktreeBaseCommit({ cwd, refName: initialBranch })); + }), + ); + + it.effect("fails instead of falling back when the worktree base remote is unreachable", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["remote", "add", "origin", `${cwd}/missing.git`]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const error = yield* driver + .fetchWorktreeBaseCommit({ cwd, refName: initialBranch }) + .pipe(Effect.flip); + assert.equal(error._tag, "GitCommandError"); + }), + ); + it.effect("pushes with upstream setup and skips when already up to date", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4155,41 +4209,71 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("allows pushes to run longer than the default command timeout", () => - Effect.gen(function* () { - const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; - const pushStarted = yield* Deferred.make(); - const delayedPushSpawner = ChildProcessSpawner.make((command) => - Effect.gen(function* () { - if (ChildProcess.isStandardCommand(command) && command.args[0] === "push") { - yield* Deferred.succeed(pushStarted, undefined); - yield* Effect.sleep("31 seconds"); - } - return yield* delegate.spawn(command); - }), - ); - const driver = yield* makeGitVcsDriverCore().pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, delayedPushSpawner), - Effect.provide(layerServerConfig), - ); - const cwd = yield* makeTmpDir(); - const remote = yield* makeTmpDir("git-remote-"); - yield* initRepoWithCommit(cwd); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); + it.effect.each(["feature/push", "origin/feature/push"])( + "publishes %s when the configured diff base already contains HEAD", + (branch) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const originRemote = yield* makeTmpDir("git-origin-remote-"); + const upstreamRemote = yield* makeTmpDir("git-upstream-remote-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "-M", "main"]); + yield* git(originRemote, ["init", "--bare"]); + yield* git(upstreamRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", originRemote]); + yield* git(cwd, ["remote", "add", "upstream", upstreamRemote]); + yield* git(cwd, ["push", "origin", "main", "main:refs/heads/feature/push"]); + yield* git(cwd, ["checkout", "--no-track", "-b", branch]); + yield* writeTextFile(cwd, "feature.txt", "feature\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add feature", ""); + yield* git(cwd, ["push", "upstream", "HEAD:refs/heads/main"]); + yield* git(cwd, ["config", `branch.${branch}.gh-merge-base`, "upstream/main"]); + + const status = yield* driver.statusDetails(cwd); + assert.equal(status.hasUpstream, false); + assert.equal(status.aheadCount, 0); + assert.equal(status.behindCount, 0); + const head = yield* git(cwd, ["rev-parse", "HEAD"]); + assert.notEqual( + yield* git(originRemote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + head, + ); - const pushing = yield* driver - .pushCurrentBranch(cwd, null) - .pipe(Effect.forkChild({ startImmediately: true })); - yield* Deferred.await(pushStarted); - yield* TestClock.adjust("31 seconds"); - const pushed = yield* Fiber.join(pushing); + const pushed = yield* driver.pushCurrentBranch(cwd, null); + assert.deepInclude(pushed, { + status: "pushed", + branch, + upstreamBranch: "origin/feature/push", + setUpstream: true, + }); + assert.equal( + yield* git(originRemote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + head, + ); - assert.deepInclude(pushed, { - status: "pushed", - setUpstream: true, - }); - }), + yield* git(cwd, ["branch", "--unset-upstream"]); + const skipped = yield* driver.pushCurrentBranch(cwd, null); + assert.deepInclude(skipped, { status: "skipped_up_to_date", branch }); + + yield* writeTextFile(cwd, "remote.txt", "remote update\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Advance publish branch", ""); + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/feature/push"]); + const publishedHead = yield* git(originRemote, [ + "--git-dir=.", + "rev-parse", + "refs/heads/feature/push", + ]); + yield* git(cwd, ["reset", "--hard", head]); + const skippedBehindRemote = yield* driver.pushCurrentBranch(cwd, null); + assert.deepInclude(skippedBehindRemote, { status: "skipped_up_to_date", branch }); + assert.equal( + yield* git(originRemote, ["--git-dir=.", "rev-parse", "refs/heads/feature/push"]), + publishedHead, + ); + }), ); it.effect( @@ -4235,6 +4319,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { Effect.gen(function* () { const cwd = yield* makeTmpDir(); const remote = yield* makeTmpDir("git-remote-"); + const upstream = yield* makeTmpDir("git-upstream-"); yield* initRepoWithCommit(cwd); const driver = yield* GitVcsDriver.GitVcsDriver; yield* git(cwd, ["branch", "-M", "main"]); @@ -4244,7 +4329,14 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["checkout", "-b", "dev"]); yield* git(cwd, ["push", "-u", "origin", "dev"]); const devSha = yield* git(cwd, ["rev-parse", "HEAD"]); - yield* git(cwd, ["checkout", "-b", "feature/x", "origin/dev"]); + yield* git(upstream, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", upstream]); + yield* writeTextFile(cwd, "upstream.txt", "upstream work\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add upstream update", ""); + yield* git(cwd, ["push", "upstream", "dev"]); + const upstreamDevSha = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* git(cwd, ["checkout", "-b", "feature/x", "upstream/dev"]); yield* writeTextFile(cwd, "feature.txt", "feature\n"); yield* git(cwd, ["add", "-A"]); yield* driver.commit(cwd, "Add feature", ""); @@ -4262,11 +4354,19 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { "Add feature", ); assert.equal(yield* git(remote, ["--git-dir=.", "rev-parse", "dev"]), devSha); + assert.equal(yield* git(upstream, ["--git-dir=.", "rev-parse", "dev"]), upstreamDevSha); assert.equal( yield* git(cwd, ["rev-parse", "--abbrev-ref", "@{upstream}"]), "origin/feature/x", ); - assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.gh-merge-base"), "dev"); + assert.equal(yield* driver.readConfigValue(cwd, "branch.feature/x.t3-merge-base"), "dev"); + + const preview = yield* driver.getReviewDiffPreview({ cwd }); + const changes = preview.sources.find((source) => source.kind === "branch-range")!; + assert.deepStrictEqual(changes.files, [ + { path: "feature.txt", previousPath: null, additions: 1, deletions: 0 }, + ]); + assert.equal(changes.baseRef, "upstream/dev"); }), ); @@ -4412,21 +4512,6 @@ describe("Windows long path configuration", () => { }), ); - it.effect("leaves Git config untouched on other platforms", () => - Effect.gen(function* () { - assert.equal(yield* readGitConfig("linux", "core.longpaths"), "false"); - assert.equal(yield* readGitConfig("linux", "user.name"), "inherited-name"); - }), - ); - - it("extends an inherited count spelled in a different case", () => { - assert.deepStrictEqual(windowsLongPathConfigEnv("win32", { git_config_count: "2" }), { - git_config_count: "3", - GIT_CONFIG_KEY_2: "core.longpaths", - GIT_CONFIG_VALUE_2: "true", - }); - }); - it("extends the per-command count when inherited and per-command casings differ", () => { assert.deepStrictEqual( windowsLongPathConfigEnv("win32", { GIT_CONFIG_COUNT: "0", git_config_count: "1" }), @@ -4473,6 +4558,7 @@ describe("Windows long path configuration", () => { } }); + // regression: #14917 Windows worktrees with long paths failed or stranded it("leaves a count Git would reject for Git to report", () => { for (const count of ["nope", "2x", "-1", "1.5", " ", "1 "]) { assert.deepStrictEqual( diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index ffab840f815fd..c689d27be2263 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1,4 +1,6 @@ import * as Cache from "effect/Cache"; +import * as Cause from "effect/Cause"; +import * as Clock from "effect/Clock"; import * as Data from "effect/Data"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; @@ -6,6 +8,7 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -28,7 +31,7 @@ import { type ReviewDiffPreviewSource, type VcsRef, } from "@t3tools/contracts"; -import { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from "@t3tools/shared/git"; +import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { compactTraceAttributes } from "@t3tools/shared/observability"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; @@ -37,7 +40,9 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings"; import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; +import { removeEmptyDirectory } from "./removeEmptyDirectory.ts"; import { explicitBareRepositoryEnv, gitConfigEnv } from "./VcsProcess.ts"; +import { removeLinkedWorktree } from "./worktreeRemoval.ts"; import { resolveWorktreesDirectory } from "../worktreesDirectory.ts"; import { parseRemoteNames, @@ -45,8 +50,16 @@ import { parseRemoteRefWithRemoteNames, } from "../git/remoteRefs.ts"; import * as ServerConfig from "../config.ts"; +import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; const DEFAULT_TIMEOUT_MS = 30_000; +/** T3's record of the branch, named as on the host, that a branch was cut from. */ +const branchBaseConfigKey = (branch: string) => `branch.${branch}.t3-merge-base`; +/** + * Where T3 kept that record before it had a key of its own, for every host alike: the GitHub + * CLI's key, which branches cut before then still carry instead. + */ +const legacyBranchBaseConfigKey = (branch: string) => `branch.${branch}.gh-merge-base`; const gitProcesses = Semaphore.makeUnsafe(8); const WORKTREE_ADD_TIMEOUT_MS = 300_000; const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5)); @@ -58,14 +71,10 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; -// Every status refresh adds the untracked files to a temporary index, and git add's cost grows -// much faster than the file count (50k files took about 30 seconds). Past this many, the -// totals are reported incomplete instead. +// Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; const REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024; -// Patches the clients render are parsed against git's default a/ and b/ path -// prefixes. A repository or global diff.noprefix or diff.mnemonicPrefix would -// otherwise leak into the patch and leave every parsed file unnamed. +// Client patch parsers require a/ and b/ prefixes; override user diff prefix settings. export const PATCH_RENDER_PREFIX_ARGS = ["--src-prefix=a/", "--dst-prefix=b/"] as const; const REVIEW_DIFF_ARGS = [ "diff", @@ -73,11 +82,11 @@ const REVIEW_DIFF_ARGS = [ "--no-color", "--no-ext-diff", "--no-textconv", - "--minimal", ...PATCH_RENDER_PREFIX_ARGS, ]; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); +const STATUS_UPSTREAM_FETCH_TIMEOUT = Duration.minutes(5); const STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN = Duration.seconds(30); const STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN = Duration.minutes(15); @@ -156,6 +165,7 @@ class GitRefsRefreshCacheKey extends Data.Class<{ interface GitRepositoryPaths { readonly gitCommonDir: string; readonly worktreeRoot: string | null; + readonly isAtRepositoryRoot: boolean | undefined; readonly currentBranch: string | null; } @@ -168,6 +178,7 @@ interface GitRefsSnapshot { interface ExecuteGitOptions { stdin?: string | undefined; timeoutMs?: number | null | undefined; + forceKillAfterMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorDetail?: string | undefined; env?: NodeJS.ProcessEnv | undefined; @@ -185,30 +196,6 @@ function parseBranchAb(value: string): { ahead: number; behind: number } { }; } -function parseNumstatEntries( - stdout: string, -): Array<{ path: string; insertions: number; deletions: number }> { - const entries: Array<{ path: string; insertions: number; deletions: number }> = []; - for (const line of stdout.split(/\r?\n/g)) { - if (line.trim().length === 0) continue; - const [addedRaw, deletedRaw, ...pathParts] = line.split("\t"); - const rawPath = - pathParts.length > 1 ? (pathParts.at(-1) ?? "").trim() : pathParts.join("\t").trim(); - if (rawPath.length === 0) continue; - const added = Number.parseInt(addedRaw ?? "0", 10); - const deleted = Number.parseInt(deletedRaw ?? "0", 10); - const renameArrowIndex = rawPath.indexOf(" => "); - const normalizedPath = - renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + " => ".length).trim() : rawPath; - entries.push({ - path: normalizedPath.length > 0 ? normalizedPath : rawPath, - insertions: Number.isFinite(added) ? added : 0, - deletions: Number.isFinite(deleted) ? deleted : 0, - }); - } - return entries; -} - function parseReviewNumstat(stdout: string): ReviewDiffFileStat[] { const fields = stdout.split("\0"); const files: ReviewDiffFileStat[] = []; @@ -228,25 +215,20 @@ function parseReviewNumstat(stdout: string): ReviewDiffFileStat[] { return files; } -function parsePorcelainPath(line: string): string | null { - if (line.startsWith("? ") || line.startsWith("! ")) { - const simple = line.slice(2).trim(); - return simple.length > 0 ? simple : null; - } - - if (!(line.startsWith("1 ") || line.startsWith("2 ") || line.startsWith("u "))) { - return null; - } - - const tabIndex = line.indexOf("\t"); - if (tabIndex >= 0) { - const fromTab = line.slice(tabIndex + 1); - const [filePath] = fromTab.split("\t"); - return filePath?.trim().length ? filePath.trim() : null; - } +// Space-separated fields precede the path in each porcelain v2 record type. The path itself +// may contain spaces, so it is everything after them. +const PORCELAIN_V2_FIELDS_BEFORE_PATH: Record = { + "1": 8, + "2": 9, + u: 10, + "?": 1, + "!": 1, +}; - const parts = line.trim().split(/\s+/g); - const filePath = parts.at(-1) ?? ""; +function parsePorcelainPath(record: string): string | null { + const fieldsBeforePath = PORCELAIN_V2_FIELDS_BEFORE_PATH[record[0] ?? ""]; + if (fieldsBeforePath === undefined) return null; + const filePath = record.split(" ").slice(fieldsBeforePath).join(" "); return filePath.length > 0 ? filePath : null; } @@ -332,12 +314,8 @@ export function splitNullSeparatedGitStdoutPaths( return splitNullSeparatedPaths(result.stdout, result.stdoutTruncated); } -/** - * Refuses a ref name with a leading "-" before it reaches checkout or `worktree add`. Git refuses - * such branch and tag names, and both commands, or the `git branch` that `worktree add` runs, read - * one as an option. `--end-of-options` cannot guard them: Git before 2.44 reads it like `--`. - * A lone "-" is the previous checkout, which both commands read as a ref. - */ +// Checkout/worktree add parse leading dashes as options; pre-2.44 Git cannot guard with --end-of-options. +// A lone - still means previous checkout. const refuseOptionLikeRefName = (operation: string, cwd: string, refName: string | undefined) => refName !== undefined && refName !== "-" && refName.startsWith("-") ? Effect.fail( @@ -363,7 +341,8 @@ function parseRemoteFetchUrls(stdout: string): Map { for (const line of stdout.split("\n")) { const trimmed = line.trim(); if (trimmed.length === 0) continue; - const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)$/.exec(trimmed); + // Partial clones append the promisor filter, e.g. `(fetch) [blob:none]`. + const match = /^(\S+)\s+(\S+)\s+\((fetch|push)\)(?:\s+\[[^\]]+\])?$/.exec(trimmed); if (!match) continue; const [, remoteName = "", remoteUrl = "", direction = ""] = match; if (direction !== "fetch" || remoteName.length === 0 || remoteUrl.length === 0) { @@ -451,10 +430,7 @@ function gitCommandContext( } as const; } -// Git states the actual cause on stderr, but stderr never leaves this module: -// it echoes argv and remote URLs, which can carry credentials. Matching it -// against fixed patterns yields a tag the caller can act on and a message that -// quotes none of the matched text. +// Stderr can echo credentials from argv/URLs; classify fixed patterns without exposing matched text. const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray = [ [/would clobber existing tag/i, "tag_would_be_clobbered"], [/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"], @@ -468,22 +444,48 @@ const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray already exists` also - // covers tag and ref collisions, which are not path collisions. + // Unquoted already-exists errors also describe ref/tag collisions; require quoted paths. [/fatal: '[^']+' already exists|destination path .+ already exists/i, "path_already_exists"], + // Ambiguous revision/path and pathspec failures can name files, so omit them. + // Anchor to a diagnostic line to avoid matching quoted paths in other errors. + [ + /^fatal: (?:invalid reference: |not a valid object name|needed a single revision|bad revision |'.+' is not a commit and a branch '.+' cannot be created from it)/im, + "ref_not_found", + ], + // `[remote rejected]` is only printed for a push. The remote's explanation + // follows in parentheses; it is server text, so it is never quoted. + [/^[ \t]*![ \t]+\[remote rejected\]/im, "push_rejected_by_remote"], + // A fetch into a diverged local branch prints the same `[rejected]` line, but + // only a push goes on to report "failed to push some refs". + [ + /^[ \t]*![ \t]+\[rejected\][^\n]*\((?:non-fast-forward|fetch first)\)[\s\S]*^error: failed to push some refs/im, + "push_rejected_non_fast_forward", + ], ]; -// Hooks write to the same stream git does, and nothing distinguishes their text -// from git's: a pre-push hook echoing "authentication failed" would otherwise -// be read as a credential failure. `remote:` is deliberately excluded — git -// prefixes every byte the server sends that way, remote hook output included, -// so trusting it would reintroduce the same false positive from the other end -// of the connection. +// Reasons the user can act on get a sentence in place of the generic detail. +const GIT_FAILURE_REASON_DETAILS: Partial> = { + push_rejected_by_remote: + "The remote rejected the push. Push this branch from a terminal to see the server's message.", + push_rejected_non_fast_forward: + "The remote has commits this branch doesn't have. Pull or rebase, then push again.", +}; + +function gitFailureDetail(reason: GitCommandFailureReason | null): string { + return ( + (reason === null ? undefined : GIT_FAILURE_REASON_DETAILS[reason]) ?? + "Git command exited with a non-zero status." + ); +} + +// Existing non-commit objects share the missing-ref fatal diagnostic; Git +// distinguishes them with a separate error line. +const GIT_NOT_A_COMMIT_PATTERN = /^error: .+(?:, not a commit|expected commit type)/im; + +// Trust only Git's diagnostic prefixes: local hooks can write indistinguishable text. +// Exclude `remote:` too, since it prefixes remote hook output as well as server diagnostics. const GIT_DIAGNOSTIC_LINE_PATTERN = /^(?:fatal|error):|^!\s|^\s+!\s/; -// ssh reports the refusal itself, unprefixed, and git only adds a generic -// "Could not read from remote repository" after it. Dropping ssh's line would -// leave that generic one to be read as an unreachable remote when the real -// cause is credentials, so these specific refusals are classified too. +// SSH credential refusals are unprefixed; Git's later generic error would otherwise misclassify them as unreachable. const SSH_TRANSPORT_REFUSAL_PATTERN = /Permission denied \((?:publickey|password|keyboard-interactive)|Permission denied, please try again|Host key verification failed/i; @@ -499,7 +501,9 @@ function classifyGitFailure(stderr: string): GitCommandFailureReason | null { if (diagnostics.length === 0) return null; if (isNonRepositoryGitStderr(diagnostics)) return "not_a_repository"; for (const [pattern, reason] of GIT_FAILURE_REASON_PATTERNS) { - if (pattern.test(diagnostics)) return reason; + if (!pattern.test(diagnostics)) continue; + if (reason === "ref_not_found" && GIT_NOT_A_COMMIT_PATTERN.test(diagnostics)) continue; + return reason; } return null; } @@ -545,9 +549,7 @@ function isUnbornHeadStderr(stderr: string): boolean { ); } -// Matches `git worktree remove` on a path git no longer tracks: "is not a -// working tree" when the registration is gone, "cannot remove working tree" -// when older gits fail validation on a registered-but-deleted directory. +// Git reports missing worktree registrations and registered-but-deleted paths differently. function isMissingWorktreeStderr(stderr: string): boolean { const normalized = stderr.toLowerCase(); return ( @@ -556,8 +558,7 @@ function isMissingWorktreeStderr(stderr: string): boolean { ); } -// Fetch stderr can contain remote credentials. Only fixed diagnoses may enter -// persisted errors; unrecognized output keeps the generic failure message. +// Fetch stderr can carry credentials; persist only fixed diagnoses or generic failures. function fetchFailureDetail(stderr: string): string | undefined { const lines = stderr.split(/\r?\n/).map((line) => line.trim()); if ( @@ -593,8 +594,7 @@ function fetchFailureDetail(stderr: string): string | undefined { return undefined; } -// Matches a fetch that lost a ref update to another Git process. Git 2.53+ -// reports it as "fetching ref failed: ..."; older Git says "cannot lock ref". +// Git 2.53+ reports ref races as fetching-ref failures; older versions say cannot lock ref. function isRefLockFailure(stderr: string): boolean { return stderr .split(/\r?\n/) @@ -614,14 +614,16 @@ const nowUnixNano = DateTime.now.pipe( Effect.map((now) => BigInt(DateTime.toEpochMillis(now)) * 1_000_000n), ); -const addCurrentSpanEvent = (name: string, attributes: Record) => - Effect.gen(function* () { - const span = yield* Effect.currentSpan; - const timestamp = yield* nowUnixNano; - yield* Effect.sync(() => { - span.event(name, timestamp, compactTraceAttributes(attributes)); - }); - }).pipe( +const addCurrentSpanEvent = + /* This helper annotates the existing operation span. */ + Effect.fnUntraced( + function* (name: string, attributes: Record) { + const span = yield* Effect.currentSpan; + const timestamp = yield* nowUnixNano; + yield* Effect.sync(() => { + span.event(name, timestamp, compactTraceAttributes(attributes)); + }); + }, Effect.catchTags({ NoSuchElementError: () => Effect.void, }), @@ -830,12 +832,10 @@ const collectOutput = Effect.fnUntraced(function* ( let text = ""; let lineBuffer = ""; let truncated = false; - // A separator-free stream past the cap must not grow the line buffer - // without bound; a line longer than this is not one the callbacks want. + // Bound newline-free output; oversized lines are not useful to callbacks. const maxPendingLineBytes = 64 * 1024; - // Git redraws progress with a bare `\r` between updates and only ends the - // line once the step is done, so `\r` has to count as a line break here. + // Git redraws progress with bare CR; treat it as a line break. const emitCompleteLines = Effect.fnUntraced(function* (flush: boolean) { let separator = OUTPUT_LINE_SEPARATOR.exec(lineBuffer); while (separator) { @@ -883,8 +883,10 @@ const collectOutput = Effect.fnUntraced(function* ( const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); text += decoded; - lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded; - yield* emitCompleteLines(false); + if (onLine) { + lineBuffer += lineDecoder ? lineDecoder.decode(chunk, { stream: true }) : decoded; + yield* emitCompleteLines(false); + } }); yield* Stream.runForEach(stream, processChunk).pipe( @@ -900,21 +902,18 @@ const collectOutput = Effect.fnUntraced(function* ( const remainder = truncated ? "" : decoder.decode(); text += remainder; - lineBuffer += remainder; - if (lineDecoder) lineBuffer += lineDecoder.decode(); - yield* emitCompleteLines(true); + if (onLine) { + lineBuffer += remainder; + if (lineDecoder) lineBuffer += lineDecoder.decode(); + yield* emitCompleteLines(true); + } return { text, truncated, }; }); -/** - * Git on Windows cannot create or delete a path longer than MAX_PATH (260) - * unless `core.longpaths` is set. The OS-level LongPathsEnabled setting does not - * cover it, and git leaves it off by default, so deep worktrees fail to check - * out and fail midway through removal. - */ +/** Windows Git needs core.longpaths beyond MAX_PATH (260); OS LongPathsEnabled alone is insufficient. */ export const windowsLongPathConfigEnv = ( platform: NodeJS.Platform, env: NodeJS.ProcessEnv, @@ -928,6 +927,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const { worktreesDir } = yield* ServerConfig.ServerConfig; const crypto = yield* Crypto.Crypto; const hostPlatform = yield* HostProcess.Platform; + const serviceScope = yield* Effect.scope; + const statusFetches = new Map>(); + const statusFetchProcesses = yield* Semaphore.make(4); const executeRaw: GitVcsDriver.GitVcsDriver["Service"]["execute"] = Effect.fnUntraced( function* (input) { @@ -954,8 +956,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); const baseEnv = { ...process.env, - // Status polling runs beside the user's own git commands; without this, - // `git status` takes index.lock to save its refreshed index. + // Concurrent status polls must not take index.lock to save refreshed indexes. GIT_OPTIONAL_LOCKS: "0", ...input.env, ...trace2Monitor.env, @@ -963,14 +964,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const env = { ...baseEnv, ...explicitBareRepositoryEnv(baseEnv, hostPlatform) }; const spawnEnv = { ...env, ...windowsLongPathConfigEnv(hostPlatform, env) }; const resolved = yield* resolveSpawnCommand("git", [], { env: spawnEnv }); - // A git.cmd wrapper would need cmd.exe, which cuts multi-line commit - // messages at the first newline; leave that case to Node's lookup. + // cmd wrappers truncate multiline commits; leave git.cmd handling to Node lookup. const executable = resolved.shell ? "git" : resolved.command; const child = yield* commandSpawner .spawn( ChildProcess.make(executable, commandInput.args, { cwd: commandInput.cwd, env: spawnEnv, + forceKillAfter: input.forceKillAfterMs, }), ) .pipe( @@ -1034,7 +1035,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* new GitCommandError({ ...gitCommandContext(commandInput), ...(reason === null ? {} : { reason }), - detail: "Git command exited with a non-zero status.", + detail: gitFailureDetail(reason), exitCode, stdoutLength: stdout.text.length, stderrLength: stderr.text.length, @@ -1108,6 +1109,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...(options.env !== undefined ? { env: options.env } : {}), allowNonZeroExit: true, ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(options.forceKillAfterMs !== undefined + ? { forceKillAfterMs: options.forceKillAfterMs } + : {}), ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), ...(options.appendTruncationMarker !== undefined ? { appendTruncationMarker: options.appendTruncationMarker } @@ -1123,7 +1127,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* new GitCommandError({ ...gitCommandContext({ operation, cwd, args }), ...(reason === null ? {} : { reason }), - detail: options.fallbackErrorDetail ?? "Git command exited with a non-zero status.", + detail: options.fallbackErrorDetail ?? gitFailureDetail(reason), ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), stdoutLength: result.stdout.length, stderrLength: result.stderr.length, @@ -1164,10 +1168,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((result) => result.stdout), ); - /** - * Runs `git worktree list --porcelain -z`. Git before 2.36 rejects `-z`, so a failed run - * retries the line form and returns it NUL-delimited, the same shape as `-z` output. - */ + // Pre-2.36 Git rejects worktree list -z; normalize its line fallback to NUL records. const executeWorktreeList = Effect.fn("executeWorktreeList")(function* ( operation: string, cwd: string, @@ -1234,7 +1235,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); }); - const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* (cwd: string) { + const readCurrentUpstreamRef = Effect.fn("readCurrentUpstreamRef")(function* (cwd: string) { const upstreamRef = yield* runGitStdout( "GitVcsDriver.resolveCurrentUpstream", cwd, @@ -1245,6 +1246,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { return null; } + return upstreamRef; + }); + + const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* ( + cwd: string, + knownUpstreamRef?: string, + ) { + const upstreamRef = knownUpstreamRef ?? (yield* readCurrentUpstreamRef(cwd)); + if (upstreamRef === null) { + return null; + } const remoteNames = yield* runGitStdout("GitVcsDriver.listRemoteNames", cwd, ["remote"]).pipe( Effect.map(parseRemoteNames), @@ -1256,40 +1268,76 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); }); - const fetchRemoteForStatus = ( + const fetchRemoteForStatus = Effect.fn("GitVcsDriver.fetchRemoteForStatus.wait")(function* ( gitCommonDir: string, remoteName: string, - ): Effect.Effect => { + ) { const fetchCwd = path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; // `--no-auto-gc` (a synonym of `--no-auto-maintenance` that older Git also knows) keeps // this poll from starting `git gc --auto`. When that gc fails, for example on a repository // with missing objects, Git retries it on every fetch and leaves a full-size `tmp_pack_*` // behind each time, so a background poll could fill the disk. - return executeGit( - "GitVcsDriver.fetchRemoteForStatus", - fetchCwd, - [ - "--git-dir", - gitCommonDir, - "fetch", - "--quiet", - "--no-tags", - "--no-auto-gc", - "--", - remoteName, - ], - { - env: STATUS_UPSTREAM_REFRESH_ENV, - fallbackErrorDetail: "Background Git fetch exited with a non-zero status.", - timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), - }, - ).pipe(Effect.asVoid); - }; + const args = [ + "--git-dir", + gitCommonDir, + "fetch", + "--quiet", + "--no-tags", + "--no-auto-gc", + "--", + remoteName, + ]; + const key = `${gitCommonDir}\0${remoteName}`; + const failure = statusRemoteRefreshFailures.get(key); + if (failure && (yield* Clock.currentTimeMillis) < failure.retryAt) return; + const fiber = yield* Effect.uninterruptible( + Effect.gen(function* () { + const pending = statusFetches.get(key); + if (pending) return pending; + // Frequent poll deadlines and disconnected clients must not interrupt a + // healthy writer. A separate safety limit prevents a hung transport from + // occupying its worker slot indefinitely. + const started = yield* executeGit("GitVcsDriver.fetchRemoteForStatus", fetchCwd, args, { + env: STATUS_UPSTREAM_REFRESH_ENV, + fallbackErrorDetail: "Background Git fetch exited with a non-zero status.", + timeoutMs: Duration.toMillis(STATUS_UPSTREAM_FETCH_TIMEOUT), + forceKillAfterMs: 1_000, + }).pipe( + Effect.asVoid, + Effect.tap(() => + Effect.sync(() => { + statusRemoteRefreshFailures.delete(key); + }), + ), + Effect.tapError(() => recordStatusRemoteRefreshFailure(key)), + Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)), + statusFetchProcesses.withPermits(1), + Effect.onExit(() => + Effect.sync(() => { + statusFetches.delete(key); + }), + ), + Effect.forkIn(serviceScope, { startImmediately: false, uninterruptible: false }), + ); + statusFetches.set(key, started); + return started; + }), + ); + const result = yield* Fiber.join(fiber).pipe( + Effect.timeoutOption(STATUS_UPSTREAM_REFRESH_TIMEOUT), + ); + if (Option.isNone(result)) { + yield* Effect.logDebug( + "Background Git fetch is still running; using the last fetched references.", + ); + } + }); const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* ( cwd: string, ) { + // Git reports relative paths from the physical cwd, which can differ from a symlink. const commonDirResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.resolveRepositoryPaths.commonDir", cwd, @@ -1318,9 +1366,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const commonDirOutput = commonDirResult.stdout.trim(); + const physicalCwd = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); const resolvedGitCommonDir = path.isAbsolute(commonDirOutput) ? path.normalize(commonDirOutput) - : path.resolve(cwd, commonDirOutput); + : path.resolve(physicalCwd, commonDirOutput); const gitCommonDir = yield* fileSystem .realPath(resolvedGitCommonDir) .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir)); @@ -1347,7 +1396,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { concurrency: 2 }, ); - const worktreeRootOutput = worktreeRootResult.stdout.trim(); + // Git terminates --show-toplevel with exactly one "\n" on every platform (stdout is + // binary mode on Windows). Whitespace before it belongs to the path and must survive, + // because this root becomes the editor target for every repository-relative status path. + const worktreeRootOutput = worktreeRootResult.stdout.endsWith("\n") + ? worktreeRootResult.stdout.slice(0, -1) + : worktreeRootResult.stdout; const worktreeRoot = worktreeRootResult.exitCode === 0 && worktreeRootOutput.length > 0 ? path.normalize( @@ -1356,6 +1410,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : path.resolve(cwd, worktreeRootOutput), ) : null; + // Git reports physical roots, so resolve project aliases before comparing. + const isAtRepositoryRoot = + worktreeRoot === null + ? undefined + : yield* fileSystem.realPath(cwd).pipe( + Effect.map((physicalCwd) => path.relative(worktreeRoot, physicalCwd) === ""), + Effect.orElseSucceed(() => undefined), + ); const currentBranchOutput = currentBranchResult.stdout.trim(); const currentBranch = currentBranchResult.exitCode === 0 && currentBranchOutput.length > 0 @@ -1365,6 +1427,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { gitCommonDir, worktreeRoot, + isAtRepositoryRoot, currentBranch, } satisfies GitRepositoryPaths; }); @@ -1449,15 +1512,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), }, ); - const invalidateStatusStaticCaches = (cwd: string) => - Effect.gen(function* () { + const invalidateStatusStaticCaches = Effect.fn("GitVcsDriverCore.invalidateStatusStaticCaches")( + function* (cwd: string) { const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe( Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }), ); const cacheKey = repositoryPaths?.gitCommonDir ?? normalizeRepositoryPathsCacheKey(cwd); yield* Cache.invalidate(defaultBranchCache, cacheKey); yield* Cache.invalidate(originExistsCache, cacheKey); - }); + }, + ); const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) { const repositoryPaths = yield* resolveRepositoryPaths(cwd); @@ -1474,46 +1538,42 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); }); - const statusRemoteRefreshFailureCounts = new Map(); + const statusRemoteRefreshFailures = new Map(); const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) => `${cacheKey.gitCommonDir}\0${cacheKey.remoteName}`; - const recordStatusRemoteRefreshFailure = (cacheKey: StatusRemoteRefreshCacheKey) => { - const key = statusRemoteRefreshFailureKey(cacheKey); - const nextCount = (statusRemoteRefreshFailureCounts.get(key) ?? 0) + 1; - statusRemoteRefreshFailureCounts.delete(key); - statusRemoteRefreshFailureCounts.set(key, nextCount); - if (statusRemoteRefreshFailureCounts.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) { - const oldestKey = statusRemoteRefreshFailureCounts.keys().next().value; + const recordStatusRemoteRefreshFailure = Effect.fn( + "GitVcsDriver.recordStatusRemoteRefreshFailure", + )(function* (key: string) { + const nextCount = (statusRemoteRefreshFailures.get(key)?.count ?? 0) + 1; + const now = yield* Clock.currentTimeMillis; + statusRemoteRefreshFailures.delete(key); + statusRemoteRefreshFailures.set(key, { + count: nextCount, + retryAt: now + Duration.toMillis(statusUpstreamRefreshFailureCooldown(nextCount)), + }); + if (statusRemoteRefreshFailures.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) { + const oldestKey = statusRemoteRefreshFailures.keys().next().value; if (oldestKey !== undefined) { - statusRemoteRefreshFailureCounts.delete(oldestKey); + statusRemoteRefreshFailures.delete(oldestKey); } } - }; - const clearStatusRemoteRefreshFailures = (cacheKey: StatusRemoteRefreshCacheKey) => { - statusRemoteRefreshFailureCounts.delete(statusRemoteRefreshFailureKey(cacheKey)); - }; + }); const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* ( cacheKey: StatusRemoteRefreshCacheKey, ) { return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe( - Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))), - Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))), - Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)), Effect.as(true as const), ); }); const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, { capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, - // A failed background fetch is intentionally cached and exponentially - // backed off. Status reads swallow this failure and use the last fetched - // refs, so repeated thread mounts cannot turn a slow or unavailable remote - // into a repository-wide Git subprocess storm. + // Cache/back off failed fetches while status uses old refs; repeated mounts must not cause subprocess storms. timeToLive: (exit, cacheKey) => Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : statusUpstreamRefreshFailureCooldown( - statusRemoteRefreshFailureCounts.get(statusRemoteRefreshFailureKey(cacheKey)) ?? 1, + statusRemoteRefreshFailures.get(statusRemoteRefreshFailureKey(cacheKey))?.count ?? 1, ), }); @@ -1637,7 +1697,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "ensureRemote", )(function* (input) { const preferredName = sanitizeRemoteName(input.preferredName); - const normalizedTargetUrl = normalizeGitRemoteUrl(input.url); + const normalizedTargetUrl = sourceControlDefinitions.repositoryKeyFromRemote(input.url); const remoteFetchUrls = yield* runGitStdout( "GitVcsDriver.ensureRemote.listRemoteUrls", input.cwd, @@ -1645,7 +1705,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { - if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) { + if (sourceControlDefinitions.repositoryKeyFromRemote(remoteUrl) === normalizedTargetUrl) { return remoteName; } } @@ -1667,30 +1727,94 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return remoteName; }); - const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* ( + const resolveComparisonBaseRef = Effect.fn("resolveComparisonBaseRef")(function* ( + cwd: string, + baseRef: string, + ) { + const comparisonRef = + baseRef.startsWith("refs/heads/") || baseRef.startsWith("refs/remotes/") + ? baseRef + : baseRef.includes("/") && !baseRef.startsWith("refs/") + ? `refs/remotes/${baseRef}` + : null; + if (comparisonRef === null) return null; + const resolved = yield* executeGit( + "GitVcsDriver.resolveComparisonBaseRef", + cwd, + ["show-ref", "--verify", "--quiet", comparisonRef], + { allowNonZeroExit: true }, + ); + return resolved.exitCode === 0 ? { baseRef, comparisonRef } : null; + }); + + // Tracking may point to a different remote than the primary one. Resolve its + // full ref so a similarly named local branch or tag cannot shadow it. + const resolveTrackedRemoteBaseRef = Effect.fn("resolveTrackedRemoteBaseRef")(function* ( cwd: string, refName: string, - options?: { readonly allowRemoteOfCurrent?: boolean }, ) { - const configuredBaseBranch = yield* runGitStdout( - "GitVcsDriver.resolveBaseBranchForNoUpstream.config", + const upstream = yield* executeGit( + "GitVcsDriver.resolveTrackedRemoteBaseRef", cwd, - ["config", "--get", `branch.${refName}.gh-merge-base`], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); + ["rev-parse", "--symbolic-full-name", `${refName}@{upstream}`], + { allowNonZeroExit: true }, + ); + const comparisonRef = upstream.stdout.trim(); + if (upstream.exitCode !== 0 || !comparisonRef.startsWith("refs/remotes/")) return null; + return { baseRef: comparisonRef.slice("refs/remotes/".length), comparisonRef }; + }); + + const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* ( + cwd: string, + refName: string, + options?: { + readonly allowRemoteOfCurrent?: boolean; + readonly knownOriginDefaultBranch?: string | null; + }, + ) { + const configuredBaseRef = yield* readConfigValue(cwd, `branch.${refName}.t3-merge-base-ref`); + if ( + configuredBaseRef?.startsWith("refs/heads/") || + configuredBaseRef?.startsWith("refs/remotes/") + ) { + const base = yield* resolveComparisonBaseRef(cwd, configuredBaseRef); + if (base !== null) { + const shortRef = configuredBaseRef.replace(/^refs\/remotes\//, ""); + return { + ...base, + baseRef: (yield* branchExists(cwd, shortRef)) ? configuredBaseRef : shortRef, + }; + } + } + + const configuredBaseBranch = (yield* readBranchBase(cwd, refName)) ?? ""; + const configuredBase = yield* resolveComparisonBaseRef(cwd, configuredBaseBranch); + if ( + configuredBase !== null && + configuredBaseBranch.includes("/") && + !configuredBaseBranch.startsWith("refs/") && + (yield* branchExists(cwd, configuredBaseBranch)) + ) { + const comparisonRef = `refs/heads/${configuredBaseBranch}`; + return { baseRef: comparisonRef, comparisonRef }; + } + if (configuredBase !== null) return configuredBase; const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( Effect.orElseSucceed(() => null), ); - const defaultBranch = - primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName); const candidates = [ - configuredBaseBranch.length > 0 ? configuredBaseBranch : null, - defaultBranch, - ...DEFAULT_BASE_BRANCH_CANDIDATES, + Effect.succeed(configuredBaseBranch), + primaryRemoteName === null + ? Effect.succeed(null) + : primaryRemoteName === "origin" && options?.knownOriginDefaultBranch != null + ? Effect.succeed(options.knownOriginDefaultBranch) + : resolveDefaultBranchName(cwd, primaryRemoteName), + ...DEFAULT_BASE_BRANCH_CANDIDATES.map(Effect.succeed), ]; - for (const candidate of candidates) { + for (const readCandidate of candidates) { + const candidate = yield* readCandidate; if (!candidate) { continue; } @@ -1706,16 +1830,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (normalizedCandidate === refName) { - if ( - options?.allowRemoteOfCurrent && - primaryRemoteName && - (yield* remoteBranchExists({ - cwd, - remoteName: primaryRemoteName, - refName: normalizedCandidate, - })) - ) { - return `${primaryRemoteName}/${normalizedCandidate}`; + if (options?.allowRemoteOfCurrent) { + const trackedRemoteBase = yield* resolveTrackedRemoteBaseRef(cwd, refName); + if (trackedRemoteBase !== null) return trackedRemoteBase; + if ( + primaryRemoteName && + (yield* remoteBranchExists({ + cwd, + remoteName: primaryRemoteName, + refName: normalizedCandidate, + })) + ) { + return { + baseRef: `${primaryRemoteName}/${normalizedCandidate}`, + comparisonRef: `refs/remotes/${primaryRemoteName}/${normalizedCandidate}`, + }; + } } continue; } @@ -1728,11 +1858,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* refName: normalizedCandidate, })) ) { - return `${primaryRemoteName}/${normalizedCandidate}`; + return { + baseRef: `${primaryRemoteName}/${normalizedCandidate}`, + comparisonRef: `refs/remotes/${primaryRemoteName}/${normalizedCandidate}`, + }; } if (yield* branchExists(cwd, normalizedCandidate)) { - return normalizedCandidate; + return { baseRef: normalizedCandidate, comparisonRef: `refs/heads/${normalizedCandidate}` }; } } @@ -1742,16 +1875,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* ( cwd: string, refName: string, + options?: { readonly knownOriginDefaultBranch: string | null }, ) { - const baseRef = yield* resolveBaseBranchForNoUpstream(cwd, refName); - if (!baseRef) { + const base = yield* resolveBaseBranchForNoUpstream(cwd, refName, options); + if (!base) { return 0; } const result = yield* executeGit( "GitVcsDriver.computeAheadCountAgainstBase", cwd, - ["rev-list", "--count", "--end-of-options", `${baseRef}..HEAD`], + ["rev-list", "--count", "--end-of-options", `${base.comparisonRef}..HEAD`], { allowNonZeroExit: true }, ); if (result.exitCode !== 0) { @@ -1807,8 +1941,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const branchValue = branchResult.stdout.trim(); branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null; } - const upstream = yield* resolveCurrentUpstream(cwd); - const upstreamRef = upstream?.upstreamRef ?? null; + const currentUpstreamRef = yield* readCurrentUpstreamRef(cwd); + let upstreamRef = + currentUpstreamRef === null + ? null + : (parseUpstreamRefByFirstSeparator(currentUpstreamRef)?.upstreamRef ?? null); + // Trimming a remote that starts with Unicode whitespace can leave a leading slash. + if (currentUpstreamRef?.startsWith("/")) { + upstreamRef = (yield* resolveCurrentUpstream(cwd, currentUpstreamRef))?.upstreamRef ?? null; + } let aheadCount = 0; let behindCount = 0; @@ -1841,7 +1982,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branch && !isDefaultBranch ? upstreamRef === null ? aheadCount - : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) + : yield* computeAheadCountAgainstBase(cwd, branch, { + knownOriginDefaultBranch: defaultBranch, + }).pipe(Effect.orElseSucceed(() => 0)) : 0; return { @@ -1866,6 +2009,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "status", "--porcelain=2", "--branch", + "-z", ...(includeDivergence ? [] : ["--no-ahead-behind"]), ]; const indexResult = yield* executeGitWithStableDiagnostics( @@ -1943,48 +2087,36 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }), ); const statusCacheKey = repositoryPaths?.gitCommonDir; - const [numstatStdout, defaultBranch, hasPrimaryRemote] = yield* Effect.all( + const [numstatEntries, defaultBranch, hasPrimaryRemote] = yield* Effect.all( [ - // Plumbing, because porcelain `git diff` rewrites the index even with - // GIT_OPTIONAL_LOCKS=0. -M keeps porcelain's rename detection. + // Porcelain diff rewrites indexes despite GIT_OPTIONAL_LOCKS=0; plumbing with -M preserves rename detection. executeGitWithStableDiagnostics( "GitVcsDriver.statusDetails.numstat", cwd, - ["diff-index", "-M", "--numstat", "HEAD", "--"], + ["diff-index", "-M", "--numstat", "-z", "HEAD", "--"], { allowNonZeroExit: true }, ).pipe( Effect.flatMap((result) => { - if (result.exitCode === 0) return Effect.succeed(result.stdout); + if (result.exitCode === 0) return Effect.succeed(parseReviewNumstat(result.stdout)); if (isUnbornHeadStderr(result.stderr)) { return Effect.map( Effect.all([ runGitStdout("GitVcsDriver.statusDetails.numstat.unborn", cwd, [ "diff-files", "--numstat", + "-z", ]), runGitStdout("GitVcsDriver.statusDetails.numstat.unborn.staged", cwd, [ "diff", "--cached", "--numstat", + "-z", ]), ]), - ([unstagedStdout, stagedStdout]) => { - const staged = parseNumstatEntries(stagedStdout); - const unstaged = parseNumstatEntries(unstagedStdout); - const map = new Map(); - for (const entry of [...staged, ...unstaged]) { - const existing = map.get(entry.path) ?? { - insertions: 0, - deletions: 0, - }; - existing.insertions += entry.insertions; - existing.deletions += entry.deletions; - map.set(entry.path, existing); - } - return Array.from(map.entries()) - .map(([p, s]) => `${s.insertions}\t${s.deletions}\t${p}`) - .join("\n"); - }, + ([unstagedStdout, stagedStdout]) => [ + ...parseReviewNumstat(stagedStdout), + ...parseReviewNumstat(unstagedStdout), + ], ); } return Effect.fail( @@ -1992,7 +2124,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ...gitCommandContext({ operation: "GitVcsDriver.statusDetails.numstat", cwd, - args: ["diff-index", "-M", "--numstat", "HEAD", "--"], + args: ["diff-index", "-M", "--numstat", "-z", "HEAD", "--"], }), detail: "git diff-index HEAD --numstat failed.", exitCode: result.exitCode, @@ -2021,7 +2153,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* let hasWorkingTreeChanges = false; const changedFilesWithoutNumstat = new Set(); - for (const line of statusStdout.split(/\r?\n/g)) { + const statusRecords = statusStdout.split("\0"); + for (let index = 0; index < statusRecords.length; index++) { + const line = statusRecords[index]!; if (line.startsWith("# branch.head ")) { const value = line.slice("# branch.head ".length).trim(); refName = value.startsWith("(") ? null : value; @@ -2039,10 +2173,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* behindCount = parsed.behind; continue; } - if (line.trim().length > 0 && !line.startsWith("#")) { + if (line.length > 0 && !line.startsWith("#")) { hasWorkingTreeChanges = true; const pathValue = parsePorcelainPath(line); if (pathValue) changedFilesWithoutNumstat.add(pathValue); + // A rename record is followed by its original path as a separate record. Listing it + // keeps the deletion selectable when committing only some files. + if (line.startsWith("2 ")) { + const originalPath = statusRecords[++index]; + if (originalPath) changedFilesWithoutNumstat.add(originalPath); + } } } @@ -2067,10 +2207,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0)); } - const numstatEntries = parseNumstatEntries(numstatStdout); const fileStatMap = new Map(); for (const entry of numstatEntries) { - fileStatMap.set(entry.path, { insertions: entry.insertions, deletions: entry.deletions }); + const stat = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; + stat.insertions += entry.additions; + stat.deletions += entry.deletions; + fileStatMap.set(entry.path, stat); } let insertions = 0; @@ -2103,6 +2245,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* upstreamRef, hasWorkingTreeChanges, workingTree: { + ...(repositoryPaths?.worktreeRoot ? { rootPath: repositoryPaths.worktreeRoot } : {}), files, insertions, deletions, @@ -2196,7 +2339,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* runGit( "GitVcsDriver.commit.addSelected", cwd, - [...config, "--literal-pathspecs", "add", "-A", "--", ...filePaths], + // Status paths are repository-relative, while cwd can be a subdirectory. + [...config, "add", "-A", "--", ...filePaths.map((file) => `:(top,literal)${file}`)], env ? { env } : {}, ); } else { @@ -2210,7 +2354,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const prepareCommitContext: GitVcsDriver.GitVcsDriver["Service"]["prepareCommitContext"] = - Effect.fn("prepareCommitContext")(function* (cwd, filePaths) { + Effect.fn("prepareCommitContext")(function* (cwd, filePaths, options) { return yield* Effect.scoped( Effect.gen(function* () { const indexValue = yield* runGitStdout( @@ -2263,6 +2407,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return null; } + // A user-supplied message needs change detection, but no patch for generation. + if (options?.includePatch === false) return { stagedSummary, stagedPatch: "" }; + const stagedPatch = yield* runGitStdoutWithOptions( "GitVcsDriver.prepareCommitContext.stagedPatch", cwd, @@ -2386,12 +2533,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; } - const hasRemoteBranch = yield* remoteBranchExists({ + const publishBranch = yield* resolvePublishBranchName(cwd, branch); + // The configured diff base can contain HEAD while the publish branch is still behind. + const publishContainsHead = yield* executeGit( + "GitVcsDriver.pushCurrentBranch.publishContainsHead", cwd, - remoteName: publishRemoteName, - refName: branch, - }).pipe(Effect.orElseSucceed(() => false)); - if (hasRemoteBranch) { + [ + "merge-base", + "--is-ancestor", + "HEAD", + `refs/remotes/${publishRemoteName}/${publishBranch}`, + ], + { allowNonZeroExit: true }, + ).pipe( + Effect.map((result) => result.exitCode === 0), + Effect.orElseSucceed(() => false), + ); + if (publishContainsHead) { return { status: "skipped_up_to_date" as const, branch, @@ -2431,11 +2589,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); if (currentUpstream) { - // A branch tracking a differently named ref was cut from it, the way `git - // checkout -b feature origin/dev` and our own worktree flow leave it. - // That upstream is the branch's base, not its publish target, and pushing - // HEAD onto it would write feature commits to a shared branch (bare `git - // push` refuses this under push.default=simple). + // Differently named upstreams are bases, not publish targets; pushing HEAD there would write features to shared branches. const isAliasOfUpstreamHead = branch === currentUpstream.branchName || (branch.endsWith(`/${currentUpstream.branchName}`) && @@ -2446,21 +2600,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); const remoteName = publishRemoteName ?? currentUpstream.remoteName; const publishBranch = yield* resolvePublishBranchName(cwd, branch); - // `-u` retargets the upstream to the published branch, so keep the - // base recorded first; base resolution reads gh-merge-base before the - // upstream ref. - const configuredMergeBase = yield* runGitStdout( - "GitVcsDriver.pushCurrentBranch.readMergeBase", - cwd, - ["config", "--get", `branch.${branch}.gh-merge-base`], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (configuredMergeBase.length === 0) { + // Publishing retargets the upstream, so preserve its comparison base first. + if ((yield* readBranchBase(cwd, branch)) === null) { yield* runGit("GitVcsDriver.pushCurrentBranch.recordMergeBase", cwd, [ "config", - `branch.${branch}.gh-merge-base`, + branchBaseConfigKey(branch), currentUpstream.branchName, ]); + if (!(yield* readConfigValue(cwd, `branch.${branch}.t3-merge-base-ref`))) { + yield* runGit("GitVcsDriver.pushCurrentBranch.recordComparisonRef", cwd, [ + "config", + `branch.${branch}.t3-merge-base-ref`, + `refs/remotes/${currentUpstream.upstreamRef}`, + ]); + } } yield* runGit( "GitVcsDriver.pushCurrentBranch.pushOwnBranch", @@ -2502,7 +2655,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn( "pullCurrentBranch", )(function* (cwd) { - const details = yield* statusDetails(cwd); + const details = yield* readStatusDetailsLocal(cwd); const refName = details.branch; if (!refName) { return yield* new GitCommandError({ @@ -2524,6 +2677,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: "Current branch has no upstream configured. Push with upstream first.", }); } + const remote = yield* readConfigValue(cwd, `branch.${refName}.remote`); + if (remote) { + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const pending = statusFetches.get(`${gitCommonDir}\0${remote}`); + // The status wait can finish while its fetch still owns reference locks. + // Let our existing writer finish before starting the pull's fetch. + if (pending) yield* Fiber.await(pending); + } const beforeSha = yield* runGitStdout( "GitVcsDriver.pullCurrentBranch.beforeSha", cwd, @@ -2533,11 +2694,67 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // After a successful pull, HEAD before and after decides the result, so its output is not // needed. A large fast-forward's diffstat can exceed the output cap, which must not fail a // pull Git applied. - yield* executeGit("GitVcsDriver.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { + const options = { timeoutMs: 30_000, - fallbackErrorDetail: "git pull failed", appendTruncationMarker: true, - }); + allowNonZeroExit: true, + }; + let args = ["pull", "--ff-only"]; + let result = yield* executeGitWithStableDiagnostics( + "GitVcsDriver.pullCurrentBranch.pull", + cwd, + args, + options, + ); + if (result.exitCode !== 0 && isRefLockFailure(result.stderr)) { + const [remote, mergeRefs, currentBranch, currentSha] = yield* Effect.all([ + readConfigValue(cwd, `branch.${refName}.remote`), + runGitStdout( + "GitVcsDriver.pullCurrentBranch.mergeRefs", + cwd, + ["config", "--get-all", `branch.${refName}.merge`], + true, + ).pipe(Effect.map((stdout) => stdout.trim().split("\n").filter(Boolean))), + runGitStdout( + "GitVcsDriver.pullCurrentBranch.currentBranch", + cwd, + ["symbolic-ref", "--quiet", "--short", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())), + runGitStdout("GitVcsDriver.pullCurrentBranch.currentSha", cwd, ["rev-parse", "HEAD"]).pipe( + Effect.map((stdout) => stdout.trim()), + ), + ]); + // A full fetch can fail on an unrelated branch's lock. Keep that fetch as the + // default, but retry only the configured upstream before any checkout movement. + const [mergeRef] = mergeRefs; + if ( + remote && + mergeRef && + mergeRefs.length === 1 && + currentBranch === refName && + currentSha === beforeSha + ) { + args = ["pull", "--ff-only", "--", remote, mergeRef]; + result = yield* executeGitWithStableDiagnostics( + "GitVcsDriver.pullCurrentBranch.pull", + cwd, + args, + options, + ); + } + } + if (result.exitCode !== 0) { + const reason = classifyGitFailure(result.stderr); + return yield* new GitCommandError({ + ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch.pull", cwd, args }), + ...(reason === null ? {} : { reason }), + detail: fetchFailureDetail(result.stderr) ?? "git pull failed", + exitCode: result.exitCode, + stdoutLength: result.stdout.length, + stderrLength: result.stderr.length, + }); + } const afterSha = yield* runGitStdout( "GitVcsDriver.pullCurrentBranch.afterSha", cwd, @@ -2545,7 +2762,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* true, ).pipe(Effect.map((stdout) => stdout.trim())); - const refreshed = yield* statusDetails(cwd); + const refreshed = yield* readStatusDetailsLocal(cwd); return { status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", refName, @@ -2632,8 +2849,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (indexExists) { const { mtime } = yield* fileSystem.stat(indexPath); yield* fileSystem.copyFile(indexPath, tempIndexPath); - // Node FileSystem.stat truncates bigint timestamps to milliseconds before creating its Date. - // Flooring preserves the source second without making preceding-second files racy. + // stat truncates bigint times to ms; floor seconds to avoid making preceding-second files racy. const indexTime = Option.isSome(mtime) ? Math.max(0, Math.floor(mtime.value.getTime() / 1000)) : 0; @@ -2660,6 +2876,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, [ ...tempIndexConfig, + // Avoid redundant tracked-entry pathspec matching in this disposable index. + "-c", + "core.preloadIndex=false", "--literal-pathspecs", "add", "--intent-to-add", @@ -2725,15 +2944,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* branch: string | null, explicitBaseRef?: string, ) { - const baseRef = - explicitBaseRef ?? - (branch - ? yield* resolveBaseBranchForNoUpstream(cwd, branch, { allowRemoteOfCurrent: true }).pipe( - Effect.orElseSucceed(() => null), - ) - : null); - if (baseRef === null) return { baseRef, mergeBase: "HEAD" }; - const args = ["merge-base", "--end-of-options", baseRef, "HEAD"]; + const base = + explicitBaseRef !== undefined + ? ((yield* resolveComparisonBaseRef(cwd, explicitBaseRef)) ?? { + baseRef: explicitBaseRef, + comparisonRef: + !explicitBaseRef.startsWith("refs/") && (yield* branchExists(cwd, explicitBaseRef)) + ? `refs/heads/${explicitBaseRef}` + : explicitBaseRef, + }) + : branch + ? yield* resolveBaseBranchForNoUpstream(cwd, branch, { allowRemoteOfCurrent: true }).pipe( + Effect.orElseSucceed(() => null), + ) + : null; + if (base === null) return { baseRef: null, mergeBase: "HEAD" }; + const { baseRef, comparisonRef } = base; + const args = ["merge-base", "--end-of-options", comparisonRef, "HEAD"]; const result = yield* executeGit("GitVcsDriver.resolveReviewMergeBase", cwd, args, { allowNonZeroExit: true, }); @@ -2838,6 +3065,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const diffArgs = [ ...REVIEW_DIFF_ARGS, + "--minimal", ...(input.ignoreWhitespace ? ["--ignore-all-space"] : []), ]; const readStats = Effect.fn("GitVcsDriver.getReviewDiffPreview.stat")(function* ( @@ -3097,7 +3325,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); - const resolveBranchName = Effect.fn("GitVcsDriver.resolveBranchName")(function* ( + const readBranchBase: GitVcsDriver.GitVcsDriver["Service"]["readBranchBase"] = Effect.fn( + "GitVcsDriver.readBranchBase", + )(function* (cwd, branch) { + const base = yield* readConfigValue(cwd, branchBaseConfigKey(branch)); + return base ?? (yield* readConfigValue(cwd, legacyBranchBaseConfigKey(branch))); + }); + + const resolveBranchBase = Effect.fn("GitVcsDriver.resolveBranchBase")(function* ( cwd: string, refName: string, ) { @@ -3112,19 +3347,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); return remoteName && (yield* remoteBranchExists({ cwd, remoteName, refName })) - ? refName + ? { baseRef: `refs/remotes/${remoteName}/${refName}`, branchName: refName } : null; } const ref = result.stdout.trim(); - if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length); + if (ref.startsWith("refs/heads/")) { + const branchName = ref.slice("refs/heads/".length); + return { baseRef: ref, branchName }; + } if (!ref.startsWith("refs/remotes/")) return null; const remoteNames = yield* listRemoteNames(cwd); - return ( - parseRemoteRefWithRemoteNames( - ref.slice("refs/remotes/".length), - remoteNames.toSorted((left, right) => right.length - left.length), - )?.branchName ?? null + const remoteRef = parseRemoteRefWithRemoteNames( + ref.slice("refs/remotes/".length), + remoteNames.toSorted((left, right) => right.length - left.length), ); + return remoteRef ? { baseRef: ref, branchName: remoteRef.branchName } : null; + }); + + const resolveBranchName = Effect.fn("GitVcsDriver.resolveBranchName")(function* ( + cwd: string, + refName: string, + ) { + const base = yield* resolveBranchBase(cwd, refName); + return base?.branchName ?? null; }); const readGitRefsSnapshot = Effect.fn("readGitRefsSnapshot")(function* (gitCommonDir: string) { @@ -3139,7 +3384,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* [ ...gitDirArgs, "for-each-ref", - "--format=%(refname)%09%(committerdate:unix)%09%(symref)", + "--format=%(refname)%09%(committerdate:unix)%09%(symref)%09%(upstream)", "refs/heads", "refs/remotes", ], @@ -3189,13 +3434,17 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* [branchName, path.normalize(path.resolve(worktreePath))] as const, ) : []; + // Without `core.worktree`, Git reports a separate git dir as the main checkout. + const normalizedGitCommonDir = path.normalize(path.resolve(gitCommonDir)); const existingWorktreeEntries = yield* Effect.filter( parsedWorktreeEntries, ([, worktreePath]) => - fileSystem.stat(worktreePath).pipe( - Effect.as(true), - Effect.orElseSucceed(() => false), - ), + worktreePath === normalizedGitCommonDir + ? Effect.succeed(false) + : fileSystem.stat(worktreePath).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), { concurrency: 16 }, ); const worktreeMap = new Map(existingWorktreeEntries); @@ -3204,7 +3453,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* for (const line of refsResult.stdout.split("\n")) { if (line.length === 0) continue; - const [fullRefName, lastCommitRaw, symbolicTarget] = line.split("\t"); + const [fullRefName, lastCommitRaw, symbolicTarget, upstreamRef] = line.split("\t"); if (!fullRefName || symbolicTarget) continue; const parsedLastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); const lastCommit = Number.isFinite(parsedLastCommit) ? parsedLastCommit : 0; @@ -3218,6 +3467,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* isRemote: false, isDefault: name === defaultBranch, worktreePath: worktreeMap.get(name) ?? null, + ...(upstreamRef ? { upstreamRef } : {}), }, lastCommit, }); @@ -3322,10 +3572,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const currentEpoch = listRefsEpochByCommonDir.get(gitCommonDir); const snapshot = refresh || currentEpoch === undefined - ? // The refresh cache owns the complete snapshot read, rather than only the - // epoch bump. Slow repositories therefore remain singleflight for the - // entire Git scan even when more refresh requests arrive after the - // coalescing TTL would otherwise have elapsed. + ? // Cache the entire snapshot read so slow scans stay single-flight beyond the coalescing TTL. yield* Cache.get( listRefsRefreshSnapshotCache, new GitRefsRefreshCacheKey({ gitCommonDir, generation }), @@ -3386,6 +3633,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* snapshot.localBranches.some((ref) => ref.worktreePath === repositoryPaths.worktreeRoot); const localBranches = snapshot.localBranches.map((ref) => ({ ...ref, + worktreePath: + ref.worktreePath ?? + (ref.name === repositoryPaths.currentBranch ? repositoryPaths.worktreeRoot : null), current: hasCurrentWorktreeBranch ? ref.worktreePath === repositoryPaths.worktreeRoot : ref.name === repositoryPaths.currentBranch, @@ -3411,6 +3661,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); return { + ...(repositoryPaths.isAtRepositoryRoot === undefined + ? {} + : { isAtRepositoryRoot: repositoryPaths.isAtRepositoryRoot }), refs: [...refs.refs], isRepo: true, hasPrimaryRemote: snapshot.hasPrimaryRemote, @@ -3427,7 +3680,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* refuseOptionLikeRefName("GitVcsDriver.createWorktree", input.cwd, input.newRefName); const targetBranch = input.newRefName ?? input.refName; const sanitizedBranch = targetBranch.replace(/\//g, "-"); - // resolve: a cwd like `/sub/..` must not name the folder `..`. + // Resolve sub/.. before taking the basename. const repoName = path.basename(path.resolve(input.cwd)); let worktreePath = input.path; if (worktreePath == null) { @@ -3454,7 +3707,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const onCheckoutProgress = progress?.onCheckoutProgress; const checkoutWorkers = (yield* readConfigValue(input.cwd, "checkout.workers")) ?? "0"; - yield* executeGit( + yield* executeGitWithStableDiagnostics( "GitVcsDriver.createWorktree", input.cwd, ["-c", `checkout.workers=${checkoutWorkers}`, ...args], @@ -3465,7 +3718,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? { // Git only prints checkout progress when stderr is a tty or the // delay elapsed. GIT_PROGRESS_DELAY=0 forces it through the pipe. - env: { GIT_PROGRESS_DELAY: "0", LC_ALL: "C" }, + env: { GIT_PROGRESS_DELAY: "0" }, progress: { onStderrLine: (line) => { const parsed = parseGitCheckoutProgressLine(line); @@ -3481,9 +3734,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* progress.onWorktreeClaimed(worktreePath); } - // `git worktree add` leaves submodules empty, so a repo that keeps agent - // skills, tooling or source in one gets a worktree that is quietly missing - // them. + // worktree add leaves submodules empty, potentially omitting project skills, tools or source. const hasSubmodules = yield* fileSystem .exists(path.join(worktreePath, ".gitmodules")) .pipe(Effect.orElseSucceed(() => false)); @@ -3549,14 +3800,32 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } - if (input.newRefName && input.baseRefName) { - const baseBranch = yield* resolveBranchName(input.cwd, input.baseRefName); - if (baseBranch) { - yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [ - "config", - `branch.${input.newRefName}.gh-merge-base`, - baseBranch, - ]); + const newRefName = input.newRefName; + if (newRefName && input.baseRefName) { + const base = yield* resolveBranchBase(input.cwd, input.baseRefName); + if (base) { + yield* Effect.gen(function* () { + yield* runGit("GitVcsDriver.createWorktree.configureBaseRef", input.cwd, [ + "config", + branchBaseConfigKey(newRefName), + base.branchName, + ]); + if (base.baseRef.startsWith("refs/remotes/")) { + // The base key names a branch on the host; this one keeps the remote it came from. + yield* runGit("GitVcsDriver.createWorktree.configureComparisonRef", input.cwd, [ + "config", + `branch.${input.newRefName}.t3-merge-base-ref`, + base.baseRef, + ]); + } + }).pipe( + Effect.catchTags({ + GitCommandError: () => + Effect.logWarning( + "worktree base-ref configuration failed; using base-branch fallback", + ), + }), + ); } } @@ -3568,25 +3837,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; }); - const fetchPullRequestBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestBranch"] = - Effect.fn("fetchPullRequestBranch")(function* (input) { - const remoteName = yield* resolvePrimaryRemoteName(input.cwd); - yield* executeGit( - "GitVcsDriver.fetchPullRequestBranch", - input.cwd, - [ - "fetch", - "--quiet", - "--no-tags", - "--", - remoteName, - `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, - ], - { - fallbackErrorDetail: "git fetch pull request branch failed", - }, - ); - }); + const fetchRefIntoBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRefIntoBranch"] = Effect.fn( + "GitVcsDriver.fetchRefIntoBranch", + )(function* (input) { + const remoteName = yield* resolvePrimaryRemoteName(input.cwd); + yield* executeGit( + "GitVcsDriver.fetchRefIntoBranch", + input.cwd, + [ + "fetch", + "--quiet", + "--no-tags", + "--", + remoteName, + `+${input.ref}:refs/heads/${input.branch}`, + ], + { + fallbackErrorDetail: "git fetch ref into branch failed", + }, + ); + }); const resolveCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveCommit"] = Effect.fn( "resolveCommit", @@ -3600,22 +3870,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { commitSha }; }); - const fetchPullRequestHeadCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchPullRequestHeadCommit"] = - Effect.fn("fetchPullRequestHeadCommit")(function* (input) { - const remoteName = yield* resolvePrimaryRemoteName(input.cwd); - // No refspec destination: the pull head lands in FETCH_HEAD (per worktree) instead of a - // branch, which is the only way to read it while that branch is checked out somewhere. - yield* executeGit( - "GitVcsDriver.fetchPullRequestHeadCommit", - input.cwd, - ["fetch", "--quiet", "--no-tags", "--", remoteName, `refs/pull/${input.prNumber}/head`], - { - fallbackErrorDetail: "git fetch pull request head failed", - }, - ); + const fetchRefCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchRefCommit"] = Effect.fn( + "GitVcsDriver.fetchRefCommit", + )(function* (input) { + const remoteName = yield* resolvePrimaryRemoteName(input.cwd); + // No refspec destination: the ref lands in FETCH_HEAD (per worktree) instead of a branch, + // which is the only way to read it while that branch is checked out somewhere. + yield* executeGit( + "GitVcsDriver.fetchRefCommit", + input.cwd, + ["fetch", "--quiet", "--no-tags", "--", remoteName, input.ref], + { + fallbackErrorDetail: "git fetch ref failed", + }, + ); - return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" }); - }); + return yield* resolveCommit({ cwd: input.cwd, revision: "FETCH_HEAD" }); + }); const refreshCheckedOutBranch: GitVcsDriver.GitVcsDriver["Service"]["refreshCheckedOutBranch"] = Effect.fn("refreshCheckedOutBranch")(function* (input) { @@ -3639,17 +3910,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["merge-base", "--is-ancestor", headCommit, input.targetCommit], { allowNonZeroExit: true }, ).pipe(Effect.map((result) => result.exitCode === 0)); - // A rewritten head (rebase, squash, amend) does not descend from the checkout, so it can - // only be taken by resetting. That is lossless exactly when the tree is clean and HEAD - // never left the commit the upstream held before the fetch. + // Rewritten heads require reset; allow only clean checkouts still at the pre-fetch upstream commit. if (!isAncestor && headCommit !== input.resetWhenHeadCommit) { return { headCommit, moved: false, onTarget: false }; } if (!isAncestor) { - // The commit being reset away is about to be reachable from nothing. It is only ever a - // commit the remote already held, but "the remote held it" stops being a way back once - // the head it belonged to has been rewritten, so a ref keeps it findable. + // Retain the reset-away commit; rewritten remote heads no longer provide a path back. yield* executeGit( "GitVcsDriver.refreshCheckedOutBranch.keepPrevious", input.cwd, @@ -3661,10 +3928,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* executeGit( "GitVcsDriver.refreshCheckedOutBranch.move", input.cwd, - // `--merge` rather than `--hard`: the cleanliness check above is a snapshot, and another - // thread may edit a tracked file between it and this move. Git itself refuses a `--merge` - // reset that would overwrite such an edit — the same guarantee `--ff-only` gives the - // other branch — so a race loses nothing; the refresh fails and is reported instead. + // reset --merge refuses tracked edits racing our cleanliness check, preserving work like --ff-only does. isAncestor ? ["merge", "--ff-only", input.targetCommit] : ["reset", "--merge", input.targetCommit], @@ -3677,83 +3941,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { headCommit: input.targetCommit, moved: true, onTarget: true }; }); - const fetchRemote: GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"] = Effect.fn("fetchRemote")( - function* (input) { - const args = ["fetch", "--quiet", "--", input.remoteName]; - const options = { - env: STATUS_UPSTREAM_REFRESH_ENV, - fallbackErrorDetail: `git fetch ${input.remoteName} failed`, - }; - // Another fetch in the same repository, such as the background status - // poll, can win the race for a remote-tracking ref. The loser fails, but - // the ref is free again by the time a rerun needs it, so retry once. - const runFetch = (fetchArgs: readonly string[]) => { - const run = executeGitWithStableDiagnostics( - "GitVcsDriver.fetchRemote", - input.cwd, - fetchArgs, - { - ...options, - allowNonZeroExit: true, - }, - ); - return run.pipe( - Effect.flatMap((result) => - result.exitCode !== 0 && isRefLockFailure(result.stderr) ? run : Effect.succeed(result), - ), - ); - }; - const fetchAll = runFetch(args).pipe( + const fetchRemote = Effect.fn("fetchRemote")(function* (input: GitVcsDriver.GitFetchRemoteInput) { + const args = ["fetch", "--quiet", "--", input.remoteName]; + const options = { + env: STATUS_UPSTREAM_REFRESH_ENV, + fallbackErrorDetail: `git fetch ${input.remoteName} failed`, + }; + // Another fetch in the same repository, such as the background status + // poll, can win the race for a remote-tracking ref. The loser fails, but + // the ref is free again by the time a rerun needs it, so retry once. + const runFetch = (fetchArgs: readonly string[]) => { + const run = executeGitWithStableDiagnostics( + "GitVcsDriver.fetchRemote", + input.cwd, + fetchArgs, + { + ...options, + allowNonZeroExit: true, + }, + ); + return run.pipe( Effect.flatMap((result) => - result.exitCode === 0 - ? Effect.void - : Effect.fail( - new GitCommandError({ - ...gitCommandContext({ - operation: "GitVcsDriver.fetchRemote", - cwd: input.cwd, - args, - }), - detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail, - ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), - stdoutLength: result.stdout.length, - stderrLength: result.stderr.length, - }), - ), + result.exitCode !== 0 && isRefLockFailure(result.stderr) ? run : Effect.succeed(result), ), ); - if (input.refName === undefined) { - return yield* fetchAll.pipe(Effect.asVoid); - } - const branch = - parseRemoteRefWithRemoteNames(input.refName, [input.remoteName])?.branchName ?? - input.refName; - const scopedArgs = [ - ...args, - `+refs/heads/${branch}:refs/remotes/${input.remoteName}/${branch}`, - ]; - const result = yield* runFetch(scopedArgs); - if (result.exitCode === 0) return; - if ( - result.stderr - .split(/\r?\n/) - .includes(`fatal: couldn't find remote ref refs/heads/${branch}`) - ) { - return yield* fetchAll.pipe(Effect.asVoid); - } - return yield* new GitCommandError({ - ...gitCommandContext({ - operation: "GitVcsDriver.fetchRemote", - cwd: input.cwd, - args: scopedArgs, - }), - detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail, - ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), - stdoutLength: result.stdout.length, - stderrLength: result.stderr.length, - }); - }, - ); + }; + const fetchAll = runFetch(args).pipe( + Effect.flatMap((result) => + result.exitCode === 0 + ? Effect.void + : Effect.fail( + new GitCommandError({ + ...gitCommandContext({ + operation: "GitVcsDriver.fetchRemote", + cwd: input.cwd, + args, + }), + detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail, + ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), + stdoutLength: result.stdout.length, + stderrLength: result.stderr.length, + }), + ), + ), + ); + if (input.refName === undefined) { + return yield* fetchAll.pipe(Effect.as(true)); + } + const branch = + parseRemoteRefWithRemoteNames(input.refName, [input.remoteName])?.branchName ?? input.refName; + const scopedArgs = [ + ...args, + `+refs/heads/${branch}:refs/remotes/${input.remoteName}/${branch}`, + ]; + const result = yield* runFetch(scopedArgs); + if (result.exitCode === 0) return true; + if ( + result.stderr.split(/\r?\n/).includes(`fatal: couldn't find remote ref refs/heads/${branch}`) + ) { + return false; + } + return yield* new GitCommandError({ + ...gitCommandContext({ + operation: "GitVcsDriver.fetchRemote", + cwd: input.cwd, + args: scopedArgs, + }), + detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail, + ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), + stdoutLength: result.stdout.length, + stderrLength: result.stderr.length, + }); + }); const resolveRemoteTrackingCommit: GitVcsDriver.GitVcsDriver["Service"]["resolveRemoteTrackingCommit"] = Effect.fn("resolveRemoteTrackingCommit")(function* (input) { @@ -3773,6 +4032,62 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { commitSha, remoteRefName }; }); + const resolveWorktreeBaseRemote: GitVcsDriver.GitVcsDriver["Service"]["resolveWorktreeBaseRemote"] = + Effect.fn("resolveWorktreeBaseRemote")(function* (input) { + const remoteNames = (yield* listRemoteNames(input.cwd)).toSorted( + (left, right) => right.length - left.length, + ); + // Upstream atoms read config even before the tracking ref has been fetched. + // Match the exact local ref: for-each-ref also returns its descendants. + const localBranch = yield* runGitStdout("GitVcsDriver.resolveWorktreeBaseRemote", input.cwd, [ + "for-each-ref", + "--format=%(refname)\t%(upstream:remotename)\t%(upstream:remoteref)", + `refs/heads/${input.refName}`, + ]).pipe( + Effect.map((stdout) => + stdout + .split("\n") + .map((line) => line.split("\t")) + .find(([refName]) => refName === `refs/heads/${input.refName}`), + ), + ); + let target: { remoteName: string; branchName: string } | null; + if (localBranch) { + // A remote of "." tracks another local branch; it is not a remote name. + const [, remoteName = "", merge = ""] = localBranch; + target = + remoteNames.includes(remoteName) && merge.startsWith("refs/heads/") + ? { remoteName, branchName: merge.slice("refs/heads/".length) } + : null; + } else { + target = parseRemoteRefWithRemoteNames(input.refName, remoteNames); + } + const { remoteName, branchName } = target ?? { + remoteName: "origin", + branchName: input.refName, + }; + return remoteNames.includes(remoteName) ? { remoteName, branchName } : null; + }); + + const fetchWorktreeBaseCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchWorktreeBaseCommit"] = + Effect.fn("fetchWorktreeBaseCommit")(function* (input) { + const target = yield* resolveWorktreeBaseRemote(input); + if (target === null) return null; + const { remoteName, branchName } = target; + const remoteRefName = `${remoteName}/${branchName}`; + // A missing remote branch can leave a stale tracking ref; never resolve it. + if (!(yield* fetchRemote({ cwd: input.cwd, remoteName, refName: remoteRefName }))) { + return null; + } + const resolved = yield* executeGit( + "GitVcsDriver.fetchWorktreeBaseCommit", + input.cwd, + ["rev-parse", "--verify", "--quiet", `refs/remotes/${remoteRefName}^{commit}`], + { allowNonZeroExit: true }, + ); + return resolved.exitCode === 0 ? { commitSha: resolved.stdout.trim(), remoteRefName } : null; + }); + const fetchRemoteBranch: GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteBranch"] = Effect.fn( "fetchRemoteBranch", )(function* (input) { @@ -3817,34 +4132,74 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* input.branch, ]); + /** + * Unlinks links under `target` without following them and removes the + * directories that leaves empty. Returns false when anything else remains. + */ + // Recursive filesystem traversal can visit many entries; removeWorktree owns the operation span. + const removeLeftoverLinks = Effect.fnUntraced(function* ( + target: string, + ): Effect.fn.Return { + if (Option.isSome(yield* fileSystem.readLink(target).pipe(Effect.option))) { + yield* fileSystem.remove(target); + return true; + } + if ((yield* fileSystem.stat(target)).type !== "Directory") return false; + let empty = true; + for (const name of yield* fileSystem.readDirectory(target)) { + if (!(yield* removeLeftoverLinks(path.join(target, name)))) empty = false; + } + // Only an empty directory goes, so files written since the listing stay. + return empty && (yield* removeEmptyDirectory(target)); + }); + const removeWorktree: GitVcsDriver.GitVcsDriver["Service"]["removeWorktree"] = Effect.fn( "removeWorktree", )(function* (input) { - // Git refuses to remove a worktree with untracked files unless forced, but - // its check honors `status.showUntrackedFiles=no` and would delete them. - const args = ["-c", "status.showUntrackedFiles=normal", "worktree", "remove"]; - if (input.force) { - args.push("--force"); - } - args.push("--", input.path); - const result = yield* executeGitWithStableDiagnostics( - "GitVcsDriver.removeWorktree", - input.cwd, - args, - { - timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS, - allowNonZeroExit: true, - }, + // Git also matches a worktree by its short name, which can name a different + // folder than this path. Resolving it once keeps Git, the Windows deletion + // in removeLinkedWorktree, and the leftover cleanup below on one directory. + const target = path.resolve(input.cwd, input.path); + const result = yield* removeLinkedWorktree({ + operation: "GitVcsDriver.removeWorktree", + cwd: input.cwd, + worktreePath: target, + force: input.force === true, + execute, + run: (args) => + executeGitWithStableDiagnostics("GitVcsDriver.removeWorktree", input.cwd, args, { + timeoutMs: WORKTREE_REMOVE_TIMEOUT_MS, + allowNonZeroExit: true, + }).pipe(Effect.map((result) => ({ ...result, args }))), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), ); if (result.exitCode === 0) { + // Git for Windows reports success without removing NTFS junctions or their parent directories. + // Log leftover cleanup failures: Git already unregistered the worktree, so removal cannot be retried. + if (yield* fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false))) { + const removed = yield* removeLeftoverLinks(target).pipe( + Effect.catch((error) => + Effect.logWarning("GitVcsDriver.removeWorktree: failed to delete leftover links", { + path: target, + error, + }).pipe(Effect.as(true)), + ), + ); + if (!removed) { + yield* Effect.logWarning( + "GitVcsDriver.removeWorktree: kept files written after git removed the worktree", + { path: target }, + ); + } + } return; } - // Threads can share a worktree path, and worktrees get removed or pruned - // outside the app, so a worktree that is already gone is a no-op rather - // than an error. + // Threads share paths and outside Git can remove worktrees; already-gone removals are no-ops. const alreadyGone = isMissingWorktreeStderr(result.stderr) && - !(yield* fileSystem.exists(input.path).pipe(Effect.orElseSucceed(() => false))); + !(yield* fileSystem.exists(target).pipe(Effect.orElseSucceed(() => false))); if (alreadyGone) { yield* pruneWorktrees({ cwd: input.cwd }); return; @@ -3853,7 +4208,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* `GitVcsDriver.removeWorktree: git worktree remove exited with code ${result.exitCode} for ${input.path} (stderr length ${result.stderr.length}).`, ); return yield* new GitCommandError({ - ...gitCommandContext({ operation: "GitVcsDriver.removeWorktree", cwd: input.cwd, args }), + ...gitCommandContext({ + operation: "GitVcsDriver.removeWorktree", + cwd: input.cwd, + args: result.args, + }), detail: "git worktree remove failed", ...(result.exitCode === null ? {} : { exitCode: result.exitCode }), stdoutLength: result.stdout.length, @@ -3979,10 +4338,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* yield* refuseOptionLikeRefName("GitVcsDriver.switchRef", input.cwd, checkoutArgs.at(-1)); // A stale ref must not turn into a path checkout that discards local edits. - yield* executeGit("GitVcsDriver.switchRef.checkout", input.cwd, [...checkoutArgs, "--"], { - timeoutMs: 10_000, - fallbackErrorDetail: "git checkout failed", - }); + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.switchRef.checkout", + input.cwd, + [...checkoutArgs, "--"], + { + timeoutMs: 10_000, + fallbackErrorDetail: "git checkout failed", + }, + ); const refName = yield* runGitStdout("GitVcsDriver.switchRef.currentBranch", input.cwd, [ "branch", @@ -4036,8 +4400,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const listWorktreePaths: GitVcsDriver.GitVcsDriver["Service"]["listWorktreePaths"] = (cwd) => executeWorktreeList("GitVcsDriver.listWorktreePaths", cwd, []).pipe( - // One record per worktree, each ended by an empty field. A `prunable` - // record's directory is gone, and another checkout may now sit there. + // A `prunable` record's directory is gone; another checkout may now sit there. Effect.map(({ stdout }) => stdout.split("\0\0").flatMap((record) => { const fields = record.split("\0"); @@ -4091,23 +4454,36 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* getReviewDiffPreview, getReviewDiffFileContents, readConfigValue, + readBranchBase, resolveBranchName, listRefs, createWorktree: (input, options) => withListRefsInvalidation(input.cwd, createWorktree(input, options)), - fetchPullRequestBranch: (input) => - withListRefsInvalidation(input.cwd, fetchPullRequestBranch(input)), - fetchPullRequestHeadCommit, + fetchRefIntoBranch: (input) => withListRefsInvalidation(input.cwd, fetchRefIntoBranch(input)), + fetchRefCommit, resolveCommit, refreshCheckedOutBranch: (input) => withListRefsInvalidation(input.cwd, refreshCheckedOutBranch(input)), ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)), resolvePrimaryRemoteName, resolveDefaultBranchName, - fetchRemote: (input) => withListRefsInvalidation(input.cwd, fetchRemote(input)), + fetchRemote: (input) => + withListRefsInvalidation( + input.cwd, + fetchRemote(input).pipe( + Effect.flatMap((fetched) => + fetched + ? Effect.void + : fetchRemote({ cwd: input.cwd, remoteName: input.remoteName }).pipe(Effect.asVoid), + ), + ), + ), remoteExists, remoteBranchExists, resolveRemoteTrackingCommit, + resolveWorktreeBaseRemote, + fetchWorktreeBaseCommit: (input) => + withListRefsInvalidation(input.cwd, fetchWorktreeBaseCommit(input)), fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)), fetchRemoteTrackingBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)), diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index 73f75ec42b4a3..4ecc5237da207 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -25,6 +25,8 @@ export interface VcsRestoreCheckpointInput { readonly fallbackToHead?: boolean; } +export const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000; + export interface VcsDiffCheckpointsInput { readonly cwd: string; readonly fromCheckpointRef: CheckpointRef; @@ -32,6 +34,8 @@ export interface VcsDiffCheckpointsInput { readonly fallbackFromToHead?: boolean; readonly ignoreWhitespace: boolean; readonly format?: "patch" | "numstat"; + /** Maximum bytes collected from the diff command. */ + readonly maxOutputBytes?: number; /** An empty list yields an empty diff. */ readonly filePaths?: ReadonlyArray; } diff --git a/apps/server/src/vcs/VcsDriverRegistry.test.ts b/apps/server/src/vcs/VcsDriverRegistry.test.ts index 1e1ed5254dec1..e5c8169774830 100644 --- a/apps/server/src/vcs/VcsDriverRegistry.test.ts +++ b/apps/server/src/vcs/VcsDriverRegistry.test.ts @@ -22,29 +22,6 @@ const normalizeGitArgs = (args: ReadonlyArray): ReadonlyArray => args[0] === "-C" && args.length >= 2 ? args.slice(2) : args; describe("VcsDriverRegistry", () => { - it.effect("routes directly by VCS driver kind for non-repository workflows", () => { - const layer = Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe( - Layer.provide(NodeServices.layer), - Layer.provide( - Layer.mock(VcsProjectConfig.VcsProjectConfig)({ - resolveKind: (input) => Effect.succeed(input.requestedKind ?? "auto"), - }), - ), - Layer.provide( - Layer.mock(VcsProcess.VcsProcess)({ - run: () => Effect.succeed(processOutput("")), - }), - ), - ); - - return Effect.gen(function* () { - const registry = yield* VcsDriverRegistry.VcsDriverRegistry; - const driver = yield* registry.get("git"); - - assert.strictEqual(driver.capabilities.kind, "git"); - }).pipe(Effect.provide(layer)); - }); - const makeDiskBackedLayer = (rootDir: string, calls: string[]) => Layer.effect(VcsDriverRegistry.VcsDriverRegistry, VcsDriverRegistry.make).pipe( Layer.provide(NodeServices.layer), @@ -83,30 +60,6 @@ describe("VcsDriverRegistry", () => { ), ); - it.effect("caches repository detection for repeated resolves in the same cwd and kind", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const repoDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" }); - yield* fs.makeDirectory(path.join(repoDir, ".git")); - const calls: string[] = []; - - yield* Effect.gen(function* () { - const registry = yield* VcsDriverRegistry.VcsDriverRegistry; - const first = yield* registry.resolve({ cwd: repoDir, requestedKind: "git" }); - const second = yield* registry.resolve({ cwd: repoDir, requestedKind: "git" }); - - assert.equal(first.repository.rootPath, repoDir); - assert.equal(second.repository.rootPath, repoDir); - assert.deepStrictEqual(calls, [ - "rev-parse --is-inside-work-tree", - "rev-parse --show-toplevel", - "rev-parse --git-common-dir", - ]); - }).pipe(Effect.provide(makeDiskBackedLayer(repoDir, calls))); - }).pipe(Effect.provide(NodeServices.layer)), - ); - it.effect("detects again when a cached repository is removed from disk", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -151,28 +104,6 @@ describe("VcsDriverRegistry", () => { }).pipe(Effect.provide(NodeServices.layer)), ); - it.effect("detects again when git init creates a repository between the cwd and its root", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const parentDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-vcs-registry-" }); - const middleDir = path.join(parentDir, "a"); - const cwd = path.join(middleDir, "b"); - yield* fs.makeDirectory(path.join(parentDir, ".git")); - yield* fs.makeDirectory(cwd, { recursive: true }); - const calls: string[] = []; - - yield* Effect.gen(function* () { - const registry = yield* VcsDriverRegistry.VcsDriverRegistry; - assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, parentDir); - - yield* fs.makeDirectory(path.join(middleDir, ".git")); - - assert.equal((yield* registry.detect({ cwd }))?.repository.rootPath, middleDir); - }).pipe(Effect.provide(makeDiskBackedLayer(parentDir, calls))); - }).pipe(Effect.provide(NodeServices.layer)), - ); - it.effect("detects a repository created after a negative lookup", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/vcs/VcsDriverRegistry.ts b/apps/server/src/vcs/VcsDriverRegistry.ts index b0273c96da07e..83d7abe6a10e1 100644 --- a/apps/server/src/vcs/VcsDriverRegistry.ts +++ b/apps/server/src/vcs/VcsDriverRegistry.ts @@ -14,9 +14,7 @@ import * as VcsProjectConfig from "./VcsProjectConfig.ts"; import * as VcsDriver from "./VcsDriver.ts"; const DETECTION_CACHE_CAPACITY = 2_048; -// Status polls detect every open cwd each tick, and detection costs three git -// processes. `detect` re-checks each hit against the disk, so this TTL only -// bounds rare changes those stats cannot see. +// Detection costs three git processes per cwd; cached hits still stat disk, so TTL bounds only undetectable changes. const DETECTION_CACHE_TTL = Duration.minutes(5); export interface VcsDriverResolveInput { @@ -118,8 +116,7 @@ export const make = Effect.gen(function* () { return yield* detectWithDriver("git", git, input.cwd); }); - // Falls back to the cwd alone when the root is not above it, such as a cwd - // reached through a symlink. + // Symlinks can put cwd outside root; then inspect cwd alone. const foldersBelowRoot = (cwd: string, rootPath: string) => { const relative = path.relative(path.resolve(rootPath), path.resolve(cwd)); if (relative.startsWith("..") || path.isAbsolute(relative)) return [cwd]; diff --git a/apps/server/src/vcs/VcsProcess.test.ts b/apps/server/src/vcs/VcsProcess.test.ts index 3e14efd78e893..212415171bdc6 100644 --- a/apps/server/src/vcs/VcsProcess.test.ts +++ b/apps/server/src/vcs/VcsProcess.test.ts @@ -1,7 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as Duration from "effect/Duration"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -13,14 +12,9 @@ import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; -import { TestClock } from "effect/testing"; import { ChildProcessSpawner } from "effect/process"; -import { - VcsProcessExitError, - VcsProcessSpawnError, - VcsProcessTimeoutError, -} from "@t3tools/contracts"; +import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts"; import * as ProcessRunner from "../processRunner.ts"; import * as VcsProcess from "./VcsProcess.ts"; @@ -57,8 +51,63 @@ const captureProcessResult = ( ); describe("VcsProcess.run", () => { + it.effect("explains a locked Git index and allows restore after the lock is released", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-index-lock-" }); + const git = (args: readonly string[]) => + run({ operation: "test.checkpoint.restore", command: "git", cwd, args }); + yield* git(["init"]); + const file = path.join(cwd, "README.md"); + yield* fs.writeFileString(file, "before\n"); + yield* git(["add", "README.md"]); + yield* git([ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "-m", + "initial", + ]); + yield* fs.writeFileString(file, "after\n"); + const lock = path.join(cwd, ".git", "index.lock"); + yield* fs.writeFileString(lock, "held by another process\n"); + const restore = ["restore", "--source=HEAD", "--worktree", "--staged", "--", "README.md"]; + + const error = yield* Effect.flip(git(restore)); + expect(error).toBeInstanceOf(VcsProcessExitError); + expect(error).toMatchObject({ + exitCode: 128, + failureKind: "command-failed", + detail: "Git's index is locked. Wait for other Git operations to finish, then try again.", + }); + expect(error.message).not.toContain("index.lock"); + expect(yield* fs.readFileString(file)).toBe("after\n"); + expect(yield* fs.readFileString(lock)).toBe("held by another process\n"); + + yield* fs.remove(lock); + yield* git(restore); + expect(yield* fs.readFileString(file)).toBe("before\n"); + }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped), + ); + it.effect.each([ - { stderr: "fatal: Unable to create '/private/repo/index.lock': File exists", retryable: true }, + { + stderr: "fatal: Unable to create '/private/repo/index.lock': File exists", + retryable: true, + detail: "Git's index is locked. Wait for other Git operations to finish, then try again.", + }, + { + stderr: "fatal: Unable to create 'C:\\private\\repo\\.git\\index.lock': File exists.", + retryable: true, + detail: "Git's index is locked. Wait for other Git operations to finish, then try again.", + }, + { + stderr: "fatal: Unable to create '/private/repo/.git/config.lock': File exists.", + retryable: true, + }, { stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied", retryable: false, @@ -75,8 +124,8 @@ describe("VcsProcess.run", () => { }, { stderr: "fatal: index file corrupt", retryable: false }, ])( - "classifies Git exit retryability without retaining stderr: $stderr", - ({ stderr, retryable }) => + "classifies Git exit retryability and safe detail without retaining stderr: $stderr", + ({ stderr, retryable, detail = "Process exited with a non-zero status." }) => Effect.gen(function* () { const error = yield* captureProcessResult( Effect.succeed({ @@ -92,102 +141,73 @@ describe("VcsProcess.run", () => { ); assert.instanceOf(error, VcsProcessExitError); expect(error.retryable === true).toBe(retryable); + expect(error.detail).toBe(detail); const encoded = yield* encodeExitError(error); - expect(encoded).not.toContain("/private/repo"); - }), - ); - - it.effect.each(["timeout", "spawn"] as const)( - "checkpoint commands do not retry %s failures", - (kind) => - Effect.gen(function* () { - let attempts = 0; - const fields = { command: "git", argumentCount: 2, cwd: "/workspace" }; - const failure = - kind === "timeout" - ? new ProcessRunner.ProcessTimeoutError({ ...fields, timeoutMs: 30_000 }) - : new ProcessRunner.ProcessSpawnError({ ...fields, cause: new Error("spawn failed") }); - const service = yield* VcsProcess.make.pipe( - Effect.provideService(ProcessRunner.ProcessRunner, { - run: () => - Effect.sync(() => { - attempts += 1; - }).pipe(Effect.andThen(Effect.fail(failure))), - }), - ); - const error = yield* service - .run({ - ...baseInput, - operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION, - }) - .pipe(Effect.flip); - expect(attempts).toBe(1); - expect(error._tag).toBe( - kind === "timeout" ? "VcsProcessTimeoutError" : "VcsProcessSpawnError", - ); + expect(encoded).not.toContain("private"); }), ); it.effect.each([ { - name: "recovers after two lock failures", - failures: 2, - attempts: 3, - transient: true, - capture: true, - streaming: false, + stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported", + fsyncMethods: ["fsync", "writeout-only"], }, { - name: "bounds persistent lock failures", - failures: Infinity, - attempts: 3, - transient: true, - capture: true, - streaming: false, + stderr: + "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'", + fsyncMethods: ["fsync", "writeout-only"], }, + { stderr: "fatal: Operation not supported", fsyncMethods: ["fsync"] }, { - name: "does not retry unknown exits", - failures: Infinity, - attempts: 1, - transient: false, - capture: true, - streaming: false, + stderr: + "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock': Input/output error", + fsyncMethods: ["fsync"], }, { - name: "leaves other operations unchanged", - failures: Infinity, - attempts: 1, - transient: true, - capture: false, - streaming: false, + stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported", + fsyncMethods: ["fsync", "writeout-only"], + fallbackFails: true, }, { - name: "does not replay stdout callbacks", - failures: Infinity, - attempts: 1, - transient: true, - capture: true, - streaming: true, + platform: "linux", + stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported", + fsyncMethods: ["fsync"], }, - ])( - "checkpoint command retry $name", - ({ failures, attempts: expectedAttempts, transient, capture, streaming }) => + { + operation: baseInput.operation, + stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported", + fsyncMethods: ["fsync"], + }, + { + stderr: "fatal: fsync error on '.git/objects/bulk_fsync_Pseg66': Operation not supported", + fsyncMethods: ["batch", "writeout-only"], + }, + { + stderr: + "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'", + fsyncMethods: ["batch", "writeout-only"], + }, + ] as const)( + "falls back to writeout-only only for unsupported flushes on macOS ($fsyncMethods): $stderr", + ({ stderr, fsyncMethods, ...scenario }) => Effect.gen(function* () { - let attempts = 0; + const seen: Array> = []; const service = yield* VcsProcess.make.pipe( + Effect.provideService( + HostProcess.Platform, + "platform" in scenario ? scenario.platform : "darwin", + ), Effect.provideService(ProcessRunner.ProcessRunner, { - run: () => + run: (input) => Effect.sync(() => { - attempts += 1; + seen.push(input.args); + const failed = + input.args.includes(`core.fsyncMethod=${fsyncMethods[0]}`) || + ("fallbackFails" in scenario && scenario.fallbackFails); return { stdout: "", - stderr: - attempts > failures - ? "" - : transient - ? "fatal: Unable to create '/repo/index.lock': File exists" - : "fatal: index file corrupt", - code: ChildProcessSpawner.ExitCode(attempts > failures ? 0 : attempts), + stderr: failed ? stderr : "", + code: ChildProcessSpawner.ExitCode(failed ? 128 : 0), timedOut: false, stdoutTruncated: false, stderrTruncated: false, @@ -197,31 +217,48 @@ describe("VcsProcess.run", () => { }), }), ); - const fiber = yield* service + const exit = yield* service .run({ ...baseInput, - operation: capture ? VcsProcess.CHECKPOINT_CAPTURE_OPERATION : baseInput.operation, - ...(streaming ? { onStdoutChunk: () => {} } : {}), + operation: + "operation" in scenario + ? scenario.operation + : VcsProcess.CHECKPOINT_CAPTURE_OPERATION, + args: [ + "-c", + "core.fsync=objects,reference", + "-c", + ...(fsyncMethods[0] === "batch" ? ["core.fsyncMethod=fsync", "-c"] : []), + `core.fsyncMethod=${fsyncMethods[0]}`, + "add", + ], }) - .pipe(Effect.exit, Effect.forkScoped); - yield* TestClock.adjust("150 millis"); - const result = yield* Fiber.join(fiber); - expect(attempts).toBe(expectedAttempts); - if (failures === Infinity) { - if (Exit.isSuccess(result)) - return yield* Effect.die("Expected a capture command failure"); - const error = Cause.findErrorOption(result.cause); - if (error._tag === "None" || error.value._tag !== "VcsProcessExitError") { - return yield* Effect.die("Expected a Git exit error"); - } - expect(error.value.exitCode).toBe(expectedAttempts); - } else { - expect(Exit.isSuccess(result)).toBe(true); + .pipe(Effect.exit); + expect(seen).toEqual( + fsyncMethods.map((method) => [ + "-c", + "core.fsync=objects,reference", + "-c", + ...(fsyncMethods[0] === "batch" + ? [`core.fsyncMethod=${method === "batch" ? "fsync" : method}`, "-c"] + : []), + `core.fsyncMethod=${method}`, + "add", + ]), + ); + expect(Exit.isSuccess(exit)).toBe( + fsyncMethods.length === 2 && !("fallbackFails" in scenario && scenario.fallbackFails), + ); + if (Exit.isFailure(exit)) { + expect(Cause.findErrorOption(exit.cause)).toMatchObject({ + _tag: "Some", + value: { _tag: "VcsProcessExitError", exitCode: 128 }, + }); } }), ); - it.effect("bounds a synthetic burst of GitHub API processes", () => + it.effect("bounds a burst of processes that share a concurrency key", () => Effect.gen(function* () { const gate = yield* Deferred.make(); const starts = yield* Queue.unbounded(); @@ -257,10 +294,11 @@ describe("VcsProcess.run", () => { const burst = yield* Effect.all( Array.from({ length: 32 }, (_, index) => service.run({ - operation: `synthetic.github.${index}`, - command: "gh", + operation: `synthetic.cli.${index}`, + command: "host-cli", args: ["api", "user"], cwd: "/workspace", + concurrency: { key: "host-cli", limit: 4 }, }), ), { concurrency: "unbounded" }, @@ -278,22 +316,6 @@ describe("VcsProcess.run", () => { }), ); - it.effect("collects stdout", () => - Effect.gen(function* () { - const result = yield* run({ - operation: "test.stdout", - command: "node", - args: ["-e", "process.stdout.write('hello')"], - cwd: process.cwd(), - }); - - expect(result.stdout).toBe("hello"); - expect(result.stderr).toBe(""); - expect(result.stdoutTruncated).toBe(false); - expect(result.stderrTruncated).toBe(false); - }).pipe(provideLive), - ); - it.effect("keeps git from opening a folder laid out as a bare repository", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -320,60 +342,6 @@ describe("VcsProcess.run", () => { }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)), ); - it.effect("writes stdin before waiting for exit", () => - Effect.gen(function* () { - const result = yield* run({ - operation: "test.stdin", - command: "node", - args: [ - "-e", - [ - "process.stdin.setEncoding('utf8');", - "let data='';", - "process.stdin.on('data', chunk => { data += chunk; });", - "process.stdin.on('end', () => { process.stdout.write(data); });", - ].join(""), - ], - cwd: process.cwd(), - stdin: "stdin payload", - }); - - expect(result.stdout).toBe("stdin payload"); - }).pipe(provideLive), - ); - - it.effect("fails with VcsProcessExitError for non-zero exits by default", () => - Effect.gen(function* () { - const secretArgument = "--token=super-secret-token"; - const secretStderr = "remote rejected super-secret-token"; - const error = yield* run({ - operation: "test.exit", - command: "node", - args: [ - "-e", - "process.stderr.write(process.argv[1]); process.exit(2)", - secretStderr, - secretArgument, - ], - cwd: process.cwd(), - }).pipe(Effect.flip); - - expect(error).toBeInstanceOf(VcsProcessExitError); - expect(error).toMatchObject({ - operation: "test.exit", - command: "node", - argumentCount: 4, - exitCode: 2, - detail: "Process exited with a non-zero status.", - failureKind: "command-failed", - stderrLength: secretStderr.length, - stderrTruncated: false, - }); - expect(error.message).not.toContain(secretArgument); - expect(error.message).not.toContain(secretStderr); - }).pipe(provideLive), - ); - it.effect("classifies authentication failures without retaining stderr", () => Effect.gen(function* () { const secretStderr = "authentication failed for token super-secret-token"; @@ -424,21 +392,27 @@ describe("VcsProcess.run", () => { }).pipe(provideLive), ); - it.effect("classifies HTTP 429 responses as rate limits", () => + it.effect("reads a failure with the command's own classifier and names it in its terms", () => Effect.gen(function* () { - const providerStderr = "HTTP 429: Too Many Requests. request-id=secret-value"; - const error = yield* run({ - operation: "test.rate-limit", - command: "node", - args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr], - cwd: process.cwd(), - }).pipe(Effect.flip); - - expect(error).toMatchObject({ - detail: "API rate limit exceeded.", - failureKind: "rate-limited", + const fail = (input: Partial) => + run({ + operation: "test.classify", + command: "node", + args: ["-e", "process.stderr.write('HTTP 404: 404 Not Found'); process.exit(1)"], + cwd: process.cwd(), + ...input, + }).pipe(Effect.flip); + + expect(yield* fail({})).toMatchObject({ + failureKind: "command-failed", + detail: "Process exited with a non-zero status.", }); - expect(error.message).not.toContain(providerStderr); + expect( + yield* fail({ + classifyFailure: (stderr) => (stderr.includes("404") ? "not-found" : null), + notFoundDetail: "Merge request not found.", + }), + ).toMatchObject({ failureKind: "not-found", detail: "Merge request not found." }); }).pipe(provideLive), ); @@ -463,68 +437,6 @@ describe("VcsProcess.run", () => { }).pipe(provideLive), ); - it.effect("preserves real boundary causes without manufacturing structural ones", () => - Effect.gen(function* () { - const cause = new Error("secret stdin failure"); - const error = yield* captureProcessResult( - Effect.fail( - new ProcessRunner.ProcessStdinError({ - command: baseInput.command, - argumentCount: baseInput.args.length, - cwd: baseInput.cwd, - stdinBytes: 47, - cause, - }), - ), - ); - - expect(error).toMatchObject({ - _tag: "VcsProcessStdinWriteError", - operation: baseInput.operation, - stdinBytes: 47, - cause, - }); - expect(error.message).not.toContain(cause.message); - - const missingExitCodeError = yield* captureProcessResult( - Effect.succeed({ - stdout: "", - stderr: "", - code: null, - timedOut: false, - stdoutTruncated: false, - stderrTruncated: false, - stdoutInvalidUtf8: false, - stderrInvalidUtf8: false, - }), - ); - - expect(missingExitCodeError).toMatchObject({ - _tag: "VcsProcessMissingExitCodeError", - operation: baseInput.operation, - command: baseInput.command, - cwd: baseInput.cwd, - argumentCount: baseInput.args.length, - }); - expect(missingExitCodeError).not.toHaveProperty("cause"); - }), - ); - - it.effect("returns output when non-zero exits are allowed", () => - Effect.gen(function* () { - const result = yield* run({ - operation: "test.allowed-exit", - command: "node", - args: ["-e", "process.stderr.write('boom'); process.exit(2)"], - cwd: process.cwd(), - allowNonZeroExit: true, - }); - - expect(result.exitCode).toBe(2); - expect(result.stderr).toBe("boom"); - }).pipe(provideLive), - ); - it.effect("truncates output and appends the marker when requested", () => Effect.gen(function* () { const result = yield* run({ @@ -542,21 +454,6 @@ describe("VcsProcess.run", () => { }).pipe(provideLive), ); - it.effect("truncates without the marker when truncation markers are disabled", () => - Effect.gen(function* () { - const result = yield* run({ - operation: "test.truncate-silent", - command: "node", - args: ["-e", "process.stdout.write('x'.repeat(2048))"], - cwd: process.cwd(), - maxOutputBytes: 128, - }); - - expect(result.stdoutTruncated).toBe(true); - expect(result.stdout).not.toContain("[truncated]"); - }).pipe(provideLive), - ); - it.effect("fails with measured byte counts when output must not be truncated", () => Effect.gen(function* () { const error = yield* run({ @@ -592,21 +489,4 @@ describe("VcsProcess.run", () => { expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0"); }).pipe(provideLive), ); - - it.effect("fails with VcsProcessTimeoutError on timeout", () => - Effect.gen(function* () { - const errorFiber = yield* run({ - operation: "test.timeout", - command: "node", - args: ["-e", "setTimeout(() => {}, 5000)"], - cwd: process.cwd(), - timeoutMs: 50, - }).pipe(Effect.flip, Effect.forkScoped); - yield* Effect.yieldNow; - yield* TestClock.adjust(Duration.millis(50)); - const error = yield* Fiber.join(errorFiber); - - expect(error).toBeInstanceOf(VcsProcessTimeoutError); - }).pipe(provideLive), - ); }); diff --git a/apps/server/src/vcs/VcsProcess.ts b/apps/server/src/vcs/VcsProcess.ts index 35694643753e5..e2055e3400531 100644 --- a/apps/server/src/vcs/VcsProcess.ts +++ b/apps/server/src/vcs/VcsProcess.ts @@ -9,6 +9,7 @@ import { ChildProcessSpawner } from "effect/process"; import { type VcsError, + type VcsProcessErrorContext, VcsProcessExitError, type VcsProcessExitFailureKind, VcsProcessMissingExitCodeError, @@ -19,7 +20,9 @@ import { VcsProcessTimeoutError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { SourceControlProcessInput } from "@t3tools/source-control-core/server/SourceControlHost"; +import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts"; import * as ProcessRunner from "../processRunner.ts"; export interface VcsProcessInput { @@ -36,6 +39,9 @@ export interface VcsProcessInput { readonly maxOutputBytes?: number; readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"]; readonly appendTruncationMarker?: boolean; + readonly classifyFailure?: SourceControlProcessInput["classifyFailure"]; + readonly notFoundDetail?: string; + readonly concurrency?: SourceControlProcessInput["concurrency"]; } export interface VcsProcessOutput { @@ -59,19 +65,39 @@ const DEFAULT_TIMEOUT_MS = 30_000; const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; const VCS_PROCESS_CONCURRENCY = 8; -const GITHUB_PROCESS_CONCURRENCY = 4; + +/** Shown to users when a Git command fails because another process holds the index lock. */ +export const GIT_INDEX_LOCKED_DETAIL = + "Git's index is locked. Wait for other Git operations to finish, then try again."; export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint"; +// Caller operations are diagnostic strings; only known labels may become metric attributes. +const gitMetricOperations = new Set([ + CHECKPOINT_CAPTURE_OPERATION, + "GitVcsDriver.checkpoints.deleteCheckpointRefs", + "GitVcsDriver.checkpoints.diffCheckpoints", + "GitVcsDriver.checkpoints.hasHeadCommit", + "GitVcsDriver.checkpoints.listAuthoredPaths", + "GitVcsDriver.checkpoints.resolveCheckpointCommit", + "GitVcsDriver.checkpoints.resolveGitCommonDir", + "GitVcsDriver.checkpoints.resolveHeadCommit", + "GitVcsDriver.checkpoints.restoreCheckpoint", + "GitVcsDriver.detectRepository.commonDir", + "GitVcsDriver.detectRepository.root", + "GitVcsDriver.filterIgnoredPaths", + "GitVcsDriver.initRepository", + "GitVcsDriver.isInsideWorkTree", + "GitVcsDriver.listRemotes", + "GitVcsDriver.listWorkspaceFiles", + "GitVcsDriver.resolveGitCommonDir", +]); + /** - * Appends `key=value` to the `GIT_CONFIG_*` entries git reads as command-line - * config, so argv stays the same on every platform and nothing is written to - * the user's config. The entry goes after any inherited ones. Windows env names - * are case-insensitive (elsewhere git reads only `GIT_CONFIG_COUNT`), so there the - * count is found regardless of casing, read from - * the last spelling (a per-command value spread over process.env), and updated - * under every spelling so the child sees it whichever one Node keeps. A count - * git would reject is left alone so git still reports it. + * Append after inherited entries without changing argv or the user's config. + * Windows env keys ignore case: read the last spelling of the count so command overrides win, + * then update every spelling because Node may keep any one. + * Leave invalid counts untouched so Git reports them. */ export const gitConfigEnv = ( env: NodeJS.ProcessEnv, @@ -87,8 +113,7 @@ export const gitConfigEnv = ( if ( inherited !== undefined && inherited !== "" && - // Git parses the count with strtoul: leading whitespace, an optional sign - // (only -0 is non-negative), digits, and nothing after them. + // Match Git's strtoul count syntax, including whitespace, signs and non-negative -0. /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited ) { return {}; @@ -102,25 +127,23 @@ export const gitConfigEnv = ( }; /** - * Git otherwise opens any folder holding `HEAD`, `objects/` and `refs/` as a - * bare repository and applies its `config`, including commands such as - * `core.fsmonitor`. Files saved in a project or checked out from a clone can - * form one, so git started by T3 (or by gh and friends) only opens a bare - * repository named with `--git-dir` or `GIT_DIR`. Git before 2.38 ignores it. + * A project can contain a fake bare repository whose config runs commands such as `core.fsmonitor`. + * Require `--git-dir` or `GIT_DIR` to open bare repositories; Git before 2.38 ignores this setting. */ export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => gitConfigEnv(env, "safe.bareRepository", "explicit", platform); -const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => { +const classifyNonZeroExit = ( + stderr: string, + classifyFailure: VcsProcessInput["classifyFailure"], +): VcsProcessExitFailureKind => { const normalized = stderr.toLowerCase(); + const commandKind = classifyFailure?.(stderr) ?? null; if ( + commandKind === "authentication" || normalized.includes("authentication failed") || normalized.includes("not logged in") || - normalized.includes("gh auth login") || - normalized.includes("glab auth login") || - normalized.includes("az devops login") || - normalized.includes("please run az login") || normalized.includes("no oauth token") || normalized.includes("unauthorized") ) { @@ -128,6 +151,7 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai } if ( + commandKind === "rate-limited" || normalized.includes("api rate limit") || normalized.includes("rate limit exceeded") || normalized.includes("secondary rate limit") || @@ -137,24 +161,7 @@ const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFai return "rate-limited"; } - if ( - (command === "gh" && - (normalized.includes("could not resolve to a pullrequest") || - normalized.includes("repository.pullrequest") || - normalized.includes("no pull requests found for branch") || - normalized.includes("pull request not found"))) || - (command === "glab" && - (normalized.includes("merge request not found") || - normalized.includes("not found") || - normalized.includes("404"))) || - (command === "az" && - normalized.includes("pull request") && - (normalized.includes("not found") || normalized.includes("does not exist"))) - ) { - return "not-found"; - } - - return "command-failed"; + return commandKind ?? "command-failed"; }; // Classify before discarding stderr; keep paths and process output out of errors. @@ -162,21 +169,37 @@ const isTransientGitExit = (stderr: string) => /unable to create [^\n]*\.lock['"]?: file exists/i.test(stderr) || /(?:unable to stat|lstat\(|error: open\()[^\n]+: no such file or directory/i.test(stderr); +// On macOS, Git's fsync uses F_FULLFSYNC; writeout-only still uses fsync(2). +// Network mounts can reject F_FULLFSYNC. Ref writes omit errno, so retry their +// bare write error too; explicit unrelated errors remain failures. +// Linux writeout-only only starts writeback, so it must not use this fallback. +const FULL_FSYNC_ARG = "core.fsyncMethod=fsync"; +const BATCH_FSYNC_ARG = "core.fsyncMethod=batch"; +const WRITEOUT_ONLY_FSYNC_ARG = "core.fsyncMethod=writeout-only"; +const canRetryFullFsync = (stderr: string) => + /fsync error on [^\r\n]+: operation not supported\r?$/im.test(stderr) || + /cannot update ref [^\r\n]+: couldn't write '[^\r\n]+\.lock'\r?$/im.test(stderr); + export const make = Effect.gen(function* () { const processRunner = yield* ProcessRunner.ProcessRunner; const hostPlatform = yield* HostProcess.Platform; const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY); - const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY); - - const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) { - const baseError = { - operation: input.operation, - command: input.command, - cwd: input.cwd, - argumentCount: input.args.length, - }; + const keyedProcesses = new Map(); + const keyedPermit = (concurrency: NonNullable) => { + let semaphore = keyedProcesses.get(concurrency.key); + if (semaphore === undefined) { + semaphore = Semaphore.makeUnsafe(concurrency.limit); + keyedProcesses.set(concurrency.key, semaphore); + } + return semaphore.withPermits(1); + }; - const result = yield* processRunner + const spawn = Effect.fn("VcsProcess.spawn")(function* ( + input: VcsProcessInput, + baseError: VcsProcessErrorContext, + ) { + let failedExit = false; + const execution = processRunner .run({ command: input.command, args: input.args, @@ -195,6 +218,10 @@ export const make = Effect.gen(function* () { timeoutBehavior: "error", }) .pipe( + Effect.tap((result) => { + failedExit = result.code === null || (!input.allowNonZeroExit && result.code !== 0); + return Effect.void; + }), Effect.mapError( Match.valueTags({ ProcessSpawnError: (error) => @@ -224,13 +251,60 @@ export const make = Effect.gen(function* () { ), ); + return yield* input.command === "git" + ? execution.pipe( + withMetrics({ + counter: gitCommandsTotal, + timer: gitCommandDuration, + attributes: { + operation: gitMetricOperations.has(input.operation) ? input.operation : "other", + }, + outcomeAttributes: (outcome) => ({ + outcome: outcome === "success" && failedExit ? "failure" : outcome, + }), + }), + ) + : execution; + }); + + const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) { + const baseError = { + operation: input.operation, + command: input.command, + cwd: input.cwd, + argumentCount: input.args.length, + }; + + let result = yield* spawn(input, baseError); + + if ( + hostPlatform === "darwin" && + input.operation === CHECKPOINT_CAPTURE_OPERATION && + !input.allowNonZeroExit && + result.code !== null && + result.code !== 0 && + input.command === "git" && + (input.args.includes(FULL_FSYNC_ARG) || input.args.includes(BATCH_FSYNC_ARG)) && + canRetryFullFsync(result.stderr) + ) { + result = yield* spawn( + { + ...input, + args: input.args.map((arg) => + arg === FULL_FSYNC_ARG || arg === BATCH_FSYNC_ARG ? WRITEOUT_ONLY_FSYNC_ARG : arg, + ), + }, + baseError, + ); + } + if (result.code === null) { return yield* new VcsProcessMissingExitCodeError(baseError); } if (!input.allowNonZeroExit && result.code !== 0) { - const failureKind = classifyNonZeroExit(input.command, result.stderr); - return yield* VcsProcessExitError.fromProcessExit( + const failureKind = classifyNonZeroExit(result.stderr, input.classifyFailure); + const error = VcsProcessExitError.fromProcessExit( baseError, { exitCode: result.code, @@ -238,10 +312,26 @@ export const make = Effect.gen(function* () { stderrTruncated: result.stderrTruncated, }, failureKind, - input.command === "git" && - failureKind === "command-failed" && - isTransientGitExit(result.stderr), + { + retryable: + input.command === "git" && + failureKind === "command-failed" && + isTransientGitExit(result.stderr), + ...(input.notFoundDetail === undefined ? {} : { notFoundDetail: input.notFoundDetail }), + }, ); + if ( + input.command === "git" && + /^fatal: unable to create ['"][^\r\n]*[/\\]index\.lock['"]: file exists\.?$/im.test( + result.stderr, + ) + ) { + return yield* new VcsProcessExitError({ + ...error, + detail: GIT_INDEX_LOCKED_DETAIL, + }); + } + return yield* error; } return { @@ -276,7 +366,9 @@ export const make = Effect.gen(function* () { }), ); } - return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded; + return yield* input.concurrency === undefined + ? bounded + : keyedPermit(input.concurrency)(bounded); }); return VcsProcess.of({ run }); diff --git a/apps/server/src/vcs/VcsProjectConfig.test.ts b/apps/server/src/vcs/VcsProjectConfig.test.ts index 1c91cbadea8cb..65e4068db3618 100644 --- a/apps/server/src/vcs/VcsProjectConfig.test.ts +++ b/apps/server/src/vcs/VcsProjectConfig.test.ts @@ -14,20 +14,6 @@ const layerTest = VcsProjectConfig.layer.pipe( ); describe("VcsProjectConfig", () => { - it.layer(layerTest)("uses an explicit requested VCS kind before config", (it) => { - it.effect("returns the requested kind", () => - Effect.gen(function* () { - const config = yield* VcsProjectConfig.VcsProjectConfig; - const kind = yield* config.resolveKind({ - cwd: "/repo", - requestedKind: "jj", - }); - - assert.equal(kind, "jj"); - }), - ); - }); - it.layer(layerTest)("discovers .t3code/vcs.json from nested workspaces", (it) => { it.effect("returns the configured kind", () => Effect.gen(function* () { @@ -95,21 +81,6 @@ describe("VcsProjectConfig", () => { }); }); - it.layer(layerTest)("falls back to auto when no config exists", (it) => { - it.effect("returns auto", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-vcs-config-test-", - }); - const config = yield* VcsProjectConfig.VcsProjectConfig; - const kind = yield* config.resolveKind({ cwd: root }); - - assert.equal(kind, "auto"); - }), - ); - }); - it.layer(layerTest)("falls back to auto when config JSON is malformed", (it) => { it.effect("returns auto and logs the failed operation and path", () => { const messages: unknown[] = []; @@ -147,61 +118,4 @@ describe("VcsProjectConfig", () => { }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))); }); }); - - it.layer(layerTest)("falls back to auto when the config path cannot be read", (it) => { - it.effect("retains the read failure context", () => { - const messages: unknown[] = []; - const logger = Logger.make(({ message }) => { - messages.push(message); - }); - - return Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-vcs-config-test-", - }); - const configPath = path.join(root, ".t3code", "vcs.json"); - yield* fileSystem.makeDirectory(configPath, { recursive: true }); - - const config = yield* VcsProjectConfig.VcsProjectConfig; - const kind = yield* config.resolveKind({ cwd: root }); - - assert.equal(kind, "auto"); - const [error] = messages[0] as ReadonlyArray; - assert.instanceOf(error, VcsProjectConfig.VcsProjectConfigError); - assert.equal(error.message, "Failed to read VCS project config at " + configPath + "."); - assert.deepInclude(error.cause, { _tag: "PlatformError" }); - assert.deepInclude(error, { - operation: "read", - cwd: root, - configPath, - _tag: "VcsProjectConfigError", - }); - }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false }))); - }); - }); - - it.layer(layerTest)("falls back to auto when config kind is invalid", (it) => { - it.effect("returns auto", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ - prefix: "t3-vcs-config-test-", - }); - const configDir = path.join(root, ".t3code"); - yield* fileSystem.makeDirectory(configDir, { recursive: true }); - yield* fileSystem.writeFileString( - path.join(configDir, "vcs.json"), - `{"vcs":{"kind":"svn"}}`, - ); - - const config = yield* VcsProjectConfig.VcsProjectConfig; - const kind = yield* config.resolveKind({ cwd: root }); - - assert.equal(kind, "auto"); - }), - ); - }); }); diff --git a/apps/server/src/vcs/VcsProjectConfig.ts b/apps/server/src/vcs/VcsProjectConfig.ts index 74d3801c06861..dfd76b1f2b48b 100644 --- a/apps/server/src/vcs/VcsProjectConfig.ts +++ b/apps/server/src/vcs/VcsProjectConfig.ts @@ -64,7 +64,7 @@ const logVcsProjectConfigError = (error: VcsProjectConfigError) => }), ); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; diff --git a/apps/server/src/vcs/VcsProvisioningService.test.ts b/apps/server/src/vcs/VcsProvisioningService.test.ts deleted file mode 100644 index ea03ed8a41ab3..0000000000000 --- a/apps/server/src/vcs/VcsProvisioningService.test.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { assert, it } from "@effect/vitest"; -import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; -import { ChildProcessSpawner } from "effect/process"; - -import * as VcsDriver from "./VcsDriver.ts"; -import * as VcsDriverRegistry from "./VcsDriverRegistry.ts"; -import * as VcsProvisioningService from "./VcsProvisioningService.ts"; - -const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"); - -function makeDriver(calls: string[]): VcsDriver.VcsDriver["Service"] { - return { - capabilities: { - kind: "git", - supportsWorktrees: true, - supportsBookmarks: false, - supportsAtomicSnapshot: false, - supportsPushDefaultRemote: true, - ignoreClassifier: "native", - }, - execute: () => - Effect.succeed({ - exitCode: ChildProcessSpawner.ExitCode(0), - stdout: "", - stderr: "", - stdoutTruncated: false, - stderrTruncated: false, - }), - detectRepository: () => Effect.succeed(null), - isInsideWorkTree: () => Effect.succeed(false), - listWorkspaceFiles: () => - Effect.succeed({ - paths: [], - truncated: false, - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - listRemotes: () => - Effect.succeed({ - remotes: [], - freshness: { - source: "live-local", - observedAt: TEST_EPOCH, - expiresAt: Option.none(), - }, - }), - filterIgnoredPaths: (_cwd, relativePaths) => Effect.succeed(relativePaths), - initRepository: (input) => - Effect.sync(() => { - calls.push(`${input.kind ?? "default"}:${input.cwd}`); - }), - }; -} - -it.effect("routes repository initialization through an explicit VCS driver kind", () => { - const calls: string[] = []; - const driver = makeDriver(calls); - const layerTest = VcsProvisioningService.layer.pipe( - Layer.provide( - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ - get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")), - }), - ), - ); - - return Effect.gen(function* () { - const provisioning = yield* VcsProvisioningService.VcsProvisioningService; - yield* provisioning.initRepository({ cwd: "/repo", kind: "git" }); - - assert.deepStrictEqual(calls, ["git:/repo"]); - }).pipe(Effect.provide(layerTest)); -}); - -it.effect("defaults repository initialization to Git until callers choose a VCS kind", () => { - const calls: string[] = []; - const driver = makeDriver(calls); - const layerTest = VcsProvisioningService.layer.pipe( - Layer.provide( - Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({ - get: (kind) => (kind === "git" ? Effect.succeed(driver) : Effect.die("unexpected kind")), - }), - ), - ); - - return Effect.gen(function* () { - const provisioning = yield* VcsProvisioningService.VcsProvisioningService; - yield* provisioning.initRepository({ cwd: "/repo" }); - - assert.deepStrictEqual(calls, ["default:/repo"]); - }).pipe(Effect.provide(layerTest)); -}); diff --git a/apps/server/src/vcs/VcsProvisioningService.ts b/apps/server/src/vcs/VcsProvisioningService.ts index e58099b615dbd..96674e940f03b 100644 --- a/apps/server/src/vcs/VcsProvisioningService.ts +++ b/apps/server/src/vcs/VcsProvisioningService.ts @@ -35,7 +35,7 @@ function resolveRequestedKind( return Effect.succeed(kind); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const registry = yield* VcsDriverRegistry.VcsDriverRegistry; diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 703190e494bae..334c0d4747bce 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -1,7 +1,6 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import { assert, it, describe } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -10,7 +9,6 @@ import * as Fiber from "effect/Fiber"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; -import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Scope from "effect/Scope"; @@ -79,11 +77,18 @@ function layerTestFor(state: { remoteInvalidationCalls: number; remoteStatusRefreshUpstreamValues?: Array; backgroundWorkEnabled?: boolean; + automaticFetchInterval?: Effect.Effect; beforeRemoteStatus?: Effect.Effect; }) { return VcsStatusBroadcaster.layer.pipe( Layer.provideMerge(NodeServices.layer), Layer.provide(layerBackgroundPolicy(() => state.backgroundWorkEnabled !== false)), + Layer.provide( + Layer.succeed( + VcsStatusBroadcaster.VcsAutomaticFetchInterval, + state.automaticFetchInterval ?? Effect.succeed(Duration.seconds(30)), + ), + ), Layer.provide( Layer.mock(GitWorkflowService.GitWorkflowService)({ localStatus: () => @@ -212,31 +217,6 @@ describe("VcsStatusBroadcaster", () => { }, ); - it.effect("reuses the cached VCS status across repeated reads", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - - const first = yield* broadcaster.getStatus({ cwd: "/repo" }); - const second = yield* broadcaster.getStatus({ cwd: "/repo" }); - - assert.deepStrictEqual(first, baseStatus); - assert.deepStrictEqual(second, baseStatus); - assert.equal(state.localStatusCalls, 1); - assert.equal(state.remoteStatusCalls, 1); - assert.equal(state.localInvalidationCalls, 0); - assert.equal(state.remoteInvalidationCalls, 0); - }).pipe(Effect.provide(layerTestFor(state))); - }); - it.effect("refreshes a loaded cwd without reusing a previous branch's PR", () => { const state = { currentLocalStatus: baseLocalStatus, @@ -356,66 +336,6 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(layer), Effect.scoped); }); - it.effect("turn-end refresh skips a loaded cwd when background policy pauses it", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - backgroundWorkEnabled: false, - }; - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - yield* broadcaster.getStatus({ cwd: "/repo" }); - yield* broadcaster.refreshPullRequestStatus("/repo"); - assert.equal(state.remoteStatusCalls, 1); - assert.equal(state.remoteInvalidationCalls, 0); - }).pipe(Effect.provide(layerTestFor(state))); - }); - - it.effect("refreshes the cached snapshot after explicit invalidation", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); - - state.currentLocalStatus = { - ...baseLocalStatus, - refName: "feature/updated-status", - }; - state.currentRemoteStatus = { - ...baseRemoteStatus, - aheadCount: 2, - }; - const refreshed = yield* broadcaster.refreshStatus("/repo"); - const cached = yield* broadcaster.getStatus({ cwd: "/repo" }); - - assert.deepStrictEqual(initial, baseStatus); - assert.deepStrictEqual(refreshed, { - ...state.currentLocalStatus, - ...state.currentRemoteStatus, - }); - assert.deepStrictEqual(cached, { - ...state.currentLocalStatus, - ...state.currentRemoteStatus, - }); - assert.equal(state.localStatusCalls, 2); - assert.equal(state.remoteStatusCalls, 2); - assert.equal(state.localInvalidationCalls, 1); - assert.equal(state.remoteInvalidationCalls, 1); - }).pipe(Effect.provide(layerTestFor(state))); - }); - it.effect("keeps the cached snapshot unchanged when a refresh branch fails", () => { const state = { currentLocalStatus: baseLocalStatus, @@ -488,42 +408,6 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(layerTest)); }); - it.effect("refreshes only the cached local snapshot when requested", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const initial = yield* broadcaster.getStatus({ cwd: "/repo" }); - - state.currentLocalStatus = { - ...baseLocalStatus, - refName: "feature/local-only-refresh", - hasWorkingTreeChanges: true, - }; - - const refreshedLocal = yield* broadcaster.refreshLocalStatus("/repo"); - const cached = yield* broadcaster.getStatus({ cwd: "/repo" }); - - assert.deepStrictEqual(initial, baseStatus); - assert.deepStrictEqual(refreshedLocal, state.currentLocalStatus); - assert.deepStrictEqual(cached, { - ...state.currentLocalStatus, - ...baseRemoteStatus, - }); - assert.equal(state.localStatusCalls, 2); - assert.equal(state.remoteStatusCalls, 1); - assert.equal(state.localInvalidationCalls, 1); - assert.equal(state.remoteInvalidationCalls, 0); - }).pipe(Effect.provide(layerTestFor(state))); - }); - it.effect.skipIf(!symlinksSupported)( "normalizes symlinked CWDs before cache lookup and workflow calls", () => { @@ -589,329 +473,6 @@ describe("VcsStatusBroadcaster", () => { }, ); - it.effect("passive streams retain cached remote status", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const snapshotDeferred = yield* Deferred.make(); - const remoteUpdatedDeferred = yield* Deferred.make(); - yield* Stream.runForEach( - broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), - (event) => { - if (event._tag === "snapshot") { - return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore); - } - if (event._tag === "remoteUpdated") { - return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore); - } - return Effect.void; - }, - ).pipe(Effect.forkScoped); - - const snapshot = yield* Deferred.await(snapshotDeferred); - yield* TestClock.adjust("1 minute"); - assert.equal(state.remoteStatusCalls, 0); - yield* broadcaster.getStatus({ cwd: "/repo" }); - state.currentRemoteStatus = remoteStatusWithPr; - yield* broadcaster.refreshPullRequestStatus("/repo"); - const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred); - - assert.deepStrictEqual(snapshot, { - _tag: "snapshot", - local: baseLocalStatus, - remote: null, - } satisfies VcsStatusStreamEvent); - assert.deepStrictEqual(remoteUpdated, { - _tag: "remoteUpdated", - remote: remoteStatusWithPr, - } satisfies VcsStatusStreamEvent); - const cachedSnapshot = yield* Stream.runHead( - broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), - ); - assert.deepStrictEqual(Option.getOrThrow(cachedSnapshot), { - _tag: "snapshot", - local: baseLocalStatus, - remote: remoteStatusWithPr, - }); - }).pipe(Effect.provide(layerTestFor(state))); - }); - - it.effect("loads remote status once when periodic refreshes are disabled", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: remoteStatusWithPr, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - remoteStatusRefreshUpstreamValues: [] as Array, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const scope = yield* Scope.make(); - const snapshotDeferred = yield* Deferred.make(); - const remoteUpdatedDeferred = yield* Deferred.make(); - yield* Stream.runForEach( - broadcaster.streamStatus( - { cwd: "/repo" }, - { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) }, - ), - (event) => { - if (event._tag === "snapshot") { - return Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore); - } - if (event._tag === "remoteUpdated") { - return Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore); - } - return Effect.void; - }, - ).pipe(Effect.forkIn(scope)); - - const snapshot = yield* Deferred.await(snapshotDeferred); - const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred); - - assert.deepStrictEqual(snapshot, { - _tag: "snapshot", - local: baseLocalStatus, - remote: null, - } satisfies VcsStatusStreamEvent); - assert.deepStrictEqual(remoteUpdated, { - _tag: "remoteUpdated", - remote: remoteStatusWithPr, - } satisfies VcsStatusStreamEvent); - assert.equal(state.remoteStatusCalls, 1); - assert.equal(state.remoteInvalidationCalls, 0); - assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]); - - yield* TestClock.adjust(Duration.minutes(2)); - assert.equal(state.remoteStatusCalls, 1); - assert.equal(state.remoteInvalidationCalls, 0); - - yield* Scope.close(scope, Exit.void); - }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer()))); - }); - - it.effect("retries the initial remote load when periodic refreshes are disabled", () => { - const state = { - currentLocalStatus: baseLocalStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - remoteStatusRefreshUpstreamValues: [] as Array, - }; - const privateCwd = "/private/user/workspace/repo"; - const nestedCause = new Error("private nested VCS failure"); - const messages: Array> = []; - const logger = Logger.make(({ message }) => { - messages.push(message as ReadonlyArray); - }); - let firstRemoteAttemptDeferred: Deferred.Deferred | null = null; - const layerTest = VcsStatusBroadcaster.layer.pipe( - Layer.provideMerge(NodeServices.layer), - Layer.provide(layerBackgroundPolicy(() => true)), - Layer.provide( - Layer.mock(GitWorkflowService.GitWorkflowService)({ - localStatus: () => - Effect.sync(() => { - state.localStatusCalls += 1; - return state.currentLocalStatus; - }), - remoteStatus: (_input, options) => - Effect.suspend(() => { - state.remoteStatusCalls += 1; - state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream); - if (state.remoteStatusCalls === 1) { - return Effect.fail( - new GitManagerError({ - operation: "VcsStatusBroadcaster.test", - cwd: privateCwd, - detail: "private initial remote status failure", - cause: nestedCause, - }), - ).pipe( - Effect.ensuring( - firstRemoteAttemptDeferred - ? Deferred.succeed(firstRemoteAttemptDeferred, undefined).pipe(Effect.ignore) - : Effect.void, - ), - ); - } - return Effect.succeed(remoteStatusWithPr); - }), - invalidateLocalStatus: () => - Effect.sync(() => { - state.localInvalidationCalls += 1; - }), - invalidateRemoteStatus: () => - Effect.sync(() => { - state.remoteInvalidationCalls += 1; - }), - }), - ), - ); - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const scope = yield* Scope.make(); - firstRemoteAttemptDeferred = yield* Deferred.make(); - const remoteUpdatedDeferred = yield* Deferred.make(); - yield* Stream.runForEach( - broadcaster.streamStatus( - { cwd: privateCwd }, - { automaticRemoteRefreshInterval: Effect.succeed(Duration.zero) }, - ), - (event) => - event._tag === "remoteUpdated" - ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore) - : Effect.void, - ).pipe(Effect.forkIn(scope)); - - yield* Deferred.await(firstRemoteAttemptDeferred); - yield* Effect.yieldNow; - assert.equal(state.remoteStatusCalls, 1); - assert.deepStrictEqual( - messages.find((message) => message[0] === "VCS remote status refresh failed"), - [ - "VCS remote status refresh failed", - { - cwdLength: privateCwd.length, - reasonCount: 1, - failureCount: 1, - failureTags: ["GitManagerError"], - failureOperations: ["VcsStatusBroadcaster.test"], - defectCount: 0, - defectTags: [], - interruptionCount: 0, - consecutiveFailures: 1, - nextDelayMs: 30_000, - }, - ], - ); - - yield* TestClock.adjust(Duration.seconds(30)); - const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred); - - assert.deepStrictEqual(remoteUpdated, { - _tag: "remoteUpdated", - remote: remoteStatusWithPr, - } satisfies VcsStatusStreamEvent); - assert.equal(state.remoteStatusCalls, 2); - assert.equal(state.remoteInvalidationCalls, 0); - assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]); - - yield* Scope.close(scope, Exit.void); - }).pipe( - Effect.provide( - Layer.mergeAll( - layerTest, - TestClock.layer(), - Logger.layer([logger], { mergeWithExisting: false }), - ), - ), - ); - }); - - it.effect("delays automatic refresh when a cached remote snapshot is available", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - yield* broadcaster.getStatus({ cwd: "/repo" }); - const scope = yield* Scope.make(); - const snapshotDeferred = yield* Deferred.make(); - yield* Stream.runForEach( - broadcaster.streamStatus( - { cwd: "/repo" }, - { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) }, - ), - (event) => - event._tag === "snapshot" - ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore) - : Effect.void, - ).pipe(Effect.forkIn(scope)); - - yield* Deferred.await(snapshotDeferred); - assert.equal(state.remoteStatusCalls, 1); - assert.equal(state.remoteInvalidationCalls, 0); - - yield* TestClock.adjust(Duration.seconds(59)); - assert.equal(state.remoteStatusCalls, 1); - - yield* TestClock.adjust(Duration.seconds(1)); - yield* Effect.yieldNow; - assert.equal(state.remoteStatusCalls, 2); - assert.equal(state.remoteInvalidationCalls, 1); - - yield* Scope.close(scope, Exit.void); - }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer()))); - }); - - it.effect.each([ - ["a push", { ...baseRemoteStatus, aheadCount: 1, aheadOfDefaultCount: 0 }], - ["a merged pull request", { ...baseRemoteStatus, aheadOfDefaultCount: 2 }], - ] as const)("re-reads local status when a fetch reflects %s", ([, initialRemote]) => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: initialRemote as VcsStatusRemoteResult | null, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - yield* broadcaster.getStatus({ cwd: "/repo" }); - const scope = yield* Scope.make(); - const snapshotDeferred = yield* Deferred.make(); - const localUpdatedDeferred = yield* Deferred.make(); - yield* Stream.runForEach( - broadcaster.streamStatus( - { cwd: "/repo" }, - { automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) }, - ), - (event) => - event._tag === "snapshot" - ? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore) - : event._tag === "localUpdated" - ? Deferred.succeed(localUpdatedDeferred, event).pipe(Effect.ignore) - : Effect.void, - ).pipe(Effect.forkIn(scope)); - yield* Deferred.await(snapshotDeferred); - - const pushedLocal: VcsStatusLocalResult = { - ...baseLocalStatus, - branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 }, - }; - state.currentLocalStatus = pushedLocal; - state.currentRemoteStatus = { ...baseRemoteStatus, aheadOfDefaultCount: 0 }; - yield* TestClock.adjust(Duration.minutes(1)); - - assert.deepStrictEqual(yield* Deferred.await(localUpdatedDeferred), { - _tag: "localUpdated", - local: pushedLocal, - } satisfies VcsStatusStreamEvent); - yield* Scope.close(scope, Exit.void); - }).pipe(Effect.provide(Layer.merge(layerTestFor(state), TestClock.layer()))); - }); - it.effect("an explicit refresh reads local totals after the fetch", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, @@ -944,101 +505,6 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(layerTestFor(state))); }); - it("backs off remote refresh failures exponentially and honors larger configured intervals", () => { - assert.equal( - Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))), - 30_000, - ); - assert.equal( - Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(2, Duration.seconds(1))), - 60_000, - ); - assert.equal( - Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(3, Duration.seconds(1))), - 120_000, - ); - assert.equal( - Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.minutes(5))), - 300_000, - ); - assert.equal( - Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(20, Duration.seconds(1))), - 900_000, - ); - }); - - it("summarizes refresh causes without exposing nested failure details", () => { - const nestedCause = new Error("private nested failure detail"); - const failure = new GitManagerError({ - operation: "VcsStatusBroadcaster.remoteStatus", - cwd: "/private/user/workspace/repo", - detail: "private Git failure detail", - cause: nestedCause, - }); - const cause = Cause.combine(Cause.fail(failure), Cause.die(new TypeError("private defect"))); - - assert.deepStrictEqual(VcsStatusBroadcaster.remoteRefreshFailureDiagnostics(cause), { - reasonCount: 2, - failureCount: 1, - failureTags: ["GitManagerError"], - failureOperations: ["VcsStatusBroadcaster.remoteStatus"], - defectCount: 1, - defectTags: ["TypeError"], - interruptionCount: 0, - }); - }); - - it.effect("does not start automatic remote refreshes without foreground client demand", () => { - const state = { - currentLocalStatus: baseLocalStatus, - currentRemoteStatus: baseRemoteStatus, - localStatusCalls: 0, - remoteStatusCalls: 0, - localInvalidationCalls: 0, - remoteInvalidationCalls: 0, - }; - const layerTest = VcsStatusBroadcaster.layer.pipe( - Layer.provideMerge(NodeServices.layer), - Layer.provide(layerBackgroundPolicy(() => false)), - Layer.provide( - Layer.mock(GitWorkflowService.GitWorkflowService)({ - localStatus: () => - Effect.sync(() => { - state.localStatusCalls += 1; - return state.currentLocalStatus; - }), - remoteStatus: () => - Effect.sync(() => { - state.remoteStatusCalls += 1; - return state.currentRemoteStatus; - }), - invalidateLocalStatus: () => - Effect.sync(() => { - state.localInvalidationCalls += 1; - }), - invalidateRemoteStatus: () => - Effect.sync(() => { - state.remoteInvalidationCalls += 1; - }), - } satisfies Partial), - ), - ); - - return Effect.gen(function* () { - const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const snapshot = yield* Stream.runHead( - broadcaster.streamStatus( - { cwd: "/repo" }, - { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) }, - ), - ); - - assert.isTrue(Option.isSome(snapshot)); - assert.equal(state.remoteStatusCalls, 0); - assert.equal(state.remoteInvalidationCalls, 0); - }).pipe(Effect.provide(layerTest)); - }); - it.effect("releases remote demand while passive observers remain", () => { const state = { currentLocalStatus: baseLocalStatus, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 7c1f7f364c25e..007a0ea1e3174 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -21,6 +21,8 @@ import type { VcsStatusStreamEvent, VcsStatusSubscriptionInput, } from "@t3tools/contracts"; +import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts"; +import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { mergeGitStatusParts } from "@t3tools/shared/git"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -30,7 +32,6 @@ import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as ServerSettings from "../serverSettings.ts"; -const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30); const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30); const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15); const MAX_FAILURE_DIAGNOSTIC_VALUES = 8; @@ -85,7 +86,7 @@ function addUniqueDiagnosticValue(values: Array, value: string | undefin } } -export function remoteRefreshFailureDiagnostics(cause: Cause.Cause) { +function remoteRefreshFailureDiagnostics(cause: Cause.Cause) { const failureTags: Array = []; const failureOperations: Array = []; const defectTags: Array = []; @@ -140,9 +141,23 @@ interface ActiveRemotePoller { readonly demandCwds: Ref.Ref>; } -interface StreamStatusOptions { - readonly automaticRemoteRefreshInterval?: Effect.Effect; -} +export class VcsAutomaticFetchInterval extends Context.Reference>( + "t3/vcs/VcsAutomaticFetchInterval", + { defaultValue: () => Effect.succeed(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) }, +) {} + +export const layerAutomaticFetchInterval = Layer.effect( + VcsAutomaticFetchInterval, + Effect.gen(function* () { + const serverSettings = yield* ServerSettings.ServerSettingsService; + return serverSettings.getSettings.pipe( + Effect.map( + (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval, + ), + Effect.orElseSucceed(() => DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL), + ); + }), +); export class VcsAutoPullPolicy extends Context.Reference<{ readonly isEnabled: (cwd: string) => Effect.Effect; @@ -169,7 +184,7 @@ export const layerAutoPullPolicy = Layer.effect( }), ); -export function remoteRefreshFailureDelay( +function remoteRefreshFailureDelay( consecutiveFailures: number, configuredInterval: Duration.Duration, ) { @@ -198,7 +213,6 @@ export class VcsStatusBroadcaster extends Context.Service< ) => Effect.Effect; readonly streamStatus: ( input: VcsStatusSubscriptionInput, - options?: StreamStatusOptions, ) => Stream.Stream; } >()("t3/vcs/VcsStatusBroadcaster") {} @@ -213,8 +227,9 @@ const normalizeCwd = (cwd: string) => Effect.orElseSucceed(() => cwd), ); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { + const automaticFetchInterval = yield* VcsAutomaticFetchInterval; const autoPullPolicy = yield* VcsAutoPullPolicy; const workflow = yield* GitWorkflowService.GitWorkflowService; const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; @@ -228,7 +243,7 @@ export const make = Effect.gen(function* () { ); const cacheRef = yield* Ref.make(new Map()); // One permit per cwd for remote reads that write the cache. Without it a - // periodic poll that started before `gh pr create` can finish after the + // periodic poll that started before an agent creates a PR can finish after the // turn-end refresh and overwrite the fresh PR with its stale `pr: null`. const remoteWriteLocks = yield* KeyedLock.make(); const withRemoteWriteLock = (cwd: string, effect: Effect.Effect) => @@ -374,10 +389,13 @@ export const make = Effect.gen(function* () { cwd, Effect.gen(function* () { const latest = yield* getCachedStatus(cwd); + const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval); const [local, remote] = yield* Effect.all( [ latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }), - latest?.remote ? Effect.succeed(latest.remote.value) : workflow.remoteStatus({ cwd }), + latest?.remote + ? Effect.succeed(latest.remote.value) + : workflow.remoteStatus({ cwd }, { refreshUpstream }), ], { concurrency: "unbounded" }, ); @@ -406,6 +424,7 @@ export const make = Effect.gen(function* () { remote: VcsStatusRemoteResult | null, policyCwds: ReadonlyArray, ) { + let pullAttempted = false; return yield* Effect.gen(function* () { const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, { concurrency: "unbounded", @@ -424,6 +443,7 @@ export const make = Effect.gen(function* () { const local = yield* workflow.localStatus({ cwd }); if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null; + pullAttempted = true; yield* workflow.pullCurrentBranch(cwd); yield* workflow.invalidateStatus(cwd); const [refreshedLocal, refreshedRemote] = yield* Effect.all( @@ -433,8 +453,19 @@ export const make = Effect.gen(function* () { yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true }); return { local: refreshedLocal, remote: refreshedRemote }; }).pipe( - Effect.catch(() => - Effect.logWarning("Automatic project pull failed", { cwd }).pipe(Effect.as(null)), + Effect.catch((error) => + Effect.gen(function* () { + yield* Effect.logWarning("Automatic project pull failed", { + cwdLength: cwd.length, + errorTag: error._tag, + }); + if (!pullAttempted) return null; + // Pull can change local state before failing; propagate reconciliation failures instead of publishing stale status. + yield* workflow.invalidateLocalStatus(cwd); + const local = yield* workflow.localStatus({ cwd }); + yield* updateCachedStatus(cwd, local, remote, { publish: true }); + return { local, remote }; + }), ), ); }); @@ -454,7 +485,10 @@ export const make = Effect.gen(function* () { } const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value; const remote = yield* workflow.remoteStatus({ cwd }, options); - const pulled = yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]); + const pulled = + options?.refreshUpstream === false + ? null + : yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]); if (pulled !== null) return pulled.remote; if ( remote && @@ -474,16 +508,17 @@ export const make = Effect.gen(function* () { "VcsStatusBroadcaster.refreshStatus", )(function* (rawCwd) { const cwd = yield* withFileSystem(normalizeCwd(rawCwd)); - // invalidateStatus (not the two partial invalidations) so an explicit - // refresh also bypasses GitManager's slow PR-lookup cache. + // Full invalidation also bypasses GitManager's slow PR cache. return yield* withRemoteWriteLock( cwd, Effect.gen(function* () { + const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval); yield* workflow.invalidateStatus(cwd); // Local after remote: the fetch can move the base that the Changes totals compare with. - const remote = yield* workflow.remoteStatus({ cwd }); + const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream }); const local = yield* workflow.localStatus({ cwd }); - const pulled = yield* maybeAutoPull(cwd, remote, [rawCwd]); + // Without a fetch, the cached behind count cannot justify an automatic pull. + const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remote, [rawCwd]) : null; if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); return yield* updateCachedStatus(cwd, local, remote, { publish: true }); }), @@ -507,8 +542,7 @@ export const make = Effect.gen(function* () { { concurrency: "unbounded" }, )).some(Boolean); if (!shouldRefresh) return null; - // Resolve the checked-out branch again. A cached PR can belong to - // the previous branch after an agent checks out another branch. + // Re-resolve the branch; cached PRs may belong to a checkout's previous branch. const remote = yield* workflow.remoteStatus( { cwd }, { refreshUpstream: false, refreshMissingPullRequest: true }, @@ -518,94 +552,91 @@ export const make = Effect.gen(function* () { ); }); - const makeRemoteRefreshLoop = ( + // A subscription owns this loop; keep each poll's spans out of a never-ending parent span. + const makeRemoteRefreshLoop = Effect.fnUntraced(function* ( cwd: string, demandCwdsRef: Ref.Ref>, - automaticRemoteRefreshInterval: Effect.Effect, refreshImmediately: boolean, - ) => { - return Effect.gen(function* () { - const consecutiveFailuresRef = yield* Ref.make(0); - const needsInitialRefreshRef = yield* Ref.make(refreshImmediately); - const refreshRemoteStatusIfEnabled = Effect.gen(function* () { - const configuredInterval = yield* automaticRemoteRefreshInterval; - const activeInterval = Duration.isZero(configuredInterval) - ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL - : configuredInterval; - const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef); - if (Duration.isZero(configuredInterval) && !needsInitialRefresh) { - return activeInterval; - } + ) { + const consecutiveFailuresRef = yield* Ref.make(0); + const needsInitialRefreshRef = yield* Ref.make(refreshImmediately); + const refreshRemoteStatusIfEnabled = Effect.gen(function* () { + const configuredInterval = yield* automaticFetchInterval; + const activeInterval = Duration.isZero(configuredInterval) + ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL + : configuredInterval; + const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef); + if (Duration.isZero(configuredInterval) && !needsInitialRefresh) { + return activeInterval; + } - const demandCwds = yield* Ref.get(demandCwdsRef); - const shouldRun = - needsInitialRefresh || - (yield* Effect.forEach( - [...demandCwds.keys()], - (demandCwd) => - backgroundPolicy.shouldRunScopeWork({ - type: "vcs-status", - cwd: demandCwd, - }), - { concurrency: "unbounded" }, - )).some(Boolean); - if (!shouldRun) { - return activeInterval; - } + const demandCwds = yield* Ref.get(demandCwdsRef); + const shouldRun = + needsInitialRefresh || + (yield* Effect.forEach( + [...demandCwds.keys()], + (demandCwd) => + backgroundPolicy.shouldRunScopeWork({ + type: "vcs-status", + cwd: demandCwd, + }), + { concurrency: "unbounded" }, + )).some(Boolean); + if (!shouldRun) { + return activeInterval; + } - const exit = yield* refreshRemoteStatus(cwd, { - refreshUpstream: !Duration.isZero(configuredInterval), - policyCwds: [...demandCwds.keys()], - }).pipe(Effect.exit); - if (Exit.isSuccess(exit)) { - yield* Ref.set(needsInitialRefreshRef, false); - yield* Ref.set(consecutiveFailuresRef, 0); - return activeInterval; - } + const exit = yield* refreshRemoteStatus(cwd, { + refreshUpstream: !Duration.isZero(configuredInterval), + policyCwds: [...demandCwds.keys()], + }).pipe(Effect.exit); + if (Exit.isSuccess(exit)) { + yield* Ref.set(needsInitialRefreshRef, false); + yield* Ref.set(consecutiveFailuresRef, 0); + return activeInterval; + } - const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason); - if (interruptionReasons.length > 0) { - return yield* Effect.failCause(Cause.fromReasons(interruptionReasons)); - } + const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason); + if (interruptionReasons.length > 0) { + return yield* Effect.failCause(Cause.fromReasons(interruptionReasons)); + } - const consecutiveFailures = yield* Ref.updateAndGet( - consecutiveFailuresRef, - (count) => count + 1, - ); - const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval); - yield* Effect.logWarning("VCS remote status refresh failed", { - cwdLength: cwd.length, - ...remoteRefreshFailureDiagnostics(exit.cause), - consecutiveFailures, - nextDelayMs: Duration.toMillis(nextDelay), - }); - return nextDelay; + const consecutiveFailures = yield* Ref.updateAndGet( + consecutiveFailuresRef, + (count) => count + 1, + ); + const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval); + yield* Effect.logWarning("VCS remote status refresh failed", { + cwdLength: cwd.length, + ...remoteRefreshFailureDiagnostics(exit.cause), + consecutiveFailures, + nextDelayMs: Duration.toMillis(nextDelay), }); + return nextDelay; + }); - if (!refreshImmediately) { - const configuredInterval = yield* automaticRemoteRefreshInterval; - yield* Effect.sleep( - Duration.isZero(configuredInterval) - ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL - : configuredInterval, - ); - } + if (!refreshImmediately) { + const configuredInterval = yield* automaticFetchInterval; + yield* Effect.sleep( + Duration.isZero(configuredInterval) + ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL + : configuredInterval, + ); + } - return yield* refreshRemoteStatusIfEnabled.pipe( - Effect.repeat( - Schedule.identity().pipe( - Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)), - ), + return yield* refreshRemoteStatusIfEnabled.pipe( + Effect.repeat( + Schedule.identity().pipe( + Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)), ), - Effect.asVoid, - ); - }); - }; + ), + Effect.asVoid, + ); + }); const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* ( cwd: string, demandCwd: string, - automaticRemoteRefreshInterval: Effect.Effect, refreshImmediately: boolean, ) { yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => { @@ -629,12 +660,7 @@ export const make = Effect.gen(function* () { return Ref.make>(new Map([[demandCwd, 1]])).pipe( Effect.flatMap((demandCwds) => - makeRemoteRefreshLoop( - cwd, - demandCwds, - automaticRemoteRefreshInterval, - refreshImmediately, - ).pipe( + makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe( Effect.forkIn(broadcasterScope), Effect.map((fiber) => { const nextPollers = new Map(activePollers); @@ -693,7 +719,7 @@ export const make = Effect.gen(function* () { } }); - const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input, options) => + const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) => Stream.unwrap( Effect.gen(function* () { const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); @@ -705,8 +731,6 @@ export const make = Effect.gen(function* () { yield* retainRemotePoller( cwd, input.cwd, - options?.automaticRemoteRefreshInterval ?? - Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL), cachedStatus?.remote === null || cachedStatus?.remote === undefined, ); } diff --git a/apps/server/src/vcs/removeEmptyDirectory.ts b/apps/server/src/vcs/removeEmptyDirectory.ts new file mode 100644 index 0000000000000..2ce80dfe588a2 --- /dev/null +++ b/apps/server/src/vcs/removeEmptyDirectory.ts @@ -0,0 +1,18 @@ +// @effect-diagnostics nodeBuiltinImport:off - Effect's FileSystem has no rmdir. +import * as NodeFSP from "node:fs/promises"; + +import * as Effect from "effect/Effect"; + +/** + * Removes `path` only while it is an empty directory. Succeeds with false when + * anything else is there, including files written after the caller looked. + * Other failures, such as a permission error, stay errors. + */ +export const removeEmptyDirectory = (path: string) => + Effect.tryPromise(() => NodeFSP.rmdir(path)).pipe( + Effect.as(true), + Effect.catchIf( + (error) => (error.cause as NodeJS.ErrnoException | undefined)?.code === "ENOTEMPTY", + () => Effect.succeed(false), + ), + ); diff --git a/apps/server/src/vcs/worktreeRemoval.ts b/apps/server/src/vcs/worktreeRemoval.ts new file mode 100644 index 0000000000000..f1140cdcc3a48 --- /dev/null +++ b/apps/server/src/vcs/worktreeRemoval.ts @@ -0,0 +1,156 @@ +import { GitCommandError } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import type * as GitVcsDriver from "./GitVcsDriver.ts"; + +const INDEX_LIST_MAX_BYTES = 64 * 1024 * 1024; + +/** + * Git for Windows before 2.54 follows NTFS junctions; newer Git leaves them behind. + * On Windows, mirror Git's removal checks, then delete with Node's `rm`, which + * unlinks junctions without following them. Git then removes the worktree metadata. + */ +export const removeLinkedWorktree = Effect.fn("WorktreeRemoval.removeLinkedWorktree")(function* < + A, + E, + R, +>(input: { + readonly operation: string; + readonly cwd: string; + readonly worktreePath: string; + readonly force: boolean; + readonly execute: GitVcsDriver.GitVcsDriver["Service"]["execute"]; + readonly run: (args: ReadonlyArray) => Effect.Effect; +}) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const worktreePath = input.worktreePath; + const gitFile = path.join(worktreePath, ".git"); + // Git refuses to remove a worktree with untracked files unless forced, but + // its check honors `status.showUntrackedFiles=no` and would delete them. + const statusConfig = ["-c", "status.showUntrackedFiles=normal"]; + const linked = + (yield* HostProcess.isWindows) && + (yield* fileSystem.stat(gitFile).pipe( + Effect.map((info) => info.type === "File"), + Effect.orElseSucceed(() => false), + )); + if (!linked) { + return yield* input.run([ + ...statusConfig, + "worktree", + "remove", + ...(input.force ? ["--force"] : []), + "--", + worktreePath, + ]); + } + + // Git's own refusals, worded the way it prints them. + const refuse = (message: string, cause?: unknown) => + new GitCommandError({ + operation: input.operation, + command: "git worktree remove", + cwd: input.cwd, + detail: `fatal: ${message}`, + ...(cause === undefined ? {} : { cause }), + }); + const gitOutput = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => + input + .execute({ + operation: input.operation, + cwd, + args, + maxOutputBytes: INDEX_LIST_MAX_BYTES, + ...(env === undefined ? {} : { env }), + }) + .pipe(Effect.map((result) => result.stdout)); + const samePath = (left: string, right: string) => + Effect.all([fileSystem.realPath(left), fileSystem.realPath(right)]).pipe( + Effect.map(([a, b]) => a.toLowerCase() === b.toLowerCase()), + Effect.orElseSucceed(() => false), + ); + + // A registered worktree of this repository: its `.git` file names an admin + // directory under the common `worktrees/`, whose `gitdir` points back. + const notAWorktree = refuse(`'${worktreePath}' is not a working tree`); + const adminDir = path.resolve( + worktreePath, + (yield* gitOutput(worktreePath, ["rev-parse", "--absolute-git-dir"]).pipe( + Effect.mapError(() => notAWorktree), + )).trim(), + ); + const commonDir = path.resolve( + input.cwd, + (yield* gitOutput(input.cwd, ["rev-parse", "--git-common-dir"])).trim(), + ); + const pointsBack = yield* fileSystem.readFileString(path.join(adminDir, "gitdir")).pipe( + Effect.flatMap((gitdir) => samePath(path.resolve(adminDir, gitdir.trim()), gitFile)), + Effect.orElseSucceed(() => false), + ); + if (!pointsBack || !(yield* samePath(path.dirname(adminDir), path.join(commonDir, "worktrees")))) + return yield* notAWorktree; + // Git counts the file's existence as a lock. T3 passes at most one + // `--force`, which never removes a locked worktree. Anything but a + // confirmed absence refuses. + const lockFile = path.join(adminDir, "locked"); + const locked = yield* fileSystem.stat(lockFile).pipe( + Effect.as(true), + Effect.catch((error) => + error.reason._tag === "NotFound" + ? Effect.succeed(false) + : Effect.fail(refuse(`cannot inspect the lock of '${worktreePath}'`, error)), + ), + ); + if (locked) { + const reason = (yield* fileSystem.readFileString(lockFile).pipe(Effect.option)).pipe( + Option.map((text) => text.trim()), + Option.getOrElse(() => ""), + ); + return yield* refuse( + reason === "" + ? "cannot remove a locked working tree;\nuse 'remove -f -f' to override or unlock first" + : `cannot remove a locked working tree, lock reason: ${reason}\nuse 'remove -f -f' to override or unlock first`, + ); + } + if (!input.force) { + // Bound like Git's own check, so `core.worktree` can't point it elsewhere. + const boundEnv = { GIT_DIR: gitFile, GIT_WORK_TREE: worktreePath }; + const submodules = refuse("working trees containing submodules cannot be moved or removed"); + // An unreadable path counts as present, so a doubt refuses. + const present = (target: string) => + fileSystem.exists(target).pipe(Effect.orElseSucceed(() => true)); + if (yield* present(path.join(adminDir, "modules"))) return yield* submodules; + const index = yield* gitOutput(worktreePath, ["ls-files", "--stage", "-z"], boundEnv); + for (const entry of index.split("\0")) { + if (!entry.startsWith("160000 ")) continue; + const submodule = entry.slice(entry.indexOf("\t") + 1); + if (yield* present(path.join(worktreePath, submodule, ".git"))) return yield* submodules; + } + const status = yield* gitOutput( + worktreePath, + [...statusConfig, "status", "--porcelain", "--ignore-submodules=none"], + boundEnv, + ); + if (status !== "") + return yield* refuse( + `'${worktreePath}' contains modified or untracked files, use --force to delete it`, + ); + } + + // A file held open can stop the delete partway. Putting `.git` back, when + // that works, leaves a worktree that a retry can remove. + const gitFileContents = yield* fileSystem + .readFileString(gitFile) + .pipe(Effect.mapError(() => notAWorktree)); + yield* fileSystem.remove(worktreePath, { recursive: true }).pipe( + Effect.tapError(() => fileSystem.writeFileString(gitFile, gitFileContents).pipe(Effect.ignore)), + Effect.mapError((cause) => refuse(`failed to delete '${worktreePath}'`, cause)), + ); + // The folder is gone, so Git only drops the worktree's metadata. + return yield* input.run(["worktree", "remove", "--force", "--force", "--", worktreePath]); +}); diff --git a/apps/server/src/workspace/KnownWorkspaces.ts b/apps/server/src/workspace/KnownWorkspaces.ts index d98939415d913..f442e4cedbb61 100644 --- a/apps/server/src/workspace/KnownWorkspaces.ts +++ b/apps/server/src/workspace/KnownWorkspaces.ts @@ -1,13 +1,6 @@ -/** - * KnownWorkspaces - the folders a client-named cwd may act in: a T3-managed - * worktree folder, a registered project, or a thread's worktree. Clients send - * the thread's worktree, else the project root. A client also sets a thread's - * worktree path, so one counts only under a managed folder or when git lists - * it as a worktree of the thread's project. - * - * @module KnownWorkspaces - */ +// Client-supplied worktrees count only under managed folders or when Git lists them for the project. import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -34,7 +27,7 @@ export class UnknownWorkspaceError extends Schema.TaggedError { const relative = path.relative(root, candidate); return ( @@ -46,14 +39,14 @@ export const isWithinRoot = (path: Path.Path, candidate: string, root: string) = export class KnownWorkspaces extends Context.Service< KnownWorkspaces, { - /** Whether a symlink-resolved path is inside a known workspace. */ + /** Takes a symlink-resolved path. */ readonly contains: (realPath: string) => Effect.Effect; /** Fails unless `cwd` exists and resolves inside a known workspace. */ readonly assertContains: (cwd: string) => Effect.Effect; } >()("t3/workspace/KnownWorkspaces") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; const fileSystem = yield* FileSystem.FileSystem; @@ -63,8 +56,7 @@ export const make = Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const git = yield* GitVcsDriver.GitVcsDriver; - // A root that does not exist yet keeps its lexical path. One that cannot be - // resolved for another reason, or resolves to a filesystem root, grants nothing. + // Missing roots keep lexical paths; other resolution failures and filesystem roots grant nothing. const resolveRoot = (value: string) => { const resolvedPath = path.resolve(value); return fileSystem.realPath(resolvedPath).pipe( @@ -105,7 +97,10 @@ export const make = Effect.gen(function* () { project_id AS "projectId" FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL AND json_extract(payload_json, '$.worktreePath') IS NOT NULL - `.pipe(Effect.orElseSucceed(() => [])); + `.pipe( + NodeSqliteClient.readOnly, + Effect.orElseSucceed(() => []), + ); const projectWorktrees = new Map>(); const isProjectWorktree = Effect.fnUntraced(function* ( projectId: string, @@ -126,8 +121,7 @@ export const make = Effect.gen(function* () { return real !== null && listed.includes(real); }); for (const { worktreePath, projectId } of threads) { - // A relative path would resolve against the server's own cwd. One under a - // managed folder is still resolved: it can be a symlink to a checkout elsewhere. + // Relative paths use server cwd; managed paths still need resolution to reject symlinks elsewhere. if (!path.isAbsolute(worktreePath)) continue; if (!within(yield* resolveRoot(worktreePath))) continue; const lexical = path.resolve(worktreePath); diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index d700ca9547e06..730d02c577f43 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -1,7 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -import * as NodeFSP from "node:fs/promises"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { FileFinder } from "@ff-labs/fff-node"; import { it, afterEach, describe, expect } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -176,7 +174,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; for (const { directoryPath, ignored, except } of [ { directoryPath: "node_modules", ignored: true, except: [] }, - // A force-tracked file and a folder holding tracked files stay unignored. { directoryPath: "dist", ignored: true, except: ["dist/kept.js", "dist/vendored"] }, // git reads `[id]/page.tsx` as a pathspec, which matches the tracked `i/page.tsx`. { directoryPath: "[id]", ignored: true, except: ["[id]/page.tsx"] }, @@ -185,8 +182,7 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { ? [ // git refuses to classify paths beyond a symlink, so nothing there is labelled. { directoryPath: "node_modules/link", ignored: false, except: [] }, - // A leading `:` is pathspec magic, so git reads `:foo/pkg-0.js` as `foo/pkg-0.js`, - // which `!foo/` keeps unignored. + // Leading : is pathspec magic; Git sees foo/pkg-0.js, unignored by !foo/. { directoryPath: ":foo", ignored: false, except: [] }, ] : []), @@ -205,8 +201,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { ); it.effect("lists a host folder and its parent, each from its own root", () => - // Folder links outside the workspace browse by passing the host folder as - // `cwd`; walking up passes the parent. Each stays bounded by its own root. Effect.gen(function* () { const parent = yield* makeTempDir(); const path = yield* Path.Path; @@ -253,39 +247,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect( - "browses a workspace with more than 25,000 entries without truncation", - () => - Effect.gen(function* () { - const cwd = yield* makeTempDir(); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - for (let directory = 0; directory < 26; directory++) { - const directoryPath = path.join(cwd, `folder-${directory}`); - yield* fileSystem.makeDirectory(directoryPath); - yield* Effect.forEach( - Array.from({ length: 1000 }, (_, i) => i), - (i) => fileSystem.writeFileString(path.join(directoryPath, `file-${i}.txt`), ""), - { concurrency: 32, discard: true }, - ); - } - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const root = yield* workspaceEntries.list({ cwd, directoryPath: "" }); - expect(root.entries).toHaveLength(26); - expect(root.truncated).toBe(false); - for (const directory of root.entries) { - const result = yield* workspaceEntries.list({ cwd, directoryPath: directory.path }); - expect(result.entries).toHaveLength(1000); - expect(result.truncated).toBe(false); - expect(result.entries).toContainEqual({ - path: `${directory.path}/file-999.txt`, - kind: "file", - }); - } - }), - 60_000, - ); - it.effect("includes images and other binary files in non-git workspace indexes", () => Effect.gen(function* () { const cwd = yield* makeTempDir(); @@ -321,116 +282,32 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect(images.truncated).toBe(false); }), ); + }); - it.effect("returns the complete cached workspace index", () => + describe("listIgnoredFiles", () => { + it.effect("lists ignored files with sizes and skips wholly ignored folders", () => Effect.gen(function* () { - const cwd = yield* makeTempDir(); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - yield* writeTextFile(cwd, "README.md"); - yield* writeTextFile(cwd, "node_modules/pkg/index.js"); + const cwd = yield* makeTempDir({ git: true }); + yield* writeTextFile(cwd, ".gitignore", "node_modules/\n.env*\n"); + yield* writeTextFile(cwd, ".env", "A=1"); + yield* writeTextFile(cwd, "apps/web/index.ts", "y"); + yield* git(cwd, ["add", "apps/web/index.ts"]); + yield* writeTextFile(cwd, "apps/web/.env.local", "B=22"); + yield* writeTextFile(cwd, "node_modules/pkg/index.js", "x"); const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const result = yield* workspaceEntries.list({ cwd }); - - expect(result.entries).toEqual( - expect.arrayContaining([ - { path: "src", kind: "directory" }, - { path: "src/components", kind: "directory" }, - { - path: "src/components/Composer.tsx", - kind: "file", - }, - { path: "README.md", kind: "file" }, - ]), - ); - expect(result.entries.some((entry) => entry.path.startsWith("node_modules"))).toBe(false); - expect(result.truncated).toBe(false); + expect(yield* workspaceEntries.listIgnoredFiles({ cwd })).toEqual({ + files: [ + { path: ".env", byteLength: 3 }, + { path: "apps/web/.env.local", byteLength: 4 }, + ], + truncated: false, + }); }), ); }); describe("search", () => { - it.effect("returns files and directories relative to cwd", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir(); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - yield* writeTextFile(cwd, "src/index.ts"); - yield* writeTextFile(cwd, "README.md"); - yield* writeTextFile(cwd, ".git/HEAD"); - yield* writeTextFile(cwd, "node_modules/pkg/index.js"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - expect(paths).toContain("src"); - expect(paths).toContain("src/components"); - expect(paths).toContain("src/components/Composer.tsx"); - expect(paths).toContain("README.md"); - expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false); - expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false); - expect(result.truncated).toBe(false); - }), - ); - - it.effect("filters and ranks entries by query", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-query-" }); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - yield* writeTextFile(cwd, "src/components/composePrompt.ts"); - yield* writeTextFile(cwd, "docs/composition.md"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "compo", limit: 5 }); - - expect(result.entries.length).toBeGreaterThan(0); - expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true); - expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe( - true, - ); - }), - ); - - it.effect("supports fuzzy subsequence queries for composer path search", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-query-" }); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - yield* writeTextFile(cwd, "src/components/composePrompt.ts"); - yield* writeTextFile(cwd, "docs/composition.md"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 }); - const paths = result.entries.map((entry) => entry.path); - - expect(result.entries.length).toBeGreaterThan(0); - expect(paths).toContain("src/components"); - expect(paths).toContain("src/components/Composer.tsx"); - }), - ); - - it.effect("prioritizes exact basename matches ahead of broader path matches", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-exact-ranking-" }); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - yield* writeTextFile(cwd, "docs/composer.tsx-notes.md"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "Composer.tsx", limit: 5 }); - - expect(result.entries[0]?.path).toBe("src/components/Composer.tsx"); - }), - ); - - it.effect("tracks truncation without sorting every fuzzy match", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" }); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - yield* writeTextFile(cwd, "src/components/composePrompt.ts"); - yield* writeTextFile(cwd, "docs/composition.md"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 }); - - expect(result.entries).toHaveLength(1); - expect(result.truncated).toBe(true); - }), - ); - it.effect("applies the file filter before limiting search results", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-file-limit-" }); @@ -452,44 +329,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect("answers an empty file-filtered query with a bounded file listing", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-empty-query-" }); - yield* writeTextFile(cwd, "src/index.ts"); - yield* writeTextFile(cwd, "README.md"); - - const result = yield* searchWorkspaceEntries({ - cwd, - query: "", - limit: 10, - kind: "file", - }); - - const paths = result.entries.map((entry) => entry.path); - expect(paths).toHaveLength(2); - expect(paths).toContain("src/index.ts"); - expect(paths).toContain("README.md"); - expect(result.entries.every((entry) => entry.kind === "file")).toBe(true); - }), - ); - - it.effect("returns only directories for the directory filter", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-directory-filter-" }); - yield* writeTextFile(cwd, "src/index.ts"); - - const result = yield* searchWorkspaceEntries({ - cwd, - query: "src", - limit: 10, - kind: "directory", - }); - - expect(result.entries).toEqual([{ path: "src", kind: "directory" }]); - expect(result.truncated).toBe(false); - }), - ); - it.effect("excludes gitignored paths for git repositories", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true }); @@ -529,57 +368,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); }), ); - - it.effect("excludes .convex in non-git workspaces", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-non-git-convex-" }); - yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); - yield* writeTextFile(cwd, "src/keep.ts", "export {};"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - expect(paths).toContain("src"); - expect(paths).toContain("src/keep.ts"); - expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); - }), - ); - - it.effect("supports typo-resistant file search through fff", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fff-typo-" }); - yield* writeTextFile(cwd, "src/components/Composer.tsx"); - - const result = yield* searchWorkspaceEntries({ cwd, query: "compoesr", limit: 10 }); - - expect(result.entries).toEqual( - expect.arrayContaining([ - expect.objectContaining({ path: "src/components/Composer.tsx" }), - ]), - ); - }), - ); - - it.effect("rebuilds the cached index after refresh fails", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-refresh-failure-" }); - yield* writeTextFile(cwd, "src/index.ts", "export {};\n"); - - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const createSpy = vi.spyOn(FileFinder, "create"); - yield* workspaceEntries.list({ cwd }); - expect(createSpy).toHaveBeenCalledTimes(1); - - vi.spyOn(FileFinder.prototype, "scanFiles").mockReturnValueOnce({ - ok: false, - error: "scan failed", - }); - yield* workspaceEntries.refresh(cwd); - - yield* workspaceEntries.list({ cwd }); - expect(createSpy).toHaveBeenCalledTimes(2); - }), - ); }); describe("searchContents", () => { @@ -634,36 +422,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect("filters whole-word matches by word boundaries without widening ranges", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-whole-word-" }); - yield* writeTextFile(cwd, "src/words.ts", "note notes denote\nfootnote note\n"); - - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const result = yield* workspaceEntries.searchContents({ - cwd, - query: "note", - limit: 100, - caseSensitive: true, - wholeWord: true, - useRegex: false, - }); - - expect(result.matches).toEqual([ - expect.objectContaining({ - path: "src/words.ts", - lineNumber: 1, - matchRanges: [{ start: 0, end: 4 }], - }), - expect.objectContaining({ - path: "src/words.ts", - lineNumber: 2, - matchRanges: [{ start: 9, end: 13 }], - }), - ]); - }), - ); - it.effect("finds later whole-word matches in a file after rejected raw matches", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-late-whole-word-" }); @@ -742,33 +500,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect("matches punctuation-edged regex queries as whole words", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-regex-punctuation-" }); - yield* writeTextFile(cwd, "src/words.ts", "foo- foo-\nafoo-b\n"); - - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const result = yield* workspaceEntries.searchContents({ - cwd, - query: "foo-", - limit: 100, - caseSensitive: true, - wholeWord: true, - useRegex: true, - }); - - expect(result.matches).toHaveLength(1); - expect(result.matches[0]).toMatchObject({ - path: "src/words.ts", - lineNumber: 1, - matchRanges: [ - { start: 0, end: 4 }, - { start: 5, end: 9 }, - ], - }); - }), - ); - it.effect("caps matches per file so one dense file cannot fill the page", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-per-file-cap-" }); @@ -813,26 +544,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect("preserves invalid regex errors during case-insensitive searches", () => - Effect.gen(function* () { - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-invalid-regex-" }); - yield* writeTextFile(cwd, "src/shapes.ts", "foobar\n"); - - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const result = yield* workspaceEntries.searchContents({ - cwd, - query: "foo)bar(", - limit: 100, - caseSensitive: false, - wholeWord: false, - useRegex: true, - }); - - expect(result.regexFallbackError).toBeDefined(); - expect(result.matches).toEqual([]); - }), - ); - it.effect("maps multi-byte lines to string-indexed ranges", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-multibyte-" }); @@ -857,29 +568,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }); describe("browse", () => { - it.effect("returns matching directories and excludes files", () => - Effect.gen(function* () { - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const path = yield* Path.Path; - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-prefix-" }); - yield* writeTextFile(cwd, "alphabet.txt", "ignore me"); - yield* writeTextFile(cwd, "alpha/index.ts", "export {};\n"); - yield* writeTextFile(cwd, "alpine/index.ts", "export {};\n"); - - const result = yield* workspaceEntries.browse({ - partialPath: path.join(cwd, "alp"), - }); - - expect(result).toEqual({ - parentPath: cwd, - entries: [ - { name: "alpha", fullPath: path.join(cwd, "alpha") }, - { name: "alpine", fullPath: path.join(cwd, "alpine") }, - ], - }); - }), - ); - it.effect("shows dot directories in directory mode and hidden-prefix mode", () => Effect.gen(function* () { const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; @@ -903,56 +591,5 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }); }), ); - - it.effect("supports relative paths when cwd is provided", () => - Effect.gen(function* () { - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const path = yield* Path.Path; - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-relative-" }); - yield* writeTextFile(cwd, "packages/pkg.json", "{}"); - - const result = yield* workspaceEntries.browse({ - cwd, - partialPath: "./pack", - }); - - expect(result).toEqual({ - parentPath: cwd, - entries: [{ name: "packages", fullPath: path.join(cwd, "packages") }], - }); - }), - ); - - it.effect("rejects relative paths without cwd", () => - Effect.gen(function* () { - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - - const error = yield* workspaceEntries - .browse({ - partialPath: "./src", - }) - .pipe(Effect.flip); - - expect(error._tag).toBe("WorkspaceEntriesCurrentProjectRequiredError"); - expect(error.message).toBe( - "A current project is required to browse relative workspace path './src'.", - ); - }), - ); - - it.effect("returns an empty listing when the OS denies directory access", () => - Effect.gen(function* () { - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const cwd = yield* makeTempDir({ prefix: "t3code-workspace-browse-eacces-" }); - - const denied = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }); - vi.mocked(NodeFSP.readdir).mockRejectedValueOnce(denied); - - const result = yield* workspaceEntries.browse({ - partialPath: yield* appendSeparator(cwd), - }); - expect(result).toEqual({ parentPath: cwd, entries: [] }); - }), - ); }); }); diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index 607db665de714..5f1c5f2660a68 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -14,6 +14,8 @@ import type { ProjectEntry, ProjectListEntriesInput, ProjectListEntriesResult, + ProjectListIgnoredFilesInput, + ProjectListIgnoredFilesResult, ProjectSearchContentsInput, ProjectSearchContentsResult, ProjectSearchEntriesInput, @@ -99,6 +101,9 @@ export class WorkspaceEntries extends Context.Service< readonly search: ( input: ProjectSearchEntriesInput, ) => Effect.Effect; + readonly listIgnoredFiles: ( + input: ProjectListIgnoredFilesInput, + ) => Effect.Effect; readonly searchContents: ( input: ProjectSearchContentsInput, ) => Effect.Effect; @@ -106,6 +111,9 @@ export class WorkspaceEntries extends Context.Service< } >()("t3/workspace/WorkspaceEntries") {} +/** Ignored files offered for copying; more than this is a build folder, not config. */ +const IGNORED_FILES_LIMIT = 200; + /** Paths sent to one `git check-ignore` call when labelling a folder's children. */ const IGNORE_CHECK_CHUNK_SIZE = 1000; @@ -137,7 +145,7 @@ const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(fu ); }); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const path = yield* Path.Path; const workspacePaths = yield* WorkspacePaths.WorkspacePaths; @@ -160,20 +168,21 @@ export const make = Effect.gen(function* () { if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) { continue; } - const recoverRefreshFailure = ( - cause: - | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed - | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut - | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed, - ) => - Effect.gen(function* () { + const recoverRefreshFailure = Effect.fn("WorkspaceEntries.recoverRefreshFailure")( + function* ( + cause: + | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed + | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut + | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed, + ) { yield* Effect.logWarning("Failed to refresh workspace search index", { cwd, variant, cause, }); yield* workspaceSearchIndexes.invalidate(indexKey); - }); + }, + ); yield* Effect.gen(function* () { const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex; yield* searchIndex.refresh(); @@ -325,8 +334,7 @@ export const make = Effect.gen(function* () { }, catch: toError, }); - // Use stdin so large directories cannot exceed the command-line argument limit. - // Ignore classification is optional in non-git workspaces or when git is unavailable. + // stdin avoids argument limits; ignore classification is optional without git/repositories. const checkIgnore = (paths: ReadonlyArray) => vcsProcess .run({ @@ -340,13 +348,8 @@ export const make = Effect.gen(function* () { maxOutputBytes: 16 * 1024 * 1024, }) .pipe(Effect.orElseSucceed(() => undefined)); - // Git consults the index for every path it classifies, which costs hundreds of - // milliseconds for a `node_modules`-sized folder. Asking about the folder itself answers - // for every child: `check-ignore` exits 0 only when the folder is ignored and nothing - // under it is tracked, and an ignored folder hides all of its children. Git reads paths as - // pathspecs, so a folder whose path has magic (`:foo`) or glob (`[id]`) characters, or - // one reached through a symlink, can get a different answer per child and still asks git - // about each. + // Check ignored folders once to avoid child index lookups; exit 0 guarantees no tracked descendants. + // Symlinks and pathspec magic still need per-child checks. if ( entries.length > IGNORE_CHECK_CHUNK_SIZE && target.relativePath !== "" && @@ -387,7 +390,56 @@ export const make = Effect.gen(function* () { }, ); - return WorkspaceEntries.of({ browse, list, refresh, search, searchContents }); + const listIgnoredFiles: WorkspaceEntries["Service"]["listIgnoredFiles"] = Effect.fn( + "WorkspaceEntries.listIgnoredFiles", + )(function* (input) { + const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd); + // `--directory` reports a folder holding nothing but ignored files as one + // `name/` entry, which is how `node_modules` and build output drop out. + const result = yield* vcsProcess + .run({ + operation: "WorkspaceEntries.listIgnoredFiles", + command: "git", + args: [ + "-c", + "core.fsmonitor=false", + "ls-files", + "--others", + "--ignored", + "--exclude-standard", + "--directory", + "--no-empty-directory", + "-z", + ], + cwd: normalizedCwd, + allowNonZeroExit: true, + timeoutMs: 10_000, + maxOutputBytes: 4 * 1024 * 1024, + }) + .pipe(Effect.orElseSucceed(() => undefined)); + if (!result || result.exitCode !== 0) return { files: [], truncated: false }; + const paths = result.stdout + .split("\0") + .filter((entry) => entry.length > 0 && !entry.endsWith("/")) + .toSorted(); + const files = yield* Effect.promise(() => + Promise.all( + paths.slice(0, IGNORED_FILES_LIMIT).map(async (relativePath) => { + // lstat: a symlink usually points outside the workspace, where reads refuse to go. + const stat = await NodeFSP.lstat(path.join(normalizedCwd, relativePath)).catch( + () => null, + ); + return stat?.isFile() ? { path: relativePath, byteLength: stat.size } : null; + }), + ), + ); + return { + files: files.filter((file) => file !== null), + truncated: paths.length > IGNORED_FILES_LIMIT, + }; + }); + + return WorkspaceEntries.of({ browse, list, listIgnoredFiles, refresh, search, searchContents }); }); export const layer = Layer.effect(WorkspaceEntries, make).pipe( diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index ae956e69d0cbc..0cf5524df4e17 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -1,6 +1,8 @@ -// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO. +// @effect-diagnostics nodeBuiltinImport:off - FileSystem cannot create a FIFO, and reads spy on native realpath. import * as NodeChildProcess from "node:child_process"; +import * as NodeFSP from "node:fs/promises"; +import * as NodePath from "@effect/platform-node/NodePath"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { it, describe, expect } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -17,8 +19,13 @@ import * as WorkspaceFileSystem from "./WorkspaceFileSystem.ts"; import * as WorkspacePaths from "./WorkspacePaths.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +import { vi } from "vite-plus/test"; + +vi.mock("node:fs/promises", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, realpath: vi.fn(actual.realpath) }; +}); -// Temp folders count as known workspaces unless named as unknown. const UNKNOWN_WORKSPACE_PREFIX = "t3code-unknown-workspace-"; const layerKnownWorkspacesTest = Layer.mock(KnownWorkspaces.KnownWorkspaces)({ assertContains: (cwd) => @@ -69,19 +76,6 @@ const writeTextFile = Effect.fn("writeTextFile")(function* ( it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (it) => { describe("getMetadata", () => { - it.effect("expands home-relative paths on the server", () => - Effect.gen(function* () { - const service = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const home = yield* makeTempDir; - yield* writeTextFile(home, "file", "hello"); - expect( - (yield* service - .getMetadata({ paths: ["~/file"] }) - .pipe(Effect.provideService(HostProcess.HomeDirectory, home))).entries, - ).toEqual([{ kind: "file", byteLength: 5 }]); - }), - ); - it.effect( "reports actual kinds for extensionless files, dotfiles, and dotted directories", () => @@ -137,65 +131,76 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); - it.effect.skipIf(!symlinksSupported)("follows file and directory symlinks", () => + // A file chip for `file://attacker.test/s/a.ts` in an agent's message sent + // the Windows user's NTLM credentials to attacker.test as it rendered. + it.effect("never stats a network path", () => Effect.gen(function* () { - const service = yield* WorkspaceFileSystem.WorkspaceFileSystem; const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "target", "text"); - yield* fs.makeDirectory(path.join(cwd, "directory")); - const fileLink = path.join(cwd, "file-link"); - const directoryLink = path.join(cwd, "directory-link"); - yield* fs.symlink(path.join(cwd, "target"), fileLink); - yield* fs.symlink(path.join(cwd, "directory"), directoryLink); - expect((yield* service.getMetadata({ paths: [fileLink, directoryLink] })).entries).toEqual([ - { kind: "file", byteLength: 4 }, - { kind: "directory" }, - ]); + const statted: Array = []; + const service = yield* WorkspaceFileSystem.make.pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.FileSystem.of({ + ...fs, + stat: (requestedPath) => { + statted.push(requestedPath); + return fs.stat(requestedPath); + }, + }), + ), + Effect.provide(layerKnownWorkspacesTest), + ); + const paths = [ + "\\\\attacker.test\\s\\a.ts", + "//attacker.test/s/a.ts", + "/\\attacker.test\\s", + ]; + expect((yield* service.getMetadata({ paths })).entries).toEqual([null, null, null]); + expect(statted).toEqual([]); }), ); }); describe("readFile", () => { - it.effect("reads UTF-8 files relative to the workspace root", () => + it.effect("reads host files outside the workspace root by absolute path", () => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const path = yield* Path.Path; const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "src/index.ts", "export const answer = 42;\n"); + const outsideDir = yield* makeTempDir; + yield* writeTextFile(outsideDir, "cleanup-report.md", "# Report\n"); + const absolutePath = path.join(outsideDir, "cleanup-report.md"); const result = yield* workspaceFileSystem.readFile({ cwd, - relativePath: "src/index.ts", + relativePath: absolutePath, }); expect(result).toEqual({ - relativePath: "src/index.ts", - contents: "export const answer = 42;\n", - byteLength: 26, + relativePath: absolutePath, + contents: "# Report\n", + byteLength: 9, truncated: false, }); }), ); - it.effect("reads host files outside the workspace root by absolute path", () => + it.effect("reads ~/ paths from the server home outside the workspace", () => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const path = yield* Path.Path; const cwd = yield* makeTempDir; - const outsideDir = yield* makeTempDir; - yield* writeTextFile(outsideDir, "cleanup-report.md", "# Report\n"); - const absolutePath = path.join(outsideDir, "cleanup-report.md"); + const home = yield* makeTempDir; + yield* writeTextFile(home, ".claude/CLAUDE.md", "# Notes\n"); + yield* writeTextFile(cwd, "~/.claude/CLAUDE.md", "Workspace decoy\n"); - const result = yield* workspaceFileSystem.readFile({ - cwd, - relativePath: absolutePath, - }); + const result = yield* workspaceFileSystem + .readFile({ cwd, relativePath: "~/.claude/CLAUDE.md" }) + .pipe(Effect.provideService(HostProcess.HomeDirectory, home)); expect(result).toEqual({ - relativePath: absolutePath, - contents: "# Report\n", - byteLength: 9, + relativePath: "~/.claude/CLAUDE.md", + contents: "# Notes\n", + byteLength: 8, truncated: false, }); }), @@ -230,21 +235,68 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i }), ); - it.effect("rejects reads outside the workspace root", () => + it.effect("refuses a network path outside the workspace", () => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const cwd = yield* makeTempDir; const error = yield* workspaceFileSystem - .readFile({ cwd, relativePath: "../escape.md" }) + .readFile({ cwd: "//nas.test/share/project", relativePath: "//attacker.test/s/a.md" }) .pipe(Effect.flip); - expect(error.message).toContain( - "Workspace file path must be relative to the project root: ../escape.md", + expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError); + }), + ); + + // This resolves inside the project, but Windows reads `\\?\` paths as + // written, so realpath on the raw string signed in to attacker.test. + it.effect("reads the network path it checked", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.make.pipe( + Effect.provide(Layer.merge(layerKnownWorkspacesTest, NodePath.layerWin32)), ); + // Rejects without touching the filesystem, so a Windows runner never looks the share up. + const realpath = vi + .mocked(NodeFSP.realpath) + .mockClear() + .mockRejectedValueOnce(Object.assign(new Error("ENOENT"), { code: "ENOENT" })); + + yield* workspaceFileSystem + .readFile({ + cwd: "\\\\?\\UNC\\nas.test\\share\\project", + relativePath: "\\\\?\\UNC\\attacker.test\\s\\..\\..\\nas.test\\share\\project\\a.md", + }) + .pipe(Effect.exit); + + expect(realpath.mock.calls.map(([target]) => target)).toEqual([ + "\\\\?\\UNC\\nas.test\\share\\project\\a.md", + ]); }), ); + // Resolving `..` before realpath would read beside the link instead of its target. + // Windows collapses `..` before the filesystem sees a path, so it has no such reads. + it.effect.skipIf(!symlinksSupported || HostProcess.Platform.defaultValue() === "win32")( + "reads `..` after a link from the link's target", + () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* makeTempDir; + yield* writeTextFile(root, "target/parent.md", "beside the target\n"); + yield* writeTextFile(root, "parent.md", "beside the link\n"); + yield* fs.makeDirectory(path.join(root, "target", "child")); + yield* fs.symlink(path.join(root, "target", "child"), path.join(root, "link")); + + const result = yield* workspaceFileSystem.readFile({ + cwd: root, + relativePath: `${root}/link/../parent.md`, + }); + + expect(result.contents).toBe("beside the target\n"); + }), + ); + it.effect.skipIf(!symlinksSupported)( "rejects symlinks that resolve outside the workspace root", () => @@ -274,30 +326,20 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i resolvedPath, }); expect("cause" in error).toBe(false); - }), - ); - - it.effect("rejects directories without manufacturing an I/O cause", () => - Effect.gen(function* () { - const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const cwd = yield* makeTempDir; - yield* fileSystem.makeDirectory(path.join(cwd, "src")); - - const error = yield* workspaceFileSystem - .readFile({ cwd, relativePath: "src" }) - .pipe(Effect.flip); - const resolvedPath = yield* fileSystem.realPath(path.join(cwd, "src")); - expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspacePathNotFileError); - expect(error).toMatchObject({ - workspaceRoot: cwd, - relativePath: "src", - resolvedPath, - }); - expect("cause" in error).toBe(false); - }), + yield* fileSystem.symlink(outsideDir, path.join(cwd, "linked-dir")); + const missingChildError = yield* workspaceFileSystem + .readFile( + Object.assign( + { cwd, relativePath: "linked-dir/missing/t3.json" }, + { allowMissing: true }, + ), + ) + .pipe(Effect.flip); + expect(missingChildError).toBeInstanceOf( + WorkspaceFileSystem.WorkspaceFilePathEscapeError, + ); + }), ); it.effect("rejects binary files without leaking their contents into the error", () => @@ -324,53 +366,9 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i expect("contents" in error).toBe(false); }), ); - - it.effect("preserves the real cause and path for I/O failures", () => - Effect.gen(function* () { - const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const path = yield* Path.Path; - const cwd = yield* makeTempDir; - const resolvedPath = path.join(cwd, "missing.txt"); - - const error = yield* workspaceFileSystem - .readFile({ cwd, relativePath: "missing.txt" }) - .pipe(Effect.flip); - - expect(error).toBeInstanceOf(WorkspaceFileSystem.WorkspaceFileSystemOperationError); - expect(error).toMatchObject({ - workspaceRoot: cwd, - relativePath: "missing.txt", - resolvedPath, - operationPath: resolvedPath, - operation: "realpath-target", - }); - expect(error.cause).toBeInstanceOf(Error); - expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT"); - }), - ); }); describe("writeFile", () => { - it.effect("writes files relative to the workspace root", () => - Effect.gen(function* () { - const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; - const cwd = yield* makeTempDir; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const result = yield* workspaceFileSystem.writeFile({ - cwd, - relativePath: "plans/effect-rpc.md", - contents: "# Plan\n", - }); - const saved = yield* fileSystem - .readFileString(path.join(cwd, "plans/effect-rpc.md")) - .pipe(Effect.orDie); - - expect(result).toEqual({ relativePath: "plans/effect-rpc.md" }); - expect(saved).toBe("# Plan\n"); - }), - ); - it.effect("rejects writes outside a known workspace", () => Effect.gen(function* () { const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem; @@ -576,7 +574,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i const path = yield* Path.Path; const cwd = yield* makeTempDir; yield* writeTextFile(cwd, ".git/config", "[core]\n"); - // A bare repository named `.bare`, and a linked worktree's git folder inside it. yield* writeTextFile(cwd, ".bare/HEAD", "ref: refs/heads/main\n"); yield* writeTextFile(cwd, ".bare/objects/info/packs"); yield* writeTextFile(cwd, ".bare/refs/heads/main"); @@ -650,7 +647,6 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const parentDir = yield* makeTempDir; - // A bare repository with a worktree checked out inside it. const bare = path.join(parentDir, "repo.git"); yield* writeTextFile(bare, "HEAD", "ref: refs/heads/main\n"); yield* writeTextFile(bare, "objects/info/packs"); diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index 96fe5a0d234f8..13c741b049bef 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -13,6 +13,7 @@ import type { } from "@t3tools/contracts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { isNetworkPath } from "@t3tools/shared/path"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -27,8 +28,7 @@ import { fileHeaderMimeType } from "./fileHeaderMimeType.ts"; const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024; -// Windows also reaches `.git` through trailing dots or spaces, a `:` stream -// suffix, or the 8.3 short name `GIT~1`. Names compare upcased, as NTFS does. +// NTFS reaches .git through trailing dots/spaces, stream suffixes and GIT~1; compare uppercased names. const isGitMetadataName = (segment: string) => { const name = (segment.split(":")[0] ?? "").replace(/[. ]+$/, "").toUpperCase(); return name === ".GIT" || name === "GIT~1"; @@ -132,7 +132,7 @@ export class WorkspaceFileSystem extends Context.Service< } >()("t3/workspace/WorkspaceFileSystem") {} -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -142,7 +142,9 @@ export const make = Effect.gen(function* () { const metadataForPath = Effect.fnUntraced(function* (requestedPath: string) { const expandedPath = expandHomePath(requestedPath, yield* HostProcess.HomeDirectory); - if (!path.isAbsolute(expandedPath)) return null; + // Chips ask as soon as an agent's message renders, and touching a network + // path makes Windows sign in to its host with the user's NTLM credentials. + if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null; const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option); if (stat._tag === "None") return null; if (stat.value.type === "Directory") return { kind: "directory" } as const; @@ -193,13 +195,8 @@ export const make = Effect.gen(function* () { ); }; - /** - * Git runs config and hooks from its own folders, so a write never lands in one: - * a `.git` entry, or a repository folder under another name such as `.bare`. - * Folders are checked upward to a linked worktree's top, which holds a `.git` - * file, since worktrees can sit inside a bare repository. `absolutePath` must - * be normalized. - */ + // Reject Git folders, including renamed bare repos whose config/hooks can execute; paths must be normalized. + // Stop at linked worktrees' .git files since worktrees can sit inside bare repos. const isInGitFolder = async (absolutePath: string) => { if (absolutePath.split(path.sep).some(isGitMetadataName)) return true; for (let folder = path.dirname(absolutePath); ; folder = path.dirname(folder)) { @@ -212,8 +209,7 @@ export const make = Effect.gen(function* () { }), ), ); - // What git reads as a repository: HEAD, plus objects and refs here or in - // the folder a `commondir` file names, as in a linked worktree's git folder. + // Git recognizes HEAD with commondir or objects/refs as a repository. if (head && (commondir || (objects && refs))) return true; if (dotGit?.isFile() || path.dirname(folder) === folder) return false; } @@ -221,26 +217,49 @@ export const make = Effect.gen(function* () { /** * Workspace-relative paths must stay inside the root, symlinks included. An - * absolute path reads a host file in place, such as a report an agent wrote to a - * temp directory; it gets no root check. + * absolute or `~/` path reads a host file in place, such as a report an agent + * wrote to a temp directory; it gets no root check. A network path does, since + * Windows signs in to its host with the user's NTLM credentials. */ const resolveReadTarget = Effect.fn("WorkspaceFileSystem.resolveReadTarget")(function* ( input: ProjectReadFileInput, ) { const requestedPath = input.relativePath.trim(); - if (path.isAbsolute(requestedPath)) { + const hostPath = requestedPath.startsWith("~/") + ? expandHomePath(requestedPath, yield* HostProcess.HomeDirectory) + : requestedPath; + if ( + isNetworkPath(hostPath) && + !KnownWorkspaces.isWithinRoot(path, path.resolve(hostPath), path.resolve(input.cwd)) + ) { + return yield* new WorkspacePaths.WorkspacePathOutsideRootError({ + workspaceRoot: input.cwd, + relativePath: input.relativePath, + }); + } + if (path.isAbsolute(hostPath)) { + // Native realpath hands Windows a `\\?\` path as written, `..` included, + // so a network path must be the resolved one the check above approved. + // Others keep POSIX `link/..` semantics, which resolving first would change. + const absolutePath = isNetworkPath(hostPath) ? path.resolve(hostPath) : hostPath; const realTargetPath = yield* Effect.tryPromise({ - try: () => NodeFSP.realpath(requestedPath), + try: () => NodeFSP.realpath(absolutePath), catch: (cause) => new WorkspaceFileSystemOperationError({ workspaceRoot: input.cwd, relativePath: input.relativePath, - resolvedPath: requestedPath, - operationPath: requestedPath, + resolvedPath: absolutePath, + operationPath: absolutePath, operation: "realpath-target", cause, }), - }); + }).pipe( + Effect.catchIf( + (error) => + input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT", + () => Effect.succeed(null), + ), + ); return { relativePath: requestedPath, realTargetPath }; } @@ -261,8 +280,36 @@ export const make = Effect.gen(function* () { cause, }), }); - const realTargetPath = yield* Effect.tryPromise({ - try: () => NodeFSP.realpath(target.absolutePath), + const resolved = yield* Effect.tryPromise({ + try: async () => { + let candidate = target.absolutePath; + for (;;) { + try { + return { + realTargetPath: path.join( + await NodeFSP.realpath(candidate), + path.relative(candidate, target.absolutePath), + ), + exists: candidate === target.absolutePath, + }; + } catch (error) { + if (!input.allowMissing || (error as NodeJS.ErrnoException).code !== "ENOENT") { + throw error; + } + // Like writes, missing reads must check the nearest existing ancestor. + // An existing entry that cannot resolve is a dangling link, not absence. + const exists = await NodeFSP.lstat(candidate).then( + () => true, + (cause: NodeJS.ErrnoException) => { + if (cause.code !== "ENOENT") throw cause; + return false; + }, + ); + if (exists || path.dirname(candidate) === candidate) throw error; + candidate = path.dirname(candidate); + } + } + }, catch: (cause) => new WorkspaceFileSystemOperationError({ workspaceRoot: input.cwd, @@ -273,27 +320,37 @@ export const make = Effect.gen(function* () { cause, }), }); - if (!isInsideRealRoot(realWorkspaceRoot, realTargetPath)) { + if (!isInsideRealRoot(realWorkspaceRoot, resolved.realTargetPath)) { return yield* new WorkspaceFilePathEscapeError({ workspaceRoot: input.cwd, relativePath: input.relativePath, resolvedWorkspaceRoot: realWorkspaceRoot, - resolvedPath: realTargetPath, + resolvedPath: resolved.realTargetPath, }); } - return { relativePath: target.relativePath, realTargetPath }; + return { + relativePath: target.relativePath, + realTargetPath: resolved.exists ? resolved.realTargetPath : null, + }; }); const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn( "WorkspaceFileSystem.readFile", )(function* (input) { const target = yield* resolveReadTarget(input); + const absentResult = { + relativePath: target.relativePath, + contents: "", + byteLength: 0, + truncated: false, + exists: false, + }; const realTargetPath = target.realTargetPath; + if (realTargetPath === null) return absentResult; return yield* Effect.acquireUseRelease( Effect.tryPromise({ - // Non-blocking so a FIFO cannot hang the open; the stat below rejects - // it. Regular files ignore the flag. Windows lacks it. + // Non-blocking opens prevent FIFO hangs before stat rejects them; Windows lacks the flag. try: () => NodeFSP.open( realTargetPath, @@ -308,9 +365,16 @@ export const make = Effect.gen(function* () { operation: "open", cause, }), - }), + }).pipe( + Effect.catchIf( + (error) => + input.allowMissing === true && (error.cause as NodeJS.ErrnoException).code === "ENOENT", + () => Effect.succeed(null), + ), + ), (handle) => Effect.gen(function* () { + if (handle === null) return absentResult; const stat = yield* Effect.tryPromise({ try: () => handle.stat(), catch: (cause) => @@ -362,27 +426,24 @@ export const make = Effect.gen(function* () { }; }), (handle) => - Effect.tryPromise({ - try: () => handle.close(), - catch: (cause) => - new WorkspaceFileSystemOperationError({ - workspaceRoot: input.cwd, - relativePath: input.relativePath, - resolvedPath: realTargetPath, - operationPath: realTargetPath, - operation: "close", - cause, + handle === null + ? Effect.void + : Effect.tryPromise({ + try: () => handle.close(), + catch: (cause) => + new WorkspaceFileSystemOperationError({ + workspaceRoot: input.cwd, + relativePath: input.relativePath, + resolvedPath: realTargetPath, + operationPath: realTargetPath, + operation: "close", + cause, + }), }), - }), ); }); - /** - * Resolves the file a write targets. The deepest existing ancestor resolves to - * its real path before the root check, so neither the file nor the directories - * created for it can follow a symlink out of the root. A dangling symlink is - * rejected rather than written through. - */ + // Resolve existing ancestors and reject dangling links so creation cannot follow symlinks outside root. const resolveWriteTarget = Effect.fn("WorkspaceFileSystem.resolveWriteTarget")(function* ( input: ProjectWriteFileInput, ) { diff --git a/apps/server/src/workspace/WorkspacePaths.test.ts b/apps/server/src/workspace/WorkspacePaths.test.ts index ecaf6116c67ac..574904b343563 100644 --- a/apps/server/src/workspace/WorkspacePaths.test.ts +++ b/apps/server/src/workspace/WorkspacePaths.test.ts @@ -4,7 +4,6 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; -import * as PlatformError from "effect/PlatformError"; import * as WorkspacePaths from "./WorkspacePaths.ts"; @@ -20,47 +19,8 @@ const makeTempDir = Effect.fn("makeTempDir")(function* () { }); }); -const writeTextFile = Effect.fn("writeTextFile")(function* ( - cwd: string, - relativePath: string, - contents = "", -) { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const absolutePath = path.join(cwd, relativePath); - yield* fileSystem - .makeDirectory(path.dirname(absolutePath), { recursive: true }) - .pipe(Effect.orDie); - yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); -}); - it.layer(layerTest)("WorkspacePathsLive", (it) => { describe("normalizeWorkspaceRoot", () => { - it.effect("resolves an existing directory", () => - Effect.gen(function* () { - const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - const cwd = yield* makeTempDir(); - - const resolved = yield* workspacePaths.normalizeWorkspaceRoot(cwd); - - expect(resolved).toBe(cwd); - }), - ); - - it.effect("rejects missing directories", () => - Effect.gen(function* () { - const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - const cwd = yield* makeTempDir(); - const path = yield* Path.Path; - - const error = yield* workspacePaths - .normalizeWorkspaceRoot(path.join(cwd, "missing")) - .pipe(Effect.flip); - - expect(error.message).toContain("Workspace root does not exist:"); - }), - ); - it.effect("creates missing directories when createIfMissing is enabled", () => Effect.gen(function* () { const workspacePaths = yield* WorkspacePaths.WorkspacePaths; @@ -78,114 +38,9 @@ it.layer(layerTest)("WorkspacePathsLive", (it) => { expect(stat.type).toBe("Directory"); }), ); - - it.effect("rejects file paths", () => - Effect.gen(function* () { - const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - const cwd = yield* makeTempDir(); - const path = yield* Path.Path; - const filePath = path.join(cwd, "README.md"); - yield* writeTextFile(cwd, "README.md", "# hi\n"); - - const error = yield* workspacePaths.normalizeWorkspaceRoot(filePath).pipe(Effect.flip); - - expect(error.message).toContain("Workspace root is not a directory:"); - }), - ); - - it.effect("preserves non-NotFound stat failures while validating the root", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const workspacePaths = yield* WorkspacePaths.make.pipe( - Effect.provideService(FileSystem.FileSystem, { - ...fileSystem, - stat: (path) => - Effect.fail( - PlatformError.systemError({ - _tag: "PermissionDenied", - module: "FileSystem", - method: "stat", - pathOrDescriptor: String(path), - description: "Test PermissionDenied stat failure.", - }), - ), - }), - ); - const path = yield* Path.Path; - const workspaceRoot = " ./permission-denied "; - const normalizedWorkspaceRoot = path.resolve(workspaceRoot.trim()); - - const error = yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(Effect.flip); - - expect(error).toBeInstanceOf(WorkspacePaths.WorkspaceRootStatFailedError); - expect(error).toMatchObject({ - workspaceRoot, - normalizedWorkspaceRoot, - phase: "validate-existing", - }); - }), - ); - - it.effect("preserves stat failures while verifying a newly created root", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - let statCalls = 0; - const workspacePaths = yield* WorkspacePaths.make.pipe( - Effect.provideService(FileSystem.FileSystem, { - ...fileSystem, - stat: (path) => { - statCalls += 1; - const reason = statCalls === 1 ? "NotFound" : "PermissionDenied"; - return Effect.fail( - PlatformError.systemError({ - _tag: reason, - module: "FileSystem", - method: "stat", - pathOrDescriptor: String(path), - description: `Test ${reason} stat failure.`, - }), - ); - }, - makeDirectory: () => Effect.void, - }), - ); - const path = yield* Path.Path; - const workspaceRoot = " ./created-then-unreadable "; - const normalizedWorkspaceRoot = path.resolve(workspaceRoot.trim()); - - const error = yield* workspacePaths - .normalizeWorkspaceRoot(workspaceRoot, { createIfMissing: true }) - .pipe(Effect.flip); - - expect(error).toBeInstanceOf(WorkspacePaths.WorkspaceRootStatFailedError); - expect(error).toMatchObject({ - workspaceRoot, - normalizedWorkspaceRoot, - phase: "verify-created", - }); - }), - ); }); describe("resolveRelativePathWithinRoot", () => { - it.effect("resolves relative paths inside the workspace root", () => - Effect.gen(function* () { - const workspacePaths = yield* WorkspacePaths.WorkspacePaths; - const cwd = yield* makeTempDir(); - const path = yield* Path.Path; - - const resolved = yield* workspacePaths.resolveRelativePathWithinRoot({ - workspaceRoot: cwd, - relativePath: "plans/effect-rpc.md", - }); - - expect(resolved).toEqual({ - absolutePath: path.join(cwd, "plans/effect-rpc.md"), - relativePath: "plans/effect-rpc.md", - }); - }), - ); - it.effect("rejects paths that escape the workspace root", () => Effect.gen(function* () { const workspacePaths = yield* WorkspacePaths.WorkspacePaths; diff --git a/apps/server/src/workspace/WorkspacePaths.ts b/apps/server/src/workspace/WorkspacePaths.ts index 2c61bbe76501e..6b748e19396ec 100644 --- a/apps/server/src/workspace/WorkspacePaths.ts +++ b/apps/server/src/workspace/WorkspacePaths.ts @@ -107,7 +107,7 @@ function toPosixRelativePath(input: string): string { return input.replaceAll("\\", "/"); } -export const make = Effect.gen(function* () { +const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts deleted file mode 100644 index f9526112af3fd..0000000000000 --- a/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts +++ /dev/null @@ -1,114 +0,0 @@ -import * as NodeModule from "node:module"; -import type { Result } from "@ff-labs/fff-node"; -import * as NodeServices from "@effect/platform-node/NodeServices"; -import { expect, it } from "@effect/vitest"; -import * as Effect from "effect/Effect"; -import * as FileSystem from "effect/FileSystem"; -import * as Path from "effect/Path"; - -const requireForFff = NodeModule.createRequire(import.meta.url); -const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node"); - -function valueOf(result: Result): T { - if (!result.ok) throw new Error(result.error); - return result.value; -} - -it.effect("decodes native search and grep strings and keeps scores only through 200 results", () => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const basePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-fff-native-" }); - const names = [ - ...Array.from({ length: 205 }, (_, index) => `file-${String(index).padStart(3, "0")}`), - "日本語", - "café", - "emoji-🦊", - ]; - const relativePaths = names.map((name) => `${name}/${name}.ts`); - const content = "prefix marker-日本語🦊\n"; - yield* Effect.forEach( - names, - (name) => - Effect.gen(function* () { - yield* fileSystem.makeDirectory(path.join(basePath, name)); - yield* fileSystem.writeFileString(path.join(basePath, name, `${name}.ts`), content); - }), - { concurrency: "unbounded" }, - ); - expect(requireForFff.resolve("@ff-labs/fff-node").replaceAll("\\", "/")).toMatch( - /\/dist\/index\.js$/u, - ); - const finder = yield* Effect.acquireRelease( - Effect.sync(() => - valueOf(FileFinder.create({ basePath, disableWatch: true, disableMmapCache: true })), - ), - (finder) => Effect.sync(() => finder.destroy()), - ); - expect(valueOf(yield* Effect.promise(() => finder.waitForIndexReady(10_000)))).toBe(true); - - const files200 = valueOf(finder.fileSearch("", { pageSize: 200 })); - const files201 = valueOf(finder.fileSearch("", { pageSize: 201 })); - expect(files200.items).toHaveLength(200); - expect(files200.scores).toHaveLength(200); - expect(files201.items).toHaveLength(201); - expect(files201.scores).toEqual([]); - expect(files201.items.slice(0, 200)).toEqual(files200.items); - const files = valueOf(finder.fileSearch("", { pageSize: 1000 })); - expect(files.items.map((item) => item.relativePath.normalize("NFC")).toSorted()).toEqual( - relativePaths.toSorted(), - ); - for (const item of files.items) { - expect(item.fileName.normalize("NFC")).toBe( - path.basename(item.relativePath).normalize("NFC"), - ); - expect(item.size).toBe(Buffer.byteLength(content)); - expect(Number.isFinite(item.modified)).toBe(true); - } - const exact = valueOf(finder.fileSearch("日本語.ts", { pageSize: 1 })); - expect(exact.items[0]?.fileName.normalize("NFC")).toBe("日本語.ts"); - expect(exact.scores[0]).toMatchObject({ exactMatch: true, matchType: "exact_filename" }); - - const dirs200 = valueOf(finder.directorySearch("", { pageSize: 200 })); - const dirs201 = valueOf(finder.directorySearch("", { pageSize: 201 })); - expect(dirs200.scores).toHaveLength(200); - expect(dirs201.items).toHaveLength(201); - expect(dirs201.scores).toEqual([]); - expect(dirs201.items.slice(0, 200)).toEqual(dirs200.items); - const directories = valueOf(finder.directorySearch("", { pageSize: 1000 })); - expect( - directories.items - .map((item) => item.relativePath.normalize("NFC")) - .filter(Boolean) - .toSorted(), - ).toEqual(names.map((name) => `${name}/`).toSorted()); - - const mixed200 = valueOf(finder.mixedSearch("", { pageSize: 200 })); - const mixed201 = valueOf(finder.mixedSearch("", { pageSize: 201 })); - expect(mixed200.scores).toHaveLength(200); - expect(mixed201.items).toHaveLength(201); - expect(mixed201.scores).toEqual([]); - expect(mixed201.items.slice(0, 200)).toEqual(mixed200.items); - const mixed = valueOf(finder.mixedSearch("", { pageSize: 1000 })); - expect(mixed.items.filter((item) => item.type === "file").map(({ item }) => item)).toEqual( - files.items, - ); - expect(mixed.items.filter((item) => item.type === "directory").map(({ item }) => item)).toEqual( - directories.items, - ); - - const grep = valueOf(finder.grep("marker", { mode: "plain", pageSize: 1000 })); - expect(grep.items.map((item) => item.relativePath.normalize("NFC")).toSorted()).toEqual( - relativePaths.toSorted(), - ); - for (const item of grep.items) { - expect(item.fileName.normalize("NFC")).toBe( - path.basename(item.relativePath).normalize("NFC"), - ); - expect(item.lineContent).toBe(content.trimEnd()); - expect(item.lineNumber).toBe(1); - expect(item.col).toBe(7); - expect(item.matchRanges).toEqual([[7, 13]]); - } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), -); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index 4a3e80e92ecc6..2c41e4ed0b3d0 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -6,9 +6,7 @@ import { type GrepResult, } from "@ff-labs/fff-node"; import { afterEach, expect, it } from "@effect/vitest"; -import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import { vi } from "vite-plus/test"; import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts"; @@ -65,279 +63,6 @@ it.effect("filters image searches before applying the result limit", () => ), ); -it.effect("preserves unexpected FileFinder creation failures", () => - Effect.gen(function* () { - const cause = new Error("native initialization failed"); - vi.spyOn(FileFinder, "create").mockImplementationOnce(() => { - throw cause; - }); - - const error = yield* Effect.flip( - Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")), - ); - - expect(error).toMatchObject({ - _tag: "WorkspaceSearchIndexCreateFailed", - cwd: "/workspace/project", - reason: "FileFinder.create threw unexpectedly.", - cause, - }); - }), -); - -it.effect("keeps returned FileFinder creation diagnostics out of the cause chain", () => - Effect.gen(function* () { - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ - ok: false, - error: "native index rejected the directory", - }); - - const error = yield* Effect.flip( - Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")), - ); - - expect(error).toMatchObject({ - _tag: "WorkspaceSearchIndexCreateFailed", - cwd: "/workspace/project", - reason: "native index rejected the directory", - }); - expect(error.cause).toBeUndefined(); - }), -); - -it.effect("waits for the full content index warmup before returning", () => - Effect.gen(function* () { - const waitForIndexReady = vi.fn(async () => ({ ok: true as const, value: true })); - const finder = { - destroy: vi.fn(), - waitForIndexReady, - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content")); - - expect(waitForIndexReady).toHaveBeenCalledWith(15_000); - }), -); - -it.effect("preserves a full-index warmup timeout as a structured error", () => - Effect.gen(function* () { - const finder = { - destroy: vi.fn(), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })), - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - const error = yield* Effect.flip( - Effect.scoped(WorkspaceSearchIndex.make("/workspace/project", "content")), - ); - - expect(error).toMatchObject({ - _tag: "WorkspaceSearchIndexScanTimedOut", - cwd: "/workspace/project", - timeout: "15 seconds", - }); - }), -); - -it.effect("returns partial path results when the initial scan times out", () => - Effect.scoped( - Effect.gen(function* () { - const mixedSearch = vi.fn(() => ({ - ok: true as const, - value: { - items: [ - { - type: "directory" as const, - item: { relativePath: "src", fileName: "src", fileCount: 1 }, - }, - { type: "file" as const, item: fileItem("src/index.ts") }, - ], - scores: [], - totalMatched: 2, - totalFiles: 1, - }, - })); - let scanning = true; - const finder = { - destroy: vi.fn(), - isScanning: vi.fn(() => scanning), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: false })), - mixedSearch, - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "paths"); - const list = yield* searchIndex.list(); - const search = yield* searchIndex.search("src", 10); - scanning = true; - mixedSearch.mockImplementationOnce(() => { - scanning = false; - return { - ok: true as const, - value: { - items: [ - { - type: "directory" as const, - item: { relativePath: "src", fileName: "src", fileCount: 1 }, - }, - { type: "file" as const, item: fileItem("src/index.ts") }, - ], - scores: [], - totalMatched: 2, - totalFiles: 1, - }, - }; - }); - const searchCompletingDuringQuery = yield* searchIndex.search("src", 10); - scanning = false; - const completedSearch = yield* searchIndex.search("src", 10); - - expect(list).toEqual({ - entries: [ - { kind: "directory", path: "src" }, - { kind: "file", path: "src/index.ts" }, - ], - truncated: true, - }); - expect(search.truncated).toBe(true); - expect(searchCompletingDuringQuery.truncated).toBe(true); - expect(completedSearch.truncated).toBe(false); - expect(mixedSearch).toHaveBeenCalledTimes(4); - }), - ), -); - -it.effect("preserves FileFinder destroy failures as structured defects", () => - Effect.gen(function* () { - const cause = new Error("native destroy failed"); - const finder = { - destroy: vi.fn(() => { - throw cause; - }), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - const exit = yield* Effect.scoped(WorkspaceSearchIndex.make("/workspace/project")).pipe( - Effect.exit, - ); - - expect(Exit.isFailure(exit)).toBe(true); - if (Exit.isFailure(exit)) { - expect(Cause.hasDies(exit.cause)).toBe(true); - const error = Cause.squash(exit.cause); - expect(error).toBeInstanceOf(WorkspaceSearchIndex.WorkspaceSearchIndexDestroyFailed); - expect(error).toMatchObject({ - _tag: "WorkspaceSearchIndexDestroyFailed", - cwd: "/workspace/project", - cause, - }); - } - }), -); - -it.effect("preserves search and refresh failures with operation context", () => - Effect.scoped( - Effect.gen(function* () { - const searchCause = new Error("native search failed"); - const refreshCause = new Error("native scan failed"); - const contentSearchCause = new Error("native grep failed"); - const finder = { - destroy: vi.fn(), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - mixedSearch: vi.fn(() => { - throw searchCause; - }), - grep: vi.fn(() => { - throw contentSearchCause; - }), - scanFiles: vi.fn(() => { - throw refreshCause; - }), - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project"); - const query = "authorization: Bearer secret-token"; - const searchError = yield* Effect.flip(searchIndex.search(query, 3)); - const contentSearchError = yield* Effect.flip( - searchIndex.searchContents({ - query, - limit: 3, - caseSensitive: false, - wholeWord: false, - useRegex: false, - }), - ); - const refreshError = yield* Effect.flip(searchIndex.refresh()); - - expect(searchError).toMatchObject({ - _tag: "WorkspaceSearchIndexSearchFailed", - cwd: "/workspace/project", - queryLength: query.length, - pageSize: 4, - reason: "FileFinder.mixedSearch threw unexpectedly.", - cause: searchCause, - }); - expect(searchError).not.toHaveProperty("query"); - expect(searchError.message).not.toMatch(/Bearer|secret-token/); - expect(contentSearchError).toMatchObject({ - _tag: "WorkspaceSearchIndexSearchFailed", - cwd: "/workspace/project", - queryLength: query.length, - pageSize: 3, - reason: "FileFinder.grep threw unexpectedly.", - cause: contentSearchCause, - }); - expect(contentSearchError).not.toHaveProperty("query"); - expect(contentSearchError.message).not.toMatch(/Bearer|secret-token/); - expect(refreshError).toMatchObject({ - _tag: "WorkspaceSearchIndexRefreshFailed", - cwd: "/workspace/project", - reason: "FileFinder.scanFiles threw unexpectedly.", - cause: refreshCause, - }); - }), - ), -); - -it.effect("keeps returned search diagnostics out of the cause chain", () => - Effect.scoped( - Effect.gen(function* () { - const finder = { - destroy: vi.fn(), - waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - mixedSearch: vi.fn(() => ({ ok: false, error: "native query rejected" })), - scanFiles: vi.fn(() => ({ ok: false, error: "native refresh rejected" })), - } as unknown as FileFinder; - vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project"); - const query = "authorization: Bearer secret-token"; - const searchError = yield* Effect.flip(searchIndex.search(query, 3)); - const refreshError = yield* Effect.flip(searchIndex.refresh()); - - expect(searchError).toMatchObject({ - _tag: "WorkspaceSearchIndexSearchFailed", - cwd: "/workspace/project", - queryLength: query.length, - pageSize: 4, - reason: "native query rejected", - }); - expect(searchError).not.toHaveProperty("query"); - expect(searchError.message).not.toMatch(/Bearer|secret-token/); - expect(searchError.cause).toBeUndefined(); - expect(refreshError).toMatchObject({ - _tag: "WorkspaceSearchIndexRefreshFailed", - cwd: "/workspace/project", - reason: "native refresh rejected", - }); - expect(refreshError.cause).toBeUndefined(); - }), - ), -); - it.effect("continues whole-word searches after a filtered grep page", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 3ae5d524611a4..8f2b64cf26a34 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -27,10 +27,7 @@ import type { } from "@t3tools/contracts"; import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; -// fff-node stays external to the CLI bundle because it dlopens a native -// library. A static `import` of an external package is a hard error inside a -// Node single-executable (only built-ins resolve there), so load it through -// `require`, which reads from the real filesystem in every runtime. +// fff-node's native library stays external; single-executables require disk packages instead of importing them. const requireForFff = NodeModule.createRequire(import.meta.url); const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node"); @@ -257,11 +254,7 @@ function mapContentMatchRanges( })); } -/** - * Whole-word filtering happens after the grep rather than by wrapping the pattern in boundary - * regex: consuming boundaries such as `(?:^|\W)` swallow the separator between adjacent matches - * and widen the reported ranges, and `\b` cannot match punctuation-edged queries at all. - */ +// Post-filter whole words: consuming boundary regexes swallow adjacent separators and widen ranges; \b misses punctuation edges. function isWholeWordRange( line: string, range: { readonly start: number; readonly end: number }, @@ -303,9 +296,7 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* ( FileFinder.create({ basePath: cwd, disableMmapCache: true, - // Content indexing costs scan CPU and memory, so only the on-demand - // content-search index pays for it; path-only consumers (file tree, - // composer path search, file picker) keep the lightweight index. + // Content indexing costs CPU/memory; path-only consumers use the lightweight index. disableContentIndexing: variant !== "content", aiMode: false, enableFsRootScanning: true, @@ -490,8 +481,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( )(function* (input) { const { searchQuery, regexMode } = buildContentSearchQuery(input); const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS; - // Grep cursors advance by file, so whole-word post-filtering needs enough - // raw candidates from the current file before moving to the next one. + // Grep cursors advance per file; whole-word filtering needs enough raw candidates before advancing. const rawPageSize = input.wholeWord ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE) : input.limit; @@ -555,9 +545,7 @@ function parseWorkspaceSearchIndexKey(key: string): { }; } -/** - * @public Service construction is part of the canonical Effect module API. - */ +/** @public */ export const layer = (key: string) => { const { cwd, variant } = parseWorkspaceSearchIndexKey(key); return Layer.effect(WorkspaceSearchIndex, make(cwd, variant)); diff --git a/apps/server/src/workspace/fileHeaderMimeType.test.ts b/apps/server/src/workspace/fileHeaderMimeType.test.ts deleted file mode 100644 index 9fe13cfd01d74..0000000000000 --- a/apps/server/src/workspace/fileHeaderMimeType.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; -import { fileHeaderMimeType } from "./fileHeaderMimeType.ts"; - -describe("fileHeaderMimeType", () => { - it.each([ - [[0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], "image/png"], - [[0xff, 0xd8, 0xff], "image/jpeg"], - [[0x50, 0x4b, 0x03, 0x04], "application/zip"], - [[0x52, 0x49, 0x46, 0x46, 0xc2, 0xa0, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50], "image/webp"], - [[0x89, 0x50, 0x4e], undefined], - ])("classifies binary header %j", (header, expected) => { - expect(fileHeaderMimeType(new Uint8Array(header))).toBe(expected); - }); - - it.each([ - ["%PDF-1.7", "application/pdf"], - ["GIF89a", "image/gif"], - ["SQLite format 3\0", "application/vnd.sqlite3"], - ["RIFF1234WEBP", "image/webp"], - ["#!/usr/bin/env python3\n", "text/x-python"], - ["#!/usr/bin/node\n", "text/javascript"], - ["#!/bin/bash\n", "text/x-shellscript"], - ["#!/usr/bin/env ruby\n", "text/x-ruby"], - ["hello", undefined], - ["", undefined], - ["#!/usr/bin/env custom\n", undefined], - ])("classifies %j", (header, expected) => { - expect(fileHeaderMimeType(new TextEncoder().encode(header))).toBe(expected); - }); -}); diff --git a/apps/server/src/worktreesDirectory.ts b/apps/server/src/worktreesDirectory.ts index aef9b8c031c43..e8464eb077f9d 100644 --- a/apps/server/src/worktreesDirectory.ts +++ b/apps/server/src/worktreesDirectory.ts @@ -8,11 +8,7 @@ import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ServerConfig from "./config.ts"; import * as ServerSettings from "./serverSettings.ts"; -/** - * Null when the setting is not an absolute path on this machine, such as `D:\worktrees` - * configured for a Windows server and synced to a Linux one, or when it is a filesystem root, - * which would make every path on that drive look managed. - */ +/** Null for filesystem roots or settings not absolute on this host, including synced foreign-platform paths. */ export function resolveWorktreesDirectory( setting: string, defaultDir: string, @@ -48,19 +44,14 @@ export function managedWorktreesDirectories( return [...directories]; } -/** - * A thread's path and branch can come from a client, so a missing worktree is - * only recreated where the server would have put it: - * `//`, compared by real path. - */ +// Client paths/branches are untrusted; recreate only real paths matching managed-folder/repo/branch. export const makeIsManagedWorktreePath = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const serverConfig = yield* ServerConfig.ServerConfig; const serverSettings = yield* ServerSettings.ServerSettingsService; - // Where git would create `target`: the real path of its nearest existing - // ancestor plus the missing rest, since git follows symlinks on the way. + // Match Git's symlink-following location: nearest real ancestor plus missing path components. const realLocation = (target: string): Effect.Effect => fileSystem.realPath(target).pipe( Effect.catch(() => { @@ -74,8 +65,7 @@ export const makeIsManagedWorktreePath = Effect.gen(function* () { return Effect.fn("worktreesDirectory.isManagedWorktreePath")(function* (worktreePath: string) { // git resolves a relative path against the project, not the server cwd. if (!path.isAbsolute(worktreePath)) return false; - // Server-made paths are normalized. A `..` would be applied after git - // follows a symlink but before realPath does, so the two disagree. + // Require normalized paths; Git and realPath disagree on .. after symlink traversal. if (path.resolve(worktreePath) !== worktreePath) return false; const settings = yield* serverSettings.getSettings.pipe( Effect.orElseSucceed(() => ({ diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index a2a9656b3f3cc..ea18643a6881f 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,29 +1,102 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { - ORCHESTRATION_PROTOCOL_VERSION, + AuthSessionId, + EnvironmentId, ProjectId, ThreadId, + WS_METHODS, + WsSubscribeServerConfigRpc, type OrchestrationV2StoredEvent, + type OrchestrationV2ThreadShell, type OrchestrationProjectShell, type ServerConfig, type ServerConfigStreamEvent, } from "@t3tools/contracts"; -import * as HostProcess from "@t3tools/shared/HostProcess"; -import * as ConfigProvider from "effect/ConfigProvider"; import * as Deferred from "effect/Deferred"; -import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; -import * as Fiber from "effect/Fiber"; -import * as 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 Stream from "effect/Stream"; -import * as TestClock from "effect/testing/TestClock"; -import { ChildProcessSpawner } from "effect/process"; +import { Headers } from "effect/http"; +import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc"; import * as SqlClient from "effect/sql/SqlClient"; +import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; +import * as ServerBrowser from "./preview/ServerBrowser.ts"; +import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; +import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; +import * as AgentSessionImporter from "./project/AgentSessionImporter.ts"; +import * as AgentSessionScanner from "./project/AgentSessionScanner.ts"; +import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; +import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts"; +import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; +import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; +import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts"; +import * as CodexInstallation from "./provider/CodexInstallation.ts"; +import * as DeviceService from "./device/DeviceService.ts"; +import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; +import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; +import * as EnvironmentTheme from "./environmentTheme.ts"; +import * as GitWorkflowService from "./git/GitWorkflowService.ts"; +import * as HostResources from "./resourceTelemetry/HostResources.ts"; +import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; +import * as McpAppRequests from "./mcpApps/McpAppRequests.ts"; +import * as ModelManifest from "./provider/ModelManifest.ts"; +import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; +import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts"; +import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; +import * as PortScanner from "./preview/PortScanner.ts"; +import * as PreviewManager from "./preview/Manager.ts"; +import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; +import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; +import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts"; +import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; +import * as ProviderAuthService from "./provider/ProviderAuthService.ts"; +import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts"; +import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; +import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; +import * as ProviderRegistry from "./provider/ProviderRegistry.ts"; +import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; +import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts"; +import * as PullRequestService from "./pullRequest/PullRequestService.ts"; +import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; +import * as RelayClient from "@t3tools/shared/relayClient"; +import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; +import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts"; +import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; +import * as ReviewService from "./review/ReviewService.ts"; +import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; +import * as SecretRequests from "./secrets/SecretRequests.ts"; +import * as GuestShareService from "./guest/GuestShareService.ts"; +import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; +import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts"; +import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts"; +import * as ServerSelfUpdate from "./cloud/selfUpdate.ts"; +import * as SessionStore from "./auth/SessionStore.ts"; +import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts"; +import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts"; +import * as StorageCleanup from "./storageCleanup.ts"; +import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; +import * as TerminalManager from "./terminal/Manager.ts"; +import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; +import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; +import * as UsageLimitSources from "./usage/UsageLimitSources.ts"; +import * as UsageService from "./usage/UsageService.ts"; +import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts"; +import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts"; +import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; +import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; +import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts"; +import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts"; +import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; +import * as WorkspacePaths from "./workspace/WorkspacePaths.ts"; +import * as ServerSecretStore from "./auth/ServerSecretStore.ts"; +import * as ServerConfigModule from "./config.ts"; +import * as Keybindings from "./keybindings.ts"; +import * as ServerSettings from "./serverSettings.ts"; + import * as EventStore from "./orchestration-v2/EventStore.ts"; import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; @@ -35,51 +108,13 @@ import * as ExternalLauncher from "./process/externalLauncher.ts"; import * as ProjectEnrichment from "./project/ProjectEnrichmentService.ts"; import * as ProjectService from "./project/ProjectService.ts"; import { - hasCompatibleOrchestrationProtocol, - resolveAvailableEditorsForConfig, - shouldUseBoundedThreadSnapshot, + layerWsRpc, subscribeOrchestrationV2Shell, subscribeOrchestrationV2Thread, + WS_RPC_SERVER_OPTIONS, withLateEditorConfig, } from "./ws.ts"; -it("accepts only the current orchestration protocol before websocket RPC setup", () => { - assert.isTrue( - hasCompatibleOrchestrationProtocol( - new URL(`https://host.test/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}`), - ), - ); - assert.isFalse(hasCompatibleOrchestrationProtocol(new URL("https://host.test/ws"))); - assert.isFalse( - hasCompatibleOrchestrationProtocol( - new URL(`https://host.test/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION - 1}`), - ), - ); -}); - -it("keeps full thread snapshot fallback unless the client opts into bounded history", () => { - assert.isFalse(shouldUseBoundedThreadSnapshot({})); - assert.isFalse(shouldUseBoundedThreadSnapshot({ acceptBoundedSnapshot: false })); - assert.isTrue(shouldUseBoundedThreadSnapshot({ acceptBoundedSnapshot: true })); -}); - -it.effect("does not block server config when editor discovery never resolves", () => - Effect.gen(function* () { - const discoveryInterrupted = yield* Deferred.make(); - const responseFiber = yield* resolveAvailableEditorsForConfig( - Effect.never.pipe( - Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)), - ), - ).pipe(Effect.forkChild); - - yield* TestClock.adjust(Duration.seconds(5)); - - const availableEditors = yield* Fiber.join(responseFiber); - yield* Deferred.await(discoveryInterrupted); - assert.deepEqual(availableEditors, []); - }), -); - const snapshotConfig = (fields: Partial) => ({ availableEditors: [], settings: {}, ...fields }) as unknown as ServerConfig; @@ -119,21 +154,6 @@ it.effect("resends late editors without rolling back updates already sent", () = }), ); -it.effect("sends no late snapshot when the scan matches the snapshot", () => - Effect.gen(function* () { - const events = yield* withLateEditorConfig( - snapshotConfig({ availableEditors: ["vscode"] }), - Stream.empty, - { - resolveAvailableEditors: () => Effect.succeed(["vscode"]), - resolveFileManagerRevealKind: () => Effect.succeed(undefined), - }, - ).pipe(Stream.runCollect); - - assert.equal(events.length, 0); - }), -); - it.effect("resends a file manager reveal kind that missed the snapshot", () => Effect.gen(function* () { const events = yield* withLateEditorConfig( @@ -154,99 +174,6 @@ it.effect("resends a file manager reveal kind that missed the snapshot", () => }), ); -const makeParkedWindowsLauncher = Effect.gen(function* () { - const parkedProbes = yield* Queue.unbounded(); - const release = yield* Deferred.make(); - const launcher = yield* ExternalLauncher.make.pipe( - Effect.provide( - Layer.mergeAll( - FileSystem.layerNoop({ - stat: () => - Queue.offer(parkedProbes, undefined).pipe( - Effect.andThen(Deferred.await(release)), - Effect.as({ type: "File" } as FileSystem.File.Info), - ), - }), - Path.layer, - Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected spawn")), - ), - ), - ), - ); - const onWindows = (effect: Effect.Effect) => - effect.pipe( - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provide( - ConfigProvider.layer( - ConfigProvider.fromEnv({ - env: { PATH: "C:\\t3-late-editors-test", PATHEXT: ".EXE" }, - }), - ), - ), - ); - return { - editors: { - resolveAvailableEditors: () => onWindows(launcher.resolveAvailableEditors()), - resolveFileManagerRevealKind: () => onWindows(launcher.resolveFileManagerRevealKind()), - }, - probeParked: Queue.take(parkedProbes), - releaseProbes: Deferred.succeed(release, undefined), - }; -}); - -it.effect("recovers editors after a real scan outlasts the config timeout", () => - Effect.gen(function* () { - const { editors, probeParked, releaseProbes } = yield* makeParkedWindowsLauncher; - - const snapshotFiber = yield* resolveAvailableEditorsForConfig( - editors.resolveAvailableEditors(), - ).pipe(Effect.forkChild); - yield* probeParked; - yield* TestClock.adjust(Duration.seconds(5)); - const snapshotEditors = yield* Fiber.join(snapshotFiber); - assert.deepEqual(snapshotEditors, []); - - const lateFiber = yield* withLateEditorConfig( - snapshotConfig({ availableEditors: snapshotEditors }), - Stream.empty, - editors, - ).pipe(Stream.runCollect, Effect.forkChild); - yield* releaseProbes; - - const [late] = Array.from(yield* Fiber.join(lateFiber)); - assert.equal(late?.type, "snapshot"); - if (late?.type === "snapshot") { - assert.equal(late.config.availableEditors.includes("vscode"), true); - } - }).pipe(Effect.scoped), -); - -it.effect("recovers a reveal kind whose real probe outlasts the config timeout", () => - Effect.gen(function* () { - const { editors, probeParked, releaseProbes } = yield* makeParkedWindowsLauncher; - - const lateFiber = yield* withLateEditorConfig( - snapshotConfig({ availableEditors: ["file-manager"] }), - Stream.empty, - { - resolveAvailableEditors: () => Effect.succeed(["file-manager"]), - resolveFileManagerRevealKind: editors.resolveFileManagerRevealKind, - }, - ).pipe(Stream.runCollect, Effect.forkChild); - yield* probeParked; - yield* TestClock.adjust(Duration.seconds(6)); - yield* releaseProbes; - - const [late] = Array.from(yield* Fiber.join(lateFiber)); - assert.equal(late?.type, "snapshot"); - if (late?.type === "snapshot") { - assert.equal(late.config.shellRevealInFileManagerKind, "file-explorer"); - } - }).pipe(Effect.scoped), -); - const ReplayTestLayer = OrchestrationEventStore.layer.pipe( Layer.provideMerge(SqlitePersistence.layerMemory), ); @@ -327,6 +254,8 @@ it.live.each(["thread", "shell"] as const)( 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"] @@ -363,6 +292,318 @@ it.live.each(["thread", "shell"] as const)( }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); +it.effect("shell snapshots leave idle subagent children out only for clients that ask", () => + Effect.gen(function* () { + const shell = (id: string, parent: string | null, activityRunStatus: "running" | null) => + ({ + id: ThreadId.make(id), + archivedAt: null, + status: activityRunStatus ?? "completed", + activityRunStatus, + pendingRuntimeRequest: null, + pendingBackgroundTasks: [], + lineage: { + parentThreadId: parent === null ? null : ThreadId.make(parent), + relationshipToParent: parent === null ? null : "subagent", + rootThreadId: ThreadId.make("parent"), + }, + }) as unknown as OrchestrationV2ThreadShell; + const threads = [ + shell("parent", null, null), + shell("idle", "parent", null), + shell("live", "parent", "running"), + ]; + const firstSnapshotThreadIds = (input: { readonly omitIdleSubagents?: boolean }) => + subscribeOrchestrationV2Shell(input).pipe( + Effect.flatMap((stream) => stream.pipe(Stream.take(1), Stream.runCollect)), + Effect.map(([item]) => + item?.kind === "snapshot" ? item.snapshot.threads.map((thread) => thread.id) : [], + ), + Effect.provideService(ThreadManagement.ThreadManagementService, { + readShellSnapshot: () => + Effect.succeed( + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 0, + threads, + archivedThreads: [], + }), + ), + } 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.succeedNone, + } as unknown as ProjectService.ProjectService["Service"]), + Effect.provideServiceEffect( + ProjectEnrichment.ProjectEnrichmentService, + PubSub.unbounded().pipe( + Effect.map( + (changes) => + ({ + subscribeChanges: PubSub.subscribe(changes), + }) as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"], + ), + ), + ), + ); + + assert.deepEqual(yield* firstSnapshotThreadIds({}), ["parent", "idle", "live"]); + assert.deepEqual(yield* firstSnapshotThreadIds({ omitIdleSubagents: true }), [ + "parent", + "live", + ]); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + +// Build the production RPC layer; unrelated capabilities fail if this test calls them. +const layerUnusedConfigRpcServices = Layer.mergeAll( + Layer.mock(ServerSecretStore.ServerSecretStore)({}), + Layer.mock(WorkspacePaths.WorkspacePaths)({}), + Layer.mock(TraceDiagnostics.TraceDiagnostics)({}), + Layer.mock(ProjectFaviconResolver.ProjectFaviconResolver)({}), + Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}), + Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}), + Layer.mock(AcpRegistrySupport.AcpRegistryCatalog)({}), + Layer.mock(AgentSessionImporter.AgentSessionImporter)({}), + Layer.mock(AgentSessionScanner.AgentSessionScanner)({}), + Layer.mock(AnalyticsService.AnalyticsService)({}), + Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused" }), + Layer.mock(BackgroundPolicy.BackgroundPolicy)({}), + Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({}), + Layer.mock(CommandOutputHub.CommandOutputHub)({}), + Layer.mock(CodexInstallation.CodexInstallation)({ managedDirectory: "/unused" }), + Layer.mock(DeviceService.DeviceService)({}), + Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}), + Layer.mock(GitWorkflowService.GitWorkflowService)({}), + Layer.mock(HostResources.HostResources)({}), + Layer.mock(McpAppRequests.McpAppRequests)({}), + Layer.mock(ModelManifest.ModelManifest)({}), + Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}), + Layer.mock(Orchestrator.OrchestratorV2)({}), + Layer.mock(OtlpEndpointCheck.OtlpEndpointCheck)({}), + Layer.mock(PairingGrantStore.PairingGrantStore)({}), + Layer.mock(PortScanner.PortDiscovery)({}), + Layer.mock(PreviewManager.PreviewManager)({}), + Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({}), + Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({}), + Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}), + Layer.mock(ProjectStore.ProjectStoreV2)({}), + Layer.mock(ProviderAuthService.ProviderAuthService)({}), + Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({}), + Layer.mock(ProviderLatestVersions.ProviderLatestVersions)({}), + Layer.mock(ProviderMaintenanceRunner.ProviderMaintenanceRunner)({}), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}), + Layer.mock(PullRequestReviewGuideService.PullRequestReviewGuideService)({}), + Layer.mock(PullRequestService.PullRequestService)({}), + Layer.mock(PullRequestSyncReactor.PullRequestSyncReactor)({}), + Layer.mock(RelayClient.RelayClient)({}), + Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}), + Layer.mock(ResourceTelemetry.ResourceTelemetry)({}), + Layer.mock(ReviewService.ReviewService)({}), + Layer.mock(ScheduledTasks.ScheduledTaskService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(GuestShareService.GuestShareService)({}), + Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}), + Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}), + Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}), + Layer.mock(SessionStore.SessionStore)({ cookieName: "config-test", legacyCookieName: undefined }), + Layer.mock(SourceControlDiscovery.SourceControlDiscovery)({}), + Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}), + Layer.mock(StorageCleanup.StorageCleanup)({}), + Layer.mock(DatabaseStorage.DatabaseStorage)({}), + Layer.mock(TerminalManager.TerminalManager)({}), + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}), + Layer.mock(ThreadManagement.ThreadManagementService)({}), + Layer.mock(ThreadSearch.ThreadSearch)({}), + Layer.mock(UsageService.UsageService)({}), + Layer.mock(VcsProvisioningService.VcsProvisioningService)({}), + Layer.mock(VcsStatusBroadcaster.VcsStatusBroadcaster)({}), + Layer.mock(WorkspaceEntries.WorkspaceEntries)({}), + Layer.mock(WorkspaceFileSystem.WorkspaceFileSystem)({}), + Layer.mock(WorktreeSetupTracker.WorktreeSetupTracker)({}), +); + +const layerConfigSources = Layer.mergeAll( + Keybindings.layer, + ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer)), +).pipe( + Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)), + Layer.provideMerge( + Layer.fresh( + ServerConfigModule.layerTest(process.cwd(), { prefix: "t3-config-subscription-test-" }), + ), + ), + Layer.provideMerge(NodeServices.layer), +); + +it.effect( + "preserves settings during discovery and keybindings during snapshot ACK at the config RPC boundary", + () => + Effect.gen(function* () { + const keybindings = yield* Keybindings.Keybindings; + const settings = yield* ServerSettings.ServerSettingsService; + const keybindingsSubscribed = yield* Deferred.make(); + const settingsSubscribed = yield* Deferred.make(); + const keybindingsChanges = keybindings.subscribeChanges.pipe( + Effect.tap(() => Deferred.succeed(keybindingsSubscribed, undefined)), + ); + const settingsChanges = settings.subscribeChanges.pipe( + Effect.tap(() => Deferred.succeed(settingsSubscribed, undefined)), + ); + const initialKeybindings = (yield* keybindings.getSnapshot).keybindings; + const discoveryStarted = yield* Deferred.make(); + const finishDiscovery = yield* Deferred.make(); + const responses = yield* Queue.unbounded(); + const configRpcServices = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ExternalLauncher.ExternalLauncher)({ + resolveAvailableEditors: () => + Deferred.succeed(discoveryStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishDiscovery)), + Effect.as([]), + ), + resolveFileManagerRevealKind: () => Effect.succeed(undefined), + }), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + streamChanges: Stream.never, + }), + Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({ + resolveTargets: () => Effect.succeed([]), + }), + Layer.mock(DirectEndpoints.DirectEndpoints)({ resolve: () => Effect.succeed([]) }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + scratchRoot: Effect.succeedNone, + namedProjectsRoot: process.cwd(), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("config-test"), + label: "Config test", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0", + capabilities: { repositoryIdentity: false }, + }), + }), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + getDescriptor: () => + Effect.succeed({ + policy: "loopback-browser", + bootstrapMethods: [], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "config-test-session", + }), + }), + // Signal subscription on either accessor so the test also fails, rather + // than hangs, against a handler that subscribes after the snapshot. + Layer.succeed(Keybindings.Keybindings, { + ...keybindings, + streamChanges: Stream.unwrap(keybindingsChanges), + subscribeChanges: keybindingsChanges, + }), + Layer.succeed(ServerSettings.ServerSettingsService, { + ...settings, + streamChanges: Stream.unwrap(settingsChanges), + subscribeChanges: settingsChanges, + }), + ); + const server = yield* RpcServer.makeNoSerialization( + RpcGroup.make(WsSubscribeServerConfigRpc), + { + ...WS_RPC_SERVER_OPTIONS, + onFromServer: (response) => + response._tag === "Chunk" + ? Effect.forEach(response.values, (event) => Queue.offer(responses, event), { + discard: true, + }) + : Effect.void, + }, + ).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("config-test"), + subject: "config-test", + method: "browser-session-cookie", + scopes: [], + }, + {}, + {}, + yield* PreviewAutomationBroker.PreviewAutomationBroker, + yield* ServerBrowser.ServerBrowser, + ).pipe(Layer.provide(configRpcServices)), + ), + ); + const requestId = RpcMessage.RequestId("config"); + const acknowledge = server.write(0, { _tag: "Ack", requestId }); + yield* server.write(0, { + _tag: "Request", + id: requestId, + tag: WS_METHODS.subscribeServerConfig, + payload: {}, + headers: Headers.empty, + }); + yield* Deferred.await(discoveryStarted); + + const duringDiscovery = yield* settings.updateSettings({ defaultAutoPull: true }); + yield* Deferred.succeed(finishDiscovery, undefined); + const snapshot = yield* Queue.take(responses); + assert.equal(snapshot.type, "snapshot"); + if (snapshot.type !== "snapshot") return yield* Effect.die("Missing initial snapshot"); + assert.isFalse(snapshot.config.settings.defaultAutoPull); + assert.deepEqual(snapshot.config.keybindings, initialKeybindings); + const duringAck = yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+y", + command: "terminal.toggle", + }); + yield* acknowledge; + yield* Deferred.await(keybindingsSubscribed); + yield* Deferred.await(settingsSubscribed); + + // Later updates expose a dropped buffered event as a value mismatch, not a timeout. + const latestSettings = yield* settings.updateSettings({ enableProviderUpdateChecks: false }); + const latestKeybindings = yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+z", + command: "terminal.split", + }); + const expectedSettings = [duringDiscovery, latestSettings].map( + ServerSettings.redactServerSettingsForClient, + ); + const expectedKeybindings = [duringAck, latestKeybindings]; + // The two sources can interleave, but each must retain its own publication order. + for (let i = 0; i < 4; i++) { + const event = yield* Queue.take(responses); + if (event.type === "settingsUpdated") { + assert.deepEqual(event.payload.settings, expectedSettings.shift()); + } else { + assert.equal(event.type, "keybindingsUpdated"); + if (event.type !== "keybindingsUpdated") + return yield* Effect.die("Unexpected config event"); + assert.deepEqual(event.payload.keybindings, expectedKeybindings.shift()); + assert.deepEqual(event.payload.issues, []); + } + yield* acknowledge; + } + assert.isEmpty(expectedSettings); + assert.isEmpty(expectedKeybindings); + yield* server.write(0, { _tag: "Interrupt", requestId, interruptors: [] }); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.fresh(layerConfigSources), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), + ), + ), + Effect.scoped, + ), +); + // Compaction keeps the oldest and newest event per message, so a cursor older // than the deleted rows still replays each message where the client would // first have seen it (reducers append on first sight) and reaches the same @@ -413,7 +654,6 @@ it.effect("thread resume across compacted history keeps message order and final ) `; } - // Only the event between a's first and newest is deleted. assert.equal((yield* maintenance.compactEventStore).deletedEventCount, 1); const items = yield* subscribeOrchestrationV2Thread({ diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 7e9181cb72230..54bcf9d4409d3 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,4 +1,5 @@ import { OrchestrationDispatchCommandError } from "@t3tools/contracts"; +import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; @@ -21,7 +22,6 @@ import { rpcInitialItems } from "./rpcInitialItems.ts"; import { subscribeChatGptHandoff } from "./provider/CodexChatGptHandoff.ts"; import { subscribeCodexAuthCallback } from "./provider/CodexAuthCallback.ts"; import { - DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL, AcpRegistryOperationError, CommandId, authScopeResponse, @@ -63,6 +63,8 @@ import { OrchestrationV2ThreadLaunchError, type OrchestrationProjectShell, type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadStreamItem, + type ApplicationStoredEvent, type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, @@ -77,8 +79,6 @@ import { ProviderSetupError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, - type ServerSelfUpdateError, - type ServerSelfUpdateProgressEvent, type ServerConfig as ClientServerConfig, type ServerConfigStreamEvent, type ServerLifecycleStreamEvent, @@ -86,6 +86,7 @@ import { FilesystemBrowseError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, + SOURCE_CONTROL_MEDIA_ASSET, ChatAttachmentId, PersistChatAttachmentsError, RpcClientId, @@ -94,22 +95,18 @@ import { type ProviderDriverKind, type ProviderInstanceId, ThreadId, - type TerminalAttachStreamEvent, - type TerminalError, - type TerminalEvent, type TerminalMetadataStreamEvent, type PullRequestRef, WS_METHODS, WsRpcGroup, } from "@t3tools/contracts"; -import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { HttpRouter, HttpServerRequest, HttpServerRespondable, HttpServerResponse, } from "effect/http"; -import { RpcSerialization, RpcServer } from "effect/rpc"; +import { RpcGroup, RpcSerialization, RpcServer } from "effect/rpc"; import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts"; import * as ServerConfig from "./config.ts"; @@ -125,18 +122,22 @@ import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts" import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts"; import * as SecretRequests from "./secrets/SecretRequests.ts"; +import * as GuestShareService from "./guest/GuestShareService.ts"; import { archivedShellStreamItemFromThreadShell, buildActiveShellSnapshot, + bufferShellLiveStream, coalesceShellApplicationEvents, coalesceStoredThreadEvents, composeShellStreamWithEnrichment, dedupeShellEnrichment, + activeShellRowsForSubscriber, loadShellSnapshotParts, shellStreamItemFromEnrichmentRefresh, shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, shellStreamItemsFromResumeSnapshot, + shouldPublishShellApplicationEvent, skipUnchangedThreadShells, toShellApplicationEvent, type ShellApplicationEvent, @@ -157,9 +158,11 @@ import { THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, } from "./orchestration-v2/threadHistoryPaging.ts"; import { + makeLiveBodyDeduper, projectDomainEventForWire, projectThreadProjectionForWire, } from "./orchestration-v2/WireProjection.ts"; +import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; @@ -170,6 +173,7 @@ import * as AcpRegistrySupport from "@t3tools/provider-acp-registry/server/AcpRe import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; import * as ModelManifest from "./provider/ModelManifest.ts"; import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions"; +import { latestProviderVersionCacheKeys } from "@t3tools/provider-core/server/maintenanceResolver"; import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner.ts"; import * as ProviderAuthService from "./provider/ProviderAuthService.ts"; import { makeProviderInstallation } from "./provider/providerInstallation.ts"; @@ -180,7 +184,7 @@ import * as ServerSettings from "./serverSettings.ts"; import * as DatabaseStorage from "./persistence/DatabaseStorage.ts"; import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; -import { withTerminalOutputWindow } from "./terminal/OutputProtocol.ts"; +import { terminalOutputStream, withTerminalOutputWindow } from "./terminal/OutputProtocol.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; @@ -194,6 +198,7 @@ import { } from "./attachmentStore.ts"; import { parseBase64DataUrl } from "./imageMime.ts"; import { deletePendingAttachment, issueAttachmentUploadUrl } from "./assets/AttachmentUpload.ts"; +import { issueSpeechToTextUploadUrl } from "./speechToText/SpeechToTextRoute.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as KnownWorkspaces from "./workspace/KnownWorkspaces.ts"; @@ -208,6 +213,7 @@ import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts"; import * as ReviewService from "./review/ReviewService.ts"; import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts"; import * as ProjectService from "./project/ProjectService.ts"; +import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import { projectMutationOperation } from "./project/ProjectMutation.ts"; import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts"; @@ -218,6 +224,7 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts"; import * as DirectEndpoints from "./environment/DirectEndpoints.ts"; import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts"; import * as DefectReporter from "./observability/DefectReporter.ts"; +import * as EventLoopMonitor from "./observability/EventLoopMonitor.ts"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import { requiredScopeForDeviceList, rpcAuthorizationError } from "./auth/RpcAuthorization.ts"; @@ -228,6 +235,8 @@ import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; +import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts"; +import type { TelemetryOwner } from "./telemetry/Identify.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; @@ -247,7 +256,9 @@ import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; +import { isNetworkPath } from "@t3tools/shared/path"; import * as RelayClient from "@t3tools/shared/relayClient"; +import { isTelemetryIdHash } from "@t3tools/shared/telemetryId"; import { sameUsageLimitCommandCoverage, withUsageLimitsCommands, @@ -268,7 +279,7 @@ const resolveDiscoveryForConfig = ( Effect.map(Option.getOrElse(onTimeout)), ); -export const resolveAvailableEditorsForConfig = ( +const resolveAvailableEditorsForConfig = ( discovery: Effect.Effect, E, R>, ) => resolveDiscoveryForConfig(discovery, () => []); @@ -281,24 +292,23 @@ type EditorDiscovery = Pick< "resolveAvailableEditors" | "resolveFileManagerRevealKind" >; -const resolveEditorConfig = ( +const resolveEditorConfig = Effect.fn("ws.resolveEditorConfig")(function* ( availableEditors: ReadonlyArray, revealKind: Effect.Effect, -) => - Effect.gen(function* () { - const fileManagerRevealKind = availableEditors.includes("file-manager") - ? yield* revealKind - : undefined; - return { - availableEditors, - ...(fileManagerRevealKind === undefined - ? {} - : { - shellRevealInFileManager: true, - shellRevealInFileManagerKind: fileManagerRevealKind, - }), - }; - }); +) { + const fileManagerRevealKind = availableEditors.includes("file-manager") + ? yield* revealKind + : undefined; + return { + availableEditors, + ...(fileManagerRevealKind === undefined + ? {} + : { + shellRevealInFileManager: true, + shellRevealInFileManagerKind: fileManagerRevealKind, + }), + }; +}); export const withLateEditorConfig = ( config: ClientServerConfig, @@ -311,8 +321,7 @@ export const withLateEditorConfig = ( editors.join() !== config.availableEditors.join() || (editors.includes("file-manager") && config.shellRevealInFileManagerKind === undefined), ), - // Unbounded, unlike the snapshot: the reveal-kind probe is not shared, so - // a timeout here would cancel a probe that outlasts it every time. + // Leave the unshared reveal probe unbounded so timeouts cannot cancel every attempt on slow hosts. Stream.mapEffect((editors) => resolveEditorConfig(editors, launcher.resolveFileManagerRevealKind()), ), @@ -345,8 +354,7 @@ export const withLateEditorConfig = ( return [{ ...current, providers: event.payload.providers }, [event]]; case "settingsUpdated": return [{ ...current, settings: event.payload.settings }, [event]]; - // Themes and usage-limit sources never ride in a snapshot; clients - // carry their projected values across one. + // Themes and usage-limit sources survive snapshots because snapshots never include them. default: return [current, [event]]; } @@ -545,12 +553,28 @@ const PROVIDER_STATUS_DEBOUNCE_MS = 200; // Middleware added later wraps middleware added earlier, so instrumentation wraps authorization. const ServerWsRpcGroup = WsRpcGroup.middleware(RpcInstrumentation); + +// RpcGroup.toLayer derives each handler's requirements by scanning every RPC in +// the group, so its type cost grows with handlers × RPCs. Near 200 methods that +// crosses TypeScript's instantiation limit and the layer's requirements degrade to +// `any`, so the handlers are registered as two disjoint, smaller groups. +type ServerWsRpc = RpcGroup.Rpcs; +const SPLIT_WS_RPC_PREFIXES = ["server", "pullRequests", "provider", "orchestration"] as const; +type SplitWsRpc = Extract< + ServerWsRpc, + { readonly _tag: `${(typeof SPLIT_WS_RPC_PREFIXES)[number]}.${string}` } +>; +const isSplitWsRpc = (rpc: ServerWsRpc): rpc is SplitWsRpc => + SPLIT_WS_RPC_PREFIXES.some((prefix) => rpc._tag.startsWith(`${prefix}.`)); +const isOtherWsRpc = (rpc: ServerWsRpc): rpc is Exclude => + !isSplitWsRpc(rpc); +const serverWsRpcs = Array.from(ServerWsRpcGroup.requests.values()); +const SplitWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isSplitWsRpc)); +const OtherWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isOtherWsRpc)); // Replaying each intervening event costs a shell refetch; past this gap a // single O(active-threads) snapshot is cheaper and bounded. const SHELL_RESUME_MAX_GAP = 1_000; -// Row count alone does not bound replay memory: a few events with large tool -// payloads can decode to gigabytes. Before replaying, sum the serialized -// payload bytes of the range in SQL and reset with a snapshot past this budget. +// Row counts do not bound large tool payloads; sum stored JSON bytes in SQL and snapshot above budget. const ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024; function toAuthAccessStreamEvent( @@ -603,14 +627,14 @@ const MAX_CLIENT_APP_VERSION_LENGTH = 64; const MAX_CLIENT_BROWSER_LENGTH = 64; const MAX_CLIENT_DEVICE_MODEL_LENGTH = 80; -export function hasCompatibleOrchestrationProtocol(url: URL): boolean { +function hasCompatibleOrchestrationProtocol(url: URL): boolean { return ( url.searchParams.get(ORCHESTRATION_PROTOCOL_QUERY_PARAM) === String(ORCHESTRATION_PROTOCOL_VERSION) ); } -export function shouldUseBoundedThreadSnapshot(input: { +function shouldUseBoundedThreadSnapshot(input: { readonly acceptBoundedSnapshot?: boolean; }): boolean { return input.acceptBoundedSnapshot === true; @@ -633,8 +657,7 @@ function readClientConnectionOrigin( }; } -// Client telemetry stays in this socket's RPC layer. It must not become a -// server-global "current client" because several client types can connect at once. +// Keep telemetry per socket; several client types can connect simultaneously. function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest) { const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { @@ -679,6 +702,28 @@ function readClientAnalyticsProps(request: HttpServerRequest.HttpServerRequest) }; } +/** + * Owners a connecting client reports: its hashed T3 Connect account and its + * hashed device id. Only hashes are accepted, so a raw id never reaches analytics. + */ +function readClientOwners( + request: HttpServerRequest.HttpServerRequest, +): ReadonlyArray { + const url = HttpServerRequest.toURL(request); + if (Option.isNone(url)) { + return []; + } + const params = url.value.searchParams; + return ( + [ + ["connect", params.get("clientOwner")], + ["device", params.get("clientDevice")], + ] as const + ).flatMap(([source, ownerId]) => + ownerId !== null && isTelemetryIdHash(ownerId) ? [{ source, ownerId }] : [], + ); +} + const canReplayPersistedRange = Effect.fnUntraced(function* ( afterSequence: number, headSequence: number, @@ -742,8 +787,14 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs readonly requestCompletionMarker?: boolean; readonly acceptBoundedSnapshot?: boolean; readonly acceptCompactTurnItems?: boolean; + readonly acceptDedupedBodies?: boolean; + readonly acceptCompactIds?: boolean; }) { const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const dedupeBodies = input.acceptDedupedBodies === true; + // Replay, snapshot, and live tail share one deduper: it must see every delivered record. + const withLiveDedupe = (stream: Stream.Stream) => + dedupeBodies ? Stream.suspend(() => Stream.map(stream, makeLiveBodyDeduper())) : stream; const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; yield* Effect.annotateCurrentSpan({ @@ -790,9 +841,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs afterSequence, throughSequence, limit: THREAD_RESUME_MAX_REPLAY_EVENTS + 1, - // A row a newer build wrote (e.g. after a downgrade) must not fail - // every resubscribe. The live tail resumes from `highWater`, so a - // dropped row never hides later events. + // Downgrades can leave unknown rows; skip them and resume live from highWater so later events survive. skipUnknownEventTypes: true, }) .pipe( @@ -842,21 +891,26 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs ? buildBoundedThreadStreamSnapshot({ ...snapshot, compactTurnItems: input.acceptCompactTurnItems === true, + dedupeBodies, + compactIds: input.acceptCompactIds === true, }) - : { - kind: "snapshot" as const, - snapshotSequence, - projection: projectThreadProjectionForWire(snapshot.projection), - }; - return Stream.concat( - Stream.concat(rpcInitialItems([snapshotItem]), completionMarker), - eventStreamFrom(snapshotSequence), + : (() => { + const projection = projectThreadProjectionForWire(snapshot.projection); + return { + kind: "snapshot" as const, + snapshotSequence, + projection: dedupeBodies ? dedupeSnapshotBodies(projection) : projection, + }; + })(); + return withLiveDedupe( + Stream.concat( + Stream.concat(rpcInitialItems([snapshotItem]), completionMarker), + eventStreamFrom(snapshotSequence), + ), ); }); - // The event sink subscribes to live events before reading the persisted - // tail, so no event published during the replay window is lost; overlapping - // events are deduped by sequence on the client. + // Subscribe before reading persisted events to retain concurrent publishes; clients dedupe overlap by sequence. if (input.afterSequence !== undefined) { const highWater = yield* applicationEvents.latestAgentSequence(input.threadId).pipe( Effect.mapError( @@ -888,8 +942,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs }), ), ); - // Bound stored JSON before decoding, then check projected event - // size separately. Neither byte count is a bound on process memory. + // Bound stored and projected payload bytes separately; neither bounds process memory. if ( stats.eventCount > THREAD_RESUME_MAX_REPLAY_EVENTS || !isThreadReplayRawPayloadSafe(stats.rawPayloadBytes) @@ -907,8 +960,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs }), ), ); - // A retained creation can belong to a thread already deleted. - // Only replace its bounded replay when a snapshot can exist. + // Retained creation events may describe deleted threads; replace replay only if a snapshot exists. if (shell !== null) return yield* snapshotThenLive(); } const replay = yield* loadReplayThrough(input.afterSequence, highWater); @@ -921,9 +973,11 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs if (plan.mode === "snapshot") { return yield* snapshotThenLive(); } - return Stream.concat( - Stream.concat(rpcInitialItems(replay), completionMarker), - eventStreamFrom(highWater), + return withLiveDedupe( + Stream.concat( + Stream.concat(rpcInitialItems(replay), completionMarker), + eventStreamFrom(highWater), + ), ); } @@ -935,6 +989,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc function* (input: { readonly afterSequence?: number; readonly requestCompletionMarker?: boolean; + readonly omitIdleSubagents?: boolean; }) { const sql = yield* SqlClient.SqlClient; const threadManagement = yield* ThreadManagementService.ThreadManagementService; @@ -942,6 +997,9 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc const projects = yield* ProjectStore.ProjectStoreV2; const projectService = yield* ProjectService.ProjectService; const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; + let subagentThreadIds = new Set(); + const filterSubagentTranscript = (stored: ApplicationStoredEvent) => + shouldPublishShellApplicationEvent(stored, subagentThreadIds); const enrichmentChanges = yield* projectEnrichment.subscribeChanges; const loadProjectMetadataSnapshot = Effect.fn("ws.orchestrationV2.loadProjectMetadataSnapshot")( @@ -968,9 +1026,15 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc latestSequence: applicationEvents.latestApplicationSequence, }), ); + const rows = activeShellRowsForSubscriber(base.threads, input.omitIdleSubagents === true); + subagentThreadIds = rows.subagentThreadIds; const enriched = yield* enrichProjectShells(base.projects); return { - snapshot: { ...base, projects: enriched.projects } as OrchestrationV2ShellSnapshot, + snapshot: { + ...base, + threads: rows.threads, + projects: enriched.projects, + } as OrchestrationV2ShellSnapshot, resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots, }; }); @@ -1025,11 +1089,12 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc ); const liveFrom = (afterSequence: number) => - bufferLiveStream( + bufferShellLiveStream( toShellStream( applicationEvents.streamProjectedApplicationEvents({ afterSequence, project: toShellApplicationEvent, + filter: filterSubagentTranscript, }), ), ); @@ -1065,11 +1130,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc ), ); - // Always attach the enrichment subscription before the first load so - // completions that race HTTP snapshot fetch still push a refresh. We still - // emit one compact metadata refresh up front: getAvailable may have been - // cold on the HTTP path (null identity), and enrichment PubSub events - // published before this subscribe attached are dropped. + // Subscribe before loading for racing enrichments; initial refresh covers pre-subscription completions and cold HTTP snapshots. const completionMarker = input.requestCompletionMarker === true ? Stream.make({ kind: "synchronized" as const }) @@ -1094,9 +1155,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, }), ); - // Initial unmarked (+ optional same-load marked) always drains first. - // Enrichment merges only with the post-prefix tail so a ready marked - // refresh cannot interleave before the authoritative initial frame. + // Drain initial frames before merging enrichment with live events so marked refreshes cannot precede the initial frame. const completionThenLive = (afterSequence: number) => Stream.concat(completionMarker, liveFrom(afterSequence)); @@ -1120,16 +1179,20 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc }); } + subagentThreadIds = new Set(yield* threadManagement.listActiveSubagentThreadIds()); + const loaded = yield* loadProjectMetadataSnapshot(highWater); const replay = toShellStream( - applicationEvents.readApplicationEvents({ - afterSequence: input.afterSequence, - throughSequence: highWater, - // A row a newer build wrote (e.g. after a downgrade) must not fail - // every shell resubscribe. The live tail below resumes from - // highWater, so a dropped row never hides later events. - skipUnknownEventTypes: true, - }), + applicationEvents + .readApplicationEvents({ + afterSequence: input.afterSequence, + throughSequence: highWater, + // A row a newer build wrote (e.g. after a downgrade) must not fail + // every shell resubscribe. The live tail below resumes from + // highWater, so a dropped row never hides later events. + skipUnknownEventTypes: true, + }) + .pipe(Stream.filter(filterSubagentTranscript)), ); return composeShellStreamWithEnrichment({ initial: initialEnrichmentItems(loaded), @@ -1159,14 +1222,14 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc }, ); -const layerWsRpc = ( +export const layerWsRpc = ( currentSession: EnvironmentAuth.AuthenticatedSession, clientOrigin: OrchestrationClientOrigin, clientAnalyticsProps: Readonly>, previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], serverBrowser: ServerBrowser.ServerBrowser["Service"], ) => - ServerWsRpcGroup.toLayer( + Layer.effectContext( Effect.gen(function* () { const currentSessionId = currentSession.sessionId; const sql = yield* SqlClient.SqlClient; @@ -1182,6 +1245,7 @@ const layerWsRpc = ( const projectStore = yield* ProjectStore.ProjectStoreV2; const projectService = yield* ProjectService.ProjectService; const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders; + const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor; const threadSearch = yield* ThreadSearch.ThreadSearch; const providerSessionsV2 = yield* ProviderSessionManager.ProviderSessionManagerV2; @@ -1189,18 +1253,25 @@ const layerWsRpc = ( const analytics = yield* AnalyticsService.AnalyticsService; const originProps = clientAnalyticsProps; const recordClientCommandAnalytics = (command: OrchestrationV2Command) => { - switch (command.type) { - case "message.dispatch": - return analytics.record("client.turn.requested", originProps).pipe(Effect.ignore); - default: - return Effect.void; + if (command.type === "message.dispatch") { + return analytics.record("client.turn.requested", originProps).pipe(Effect.ignore); } + const usage = commandFeatureUsage(command); + return usage === undefined + ? Effect.void + : analytics + .record("feature.used", { + ...usage, + ...(originProps.surface === undefined ? {} : { surface: originProps.surface }), + }) + .pipe(Effect.ignore); }; const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const commandOutputHub = yield* CommandOutputHub.CommandOutputHub; const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2; const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; const secretRequests = yield* SecretRequests.SecretRequests; + const guestShares = yield* GuestShareService.GuestShareService; const pullRequests = yield* PullRequestService.PullRequestService; const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService; const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor; @@ -1230,6 +1301,7 @@ const layerWsRpc = ( const projectCloneTracker = yield* ProjectCloneTracker.ProjectCloneTracker; const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver; + const projectEnrichment = yield* ProjectEnrichmentService.ProjectEnrichmentService; const agentSessionScanner = yield* AgentSessionScanner.AgentSessionScanner; const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter; const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery; @@ -1284,16 +1356,6 @@ const layerWsRpc = ( const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery; const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck; - const automaticGitFetchInterval = serverSettings.getSettings.pipe( - Effect.map( - (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval, - ), - Effect.catch((cause) => - Effect.logWarning("Failed to read automatic Git fetch interval setting", { - detail: cause.message, - }).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)), - ), - ); const sourceControlRepositories = yield* SourceControlRepositoryService.SourceControlRepositoryService; const withPullRequestViewer = pullRequests.withRoutingCredential; @@ -1304,8 +1366,7 @@ const layerWsRpc = ( const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry; const relayClient = yield* RelayClient.RelayClient; - // A webhook URL starts agent runs, so only sessions that may operate - // see it; read-only sessions still see the task itself. + // Webhook URLs start agents; expose them only to operate-scoped sessions while keeping tasks readable. const withVisibleWebhookUrls = (result: ScheduledTaskListResult): ScheduledTaskListResult => currentSession.scopes.includes(AuthOrchestrationOperateScope) ? result @@ -1654,64 +1715,82 @@ const layerWsRpc = ( ), ); - const loadServerConfig = (options: { readonly usageLimitsCommand: boolean }) => - Effect.gen(function* () { - const keybindingsConfig = yield* keybindings.loadConfigState; - const currentProviders = yield* providerRegistry.getProviders; - const providers = options.usageLimitsCommand - ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current) - : currentProviders; - const settings = ServerSettings.redactServerSettingsForClient( - yield* serverSettings.getSettings, - ); - const environment = yield* serverEnvironment.getDescriptor; - const auth = yield* serverAuth.getDescriptor(); - const scratchWorkspaceRoot = yield* managedFolders.scratchRoot; - const editorConfig = yield* resolveEditorConfig( - yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()), - resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()), - ); + const loadServerConfig = Effect.fn("ws.loadServerConfig")(function* (options: { + readonly usageLimitsCommand: boolean; + }) { + const keybindingsConfig = yield* keybindings.loadConfigState; + const currentProviders = yield* providerRegistry.getProviders; + const providers = options.usageLimitsCommand + ? withUsageLimitsCommands(currentProviders, yield* usageLimitSources.current) + : currentProviders; + const settings = ServerSettings.redactServerSettingsForClient( + yield* serverSettings.getSettings, + ); + const environment = yield* serverEnvironment.getDescriptor; + const auth = yield* serverAuth.getDescriptor(); + const scratchWorkspaceRoot = yield* managedFolders.scratchRoot; + const lastEventLoopStall = yield* eventLoopMonitor.latestNoticeableStall; + const editorConfig = yield* resolveEditorConfig( + yield* resolveAvailableEditorsForConfig(externalLauncher.resolveAvailableEditors()), + resolveFileManagerRevealKindForConfig(externalLauncher.resolveFileManagerRevealKind()), + ); - return { - environment, - auth, - cwd: config.cwd, - keybindingsConfigPath: config.keybindingsConfigPath, - keybindings: keybindingsConfig.keybindings, - issues: keybindingsConfig.issues, - providers, - ...editorConfig, - remoteOpenTargets: yield* resolveAvailableEditorsForConfig( - remoteOpenTargets.resolveTargets(), - ), - directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()), - observability: { - logsDirectoryPath: config.logsDir, - localTracingEnabled: true, - ...(config.otlpTracesUrl !== undefined - ? { otlpTracesUrl: config.otlpTracesUrl } - : {}), - otlpTracesEnabled: config.otlpTracesUrl !== undefined, - ...(config.otlpMetricsUrl !== undefined - ? { otlpMetricsUrl: config.otlpMetricsUrl } - : {}), - otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, - ...(config.otlpLogsUrl !== undefined ? { otlpLogsUrl: config.otlpLogsUrl } : {}), - otlpLogsEnabled: config.otlpLogsUrl !== undefined, - }, - settings, - shellResumeCompletionMarker: true, - threadResumeCompletionMarker: true, - threadSnapshotPagination: true, - threadFind: true, - threadFindProgressive: true, - ...Option.match(scratchWorkspaceRoot, { - onNone: () => ({}), - onSome: (root) => ({ scratchWorkspaceRoot: root }), - }), - newProjectsRoot: managedFolders.namedProjectsRoot, - }; - }); + return { + environment, + auth, + cwd: config.cwd, + keybindingsConfigPath: config.keybindingsConfigPath, + keybindings: keybindingsConfig.keybindings, + issues: keybindingsConfig.issues, + providers, + ...editorConfig, + remoteOpenTargets: yield* resolveAvailableEditorsForConfig( + remoteOpenTargets.resolveTargets(), + ), + directEndpoints: yield* resolveAvailableEditorsForConfig(directEndpoints.resolve()), + observability: { + logsDirectoryPath: config.logsDir, + localTracingEnabled: true, + ...(config.otlpTracesUrl !== undefined + ? { + otlpTracesUrl: config.otlpTracesUrl, + otlpTracesSource: config.otlpTracesSource, + otlpTracesVariable: config.otlpTracesVariable, + } + : {}), + otlpTracesEnabled: config.otlpTracesUrl !== undefined, + ...(config.otlpMetricsUrl !== undefined + ? { + otlpMetricsUrl: config.otlpMetricsUrl, + otlpMetricsSource: config.otlpMetricsSource, + otlpMetricsVariable: config.otlpMetricsVariable, + } + : {}), + otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, + ...(config.otlpLogsUrl !== undefined + ? { + otlpLogsUrl: config.otlpLogsUrl, + otlpLogsSource: config.otlpLogsSource, + otlpLogsVariable: config.otlpLogsVariable, + } + : {}), + otlpLogsEnabled: config.otlpLogsUrl !== undefined, + }, + settings, + shellResumeCompletionMarker: true, + shellThreadFamilies: true, + threadResumeCompletionMarker: true, + threadSnapshotPagination: true, + threadFind: true, + threadFindProgressive: true, + ...Option.match(scratchWorkspaceRoot, { + onNone: () => ({}), + onSome: (root) => ({ scratchWorkspaceRoot: root }), + }), + newProjectsRoot: managedFolders.namedProjectsRoot, + ...(lastEventLoopStall === undefined ? {} : { lastEventLoopStall }), + }; + }); const refreshGitStatus = (cwd: string) => vcsStatusBroadcaster @@ -1746,6 +1825,26 @@ const layerWsRpc = ( ), ); + // Rows the shell can omit, read with the same snapshot sequence the shell uses. + const readOmittableShellRows = Effect.fn("ws.orchestrationV2.readOmittableShellRows")( + function* ( + options: { readonly subagentFamilyOf: ThreadId } | { readonly worktreePath: string }, + message: string, + ) { + const { threads, snapshotSequence } = yield* loadShellSnapshotParts({ + sql, + readThreads: threadManagement.readShellSnapshot({ location: "active", ...options }), + listProjects: Effect.succeed([]), + latestSequence: applicationEvents.latestApplicationSequence, + }).pipe( + Effect.mapError( + (cause) => new OrchestrationV2GetShellSnapshotError({ message, cause }), + ), + ); + return { snapshotSequence, threads: threads.threads }; + }, + ); + const subscribeOrchestrationV2ArchivedShell = Effect.fn( "ws.orchestrationV2.subscribeArchivedShell", )(function* () { @@ -1823,7 +1922,9 @@ const layerWsRpc = ( ).pipe(Effect.provide(intakeContext)), ) .pipe( - Effect.tap(() => recordClientCommandAnalytics(command)), + Effect.tap((result) => + result.replayed ? Effect.void : recordClientCommandAnalytics(command), + ), Effect.map((result) => ({ sequence: result.sequence })), Effect.mapError((cause) => { const detail = userFacingDispatchErrorMessage(cause); @@ -1892,23 +1993,31 @@ const layerWsRpc = ( ), [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => getOrchestrationV2ArchivedShellSnapshot, + [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) => + readOmittableShellRows( + { subagentFamilyOf: input.threadId }, + "Failed to load the thread family", + ), + [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: (input) => + readOmittableShellRows( + { worktreePath: input.worktreePath }, + "Failed to load the worktree's threads", + ).pipe(Effect.map(({ threads }) => ({ threadIds: threads.map((thread) => thread.id) }))), [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen( - // Pre-pagination clients still call this compatibility endpoint. - // Keep stale clients from materializing an unbounded transcript. + // Bound compatibility snapshots so pre-pagination clients cannot materialize unlimited transcripts. threadManagement .getThreadSnapshotWindow(input.threadId, { rowLimit: THREAD_HISTORY_SNAPSHOT_ROW_LIMIT, }) .pipe( - Effect.map((snapshot) => - projectThreadProjectionForWire( + Effect.map( + (snapshot) => buildBoundedThreadProjection({ - projection: snapshot.projection, + projection: projectThreadProjectionForWire(snapshot.projection), snapshotSequence: snapshot.snapshotSequence, }).projection, - ), ), Effect.mapError( (cause) => @@ -1963,17 +2072,23 @@ const layerWsRpc = ( }).pipe(Effect.provide(intakeContext)), ) .pipe( - Effect.tap(() => - analytics - .record("client.thread.started", originProps) - .pipe( - Effect.andThen( - input.initialMessage === undefined - ? Effect.void - : analytics.record("client.turn.requested", originProps), - ), - Effect.ignore, - ), + // A resumed launch is a retry of one already counted. + Effect.tap((result) => + result.resumed + ? Effect.void + : analytics + .record("client.thread.started", { + ...originProps, + workspaceStrategy: input.workspaceStrategy.type, + }) + .pipe( + Effect.andThen( + input.initialMessage === undefined + ? Effect.void + : analytics.record("client.turn.requested", originProps), + ), + Effect.ignore, + ), ), Effect.map((result) => ({ ...result, @@ -2049,6 +2164,10 @@ const layerWsRpc = ( Effect.annotateCurrentSpan({ "scheduled_task.id": input.id }).pipe( Effect.andThen(scheduledTasks.rotateWebhookToken(input)), ), + [WS_METHODS.guestShareCreate]: (input) => + Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( + Effect.andThen(guestShares.create(input)), + ), [WS_METHODS.secretsAnswerRequest]: (input) => Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(secretRequests.answer(input)), @@ -2162,8 +2281,9 @@ const layerWsRpc = ( }), ), ), - [WS_METHODS.serverRefreshProviders]: (input) => - Effect.gen(function* () { + [WS_METHODS.serverRefreshProviders]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (input) { if (input.refreshModels) { yield* modelManifest.forceRefresh; const instances = yield* providerInstances.listInstances; @@ -2176,16 +2296,21 @@ const layerWsRpc = ( Effect.gen(function* () { yield* instance.invalidateCaches ?? Effect.void; const maintenance = yield* instance.snapshot.resolveMaintenance({ - fresh: true, + fresh: + input.instanceId !== undefined && + input.cwd !== undefined && + input.fresh !== true, }); - if (maintenance.packageName) - yield* providerLatestVersions.invalidate(maintenance.packageName); + yield* Effect.forEach( + latestProviderVersionCacheKeys(maintenance), + providerLatestVersions.invalidate, + { discard: true }, + ); }), { concurrency: "unbounded", discard: true }, ); } - // Awaited, not forked: the RPC scope closes on return and would - // interrupt a fork before the hub answered. + // Await refresh; RPC scope closure would interrupt a fork before the hub answered. if (input.instanceId === undefined) { yield* usageLimitSources.refresh; } @@ -2231,59 +2356,65 @@ const layerWsRpc = ( [WS_METHODS.mcpAppsToolInfo]: (input) => mcpAppRequests.toolInfo(input), [WS_METHODS.mcpAppsUpdateModelContext]: (input) => mcpAppRequests.updateModelContext(input), [WS_METHODS.mcpAppsReadResource]: (input) => mcpAppRequests.readResource(input), - [WS_METHODS.providerUploadFeedback]: (input) => - Effect.gen(function* () { - const projection = yield* threadManagement.getThreadRecords(input.threadId, [ - "providerThreads", - ]); - const providerThread = - projection.providerThreads.find( - (candidate) => candidate.id === projection.thread.activeProviderThreadId, - ) ?? projection.providerThreads.at(-1); - const providerSessionId = providerThread?.providerSessionId ?? null; - if (providerThread === undefined || providerSessionId === null) { - return yield* Effect.fail( - new ProviderUploadFeedbackError({ - threadId: input.threadId, - cause: "No provider session has run in this thread yet.", - }), - ); - } - const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId)); - if (runtime === null) { - return yield* Effect.fail( - new ProviderUploadFeedbackError({ - threadId: input.threadId, - cause: "The provider session is no longer running. Send a message first.", - }), - ); - } - if (runtime.uploadFeedback === undefined) { - return yield* Effect.fail( - new ProviderUploadFeedbackError({ - threadId: input.threadId, - cause: `Provider '${runtime.driver}' does not support feedback uploads.`, - }), - ); - } - return yield* runtime.uploadFeedback({ - providerThread, - ...(input.reason === undefined ? {} : { reason: input.reason }), - }); - }).pipe( - Effect.mapError((cause) => - isProviderUploadFeedbackError(cause) - ? cause - : new ProviderUploadFeedbackError({ + [WS_METHODS.providerUploadFeedback]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced( + function* (input) { + const projection = yield* threadManagement.getThreadRecords(input.threadId, [ + "providerThreads", + ]); + const providerThread = + projection.providerThreads.find( + (candidate) => candidate.id === projection.thread.activeProviderThreadId, + ) ?? projection.providerThreads.at(-1); + const providerSessionId = providerThread?.providerSessionId ?? null; + if (providerThread === undefined || providerSessionId === null) { + return yield* Effect.fail( + new ProviderUploadFeedbackError({ threadId: input.threadId, - cause, + cause: "No provider session has run in this thread yet.", }), - ), + ); + } + const runtime = Option.getOrNull(yield* providerSessionsV2.get(providerSessionId)); + if (runtime === null) { + return yield* Effect.fail( + new ProviderUploadFeedbackError({ + threadId: input.threadId, + cause: "The provider session is no longer running. Send a message first.", + }), + ); + } + if (runtime.uploadFeedback === undefined) { + return yield* Effect.fail( + new ProviderUploadFeedbackError({ + threadId: input.threadId, + cause: `Provider '${runtime.driver}' does not support feedback uploads.`, + }), + ); + } + return yield* runtime.uploadFeedback({ + providerThread, + ...(input.reason === undefined ? {} : { reason: input.reason }), + }); + }, + (effect, input) => + effect.pipe( + Effect.mapError((cause) => + isProviderUploadFeedbackError(cause) + ? cause + : new ProviderUploadFeedbackError({ + threadId: input.threadId, + cause, + }), + ), + ), ), [WS_METHODS.serverUpdateProvider]: (input) => providerMaintenanceRunner.updateProvider(input), - [WS_METHODS.providerConsumeResetCredit]: (input) => - Effect.gen(function* () { + [WS_METHODS.providerConsumeResetCredit]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (input) { if ("sourceId" in input) return yield* usageLimitSources.consumeResetCredit(input); const instance = yield* providerInstances.getInstance(input.instanceId); if (instance === undefined || !instance.enabled) { @@ -2335,37 +2466,18 @@ const layerWsRpc = ( [WS_METHODS.providerInstallRemove]: (input) => providerInstallation.remove(input), [WS_METHODS.serverUpdateServer]: (input) => serverSelfUpdate.update(input), [WS_METHODS.serverUpdateServerWithProgress]: (input) => - Stream.callback((queue) => - serverSelfUpdate - .update(input, (stage) => - Queue.offer(queue, { - type: "progress", - stage, - }).pipe(Effect.asVoid), - ) - .pipe( - Effect.flatMap((result) => - Queue.offer(queue, { - type: "complete", - result, - }), - ), - Effect.catchTags({ - ServerSelfUpdateError: (error) => Queue.fail(queue, error), - }), - Effect.andThen(Queue.end(queue)), - Effect.forkScoped, - ), - ), + ServerSelfUpdate.updateProgressStream(serverSelfUpdate, input), [WS_METHODS.serverCommitDesktopUpdate]: (input) => serverSelfUpdate.commitDesktopUpdate(input.requestId), - [WS_METHODS.serverUpsertKeybinding]: (rule) => - Effect.gen(function* () { + [WS_METHODS.serverUpsertKeybinding]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (rule) { const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); return { keybindings: keybindingsConfig, issues: [] }; }), - [WS_METHODS.serverRemoveKeybinding]: (rule) => - Effect.gen(function* () { + [WS_METHODS.serverRemoveKeybinding]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (rule) { const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule); return { keybindings: keybindingsConfig, issues: [] }; }), @@ -2374,8 +2486,9 @@ const layerWsRpc = ( [WS_METHODS.serverGetDatabaseStorage]: () => databaseStorage.status, [WS_METHODS.serverGetSettings]: (_input) => serverSettings.getSettings.pipe(Effect.map(ServerSettings.redactServerSettingsForClient)), - [WS_METHODS.serverUpdateSettings]: ({ patch, providerInstanceMutation }) => - Effect.gen(function* () { + [WS_METHODS.serverUpdateSettings]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* ({ patch, providerInstanceMutation }) { const deviceHosts = patch.deviceHosts ? yield* remoteSshDeviceHosts(patch.deviceHosts).pipe( Effect.provide(deviceHostContext), @@ -2449,6 +2562,7 @@ const layerWsRpc = ( ), [WS_METHODS.pullRequestsList]: (input) => pullRequests.list(input), [WS_METHODS.pullRequestsListStats]: (input) => pullRequests.listStats(input), + [WS_METHODS.pullRequestsFilterOptions]: (input) => pullRequests.filterOptions(input), [WS_METHODS.pullRequestsRoutingIdentity]: (input) => pullRequests.routingIdentity(input), [WS_METHODS.pullRequestsRouting]: (input) => pullRequests.routing(input), [WS_METHODS.pullRequestsSummary]: (input) => @@ -2483,6 +2597,8 @@ const layerWsRpc = ( withPullRequestViewer(input, pullRequests.diffFileContents(input)), [WS_METHODS.pullRequestsFilesViewed]: (input) => withPullRequestViewer(input, pullRequests.filesViewed(input)), + [WS_METHODS.pullRequestsChangeBreakdown]: (input) => + withPullRequestViewer(input, pullRequests.changeBreakdown(input)), [WS_METHODS.pullRequestsSetFilesViewed]: (input) => withPullRequestViewer(input, pullRequests.setFilesViewed(input)), [WS_METHODS.pullRequestsRunAction]: (input) => @@ -2567,6 +2683,10 @@ const layerWsRpc = ( }), ), Effect.andThen(refreshGitStatus(project.workspaceRoot)), + // The folder was empty when the project was created, so the cached + // enrichment says "no repository" and clients cannot group it yet. + Effect.andThen(projectEnrichment.invalidate([project.workspaceRoot])), + Effect.andThen(projectEnrichment.request(project.workspaceRoot)), Effect.ignoreCause({ log: true }), ), }), @@ -2631,6 +2751,17 @@ const layerWsRpc = ( }), ), ), + [WS_METHODS.projectsListIgnoredFiles]: (input) => + workspaceEntries.listIgnoredFiles(input).pipe( + Effect.mapError( + (cause) => + new ProjectListEntriesError({ + ...input, + ...projectEntriesFailureContext(cause), + cause, + }), + ), + ), [WS_METHODS.projectsReadFile]: (input) => workspaceFileSystem.readFile(input).pipe( Effect.mapError( @@ -2682,19 +2813,24 @@ const layerWsRpc = ( ), ), [WS_METHODS.attachmentsCreateUploadUrl]: (input) => issueAttachmentUploadUrl(input), + [WS_METHODS.speechToTextCreateUploadUrl]: (input) => issueSpeechToTextUploadUrl(input), [WS_METHODS.attachmentsDelete]: (input) => deletePendingAttachment(input.attachmentId), [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, [WS_METHODS.agentSessionsImport]: (input) => agentSessionImporter.importRecentAgentThreads(input), - [WS_METHODS.assetsCreateUrl]: (input) => - Effect.gen(function* () { + [WS_METHODS.assetsCreateUrl]: + /* Request instrumentation already owns the span; keep this helper in that context. */ + Effect.fnUntraced(function* (input) { const path = yield* Path.Path; if ( input.resource._tag === "attachment" || input.resource._tag === "native-app-icon" || input.resource._tag === "tool-output-image" || - input.resource._tag === "github-media" || - (input.resource._tag === "media-file" && path.isAbsolute(input.resource.path)) + input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET || + // A network path is served only from the thread's project, looked up below. + (input.resource._tag === "media-file" && + path.isAbsolute(input.resource.path) && + !isNetworkPath(input.resource.path)) ) { return yield* issueAssetUrl({ resource: input.resource }); } @@ -2721,18 +2857,16 @@ const layerWsRpc = ( resource: input.resource, }); } - // A cloned project exists before its files do. Clients ask again - // when the clone lands (see createProjectFaviconUrlAtomFamily). + // Clone projects precede their files; clients retry asset URLs after clone completion. const clone = yield* projectCloneTracker.get(project.value.projectId); return yield* issueAssetUrl({ resource: input.resource, ...(project.value.faviconPath ? { projectFaviconPath: project.value.faviconPath } : {}), - projectCheckoutPending: - clone !== null && - clone.phase !== "done" && - clone.destinationPath === project.value.workspaceRoot, + ...(clone !== null && clone.destinationPath === project.value.workspaceRoot + ? { projectCheckout: clone.phase === "done" ? "cloned" : "pending" } + : {}), }); } const thread = yield* threadManagement @@ -2767,10 +2901,7 @@ const layerWsRpc = ( }), [WS_METHODS.assetsPersistChatAttachments]: (input) => persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))), - [WS_METHODS.subscribeVcsStatus]: (input) => - vcsStatusBroadcaster.streamStatus(input, { - automaticRemoteRefreshInterval: automaticGitFetchInterval, - }), + [WS_METHODS.subscribeVcsStatus]: (input) => vcsStatusBroadcaster.streamStatus(input), [WS_METHODS.subscribeWorktreeSetup]: (input) => worktreeSetupTracker.stream(input.threadId), [WS_METHODS.worktreeSetupCancel]: (input) => worktreeSetupTracker @@ -2845,11 +2976,11 @@ const layerWsRpc = ( [WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input), [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), [WS_METHODS.terminalAttach]: (input) => - Stream.callback((queue) => - Effect.acquireRelease( - terminalManager.attachStream(input, (event) => Queue.offer(queue, event)), - (unsubscribe) => Effect.sync(unsubscribe), - ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))), + terminalOutputStream( + (listener, registerCleanup) => + terminalManager.attachStream(input, listener, registerCleanup), + (listener, registerCleanup) => + terminalManager.resyncStream(input, listener, registerCleanup), ), [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input), [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input), @@ -2857,19 +2988,14 @@ const layerWsRpc = ( [WS_METHODS.terminalRestart]: (input) => terminalManager.restart(input), [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), [WS_METHODS.terminalObserve]: (input) => - Stream.callback((queue) => - Effect.acquireRelease( - terminalManager.observeStream(input, (event) => Queue.offer(queue, event)), - (unsubscribe) => Effect.sync(unsubscribe), - ).pipe(Effect.catchCause((cause) => Queue.failCause(queue, cause))), + terminalOutputStream( + (listener, registerCleanup) => + terminalManager.observeStream(input, listener, registerCleanup), + (listener, registerCleanup) => + terminalManager.resyncStream(input, listener, registerCleanup), ), [WS_METHODS.subscribeTerminalEvents]: (_input) => - Stream.callback((queue) => - Effect.acquireRelease( - terminalManager.subscribe((event) => Queue.offer(queue, event)), - (unsubscribe) => Effect.sync(unsubscribe), - ), - ), + terminalOutputStream(terminalManager.subscribe), [WS_METHODS.subscribeTerminalMetadata]: (_input) => Stream.callback((queue) => Effect.acquireRelease( @@ -2890,6 +3016,7 @@ const layerWsRpc = ( [WS_METHODS.subscribePreviewEvents]: (_input) => previewManager.events, [WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input), [WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input), + [WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input), [WS_METHODS.deviceList]: (input) => input.inspectOnly && !input.updateTool ? deviceService.inspect @@ -2901,7 +3028,10 @@ const layerWsRpc = ( ? deviceService.retryHost(input.retryHostId) : deviceService.list, ), - [WS_METHODS.deviceOpen]: (input) => deviceService.open(input), + [WS_METHODS.deviceOpen]: (input) => + threadWorkspaceRoot(input.threadId).pipe( + Effect.flatMap((workspaceRoot) => deviceService.open(input, { workspaceRoot })), + ), [WS_METHODS.deviceClose]: (input) => deviceService.close(input), [WS_METHODS.deviceShutdown]: (input) => deviceService.shutdown(input), [WS_METHODS.deviceDetail]: (input) => deviceService.detail(input), @@ -2937,8 +3067,11 @@ const layerWsRpc = ( Stream.unwrap( Effect.gen(function* () { const usageLimitsCommand = input.usageLimitsCommand === true; + // Buffer changes through discovery and the initial snapshot's RPC ACK wait. + const keybindingsChanges = yield* keybindings.subscribeChanges; + const settingsChanges = yield* serverSettings.subscribeChanges; const config = yield* loadServerConfig({ usageLimitsCommand }); - const keybindingsUpdates = keybindings.streamChanges.pipe( + const keybindingsUpdates = keybindingsChanges.pipe( Stream.map((event) => ({ version: 1 as const, type: "keybindingsUpdated" as const, @@ -2949,9 +3082,7 @@ const layerWsRpc = ( })), ); const providerStatuses = Stream.zipLatestWith( - // The registry stream carries changes only. Seed it with the current - // providers so a source refresh that lands before any provider change - // still pairs up and reaches the client. + // Seed the changes-only stream so early source refreshes pair with current providers. Stream.concat( Stream.fromEffect(providerRegistry.getProviders), providerRegistry.streamChanges, @@ -2964,10 +3095,7 @@ const layerWsRpc = ( (providers, sources) => usageLimitsCommand ? withUsageLimitsCommands(providers, sources) : providers, ).pipe( - // Both sides replay their current value, so the first pairing normally - // repeats the snapshot the client already holds. Compare against that - // snapshot rather than dropping blindly: a refresh that landed between - // the snapshot and the subscription still goes out. + // Compare initial paired values with the snapshot; blindly dropping them loses changes between snapshot and subscription. (updates) => Stream.concat(rpcInitialItems([config.providers]), updates), Stream.changesWith( (previous, next) => JSON.stringify(previous) === JSON.stringify(next), @@ -2980,10 +3108,7 @@ const layerWsRpc = ( })), Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)), ); - // Gated on the subscriber's capability flag because an - // already-shipped client decodes this stream against the old - // event union and its whole config subscription dies on an - // unknown member. + // Gate capability-specific events; older clients reject them and lose their config subscription. const environmentThemeUpdates = input.environmentThemes === true ? environmentTheme.streamChanges.pipe( @@ -3004,7 +3129,7 @@ const layerWsRpc = ( })), ) : Stream.empty; - const settingsUpdates = serverSettings.streamChanges.pipe( + const settingsUpdates = settingsChanges.pipe( Stream.map((settings) => ServerSettings.redactServerSettingsForClient(settings)), Stream.map((settings) => ({ version: 1 as const, @@ -3095,12 +3220,17 @@ const layerWsRpc = ( ), ), }); - return handlers; + const splitHandlers: Pick = handlers; + const otherHandlers: Pick["_tag"]> = + handlers; + return Context.merge( + yield* SplitWsRpcGroup.toHandlers(splitHandlers), + yield* OtherWsRpcGroup.toHandlers(otherHandlers), + ); }), ); -// RpcServer's default sends a socket-level Defect frame instead, and the client -// ends every pending request on the socket with it. +// Default socket-level Defect frames end every pending client request. export const WS_RPC_SERVER_OPTIONS = { disableTracing: true, disableFatalDefects: true, @@ -3133,7 +3263,7 @@ export const layer = Layer.unwrap( const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; const sessions = yield* SessionStore.SessionStore; const analytics = yield* AnalyticsService.AnalyticsService; - const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe( + const session = yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc").pipe( Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => failEnvironmentAuthInvalid( EnvironmentAuth.serverAuthCredentialReason(error), @@ -3147,13 +3277,30 @@ export const layer = Layer.unwrap( const clientOrigin = readClientConnectionOrigin(request); const clientAnalyticsProps = readClientAnalyticsProps(request); yield* sessions.recordClientConnection(session.sessionId, clientOrigin); - yield* analytics.record("client.connected", clientAnalyticsProps); + yield* analytics.recordOwners(readClientOwners(request), "client"); const rpcWebSocketHttpEffect = yield* Effect.gen(function* () { const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket; yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe( Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)), Effect.provide( - Layer.merge(RpcAuthorization.layer(session.scopes), rpcInstrumentationLayer), + Layer.merge( + RpcAuthorization.layer(session.scopes, (method, payload) => { + // Anonymous product signal: the feature and its enum variant, + // credited to the connecting client's surface only. + const usage = featureUsage(method, payload); + return usage === undefined + ? Effect.void + : analytics + .record("feature.used", { + ...usage, + ...(clientAnalyticsProps.surface === undefined + ? {} + : { surface: clientAnalyticsProps.surface }), + }) + .pipe(Effect.ignore); + }), + rpcInstrumentationLayer, + ), ), Effect.forkScoped, ); @@ -3169,15 +3316,13 @@ export const layer = Layer.unwrap( serverBrowser, ).pipe( Layer.provideMerge(RpcSerialization.layerJson), - // Request fibers run in the handlers' context, so this reporter sees - // their defects, not the rest of the server's. + // Handler-context reporters see only request defects, not server-wide defects. Layer.provide(DefectReporter.layer), Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)), Layer.provide(AgentSessionScanner.layer), Layer.provide(ProviderMaintenanceRunner.layer), Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)), - // One server-lifetime service means clients share the same PR caches, and a WS - // mutation invalidates the HTTP diff cache that every client reads from. + // Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs. Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)), Layer.provide(OtlpEndpointCheck.layer), Layer.provide( diff --git a/apps/server/src/zipArchive.ts b/apps/server/src/zipArchive.ts index 33c8099473889..6711fbd3f5ee8 100644 --- a/apps/server/src/zipArchive.ts +++ b/apps/server/src/zipArchive.ts @@ -3,9 +3,7 @@ import * as Effect from "effect/Effect"; import type * as NodeStream from "node:stream"; import * as Yauzl from "yauzl"; -/** - * Close the scope to close the archive. - */ +/** Closing the scope closes the archive. */ export const openZipArchive = Effect.fn("zipArchive.open")(function* ( archivePath: string, makeError: (detail: string, cause: unknown) => E, diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index a26e5afb06157..5d36d0867c597 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig, mergeConfig } from "vite-plus"; import baseConfig from "../../vite.config.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import rootPackageJson from "../../package.json" with { type: "json" }; import packageJson from "./package.json" with { type: "json" }; import { WeightedShardSequencer } from "./src/testUtils/weightedShardSequencer.ts"; @@ -18,13 +19,17 @@ const repoEnv = loadRepoEnv(); const cliBuildChannel = /^[^-+]+-(?:nightly|preview)\./.test(packageJson.version) ? "nightly" : "latest"; +// Official release workflows set the telemetry channel; local builds and forks use "dev". +const TELEMETRY_CHANNELS = ["stable", "nightly", "preview", "dev"]; +const telemetryChannel = process.env.T3CODE_TELEMETRY_CHANNEL?.trim() || "dev"; +if (!TELEMETRY_CHANNELS.includes(telemetryChannel)) { + throw new Error( + `T3CODE_TELEMETRY_CHANNEL must be one of ${TELEMETRY_CHANNELS.join(", ")}, got "${telemetryChannel}".`, + ); +} -// `build:exe` wraps the same bundle in a Node single-executable. tsdown's exe -// step refuses multi-chunk output and counts the sourcemap as a chunk, and the -// executable needs a host Node that supports `--build-sea` (25.7+), so this is -// a separate mode rather than a second entry in the default build. +// tsdown SEA needs one chunk (sourcemaps count) and Node >=25.7, so package separately. const packExecutable = process.env.T3CODE_PACK_EXE === "1"; -const SEA_NODE_VERSION = "26.8.2"; const SEA_TARGETS = { "darwin-arm64": { platform: "darwin", arch: "arm64" }, "darwin-x64": { platform: "darwin", arch: "x64" }, @@ -34,6 +39,12 @@ const SEA_TARGETS = { "win-x64": { platform: "win", arch: "x64" }, } as const; const packExecutableTarget = process.env.T3CODE_PACK_EXE_TARGET?.trim(); +const cliNodeVersion = rootPackageJson.engines.node; +if (packExecutable && !packExecutableTarget && process.versions.node !== cliNodeVersion) { + throw new Error( + `Native CLI executables must be built with Node ${cliNodeVersion}; running ${process.versions.node}.`, + ); +} if (packExecutableTarget && !Object.hasOwn(SEA_TARGETS, packExecutableTarget)) { throw new Error( `T3CODE_PACK_EXE_TARGET must be one of ${Object.keys(SEA_TARGETS).join(", ")}, got "${packExecutableTarget}".`, @@ -43,13 +54,19 @@ const packExecutableTargets = packExecutableTarget ? [ { ...SEA_TARGETS[packExecutableTarget as keyof typeof SEA_TARGETS], - nodeVersion: SEA_NODE_VERSION, + nodeVersion: cliNodeVersion, }, ] : undefined; +// The root config's `projects` route repo-root runs to package configs, +// including this one. Inheriting them would make this config a container. +const { projects: _rootTestProjects, ...baseTestConfig } = baseConfig.test ?? {}; +// Workspace cache configuration is invalid on a package config. +const { run: _rootRunConfig, ...basePackageConfig } = baseConfig; + export default mergeConfig( - baseConfig, + { ...basePackageConfig, test: baseTestConfig }, defineConfig({ run: { tasks: { @@ -61,8 +78,7 @@ export default mergeConfig( }, }, pack: { - // The executable embeds one entry; the history worker becomes a hidden - // subcommand there instead of a sibling script. + // SEA embeds one entry; expose the history worker as a hidden subcommand. entry: packExecutable ? ["src/bin.ts"] : ["src/bin.ts", "src/claude-history-worker.ts"], outDir: packExecutable ? "dist-exe" : "dist", sourcemap: !packExecutable, @@ -73,17 +89,13 @@ export default mergeConfig( fileName: "t3", outDir: "dist-exe", ...(packExecutableTargets ? { targets: packExecutableTargets } : {}), - // Node's SEA docs: `import()` does not work when useCodeCache is - // true, and the server reaches several modules that way. + // Node SEA useCodeCache breaks import(), which the server needs. seaConfig: { useCodeCache: false }, }, } : {}), deps: { - // `neverBundle` forces the native packages out: returning false from - // `alwaysBundle` only means "no opinion", so a transitive dependency - // would still be bundled — which silently inlined native loaders such - // as node-gyp-build, losing native acceleration. + // alwaysBundle=false has no opinion; neverBundle must retain transitive native acceleration. alwaysBundle: shouldBundleCliDependency, neverBundle: (id: string) => isExternalCliDependency(id), onlyBundle: false, @@ -93,6 +105,7 @@ export default mergeConfig( }, define: { __T3CODE_BUILD_CHANNEL__: JSON.stringify(cliBuildChannel), + __T3CODE_TELEMETRY_CHANNEL__: JSON.stringify(telemetryChannel), __T3CODE_BUILD_RELAY_URL__: JSON.stringify(repoEnv.T3CODE_RELAY_URL?.trim() ?? ""), __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: JSON.stringify( repoEnv.T3CODE_CLERK_PUBLISHABLE_KEY?.trim() ?? "", @@ -112,11 +125,9 @@ export default mergeConfig( }, }, test: { - // The server suite exercises sqlite, git, temp worktrees, and orchestration - // runtimes heavily. Running files in parallel introduces load-sensitive flakes. + // Parallel sqlite/git/worktree/orchestration tests introduce load-sensitive flakes. fileParallelism: false, sequence: { sequencer: WeightedShardSequencer }, - // Appended to the root setup, which mergeConfig concatenates. setupFiles: ["./src/testUtils/gitConfig.setup.ts"], hookTimeout: 120_000, testTimeout: 120_000, diff --git a/apps/web/index.html b/apps/web/index.html index bd4a3d6d5f8ac..c6941cd039788 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -122,8 +122,6 @@ }, }, }; - // Keep the built-in mode list in sync with the runtime so the selected - // T3 Chat palette is visible before React has mounted. const BUILT_IN_THEME_MODES = Object.fromEntries( Object.entries(BUILT_IN_THEME_PALETTES).map(([id, palettes]) => [ id, @@ -145,8 +143,6 @@ "t3-ember", "t3-iris", ]; - // Update every theme-color meta so any element another layer added - // carries the resolved color too. const setThemeColor = (color) => { for (const meta of document.querySelectorAll('meta[name="theme-color"]')) { meta.setAttribute("content", color); @@ -219,9 +215,6 @@ try { const storedTheme = window.localStorage.getItem("t3code:theme"); const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; - // Older builds stored the dark T3 Chat palette as its own theme id - // and every maintainer theme under a t3- prefix; keep those - // preferences readable. Mirrors the runtime's legacy alias table. const LEGACY_THEME_IDS = { "t3-chat-dark": "t3-chat", "t3-grove": "grove", @@ -242,7 +235,6 @@ (mode) => mode === customTheme.appearance || customTheme.variants?.[mode], ) : null); - // Mirrors the runtime's isKnownThemePreference. const isKnownTheme = storedTheme === "light" || storedTheme === "dark" || @@ -256,8 +248,6 @@ THEME_APPEARANCE_MODE_STORAGE_KEY, ); const storedFollowSystem = window.localStorage.getItem(THEME_FOLLOW_SYSTEM_STORAGE_KEY); - // Mirrors the runtime's getThemePreferenceMode fallback: a bare - // "light"/"dark" preference names its own mode. const preferenceMode = theme === "light" || theme === "dark" ? theme : (legacyMode ?? baseAppearance); const appearanceMode = isThemePreferenceMode(storedAppearanceMode) @@ -296,9 +286,7 @@ halfCustomTheme = halfCustom; } } - } catch { - // A malformed mix degrades to the base preference. - } + } catch {} const themeMode = !isThemed ? null : appearanceMode === "system" @@ -385,13 +373,10 @@ } setThemeColor(chromeColor); } catch { - // Mirror the runtime's storage-failure fallback: follow the OS. let prefersDark = true; try { prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches; - } catch { - // Keep the dark default when even matchMedia is unavailable. - } + } catch {} delete document.documentElement.dataset.themeId; delete document.documentElement.dataset.themeSelected; document.documentElement.classList.toggle("dark", prefersDark); diff --git a/apps/web/package.json b/apps/web/package.json index 15a202c071b06..2ad03efe77e15 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,14 +1,14 @@ { "name": "@t3tools/web", - "version": "0.1.0", + "version": "0.1.2", "private": true, "type": "module", "scripts": { "build:ghostty-wasm": "bash scripts/build-libghostty-wasm.sh", "dev": "vp dev", + "dev:built": "vp build --watch", "build": "vp build", "preview": "vp preview", - "typecheck": "tsc-rs --noEmit", "test": "vp test run --passWithNoTests --project unit --project browser" }, "dependencies": { @@ -45,6 +45,7 @@ "@tiptap/extension-code-block": "^3.31.3", "@tiptap/extension-heading": "^3.31.3", "@tiptap/extension-horizontal-rule": "^3.31.3", + "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", @@ -61,16 +62,20 @@ "jose": "catalog:", "jsonc-parser": "3.3.1", "jszip": "3.10.1", + "katex": "^0.16.47", "lucide": "^0.564.0", "lucide-react": "^0.564.0", - "mermaid": "^11.17.2", "morphicons": "^1.7.1", - "react": "19.2.6", - "react-dom": "19.2.6", + "pele": "^1.8.0", + "react": "catalog:", + "react-dom": "catalog:", "react-markdown": "^10.1.0", "remark-gfm": "catalog:", + "remark-math": "6.0.0", + "remark-parse": "catalog:", "tailwind-merge": "^3.4.0", "unbash": "^5.0.0", + "unified": "catalog:", "use-sync-external-store": "^1.6.0", "zustand": "^5.0.11" }, @@ -82,17 +87,16 @@ "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/mdast": "^4.0.4", - "@types/react": "~19.3.0", - "@types/react-dom": "~19.2.3", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", "@types/use-sync-external-store": "^0.0.6", "@vercel/config": "^0.3.0", "@vitejs/plugin-react": "^6.1.2", - "@vitest/browser-playwright": "5.0.1", + "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", "oxc-transform-react": "~0.152.0", "playwright": "1.60.0", "tailwindcss": "^4.0.0", - "unified": "catalog:", "vite": "catalog:", "vite-plus": "catalog:" } diff --git a/apps/web/scripts/warm-dep-cache.ts b/apps/web/scripts/warm-dep-cache.ts index 004eb9b53eebb..1b3bbee034642 100644 --- a/apps/web/scripts/warm-dep-cache.ts +++ b/apps/web/scripts/warm-dep-cache.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off - setup-script bootstrap, runs before any Effect runtime exists. +// @effect-diagnostics nodeBuiltinImport:off - plain Node script that dev-runner spawns on a cold cache. /** * The cache cannot be shared between worktrees: Vite's config hash includes * the absolute project root, so each worktree must warm its own. diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx index df610d8e1ab8f..5e5b5ff16be90 100644 --- a/apps/web/src/AppRoot.tsx +++ b/apps/web/src/AppRoot.tsx @@ -1,17 +1,28 @@ import { RouterProvider } from "@tanstack/react-router"; +import { useEffect } from "react"; + +import { subscribeComposerDraftModelReconciliation } from "./composerDraftStore"; +import { environmentThreadShells } from "./state/threads"; +import { environmentShell } from "./state/shell"; import { BrowserProfileReporter } from "./browser/BrowserProfileReporter"; import { ElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { QuitHoldOverlay } from "./components/QuitHoldOverlay"; -import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; +import { appAtomRegistry, AppAtomRegistryProvider } from "./rpc/atomRegistry"; import type { AppRouter } from "./router"; -/** - * The Electron browser host intentionally sits outside the router so its - * webviews survive route transitions, but it must share the same atom registry - * as routed UI. - */ +// Keep webviews outside the router but inside its atom registry so route changes preserve them. export function AppRoot({ router }: { readonly router: AppRouter }) { + useEffect( + () => + subscribeComposerDraftModelReconciliation({ + registry: appAtomRegistry, + threadShellAtom: environmentThreadShells.threadShellAtom, + threadRefsAtom: environmentThreadShells.threadRefsAtom, + shellStateAtom: environmentShell.stateAtom, + }), + [], + ); return ( diff --git a/apps/web/src/appearanceContrast.test.ts b/apps/web/src/appearanceContrast.test.ts deleted file mode 100644 index 3e6c1fad04485..0000000000000 --- a/apps/web/src/appearanceContrast.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it, vi } from "vite-plus/test"; - -import { applyAppearanceContrast } from "./appearanceContrast"; - -function makeRoot() { - const setProperty = vi.fn(); - return { - root: { style: { setProperty } } as unknown as HTMLElement, - setProperty, - }; -} - -describe("applyAppearanceContrast", () => { - it("boosts semantic contrast above the default", () => { - const { root, setProperty } = makeRoot(); - - applyAppearanceContrast(root, 135); - - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-base", "100%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-boost", "35%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-border-boost", "8.75%"); - }); - - it("supports the maximum contrast boost", () => { - const { root, setProperty } = makeRoot(); - - applyAppearanceContrast(root, 200); - - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-base", "100%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-boost", "100%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-border-boost", "25%"); - }); - - it("softens semantic contrast below the default", () => { - const { root, setProperty } = makeRoot(); - - applyAppearanceContrast(root, 70); - - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-base", "70%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-boost", "0%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-border-boost", "0%"); - }); - - it("disables contrast mixing at the default", () => { - const { root, setProperty } = makeRoot(); - - applyAppearanceContrast(root, 100); - - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-base", "100%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-boost", "0%"); - expect(setProperty).toHaveBeenCalledWith("--appearance-contrast-border-boost", "0%"); - }); -}); diff --git a/apps/web/src/appearanceFonts.test.ts b/apps/web/src/appearanceFonts.test.ts deleted file mode 100644 index 31a2f1d779c56..0000000000000 --- a/apps/web/src/appearanceFonts.test.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; - -import { - areFontAdvancesMonospace, - clampCodeFontSize, - clampInterfaceFontSize, - clampPromptFontSize, - DEFAULT_CODE_FONT_STACK, - DEFAULT_SANS_FONT_STACK, - appearanceFontStack, - cssFontFamilies, - resolveDefaultFamilyLabel, - resolveTerminalFontPreference, - resolveTerminalFontSizePreference, -} from "./appearanceFonts"; - -describe("areFontAdvancesMonospace", () => { - it("accepts a fixed advance and rejects any proportional glyph", () => { - expect(areFontAdvancesMonospace([10, 10, 10, 10])).toBe(true); - expect(areFontAdvancesMonospace([10, 10, 7, 10])).toBe(false); - expect(areFontAdvancesMonospace([10, 10.02])).toBe(false); - }); - - it("fails open when canvas metrics are unavailable", () => { - expect(areFontAdvancesMonospace([])).toBe(true); - expect(areFontAdvancesMonospace([Number.NaN, Number.NaN])).toBe(true); - }); -}); - -describe("cssFontFamilies", () => { - it("returns null for effectively empty input", () => { - expect(cssFontFamilies("")).toBeNull(); - expect(cssFontFamilies(" ")).toBeNull(); - expect(cssFontFamilies(" , , ")).toBeNull(); - }); - - it("quotes names with spaces and keeps single idents bare", () => { - expect(cssFontFamilies("Fira Code")).toBe('"Fira Code"'); - expect(cssFontFamilies("monospace")).toBe("monospace"); - expect(cssFontFamilies('"Comic Mono"')).toBe('"Comic Mono"'); - }); - - it("normalizes comma-separated lists and strips embedded quotes", () => { - expect(cssFontFamilies(" Fira Code , Menlo ")).toBe('"Fira Code", Menlo'); - expect(cssFontFamilies('Bad"Name')).toBe('"BadName"'); - }); - - it("quotes names that are not single CSS idents", () => { - expect(cssFontFamilies("3270 Nerd Font")).toBe('"3270 Nerd Font"'); - expect(cssFontFamilies("M+ 1m")).toBe('"M+ 1m"'); - }); -}); - -describe("resolveDefaultFamilyLabel", () => { - it("skips generic keywords and returns null for a stack of only generics", () => { - expect(resolveDefaultFamilyLabel("system-ui, sans-serif")).toBeNull(); - expect(resolveDefaultFamilyLabel("ui-monospace, monospace")).toBeNull(); - }); -}); - -describe("appearanceFontStack", () => { - it("prepends the custom family to the default stack", () => { - expect(appearanceFontStack("Fira Code", DEFAULT_CODE_FONT_STACK)).toBe( - `"Fira Code", ${DEFAULT_CODE_FONT_STACK}`, - ); - }); - - it("falls back to the default stack when unset", () => { - expect(appearanceFontStack("", DEFAULT_SANS_FONT_STACK)).toBe(DEFAULT_SANS_FONT_STACK); - }); -}); - -describe("resolveTerminalFontPreference", () => { - it("inherits the code font in simple mode", () => { - expect( - resolveTerminalFontPreference({ advanced: false, code: "Fira Code", terminal: "" }), - ).toBe("Fira Code"); - expect( - resolveTerminalFontPreference({ - advanced: false, - code: "Fira Code", - terminal: "Berkeley Mono", - }), - ).toBe("Fira Code"); - }); - - it("keeps code and terminal fonts independent in advanced mode", () => { - expect(resolveTerminalFontPreference({ advanced: true, code: "Fira Code", terminal: "" })).toBe( - "", - ); - expect( - resolveTerminalFontPreference({ - advanced: true, - code: "Fira Code", - terminal: "Berkeley Mono", - }), - ).toBe("Berkeley Mono"); - }); -}); - -describe("resolveTerminalFontSizePreference", () => { - it("inherits the code font size in simple mode", () => { - expect(resolveTerminalFontSizePreference({ advanced: false, code: 15, terminal: 12 })).toBe(15); - }); - - it("keeps code and terminal font sizes independent in advanced mode", () => { - expect(resolveTerminalFontSizePreference({ advanced: true, code: 15, terminal: 12 })).toBe(12); - }); -}); - -describe("font size clamping", () => { - it("keeps sizes inside the ranges the UI can absorb", () => { - expect(clampInterfaceFontSize(16)).toBe(16); - expect(clampInterfaceFontSize(2)).toBe(12); - expect(clampInterfaceFontSize(96)).toBe(20); - expect(clampPromptFontSize(40)).toBe(20); - expect(clampCodeFontSize(1)).toBe(10); - }); - - it("rounds fractional values and falls back for unusable input", () => { - expect(clampCodeFontSize(13.4)).toBe(13); - expect(clampInterfaceFontSize(Number.NaN)).toBe(16); - expect(clampPromptFontSize(Number.POSITIVE_INFINITY)).toBe(14); - }); -}); diff --git a/apps/web/src/appearanceFonts.ts b/apps/web/src/appearanceFonts.ts index 3341ec27c2c1b..6d94ed565c707 100644 --- a/apps/web/src/appearanceFonts.ts +++ b/apps/web/src/appearanceFonts.ts @@ -13,8 +13,7 @@ import { export const DEFAULT_SANS_FONT_STACK = '-apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif'; -// Concrete names first: some engines alias `ui-monospace` to the -// proportional system UI font, which would break every code surface. +// Some engines map `ui-monospace` to a proportional font, so prefer concrete names. export const DEFAULT_CODE_FONT_STACK = '"SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace'; @@ -46,7 +45,7 @@ function quoteFontFamilyName(name: string): string { return `"${bare.replaceAll('"', "")}"`; } -export function cssFontFamilies(input: string): string | null { +function cssFontFamilies(input: string): string | null { const families = input .split(",") .map(quoteFontFamilyName) @@ -69,11 +68,7 @@ export interface AppearanceFontPreferences { readonly smoothing: boolean; } -/** - * Sizes are always written: the interface size drives the root font size (and - * with it every rem-based dimension), while the prompt and code sizes stay in - * absolute pixels so they do not scale twice. - */ +/** Always writes sizes: interface size sets the root; prompt and code use pixels to avoid double scaling. */ export function applyAppearanceFontVariables( root: HTMLElement, preferences: AppearanceFontPreferences, @@ -110,7 +105,7 @@ function clampFontSize(value: number, minimum: number, maximum: number, fallback return Math.min(maximum, Math.max(minimum, Math.round(value))); } -export function clampInterfaceFontSize(value: number): number { +function clampInterfaceFontSize(value: number): number { return clampFontSize( value, MIN_INTERFACE_FONT_SIZE, @@ -119,11 +114,11 @@ export function clampInterfaceFontSize(value: number): number { ); } -export function clampPromptFontSize(value: number): number { +function clampPromptFontSize(value: number): number { return clampFontSize(value, MIN_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE, DEFAULT_PROMPT_FONT_SIZE); } -export function clampCodeFontSize(value: number): number { +function clampCodeFontSize(value: number): number { return clampFontSize(value, MIN_CODE_FONT_SIZE, MAX_CODE_FONT_SIZE, DEFAULT_CODE_FONT_SIZE); } @@ -139,11 +134,7 @@ function probeWidth(fontList: string): number | null { return fontProbeContext.measureText(FONT_PROBE_TEXT).width; } -/** - * Canvas metric probing instead of document.fonts.check(): check() reports true - * for families that are not installed at all (nothing needs loading), so it - * cannot filter the dropdown. - */ +/** Probes canvas metrics because document.fonts.check() accepts uninstalled families. */ export function isFontFamilyAvailable(family: string): boolean { const families = cssFontFamilies(family); if (families === null) return false; @@ -165,7 +156,7 @@ const MONOSPACE_PROBE_VARIANTS = ["normal 400", "normal 700", "italic 400", "ita const MONOSPACE_PROBE_GLYPHS = ["i", "M", "W", "0", "@", "#", ".", " "] as const; const MONOSPACE_ADVANCE_TOLERANCE = 0.01; -export function areFontAdvancesMonospace(advances: readonly number[]): boolean { +function areFontAdvancesMonospace(advances: readonly number[]): boolean { const reference = advances[0]; if ( reference === undefined || @@ -223,11 +214,7 @@ const MONO_GENERIC_CANDIDATES = [ const GENERIC_PROBE_TEXT = "RagIl10O@ fjord quiz"; -/** - * Advance width of the probe text laid out by the DOM - not canvas, whose - * generic-family mapping diverges from real rendering (this engine draws - * `ui-monospace` as the proportional UI font on canvas but not in CSS). - */ +// Canvas generic-family mappings can differ from CSS, so measure the DOM. function measureDomProbeWidth(fontFamily: string): number | null { try { const body = document.body; @@ -263,9 +250,7 @@ function resolveGenericFamilyLabel(generic: string): string | null { return candidate; } } - // No nameable face matched; on Apple platforms that means one of the San - // Francisco faces, which CSS cannot name. Comparing against -apple-system - // tells the UI face apart from SF Mono. + // Unnameable Apple faces need -apple-system metrics to distinguish the UI face from SF Mono. if (/mac|iphone|ipad|ipod/i.test(navigator.platform)) { const systemWidth = measureDomProbeWidth("-apple-system"); if (systemWidth !== null && widthsMatch(genericWidth, systemWidth)) return "SF Pro"; @@ -299,10 +284,7 @@ export interface InstalledFontFamiliesResult { let installedFamiliesCache: InstalledFontFamiliesResult | null = null; -/** - * Call from a user gesture: the first call raises the browser's local-fonts - * permission prompt. - */ +/** Call from a user gesture; the first call prompts for local-fonts permission. */ export async function queryInstalledFontFamilies(): Promise { if (installedFamiliesCache !== null) return installedFamiliesCache; const query = ( @@ -317,12 +299,10 @@ export async function queryInstalledFontFamilies(): Promise font.family))] - // Dot-prefixed families are macOS-internal UI faces; selecting one is - // never intended and most refuse to render for web content anyway. + // Dot-prefixed macOS UI faces often refuse to render in web content. .filter((family) => !family.startsWith(".")) .sort((left, right) => left.localeCompare(right)); - // A denied permission check resolves with an empty list instead of - // throwing; no machine has zero fonts, so treat empty as denied. + // Denied access can return an empty list instead of throwing. if (families.length === 0) return { families: [], status: "denied" }; installedFamiliesCache = { families, status: "granted" }; return installedFamiliesCache; diff --git a/apps/web/src/assets/assetUrls.test.ts b/apps/web/src/assets/assetUrls.test.ts deleted file mode 100644 index 13ff3ea8e5797..0000000000000 --- a/apps/web/src/assets/assetUrls.test.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { - AuthFilesystemReadScope, - EnvironmentAuthorizationError, - EnvironmentId, - ThreadId, - type AuthSessionState, -} from "@t3tools/contracts"; -import * as Cause from "effect/Cause"; -import { AsyncResult } from "effect/reactivity"; -import { beforeEach, expect, it, vi } from "vite-plus/test"; - -const state = vi.hoisted(() => ({ - session: null as Pick | null, - phase: "connected" as "connected" | "offline", - assetAtom: {}, - mint: vi.fn(), - assetQuery: vi.fn(), -})); - -vi.mock("react", () => ({ useCallback: (callback: A) => callback })); -vi.mock("@effect/atom-react", () => ({ - useAtomValue: (atom: unknown) => - atom === state.assetAtom - ? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }) - : AsyncResult.initial(false), -})); -vi.mock("~/state/session", () => ({ - usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }), -})); -vi.mock("~/state/filesystem", async () => { - const { resolveFilesystemReadAccess } = await import("@t3tools/client-runtime/state/filesystem"); - return { - useFilesystemReadAccess: () => - resolveFilesystemReadAccess({ - isCatalogReady: true, - connection: { phase: state.phase, error: null }, - session: state.session, - sessionError: null, - }), - }; -}); -vi.mock("~/state/assets", () => ({ - assetEnvironment: { createUrl: state.assetQuery }, -})); -vi.mock("~/state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint })); - -import { useAssetUrlRefresh, useAssetUrlState } from "./assetUrls"; - -const environmentId = EnvironmentId.make("asset-environment"); -const threadId = ThreadId.make("asset-thread"); -const resource = { _tag: "media-file", threadId, path: "/repo/image.png" } as const; - -beforeEach(() => { - state.session = null; - state.phase = "connected"; - state.assetQuery.mockReset().mockReturnValue(state.assetAtom); - state.mint - .mockReset() - .mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })); -}); - -it.each(["workspace-file", "media-file"] as const)( - "keeps %s loading until its file grant resolves", - (_tag) => { - expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({ _tag: "Loading" }); - expect(state.assetQuery).not.toHaveBeenCalled(); - - state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] }; - expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({ - _tag: "Success", - expiresAt: 1, - url: "https://host.test/api/assets/image.png", - }); - }, -); - -it("hides host assets with a denied grant while preserving attachments", () => { - state.session = { authenticated: true, scopes: [] }; - expect(useAssetUrlState(environmentId, resource)).toEqual({ - _tag: "Failure", - reason: "missing-file-access", - }); - expect(state.assetQuery).not.toHaveBeenCalled(); - expect(useAssetUrlState(environmentId, { _tag: "attachment", attachmentId: "upload" })).toEqual({ - _tag: "Success", - expiresAt: 1, - url: "https://host.test/api/assets/image.png", - }); -}); - -it("stops waiting for an unresolved grant when the connection is offline", () => { - state.phase = "offline"; - expect(useAssetUrlState(environmentId, resource)).toEqual({ _tag: "Failure" }); - expect(state.assetQuery).not.toHaveBeenCalled(); -}); - -it("lets the server authorize an explicit refresh before the client grant loads", async () => { - await expect(useAssetUrlRefresh(environmentId, resource)()).resolves.toBe( - "https://host.test/api/assets/image.png", - ); - expect(state.mint).toHaveBeenCalledWith({ environmentId, input: { resource } }); - - const denied = new EnvironmentAuthorizationError({ - message: "This connection cannot read host files.", - requiredScope: AuthFilesystemReadScope, - }); - state.mint.mockResolvedValue(AsyncResult.failure(Cause.fail(denied))); - await expect(useAssetUrlRefresh(environmentId, resource)()).rejects.toBe(denied); -}); diff --git a/apps/web/src/assets/assetUrls.ts b/apps/web/src/assets/assetUrls.ts index 1c77e91f7acea..38a282279f8f0 100644 --- a/apps/web/src/assets/assetUrls.ts +++ b/apps/web/src/assets/assetUrls.ts @@ -1,6 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import { - type AssetUrlState, + type AssetUrlState as RuntimeAssetUrlState, assetUrlStateFromResult, blockedAssetUrlState, EMPTY_ASSET_URL_ATOM, @@ -15,7 +15,9 @@ import { useFilesystemReadAccess } from "~/state/filesystem"; import { usePreparedConnection } from "~/state/session"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; -export { resolveAssetUrl, type AssetUrlState } from "@t3tools/client-runtime/state/assets"; +export { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; + +export type AssetUrlState = RuntimeAssetUrlState & { readonly waiting?: boolean }; export function useAssetUrlState( environmentId: EnvironmentId | null, @@ -29,10 +31,13 @@ export function useAssetUrlState( : assetEnvironment.createUrl({ environmentId, input: { resource } }), ); if (blocked !== null) return blocked; - return assetUrlStateFromResult( - result, - preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null, - ); + return { + ...assetUrlStateFromResult( + result, + preparedConnection._tag === "Some" ? preparedConnection.value.httpBaseUrl : null, + ), + ...(result.waiting ? { waiting: true } : {}), + }; } export function useAssetUrlRefresh( diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts index 6add5c1856e7d..65c6f8edd3424 100644 --- a/apps/web/src/authBootstrap.test.ts +++ b/apps/web/src/authBootstrap.test.ts @@ -8,11 +8,10 @@ import { import { createBrowserHistory } from "@tanstack/react-router"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import { HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { installEnvironmentHttpTest } from "../test/environmentHttpTest"; -import { __setPrimaryHttpRunnerForTests, type PrimaryHttpEffectRunner } from "./lib/runtime"; +import { __setPrimaryHttpRunnerForTests } from "./lib/runtime"; type TestWindow = { location: URL; @@ -77,21 +76,6 @@ function installTestBrowser(url: string) { return testWindow; } -function installDesktopBootstrap() { - const testWindow = installTestBrowser("http://localhost/"); - testWindow.desktopBridge = { - getLocalEnvironmentBootstraps: () => [ - { - id: "primary", - label: "Local environment", - httpBaseUrl: "http://localhost:3773", - wsBaseUrl: "ws://localhost:3773", - bootstrapToken: "desktop-bootstrap-token", - }, - ], - } as unknown as DesktopBridge; -} - function sequence(...values: ReadonlyArray) { let index = 0; return () => values[Math.min(index++, values.length - 1)]!; @@ -181,108 +165,6 @@ describe("resolveInitialServerAuthGateState", () => { expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]); }); - it("uses https urls when the primary environment uses wss", async () => { - await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) }); - vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com"); - vi.stubEnv("VITE_WS_URL", "wss://remote.example.com"); - - const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } = - await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "requires-auth", - auth: LOOPBACK_AUTH, - }); - expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe( - "https://remote.example.com/api/auth/session", - ); - }); - - it("uses the current origin as an auth proxy base for local dev environments", async () => { - await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) }); - installTestBrowser("http://localhost:5735/"); - - const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } = - await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "requires-auth", - auth: LOOPBACK_AUTH, - }); - expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe( - "http://localhost:5735/api/auth/session", - ); - }); - - it("uses the vite proxy for desktop-managed loopback auth requests during local dev", async () => { - await installAuthApi({ session: () => unauthenticatedSession(DESKTOP_AUTH) }); - vi.stubEnv("VITE_DEV_SERVER_URL", "http://127.0.0.1:5733"); - - const testWindow = installTestBrowser("http://127.0.0.1:5733/"); - testWindow.desktopBridge = { - getLocalEnvironmentBootstraps: () => [ - { - id: "primary", - label: "Windows", - httpBaseUrl: "http://127.0.0.1:3773", - wsBaseUrl: "ws://127.0.0.1:3773", - }, - ], - } as unknown as DesktopBridge; - - const { resolveInitialServerAuthGateState, resolvePrimaryEnvironmentHttpUrl } = - await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "requires-auth", - auth: DESKTOP_AUTH, - }); - expect(resolvePrimaryEnvironmentHttpUrl("/api/auth/session")).toBe( - "http://127.0.0.1:5733/api/auth/session", - ); - }); - - it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => { - await installAuthApi({ session: () => unauthenticatedSession(LOOPBACK_AUTH) }); - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "requires-auth", - auth: LOOPBACK_AUTH, - }); - }); - - it("retries transient auth session bootstrap failures after restart", async () => { - vi.useFakeTimers(); - let attempts = 0; - const request = HttpClientRequest.get("http://localhost/api/auth/session"); - const response = HttpClientResponse.fromWeb( - request, - new Response("Bad Gateway", { status: 502 }), - ); - const runner: PrimaryHttpEffectRunner = async () => { - attempts += 1; - if (attempts < 4) { - throw new HttpClientError.HttpClientError({ - reason: new HttpClientError.StatusCodeError({ request, response }), - }); - } - return unauthenticatedSession(LOOPBACK_AUTH) as A; - }; - __setPrimaryHttpRunnerForTests(runner); - - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - const gateStatePromise = resolveInitialServerAuthGateState(); - await vi.advanceTimersByTimeAsync(2_000); - - await expect(gateStatePromise).resolves.toEqual({ - status: "requires-auth", - auth: LOOPBACK_AUTH, - }); - expect(attempts).toBe(4); - }); - it("takes a pairing token from the location hash and strips it immediately", async () => { const testWindow = installTestBrowser("http://localhost/#token=pairing-token"); const { takePairingTokenFromUrl } = await import("./environments/primary"); @@ -292,14 +174,6 @@ describe("resolveInitialServerAuthGateState", () => { expect(testWindow.location.searchParams.get("token")).toBeNull(); }); - it("accepts query-string pairing tokens as a backward-compatible fallback", async () => { - const testWindow = installTestBrowser("http://localhost/?token=pairing-token"); - const { takePairingTokenFromUrl } = await import("./environments/primary"); - - expect(takePairingTokenFromUrl()).toBe("pairing-token"); - expect(testWindow.location.searchParams.get("token")).toBeNull(); - }); - it.each([ { suffix: "#token=replacement-token", cached: false }, { suffix: "#token=replacement-token", cached: true }, @@ -404,8 +278,7 @@ describe("resolveInitialServerAuthGateState", () => { const requiresAuth = { status: "requires-auth", auth: LOOPBACK_AUTH }; await expect(resolveInitialServerAuthGateState()).resolves.toEqual(requiresAuth); - // The pairing form strips the token before submitting. TanStack history - // reloads the auth gate synchronously when replaceState runs. + // Token removal synchronously reloads the TanStack auth gate via replaceState. const token = takePairingTokenFromUrl(); expect(gateLoads).toHaveLength(1); await expect(gateLoads[0]).resolves.toEqual(requiresAuth); @@ -433,261 +306,6 @@ describe("resolveInitialServerAuthGateState", () => { }, ); - it("allows manual token submission after the initial auth check requires pairing", async () => { - const nextSession = sequence( - unauthenticatedSession(LOOPBACK_AUTH), - authenticatedSession(LOOPBACK_AUTH), - ); - const testApi = await installAuthApi({ - session: nextSession, - browserSession: () => Effect.succeed(browserSession(["orchestration:read"])), - }); - const { resolveInitialServerAuthGateState, submitServerAuthCredential } = - await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "requires-auth", - auth: LOOPBACK_AUTH, - }); - await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined(); - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "authenticated", - }); - expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]); - expect(testApi.calls.session).toBe(2); - }); - - it("keeps manual token submission pending until the session is authenticated", async () => { - vi.useFakeTimers(); - let authenticated = false; - let settled = false; - try { - const testApi = await installAuthApi({ - session: () => - authenticated - ? authenticatedSession(LOOPBACK_AUTH) - : unauthenticatedSession(LOOPBACK_AUTH), - browserSession: () => Effect.succeed(browserSession(["orchestration:read"])), - }); - const { submitServerAuthCredential } = await import("./environments/primary"); - - const submission = submitServerAuthCredential("retry-token").finally(() => { - settled = true; - }); - await vi.advanceTimersByTimeAsync(0); - - expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]); - expect(testApi.calls.session).toBe(1); - expect(settled).toBe(false); - - authenticated = true; - await vi.advanceTimersByTimeAsync(100); - await expect(submission).resolves.toBeUndefined(); - expect(testApi.calls.session).toBe(2); - } finally { - vi.useRealTimers(); - } - }); - - it("fails manual token submission when the session is not established", async () => { - vi.useFakeTimers(); - try { - const testApi = await installAuthApi({ - session: () => unauthenticatedSession(LOOPBACK_AUTH), - browserSession: () => Effect.succeed(browserSession(["orchestration:read"])), - }); - const { PrimaryEnvironmentAuthSessionTimeoutError, submitServerAuthCredential } = - await import("./environments/primary/auth"); - - const submission = submitServerAuthCredential("retry-token"); - const failure = submission.then( - () => null, - (error: unknown) => error, - ); - await vi.advanceTimersByTimeAsync(2_000); - - await expect(failure).resolves.toBeInstanceOf(PrimaryEnvironmentAuthSessionTimeoutError); - expect(testApi.calls.browserSession).toEqual([{ credential: "retry-token" }]); - expect(testApi.calls.session).toBeGreaterThan(1); - } finally { - vi.useRealTimers(); - } - }); - - it("rejects a blank pairing token with a structured validation error", async () => { - const { PrimaryEnvironmentPairingCredentialRequiredError, submitServerAuthCredential } = - await import("./environments/primary/auth"); - - const error = await submitServerAuthCredential(" ").then( - () => null, - (failure: unknown) => failure, - ); - - expect(error).toBeInstanceOf(PrimaryEnvironmentPairingCredentialRequiredError); - expect(error).toMatchObject({ - _tag: "PrimaryEnvironmentPairingCredentialRequiredError", - providedLength: 3, - message: "Enter a pairing token to continue.", - }); - }); - - it("surfaces a friendly error message when an invalid pairing token is submitted", async () => { - const cause = new EnvironmentAuthInvalidError({ - code: "auth_invalid", - reason: "invalid_credential", - traceId: "trace-invalid-credential", - }); - const testApi = await installAuthApi({ - browserSession: () => Effect.fail(cause), - }); - - const { isPrimaryEnvironmentPairingCredentialRejectedError, submitServerAuthCredential } = - await import("./environments/primary"); - - const error = await submitServerAuthCredential("bad-token").then( - () => null, - (failure: unknown) => failure, - ); - expect(error).toMatchObject({ - _tag: "PrimaryEnvironmentPairingCredentialRejectedError", - providedLength: 9, - message: "Invalid pairing token. Check the token and try again.", - }); - expect(isPrimaryEnvironmentPairingCredentialRejectedError(error)).toBe(true); - if (!isPrimaryEnvironmentPairingCredentialRejectedError(error)) { - throw new Error("Expected a structured rejected pairing credential error."); - } - expect(error.cause).toMatchObject({ - _tag: "EnvironmentAuthInvalidError", - code: "auth_invalid", - reason: "invalid_credential", - traceId: "trace-invalid-credential", - }); - expect(testApi.calls.browserSession).toEqual([{ credential: "bad-token" }]); - }); - - it("derives primary request messages from structural request context", async () => { - const cause = new Error("private transport detail"); - const { PrimaryEnvironmentRequestError } = await import("./environments/primary"); - const error = PrimaryEnvironmentRequestError.fromCause({ - operation: "list-pairing-links", - cause, - }); - - expect(error.status).toBe(500); - expect(error.cause).toBe(cause); - expect(error.message).toBe( - "Primary environment request failed during list-pairing-links (HTTP 500).", - ); - expect(error.message).not.toContain(cause.message); - }); - - it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => { - vi.useFakeTimers(); - const nextSession = sequence( - unauthenticatedSession(DESKTOP_AUTH), - unauthenticatedSession(DESKTOP_AUTH), - authenticatedSession(DESKTOP_AUTH), - ); - const testApi = await installAuthApi({ - session: nextSession, - browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])), - }); - - const testWindow = installTestBrowser("http://localhost/"); - testWindow.desktopBridge = { - getLocalEnvironmentBootstraps: () => [ - { - id: "primary", - label: "Windows", - httpBaseUrl: "http://localhost:3773", - wsBaseUrl: "ws://localhost:3773", - bootstrapToken: "desktop-bootstrap-token", - }, - ], - } as unknown as DesktopBridge; - - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - const gateStatePromise = resolveInitialServerAuthGateState(); - await vi.advanceTimersByTimeAsync(100); - - await expect(gateStatePromise).resolves.toEqual({ status: "authenticated" }); - expect(testApi.calls.session).toBe(3); - }); - - it("preserves the timeout message when a bootstrapped session never becomes observable", async () => { - vi.useFakeTimers(); - const testApi = await installAuthApi({ - session: () => unauthenticatedSession(DESKTOP_AUTH), - browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])), - }); - - installDesktopBootstrap(); - - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - const gateStatePromise = resolveInitialServerAuthGateState(); - await vi.advanceTimersByTimeAsync(2_000); - - await expect(gateStatePromise).resolves.toEqual({ - status: "requires-auth", - auth: DESKTOP_AUTH, - errorMessage: "Timed out waiting for authenticated session after bootstrap.", - }); - expect(testApi.calls.browserSession).toEqual([{ credential: "desktop-bootstrap-token" }]); - }); - - it("memoizes the authenticated gate state after the first successful read", async () => { - const testApi = await installAuthApi({ - session: sequence(authenticatedSession(LOOPBACK_AUTH), unauthenticatedSession(LOOPBACK_AUTH)), - }); - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "authenticated", - }); - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "authenticated", - }); - expect(testApi.calls.session).toBe(1); - }); - - it("exchanges a URL token when the browser already has a session", async () => { - const testApi = await installAuthApi({ - session: () => authenticatedSession(LOOPBACK_AUTH), - browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])), - }); - const testWindow = installTestBrowser("http://localhost/#token=reusable-token"); - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "authenticated", - }); - - expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]); - expect(testWindow.location.hash).toBe(""); - }); - - it("exchanges a root URL token after caching an authenticated state", async () => { - const testApi = await installAuthApi({ - session: () => authenticatedSession(LOOPBACK_AUTH), - browserSession: () => Effect.succeed(browserSession(["orchestration:read", "access:write"])), - }); - const testWindow = installTestBrowser("http://localhost/"); - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "authenticated", - }); - testWindow.location = new URL("http://localhost/#token=reusable-token"); - - await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]); - - expect(testApi.calls.browserSession).toEqual([{ credential: "reusable-token" }]); - expect(testApi.calls.session).toBe(3); - }); - it("makes later callers wait for a URL token that arrives during bootstrap", async () => { let releaseExchange!: () => void; const exchangeRelease = new Promise((resolve) => { @@ -749,20 +367,6 @@ describe("resolveInitialServerAuthGateState", () => { expect(testApi.calls.session).toBe(2); }); - it("does not exchange a token during an ordinary authenticated load", async () => { - const testApi = await installAuthApi({ - session: () => authenticatedSession(LOOPBACK_AUTH), - browserSession: () => Effect.succeed(browserSession(["orchestration:read"])), - }); - const { resolveInitialServerAuthGateState } = await import("./environments/primary"); - - await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ - status: "authenticated", - }); - - expect(testApi.calls.browserSession).toEqual([]); - }); - it("reports a rejected URL token without caching false success", async () => { const cause = new EnvironmentAuthInvalidError({ code: "auth_invalid", @@ -791,31 +395,4 @@ describe("resolveInitialServerAuthGateState", () => { }); expect(testApi.calls.browserSession).toEqual([{ credential: "rejected-token" }]); }); - - it("creates a pairing credential from the authenticated auth endpoint", async () => { - const testApi = await installAuthApi({ - pairingCredential: (payload) => - Effect.succeed({ - id: "pairing-link-1", - credential: "pairing-token", - ...(payload.label === undefined ? {} : { label: payload.label }), - expiresAt: SESSION_EXPIRES_AT, - }), - }); - const { createServerPairingCredential } = await import("./environments/primary"); - - const credential = await createServerPairingCredential({ - label: "Julius iPhone", - scopes: ["orchestration:read"], - }); - expect(credential).toMatchObject({ - id: "pairing-link-1", - credential: "pairing-token", - label: "Julius iPhone", - }); - expect(DateTime.formatIso(credential.expiresAt)).toBe("2026-04-05T00:00:00.000Z"); - expect(testApi.calls.pairingCredential).toEqual([ - { label: "Julius iPhone", scopes: ["orchestration:read"] }, - ]); - }); }); diff --git a/apps/web/src/bootstrap.test.ts b/apps/web/src/bootstrap.test.ts deleted file mode 100644 index c5c0d89597aa3..0000000000000 --- a/apps/web/src/bootstrap.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; - -import { showBootError } from "./lib/bootError"; - -class BootElement extends EventTarget { - children: BootElement[] = []; - textContent = ""; - - constructor(readonly tagName: string) { - super(); - } - - setAttribute() {} - - append(child: BootElement) { - this.children.push(child); - } - - replaceChildren(...children: BootElement[]) { - this.children = children; - } - - get text(): string { - return this.textContent + this.children.map((child) => child.text).join(" "); - } -} - -describe("app startup failures", () => { - let bootShell: BootElement | null; - - beforeEach(() => { - vi.resetModules(); - bootShell = new BootElement("div"); - vi.stubGlobal("document", { - getElementById: () => bootShell, - createElement: (tagName: string) => new BootElement(tagName), - }); - vi.spyOn(console, "error").mockImplementation(() => {}); - }); - - it("shows failures from asynchronous app startup", async () => { - vi.doMock("./main", () => ({ startup: Promise.reject(new Error("Startup chunks failed")) })); - - await import("./bootstrap"); - await vi.dynamicImportSettled(); - - expect(bootShell?.text).toContain("Startup chunks failed"); - }); - - afterEach(() => { - vi.doUnmock("./main"); - vi.unstubAllGlobals(); - vi.unstubAllEnvs(); - vi.restoreAllMocks(); - }); - - it("replaces the splash when an app import throws before main can run", async () => { - vi.doMock("./main", () => { - throw new Error("@vitejs/plugin-react can't detect preamble. Something is wrong."); - }); - const reload = vi.fn(); - vi.stubGlobal("window", { location: { reload } }); - - await import("./bootstrap"); - await vi.dynamicImportSettled(); - - expect(bootShell?.text).toContain("T3 Code could not load."); - const reloadButton = bootShell?.children[0]?.children.find( - (element) => element.tagName === "button", - ); - expect(reloadButton?.text).toBe("Reload"); - reloadButton?.dispatchEvent(new Event("click")); - expect(reload).toHaveBeenCalledOnce(); - }); - - it.each([true, false])("shows startup error details only in dev mode, DEV=%s", (dev) => { - vi.stubEnv("DEV", dev); - - showBootError(new Error("internal module path")); - - expect(bootShell?.text).toContain("T3 Code could not load."); - expect(bootShell?.text.includes("internal module path")).toBe(dev); - }); - - it("does not replace the app after React removes the splash", () => { - bootShell = null; - const createElement = vi.spyOn(document, "createElement"); - - showBootError(new Error("late failure")); - - expect(createElement).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/web/src/bootstrap.ts b/apps/web/src/bootstrap.ts index 9a3d4a03b3caf..b6f422c5d68f4 100644 --- a/apps/web/src/bootstrap.ts +++ b/apps/web/src/bootstrap.ts @@ -1,5 +1,4 @@ import { showBootError } from "./lib/bootError"; -// Bundled dev can move UI code into shared chunks. Load it only after this -// entry runs the React refresh preamble, and catch failures before React mounts. +// Shared dev chunks need the React refresh preamble first. Catch failures before React mounts. void import("./main").then(({ startup }) => startup).catch(showBootError); diff --git a/apps/web/src/branding.test.ts b/apps/web/src/branding.test.ts deleted file mode 100644 index e1c87bcf0595e..0000000000000 --- a/apps/web/src/branding.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { - resolveServerBackedAppDisplayName, - resolveServerBackedAppStageLabel, -} from "./branding.logic"; - -const originalWindow = globalThis.window; - -afterEach(() => { - vi.resetModules(); - - if (originalWindow === undefined) { - Reflect.deleteProperty(globalThis, "window"); - return; - } - - globalThis.window = originalWindow; -}); - -describe("branding", () => { - it("uses injected desktop branding when available", async () => { - Object.defineProperty(globalThis, "window", { - configurable: true, - value: { - desktopBridge: { - getAppBranding: () => ({ - baseName: "T3 Code", - stageLabel: "Nightly", - displayName: "T3 Code (Nightly)", - }), - }, - }, - }); - - const branding = await import("./branding"); - - expect(branding.APP_BASE_NAME).toBe("T3 Code"); - expect(branding.APP_STAGE_LABEL).toBe("Nightly"); - expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)"); - }); - - it("normalizes hosted app channel metadata", async () => { - vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "nightly"); - - const branding = await import("./branding"); - - expect(branding.HOSTED_APP_CHANNEL).toBe("nightly"); - expect(branding.HOSTED_APP_CHANNEL_LABEL).toBe("Nightly"); - expect(branding.APP_STAGE_LABEL).toBe("Nightly"); - expect(branding.APP_DISPLAY_NAME).toBe("T3 Code (Nightly)"); - }); - - it("does not label the latest hosted app channel", async () => { - vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "latest"); - - const branding = await import("./branding"); - - expect(branding.HOSTED_APP_CHANNEL).toBe("latest"); - expect(branding.HOSTED_APP_CHANNEL_LABEL).toBe("Latest"); - expect(branding.APP_STAGE_LABEL).toBe("Latest"); - expect(branding.APP_DISPLAY_NAME).toBe("T3 Code"); - }); - - it("ignores unknown hosted app channels", async () => { - vi.stubEnv("VITE_HOSTED_APP_CHANNEL", "preview"); - - const branding = await import("./branding"); - - expect(branding.HOSTED_APP_CHANNEL).toBeNull(); - expect(branding.HOSTED_APP_CHANNEL_LABEL).toBeNull(); - }); -}); - -describe("branding logic", () => { - it("returns Nightly for nightly primary server versions", () => { - expect( - resolveServerBackedAppStageLabel({ - primaryServerVersion: "0.0.28-nightly.20260616.12", - fallbackStageLabel: "Alpha", - }), - ).toBe("Nightly"); - }); - - it("updates the display name for nightly primary server versions", () => { - expect( - resolveServerBackedAppDisplayName({ - baseName: "T3 Code", - fallbackDisplayName: "T3 Code (Alpha)", - fallbackStageLabel: "Alpha", - primaryServerVersion: "0.0.28-nightly.20260616.12", - }), - ).toBe("T3 Code (Nightly)"); - }); - - it("keeps the fallback display name for stable primary server versions", () => { - expect( - resolveServerBackedAppDisplayName({ - baseName: "T3 Code", - fallbackDisplayName: "T3 Code (Alpha)", - fallbackStageLabel: "Alpha", - primaryServerVersion: "0.0.27", - }), - ).toBe("T3 Code (Alpha)"); - }); - - it("keeps the fallback display name for malformed nightly primary server versions", () => { - expect( - resolveServerBackedAppDisplayName({ - baseName: "T3 Code", - fallbackDisplayName: "T3 Code (Alpha)", - fallbackStageLabel: "Alpha", - primaryServerVersion: "0.0.28-nightly.20260616", - }), - ).toBe("T3 Code (Alpha)"); - }); -}); diff --git a/apps/web/src/branding.ts b/apps/web/src/branding.ts index 528609d36e608..7d14e2cea858b 100644 --- a/apps/web/src/branding.ts +++ b/apps/web/src/branding.ts @@ -25,3 +25,4 @@ export const APP_DISPLAY_NAME = injectedDesktopAppBranding?.displayName ?? formatAppDisplayName({ baseName: APP_BASE_NAME, stageLabel: APP_STAGE_LABEL }); export const APP_VERSION = import.meta.env.APP_VERSION || "0.0.0"; +export const DESKTOP_DOWNLOAD_URL = "https://t3.codes/download"; diff --git a/apps/web/src/browser/BrowserDeviceToolbar.test.ts b/apps/web/src/browser/BrowserDeviceToolbar.test.ts deleted file mode 100644 index 087b5d109b40c..0000000000000 --- a/apps/web/src/browser/BrowserDeviceToolbar.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { PreviewViewportSetting } from "@t3tools/contracts"; -import { describe, expect, it, vi } from "vite-plus/test"; - -import { commitViewportAndAspectRatio } from "./browserDeviceToolbarState"; - -describe("commitViewportAndAspectRatio", () => { - it("commits the aspect ratio only after the viewport succeeds", async () => { - let resolveChange: (() => void) | undefined; - const onChange = vi.fn( - () => - new Promise((resolve) => { - resolveChange = resolve; - }), - ); - const onAspectRatioChange = vi.fn(); - const setting: PreviewViewportSetting = { _tag: "freeform", width: 900, height: 600 }; - - const commit = commitViewportAndAspectRatio(setting, 1.5, onChange, onAspectRatioChange); - expect(onAspectRatioChange).not.toHaveBeenCalled(); - - resolveChange?.(); - await commit; - expect(onAspectRatioChange).toHaveBeenCalledWith(1.5); - }); - - it("keeps the previous aspect ratio when the viewport commit fails", async () => { - const onAspectRatioChange = vi.fn(); - await expect( - commitViewportAndAspectRatio( - { _tag: "fill" }, - null, - async () => Promise.reject(new Error("resize failed")), - onAspectRatioChange, - ), - ).rejects.toThrow("resize failed"); - expect(onAspectRatioChange).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/web/src/browser/BrowserDeviceToolbar.tsx b/apps/web/src/browser/BrowserDeviceToolbar.tsx index 390c77de4424f..dd5b707cfebdb 100644 --- a/apps/web/src/browser/BrowserDeviceToolbar.tsx +++ b/apps/web/src/browser/BrowserDeviceToolbar.tsx @@ -1,5 +1,3 @@ -"use client"; - import { PREVIEW_VIEWPORT_MAX_AREA, PREVIEW_VIEWPORT_MAX_DIMENSION, @@ -308,7 +306,6 @@ export function BrowserDeviceToolbar({ > - {/* Sticky backing so scrolled controls do not show through the close action. */}