diff --git a/.github/actions/record-build-tag/action.yml b/.github/actions/record-build-tag/action.yml index 2086d004b295c..b38d5136e51ca 100644 --- a/.github/actions/record-build-tag/action.yml +++ b/.github/actions/record-build-tag/action.yml @@ -8,6 +8,9 @@ inputs: message: description: Annotated tag message; empty makes a lightweight tag default: "" + commit: + description: Commit to tag, 40 hex characters and reachable from the workflow's ref; empty tags HEAD + default: "" replace: description: "true replaces an existing tag; otherwise an existing tag counts as recorded" default: "false" @@ -22,6 +25,7 @@ runs: shell: bash env: TAG: ${{ inputs.tag }} + COMMIT: ${{ inputs.commit }} MESSAGE: ${{ inputs.message }} REPLACE: ${{ inputs.replace }} GH_TOKEN: ${{ inputs.token }} @@ -29,9 +33,19 @@ runs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" remote="https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" + if [ -n "$COMMIT" ] && ! [[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::The commit to tag is not a full SHA." + exit 1 + fi # GitHub occasionally fails ref writes server-side ("fatal error in commit_refs"). for attempt in 1 2 3; do - if refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then + if { [ -z "$COMMIT" ] || git fetch --quiet "$remote" "$GITHUB_REF"; } && + refs="$(git ls-remote "$remote" "refs/tags/$TAG")"; then + # A named commit is tagged only when it is on the ref this workflow runs for. + if [ -n "$COMMIT" ] && ! git merge-base --is-ancestor "$COMMIT" FETCH_HEAD 2>/dev/null; then + echo "::error::$COMMIT is not on $GITHUB_REF." + exit 1 + fi old="$(printf '%s\n' "$refs" | while read -r sha ref; do if [ "$ref" = "refs/tags/$TAG" ]; then echo "$sha"; fi done)" @@ -40,9 +54,9 @@ runs: exit 0 fi if [ -n "$MESSAGE" ]; then - git tag -f -a "$TAG" -m "$MESSAGE" + git tag -f -a "$TAG" -m "$MESSAGE" ${COMMIT:+"$COMMIT"} else - git tag -f "$TAG" + git tag -f "$TAG" ${COMMIT:+"$COMMIT"} fi # An empty lease means the tag must not exist yet. if git push --force-with-lease="refs/tags/$TAG:$old" "$remote" "refs/tags/$TAG"; then diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index cc6dc80511aca..b2236f6a15cf8 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -31,14 +31,16 @@ runs: echo "node=$(jq -r '.engines.node' package.json)" >> "$GITHUB_OUTPUT" echo "pnpm=$(jq -r '.packageManager' package.json)" >> "$GITHUB_OUTPUT" + # Restore only: "Save Vite+" below writes the toolchain before this job + # installs or runs project code. # Pinned because release-desktop.yml signs builds with this action in the job. - - name: Cache Vite+ + - name: Restore Vite+ id: vp_cache if: steps.vp.outputs.version != '' - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: ~/.vite-plus - key: vite-plus-home-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.vp.outputs.version }}-node${{ steps.vp.outputs.node }}-${{ steps.vp.outputs.pnpm }} + key: vite-plus-home-v3-${{ 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 @@ -64,6 +66,19 @@ runs: cache: false run-install: false + # vp downloads pnpm on first use, which would otherwise be after the save. + - name: Fetch pnpm + if: steps.vp.outputs.version != '' && steps.vp_cache.outputs.cache-hit != 'true' + shell: bash + run: vp pm cache dir + + - name: Save Vite+ + if: steps.vp.outputs.version != '' && steps.vp_cache.outputs.cache-hit != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ~/.vite-plus + key: ${{ steps.vp_cache.outputs.cache-primary-key }} + # A shared key lets whichever install saves first, often a small filtered # one, become every job's store. Each set of install args gets its own. - name: Resolve pnpm store diff --git a/.github/scripts/set-mobile-version.cjs b/.github/scripts/set-mobile-version.cjs new file mode 100644 index 0000000000000..bb45a524ed357 --- /dev/null +++ b/.github/scripts/set-mobile-version.cjs @@ -0,0 +1,30 @@ +const fs = require("node:fs"); + +const CONFIG_PATH = "apps/mobile/app.config.ts"; +const VERSION_LINE = /^( {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? ")[^"]+(".*)$/m; + +// Replaces one string literal, so the result needs no formatter. +function setMobileVersion(source, version) { + if (!/^[0-9]+(\.[0-9]+){1,2}$/.test(version)) { + throw new Error( + `Version override must contain two or three dot-separated integers; received '${version}'.`, + ); + } + if (!VERSION_LINE.test(source)) throw new Error("Could not update app version"); + return source.replace(VERSION_LINE, `$1${version}$2`); +} + +if (require.main === module) { + const { GITHUB_REF_TYPE, GITHUB_REF_NAME } = process.env; + if (GITHUB_REF_TYPE !== "branch") { + throw new Error( + `Version overrides require dispatching this workflow from a branch; received ${GITHUB_REF_TYPE} '${GITHUB_REF_NAME}'.`, + ); + } + fs.writeFileSync( + CONFIG_PATH, + setMobileVersion(fs.readFileSync(CONFIG_PATH, "utf8"), process.argv[2] ?? ""), + ); +} + +module.exports = { setMobileVersion }; diff --git a/.github/scripts/set-release-version.cjs b/.github/scripts/set-release-version.cjs new file mode 100644 index 0000000000000..1a15e2f81475a --- /dev/null +++ b/.github/scripts/set-release-version.cjs @@ -0,0 +1,31 @@ +const fs = require("node:fs"); + +// The manifests in scripts/lib/tagged-source-version.ts. +const RELEASE_PACKAGE_FILES = [ + "apps/server/package.json", + "apps/desktop/package.json", + "apps/web/package.json", + "packages/contracts/package.json", +]; +const VERSION_LINE = /^( {2}"version": ")[^"]*(",?)$/gm; + +// Replaces one string literal, so the result needs no formatter and no dependencies. +function setReleaseVersion(source, version) { + if (!/^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$/.test(version)) { + throw new Error(`Invalid release version: '${version}'.`); + } + if (source.match(VERSION_LINE)?.length !== 1) { + throw new Error("Expected exactly one top-level version in the manifest"); + } + return source.replace(VERSION_LINE, `$1${version}$2`); +} + +if (require.main === module) { + for (const file of RELEASE_PACKAGE_FILES) { + const source = fs.readFileSync(file, "utf8"); + const next = setReleaseVersion(source, process.argv[2] ?? ""); + if (next !== source) fs.writeFileSync(file, next); + } +} + +module.exports = { RELEASE_PACKAGE_FILES, setReleaseVersion }; diff --git a/.github/scripts/vercel-deployment-output.test.cjs b/.github/scripts/vercel-deployment-output.test.cjs index a249653350f22..b5a3ea7b94471 100644 --- a/.github/scripts/vercel-deployment-output.test.cjs +++ b/.github/scripts/vercel-deployment-output.test.cjs @@ -8,7 +8,7 @@ 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; + / name: (?:Build staged deployment|Deploy preview)\n shell: bash\n(?: env:\n(?: .*\n)+)? run: \|\n((?: .*\n|\n)+)/g; const steps = [ ...Array.from(release.matchAll(stepPattern), (match, index) => [ index === 0 ? "hosted web" : "marketing", diff --git a/.github/scripts/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs new file mode 100644 index 0000000000000..35d0c5bf56e73 --- /dev/null +++ b/.github/scripts/workflow-credentials.test.cjs @@ -0,0 +1,344 @@ +const assert = require("node:assert/strict"); +const { execFileSync, spawnSync } = require("node:child_process"); +const { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} = require("node:fs"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const { test } = require("node:test"); + +const { setMobileVersion } = require("./set-mobile-version.cjs"); +const { RELEASE_PACKAGE_FILES, setReleaseVersion } = require("./set-release-version.cjs"); + +const read = (path) => readFileSync(join(__dirname, "..", path), "utf8"); + +function jobs(path) { + const body = read(path).split(/^jobs:\n/m)[1]; + const found = {}; + for (const block of body.split(/^(?= [\w-]+:\n)/m)) { + const name = /^ ([\w-]+):\n/.exec(block)?.[1]; + if (name) found[name] = block; + } + return found; +} + +const steps = (block) => block.split(/^ {4,6}- /m).slice(1); +const runsProjectCode = (block) => + /setup-vp@|setup-ci-deps|eas-local-build|expo-github-action|\b(?:vp|pnpm|npm|npx|eas) /.test( + block, + ); + +test("npm publishing is bound to the environment that admits only main and v* tags", () => { + const publish = jobs("workflows/release.yml").publish_cli; + assert.match(publish, /^ {6}id-token: write$/m); + assert.match(publish, /^ {4}environment: production$/m); +}); + +test("the web preview gives the Vercel token to the deploy step only, after an install without lifecycle scripts", () => { + const deploy = jobs("workflows/web-preview.yml").deploy; + assert.doesNotMatch(deploy.split(/^ {4}steps:\n/m)[0], /secrets\./); + const withSecrets = steps(deploy).filter((step) => step.includes("secrets.")); + assert.equal(withSecrets.length, 1); + assert.match(withSecrets[0], /name: Deploy preview/); + assert.match(deploy, /run-install: \|\n {12}args:\n {14}- --ignore-scripts\n/); +}); + +const mobileWorkflows = [ + "workflows/mobile-eas-preview.yml", + "workflows/mobile-eas-preview-build.yml", + "workflows/mobile-eas-production.yml", + "workflows/mobile-eas-production-build.yml", +]; + +for (const path of mobileWorkflows) { + test(`${path}: no job that installs or builds can push to the repository`, () => { + for (const [name, block] of Object.entries(jobs(path))) { + if (/^ {4}uses: /m.test(block)) continue; + const writes = /contents: write|write-all|record-build-tag|create-github-app-token/.test( + block, + ); + assert.match(block, /^ {4}permissions:\n/m, `${name} declares its permissions`); + assert.ok(!(writes && runsProjectCode(block)), `${name} holds a write token and runs code`); + } + }); +} + +test("the build record is pushed by the record job of each build workflow", () => { + for (const path of [ + "workflows/mobile-eas-preview-build.yml", + "workflows/mobile-eas-production-build.yml", + ]) { + const { record, ...builds } = jobs(path); + assert.match(record, /uses: \.\/\.github\/actions\/record-build-tag/); + assert.match(record, /^ {6}contents: write/m); + for (const block of Object.values(builds)) assert.match(block, /^ {6}contents: read$/m); + } +}); + +test("jobs that push run this workflow's own actions", () => { + for (const file of mobileWorkflows) { + for (const [name, block] of Object.entries(jobs(file))) { + if (!/contents: write|create-github-app-token/.test(block)) continue; + const jobSteps = steps(block); + const checkout = jobSteps.findIndex((step) => /^ +ref: .*\b(?:inputs|needs)\./m.test(step)); + if (checkout === -1) continue; + const local = jobSteps.slice(checkout).filter((step) => /^ +uses: \.\//m.test(step)); + assert.equal(local.length, 0, `${file} ${name} runs a local action from another checkout`); + } + } +}); + +const recordScript = read("actions/record-build-tag/action.yml") + .split(/^ {6}run: \|\n/m)[1] + .replace(/^ {8}/gm, "") + .replace(/^remote=.*$/m, 'remote="$TEST_REMOTE"'); + +function recordTag(commitOf, failedFetches = 0) { + const directory = mkdtempSync(join(tmpdir(), "t3-record-tag-")); + const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); + try { + const remote = join(directory, "remote.git"); + const work = join(directory, "work"); + git(directory, "init", "--quiet", "--bare", remote); + git(directory, "init", "--quiet", "--initial-branch=main", work); + const commit = (message) => { + git( + work, + "-c", + "user.name=t", + "-c", + "user.email=t@example.com", + "commit", + "--quiet", + "--allow-empty", + "-m", + message, + ); + return git(work, "rev-parse", "HEAD"); + }; + const shas = { first: commit("first") }; + shas.head = commit("second"); + git(work, "push", "--quiet", remote, "main"); + git(work, "checkout", "--quiet", "--detach"); + shas.elsewhere = commit("not on main"); + git(work, "push", "--quiet", remote, "HEAD:refs/heads/other"); + git(work, "checkout", "--quiet", "main"); + // The first fetches fail, and the waits between attempts are skipped. + const bin = join(directory, "bin"); + mkdirSync(bin); + writeFileSync( + join(bin, "git"), + `#!/bin/bash\nif [ "$1" = fetch ] && [ "$(wc -l < "$FETCHES")" -lt "$FAILED_FETCHES" ]; then echo x >> "$FETCHES"; exit 1; fi\nexec "$REAL_GIT" "$@"\n`, + ); + writeFileSync(join(bin, "sleep"), "#!/bin/bash\n"); + chmodSync(join(bin, "git"), 0o755); + chmodSync(join(bin, "sleep"), 0o755); + writeFileSync(join(directory, "fetches"), ""); + const result = spawnSync("bash", ["-c", recordScript], { + cwd: work, + encoding: "utf8", + env: { + PATH: `${bin}:${process.env.PATH}`, + REAL_GIT: execFileSync("bash", ["-c", "command -v git"], { encoding: "utf8" }).trim(), + FETCHES: join(directory, "fetches"), + FAILED_FETCHES: String(failedFetches), + HOME: directory, + TEST_REMOTE: remote, + GITHUB_REF: "refs/heads/main", + TAG: "build/1", + MESSAGE: "", + REPLACE: "false", + COMMIT: commitOf(shas), + }, + }); + const tagged = git(directory, "ls-remote", remote, "refs/tags/build/1").split(/\s/)[0]; + return { status: result.status, tagged, shas }; + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +test("the build record tags the named commit only when it is on the workflow's ref", () => { + const onRef = recordTag((shas) => shas.first); + assert.deepEqual([onRef.status, onRef.tagged], [0, onRef.shas.first]); + const retried = recordTag((shas) => shas.first, 2); + assert.deepEqual([retried.status, retried.tagged], [0, retried.shas.first]); + assert.equal(recordTag((shas) => shas.first, 3).status, 1); + const head = recordTag(() => ""); + assert.deepEqual([head.status, head.tagged], [0, head.shas.head]); + for (const commitOf of [(shas) => shas.elsewhere, () => "main", () => "0".repeat(40)]) { + const refused = recordTag(commitOf); + assert.deepEqual([refused.status, refused.tagged], [1, ""]); + } +}); + +test("the store build record job runs the workflow's own action and passes the built commit as data", () => { + const { record } = jobs("workflows/mobile-eas-production-build.yml"); + assert.doesNotMatch(record, /^ +ref: /m); + assert.match(record, /^ {10}commit: \$\{\{ inputs\.sha \}\}$/m); +}); + +test("release deploys give the Vercel token to the deploy step only", () => { + const all = jobs("workflows/release.yml"); + for (const name of ["build_web", "build_marketing"]) { + assert.doesNotMatch(all[name].split(/^ {4}steps:\n/m)[0], /secrets\.VERCEL/); + const withToken = steps(all[name]).filter((step) => step.includes("secrets.VERCEL_TOKEN")); + assert.equal(withToken.length, 1); + assert.match(withToken[0], /name: Build staged deployment/); + } +}); + +test("the version override token covers this repository only", () => { + const { version, production } = jobs("workflows/mobile-eas-production.yml"); + const mint = steps(version).find((step) => step.includes("create-github-app-token")); + assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m); + assert.match(mint, /^\s+permission-contents: write$/m); + assert.doesNotMatch(production, /RELEASE_APP|create-github-app-token/); +}); + +test("the release version bump is pushed by a job that installs nothing, with a token for this repository only", () => { + const { finalize } = jobs("workflows/release.yml"); + const mint = steps(finalize).find((step) => step.includes("create-github-app-token")); + assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m); + assert.match(mint, /^\s+permission-contents: write$/m); + assert.ok(!runsProjectCode(finalize), "finalize holds a write token and runs code"); + assert.match(finalize, /run: node \.github\/scripts\/set-release-version\.cjs /); +}); + +test("the Vite+ toolchain is cached before the job installs or runs project code", () => { + const names = Array.from( + read("actions/setup-ci-deps/action.yml").matchAll( + /^ {4}- name: (.+)\n(?: {6}.*\n)*? {6}uses: (\S+)|^ {4}- name: (.+)$/gm, + ), + (match) => ({ name: match[1] ?? match[3], uses: match[2] ?? "" }), + ); + const index = (name) => names.findIndex((step) => step.name === name); + assert.match(names[index("Restore Vite+")].uses, /^actions\/cache\/restore@/); + assert.match(names[index("Save Vite+")].uses, /^actions\/cache\/save@/); + assert.ok(index("Save Vite+") < index("Resolve pnpm store")); + assert.ok(index("Save Vite+") < index("Install dependencies")); + // The combined action saves at the end of the job, after everything ran. + assert.ok(names.every((step) => !step.uses.startsWith("actions/cache@"))); +}); + +const consumeScript = steps(jobs("workflows/mobile-eas-preview-fork.yml").preview) + .find((step) => step.startsWith("id: consume\n")) + .split(/^ {10}script: \|\n/m)[1] + .replace(/^ {12}/gm, ""); +const consume = new (Object.getPrototypeOf(async () => {}).constructor)( + "github", + "context", + "core", + consumeScript, +); + +async function runConsume(permission, removeStatus, removed = []) { + const outputs = {}; + await consume( + { + rest: { + repos: { + async getCollaboratorPermissionLevel({ username }) { + assert.equal(username, "labeler"); + if (permission === undefined) throw Object.assign(new Error("denied"), { status: 403 }); + return { data: { permission } }; + }, + }, + issues: { + async removeLabel(params) { + if (removeStatus) throw Object.assign(new Error("gone"), { status: removeStatus }); + removed.push(params.name); + }, + }, + }, + }, + { + repo: { owner: "example", repo: "app" }, + payload: { + sender: { login: "labeler" }, + label: { name: "deploy" }, + pull_request: { number: 7 }, + }, + }, + { info() {}, warning() {}, setOutput: (name, value) => (outputs[name] = value) }, + ); + return { outputs, removed }; +} + +for (const [permission, consumed] of [ + ["admin", "true"], + ["maintain", "true"], + ["write", "true"], + ["triage", "false"], + ["read", "false"], + ["none", "false"], +]) { + test(`a fork preview label from ${permission} access is removed and ${consumed === "true" ? "builds" : "builds nothing"}`, async () => { + assert.deepEqual(await runConsume(permission), { + outputs: { consumed }, + removed: ["deploy"], + }); + }); +} + +test("a fork preview label is removed even when the access lookup fails", async () => { + const removed = []; + await assert.rejects(runConsume(undefined, undefined, removed), { status: 403 }); + assert.deepEqual(removed, ["deploy"]); +}); + +test("a fork preview label removed before the run builds nothing", async () => { + assert.deepEqual(await runConsume("admin", 404), { outputs: { consumed: "false" }, removed: [] }); +}); + +test("a version override rewrites only the app version", () => { + const config = read("../apps/mobile/app.config.ts"); + const next = setMobileVersion(config, "9.8.7"); + assert.match(next, /^ {2}version: repoEnv\.T3CODE_MOBILE_VERSION \?\? "9\.8\.7",$/m); + assert.equal(setMobileVersion(next, "9.8.7"), next); + assert.deepEqual( + next.split("\n").filter((line, index) => line !== config.split("\n")[index]).length, + 1, + ); + for (const version of ["", "1", "1.2.3.4", "1.2-beta", '1.2", extra: "x']) { + assert.throws(() => setMobileVersion(config, version), /two or three dot-separated integers/); + } + assert.throws(() => setMobileVersion("export default {};", "1.2.3"), /Could not update/); +}); + +test("a release version bump rewrites only the version of each release manifest", () => { + const listed = /releasePackageFiles = \[\n([^\]]+)\]/.exec( + read("../scripts/lib/tagged-source-version.ts"), + )[1]; + assert.deepEqual( + RELEASE_PACKAGE_FILES, + Array.from(listed.matchAll(/"([^"]+)"/g), (m) => m[1]), + ); + for (const file of RELEASE_PACKAGE_FILES) { + const manifest = read(`../${file}`); + const next = setReleaseVersion(manifest, "98.7.6"); + assert.equal(JSON.parse(next).version, "98.7.6"); + assert.deepEqual( + { ...JSON.parse(next), version: "" }, + { ...JSON.parse(manifest), version: "" }, + ); + assert.equal(setReleaseVersion(next, "98.7.6"), next); + assert.deepEqual( + next.split("\n").filter((line, index) => line !== manifest.split("\n")[index]).length, + 1, + ); + } + for (const version of ["", "1", "1.2", "v1.2.3", '1.2.3", "x": "y']) { + assert.throws(() => setReleaseVersion('{\n "version": "1.0.0"\n}\n', version), /Invalid/); + } + assert.equal( + setReleaseVersion('{\n "version": "1.0.0"\n}\n', "1.2.3-rc.1"), + '{\n "version": "1.2.3-rc.1"\n}\n', + ); + assert.throws(() => setReleaseVersion('{\n "name": "x"\n}\n', "1.2.3"), /exactly one/); +}); diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4c0cfc691b37..70208c7a16479 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -339,7 +339,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 .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs + run: node --test .github/scripts/check-nightly-release.test.cjs .github/scripts/vercel-deployment-output.test.cjs .github/scripts/mobile-preview-comment.test.cjs .github/scripts/mobile-ios-preview-record.test.cjs .github/scripts/test-delta.test.cjs .github/scripts/workflow-credentials.test.cjs - name: Finish installing browser secret helper build libraries timeout-minutes: 5 diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index da779c2783d4c..bbe7054666b7e 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -16,7 +16,6 @@ on: permissions: contents: read id-token: none - statuses: write concurrency: group: relay-production @@ -29,6 +28,9 @@ jobs: if: github.repository == 'pingdotgg/t3code' && github.ref == 'refs/heads/main' runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 15 + permissions: + contents: read + statuses: write environment: name: production env: diff --git a/.github/workflows/issue-labels.yml b/.github/workflows/issue-labels.yml index fd9ba6b60302b..97ddab983015d 100644 --- a/.github/workflows/issue-labels.yml +++ b/.github/workflows/issue-labels.yml @@ -9,13 +9,14 @@ on: - .github/workflows/issue-labels.yml workflow_dispatch: -permissions: - issues: write +permissions: {} jobs: sync: name: Sync issue labels runs-on: ubuntu-24.04 + permissions: + issues: write steps: - name: Ensure managed issue labels exist uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 diff --git a/.github/workflows/issue-vouch.yml b/.github/workflows/issue-vouch.yml index d65882593c649..8a14d4cc41bba 100644 --- a/.github/workflows/issue-vouch.yml +++ b/.github/workflows/issue-vouch.yml @@ -13,7 +13,6 @@ on: permissions: contents: read - issues: write concurrency: group: issue-vouch-${{ github.event.issue.number || 'all' }} @@ -23,6 +22,9 @@ jobs: label: name: Label issues by author trust runs-on: ubuntu-24.04 + permissions: + contents: read + issues: write steps: - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 with: diff --git a/.github/workflows/mobile-android-apk.yml b/.github/workflows/mobile-android-apk.yml index 8650b5a6d527d..8e028821a685f 100644 --- a/.github/workflows/mobile-android-apk.yml +++ b/.github/workflows/mobile-android-apk.yml @@ -8,6 +8,9 @@ on: - cron: "23 * * * *" workflow_dispatch: +permissions: + contents: read + concurrency: group: mobile-android-apk cancel-in-progress: false diff --git a/.github/workflows/mobile-eas-preview-build.yml b/.github/workflows/mobile-eas-preview-build.yml new file mode 100644 index 0000000000000..d344daeb76718 --- /dev/null +++ b/.github/workflows/mobile-eas-preview-build.yml @@ -0,0 +1,201 @@ +name: Mobile EAS Preview Build + +# One preview client and its build record, called per platform by +# mobile-eas-preview.yml. The build job runs dependency and build scripts with a +# read-only token. Only the record job, on a fresh runner that runs none of +# them, gets the token that can push tags. The caller's concurrency group covers +# both jobs, so a build queued for the same fingerprint starts after the tag exists. + +on: + workflow_call: + inputs: + platform: + description: android or ios + required: true + type: string + fingerprint: + required: true + type: string + secrets: + EXPO_PREVIEW_TOKEN: + required: true + outputs: + client: + description: Install link for the client with this fingerprint + value: ${{ jobs.android.outputs.client || jobs.ios.outputs.client }} + +permissions: + contents: read + +jobs: + android: + name: Build + if: inputs.platform == 'android' + runs-on: blacksmith-32vcpu-ubuntu-2404 + timeout-minutes: 60 + permissions: + contents: read + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + # Set only by a new build: the tag message, which is the install link. + record: ${{ steps.build.outputs.link }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ inputs.fingerprint }} + BUILD_TAG: mobile-android-preview-build/${{ inputs.fingerprint }} + # Phones only: emulators use the development client from the native-client cache. + ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - id: record + name: Check build record + run: | + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" + fi + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: android + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.apk + + # `eas upload` hosts the APK on EAS and returns the page testers install from. + - id: build + name: Upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" + + ios: + name: Build + if: inputs.platform == 'ios' + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + outputs: + client: ${{ steps.build.outputs.link || steps.record.outputs.link }} + # Set only by a new build: the tag message, the install link and profile expiry. + record: ${{ steps.profile.outputs.record }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} + FINGERPRINT: ${{ inputs.fingerprint }} + BUILD_TAG: mobile-ios-preview-build/${{ inputs.fingerprint }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Setup Node + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: package.json + + - id: record + name: Check build record + run: | + if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then + link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" + if [ -n "$link" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo "link=$link" >> "$GITHUB_OUTPUT" + fi + fi + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: preview:dev + environment: preview + expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} + output: ${{ runner.temp }}/t3code-preview.ipa + + # EAS hosts the signed client and returns its install page. + - id: build + name: Upload + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + shell: bash + run: | + eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" + link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" + if [ -z "$link" ]; then + echo "::error::eas upload returned no install link" + exit 1 + fi + echo "link=$link" >> "$GITHUB_OUTPUT" + echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" + + # The tag stores the install link and provisioning-profile expiry. + - id: profile + name: Read the provisioning profile + if: steps.record.outputs.built != 'true' + env: + LINK: ${{ steps.build.outputs.link }} + run: | + profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" + unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" + security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" + record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" + echo "record=$record" >> "$GITHUB_OUTPUT" + + # The tag is the record later runs look up. Android's message is the install + # link and is never replaced; iOS replaces an expired record for the fingerprint. + record: + name: Record build + needs: [android, ios] + if: ${{ !cancelled() && (needs.android.outputs.record != '' || needs.ios.outputs.record != '') }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + permissions: + contents: write # pushes the build record tag + steps: + # The commit the build job built. No build ran in this checkout. + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Record build + uses: ./.github/actions/record-build-tag + with: + tag: mobile-${{ inputs.platform }}-preview-build/${{ inputs.fingerprint }} + message: ${{ needs.android.outputs.record || needs.ios.outputs.record }} + replace: ${{ inputs.platform == 'ios' }} + token: ${{ github.token }} diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 890bd0c2aecd9..2953ac50b06bb 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -43,7 +43,9 @@ jobs: NODE_OPTIONS: --max-old-space-size=8192 MOBILE_VERSION_POLICY: fingerprint steps: - # If a maintainer removed the label first, that removal wins. + # The label counts only from someone with write access, who could push a + # same-repo branch and get this build anyway. If a maintainer removed the + # label first, that removal wins. - id: consume name: Consume the deployment label uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 @@ -56,12 +58,23 @@ jobs: issue_number: context.payload.pull_request.number, name: context.payload.label.name, }); - core.setOutput("consumed", "true"); } catch (error) { if (error.status !== 404) throw error; core.info("The label was removed before this run could consume it. Skipping."); core.setOutput("consumed", "false"); + return; } + const sender = context.payload.sender.login; + const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, + repo: context.repo.repo, + username: sender, + }); + const authorized = ["admin", "maintain", "write"].includes(access.permission); + if (!authorized) { + core.warning(`${sender} has ${access.permission} access; a fork preview needs write access. Label removed, nothing built.`); + } + core.setOutput("consumed", String(authorized)); - id: expo-token name: Check for EXPO_PREVIEW_TOKEN @@ -231,7 +244,6 @@ jobs: timeout-minutes: 60 permissions: contents: read - pull-requests: write outputs: client: ${{ steps.build.outputs.link }} env: @@ -295,7 +307,6 @@ jobs: timeout-minutes: 60 permissions: contents: read - pull-requests: write outputs: client: ${{ steps.build.outputs.link }} env: diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 53061f25e9c48..501c333f0092e 100644 --- a/.github/workflows/mobile-eas-preview.yml +++ b/.github/workflows/mobile-eas-preview.yml @@ -4,6 +4,9 @@ on: pull_request: types: [opened, reopened, synchronize, labeled] +permissions: + contents: read + jobs: ios: name: EAS Preview (iOS) @@ -17,7 +20,6 @@ jobs: cancel-in-progress: true permissions: contents: read - pull-requests: write outputs: group: ${{ steps.update.outputs.group }} client: ${{ steps.client.outputs.link }} @@ -139,7 +141,6 @@ jobs: cancel-in-progress: true permissions: contents: read - pull-requests: write outputs: group: ${{ steps.update.outputs.group }} client: ${{ steps.client.outputs.link }} @@ -247,181 +248,43 @@ jobs: group="$(eas update --auto --branch "pr-$PR" --platform android --environment preview --non-interactive --json | sed -n '/^\[/,$p' | jq -er '.[0].group')" echo "group=$group" >> "$GITHUB_OUTPUT" + # Each build runs in mobile-eas-preview-build.yml, whose record job alone gets + # the token that pushes the tag. The group covers both of its jobs. android-build: name: Android preview client needs: android if: needs.android.outputs.build == 'true' - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 60 concurrency: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-android-preview-build-${{ needs.android.outputs.fingerprint }} cancel-in-progress: false queue: max permissions: - contents: write # pushes the build record tag - pull-requests: write - outputs: - client: ${{ steps.build.outputs.link || steps.record.outputs.link }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - FINGERPRINT: ${{ needs.android.outputs.fingerprint }} - BUILD_TAG: mobile-android-preview-build/${{ needs.android.outputs.fingerprint }} - # Phones only: emulators use the development client from the native-client cache. - ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - fetch-depth: 0 - - - id: record - name: Check build record - run: | - if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo "link=$(git tag -l --format='%(contents:subject)' "$BUILD_TAG")" >> "$GITHUB_OUTPUT" - fi - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: android - profile: preview:dev - environment: preview - expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - output: ${{ runner.temp }}/t3code-preview.apk - - # `eas upload` hosts the APK on EAS and returns the page testers install from. - - id: build - name: Upload - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - shell: bash - run: | - eas upload --platform android --build-path "$RUNNER_TEMP/t3code-preview.apk" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" - link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" - if [ -z "$link" ]; then - echo "::error::eas upload returned no install link" - exit 1 - fi - echo "link=$link" >> "$GITHUB_OUTPUT" - echo "### Android preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - # The tag is the record later runs look up; its message is the install link. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - message: ${{ steps.build.outputs.link }} - token: ${{ github.token }} + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-preview-build.yml + with: + platform: android + fingerprint: ${{ needs.android.outputs.fingerprint }} + secrets: + EXPO_PREVIEW_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} ios-build: name: iOS preview client needs: ios if: needs.ios.outputs.build == 'true' - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 60 concurrency: # One build per fingerprint; a second PR with the same one finds the tag. group: mobile-ios-preview-build-${{ needs.ios.outputs.fingerprint }} cancel-in-progress: false queue: max permissions: - contents: write # pushes the build record tag - pull-requests: write - outputs: - client: ${{ steps.build.outputs.link || steps.record.outputs.link }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint - EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} - FINGERPRINT: ${{ needs.ios.outputs.fingerprint }} - BUILD_TAG: mobile-ios-preview-build/${{ needs.ios.outputs.fingerprint }} - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - fetch-depth: 0 - - - name: Setup Node - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 - with: - node-version-file: package.json - - - id: record - name: Check build record - run: | - if git fetch --quiet origin "refs/tags/$BUILD_TAG:refs/tags/$BUILD_TAG" 2>/dev/null; then - link="$(git tag -l --format='%(contents)' "$BUILD_TAG" | node .github/scripts/mobile-ios-preview-record.cjs read)" - if [ -n "$link" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo "link=$link" >> "$GITHUB_OUTPUT" - fi - fi - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: ios - profile: preview:dev - environment: preview - expo-token: ${{ secrets.EXPO_PREVIEW_TOKEN }} - output: ${{ runner.temp }}/t3code-preview.ipa - - # EAS hosts the signed client and returns its install page. - - id: build - name: Upload - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - shell: bash - run: | - eas upload --platform ios --build-path "$RUNNER_TEMP/t3code-preview.ipa" --fingerprint "$FINGERPRINT" --non-interactive --json | tee "$RUNNER_TEMP/upload.json" - link="$(sed -n '/^{/,$p' "$RUNNER_TEMP/upload.json" | jq -r '.url // empty')" - if [ -z "$link" ]; then - echo "::error::eas upload returned no install link" - exit 1 - fi - echo "link=$link" >> "$GITHUB_OUTPUT" - echo "### iOS preview client for \`$FINGERPRINT\`: $link" >> "$GITHUB_STEP_SUMMARY" - - # The tag stores the install link and provisioning-profile expiry. - - id: profile - name: Read the provisioning profile - if: steps.record.outputs.built != 'true' - env: - LINK: ${{ steps.build.outputs.link }} - run: | - profile_path="$(unzip -Z -1 "$RUNNER_TEMP/t3code-preview.ipa" | grep -E '^Payload/[^/]+\.app/embedded\.mobileprovision$')" - unzip -p "$RUNNER_TEMP/t3code-preview.ipa" "$profile_path" > "$RUNNER_TEMP/preview.mobileprovision" - security cms -D -i "$RUNNER_TEMP/preview.mobileprovision" > "$RUNNER_TEMP/preview-profile.plist" - record="$(node .github/scripts/mobile-ios-preview-record.cjs create "$LINK" "$RUNNER_TEMP/preview-profile.plist")" - echo "record=$record" >> "$GITHUB_OUTPUT" - - # Replaces an expired record for the same fingerprint. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - message: ${{ steps.profile.outputs.record }} - replace: "true" - token: ${{ github.token }} + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-preview-build.yml + with: + platform: ios + fingerprint: ${{ needs.ios.outputs.fingerprint }} + secrets: + EXPO_PREVIEW_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} comment: name: Mobile preview comment diff --git a/.github/workflows/mobile-eas-production-build.yml b/.github/workflows/mobile-eas-production-build.yml new file mode 100644 index 0000000000000..766b9cb7c4c5d --- /dev/null +++ b/.github/workflows/mobile-eas-production-build.yml @@ -0,0 +1,199 @@ +name: Mobile EAS Production Build + +# One store build and its build record, called per platform by +# mobile-eas-production.yml. The build job runs dependency and build scripts with +# a read-only token. Only the record job, on a fresh runner that runs none of +# them, gets the token that can push tags. The caller's concurrency group covers +# both jobs, so a queued run for the same fingerprint starts after the tag exists. + +on: + workflow_call: + inputs: + platform: + description: android or ios + required: true + type: string + profile: + description: eas.json build and submit profile + required: true + type: string + sha: + description: Commit to build and tag + required: true + type: string + tag: + description: Build record tag, without refs/tags/ + required: true + type: string + secrets: + EXPO_PRODUCTION_TOKEN: + required: true + MOBILE_SOURCEMAPS_R2: + required: false + +permissions: + contents: read + +jobs: + # ARM-only, without release lint (see the production profile in eas.json), + # with Gradle, ccache, and pnpm state on a sticky disk. + android: + name: Build + if: ${{ !cancelled() && inputs.platform == 'android' }} + runs-on: blacksmith-32vcpu-ubuntu-2404 + timeout-minutes: 60 + permissions: + contents: read + outputs: + submitted: ${{ steps.submit.outcome == 'success' }} + env: + APP_VARIANT: production + NODE_OPTIONS: --max-old-space-size=8192 + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + BUILD_TAG: ${{ inputs.tag }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + # A queued run can follow a build of the same fingerprint; manual runs always build. + - id: record + name: Check build record + env: + FORCE: ${{ github.event_name == 'workflow_dispatch' }} + run: | + if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: android + profile: production + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.aab + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - name: Check ABIs + if: steps.record.outputs.built != 'true' + run: | + abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" + echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" + if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then + echo "::error::Expected only ARM native libraries in the AAB, found $abis" + exit 1 + fi + + # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. + - name: Keep the AAB + if: steps.record.outputs.built != 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/t3code.aab + retention-days: 14 + if-no-files-found: error + + - id: submit + name: Submit to Google Play + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + run: eas submit --platform android --profile production --path "$RUNNER_TEMP/t3code.aab" --non-interactive + + # No sticky disk: it mounts ext4 and only works on Linux runners. + ios: + name: Build + if: ${{ !cancelled() && inputs.platform == 'ios' }} + runs-on: blacksmith-12vcpu-macos-27 + timeout-minutes: 60 + permissions: + contents: read + outputs: + submitted: ${{ steps.submit.outcome == 'success' }} + env: + APP_VARIANT: production + NODE_OPTIONS: --max-old-space-size=8192 + EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + PROFILE: ${{ inputs.profile }} + BUILD_TAG: ${{ inputs.tag }} + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ inputs.sha }} + fetch-depth: 0 + + # The steps below run dependency and build scripts; they get no token. + - name: Drop checkout credentials + uses: ./.github/actions/drop-checkout-credentials + + # A queued run can follow a build of the same fingerprint; manual runs always build. + - id: record + name: Check build record + env: + FORCE: ${{ github.event_name == 'workflow_dispatch' }} + run: | + if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then + echo "built=true" >> "$GITHUB_OUTPUT" + echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Build + if: steps.record.outputs.built != 'true' + uses: ./.github/actions/eas-local-build + with: + platform: ios + profile: ${{ env.PROFILE }} + environment: production + expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + output: ${{ runner.temp }}/t3code.ipa + sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} + + - id: submit + name: Submit to App Store Connect + if: steps.record.outputs.built != 'true' + working-directory: apps/mobile + run: eas submit --platform ios --profile "$PROFILE" --path "$RUNNER_TEMP/t3code.ipa" --non-interactive + + # The tag means "delivered", so it follows the submit. If it can't be + # pushed, the next merge rebuilds with a new build number; nothing is lost. + record: + name: Record build + needs: [android, ios] + if: ${{ !cancelled() && (needs.android.outputs.submitted == 'true' || needs.ios.outputs.submitted == 'true') }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 + permissions: + contents: write # pushes the build record tag + env: + BUILD_TAG: ${{ inputs.tag }} + steps: + # The workflow's own commit, so the action below is this workflow's. The + # built commit is passed as data. + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + fetch-depth: 0 + + - name: Record build + uses: ./.github/actions/record-build-tag + with: + tag: ${{ inputs.tag }} + commit: ${{ inputs.sha }} + token: ${{ github.token }} + + - name: Summarize + env: + PLATFORM: ${{ inputs.platform }} + run: | + echo ":rocket: $PLATFORM: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index fe4d7456acdf4..249150ff0951b 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -68,6 +68,10 @@ on: - pnpm-lock.yaml - pnpm-workspace.yaml - .github/workflows/mobile-eas-production.yml + - .github/workflows/mobile-eas-production-build.yml + +permissions: + contents: read jobs: production: @@ -83,6 +87,7 @@ jobs: permissions: contents: read outputs: + version_override: ${{ steps.version_override.outputs.applied }} android_build: ${{ steps.reconcile.outputs.android_build || steps.android_manual.outputs.android_build }} android_fingerprint: ${{ steps.reconcile.outputs.android_fingerprint || steps.android_manual.outputs.android_fingerprint }} android_version: ${{ steps.reconcile.outputs.android_version || steps.android_manual.outputs.android_version }} @@ -119,21 +124,11 @@ jobs: echo "EXPO_PRODUCTION_TOKEN is not available; skipping EAS production job." fi - - id: version_app_token - name: Mint release app token for version override - if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' - uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 - with: - app-id: ${{ secrets.RELEASE_APP_ID }} - private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} - - name: Checkout if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 - token: ${{ steps.version_app_token.outputs.token || github.token }} # No sparse-checkout here: it makes actions/checkout fetch with # --filter=blob:none, and eas-cli archives the project via # `git clone --depth 1 file://`, which fails (exit 128) @@ -188,48 +183,21 @@ jobs: appendFileSync(process.env.GITHUB_ENV, `T3CODE_ANDROID_GOOGLE_SERVICES_FILE=${googleServicesFile}\n`); NODE - - name: Apply manual version override - if: steps.version_app_token.outcome == 'success' + # Only so the versions and fingerprints below are read from the tree that + # will be built. This job installs dependencies, so it gets no token that can + # push: the version job makes the same commit as the Release App afterwards. + - id: version_override + name: Apply manual version override + if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != '' && inputs.profile != 'testflight' env: - GH_TOKEN: ${{ steps.version_app_token.outputs.token }} - APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }} RELEASE_VERSION: ${{ inputs.version }} run: | - if [ "$GITHUB_REF_TYPE" != "branch" ]; then - echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2 - exit 1 - fi - if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then - echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2 - exit 1 + node .github/scripts/set-mobile-version.cjs "$RELEASE_VERSION" + if ! git diff --quiet -- apps/mobile/app.config.ts; then + git -c user.name=mobile-version -c user.email=mobile-version@users.noreply.github.com \ + commit --no-verify --quiet -m "chore(mobile): bump app version to $RELEASE_VERSION" -- apps/mobile/app.config.ts fi - - node --input-type=module -e ' - import fs from "node:fs"; - const path = "apps/mobile/app.config.ts"; - const source = fs.readFileSync(path, "utf8"); - const next = source.replace( - /^( version: repoEnv\.T3CODE_MOBILE_VERSION \?\? ")[^"]+(".*)$/m, - `$1${process.env.RELEASE_VERSION}$2`, - ); - if (next === source && !source.includes(` version: repoEnv.T3CODE_MOBILE_VERSION ?? "${process.env.RELEASE_VERSION}"`)) { - throw new Error("Could not update app version"); - } - fs.writeFileSync(path, next); - ' - vp fmt apps/mobile/app.config.ts - - if git diff --quiet -- apps/mobile/app.config.ts; then - echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed." - exit 0 - fi - - user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" - git config user.name "${APP_SLUG}[bot]" - git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" - git add apps/mobile/app.config.ts - git commit --no-verify -m "chore(mobile): bump app version to $RELEASE_VERSION" - git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" + echo "applied=true" >> "$GITHUB_OUTPUT" - name: Summarize manual build version if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' @@ -453,165 +421,95 @@ jobs: fi done - # ARM-only, without release lint (see the production profile in eas.json), - # with Gradle, ccache, and pnpm state on a sticky disk. Its own concurrency - # group keeps later OTAs from waiting on it. - android: - name: Android store build + # Commits a store version override as the Release App. It installs nothing and + # runs no dependency code, so that token never shares a runner with any. It + # runs after the production job so the push's own run queues behind this one. + version: + name: Commit version override needs: production - # Skipped when the production job failed: no store build after a failed OTA. - if: needs.production.outputs.android_build == 'true' - runs-on: blacksmith-32vcpu-ubuntu-2404 - timeout-minutes: 60 - concurrency: - group: mobile-android-store-build - cancel-in-progress: false + if: ${{ !cancelled() && needs.production.result == 'success' && needs.production.outputs.version_override == 'true' }} + runs-on: blacksmith-2vcpu-ubuntu-2404 + timeout-minutes: 5 permissions: - contents: write # pushes the build record tag - env: - APP_VARIANT: production - NODE_OPTIONS: --max-old-space-size=8192 - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - BUILD_TAG: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} + contents: read + outputs: + sha: ${{ steps.commit.outputs.sha }} steps: + # No owner input: the token covers this repository only, with contents write. + - id: app_token + name: Mint release app token + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 + with: + app-id: ${{ secrets.RELEASE_APP_ID }} + private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} + permission-contents: write + - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ needs.production.outputs.android_sha }} - fetch-depth: 0 + token: ${{ steps.app_token.outputs.token }} - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - # A queued run can follow a build of the same fingerprint; manual runs always build. - - id: record - name: Check build record + - id: commit + name: Commit and push the version env: - FORCE: ${{ github.event_name == 'workflow_dispatch' }} - run: | - if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo ":white_check_mark: android: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: android - profile: production - environment: production - expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - output: ${{ runner.temp }}/t3code.aab - sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - - - name: Check ABIs - if: steps.record.outputs.built != 'true' + GH_TOKEN: ${{ steps.app_token.outputs.token }} + APP_SLUG: ${{ steps.app_token.outputs.app-slug }} + RELEASE_VERSION: ${{ inputs.version }} run: | - abis="$(unzip -Z1 "$RUNNER_TEMP/t3code.aab" | sed -n 's|^base/lib/\([^/]*\)/.*|\1|p' | sort -u | paste -sd, -)" - echo "### Android $BUILD_TAG: \`$abis\`" >> "$GITHUB_STEP_SUMMARY" - if [ "$abis" != "arm64-v8a,armeabi-v7a" ]; then - echo "::error::Expected only ARM native libraries in the AAB, found $abis" - exit 1 + node .github/scripts/set-mobile-version.cjs "$RELEASE_VERSION" + if git diff --quiet -- apps/mobile/app.config.ts; then + echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed." + else + user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)" + git config user.name "${APP_SLUG}[bot]" + git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" + git add apps/mobile/app.config.ts + git commit --no-verify -m "chore(mobile): bump app version to $RELEASE_VERSION" + git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}" fi + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - # A --path submission doesn't keep its archive on EAS; this is the only downloadable copy. - - name: Keep the AAB - if: steps.record.outputs.built != 'true' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: android-store-aab-${{ github.run_id }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/t3code.aab - retention-days: 14 - if-no-files-found: error - - - name: Submit to Google Play - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas submit --platform android --profile production --path "$RUNNER_TEMP/t3code.aab" --non-interactive - - # The tag means "delivered", so it follows the submit. If it can't be - # pushed, the next merge rebuilds with a new build number; nothing is lost. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - token: ${{ github.token }} - - - name: Summarize - if: steps.record.outputs.built != 'true' - run: | - echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" + # Each store build runs in mobile-eas-production-build.yml, whose record job + # alone gets the token that pushes the tag. The group covers both of its jobs, + # and being its own group keeps later OTAs from waiting on a build. + android: + name: Android store build + needs: [production, version] + # Skipped when the production job failed: no store build after a failed OTA. + # The version job is skipped unless there is an override. + if: ${{ !cancelled() && needs.production.result == 'success' && needs.version.result != 'failure' && needs.production.outputs.android_build == 'true' }} + concurrency: + group: mobile-android-store-build + cancel-in-progress: false + permissions: + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-production-build.yml + with: + platform: android + profile: production + sha: ${{ needs.version.outputs.sha || needs.production.outputs.android_sha }} + tag: mobile-android-build/${{ needs.production.outputs.android_version }}/${{ needs.production.outputs.android_fingerprint }} + secrets: + EXPO_PRODUCTION_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - # No sticky disk: it mounts ext4 and only works on Linux runners. ios: name: iOS store build - needs: production + needs: [production, version] # Skipped when the production job failed: no store build after a failed OTA. - if: needs.production.outputs.ios_build == 'true' - runs-on: blacksmith-12vcpu-macos-27 - timeout-minutes: 60 + # The version job is skipped unless there is an override. + if: ${{ !cancelled() && needs.production.result == 'success' && needs.version.result != 'failure' && needs.production.outputs.ios_build == 'true' }} concurrency: group: mobile-ios-store-build cancel-in-progress: false permissions: - contents: write # pushes the build record tag - env: - APP_VARIANT: production - NODE_OPTIONS: --max-old-space-size=8192 - EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - PROFILE: ${{ needs.production.outputs.ios_profile }} - BUILD_TAG: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} - steps: - - name: Checkout - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 - with: - ref: ${{ needs.production.outputs.ios_sha }} - fetch-depth: 0 - - # The steps below run dependency and build scripts; they get no token. - - name: Drop checkout credentials - uses: ./.github/actions/drop-checkout-credentials - - # A queued run can follow a build of the same fingerprint; manual runs always build. - - id: record - name: Check build record - env: - FORCE: ${{ github.event_name == 'workflow_dispatch' }} - run: | - if [ "$FORCE" != "true" ] && [ -n "$(git tag -l "$BUILD_TAG")" ]; then - echo "built=true" >> "$GITHUB_OUTPUT" - echo ":white_check_mark: ios: \`$BUILD_TAG\` was built by an earlier run" >> "$GITHUB_STEP_SUMMARY" - fi - - - name: Build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/eas-local-build - with: - platform: ios - profile: ${{ env.PROFILE }} - environment: production - expo-token: ${{ secrets.EXPO_PRODUCTION_TOKEN }} - output: ${{ runner.temp }}/t3code.ipa - sourcemaps-r2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} - - - name: Submit to App Store Connect - if: steps.record.outputs.built != 'true' - working-directory: apps/mobile - run: eas submit --platform ios --profile "$PROFILE" --path "$RUNNER_TEMP/t3code.ipa" --non-interactive - - # The tag means "delivered", so it follows the submit. If it can't be - # pushed, the next merge rebuilds with a new build number; nothing is lost. - - name: Record build - if: steps.record.outputs.built != 'true' - uses: ./.github/actions/record-build-tag - with: - tag: ${{ env.BUILD_TAG }} - token: ${{ github.token }} - - - name: Summarize - if: steps.record.outputs.built != 'true' - run: | - echo ":rocket: ios: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" + contents: write # the record job pushes the build record tag + uses: ./.github/workflows/mobile-eas-production-build.yml + with: + platform: ios + profile: ${{ needs.production.outputs.ios_profile }} + sha: ${{ needs.version.outputs.sha || needs.production.outputs.ios_sha }} + tag: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} + secrets: + EXPO_PRODUCTION_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} + MOBILE_SOURCEMAPS_R2: ${{ secrets.MOBILE_SOURCEMAPS_R2 }} diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index 303348a27f916..29a05c039b025 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -18,6 +18,9 @@ on: # diff, so the label can be cleared without installing Expo dependencies. types: [opened, synchronize, reopened, edited] +permissions: + contents: read + concurrency: # A title or body edit gets its own group, so it cannot cancel the PR's real # run and leave a cancelled check on the head commit. diff --git a/.github/workflows/mobile-fingerprint-label.yml b/.github/workflows/mobile-fingerprint-label.yml index a48462eec8c53..d8aa3738158e2 100644 --- a/.github/workflows/mobile-fingerprint-label.yml +++ b/.github/workflows/mobile-fingerprint-label.yml @@ -27,8 +27,6 @@ jobs: timeout-minutes: 5 permissions: actions: read - contents: read - issues: write pull-requests: write steps: - id: pr diff --git a/.github/workflows/pr-limits.yml b/.github/workflows/pr-limits.yml index d6a2864f94a9b..3a0fbe591a93f 100644 --- a/.github/workflows/pr-limits.yml +++ b/.github/workflows/pr-limits.yml @@ -21,14 +21,15 @@ on: permissions: contents: read - issues: write - pull-requests: write jobs: open-limit: name: Open PR limit if: github.event_name == 'pull_request_target' runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: write steps: # pull_request_target has a write token. Load the script from the default # branch and never run PR code. Cone mode also checks out the files beside @@ -52,6 +53,9 @@ jobs: name: Conflict and close windows if: github.event_name != 'pull_request_target' runs-on: ubuntu-24.04 + permissions: + contents: read + pull-requests: write concurrency: group: pr-limits-sweep cancel-in-progress: false diff --git a/.github/workflows/relay-preview-cleanup.yml b/.github/workflows/relay-preview-cleanup.yml index 483e3e0b01b7e..936d19cadad56 100644 --- a/.github/workflows/relay-preview-cleanup.yml +++ b/.github/workflows/relay-preview-cleanup.yml @@ -38,7 +38,6 @@ jobs: cancel-in-progress: false permissions: contents: read - issues: write pull-requests: write runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 30 @@ -139,7 +138,6 @@ jobs: cancel-in-progress: false permissions: contents: read - issues: write pull-requests: write environment: name: relay-preview-cleanup diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8693e959055bf..6fe82ebcb0069 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1103,6 +1103,9 @@ jobs: if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel != 'preview' }} runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 15 + # npm's trusted publisher for `t3` names this environment, which admits only + # main and v* tags. + environment: production permissions: contents: read id-token: write @@ -1191,9 +1194,6 @@ jobs: T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ needs.relay_public_config.outputs.clerk_cli_oauth_client_id }} T3CODE_RELAY_URL: ${{ needs.relay_public_config.outputs.relay_url }} - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: @@ -1231,9 +1231,14 @@ jobs: - name: Refresh release lockfile run: vp install --lockfile-only --ignore-scripts + # The Vercel secrets are on this step only, not on the install above. - id: deploy name: Build staged deployment shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} run: | set -euo pipefail @@ -1364,8 +1369,6 @@ jobs: deployment_url: ${{ steps.deploy.outputs.deployment_url }} project_id: ${{ steps.deploy.outputs.project_id }} env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: - name: Checkout @@ -1382,9 +1385,13 @@ jobs: with: install-args: --filter=@t3tools/marketing... + # The Vercel secrets are on this step only, not on the install above. - id: deploy name: Build staged deployment shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} run: | set -euo pipefail @@ -1464,6 +1471,8 @@ jobs: --token "$VERCEL_TOKEN" \ --scope "${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}" + # Commits the version bump as the Release App. It installs nothing and runs no + # dependency code, so that token never shares a runner with any. finalize: name: Finalize release if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }} @@ -1471,13 +1480,14 @@ jobs: runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 steps: + # No owner input: the token covers this repository only, with contents write. - id: app_token name: Mint release app token uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 with: app-id: ${{ secrets.RELEASE_APP_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} + permission-contents: write - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -1501,32 +1511,19 @@ jobs: echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT" echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT" - - name: Setup dependencies - uses: ./.github/actions/setup-ci-deps - with: - install-args: --filter=@t3tools/scripts... --filter=@t3tools/oxlint-plugin-t3code... - - - id: update_versions - name: Update version strings + # Rewrites the version string in place: the manifests stay formatted, and + # the lockfile records no workspace package version. + - name: Update version strings env: RELEASE_VERSION: ${{ needs.preflight.outputs.version }} - run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output - - - name: Format package.json files - if: steps.update_versions.outputs.changed == 'true' - run: vp fmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json - - - name: Refresh lockfile - if: steps.update_versions.outputs.changed == 'true' - run: vp install --lockfile-only --ignore-scripts + run: node .github/scripts/set-release-version.cjs "$RELEASE_VERSION" - name: Commit and push version bump - if: steps.update_versions.outputs.changed == 'true' shell: bash env: RELEASE_TAG: ${{ needs.preflight.outputs.tag }} run: | - if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml; then + if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json; then echo "No version changes to commit." exit 0 fi @@ -1534,7 +1531,7 @@ jobs: git config user.name "${{ steps.app_bot.outputs.name }}" git config user.email "${{ steps.app_bot.outputs.email }}" - git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml + git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json git commit --no-verify -m "chore(release): prepare $RELEASE_TAG" # main moves while this job runs, so a rejected push rebases and retries. diff --git a/.github/workflows/stale-needs-more-info.yml b/.github/workflows/stale-needs-more-info.yml index 9d994115705f4..d885c244316e9 100644 --- a/.github/workflows/stale-needs-more-info.yml +++ b/.github/workflows/stale-needs-more-info.yml @@ -5,13 +5,14 @@ on: - cron: "17 6 * * *" workflow_dispatch: -permissions: - actions: write - issues: write +permissions: {} jobs: stale: runs-on: ubuntu-latest + permissions: + actions: write + issues: write steps: - uses: actions/stale@5bef64f19d7facfb25b37b414482c7164d639639 # v9.1.0 with: diff --git a/.github/workflows/thread-transfer-report.yml b/.github/workflows/thread-transfer-report.yml index 94987b447745b..69056d5635403 100644 --- a/.github/workflows/thread-transfer-report.yml +++ b/.github/workflows/thread-transfer-report.yml @@ -6,15 +6,17 @@ on: types: [completed] permissions: - actions: read contents: read - pull-requests: write jobs: publish: name: Publish PR comment if: github.event.workflow_run.event == 'pull_request' runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + pull-requests: write concurrency: group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }} cancel-in-progress: true diff --git a/.github/workflows/web-preview.yml b/.github/workflows/web-preview.yml index 69db6b6025e8f..e475c69efa2f8 100644 --- a/.github/workflows/web-preview.yml +++ b/.github/workflows/web-preview.yml @@ -21,7 +21,6 @@ on: permissions: contents: read - pull-requests: write concurrency: group: web-preview-${{ github.event.pull_request.number }} @@ -39,11 +38,9 @@ jobs: (github.event.action != 'labeled' || github.event.label.name == 'preview:web') runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 - env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} - VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} + permissions: + contents: read + pull-requests: write steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -54,6 +51,8 @@ jobs: !/.repos/ sparse-checkout-cone-mode: false + # The Vercel CLI imports @vercel/config from here to read apps/web/vercel.ts. + # No dependency lifecycle script runs in this job. - name: Setup Vite+ uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1.15.0 with: @@ -61,12 +60,18 @@ jobs: cache: true run-install: | args: + - --ignore-scripts - --filter=@t3tools/scripts... - --filter=@t3tools/web... - id: deploy name: Deploy preview shell: bash + env: + VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} + VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} + VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} + VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} run: | set -euo pipefail diff --git a/AGENTS.md b/AGENTS.md index d62b4bab416b5..d0adefb8896df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ We have over 500,000 users who love T3 Code. It's important we maintain the thin ### 1. Open at the core -T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks. We work in the open, and should strive to stay that way. +T3 Code is truly open. We share our roadmap, we share how we think about things, and of course we share all our code. A large number of our users run forks (our MIT license covers source code only, not T3 Code's trademarks or branding; see [TRADEMARK.md](TRADEMARK.md)). We work in the open, and should strive to stay that way. ### 2. Performance without compromise diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b5445efd4d197..8780eda18a5d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -138,6 +138,10 @@ hours later. A reply or a push in that time sends it back for another look. After it is closed, fix the problem and comment on the PR, or open a focused replacement PR that links the old one. +## Forks and branding + +If you want changes outside our scope, you are welcome to fork the MIT-licensed source code. That license covers the source code only, not the **T3 Code** name, wordmark, logos, or branding. Any fork or derivative project must use its own branding and make it unmistakably clear that it is unofficial and not affiliated with T3 Tools, Inc. Using our name, wordmark, logo, or branding without making it unmistakably clear that your project is unofficial, or indicating that an unofficial project is an official version of T3 Code, is unlawful and will be pursued to the full extent of the law. Truthful, plain-text attribution is fine; see [TRADEMARK.md](./TRADEMARK.md). + ## Setup See the [development runbook](docs/operations/00_development.md#first-checkout). diff --git a/README.md b/README.md index 2ff0418fcd2e0..b3ad8bae49b70 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ It works with Claude Code, Codex, Cursor, OpenCode, Grok Build, Antigravity, Kir - **Remote ready.** Run agents on any machine. Connect over your local network, Tailscale, or [T3 Connect](./docs/user/remote-access.md). - **Git built in.** Each thread can work in its own worktree. Review the diff, then commit, push, and open a pull request with one button. - **Fast.** Performance is a feature here. We measure it, and we treat a dropped frame as a bug. -- **Open.** MIT licensed. If you don't like something, fork it. +- **Open.** Source code is MIT licensed. If you don't like something, fork it under your own branding (see [Trademarks and forks](#trademarks-and-forks)). ## Install @@ -81,7 +81,7 @@ T3 Code needs one agent that is installed and signed in. For example, install [C Nothing. We built T3 Code because we wanted the best possible development experience with agents. We were inspired by existing solutions like the Codex desktop app, Conductor, Claude Desktop and Cursor Glass, but none met our bar. -We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork and build the tool that you want. +We wanted something performant, remote-ready, and truly open. If we ever go the wrong direction, we want you to have everything you need to fork the source code and build the tool that you want, under your own name and branding. ## Documentation @@ -105,4 +105,17 @@ We have limited review capacity. Small, focused fixes are the most likely to be ## License -[MIT](./LICENSE) +The source code in this repository is licensed under the [MIT License](./LICENSE). + +## Trademarks and forks + +The MIT license applies **only to the source code**. It does not grant any rights to T3 Tools, Inc.'s trademarks, branding, or trade dress, including the **T3 Code** name, wordmark, logos, and application icons. + +If you fork, redistribute, or build on T3 Code's source code: + +- **Use your own branding.** Replace the T3 Code name, wordmark, logos, and application icons in any public fork, redistributed build, website, package, or app store listing. +- **Be explicitly clear that your project is unofficial.** Do not use the T3 Code name, wordmark, logo, or branding in your own projects without making it unmistakably clear that your project is unofficial and not affiliated with or endorsed by T3 Tools, Inc. + +Using our name, wordmark, logo, or branding in a way that suggests official status or affiliation is trademark infringement and unlawful. **Any project indicating or implying that it is an official version of T3 Code when it is not will be pursued to the full extent of the law.** + +See [TRADEMARK.md](./TRADEMARK.md) for the full trademark and branding policy. diff --git a/SECURITY.md b/SECURITY.md index 156e7292e3da2..9c63913169305 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,46 +4,46 @@ Report vulnerabilities to [security@t3.codes](mailto:security@t3.codes). The [security policy](.github/SECURITY.md) covers disclosure and safe harbor. The rest of this file is for agents and maintainers auditing T3 Code or triaging -a report. It says who is trusted with what, which boundaries a real finding +reports. It defines who is trusted with what, which boundaries a real finding crosses, and what is intended. The reasoning behind each boundary lives in [environment auth](docs/internals/04_environment-auth.md), [T3 Connect](docs/internals/06_t3-connect.md), and -[remote environments](docs/internals/05_remote.md). Read those before you report a -finding in their area. +[remote environments](docs/internals/05_remote.md); read those before reporting +in their area. ## The model in one paragraph An environment is a T3 server running as an OS user. It is not a sandbox: it -runs agents and terminals with that user's privileges, on purpose. Clients get -authority by pairing, which issues a scoped session. A full-scope session is -equivalent to a shell as the server's user, because `terminal:operate` opens a -PTY and `orchestration:operate` can start a full-access agent. Security work -here is about who can get a session, what each kind of session can reach, and -whether revocation and ceilings hold. It is not about what a full session can do -once it has one. +intentionally runs agents and terminals with that user's privileges. Clients +gain authority by pairing, which issues a scoped session. A full-scope session +equals a shell as the server's OS user, because `terminal:operate` opens a PTY +and `orchestration:operate` can start a full-access agent. Security here is +about who can obtain a session, what each session type can reach, and whether +revocation and ceilings hold, not what a full-scope session can do once issued. ## Principals -| Principal | How it gets in | What it may do | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Anyone who reaches the port | Network | Read the environment descriptor, pair with a valid one-time credential, run OAuth flows. Nothing else. | -| Full-scope client (desktop, paired browser or phone, `t3 auth session issue`, T3 Connect device) | Pairing, token exchange, Connect mint | Everything the server's OS user can do. This is the default grant. | -| Narrow client | Pairing link with explicit scopes | Only the RPCs and routes its scopes allow. Can never widen its own grant. | -| MCP client (outside agent, subject `mcp-client`) | OAuth on `/mcp` | Only `/mcp`, within a read-only grant or a runtime-mode ceiling. Every other route rejects it. | -| Linked environment (peer link) | OAuth client `t3code-peer-link` | Work it starts carries an immutable `linkOrigin` and never exceeds the access it was paired with. | -| Agent run by T3 | Thread's runtime mode and thread credential | Within its runtime mode, managed policy, and the MCP access declared per tool. | -| Guest link | HMAC token for one share | Read one thread and propose messages. Never a session; no RPC, WebSocket, or MCP path accepts it. | -| Signed asset URL | Minted with `filesystem:read` | One file, by device and inode identity, until it expires. | -| T3 Connect relay | Environment link | Trusted broker for mint requests. It never sees environment session tokens. With `requireConnectDeviceApproval` on, a new device key also needs approval from someone with `access:write`. | -| Managed policy | Admin-deployed file, read at startup | Ceilings and locks the server enforces for every client. | -| Preview pages, HTML renders, file previews, agent output | Rendered by clients | Untrusted content. It must never run script in the app's origin or reach Electron IPC or Node. | +| Principal | How it gets in | What it may do | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Anyone who reaches the port | Network | Read the environment descriptor, pair with a valid one-time credential, run OAuth flows. Nothing else. | +| Full-scope client (desktop, paired browser or phone, `t3 auth session issue`, T3 Connect device) | Pairing, token exchange, Connect mint | Everything the server's OS user can do. This is the default grant. | +| Narrow client | Pairing link with explicit scopes | Only the RPCs and routes its scopes allow. Can never widen its own grant. | +| MCP client (outside agent, subject `mcp-client`) | OAuth on `/mcp` | Only `/mcp`, within a read-only grant or a runtime-mode ceiling. Every other route rejects it. | +| Linked environment (peer link) | OAuth client `t3code-peer-link` | Work it starts carries an immutable `linkOrigin` and never exceeds the access it was paired with. | +| Agent run by T3 | Thread's runtime mode and thread credential | Within its runtime mode, managed policy, and the MCP access declared per tool. | +| Guest link | HMAC token for one share | Read one thread and propose messages. Never a session; no RPC, WebSocket, or MCP path accepts it. | +| Signed asset URL | Minted with `filesystem:read` | One file, by device and inode identity, until it expires. | +| Webhook sender | A task's webhook URL, plus its signing secret when the task requires one | Start that one task's run with content of its choosing. Nothing in the request is trusted beyond the signature check. | +| T3 Connect relay | Environment link | Trusted broker for mint requests. It never sees environment session tokens. With `requireConnectDeviceApproval` on, a new device key also needs approval from someone with `access:write`. | +| Managed policy | Admin-deployed file, read at startup | Ceilings and locks the server enforces for every client. | +| Preview pages, HTML renders, file previews, agent output | Rendered by clients | Untrusted content. It must never run script in the app's origin or reach Electron IPC or Node. | ## A real finding crosses one of these -1. **No credential → session.** Any route or socket that grants access without - a valid credential, or a pairing credential that can be redeemed twice. -2. **Scope escalation.** An RPC, HTTP route, or MCP tool that runs without the - scope it declares; pairing or token exchange that widens a grant; an +1. **No credential → session.** Any route or socket granting access without + a valid credential, or a pairing credential redeemable twice. +2. **Scope escalation.** An RPC, HTTP route, or MCP tool running without its + declared scope; pairing or token exchange widening a grant; an `mcp-client` session reaching a non-`/mcp` route; a read-only MCP grant calling a write tool. 3. **Mode or policy escalation.** An agent, MCP client, or peer link acting @@ -52,43 +52,77 @@ once it has one. 4. **Guest escape.** A guest token reading another thread, acting beyond proposing messages, or surviving a closed or replaced share. 5. **Revocation that doesn't take effect.** A revoked session, device key, - pairing link, or peer link that still works. The exception is documented: - signed asset URLs last until they expire. + pairing link, or peer link that still works. Documented exception: signed + asset URLs last until they expire. 6. **Credential exposure.** Tokens or secrets reaching logs, traces, telemetry, the relay, socket URLs (outside short-lived tickets), the access read model, or error messages. A token sent to an address that has not answered as the - expected environment. A token paired over HTTPS starting to travel over plain - HTTP. + expected environment, or a token paired over HTTPS sent over plain HTTP. 7. **Impersonation and egress.** Another process or the relay impersonating an - environment, or endpoint discovery, previews, or webhooks used to reach + environment; endpoint discovery, previews, or webhooks used to reach arbitrary hosts (SSRF). 8. **Client-side code execution.** Untrusted content running script in the web origin, the desktop renderer, or with access to preload or IPC. -9. **Filesystem writes escaping workspace path rules.** Reads are another - matter: `filesystem:read` is intentionally the whole account. +9. **Filesystem writes escaping workspace path rules.** Reads are separate: + `filesystem:read` intentionally covers the whole OS account. ## Intended, not vulnerabilities -- A full-scope token gives a shell. Leaking one is serious, but the bug is the - leak, not the shell. -- The default grant includes `access:write`, so a full session can mint more - pairing links and sessions. They appear in Sharing & access, and "revoke all - others" removes them. -- `filesystem:read` reads anything the server's user can read, including paths - outside projects. -- Plain HTTP on a LAN or tailnet is the user's choice. `t3 serve` warns when it - advertises a non-loopback HTTP address. The iOS app allows arbitrary loads so +- A full-scope session gives a shell. Leaking its token is serious, but the bug + is the leak, not the shell. The same applies to a narrow session holding + `terminal:operate` or `orchestration:operate`: reaching via another route + what its shell can already do crosses no boundary, though it can still be an + ordinary bug. That stops at what a shell as the server's OS user cannot reach: + another client's device, what another scope guards by name (as + `providers:manage` does for secret references), a managed-policy ceiling or + lock, and access that outlives the session's revocation. Where the session + can obtain that shell, file contents are within its reach, so reading a file + via a route that does not check `filesystem:read` crosses no boundary. +- The default grant includes `access:write`, so a full-scope session can mint + more pairing links and sessions. They appear in Sharing & access, and "revoke + all others" removes them. +- `filesystem:read` reads anything the server's OS user can read, including + paths outside projects. +- Plain HTTP on a LAN or tailnet is the user's choice. `t3 serve` warns when + advertising a non-loopback HTTP address. The iOS app allows arbitrary loads so it can reach these addresses. - `access-control-allow-origin: *` on the environment API. Auth is a bearer header, so the wildcard grants nothing a caller without a token lacks. -- An agent in full-access mode can do whatever the user can. Prompt injection - that stays within the agent's mode is the provider's concern. One that lets - it act above that mode is in scope (see 3). +- Rendered Markdown loads remote images and media from the host its author + names, so that host learns the reader's network address and when the content + was shown. A page in a preview tab can likewise start a download, as it can + in a browser. It is a finding when the request carries a credential or names + the environment it was rendered in, when it is made where the product says + none is made, or when the app does for the content what the content could + not do from where it runs (see 7 and 8). +- A full-access agent can do whatever the user can. Prompt injection that stays + within the agent's mode is the provider's concern; one that lets it act above + that mode is in scope (see 3). - A compromised relay signing key can mint for linked environments. That is the stated trust assumption; device approval is the mitigation. - `T3CODE_DEV_AUTH_TOKEN` and dev startup URLs are administrative by design and ignored outside development servers. -- An attacker already running code as the same OS user. +- A webhook URL is a credential for one task. Unless the task requires a + signature, whoever holds the URL can start that task's run, and the request's + content, within the route's limits, is theirs to choose. It is a finding when + a request starts a different task, runs without a signature the task + requires, or has its values treated as anything but untrusted data. Tokens in + or around the request remain covered by 6. +- The machine owner's own configuration. Whoever sets a provider's launch + arguments, an environment variable, a binary path, or the endpoint or file T3 + Code points at already holds the OS account, so a value weakening their own + setup is their choice. It is a finding when a narrower principal can set it + for them (a narrow client, an MCP client, an agent below full access, + repository content), when [managed policy](docs/user/managed-policy.md) locks + the setting and the value still applies, or when the value leaks (see 6). + Choosing a host does not make it trusted: what a configured endpoint can do + to the server or its clients stays in scope. +- An attacker already running code as the same OS user. That includes one whose + only move is to rewrite files that user owns outside a workspace: T3 Code's + data directory, its installed helpers, the user's own config. Another OS + account on the same machine is not this attacker; neither is repository + content or an agent below full access, which write inside a workspace without + holding the OS account. ## Where enforcement lives @@ -106,10 +140,30 @@ once it has one. - Name the precondition first. If a chain starts with "the attacker holds a full-scope token", it is a new vulnerability only if it widens that token's reach (2–3), outlives revocation (5), or shows how the token leaks (6). +- Name the actor next and what they can already do. If the only actor is the + user on their own device, or a principal reaching the same outcome via a + documented route, no boundary is crossed unless data goes somewhere they did + not send it. It may still be a bug; report it as one. +- Read tests and comments beside the code before calling a behaviour a defect. + They show author intent and are evidence, not a decision: a test can pin a + behaviour nobody chose, and a comment can be stale. Only this file and the + docs say what is intended. If only a test or comment supports a behaviour, + report it and say so. +- Follow the claim to its effect. A guard in a caller, a schema, or a version + check elsewhere often means the cited lines cannot do what the report says. +- Rate severity by what the actor must already hold, not the worst outcome + named. Each of these lowers severity and none removes the finding: a narrow + grant the owner chose to issue (the default grant is full scope); another OS + account on the same machine; a host or service the owner connected turning + hostile; a change that must land in the moment between a person's look and + their action; a person acting on prepared input (opening a file, pasting, + following a link); and an effect limited to resource use or a stalled + client. A finding that needs none of these, or that yields a session, a + credential, or code execution above the actor's grant, keeps its severity. - Check the reported commit against `main`. Reports often trail fixes. - Prove a finding with a failing test at the lowest layer that shows it, as [Verifying](AGENTS.md#verifying) describes. Do not run a PoC against - `~/.t3/userdata` or any live environment. Use a dev server on seeded data. + `~/.t3/userdata` or any live environment; use a dev server on seeded data. - Treat report attachments as untrusted. Extract them into an empty directory outside the worktree and read PoCs before running anything. - Fix confirmed findings rather than filing them. Keep advisory details out of diff --git a/TRADEMARK.md b/TRADEMARK.md new file mode 100644 index 0000000000000..346822bdfbc6c --- /dev/null +++ b/TRADEMARK.md @@ -0,0 +1,38 @@ +# Trademark and Branding Policy + +The [MIT License](./LICENSE) in this repository applies **only to the source code**. It does not grant any rights to T3 Tools, Inc.'s trademarks, service marks, trade names, trade dress, or branding. + +## Protected marks and brand assets + +T3 Tools, Inc. owns the following marks and brand assets, whether registered or unregistered: + +- The names **T3 Code**, **T3 Connect**, and **T3 Tools** +- The **T3** wordmark, logos, application icons (including the brand assets in [`assets/`](./assets/) and `T3Wordmark`), and visual trade dress +- Official domains (`t3.codes`, `app.t3.codes`) and official package or app store listings + +## Forks and derivative projects + +You are welcome to fork, modify, self-host, and redistribute the MIT-licensed source code under the terms of the [MIT License](./LICENSE). However, if you publish or distribute a fork, custom build, website, package, app store listing, or derivative project: + +- **Use your own branding.** Remove and replace the T3 Code name, wordmark, logos, application icons, and other T3 branding with your own. +- **Make it unmistakably clear that your project is unofficial.** You may not use the T3 Code name, wordmark, logo, or other branding in your own projects without being explicitly and prominently clear that your project is unofficial and is not affiliated with, endorsed by, or maintained by T3 Tools, Inc. +- **Keep references strictly factual.** You may include a truthful, plain-text attribution statement noting that your project is derived from this repository (for example, "An unofficial fork based on the T3 Code source code"), provided you do not use T3 logos or wordmarks, do not adopt "T3 Code" as your project's name or domain, and prominently state that your project is unofficial. + +## Prohibited uses and enforcement + +Using the T3 Code name, wordmark, logo, icons, or branding in your own projects without being explicitly clear that they are unofficial, or in any way that suggests official status, sponsorship, or affiliation, is trademark infringement and unlawful. + +**Any project indicating or implying that it is an official version of T3 Code when it is not will be pursued to the full extent of the law.** T3 Tools, Inc. actively enforces its trademark rights, including through platform takedowns, domain disputes, and legal action. + +## Official channels + +The only official T3 Code websites and distributions are: + +- Websites: [t3.codes](https://t3.codes) and [app.t3.codes](https://app.t3.codes) +- Source repository and releases: [github.com/pingdotgg/t3code](https://github.com/pingdotgg/t3code) +- CLI package: [`t3` on npm](https://www.npmjs.com/package/t3) +- Mobile apps: [iOS App Store](https://apps.apple.com/us/app/t3-code-remote-claude-more/id6787819824) and [Google Play](https://play.google.com/store/apps/details?id=com.t3tools.t3code) + +## Contact + +For trademark permission requests or to report unauthorized use or impersonation, contact [legal@t3.tools](mailto:legal@t3.tools). diff --git a/apps/desktop/scripts/preview-preload-bundle.test.mjs b/apps/desktop/scripts/preview-preload-bundle.test.mjs new file mode 100644 index 0000000000000..59da2e643700a --- /dev/null +++ b/apps/desktop/scripts/preview-preload-bundle.test.mjs @@ -0,0 +1,70 @@ +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeVM from "node:vm"; +import { JSDOM } from "jsdom"; +import { build } from "vite-plus/pack"; +import { assert, it } from "vite-plus/test"; + +import desktopConfig from "../vite.config.ts"; + +it("gives the page's world a function that runs without the preload's scope", async () => { + const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-preview-preload-")); + try { + assert.ok(Array.isArray(desktopConfig.pack)); + const packConfig = desktopConfig.pack.find( + (config) => + Array.isArray(config.entry) && config.entry.includes("src/preview-pick-preload.ts"), + ); + assert.ok(packConfig); + await build({ + ...packConfig, + config: false, + cwd: NodePath.join(import.meta.dirname, ".."), + outDir: directory, + sourcemap: false, + logLevel: "silent", + }); + const source = await NodeFSP.readFile( + NodePath.join(directory, "preview-pick-preload.cjs"), + "utf8", + ); + + const executions = []; + const electron = { + contextBridge: { + executeInMainWorld: (execution) => { + executions.push(execution); + return { elementContext: async () => null }; + }, + }, + ipcRenderer: { on: () => {}, off: () => {}, send: () => {}, sendToHost: () => {} }, + }; + const preload = new JSDOM("", { runScripts: "outside-only" }); + NodeVM.runInContext( + source, + Object.assign(preload.getInternalVMContext(), { + process: { argv: [] }, + require: (specifier) => { + assert.equal(specifier, "electron"); + return electron; + }, + }), + ); + assert.equal(executions.length, 1); + + // Electron compiles the function's source text in the page, where nothing of the preload exists. + const page = new JSDOM('', { + runScripts: "outside-only", + // React Grab binds requestAnimationFrame while it loads. + pretendToBeVisual: true, + }); + const install = NodeVM.runInContext(`(${executions[0].func})`, page.getInternalVMContext()); + const context = await install(...executions[0].args).elementContext( + page.window.document.getElementById("target"), + ); + assert.equal(context.selector, "#target"); + } finally { + await NodeFSP.rm(directory, { recursive: true, force: true }); + } +}); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index fd820a2c478d1..67ab6eb2195cc 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -2,6 +2,11 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; +import { + DESKTOP_READINESS_CHALLENGE_PARAM, + DESKTOP_READINESS_PROOF_PATH, + desktopReadinessProof, +} from "@t3tools/shared/desktopReadinessProof"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; @@ -699,6 +704,44 @@ describe("DesktopBackendConfiguration", () => { ), ); + it.effect("resolveWsl gives each launch a readiness probe only its own backend passes", () => + withHarness( + Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + + const primary = yield* configuration.resolvePrimary; + const first = yield* configuration.resolveWsl({ port: 5000, distro: null }); + const second = yield* configuration.resolveWsl({ port: 5000, distro: null }); + const firstSecret = first.bootstrap.desktopReadinessSecret; + const secondSecret = second.bootstrap.desktopReadinessSecret; + assert.isDefined(firstSecret); + assert.isDefined(secondSecret); + assert.notEqual(firstSecret, secondSecret); + assert.notEqual(firstSecret, first.bootstrap.desktopBootstrapSecret); + assert.isUndefined(first.bootstrap.desktopTelemetryControlFd); + assert.isUndefined(primary.readinessProbe); + assert.isDefined(first.readinessProbe); + + const probe = yield* first.readinessProbe!; + const laterProbe = yield* first.readinessProbe!; + assert.notEqual(probe.path, laterProbe.path); + const url = new URL(probe.path, first.httpBaseUrl); + assert.equal(url.pathname, DESKTOP_READINESS_PROOF_PATH); + const challenge = url.searchParams.get(DESKTOP_READINESS_CHALLENGE_PARAM)!; + const answerWith = (secret: string) => + desktopReadinessProof(secret, challenge).pipe(Effect.provide(NodeCrypto.layerMac)); + + assert.isTrue(yield* probe.accept(yield* answerWith(firstSecret!))); + assert.isFalse(yield* probe.accept(yield* answerWith(secondSecret!))); + assert.isFalse( + yield* probe.accept(yield* answerWith(first.bootstrap.desktopBootstrapSecret!)), + ); + assert.isFalse(yield* laterProbe.accept(yield* answerWith(firstSecret!))); + assert.isFalse(yield* probe.accept("{}")); + }), + ), + ); + it.effect("gives the Windows and WSL backends one host scope that survives a restart", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 5474583be9976..e3ad877d40c53 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -2,6 +2,11 @@ import * as NodeOS from "node:os"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; +import { + DESKTOP_READINESS_CHALLENGE_PARAM, + DESKTOP_READINESS_PROOF_PATH, + isValidDesktopReadinessProof, +} from "@t3tools/shared/desktopReadinessProof"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; @@ -586,10 +591,16 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv }, ); +interface LaunchReadiness { + readonly secret: string; + readonly probe: Effect.Effect; +} + const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl")(function* ( input: SharedBootstrapInput & { readonly port: number; readonly distro: string | null; + readonly readiness: LaunchReadiness; }, ): Effect.fn.Return< DesktopBackendManager.DesktopBackendStartConfig, @@ -615,6 +626,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl host: wslBindHost, desktopBootstrapToken: input.bootstrapToken, desktopBootstrapSecret: input.bootstrapSecret, + desktopReadinessSecret: input.readiness.secret, // PortSchema rejects 0 even when Tailscale Serve is disabled. tailscaleServeEnabled: false, tailscaleServePort: 443, @@ -704,6 +716,8 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl bootstrap, bootstrapDelivery: "stdin" as const, httpBaseUrl, + // wsl.exe carries no control channel, so the backend proves over HTTP that it is this launch. + readinessProbe: input.readiness.probe, captureOutput: true, ...(runningDistro !== null ? { runningDistro } : {}), }; @@ -796,6 +810,22 @@ export const make = Effect.gen(function* () { }), ); + // A secret per launch: only the backend started with it can pass that launch's probe. + const makeLaunchReadiness = Effect.gen(function* () { + const secret = Hex.encode(yield* random.randomBytes(32)); + const probe = Effect.gen(function* () { + const challenge = Hex.encode(yield* random.randomBytes(16).pipe(Effect.orDie)); + return { + path: `${DESKTOP_READINESS_PROOF_PATH}?${DESKTOP_READINESS_CHALLENGE_PARAM}=${challenge}`, + accept: (body: string) => + isValidDesktopReadinessProof(secret, challenge, body).pipe( + Effect.provideService(Mac.Mac, mac), + ), + }; + }); + return { secret, probe } satisfies LaunchReadiness; + }); + const sharedInputs = Effect.gen(function* () { const bootstrapSecret = yield* getOrCreateBootstrapSecret; const bootstrapToken = yield* currentDesktopBootstrapToken( @@ -823,6 +853,7 @@ export const make = Effect.gen(function* () { ...shared, port: backendExposure.port, distro: persistedSettings.wslDistro, + readiness: yield* makeLaunchReadiness, }).pipe( Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment), @@ -895,7 +926,8 @@ export const make = Effect.gen(function* () { resolveWsl: Effect.fnUntraced( function* (input) { const shared = yield* sharedInputs; - return yield* resolveWslStartConfig({ ...shared, ...input }).pipe( + const readiness = yield* makeLaunchReadiness; + return yield* resolveWslStartConfig({ ...shared, ...input, readiness }).pipe( Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment), Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree), diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index c69e84515533d..ff9bd656d2f1c 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -75,6 +75,18 @@ const configWithObservability: DesktopBackendBootstrapValue = { otlpTracesUrl: "http://127.0.0.1:4318/v1/traces", }; +const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" }); +const readyControlChannel: ChildProcessSpawner.ChildProcessHandle["getOutputFd"] = (fd) => + fd === 5 ? Stream.encodeText(Stream.make(`${readyLine}\n`)) : Stream.empty; + +// WSL backends get their bootstrap on stdin and have no control channel, so readiness is polled. +const { desktopTelemetryControlFd: _controlFd, ...pollingBootstrap } = baseConfig.bootstrap; +const pollingConfig: DesktopBackendManager.DesktopBackendStartConfig = { + ...baseConfig, + bootstrap: pollingBootstrap, + bootstrapDelivery: "stdin", +}; + function makeProcess(options?: { readonly stdout?: Stream.Stream; readonly stderr?: Stream.Stream; @@ -92,7 +104,7 @@ function makeProcess(options?: { kill: options?.kill ?? (() => Effect.void), stdin: Sink.drain, getInputFd: () => Sink.drain, - getOutputFd: options?.getOutputFd ?? (() => Stream.empty), + getOutputFd: options?.getOutputFd ?? readyControlChannel, unref: Effect.succeed(Effect.void), }); } @@ -205,6 +217,7 @@ describe("DesktopBackendManager", () => { const ready = yield* Deferred.make(); const exit = yield* Deferred.make(); const instance = yield* makeTestInstance({ + config: pollingConfig, spawnerLayer: Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => @@ -240,12 +253,66 @@ describe("DesktopBackendManager", () => { }), ); + it.effect("a polled backend is ready only once its listener answers as this launch", () => + Effect.gen(function* () { + const answersAsLaunch = yield* Ref.make(false); + const probedUrls = yield* Ref.make>([]); + const ready = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + config: { + ...pollingConfig, + readinessProbe: Effect.succeed({ + path: "/launch-proof?challenge=abc", + accept: (body: string) => Effect.succeed(body === "proof-for-abc"), + }), + }, + onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid), + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.acquireRelease( + Effect.succeed(makeProcess({ exitCode: Deferred.await(exit) })), + () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)), + ), + ), + ), + httpClientLayer: layerHttpClient((request) => + Ref.update(probedUrls, (urls) => [...urls, request.url]).pipe( + Effect.andThen(Ref.get(answersAsLaunch)), + Effect.map((asLaunch) => + HttpClientResponse.fromWeb( + request, + new Response(asLaunch ? "proof-for-abc" : "{}", { status: 200 }), + ), + ), + ), + ), + }); + yield* instance.start; + yield* TestClock.adjust(Duration.seconds(5)); + + assert.isFalse(yield* Deferred.isDone(ready)); + assert.isFalse((yield* instance.snapshot).ready); + assert.deepStrictEqual( + [...new Set(yield* Ref.get(probedUrls))], + ["http://127.0.0.1:3773/launch-proof?challenge=abc"], + ); + + yield* Ref.set(answersAsLaunch, true); + yield* TestClock.adjust(Duration.seconds(1)); + + assert.isTrue(yield* Deferred.isDone(ready)); + yield* instance.stop(); + }), + ); + it.effect("notices a WSL backend soon after it listens despite slow refused connects", () => Effect.gen(function* () { const ready = yield* Deferred.make(); const exit = yield* Deferred.make(); const instance = yield* makeTestInstance({ - config: { ...baseConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") }, + config: { ...pollingConfig, httpBaseUrl: new URL("http://172.20.84.98:3773") }, onReady: Deferred.succeed(ready, undefined).pipe(Effect.asVoid), spawnerLayer: Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -471,40 +538,41 @@ describe("DesktopBackendManager", () => { }), ); - it.effect("becomes ready from the server ready line while HTTP probes stall", () => - Effect.scoped( - Effect.gen(function* () { - const probeStarted = yield* Deferred.make(); - const exit = yield* Deferred.make(); - const readyLine = encodeDesktopTelemetryControl({ version: 1, type: "serverReady" }); - const instance = yield* makeTestInstance({ - spawnerLayer: Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => - Effect.succeed( - makeProcess({ - getOutputFd: (fd) => - fd === 5 - ? Stream.fromEffect(Deferred.await(probeStarted)).pipe( - Stream.flatMap(() => Stream.encodeText(Stream.make(`${readyLine}\n`))), - ) - : Stream.empty, - exitCode: Deferred.await(exit), - kill: () => - Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), - }), - ), + it.effect("a backend with a control channel is ready only once it says so there", () => + Effect.gen(function* () { + const announce = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.succeed( + makeProcess({ + getOutputFd: (fd) => + fd === 5 + ? Stream.fromEffect(Deferred.await(announce)).pipe( + Stream.flatMap(() => readyControlChannel(fd)), + ) + : Stream.empty, + exitCode: Deferred.await(exit), + kill: () => + Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid), + }), ), ), - httpClientLayer: layerHttpClient(() => - Deferred.succeed(probeStarted, undefined).pipe(Effect.andThen(Effect.never)), - ), - }); + ), + // An HTTP answer on the port is not the backend's own ready signal. + httpClientLayer: layerHealthyHttpClient, + }); - yield* instance.start; - assert.isTrue(yield* instance.waitForReady(Duration.seconds(15))); - }), - ), + yield* instance.start; + const early = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild); + yield* TestClock.adjust(Duration.seconds(15)); + assert.isFalse(yield* Fiber.join(early)); + + yield* Deferred.succeed(announce, undefined); + assert.isTrue(yield* instance.waitForReady(Duration.seconds(15))); + }).pipe(Effect.scoped), ); it.effect("continues routing desktop telemetry control messages after an invalid line", () => @@ -804,6 +872,7 @@ describe("DesktopBackendManager", () => { const reports = yield* Queue.unbounded(); const startInstance = (status: Ref.Ref, onReady?: Effect.Effect, stdout = "") => makeTestInstance({ + config: pollingConfig, spawnerLayer: Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make(() => diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 3f65c70305be6..32befda6e97cf 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -72,6 +72,12 @@ export interface BackendProcessContext { export type DesktopBackendBootstrapDelivery = "fd3" | "stdin"; +/** One readiness request and the test its answer must pass to count as this launch's backend. */ +export interface BackendReadinessProbe { + readonly path: string; + readonly accept: (body: string) => Effect.Effect; +} + export interface DesktopBackendStartConfig extends BackendProcessContext { readonly args: ReadonlyArray; readonly env: Record; @@ -82,6 +88,8 @@ export interface DesktopBackendStartConfig extends BackendProcessContext { readonly httpBaseUrl: URL; readonly captureOutput: boolean; readonly preflightFailure: Option.Option; + /** Set for a backend without a control channel; each evaluation yields a fresh probe. */ + readonly readinessProbe?: Effect.Effect; readonly runningDistro?: string; readonly wslRuntimeId?: string; readonly wslT3Home?: string | null; @@ -355,8 +363,13 @@ const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]); const STAGGERED_READINESS_POLLERS = 4; const READINESS_POLLER_STAGGER = Duration.millis(250); +interface HttpReadinessOptions extends BackendProcessContext { + readonly timeout: Duration.Duration; + readonly readinessProbe?: Effect.Effect; +} + const waitForHttpReady = ( - options: BackendProcessContext & { readonly timeout: Duration.Duration }, + options: HttpReadinessOptions, ): Effect.Effect => { const poll = pollHttpReady(options); if (LOOPBACK_HOSTNAMES.has(options.httpBaseUrl.hostname)) return poll; @@ -367,13 +380,16 @@ const waitForHttpReady = ( ); }; -const pollHttpReady = ( - options: BackendProcessContext & { readonly timeout: Duration.Duration }, -): Effect.Effect => { - const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl); - return waitForHttpReadyShared({ +const pollHttpReady = Effect.fnUntraced(function* ( + options: HttpReadinessOptions, +): Effect.fn.Return { + const probe = options.readinessProbe === undefined ? undefined : yield* options.readinessProbe; + const path = probe?.path ?? BACKEND_READINESS_PATH; + const readinessUrl = new URL(path, options.httpBaseUrl); + return yield* waitForHttpReadyShared({ baseUrl: options.httpBaseUrl.href, - path: BACKEND_READINESS_PATH, + path, + ...(probe === undefined ? {} : { accept: probe.accept }), timeoutMs: Duration.toMillis(options.timeout), intervalMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_INTERVAL), probeTimeoutMs: Duration.toMillis(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT), @@ -388,7 +404,7 @@ const pollHttpReady = ( cause, }), }); -}; +}); function drainBackendOutput( context: BackendProcessContext & { readonly pid: number }, @@ -599,19 +615,41 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( ).pipe(Effect.forkScoped), ); } + const readinessContext = { + executablePath: options.executablePath, + entryPath: options.entryPath, + cwd: options.cwd, + httpBaseUrl: options.httpBaseUrl, + }; + const readinessTimeout = options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT; + // A backend with a control fd reports readiness there itself, after its HTTP server is up. + // Backends without the fd, such as WSL, are polled over HTTP and must pass their readiness probe. + const awaitReady = + options.bootstrap.desktopTelemetryControlFd === undefined + ? waitForHttpReady({ + ...readinessContext, + timeout: readinessTimeout, + ...(options.readinessProbe === undefined + ? {} + : { readinessProbe: options.readinessProbe }), + }) + : Deferred.await(serverReady).pipe( + Effect.timeoutOrElse({ + duration: readinessTimeout, + orElse: () => + Effect.fail( + new BackendReadinessTimeoutError({ + ...readinessContext, + readinessUrl: new URL(BACKEND_READINESS_PATH, options.httpBaseUrl), + timeoutMs: Duration.toMillis(readinessTimeout), + cause: "The backend did not signal readiness on its control channel.", + }), + ), + }), + ); // Cold WSL boots across /mnt/c can exceed one probe budget; retry while the backend is alive. - // HTTP polling stays as the fallback for backends without the control fd, such as WSL. const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() => - Effect.raceFirst( - waitForHttpReady({ - executablePath: options.executablePath, - entryPath: options.entryPath, - cwd: options.cwd, - httpBaseUrl: options.httpBaseUrl, - timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT, - }), - Deferred.await(serverReady), - ).pipe( + awaitReady.pipe( Effect.flatMap(() => options.onReady?.(handle.pid) ?? Effect.void), Effect.as(true), Effect.catchTags({ diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index f32bc489a2194..7af3b0d21d0cf 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -43,7 +43,10 @@ const { logInfo: logBackendPoolInfo, logWarning: logBackendPoolWarning } = const makeRecovery = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; - if (environment.platform !== "darwin" || !environment.isPackaged) return undefined; + const supported = + environment.platform === "linux" || + (environment.platform === "darwin" && environment.isPackaged); + if (!supported) return undefined; const runFork = Effect.runForkWith(yield* Effect.context()); return DesktopBackendRecoveryProcess.make({ appDataDirectory: environment.appDataDirectory, diff --git a/apps/desktop/src/backend/DesktopBackendRecovery.test.ts b/apps/desktop/src/backend/DesktopBackendRecovery.test.ts index 41bccac67002d..0dc8fb8b61273 100644 --- a/apps/desktop/src/backend/DesktopBackendRecovery.test.ts +++ b/apps/desktop/src/backend/DesktopBackendRecovery.test.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off - Drive actual macOS subprocesses and their file permissions. +// @effect-diagnostics nodeBuiltinImport:off - Drive actual subprocesses and their file permissions. import * as NodeChildProcess from "node:child_process"; import * as NodeCrypto from "node:crypto"; import * as NodeFS from "node:fs"; @@ -12,8 +12,14 @@ import * as NodeProcess from "node:process"; import { assert, describe, expect, it } from "@effect/vitest"; import { make } from "./DesktopBackendRecovery.ts"; +import { linuxProcessIdentity } from "./LinuxProcessIdentity.ts"; import { loadMacProcessAuditToken } from "./MacProcessAuditToken.ts"; +const loadNative = () => + NodeProcess.platform === "darwin" + ? loadMacProcessAuditToken() + : Promise.resolve(linuxProcessIdentity); + const childCode = ` import { createServer } from "node:net"; process.once("message", () => { @@ -55,12 +61,13 @@ async function spawnTrackedBackend( appDataDirectory: string, stateDir: string, cleanup: AsyncDisposableStack, + options: { readonly execPath?: string; readonly env?: NodeJS.ProcessEnv } = {}, ) { const moduleUrl = new URL("./DesktopBackendRecovery.ts", import.meta.url).href; const launcher = NodeChildProcess.spawn( - NodeProcess.execPath, + options.execPath ?? NodeProcess.execPath, ["--input-type=module", "-e", launcherCode, moduleUrl, appDataDirectory, stateDir, childCode], - { stdio: ["ignore", "ignore", "inherit", "ipc"] }, + { stdio: ["ignore", "ignore", "inherit", "ipc"], env: options.env ?? NodeProcess.env }, ); const exited = NodeEvents.EventEmitter.once(launcher, "exit"); const stopLauncher = async () => { @@ -76,7 +83,7 @@ async function spawnTrackedBackend( throw new Error("Fixture launcher exited before its backend was ready"); }), ]); - const native = await loadMacProcessAuditToken(); + const native = await loadNative(); const token = native.read(backend.pid); assert.isDefined(token); cleanup.defer(() => native.signal(token, "SIGKILL")); @@ -93,109 +100,162 @@ async function checkPortIsFree(port: number) { } } -describe.runIf(NodeProcess.platform === "darwin")("macOS desktop backend recovery", () => { - it("cleans up a truncated record only after the writer releases it", async () => { - await using cleanup = new AsyncDisposableStack(); - const stateDir = await NodeFSP.realpath( - await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-record-")), +describe.runIf(NodeProcess.platform === "darwin" || NodeProcess.platform === "linux")( + "desktop backend recovery", + () => { + it.runIf(NodeProcess.platform === "darwin")( + "cleans up a truncated record only after the writer releases it", + async () => { + await using cleanup = new AsyncDisposableStack(); + const stateDir = await NodeFSP.realpath( + await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-record-")), + ); + cleanup.defer(() => NodeFSP.rm(stateDir, { recursive: true, force: true })); + const directory = NodePath.join(stateDir, "t3code-backend-recovery"); + await NodeFSP.mkdir(directory, { mode: 0o700 }); + const scope = NodeCrypto.createHash("sha256") + .update(JSON.stringify([stateDir, await NodeFSP.realpath(NodeProcess.execPath)])) + .digest("hex"); + const path = () => NodePath.join(directory, `${scope}.${NodeCrypto.randomUUID()}.json`); + const partial = path(); + const future = path(); + const unsafe = path(); + await NodeFSP.writeFile(future, '{"version":2}', { mode: 0o600 }); + await NodeFSP.writeFile(unsafe, "{", { mode: 0o600 }); + await NodeFSP.chmod(unsafe, 0o644); + const errors: unknown[] = []; + const recovered: number[] = []; + const recovery = make({ + appDataDirectory: stateDir, + stateDir, + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }); + { + // Darwin O_EXLOCK keeps the record private to the writer until close or exit. + await using writer = await NodeFSP.open( + partial, + NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL | 0x20, + 0o600, + ); + await writer.writeFile('{"version":'); + await recovery.recover(); + assert.equal(await NodeFSP.readFile(partial, "utf8"), '{"version":'); + } + await recovery.recover(); + await recovery.recover(); + await expect(NodeFSP.stat(partial)).rejects.toMatchObject({ code: "ENOENT" }); + assert.equal(await NodeFSP.readFile(future, "utf8"), '{"version":2}'); + assert.equal(await NodeFSP.readFile(unsafe, "utf8"), "{"); + assert.deepEqual(recovered, []); + assert.deepEqual(errors, []); + }, ); - cleanup.defer(() => NodeFSP.rm(stateDir, { recursive: true, force: true })); - const directory = NodePath.join(stateDir, "t3code-backend-recovery"); - await NodeFSP.mkdir(directory, { mode: 0o700 }); - const scope = NodeCrypto.createHash("sha256") - .update(JSON.stringify([stateDir, await NodeFSP.realpath(NodeProcess.execPath)])) - .digest("hex"); - const path = () => NodePath.join(directory, `${scope}.${NodeCrypto.randomUUID()}.json`); - const partial = path(); - const future = path(); - const unsafe = path(); - await NodeFSP.writeFile(future, '{"version":2}', { mode: 0o600 }); - await NodeFSP.writeFile(unsafe, "{", { mode: 0o600 }); - await NodeFSP.chmod(unsafe, 0o644); - const errors: unknown[] = []; - const recovered: number[] = []; - const recovery = make({ - appDataDirectory: stateDir, - stateDir, - launcherPid: NodeProcess.pid, - onRecovery: (pid) => recovered.push(pid), - onError: (_, error) => errors.push(error), - }); - { - // Darwin O_EXLOCK keeps the record private to the writer until close or exit. - await using writer = await NodeFSP.open( - partial, - NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL | 0x20, - 0o600, + + it("releases a frozen orphan's port and leaves a backend with a live launcher running", async () => { + await using cleanup = new AsyncDisposableStack(); + const appDataDirectory = await NodeFSP.mkdtemp( + NodePath.join(NodeOS.tmpdir(), "t3-backend-recovery-"), ); - await writer.writeFile('{"version":'); + cleanup.defer(() => NodeFSP.rm(appDataDirectory, { recursive: true, force: true })); + // The first launcher records ownership before the home exists. + const stateDir = NodePath.join(appDataDirectory, "home", "userdata"); + const orphan = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup); + await NodeFSP.mkdir(stateDir, { recursive: true }); + const live = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup); + const native = await loadNative(); + const recovered: number[] = []; + const errors: unknown[] = []; + const recovery = make({ + appDataDirectory, + stateDir, + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }); + + NodeProcess.kill(orphan.pid, "SIGSTOP"); + await orphan.stopLauncher(); + await expect(checkPortIsFree(orphan.port)).rejects.toMatchObject({ code: "EADDRINUSE" }); + + const wrongVersion = Buffer.from(live.token, "hex"); + wrongVersion[28] = wrongVersion[28]! ^ 1; + native.signal(wrongVersion.toString("hex"), "SIGKILL"); + assert.equal(native.read(live.pid), live.token); + + const otherHome = make({ + appDataDirectory, + stateDir: NodePath.join(stateDir, "other"), + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }); + await otherHome.recover(); + assert.deepEqual(recovered, []); + + const records = NodePath.join(appDataDirectory, "t3code-backend-recovery"); + for (const name of await NodeFSP.readdir(records)) + await NodeFSP.chmod(NodePath.join(records, name), 0o644); await recovery.recover(); - assert.equal(await NodeFSP.readFile(partial, "utf8"), '{"version":'); - } - await recovery.recover(); - await recovery.recover(); - await expect(NodeFSP.stat(partial)).rejects.toMatchObject({ code: "ENOENT" }); - assert.equal(await NodeFSP.readFile(future, "utf8"), '{"version":2}'); - assert.equal(await NodeFSP.readFile(unsafe, "utf8"), "{"); - assert.deepEqual(recovered, []); - assert.deepEqual(errors, []); - }); + assert.deepEqual(recovered, []); + assert.equal(native.read(orphan.pid), orphan.token); + for (const name of await NodeFSP.readdir(records)) + await NodeFSP.chmod(NodePath.join(records, name), 0o600); - it("releases a frozen orphan's port and leaves a backend with a live launcher running", async () => { - await using cleanup = new AsyncDisposableStack(); - const appDataDirectory = await NodeFSP.mkdtemp( - NodePath.join(NodeOS.tmpdir(), "t3-backend-recovery-"), - ); - cleanup.defer(() => NodeFSP.rm(appDataDirectory, { recursive: true, force: true })); - // The first launcher records ownership before the home exists. - const stateDir = NodePath.join(appDataDirectory, "home", "userdata"); - const orphan = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup); - await NodeFSP.mkdir(stateDir, { recursive: true }); - const live = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup); - const native = await loadMacProcessAuditToken(); - const recovered: number[] = []; - const errors: unknown[] = []; - const recovery = make({ - appDataDirectory, - stateDir, - launcherPid: NodeProcess.pid, - onRecovery: (pid) => recovered.push(pid), - onError: (_, error) => errors.push(error), + await recovery.recover(); + assert.deepEqual(errors, []); + assert.deepEqual(recovered, [orphan.pid]); + assert.isUndefined(native.read(orphan.pid)); + await checkPortIsFree(orphan.port); + assert.equal(native.read(live.pid), live.token); }); - NodeProcess.kill(orphan.pid, "SIGSTOP"); - await orphan.stopLauncher(); - await expect(checkPortIsFree(orphan.port)).rejects.toMatchObject({ code: "EADDRINUSE" }); - - const wrongVersion = Buffer.from(live.token, "hex"); - wrongVersion[28] = wrongVersion[28]! ^ 1; - native.signal(wrongVersion.toString("hex"), "SIGKILL"); - assert.equal(native.read(live.pid), live.token); - - const otherHome = make({ - appDataDirectory, - stateDir: NodePath.join(stateDir, "other"), - launcherPid: NodeProcess.pid, - onRecovery: (pid) => recovered.push(pid), - onError: (_, error) => errors.push(error), - }); - await otherHome.recover(); - assert.deepEqual(recovered, []); - - const records = NodePath.join(appDataDirectory, "t3code-backend-recovery"); - for (const name of await NodeFSP.readdir(records)) - await NodeFSP.chmod(NodePath.join(records, name), 0o644); - await recovery.recover(); - assert.deepEqual(recovered, []); - assert.equal(native.read(orphan.pid), orphan.token); - for (const name of await NodeFSP.readdir(records)) - await NodeFSP.chmod(NodePath.join(records, name), 0o600); - - await recovery.recover(); - assert.deepEqual(errors, []); - assert.deepEqual(recovered, [orphan.pid]); - assert.isUndefined(native.read(orphan.pid)); - await checkPortIsFree(orphan.port); - assert.equal(native.read(live.pid), live.token); - }); -}); + it.runIf(NodeProcess.platform === "linux")( + "recovers an AppImage orphan after a relaunch mounts the app at a new path", + async () => { + await using cleanup = new AsyncDisposableStack(); + const appDataDirectory = await NodeFSP.realpath( + await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-appimage-recovery-")), + ); + cleanup.defer(() => NodeFSP.rm(appDataDirectory, { recursive: true, force: true })); + const stateDir = NodePath.join(appDataDirectory, "home"); + const appImage = NodePath.join(appDataDirectory, "T3-Code.AppImage"); + await NodeFSP.writeFile(appImage, ""); + // The previous launch ran from another mount, so its executable path differs from ours. + const previousMount = NodePath.join(appDataDirectory, "mount-previous"); + await NodeFSP.mkdir(previousMount); + const previousExecutable = NodePath.join(previousMount, "node"); + await NodeFSP.link(NodeProcess.execPath, previousExecutable).catch(() => + NodeFSP.copyFile(NodeProcess.execPath, previousExecutable), + ); + const orphan = await spawnTrackedBackend(appDataDirectory, stateDir, cleanup, { + execPath: previousExecutable, + env: { ...NodeProcess.env, APPIMAGE: appImage }, + }); + const native = await loadNative(); + NodeProcess.kill(orphan.pid, "SIGSTOP"); + await orphan.stopLauncher(); + + const recovered: number[] = []; + const errors: unknown[] = []; + const previousAppImage = NodeProcess.env.APPIMAGE; + NodeProcess.env.APPIMAGE = appImage; + cleanup.defer(() => { + if (previousAppImage === undefined) delete NodeProcess.env.APPIMAGE; + else NodeProcess.env.APPIMAGE = previousAppImage; + }); + await make({ + appDataDirectory, + stateDir, + launcherPid: NodeProcess.pid, + onRecovery: (pid) => recovered.push(pid), + onError: (_, error) => errors.push(error), + }).recover(); + assert.deepEqual(errors, []); + assert.deepEqual(recovered, [orphan.pid]); + assert.isUndefined(native.read(orphan.pid)); + }, + ); + }, +); diff --git a/apps/desktop/src/backend/DesktopBackendRecovery.ts b/apps/desktop/src/backend/DesktopBackendRecovery.ts index 3077b69224001..d2a9560d0eba6 100644 --- a/apps/desktop/src/backend/DesktopBackendRecovery.ts +++ b/apps/desktop/src/backend/DesktopBackendRecovery.ts @@ -14,13 +14,16 @@ import { loadMacProcessAuditToken, type MacProcessAuditToken, } from "./MacProcessAuditToken.ts"; +import { linuxProcessIdentity } from "./LinuxProcessIdentity.ts"; const exec = NodeUtil.promisify(NodeChildProcess.execFile); const directoryName = "t3code-backend-recovery"; const maxRecordBytes = 512; -// Darwin sys/fcntl.h. Node accepts these open flags but does not export them. -const O_SHLOCK = 0x10; -const O_EXLOCK = 0x20; +const isDarwin = NodeProcess.platform === "darwin"; +// Darwin sys/fcntl.h. Node accepts these open flags but does not export them. Linux has no +// open-time locks, so there a record is written under a temporary name and renamed into place. +const O_SHLOCK = isDarwin ? 0x10 : 0; +const O_EXLOCK = isDarwin ? 0x20 : 0; const observedFileName = /^[0-9a-f]{64}\.[0-9a-f-]{36}\.json$/; const scopePattern = /^[0-9a-f]{64}$/; const bootIdPattern = /^[0-9a-f-]{36}$/i; @@ -144,7 +147,8 @@ async function recoverRecord( const ownsOrphan = () => status(native, record.launcher) === "gone" && status(native, record.backend) === "same" && - native.parent(backendPid) === 1; + // macOS reparents orphans to launchd; Linux may pick a subreaper such as systemd --user. + native.parent(backendPid) !== auditTokenPid(record.launcher); if (status(native, record.backend) === "gone") return true; if (!ownsOrphan()) return false; @@ -160,14 +164,18 @@ async function recoverRecord( } async function readBootId(): Promise { - const { stdout } = await exec("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { - timeout: 1_000, - }); - const bootId = stdout.trim(); - if (!bootIdPattern.test(bootId)) throw new Error("Could not identify the current macOS boot"); + const bootId = isDarwin + ? ( + await exec("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { timeout: 1_000 }) + ).stdout.trim() + : (await NodeFSP.readFile("/proc/sys/kernel/random/boot_id", "utf8")).trim(); + if (!bootIdPattern.test(bootId)) throw new Error("Could not identify the current boot"); return bootId; } +const loadProcessIdentity = (): Promise => + isDarwin ? loadMacProcessAuditToken() : Promise.resolve(linuxProcessIdentity); + // A first launch can precede creation of the state directory. Resolve existing // ancestors so a symlinked home keeps the same key after that directory appears. async function canonicalHome(path: string): Promise { @@ -190,12 +198,15 @@ export function make(input: { // Use Application Support even when the T3 home or the app lives on removable storage. const directory = NodePath.join(input.appDataDirectory, directoryName); const scope = async () => { - const [home, executable] = await Promise.all([ + const appImage = isDarwin ? undefined : NodeProcess.env.APPIMAGE?.trim(); + const [home, executable, installation] = await Promise.all([ canonicalHome(input.stateDir), NodeFSP.realpath(NodeProcess.execPath), + // An AppImage runs from a new mount path each launch; its file path is the stable install. + appImage ? NodeFSP.realpath(appImage) : undefined, ]); const prefix = NodeCrypto.createHash("sha256") - .update(JSON.stringify([home, executable])) + .update(JSON.stringify([home, installation ?? executable])) .digest("hex"); return { prefix, executable }; }; @@ -211,7 +222,7 @@ export function make(input: { async track(backendPid: number): Promise { try { const [native, bootId, { prefix, executable }] = await Promise.all([ - loadMacProcessAuditToken(), + loadProcessIdentity(), readBootId(), scope(), ]); @@ -232,10 +243,11 @@ export function make(input: { }); await privateDirectory(); const path = NodePath.join(directory, `${prefix}.${NodeCrypto.randomUUID()}.json`); + const writePath = isDarwin ? path : `${path}.partial`; // Take the lock at creation so recovery can distinguish a partial write from a crash. { await using file = await NodeFSP.open( - path, + writePath, NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL | @@ -246,6 +258,7 @@ export function make(input: { JSON.stringify({ version: 1, bootId, scope: prefix, launcher, backend }), ); } + if (writePath !== path) await NodeFSP.rename(writePath, path); return path; } catch (error) { input.onError("record backend", error); @@ -261,7 +274,7 @@ export function make(input: { ); if (records.length === 0) return; - const [bootId, native] = await Promise.all([readBootId(), loadMacProcessAuditToken()]); + const [bootId, native] = await Promise.all([readBootId(), loadProcessIdentity()]); await Promise.all( records.map(async (name) => { const path = NodePath.join(directory, name); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index c15ce3932bb80..a2c667cd476a4 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -218,6 +218,61 @@ describe("DesktopLocalEnvironmentAuth", () => { return { auth, requestCount }; }); + it.effect("does not retry the exchange while the backend is not ready", () => + Effect.gen(function* () { + const stopped = yield* Ref.make(false); + const readyAgain = yield* Deferred.make(); + const requestCount = yield* Ref.make(0); + const layerHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Ref.updateAndGet(requestCount, (count) => count + 1).pipe( + Effect.tap(() => Ref.set(stopped, true)), + Effect.map((count) => + count === 1 + ? HttpClientResponse.fromWeb(request, new Response(null, { status: 503 })) + : tokenResponse(request), + ), + ), + ), + ); + const layerRestartingPool = Layer.succeed(DesktopBackendPool.DesktopBackendPool, { + list: Effect.succeed([ + { + id: PRIMARY_LOCAL_ENVIRONMENT_ID, + label: Effect.succeed("Windows"), + currentConfig: Effect.succeedSome(config), + waitForReady: () => + Ref.get(stopped).pipe( + Effect.flatMap((isStopped) => + isStopped ? Deferred.await(readyAgain) : Effect.void, + ), + Effect.as(true), + ), + }, + ]), + } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]); + const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe( + Effect.provide( + DesktopLocalEnvironmentAuth.layer.pipe( + Layer.provide( + Layer.mergeAll(layerRestartingPool, layerHttpClient, NodeCrypto.layerMac), + ), + ), + ), + ); + + const fiber = yield* Effect.forkChild(auth.getBearerToken); + yield* TestClock.adjust(Duration.seconds(5)); + assert.strictEqual(yield* Ref.get(requestCount), 1); + + yield* Ref.set(stopped, false); + yield* Deferred.succeed(readyAgain, undefined); + assert.strictEqual(yield* Fiber.join(fiber), "desktop-bearer-token"); + assert.strictEqual(yield* Ref.get(requestCount), 2); + }).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 89aa3cd2a678c..25187f451f830 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -102,25 +102,32 @@ export const make = Effect.gen(function* () { if (!credential) { return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); } - const session = yield* bootstrapRemoteBearerSession({ - httpBaseUrl: config.httpBaseUrl.href, - credential, - clientMetadata: { - label: "T3 Code Desktop", - deviceType: "desktop", - }, - }).pipe( - Effect.provideService(HttpClient.HttpClient, httpClient), + const exchange = Effect.gen(function* () { + // Each attempt goes only to a backend that is currently ready. + if (!(yield* primary.waitForReady(Duration.infinity))) { + return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); + } + return yield* bootstrapRemoteBearerSession({ + httpBaseUrl: config.httpBaseUrl.href, + credential, + clientMetadata: { + label: "T3 Code Desktop", + deviceType: "desktop", + }, + }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)); + }); + const session = yield* exchange.pipe( Effect.retry({ - while: isTransientBearerBootstrapError, + while: (error) => + error._tag !== "DesktopLocalEnvironmentAuthBackendNotConfiguredError" && + isTransientBearerBootstrapError(error), schedule: Schedule.spaced(BOOTSTRAP_TRANSIENT_RETRY_INTERVAL), }), Effect.timeout(BOOTSTRAP_TRANSIENT_RETRY_TIMEOUT), - Effect.mapError( - (cause) => - new DesktopLocalEnvironmentAuthSessionBootstrapError({ - cause, - }), + Effect.mapError((cause) => + cause._tag === "DesktopLocalEnvironmentAuthBackendNotConfiguredError" + ? cause + : new DesktopLocalEnvironmentAuthSessionBootstrapError({ cause }), ), ); yield* Ref.set(tokenRef, Option.some(session.access_token)); diff --git a/apps/desktop/src/backend/LinuxProcessIdentity.ts b/apps/desktop/src/backend/LinuxProcessIdentity.ts new file mode 100644 index 0000000000000..2774ad426abfe --- /dev/null +++ b/apps/desktop/src/backend/LinuxProcessIdentity.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics nodeBuiltinImport:off - Recovery reads /proc synchronously inside its helper process. +import * as NodeFS from "node:fs"; +import * as NodeProcess from "node:process"; + +import type { MacProcessAuditToken } from "./MacProcessAuditToken.ts"; + +// Same 32-byte layout as a macOS audit token, so records and auditTokenPid work unchanged: +// the start time (clock ticks since boot) in bytes 0-7 and the PID at byte 20. +const TOKEN_BYTES = 32; +const PID_OFFSET = 20; + +function readStat(pid: number): { state: string; parent: number; startTime: bigint } | undefined { + let stat: string; + try { + stat = NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); + } catch { + return undefined; + } + // proc(5): the command name is in parentheses and may itself contain ") ". + const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + const parent = Number(fields[1]); + const startTime = fields[19]; + if (fields[0] === undefined || !Number.isSafeInteger(parent) || !/^\d+$/.test(startTime ?? "")) { + return undefined; + } + return { state: fields[0], parent, startTime: BigInt(startTime!) }; +} + +/** A PID with its start time; the recovery record's boot id makes the pair unique. */ +export const linuxProcessIdentity: MacProcessAuditToken = { + read(pid) { + const stat = readStat(pid); + // A zombie holds no lock and cannot be signalled into exiting. + if (stat === undefined || stat.state === "Z") return undefined; + const token = Buffer.alloc(TOKEN_BYTES); + token.writeBigUInt64LE(stat.startTime); + token.writeUInt32LE(pid, PID_OFFSET); + return token.toString("hex"); + }, + executable(pid) { + try { + return NodeFS.readlinkSync(`/proc/${pid}/exe`); + } catch { + return undefined; + } + }, + parent: (pid) => readStat(pid)?.parent, + signal(token, name) { + const pid = Buffer.from(token, "hex").readUInt32LE(PID_OFFSET); + // Node has no pidfd signal; checking the start time first leaves only a reuse race of + // microseconds, after the record's process was already seen as this backend. + if (linuxProcessIdentity.read(pid) !== token) return; + try { + NodeProcess.kill(pid, name); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } + }, +}; diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index a967c75383447..48b61dbefd025 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -85,6 +85,7 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM disabled: sourceItem.disabled === true, ...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}), ...(typeof sourceItem.checked === "boolean" ? { checked: sourceItem.checked } : {}), + ...(typeof sourceItem.iconImage === "string" ? { iconImage: sourceItem.iconImage } : {}), }; if (sourceItem.children) { @@ -114,6 +115,17 @@ const normalizePosition = ( Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })), ); +// Renderer icons are 32px PNGs; a 2x representation keeps them 16pt and sharp on Retina. +function menuIconImage(dataUrl: string): Option.Option { + try { + const image = Electron.nativeImage.createEmpty(); + image.addRepresentation({ scaleFactor: 2, dataURL: dataUrl }); + return image.isEmpty() ? Option.none() : Option.some(image); + } catch { + return Option.none(); + } +} + /** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -179,6 +191,12 @@ export const make = Effect.gen(function* () { } else { itemOption.click = () => complete(Option.some(item.id)); } + if (item.iconImage !== undefined) { + const image = menuIconImage(item.iconImage); + if (Option.isSome(image)) { + itemOption.icon = image.value; + } + } if (item.destructive && (!item.children || item.children.length === 0)) { const destructiveIcon = getDestructiveMenuIcon(); if (Option.isSome(destructiveIcon)) { diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts index d27c51d57c6eb..b10bde6fe6cbc 100644 --- a/apps/desktop/src/electron/ElectronShell.ts +++ b/apps/desktop/src/electron/ElectronShell.ts @@ -67,6 +67,12 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option { } } +/** Links that open in the browser, for callers such as popups that carry no identity. */ +export const parseWebExternalUrl = (rawUrl: unknown): Option.Option => + Option.filter(parseSafeExternalUrl(rawUrl), (url) => + SAFE_WEB_PROTOCOLS.has(new URL(url).protocol), + ); + export class ElectronShell extends Context.Service< ElectronShell, { diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 9c50501a1bdfd..02f60ef3358ac 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -131,6 +131,37 @@ describe("getLocalEnvironmentBootstraps", () => { ), ); + it.effect("includes the token only once the backend has reported ready", () => + 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/", + }, + ]); + }).pipe( + Effect.provide( + bootstrapsLayer([ + { + ...defaultWslInstance, + snapshot: Effect.succeed({ + desiredRunning: true, + ready: false, + activePid: Option.some(123), + restartAttempt: 0, + restartScheduled: false, + }), + }, + ]), + ), + ), + ); + it.effect("publishes a pending bootstrap only while a transient retry is scheduled", () => { const retryingConfig: DesktopBackendManager.DesktopBackendStartConfig = { ...readyWslConfig, diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index c6ad0bef18c81..ac69c40d4a917 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -187,12 +187,15 @@ export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({ runningDistro, httpBaseUrl: httpBaseUrl.href, wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl), + // The renderer uses this token with httpBaseUrl once the backend has reported ready. // Use the current window's derived token; the launch config's token may be stale. - ...(bootstrap.desktopBootstrapSecret - ? { bootstrapToken: yield* configuration.currentBootstrapToken } - : bootstrap.desktopBootstrapToken - ? { bootstrapToken: bootstrap.desktopBootstrapToken } - : {}), + ...(!snapshot.ready + ? {} + : bootstrap.desktopBootstrapSecret + ? { bootstrapToken: yield* configuration.currentBootstrapToken } + : bootstrap.desktopBootstrapToken + ? { bootstrapToken: bootstrap.desktopBootstrapToken } + : {}), }); } return bootstraps; diff --git a/apps/desktop/src/preview-pick-preload.ts b/apps/desktop/src/preview-pick-preload.ts index 3511f511321dd..03b55354cdfcc 100644 --- a/apps/desktop/src/preview-pick-preload.ts +++ b/apps/desktop/src/preview-pick-preload.ts @@ -1,17 +1,7 @@ -import { ipcRenderer } from "electron"; - -import { - PASSKEY_BRIDGE_ARGUMENT, - PRIMARY_PASTE_DISABLED_ARGUMENT, -} from "./preview/GuestProtocol.ts"; -import { installPasskeyBridge } from "./preview/PasskeyBridge.ts"; +import { PRIMARY_PASTE_DISABLED_ARGUMENT } from "./preview/GuestProtocol.ts"; import "./preview/PickPreload.ts"; // Electron hands webPreferences.additionalArguments to sandboxed preloads in process.argv. -if (process.argv.includes(PASSKEY_BRIDGE_ARGUMENT)) { - installPasskeyBridge((channel, publicKey) => ipcRenderer.invoke(channel, publicKey)); -} - if (process.argv.includes(PRIMARY_PASTE_DISABLED_ARGUMENT)) { // Same guard as the app preload: Blink pastes PRIMARY on an uncancelled middle mouseup. window.addEventListener( diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 8e96129293fc8..1eb6f00da37cb 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -16,6 +16,11 @@ const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); const decodeCdpReply = Schema.decodeUnknownSync( Schema.fromJsonString(Schema.Struct({ id: Schema.Number })), ); +const decodeCdpError = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ error: Schema.optional(Schema.Struct({ message: Schema.String })) }), + ), +); const decodeCdpMessage = Schema.decodeUnknownSync( Schema.fromJsonString( Schema.Struct({ @@ -50,7 +55,13 @@ const makeDebuggee = ( readonly deferFocus?: boolean; /** The guest is still loading its first page. */ readonly loading?: boolean; + /** Like a guest of a hidden window: it answers a capture only once Electron captures it. */ + readonly drawsOnlyWhenCaptured?: () => boolean; + /** Electron's capture of this guest never settles. */ + readonly capturesStall?: () => boolean; readonly refuse?: (method: string, sessionId: string | undefined) => boolean; + /** Answers a command at once with this value, unless it returns undefined. */ + readonly answer?: (method: string, sessionId: string | undefined) => unknown; } = {}, ) => { const emitter = new NodeEvents.EventEmitter(); @@ -58,6 +69,7 @@ const makeDebuggee = ( const focusChanges: Array<() => void> = []; const sent: Array = []; const methods: Array = []; + const sessionIds: Array = []; const rejects: Array<() => void> = []; const sendWaiters: Array<() => void> = []; const focusEmulation: Array = []; @@ -82,15 +94,28 @@ const makeDebuggee = ( else resolve({}); return; } + const answer = options.answer?.(method, sessionId); + if (answer !== undefined) { + resolve(answer); + return; + } sent.push(params?.id); methods.push(method); + sessionIds.push(sessionId); rejects.push(() => reject(new Error("Refused"))); pending.push(() => resolve({ method })); sendWaiters.shift()?.(); }), }); let destroyed = false; + let nativeCaptures = 0; const webContents = Object.assign(new NodeEvents.EventEmitter(), { + capturePage: () => { + nativeCaptures += 1; + if (options.capturesStall?.()) return new Promise(() => {}); + if (options.drawsOnlyWhenCaptured?.()) pending.splice(0).forEach((resolve) => resolve()); + return Promise.resolve({}); + }, getURL: () => "http://localhost/", getTitle: () => "Page", getUserAgent: () => "Electron", @@ -114,9 +139,12 @@ const makeDebuggee = ( sent, /** Methods of the same commands, in order. */ methods, + /** Sessions of the same commands, in order; undefined for the page. */ + sessionIds, /** Refuses the pending command the debugger received with this id. */ refuse: (id: number) => rejects[sent.indexOf(id)]?.(), focusEmulation, + nativeCaptures: () => nativeCaptures, nextSend: () => new Promise((resolve) => sendWaiters.push(resolve)), release: () => pending.splice(0).forEach((resolve) => resolve()), releaseFirst: () => pending.shift()?.(), @@ -364,6 +392,91 @@ describe("DesktopBrowserHost", () => { }).pipe(Effect.scoped), ); + it.effect("prods a guest its window stopped drawing until what waits on it settles", () => + Effect.gen(function* () { + let drawsWhenCaptured = true; + let capturesStall = false; + const host = yield* makeDrawnHost; + const debuggee = makeDebuggee({ + drawsOnlyWhenCaptured: () => drawsWhenCaptured, + capturesStall: () => capturesStall, + }); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const painting = yield* watchPainting(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("250 millis"); + expect(yield* Queue.take(replies)).toBe(1); + expect(debuggee.nativeCaptures()).toBe(1); + + // A wait that settles within a frame is never prodded. + yield* command(host, 3, "Page.captureScreenshot"); + yield* settle; + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(3); + yield* TestClock.adjust("1 second"); + expect(debuggee.nativeCaptures()).toBe(1); + + // A long wait is prodded less often as it goes on, once per tick though it holds focus too. + drawsWhenCaptured = false; + yield* command(host, 4, "Page.captureScreenshot"); + yield* settle; + for (const [wait, prods] of [ + ["250 millis", 2], + ["500 millis", 3], + ["1 second", 4], + ["2 seconds", 5], + ["2 seconds", 6], + ] as const) { + yield* TestClock.adjust(wait); + expect(debuggee.nativeCaptures()).toBe(prods); + } + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(4); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(6); + + // A command that outlasts its first prod is painted like a capture, which also unthrottles it. + // A wait the agent's turn gave up on is no longer prodded. + yield* command(host, 5, "Runtime.evaluate"); + yield* settle; + painting.length = 0; + yield* TestClock.adjust("250 millis"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true]); + yield* host.handleCommandLine( + encodeJson({ type: "turn", threadId: key.threadId, active: false }), + ); + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(7); + expect(painting).toEqual([true, false]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(5); + + // Captures Electron never settles pile up no further than two. + capturesStall = true; + yield* command(host, 6, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(6); + // Even across a reattach of the same guest, as when DevTools closes. + host.detach(key); + host.attach(key, debuggee.tab); + const reattached = yield* watchReplies(host); + yield* command(host, 7, "Runtime.evaluate"); + yield* settle; + yield* TestClock.adjust("10 seconds"); + expect(debuggee.nativeCaptures()).toBe(9); + debuggee.releaseFirst(); + expect(yield* Queue.take(reattached)).toBe(7); + }).pipe(Effect.scoped), + ); + it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { const host = yield* makeDrawnHost; @@ -997,6 +1110,118 @@ describe("DesktopBrowserHost", () => { }), ); + it.effect("finds the frame under the mouse only on a guest the window does not show", () => + Effect.gen(function* () { + const host = yield* makeDrawnHost; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const move = (id: number) => + host.handleCommandLine( + encodeJson({ + type: "cdp", + ...key, + message: encodeJson({ + id, + method: "Input.dispatchMouseEvent", + params: { id, type: "mouseMoved", x: 5, y: 5 }, + sessionId: "t3-preview-page", + }), + }), + ); + + // No cross-site frame is attached yet. + yield* move(1); + yield* settle; + expect(debuggee.methods).toEqual(["Input.dispatchMouseEvent"]); + debuggee.release(); + + debuggee.emit("Target.attachedToTarget", { + sessionId: "FRAME-SESSION", + targetInfo: { targetId: "FRAME", type: "iframe" }, + }); + yield* move(2); + yield* settle; + expect(debuggee.methods.at(-1)).toBe("Page.getLayoutMetrics"); + // A lookup that fails leaves the event on the page. + debuggee.releaseFirst(); + yield* settle; + expect(debuggee.methods.at(-1)).toBe("Input.dispatchMouseEvent"); + debuggee.release(); + + host.setShown(key, true); + yield* move(3); + yield* settle; + debuggee.release(); + host.setShown(key, false); + debuggee.emit("Target.detachedFromTarget", { sessionId: "FRAME-SESSION" }); + yield* move(4); + yield* settle; + expect(debuggee.methods.slice(-2)).toEqual([ + "Input.dispatchMouseEvent", + "Input.dispatchMouseEvent", + ]); + expect(debuggee.methods.filter((method) => method === "Page.getLayoutMetrics")).toHaveLength( + 1, + ); + }), + ); + + it.effect("fails mouse input whose frame detaches before taking it, then moves on", () => + Effect.gen(function* () { + const host = yield* makeDrawnHost; + const lookup: Record = { + "Page.getLayoutMetrics": { cssLayoutViewport: { pageX: 0, pageY: 0 } }, + "DOM.getNodeForLocation": { backendNodeId: 1 }, + "DOM.describeNode": { node: { frameId: "FRAME" } }, + "DOM.getBoxModel": { model: { content: [0, 0, 100, 0, 100, 100, 0, 100] } }, + }; + const debuggee = makeDebuggee({ answer: (method) => lookup[method] }); + host.attach(key, debuggee.tab); + const errors: Array = []; + yield* host.events.pipe( + Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type !== "cdp") return; + const { error } = decodeCdpError(event.message); + if (error) errors.push(error.message); + }), + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const mouse = (id: number, type: string) => + host.handleCommandLine( + encodeJson({ + type: "cdp", + ...key, + message: encodeJson({ + id, + method: "Input.dispatchMouseEvent", + params: { id, type, x: 5, y: 5 }, + sessionId: "t3-preview-page", + }), + }), + ); + + debuggee.emit("Target.attachedToTarget", { + sessionId: "FRAME-SESSION", + targetInfo: { targetId: "FRAME", type: "iframe" }, + }); + yield* mouse(1, "mousePressed"); + yield* settle; + expect(debuggee.sessionIds).toEqual(["FRAME-SESSION"]); + + // Chromium never acknowledges input on a frame that detaches first. + debuggee.emit("Target.detachedFromTarget", { sessionId: "FRAME-SESSION" }); + yield* settle; + expect(errors).toEqual([expect.stringContaining("went away before it took this input")]); + yield* mouse(2, "mouseReleased"); + yield* settle; + expect(debuggee.sessionIds).toEqual(["FRAME-SESSION", undefined]); + }), + ); + it.effect("paints a hidden guest only while the screenshot it is taking is pending", () => Effect.gen(function* () { const host = yield* makeDrawnHost; @@ -1374,6 +1599,101 @@ describe("DesktopBrowserHost", () => { }).pipe(Effect.scoped), ); + it.effect("relays no input to a guest while the person at its window annotates it", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + let annotating = true; + host.attach(key, { ...debuggee.tab, annotating: () => annotating }); + const refusals: Array = []; + yield* host.events.pipe( + Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type !== "cdp") return; + const { id } = decodeCdpMessage(event.message); + const { error } = decodeCdpError(event.message); + if (id !== undefined && error?.message.includes("annotat")) refusals.push(id); + }), + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + yield* raw({ id: 1, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + yield* settle; + + // A viewer's own session and the page's, as a person and an agent send them. + yield* raw({ + id: 10, + method: "Input.dispatchKeyEvent", + params: { id: 10, type: "rawKeyDown" }, + sessionId: "t3-preview-page-1", + }); + yield* command(host, 11, "Input.insertText"); + yield* command(host, 12, "Input.dispatchKeyEvent"); + yield* settle; + expect(debuggee.methods).toEqual([]); + expect(refusals).toEqual([10, 11, 12]); + + // The page stays readable meanwhile, and input resumes once the annotation ends. + yield* command(host, 20, "DOM.getDocument"); + yield* settle; + expect(debuggee.methods).toEqual(["DOM.getDocument"]); + annotating = false; + yield* command(host, 21, "Input.insertText"); + yield* settle; + expect(debuggee.methods).toHaveLength(2); + expect(refusals).toEqual([10, 11, 12]); + }).pipe(Effect.scoped), + ); + + it.effect("relays no input that was still waiting when the annotation started", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee({ deferFocus: true }); + let annotating = false; + host.attach(key, { ...debuggee.tab, annotating: () => annotating }); + const refusals: Array = []; + yield* host.events.pipe( + Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type !== "cdp") return; + const { id } = decodeCdpMessage(event.message); + const { error } = decodeCdpError(event.message); + if (id !== undefined && error?.message.includes("annotat")) refusals.push(id); + }), + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + + // Waiting for the guest to take focus. + yield* command(host, 1, "Input.dispatchMouseEvent"); + yield* settle; + expect(debuggee.methods).toEqual([]); + annotating = true; + debuggee.settleFocus(); + yield* settle; + expect(debuggee.methods).toEqual([]); + expect(refusals).toEqual([1]); + + // Waiting behind an earlier pointer event the guest has not answered. + annotating = false; + yield* command(host, 2, "Input.dispatchMouseEvent"); + yield* command(host, 3, "Input.dispatchMouseEvent"); + yield* settle; + expect(debuggee.sent).toEqual([2]); + annotating = true; + debuggee.release(); + yield* settle; + expect(debuggee.sent).toEqual([2]); + expect(refusals).toEqual([1, 3]); + }).pipe(Effect.scoped), + ); + it.effect("detaches only the tab whose CDP event is too large to relay", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index ce5d7074a786c..b0fe8509a51fa 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -17,7 +17,12 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts"; -import { sendPageCommand } from "./GuestInput.ts"; +import { + type FrameDetachWatch, + type PointerRoute, + routeMouseToFrame, + sendPageCommand, +} from "./GuestInput.ts"; const encodeEvent = Schema.encodeSync(Schema.fromJsonString(DesktopBrowserEvent)); const decodeCommand = Schema.decodeUnknownOption(Schema.fromJsonString(DesktopBrowserCommand)); @@ -29,9 +34,17 @@ const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|cal const AGENT_INPUT_WINDOW_MS = 5_000; /** A viewer's pointer travelling over the stream activates nothing on the page. */ const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); +const ANNOTATING_MESSAGE = + "This page is being annotated in the desktop app. Input resumes when the annotation ends."; const FOCUS_IDLE = "5 seconds"; /** How long a screenshot waits for the client to draw its guest at full detail. */ const CAPTURE_DRAW_WAIT = "1 second"; +/** Most waits settle within a frame or two of this, so a quick one is never prodded. */ +const PAINT_NUDGE_FIRST_MS = 250; +/** A long wait, such as a page awaiting a timer, is prodded less often as it goes on. */ +const PAINT_NUDGE_LONGEST_MS = 2_000; +/** Electron's capture has no deadline and a cold guest can stall one, so a second may follow. */ +const PAINT_NUDGE_IN_FLIGHT = 2; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -46,10 +59,61 @@ export interface DesktopBrowserTabDebugger { readonly debugger: Electron.Debugger; /** Runs after the server clears the tab's cookies, so state kept beside them goes too. */ readonly cookiesCleared?: () => Promise; + /** Whether the person at this window is annotating the page, whose overlay is theirs alone. */ + readonly annotating?: () => boolean; } const keyOf = ({ threadId, tabId }: DesktopBrowserTabKey) => `${threadId}\u0000${tabId}`; +const trackFrameSession = ( + tab: { + readonly frameSessions: Map; + readonly frameDetachListeners: Map void>>; + }, + method: string, + params: unknown, +) => { + if (method === "Target.attachedToTarget") { + const { sessionId, targetInfo } = params as { + readonly sessionId?: string; + readonly targetInfo?: { readonly targetId?: string; readonly type?: string }; + }; + if (targetInfo?.type === "iframe" && targetInfo.targetId && sessionId) { + tab.frameSessions.set(targetInfo.targetId, sessionId); + } + } else if (method === "Target.detachedFromTarget") { + const { sessionId } = params as { readonly sessionId?: string }; + for (const [frameId, frameSession] of tab.frameSessions) { + if (frameSession === sessionId) tab.frameSessions.delete(frameId); + } + if (sessionId === undefined) return; + const listeners = tab.frameDetachListeners.get(sessionId); + tab.frameDetachListeners.delete(sessionId); + for (const listener of listeners ?? []) listener(); + } +}; + +const watchFrameDetach = + (tab: { + readonly frameSessions: Map; + readonly frameDetachListeners: Map void>>; + }): FrameDetachWatch => + (sessionId, listener) => { + if (![...tab.frameSessions.values()].includes(sessionId)) { + listener(); + return () => {}; + } + const listeners = tab.frameDetachListeners.get(sessionId) ?? new Set(); + tab.frameDetachListeners.set(sessionId, listeners); + listeners.add(listener); + return () => { + listeners.delete(listener); + if (listeners.size === 0 && tab.frameDetachListeners.get(sessionId) === listeners) { + tab.frameDetachListeners.delete(sessionId); + } + }; + }; + interface AttachedTab { readonly key: DesktopBrowserTabKey; readonly debuggee: DesktopBrowserTabDebugger; @@ -73,6 +137,15 @@ interface AttachedTab { readonly focusPending: Map; /** Screenshots Chromium was sent and has not answered; each keeps its wake lock until then. */ readonly capturing: Set; + /** Each wait on the guest's next frame, as whether it still waits; the guest is prodded until none do. */ + readonly frameWaits: Set<() => boolean>; + /** Sessions of the guest's cross-site frames that Chromium attached, by frame id. */ + readonly frameSessions: Map; + /** Input sent to a frame session, waiting to learn if the frame detaches first. */ + readonly frameDetachListeners: Map void>>; + nudging: Fiber.Fiber | null; + /** A wait outlasted its first nudge, so the guest is painted and unthrottled like a capture. */ + frameStalled: boolean; /** Whether the client keeps the guest painting, as published on `painting`. */ painting: boolean; /** @@ -243,7 +316,7 @@ export const make = Effect.gen(function* () { }; /** - * Electron composites no offscreen guest, so its screenshot or screencast waits for a frame + * Electron composites no offscreen guest, so a screenshot, screencast or stalled command waits for a frame * that never comes. The client paints the guest behind the app while one is pending; the * capture then finishes on its own, and the guest goes back offscreen once none is. */ @@ -252,12 +325,78 @@ export const make = Effect.gen(function* () { tabs.get(keyOf(tab.key)) === tab && (tab.screencasts.size > 0 || tab.capturing.size > 0 || + tab.frameStalled || tab.waitingScreenshots.some((waiting) => waiting.live())); if (tab.painting === active) return; tab.painting = active; runFork(PubSub.publish(painting, { key: tab.key, active })); }; + /** By guest rather than attachment, since reopening DevTools reattaches the same guest. */ + const nativeCaptures = new WeakMap(); + const startNudging = (tab: AttachedTab) => { + tab.nudging ??= runFork(nudgePaint(tab, PAINT_NUDGE_FIRST_MS)); + }; + + const endNudging = (tab: AttachedTab) => { + tab.nudging = null; + if (!tab.frameStalled) return; + tab.frameStalled = false; + syncPainting(tab); + }; + + /** + * A hidden, minimized or covered window (which Electron reports as visible) stops drawing its + * guest, so a wait on its next frame never ends. Electron's own capture still draws one. + */ + const nudgePaint = (tab: AttachedTab, delayMs: number): Effect.Effect => + Effect.sleep(delayMs).pipe( + Effect.andThen( + Effect.suspend(() => { + const { webContents } = tab.debuggee; + for (const waits of tab.frameWaits) if (!waits()) tab.frameWaits.delete(waits); + if ( + tab.frameWaits.size === 0 || + tabs.get(keyOf(tab.key)) !== tab || + webContents.isDestroyed() + ) { + endNudging(tab); + return Effect.void; + } + // On Windows a hidden window's throttled guest draws nothing, and capturePage cannot wake it. + if (!tab.frameStalled) { + tab.frameStalled = true; + syncPainting(tab); + } + const inFlight = nativeCaptures.get(webContents) ?? 0; + if (inFlight < PAINT_NUDGE_IN_FLIGHT) { + nativeCaptures.set(webContents, inFlight + 1); + const settled = () => { + nativeCaptures.set(webContents, (nativeCaptures.get(webContents) ?? 1) - 1); + }; + webContents.capturePage().then(settled, settled); + } + return nudgePaint(tab, Math.min(delayMs * 2, PAINT_NUDGE_LONGEST_MS)); + }), + ), + ); + + /** Prods the guest while `work` is pending and `waits` holds; one loop serves all of a tab's waits. */ + const nudgedUntilSettled = ( + tab: AttachedTab, + waits: () => boolean, + work: () => Promise, + ) => { + tab.frameWaits.add(waits); + startNudging(tab); + return work().finally(() => { + tab.frameWaits.delete(waits); + if (tab.frameWaits.size > 0 || tab.nudging === null) return; + runFork(Fiber.interrupt(tab.nudging)); + endNudging(tab); + }); + }; + /** A command may wait on the page's next frame, so the guest stays focused until it settles. */ const holdFocus = (tab: AttachedTab, owner: string | undefined, work: () => Promise) => { const pending = {}; @@ -265,7 +404,8 @@ export const make = Effect.gen(function* () { tab.focusUses += 1; setFocusEmulation(tab, true); releaseFocusWhenIdle(tab); - return work().finally(() => { + // Dropping the hold, at a turn's end or a new document, stops the prods too. + return nudgedUntilSettled(tab, () => tab.focusPending.has(pending), work).finally(() => { if (!tab.focusPending.delete(pending)) return; tab.focusUses += 1; releaseFocusWhenIdle(tab); @@ -296,11 +436,14 @@ export const make = Effect.gen(function* () { const sent = {}; tab.capturing.add(sent); syncPainting(tab); + const sendNudged = () => nudgedUntilSettled(tab, () => tab.capturing.has(sent), send); // Sent at once when already drawn, so it keeps its place among the commands after it. - return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { - tab.capturing.delete(sent); - syncPainting(tab); - }); + return (drawnTabs.has(keyOf(tab.key)) ? sendNudged() : whenDrawn(tab).then(sendNudged)).finally( + () => { + tab.capturing.delete(sent); + syncPainting(tab); + }, + ); }; /** @@ -356,8 +499,29 @@ export const make = Effect.gen(function* () { const relayFor = (tab: AttachedTab) => { if (tab.relay) return tab.relay; const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee; + const routeHidden = routeMouseToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab)); + // Read when the pointer queue reaches the event: a guest the window shows routes its own input. + const routeMouse: PointerRoute = (params) => + shownTabs.get(keyOf(tab.key)) === true ? Promise.resolve(null) : routeHidden(params); + // The annotation overlay lives in the guest and takes any input sent there as the + // person's at this window, so relayed input waits until they finish. + const annotated = (method: string) => + method.startsWith("Input.") && tab.debuggee.annotating?.() === true; const send = async (method: string, params: Record, sessionId?: string) => { - const result = await sendPageCommand(webContents, debuggee, method, params, sessionId); + // Asked again at each dispatch: an annotation can start while the input waits its turn. + const refuseAnnotated = () => { + if (annotated(method)) throw new Error(ANNOTATING_MESSAGE); + }; + refuseAnnotated(); + const result = await sendPageCommand( + webContents, + debuggee, + method, + params, + sessionId, + routeMouse, + refuseAnnotated, + ); if (method === "Network.clearBrowserCookies") await cookiesCleared?.(); return result; }; @@ -382,6 +546,7 @@ export const make = Effect.gen(function* () { syncPainting(tab); if (tab.screencasts.size > 0) return Promise.resolve({}); } + if (annotated(method)) return Promise.reject(new Error(ANNOTATING_MESSAGE)); // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's. if (AGENT_INPUT_METHOD.test(method)) { if (owner === undefined || !streamingOwners.has(owner)) { @@ -514,6 +679,12 @@ export const make = Effect.gen(function* () { tab.relay = null; tab.debuggee.debugger.off("message", tab.onMessage); tab.debuggee.webContents.off("did-navigate", tab.onNewDocument); + // Input routed to a frame would wait for a detach event the tab no longer hears. + const listeners = [...tab.frameDetachListeners.values()].flatMap((set) => [...set]); + tab.frameDetachListeners.clear(); + // A route resolved after this would find no session and go to the page. + tab.frameSessions.clear(); + for (const listener of listeners) listener(); syncPainting(tab); if (announced) emit({ type: "detached", ...key }); }; @@ -537,6 +708,11 @@ export const make = Effect.gen(function* () { focusUses: 0, focusPending: new Map(), capturing: new Set(), + frameWaits: new Set(), + frameSessions: new Map(), + frameDetachListeners: new Map(), + nudging: null, + frameStalled: false, painting: false, agentUsed: false, focusReleasing: false, @@ -546,6 +722,7 @@ export const make = Effect.gen(function* () { const guid = (params as { guid?: unknown } | undefined)?.guid; tab.pendingDownloadGuid = typeof guid === "string" ? guid : null; } + trackFrameSession(tab, method, params); tab.relay?.event(method, params, sessionId); }, // A screenshot pending when the page loads a new document, a reload included, can diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index 48191ce2c4b98..47941de0bd27d 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -2,7 +2,7 @@ import * as NodeVM from "node:vm"; import { describe, expect, it, vi } from "vite-plus/test"; -import { sendPageCommand, toKeyboardInputEvents } from "./GuestInput.ts"; +import { routeMouseToFrame, sendPageCommand, toKeyboardInputEvents } from "./GuestInput.ts"; const makeGuest = ({ focused, @@ -264,6 +264,149 @@ describe("preview guest input", () => { }, ); + describe("mouse input over a cross-site frame of a guest the window does not show", () => { + type Box = readonly [left: number, top: number, right: number, bottom: number]; + // Boxes are in each frame's viewport. The page is scrolled 1000px and holds a cross-site + // frame with a 10px border and a same-site frame; the cross-site frame, scrolled 300px, + // holds another cross-site frame. + const documents: Record< + string, + { + readonly ownFrameId: string; + readonly scroll: { readonly pageX: number; readonly pageY: number }; + readonly owners: ReadonlyArray<{ border: Box; content: Box; frameId: string }>; + } + > = { + page: { + ownFrameId: "MAIN", + scroll: { pageX: 0, pageY: 1000 }, + owners: [ + { border: [0, 89, 620, 409], content: [10, 99, 610, 399], frameId: "CROSS" }, + { border: [700, 0, 900, 200], content: [700, 0, 900, 200], frameId: "SAME" }, + ], + }, + "session-cross": { + ownFrameId: "CROSS", + scroll: { pageX: 0, pageY: 300 }, + owners: [ + { border: [100, 100, 300, 300], content: [100, 100, 300, 300], frameId: "NESTED" }, + ], + }, + "session-nested": { ownFrameId: "NESTED", scroll: { pageX: 0, pageY: 0 }, owners: [] }, + }; + const inside = ([left, top, right, bottom]: Box, x: number, y: number) => + x >= left && x < right && y >= top && y < bottom; + const makeFramedGuest = ( + frameSessions: ReadonlyMap = new Map([ + ["CROSS", "session-cross"], + ["NESTED", "session-nested"], + ]), + unansweredLookup?: string, + ) => { + const input: Array<{ sessionId: string | undefined; x: unknown; y: unknown }> = []; + const lookups: Array<{ sessionId: string | undefined; x: unknown; y: unknown }> = []; + const sendCommand = vi.fn( + async (method: string, params: Record, sessionId?: string) => { + const document = documents[sessionId ?? "page"]!; + if (method === "Page.getLayoutMetrics") { + if (sessionId !== undefined && sessionId === unansweredLookup) { + return new Promise(() => {}); + } + return { cssLayoutViewport: document.scroll }; + } + if (method === "DOM.getNodeForLocation") { + lookups.push({ sessionId, x: params["x"], y: params["y"] }); + // Chromium hit-tests in document coordinates. + const x = (params["x"] as number) - document.scroll.pageX; + const y = (params["y"] as number) - document.scroll.pageY; + const index = document.owners.findIndex(({ border }) => inside(border, x, y)); + return { backendNodeId: index + 1, frameId: document.ownFrameId }; + } + const owner = document.owners[(params["backendNodeId"] as number) - 1]; + // A miss lands on the document's root element, which names the document's own frame. + if (method === "DOM.describeNode") { + return { node: { frameId: owner?.frameId ?? document.ownFrameId } }; + } + if (method === "DOM.getBoxModel") { + const [left, top, right, bottom] = owner!.content; + return { model: { content: [left, top, right, top, right, bottom, left, bottom] } }; + } + input.push({ sessionId, x: params["x"], y: params["y"] }); + return {}; + }, + ); + const debuggee = { sendCommand } as unknown as Electron.Debugger; + const send = (params: Record, routed: boolean) => + sendPageCommand( + {} as Electron.WebContents, + debuggee, + "Input.dispatchMouseEvent", + params, + undefined, + routed ? routeMouseToFrame(debuggee, frameSessions, () => () => {}) : undefined, + ); + const click = async (x: number, y: number, routed = true) => { + for (const type of ["mouseMoved", "mousePressed", "mouseReleased"]) { + await send({ type, x, y }, routed); + } + }; + return { click, send, input, lookups }; + }; + + it("sends it to the frame under the point, at the frame's own coordinates", async () => { + const guest = makeFramedGuest(); + await guest.click(75.4, 116.5); + expect(guest.input).toEqual( + Array.from({ length: 3 }, () => ({ sessionId: "session-cross", x: 65.4, y: 17.5 })), + ); + // The lookup takes whole document pixels, so it adds each frame's scroll. + expect(guest.lookups.slice(0, 2)).toEqual([ + { sessionId: undefined, x: 75, y: 1117 }, + { sessionId: "session-cross", x: 65, y: 318 }, + ]); + }); + + it("follows a cross-site frame inside another", async () => { + const guest = makeFramedGuest(); + await guest.click(160, 250); + expect(guest.input[0]).toEqual({ sessionId: "session-nested", x: 50, y: 51 }); + }); + + it("keeps input over the page, a same-site frame or a frame's border on the page", async () => { + const guest = makeFramedGuest(); + await guest.click(650, 50); + await guest.click(750, 50); + await guest.click(5, 95); + expect(guest.input.map(({ sessionId }) => sessionId)).toEqual(Array(9).fill(undefined)); + }); + + it("gives the page an event whose frame never answers its lookup", async () => { + vi.useFakeTimers(); + try { + const guest = makeFramedGuest(undefined, "session-cross"); + const stalled = guest.click(75, 116); + await vi.advanceTimersByTimeAsync(3_000); + await stalled; + await guest.click(650, 50); + expect(guest.input.map(({ sessionId }) => sessionId)).toEqual(Array(6).fill(undefined)); + } finally { + vi.useRealTimers(); + } + }); + + it("leaves wheels, pages without cross-site frames, and shown guests to Chromium", async () => { + const guest = makeFramedGuest(); + await guest.send({ type: "mouseWheel", x: 75, y: 116, deltaY: 100 }, true); + await guest.click(75, 116, false); + const bare = makeFramedGuest(new Map()); + await bare.click(75, 116); + expect([...guest.lookups, ...bare.lookups]).toEqual([]); + expect([...guest.input, ...bare.input].map(({ sessionId }) => sessionId)).toEqual( + Array(7).fill(undefined), + ); + }); + }); + 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( @@ -271,6 +414,31 @@ describe("preview guest input", () => { ); expect(guest.webContents.insertText).not.toHaveBeenCalled(); }); + + it("asks before typing into an unfocused guest, once its focus lookup has answered", async () => { + const guest = makeGuest({ focused: false }); + let held = false; + const type = () => + sendPageCommand( + guest.webContents as unknown as Electron.WebContents, + { sendCommand: guest.sendCommand } as unknown as Electron.Debugger, + "Input.insertText", + { text: "note" }, + undefined, + undefined, + () => { + if (held) throw new Error("Held"); + }, + ); + const typing = type(); + // The lookup is on its way; the hold starts before it answers. + held = true; + await expect(typing).rejects.toThrow("Held"); + expect(guest.webContents.insertText).not.toHaveBeenCalled(); + held = false; + await type(); + expect(guest.webContents.insertText).toHaveBeenCalledWith("note"); + }); }); describe("CDP key events as Electron input", () => { diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 4d794beea62bc..6ab33e3896e4e 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -1,5 +1,8 @@ // CDP input follows shared window focus; send directly to unfocused guests to avoid typing into the app. +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + const FOCUS_ROUTED_INPUT = new Set([ "Input.insertText", "Input.dispatchKeyEvent", @@ -98,15 +101,10 @@ const HOST_FOCUS = "globalThis.__t3PreviewFocus"; /** A CDP pointer press focuses the guest's native view even with focus emulation enabled. */ const sendPointerPress = async ( webContents: Electron.WebContents, - debuggee: Electron.Debugger, - method: string, - params: Record, - sessionId: string | undefined, + dispatch: () => Promise, ) => { const host = webContents.hostWebContents; - if (!host || host.isDestroyed() || webContents.focusedFrame) { - return debuggee.sendCommand(method, params, sessionId); - } + if (!host || host.isDestroyed() || webContents.focusedFrame) return dispatch(); // Focus in a webview with a press in flight came from that press, so keep the earlier save. await host.executeJavaScript(`(() => { const state = (${HOST_FOCUS} ??= { saved: null, presses: [] }); @@ -121,7 +119,7 @@ const sendPointerPress = async ( state.presses.push(${webContents.id}); })()`); try { - return await debuggee.sendCommand(method, params, sessionId); + return await dispatch(); } finally { if (!host.isDestroyed()) { // Membership check: a host reload starts a new state without this press. @@ -141,6 +139,116 @@ const sendPointerPress = async ( } }; +/** Calls `listener` once the frame session detaches, at once if it already has; returns a stop. */ +export type FrameDetachWatch = (sessionId: string, listener: () => void) => () => void; + +interface FrameRoute { + readonly params: Record; + readonly sessionId: string; + readonly onDetach: FrameDetachWatch; +} + +/** Moves a page point into the cross-site frame under it, if one has a session; null when none does. */ +export type PointerRoute = (params: Record) => Promise; + +const FRAME_GONE_MESSAGE = + "The frame under the pointer went away before it took this input. Check the page before retrying."; + +const MAX_FRAME_DEPTH = 8; +const ROUTE_DEADLINE = "1 second"; + +/** + * Chromium picks a pointer event's frame by hit-testing what the window composites, so on a + * guest the window does not show, input over a cross-site frame lands on the page instead. + * That frame's own session takes the event at frame-local coordinates. + */ +export const routeMouseToFrame = + ( + debuggee: Electron.Debugger, + frameSessions: ReadonlyMap, + onDetach: FrameDetachWatch, + ): PointerRoute => + async (params) => { + // A wheel over a frame that cannot scroll would no longer reach the page behind it. + if (params["type"] === "mouseWheel" || frameSessions.size === 0) return null; + // Chromium never answers a lookup on a frame that detaches mid-navigation; the page takes it. + const routed = await Effect.runPromise( + Effect.promise(() => locateFrame(debuggee, frameSessions, params)).pipe( + Effect.timeoutOption(ROUTE_DEADLINE), + Effect.map(Option.getOrNull), + ), + ); + if (!routed || ![...frameSessions.values()].includes(routed.sessionId)) return null; + return { ...routed, onDetach }; + }; + +/** Chromium can drop the reply to input on a frame that detaches before acknowledging it. */ +const sendToFrame = (debuggee: Electron.Debugger, method: string, route: FrameRoute) => + new Promise((resolve, reject) => { + let gone = false; + const stop = route.onDetach(route.sessionId, () => { + gone = true; + reject(new Error(FRAME_GONE_MESSAGE)); + }); + if (gone) return; + debuggee.sendCommand(method, route.params, route.sessionId).then(resolve, reject).finally(stop); + }); + +const locateFrame = async ( + debuggee: Electron.Debugger, + frameSessions: ReadonlyMap, + params: Record, +) => { + let { x, y } = params; + if (typeof x !== "number" || typeof y !== "number") return null; + let sessionId: string | undefined; + for (let depth = 0; depth < MAX_FRAME_DEPTH; depth++) { + try { + const { cssLayoutViewport: scroll } = (await debuggee.sendCommand( + "Page.getLayoutMetrics", + {}, + sessionId, + )) as { readonly cssLayoutViewport: { readonly pageX: number; readonly pageY: number } }; + // The lookup takes whole document pixels; the event and box model use the viewport. + const { backendNodeId } = (await debuggee.sendCommand( + "DOM.getNodeForLocation", + { + x: Math.round(x + scroll.pageX), + y: Math.round(y + scroll.pageY), + includeUserAgentShadowDOM: true, + }, + sessionId, + )) as { readonly backendNodeId: number }; + const { node } = (await debuggee.sendCommand( + "DOM.describeNode", + { backendNodeId }, + sessionId, + )) as { readonly node: { readonly frameId?: string } }; + // A cross-site frame's target id is its frame id; a same-site frame has no session, + // and a document's own root element names the frame it is already in. + const frameSession = node.frameId === undefined ? undefined : frameSessions.get(node.frameId); + if (frameSession === undefined || frameSession === sessionId) break; + const { model } = (await debuggee.sendCommand( + "DOM.getBoxModel", + { backendNodeId }, + sessionId, + )) as { readonly model: { readonly content: ReadonlyArray } }; + const xs = model.content.filter((_, index) => index % 2 === 0); + const ys = model.content.filter((_, index) => index % 2 === 1); + const left = Math.min(...xs); + const top = Math.min(...ys); + // The frame owner's border and padding belong to the page. + if (x < left || x >= Math.max(...xs) || y < top || y >= Math.max(...ys)) break; + x -= left; + y -= top; + sessionId = frameSession; + } catch { + break; + } + } + return sessionId === undefined ? null : { params: { ...params, x, y }, sessionId }; +}; + const pointerCommands = new WeakMap>(); /** Focus capture crosses processes; later pointer events must not overtake the press. */ @@ -150,15 +258,24 @@ const sendPointerCommand = async ( method: string, params: Record, sessionId: string | undefined, + route: PointerRoute | undefined, + beforeDispatch: (() => void) | undefined, ) => { const previous = pointerCommands.get(webContents) ?? Promise.resolve(); const current = previous .catch(() => {}) - .then(() => - params["type"] === "mousePressed" || params["type"] === "touchStart" - ? sendPointerPress(webContents, debuggee, method, params, sessionId) - : debuggee.sendCommand(method, params, sessionId), - ); + .then(async () => { + const routed = route && sessionId === undefined ? await route(params) : null; + const dispatch = () => { + beforeDispatch?.(); + return routed + ? sendToFrame(debuggee, method, routed) + : debuggee.sendCommand(method, params, sessionId); + }; + return params["type"] === "mousePressed" || params["type"] === "touchStart" + ? sendPointerPress(webContents, dispatch) + : dispatch(); + }); pointerCommands.set(webContents, current); try { return await current; @@ -167,16 +284,40 @@ const sendPointerCommand = async ( } }; -/** Sends one command to the guest's page, keeping reloads and input inside it. */ +/** + * Sends one command to the guest's page, keeping reloads and input inside it. Input that waits + * before it reaches the guest calls `beforeDispatch` once the wait ends, which throws to drop it. + */ export const sendPageCommand = async ( webContents: Electron.WebContents, debuggee: Electron.Debugger, method: string, params: Record, sessionId?: string, + routeMouse?: PointerRoute, + beforeDispatch?: () => void, ): Promise => { - if (method === "Input.dispatchMouseEvent" || method === "Input.dispatchTouchEvent") { - return sendPointerCommand(webContents, debuggee, method, params, sessionId); + if (method === "Input.dispatchMouseEvent") { + return sendPointerCommand( + webContents, + debuggee, + method, + params, + sessionId, + routeMouse, + beforeDispatch, + ); + } + if (method === "Input.dispatchTouchEvent") { + return sendPointerCommand( + webContents, + debuggee, + method, + params, + sessionId, + undefined, + beforeDispatch, + ); } if (sessionId !== undefined) return debuggee.sendCommand(method, params, sessionId); // Electron's debugger routes Page.reload on a webview to its embedder window. @@ -195,6 +336,7 @@ export const sendPageCommand = async ( if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) { throw new Error(CROSS_SITE_FOCUS_MESSAGE); } + beforeDispatch?.(); switch (method) { case "Input.insertText": await webContents.insertText(typeof params["text"] === "string" ? params["text"] : ""); diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index 5b3cf08c9f728..c4f43ba7086f4 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -1,4 +1,5 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeWS from "@effect/platform-node/NodeWS"; import { EnvironmentId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -12,6 +13,9 @@ import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Result from "effect/Result"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as LoopbackTunnel from "./LoopbackTunnel.ts"; @@ -81,11 +85,16 @@ const unusedPort = Effect.promise( }), ); +type HostLayer = + | Layer.Layer + | Layer.Layer + | Layer.Layer; + /** The tunnel service, with every access request answered with `tunnelUrl`. */ const makeTunnel = ( /** A function answers each access request with its current value. */ tunnelUrl: string | null | (() => string | null), - host?: Layer.Layer | Layer.Layer, + host?: HostLayer, ) => Effect.gen(function* () { const accessRequests = yield* Queue.unbounded(); @@ -103,12 +112,12 @@ const makeTunnel = ( Layer.mock(ElectronWindow.ElectronWindow, { currentMainOrFirst: Effect.succeedSome(window as unknown as Electron.BrowserWindow), }), - NodeFileSystem.layer, + host ?? Layer.empty, SecureRandom.layerWebCrypto, NetService.layer, - host ?? Layer.empty, ), ), + Layer.provide(NodeServices.layer), ), ); const tunnel = Context.get(services, LoopbackTunnel.LoopbackTunnel); @@ -126,10 +135,7 @@ const makeTunnel = ( }); /** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ -const routeThroughTunnel = ( - tunnelUrl: string | null, - host?: Layer.Layer | Layer.Layer, -) => +const routeThroughTunnel = (tunnelUrl: string | null, host?: HostLayer) => Effect.gen(function* () { const tunnel = yield* makeTunnel(tunnelUrl, host); let proxyRules = ""; @@ -247,6 +253,7 @@ it.effect.each([ { case: "another OS user's client", host: "localhost", tunnel: "other-user" }, { case: "a TCP row whose client address differs", host: "localhost", tunnel: "moved-client" }, { case: "a TCP row whose listener address differs", host: "localhost", tunnel: "moved-listener" }, + { case: "no TCP row and no user id to compare", host: "localhost", tunnel: "no-user-id" }, ] as const)("fails the SOCKS request for $case without dialling locally", ({ host, tunnel }) => Effect.gen(function* () { const decoy = yield* listenDecoy; @@ -266,7 +273,13 @@ it.effect.each([ Layer.succeed(HostProcess.Platform, "linux"), tcpTablesWithMovedAddress(tunnel === "moved-client" ? 1 : 2), ) - : undefined, + : tunnel === "no-user-id" + ? Layer.mergeAll( + Layer.succeed(HostProcess.Platform, "linux"), + Layer.succeed(HostProcess.UserId, undefined), + tcpTablesWithMovedAddress(1), + ) + : undefined, ); const { reply } = yield* socksConnect(proxyPort, host, addressPort(decoy.server)); expect(reply[1]).not.toBe(0); @@ -275,6 +288,98 @@ it.effect.each([ }), ); +/** Stands in for the system's own tools: each command prints what `print` returns for it. */ +const systemTools = (print: (command: string, args: ReadonlyArray) => string) => + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.sync(() => { + const { command: name, args } = command as unknown as { + readonly command: string; + readonly args: ReadonlyArray; + }; + 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(new TextEncoder().encode(print(name, args))), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); + }), + ), + ); + +const ownUserId = process.getuid?.() ?? 501; + +it.effect.each([ + { client: "own", served: true }, + { client: "another user's", served: false }, + { client: "unlisted", served: false }, +] as const)( + "serves a SOCKS client on macOS only when the system lists it as this user's: $client", + ({ client, served }) => + Effect.gen(function* () { + const decoy = yield* listenDecoy; + const endpoint = yield* listenEndpoint; + const commands: Array = []; + let proxyPort = 0; + const lsof = (args: ReadonlyArray) => { + const clientEnd = /^-iTCP@(.+)$/.exec(args[1] ?? "")?.[1]; + // The listener's accepted socket is this app's own and is always listed. + const accepted = `p100\nu${ownUserId}\nf30\nn127.0.0.1:${proxyPort}->${clientEnd}\n`; + if (client === "unlisted") return accepted; + const owner = client === "own" ? ownUserId : ownUserId + 1; + return `${accepted}p200\nu${owner}\nf12\nn${clientEnd}->127.0.0.1:${proxyPort}\n`; + }; + proxyPort = yield* routeThroughTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + Layer.mergeAll( + Layer.succeed(HostProcess.Platform, "darwin"), + Layer.succeed(HostProcess.UserId, ownUserId), + systemTools((command, args) => { + commands.push(command); + return command === "/usr/sbin/lsof" ? lsof(args) : ""; + }), + ), + ); + const { reply } = yield* socksConnect(proxyPort, "localhost", addressPort(decoy.server)); + expect(reply[1] === 0).toBe(served); + expect(endpoint.requests.length).toBe(served ? 1 : 0); + expect(decoy.connections()).toBe(0); + expect(commands).toEqual(["/usr/sbin/lsof"]); + }), +); + +it.effect("serves a SOCKS client on Windows without looking up its owner", () => + Effect.gen(function* () { + const decoy = yield* listenDecoy; + const endpoint = yield* listenEndpoint; + const commands: Array = []; + const proxyPort = yield* routeThroughTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + Layer.mergeAll( + Layer.succeed(HostProcess.Platform, "win32"), + Layer.succeed(HostProcess.UserId, undefined), + systemTools((command) => { + commands.push(command); + return ""; + }), + ), + ); + const { reply } = yield* socksConnect(proxyPort, "localhost", addressPort(decoy.server)); + expect(reply[1]).toBe(0); + expect(endpoint.requests.length).toBe(1); + expect(decoy.connections()).toBe(0); + expect(commands).toEqual([]); + }), +); + it.effect("connects straight to the environment's own forwarded origin port", () => Effect.gen(function* () { // Over SSH the origin is a local forward, and signed file previews load from it. @@ -520,6 +625,7 @@ it.effect("closes connections beyond a forward's limit without tunnelling them", () => new Promise((resolve) => { const socket = NodeNet.connect(forward.localPort, "127.0.0.1"); + socket.on("error", () => {}); socket.on("close", () => resolve(true)); socket.on("data", () => resolve(false)); socket.write(Uint8Array.of(2)); diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index f84dc3e5c38a2..0144dc1f30b7f 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -26,6 +26,7 @@ import * as Schema from "effect/Schema"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as Socket from "effect/socket/Socket"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -35,6 +36,7 @@ const ACCESS_TIMEOUT = "15 seconds"; const PROBE_TIMEOUT = "3 seconds"; const MAX_FORWARD_CONNECTIONS = 64; const CONNECT_TIMEOUT = "10 seconds"; +const OWNER_LOOKUP_TIMEOUT = "5 seconds"; const REPLY_SUCCEEDED = 0; const REPLY_FAILURE = 1; @@ -226,6 +228,27 @@ const connectionOwner = ( return undefined; }; +interface ConnectionEnd { + readonly address: string; + readonly port: number; +} + +/** + * The owner of the client's socket in `lsof -F un`, which prints a process as `p` and + * `u`, then each of its sockets as `n->`. Without root it lists this user's + * processes only, so another user's client has no row. + */ +const lsofConnectionOwner = (output: string, client: ConnectionEnd, listener: ConnectionEnd) => { + const socket = `n${client.address}:${client.port}->${listener.address}:${listener.port}`; + let owner: number | undefined; + for (const line of output.split("\n").map((line) => line.trim())) { + if (line.startsWith("p")) owner = undefined; + else if (line.startsWith("u")) owner = Number(line.slice(1)); + else if (line === socket) return owner; + } + return undefined; +}; + const pump = /* Runs for the life of the connection; a span per direction adds no diagnostic value. */ Effect.fnUntraced(function* ( @@ -314,6 +337,7 @@ const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const random = yield* SecureRandom.SecureRandom; const net = yield* NetService.NetService; const listenerScope = yield* Effect.scope; @@ -352,24 +376,55 @@ const make = Effect.gen(function* () { ); }); - // Chromium can't authenticate to a SOCKS proxy, so on Linux the listener checks that the - // client belongs to this OS user. Other users could otherwise ride this user's tunnel. + /** What the command printed, or nothing when it could not run or took too long. */ + const commandOutput = (command: string, args: ReadonlyArray) => + spawner.string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" })).pipe( + Effect.timeoutOption(OWNER_LOOKUP_TIMEOUT), + Effect.map(Option.getOrElse(() => "")), + Effect.orElseSucceed(() => ""), + ); + + const isOwnLinuxConnection = Effect.fn("LoopbackTunnel.isOwnLinuxConnection")(function* ( + client: ConnectionEnd, + listener: ConnectionEnd, + ) { + const tables = yield* Effect.forEach(TCP_TABLES, (path) => + fileSystem.readFileString(path).pipe(Effect.orElseSucceed(() => "")), + ); + const owner = connectionOwner(tables, client, listener); + return owner !== undefined && owner === userId; + }); + + const isOwnMacConnection = Effect.fn("LoopbackTunnel.isOwnMacConnection")(function* ( + client: ConnectionEnd, + listener: ConnectionEnd, + ) { + const sockets = yield* commandOutput("/usr/sbin/lsof", [ + "-nP", + `-iTCP@${client.address}:${client.port}`, + "-F", + "un", + ]); + const owner = lsofConnectionOwner(sockets, client, listener); + return owner !== undefined && owner === userId; + }); + + // Neither Chromium's SOCKS client nor a plain forwarded port can authenticate, so on Linux and + // macOS a listener serves only clients of this OS user, and a connection whose owner cannot be + // read is refused. Windows and other platforms have no owner check. const isOwnConnection = Effect.fn("LoopbackTunnel.isOwnConnection")(function* () { - if (platform !== "linux") return true; + if (platform !== "linux" && platform !== "darwin") return true; const connection = yield* Effect.serviceOption(NodeSocket.NetSocket); if (Option.isNone(connection)) return false; const { remoteAddress, remotePort, localAddress, localPort } = connection.value; if (!remoteAddress || !remotePort || !localAddress || !localPort) return false; - const tables = yield* Effect.forEach(TCP_TABLES, (path) => - fileSystem.readFileString(path).pipe(Effect.orElseSucceed(() => "")), - ); - return ( - connectionOwner( - tables, - { address: remoteAddress, port: remotePort }, - { address: localAddress, port: localPort }, - ) === userId - ); + // A dual-stack socket reports an IPv4 peer as ::ffff:a.b.c.d; the lookups print it plain. + const plain = (address: string) => address.replace(/^::ffff:/i, ""); + const client = { address: plain(remoteAddress), port: remotePort }; + const listener = { address: plain(localAddress), port: localPort }; + return platform === "linux" + ? yield* isOwnLinuxConnection(client, listener) + : yield* isOwnMacConnection(client, listener); }); /** Serves one SOCKS connection; never falls back to a direct local connection. */ diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 9c15a0e0a4a95..ff5a9fd58d0b5 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -1271,6 +1271,72 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("preserves postBody on in-place window-open navigations", () => + withManager((manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + const setWindowOpenHandler = vi.fn(); + Object.assign(preview.webContents, { setWindowOpenHandler }); + fromId.mockReturnValue(preview.webContents); + + yield* manager.createTab("tab_window_open_post"); + yield* manager.registerWebview("tab_window_open_post", 42); + + const openWindow = setWindowOpenHandler.mock.calls[0]![0]; + const detailsBase = { + frameName: "", + features: "", + referrer: { url: "", policy: "default" as const }, + }; + const multipartData: Electron.PostBody["data"] = [ + { type: "rawData", bytes: Buffer.from("a=1") }, + ]; + + expect( + openWindow({ + ...detailsBase, + url: "http://localhost:5173/submit", + disposition: "foreground-tab", + postBody: { + contentType: "multipart/form-data", + boundary: "----x", + data: multipartData, + }, + }), + ).toEqual({ action: "deny" }); + expect( + openWindow({ + ...detailsBase, + url: "https://example.com/submit", + disposition: "background-tab", + postBody: { + contentType: "application/x-www-form-urlencoded", + data: [], + }, + }), + ).toEqual({ action: "deny" }); + yield* Effect.yieldNow; + + expect(preview.loadURL.mock.calls).toEqual([ + [ + "http://localhost:5173/submit", + { + postData: multipartData, + extraHeaders: "content-type: multipart/form-data; boundary=----x", + }, + ], + [ + "https://example.com/submit", + { + postData: [], + extraHeaders: "content-type: application/x-www-form-urlencoded", + }, + ], + ]); + }), + ), + ); + effectIt.effect("treats a load superseded by a page redirect as a successful navigation", () => withManager((manager) => Effect.gen(function* () { @@ -2433,6 +2499,67 @@ describe("PreviewManager", () => { }).pipe(Effect.provide(managerLayer())), ); + effectIt.effect("holds relayed input off a server tab while its annotation is open", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.DesktopBrowserHost; + const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; + const lines = yield* Queue.unbounded(); + yield* host.events.pipe( + Stream.runForEach((line) => Queue.offer(lines, new TextDecoder().decode(line))), + Effect.forkScoped, + ); + const contents = Object.assign( + makeTestPreviewWebContents(async () => { + throw new Error("unused"); + }, 42), + { + isDevToolsOpened: () => false, + getUserAgent: () => "Electron", + isFocused: () => true, + focusedFrame: {}, + once: vi.fn(), + ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, + }, + ); + fromId.mockReturnValue(contents); + const manager = yield* PreviewManager.PreviewManager; + yield* manager.createTab("tab_1", { serverTab }); + yield* manager.registerWebview("tab_1", 42); + expect(yield* Queue.take(lines)).toContain('"type":"attached"'); + const typeText = (id: number) => + host.handleCommandLine( + JSON.stringify({ + type: "cdp", + ...serverTab, + message: JSON.stringify({ + id, + method: "Input.insertText", + params: { text: "x" }, + sessionId: "t3-preview-page", + }), + }), + ); + const typed = () => + vi + .mocked(contents.debugger.sendCommand) + .mock.calls.filter(([method]) => method === "Input.insertText").length; + + const pick = yield* manager.pickElement("tab_1").pipe(Effect.forkChild); + yield* Effect.yieldNow; + yield* typeText(1); + const refused = yield* Queue.take(lines); + expect(refused).toContain('\\"id\\":1'); + expect(refused).toContain("being annotated"); + expect(typed()).toBe(0); + + yield* manager.cancelPickElement("tab_1"); + expect(yield* Fiber.join(pick)).toBeNull(); + yield* typeText(2); + expect(yield* Queue.take(lines)).toContain('\\"id\\":2'); + expect(typed()).toBe(1); + }).pipe(Effect.provide(managerLayer())), + ); + effectIt.effect( "asks the client to paint a navigated server tab while the agent captures it", () => diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index e634d5a6fa3cb..ac3e4bf1ef874 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -480,7 +480,7 @@ const IN_PLACE_DENIED_PROTOCOLS = new Set([ "view-source:", ]); -/** Popups bypass will-attach-webview hardening and would inherit the picker's contextIsolation:false. */ +/** Popups bypass will-attach-webview hardening, so they are isolated and sandboxed here. */ const POPUP_WINDOW_OPTIONS = { webPreferences: { contextIsolation: true, @@ -1703,9 +1703,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); return { action: "deny" }; } + const { postBody } = details; runFork( attemptPromise({ operation: "openPreviewWindow", tabId, webContentsId: wc.id }, () => - wc.loadURL(details.url), + postBody + ? wc.loadURL(details.url, { + postData: postBody.data, + extraHeaders: postBody.boundary + ? `content-type: ${postBody.contentType}; boundary=${postBody.boundary}` + : `content-type: ${postBody.contentType}`, + }) + : wc.loadURL(details.url), ).pipe(Effect.ignore), ); return { action: "deny" }; @@ -2586,6 +2594,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function webContents: wc, debugger: control.debugger, cookiesCleared: () => runPromise(browserSession.cookiesCleared(wc.session)), + annotating: () => Ref.getUnsafe(pickSessionsRef).has(tabId), }); // CDP cannot recover a failure that happened before it attached. const { navStatus } = afterAttach; diff --git a/apps/desktop/src/preview/PageWorld.ts b/apps/desktop/src/preview/PageWorld.ts new file mode 100644 index 0000000000000..5877237054a07 --- /dev/null +++ b/apps/desktop/src/preview/PageWorld.ts @@ -0,0 +1,36 @@ +import { getElementContext } from "react-grab/primitives"; + +import { installPasskeyBridge } from "./PasskeyBridge.ts"; + +export interface PageWorldHost { + /** Absent when this guest has no passkey bridge. */ + readonly invokePasskey?: Parameters[0]; +} + +/** + * Runs in the page's own JavaScript world: React's fibers and `navigator.credentials` cannot be + * reached from the isolated preload. The preload serializes this function into the page, so the + * bundler inlines its imports (see `pageWorldFunction` in vite.config.ts), and everything it + * returns is page-controlled data. + */ +export function installPageWorld(host: PageWorldHost) { + if (host.invokePasskey) installPasskeyBridge(host.invokePasskey); + return { + elementContext: async (element: Element) => { + const context = await getElementContext(element); + return { + selector: context.selector, + htmlPreview: context.htmlPreview, + componentName: context.componentName, + styles: context.styles, + // Fibers and elements cannot cross back to the preload, so only plain fields are passed. + stack: context.stack?.map((frame) => ({ + functionName: frame.functionName, + fileName: frame.fileName, + lineNumber: frame.lineNumber, + columnNumber: frame.columnNumber, + })), + }; + }, + }; +} diff --git a/apps/desktop/src/preview/PageWorldBridge.ts b/apps/desktop/src/preview/PageWorldBridge.ts new file mode 100644 index 0000000000000..24a6971f6a202 --- /dev/null +++ b/apps/desktop/src/preview/PageWorldBridge.ts @@ -0,0 +1,25 @@ +import { contextBridge, ipcRenderer } from "electron"; + +import { + PASSKEY_BRIDGE_ARGUMENT, + PASSKEY_CREATE_CHANNEL, + PASSKEY_GET_CHANNEL, +} from "./GuestProtocol.ts"; +import { installPageWorld, type PageWorldHost } from "./PageWorld.ts"; + +// Electron hands webPreferences.additionalArguments to sandboxed preloads in process.argv. +const host: PageWorldHost = process.argv.includes(PASSKEY_BRIDGE_ARGUMENT) + ? { + // Only the two passkey channels are reachable from the page's world. + invokePasskey: (channel, publicKey) => + channel === PASSKEY_CREATE_CHANNEL || channel === PASSKEY_GET_CHANNEL + ? ipcRenderer.invoke(channel, publicKey) + : Promise.reject(new Error("Unsupported passkey channel.")), + } + : {}; + +/** Installed before any page script runs; calls cross into the page's world and back. */ +export const pageWorld: ReturnType = contextBridge.executeInMainWorld({ + func: installPageWorld, + args: [host], +}); diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index 4e2fc39a8a645..8c83a8c83ccd0 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -5,6 +5,7 @@ import "./PickPreload.ts"; const ipcListeners = vi.hoisted(() => new Map void>>()); const ipcSend = vi.hoisted(() => ({ calls: [] as unknown[][] })); +const pageElementContext = vi.hoisted(() => vi.fn(async (): Promise => null)); vi.mock("electron", () => ({ ipcRenderer: { @@ -19,7 +20,7 @@ vi.mock("electron", () => ({ }, })); -vi.mock("react-grab/primitives", () => ({ getElementContext: async () => null })); +vi.mock("./PageWorldBridge.ts", () => ({ pageWorld: { elementContext: pageElementContext } })); const startAnnotation = (): ShadowRoot => { vi.stubGlobal( @@ -159,3 +160,48 @@ it.each([ expect((annotation as { elements: Array<{ rect: unknown }> }).elements[0]?.rect).toEqual(rect); }, ); + +it("keeps only the well-typed fields of what the page reports about an element", async () => { + ipcSend.calls.length = 0; + pageElementContext.mockResolvedValueOnce({ + selector: { toString: () => "#object" }, + htmlPreview: "", + componentName: 7, + styles: null, + stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3], + }); + const card = document.body.appendChild(document.createElement("div")); + document.elementsFromPoint = () => [card]; + using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); + const shadowRoot = startAnnotation(); + card.dispatchEvent( + new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), + ); + const attach = Array.from(shadowRoot.querySelectorAll("button")).find( + (button) => button.textContent === "Attach", + ); + const listenerIndex = listeners.mock.contexts.findIndex( + (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", + ); + const listener = listeners.mock.calls[listenerIndex]?.[1]; + if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); + // The DOM test environment has no native input source. + listener.call(attach, { isTrusted: true } as MouseEvent); + + await vi.waitFor(() => + expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), + ); + const [, annotation] = + ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 }; + expect( + (annotation as { elements: Array<{ element: unknown }> }).elements[0]?.element, + ).toMatchObject({ + selector: null, + htmlPreview: "", + componentName: null, + styles: "", + source: frame, + stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }], + }); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 5113617a8f324..9c7c2901b1085 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -1,6 +1,5 @@ // @effect-diagnostics globalDate:off globalTimers:off - This isolated Electron preload does not run inside an Effect runtime. import { ipcRenderer } from "electron"; -import { getElementContext } from "react-grab/primitives"; import { matchesKeybindingShortcut } from "@t3tools/shared/keybindingMatching"; import type { DesktopPreviewAnnotationTheme, @@ -28,6 +27,7 @@ import { type StrokeGeometry, } from "./AnnotationStroke.ts"; import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts"; +import { pageWorld } from "./PageWorldBridge.ts"; import { pickElementAtPoint } from "./PickTarget.ts"; import { installRecordingCursor } from "./RecordingCursor.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS } from "./RecordingInput.ts"; @@ -435,19 +435,24 @@ function updateSelectedVisual(target: SelectedElement): void { target.label.style.transform = `translate(${Math.max(4, rect.x)}px, ${Math.max(4, rect.y - 22)}px)`; } -function toStackFrame(frame: { - functionName?: string; - fileName?: string; - lineNumber?: number; - columnNumber?: number; -}): PickedElementStackFrame { - return { - functionName: frame.functionName ?? null, - fileName: frame.fileName ?? null, - lineNumber: frame.lineNumber ?? null, - columnNumber: frame.columnNumber ?? null, - }; -} +// Everything the page's world returns is page-controlled, so each field is checked, not trusted. +const pageField = (source: unknown, key: string): unknown => + typeof source === "object" && source !== null ? Reflect.get(source, key) : undefined; +const pageString = (source: unknown, key: string): string | null => { + const value = pageField(source, key); + return typeof value === "string" ? value : null; +}; +const pageNumber = (source: unknown, key: string): number | null => { + const value = pageField(source, key); + return typeof value === "number" && Number.isFinite(value) ? value : null; +}; + +const toStackFrame = (frame: unknown): PickedElementStackFrame => ({ + functionName: pageString(frame, "functionName"), + fileName: pageString(frame, "fileName"), + lineNumber: pageNumber(frame, "lineNumber"), + columnNumber: pageNumber(frame, "columnNumber"), +}); /** React-internals lookups can remain pending forever; bound them so submit cannot stall the overlay. */ function withCaptureTimeout(promise: Promise, millis: number): Promise { @@ -471,20 +476,21 @@ async function captureElement(element: Element): Promise { pickedAt: new Date().toISOString(), }; try { - const context = await withCaptureTimeout( - Promise.resolve(getElementContext(element)), + const context: unknown = await withCaptureTimeout( + Promise.resolve(pageWorld.elementContext(element)), ELEMENT_CONTEXT_TIMEOUT_MS, ); - if (context) { - const stack = (context.stack ?? []).map(toStackFrame); + if (typeof context === "object" && context !== null) { + const frames = pageField(context, "stack"); + const stack = Array.isArray(frames) ? frames.map(toStackFrame) : []; return { ...base, - selector: context.selector, - htmlPreview: context.htmlPreview ?? "", - componentName: context.componentName, + selector: pageString(context, "selector"), + htmlPreview: pageString(context, "htmlPreview") ?? "", + componentName: pageString(context, "componentName"), source: stack[0] ?? null, stack, - styles: context.styles ?? "", + styles: pageString(context, "styles") ?? "", }; } } catch {} diff --git a/apps/desktop/src/preview/WebviewPreferences.test.ts b/apps/desktop/src/preview/WebviewPreferences.test.ts index 572a290e2b669..ed3df8bb1f9c7 100644 --- a/apps/desktop/src/preview/WebviewPreferences.test.ts +++ b/apps/desktop/src/preview/WebviewPreferences.test.ts @@ -25,6 +25,10 @@ describe("PREVIEW_WEBVIEW_PREFERENCES", () => { } }); + it("keeps the page out of the picker preload's JavaScript world", () => { + expect(parsed["contextIsolation"]).toBe("true"); + }); + it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => { expect(parsed["sandbox"]).toBe("true"); }); diff --git a/apps/desktop/src/preview/WebviewPreferences.ts b/apps/desktop/src/preview/WebviewPreferences.ts index 4dc9d9aa6b732..cb1ddb11bd1ea 100644 --- a/apps/desktop/src/preview/WebviewPreferences.ts +++ b/apps/desktop/src/preview/WebviewPreferences.ts @@ -1,3 +1,3 @@ -/** sandbox:true is required with contextIsolation:false or the shared page global would expose Node and IPC. */ +/** The picker preload runs in its own JavaScript world; PageWorld.ts holds what must run in the page's. */ export const PREVIEW_WEBVIEW_PREFERENCES = - "contextIsolation=false,sandbox=true,nodeIntegration=false"; + "contextIsolation=true,sandbox=true,nodeIntegration=false"; diff --git a/apps/desktop/src/snapShot/SnapShotAccessibility.ts b/apps/desktop/src/snapShot/SnapShotAccessibility.ts index 3a6d3367c583f..e19a20951a562 100644 --- a/apps/desktop/src/snapShot/SnapShotAccessibility.ts +++ b/apps/desktop/src/snapShot/SnapShotAccessibility.ts @@ -12,6 +12,7 @@ import { compactAccessibilityTree, findAccessibleWindow, isWaylandSession, + MAX_ACCESSIBILITY_TREE_DEPTH, } from "./snapShot.ts"; const ACCESSIBILITY_TIMEOUT_MS = 3_000; @@ -163,7 +164,7 @@ async function readCapturedWindowAccessibility( Math.abs(accessibleBounds.x - matchingBounds.x) <= 2 && Math.abs(accessibleBounds.y - matchingBounds.y) <= 2)); const flatRead = window - .tree() + .tree(MAX_ACCESSIBILITY_TREE_DEPTH) .then((tree) => { progress.accessibleText = accessibleWindowText(tree, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS) || undefined; diff --git a/apps/desktop/src/snapShot/snapShot.test.ts b/apps/desktop/src/snapShot/snapShot.test.ts index fe166f5d099a0..cac5a0515eb67 100644 --- a/apps/desktop/src/snapShot/snapShot.test.ts +++ b/apps/desktop/src/snapShot/snapShot.test.ts @@ -224,6 +224,23 @@ describe("accessibleWindowElementTree", () => { expect(tree?.root.children.length).toBeLessThan(10); expect(JSON.stringify(tree).length).toBeLessThanOrEqual(32_000); }); + + it("stops descending a cyclic tree", async () => { + const group = { + role: "group", + name: "Loop", + bounds: null, + children: async () => [group], + }; + const tree = await accessibleWindowElementTree( + { role: "window", name: "Inbox", bounds: null, children: async () => [group] }, + { x: 0, y: 0, width: 800, height: 600 }, + { width: 800, height: 600 }, + ); + + expect(tree?.truncated).toBe(true); + expect(tree?.root.name).toBe("Inbox"); + }); }); describe("compactAccessibilityTree", () => { diff --git a/apps/desktop/src/snapShot/snapShot.ts b/apps/desktop/src/snapShot/snapShot.ts index 8be137cb32a46..80927ed5ba20b 100644 --- a/apps/desktop/src/snapShot/snapShot.ts +++ b/apps/desktop/src/snapShot/snapShot.ts @@ -23,6 +23,9 @@ interface AccessibilityTreeNode { } const MAX_ACCESSIBILITY_TREE_NODES = 10_000; +// Some apps (seen in Microsoft Outlook) expose cyclic accessibility trees. xa11y's native tree() +// recursion cannot be interrupted, and both walks recurse, so the depth must be capped. +export const MAX_ACCESSIBILITY_TREE_DEPTH = 512; export const WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS: Record< SnapShotModifier, @@ -370,6 +373,7 @@ export async function accessibleWindowElementTree( const visit = async ( current: AccessibilityElement, required: boolean, + depth: number, ): Promise => { if (!shouldContinue()) { truncated = true; @@ -417,8 +421,12 @@ export async function accessibleWindowElementTree( truncated = true; return node; } + if (depth >= MAX_ACCESSIBILITY_TREE_DEPTH && children.length > 0) { + truncated = true; + return node; + } for (const child of children) { - const childNode = await visit(child, false); + const childNode = await visit(child, false, depth + 1); if (!childNode) break; node.children.push(childNode); options.onProgress?.(root, true, descendantLocationsReliable()); @@ -426,7 +434,7 @@ export async function accessibleWindowElementTree( return node; }; - const completedRoot = await visit(element, true); + const completedRoot = await visit(element, true, 0); if (!completedRoot) return undefined; const locationsReliable = descendantLocationsReliable(); const compacted = compactAccessibilityTree(completedRoot, { diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 3d882399a6173..28a2cde19d0cc 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -76,6 +76,7 @@ function makeFakeBrowserWindow() { const webContents = { id: 1, session: { + setPermissionRequestHandler: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn(), }, @@ -1536,7 +1537,7 @@ describe("DesktopWindow", () => { }, { primaryPasteEnabled: true, expected: [PASSKEY_BRIDGE_ARGUMENT] }, ])( - "passes the primary-paste setting to preview guests (enabled: $primaryPasteEnabled)", + "isolates preview guests and passes them the primary-paste setting (enabled: $primaryPasteEnabled)", ({ primaryPasteEnabled, expected }) => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1562,6 +1563,7 @@ describe("DesktopWindow", () => { }); assert.deepEqual(webPreferences.additionalArguments, expected); + assert.isTrue(webPreferences.contextIsolation); }).pipe(Effect.provide(layer)); }), ); @@ -1615,6 +1617,63 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens only web links from popups and declines external-protocol navigations", () => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const openedExternalUrls: unknown[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount: yield* Ref.make(0), + mainWindow: yield* Ref.make>(Option.none()), + openedExternalUrls, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const openHandler = vi.mocked(fakeWindow.window.webContents.setWindowOpenHandler).mock + .lastCall?.[0]; + if (!openHandler) { + return yield* Effect.die("window open handler was not registered"); + } + for (const url of [ + "vscode://file/home/user/project/readme.md", + "vscode://vscode-remote/ssh-remote+remote.example/home/user/project", + "zed://ssh/remote.example/home/user/project", + "jetbrains://gateway/ssh/environment?h=remote.example", + "grokbot://app/v1/prompt?text=hi", + "https://example.com/docs", + ]) { + assert.deepEqual( + openHandler({ url } as Electron.HandlerDetails), + { action: "deny" }, + url, + ); + } + yield* Effect.promise(() => Promise.resolve()); + + assert.deepEqual(openedExternalUrls, ["https://example.com/docs"]); + + const answerPermission = vi.mocked( + fakeWindow.window.webContents.session.setPermissionRequestHandler, + ).mock.lastCall?.[0]; + if (!answerPermission) { + return yield* Effect.die("permission request handler was not registered"); + } + const answers = (["openExternal", "media"] as const).map((permission) => { + const callback = vi.fn(); + answerPermission(fakeWindow.window.webContents, permission, callback, { + isMainFrame: false, + requestingUrl: "http://127.0.0.1:3773/api/assets/token/page.html", + }); + return callback.mock.lastCall?.[0]; + }); + assert.deepEqual(answers, [false, true]); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("offers to copy the bare address when right-clicking a mailto link", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 5117ea30407dd..20e56ed2be9d8 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -634,7 +634,7 @@ export const make = Effect.gen(function* () { webPreferences.sandbox = true; webPreferences.nodeIntegration = false; webPreferences.nodeIntegrationInSubFrames = false; - webPreferences.contextIsolation = false; + webPreferences.contextIsolation = true; webPreferences.disableHtmlFullscreenWindowResize = true; applyGuestWebAuthnPolicy(previewPasskeys, webPreferences); if (previewPasskeys.bridgeEnabled) { @@ -775,12 +775,19 @@ export const make = Effect.gen(function* () { void runPromise(previewManager.prepareWebview(contents)); }); + // Popups from every frame in this window arrive here without a caller, so only web links + // pass. The app opens editors and other applications over IPC. window.webContents.setWindowOpenHandler(({ url }) => { - if (Option.isSome(ElectronShell.parseSafeExternalUrl(url))) { + if (Option.isSome(ElectronShell.parseWebExternalUrl(url))) { void runPromise(electronShell.openExternal(url)); } return { action: "deny" }; }); + // Chromium asks this before handing a navigation to an OS protocol handler, and grants it + // when nothing answers. External links are opened through ElectronShell only. + window.webContents.session.setPermissionRequestHandler((_contents, permission, callback) => + callback(permission !== "openExternal"), + ); window.webContents.on("will-navigate", (event, url) => { if ( isSameOriginRendererNavigation({ diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 42063f99b63a0..4866dd32d08f9 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -2,6 +2,7 @@ import "vite-plus/test/config"; import * as NodeOS from "node:os"; import { defaultInclude, defineConfig } from "vite-plus"; +import { Rolldown } from "vite-plus/pack"; import { isDesktopRuntimeExternalDependency } from "../../scripts/lib/desktop-external-packages.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; @@ -26,6 +27,28 @@ const publicConfigDefine = { ), }; +const PAGE_WORLD_MODULE = /[\\/]src[\\/]preview[\\/]PageWorld\.ts$/; + +/** + * The preview preload passes `installPageWorld` to `contextBridge.executeInMainWorld`, which runs + * the function's source text in the page. Inline the module's imports into the function body so + * that text is complete on its own. + */ +const pageWorldFunction = (): Rolldown.Plugin => ({ + name: "t3code:preview-page-world", + async load(id) { + if (!PAGE_WORLD_MODULE.test(id)) return null; + const bundle = await Rolldown.rolldown({ input: id, platform: "browser" }); + try { + const { output } = await bundle.generate({ format: "iife", name: "pageWorld" }); + for (const file of await bundle.watchFiles) this.addWatchFile(file); + return `export function installPageWorld(host) {\n${output[0].code}\nreturn pageWorld.installPageWorld(host);\n}\n`; + } finally { + await bundle.close(); + } + }, +}); + export default defineConfig({ run: { tasks: { @@ -136,11 +159,9 @@ export default defineConfig({ sourcemap: true, outExtensions: () => ({ js: ".cjs" }), entry: ["src/preview-pick-preload.ts"], + plugins: [pageWorldFunction()], deps: { - alwaysBundle: (id) => - id === "react-grab" || - id.startsWith("react-grab/") || - id === "@t3tools/shared/keybindingMatching", + alwaysBundle: (id) => id === "@t3tools/shared/keybindingMatching", }, }, { diff --git a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx new file mode 100644 index 0000000000000..e44b2dffa3a91 --- /dev/null +++ b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx @@ -0,0 +1,58 @@ +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const { Children, loaded } = vi.hoisted(() => ({ + Children: ({ children }: { children?: ReactNode }) => <>{children}, + loaded: [] as string[], +})); + +vi.mock("react-native", () => ({ View: Children })); +vi.mock("react-native-safe-area-context", () => ({ SafeAreaView: Children })); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ goBack: vi.fn() }) })); +vi.mock("../../components/ui/AppText", () => ({ AppText: Children })); +vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); +vi.mock("../../components/ui/EmptyState", () => ({ EmptyState: () => null })); +vi.mock("../../state/entities", () => ({ useEnvironmentPreviewTunnelOff: () => false })); +vi.mock("../../state/environments", () => ({ + useEnvironments: () => ({ presentationById: new Map() }), +})); +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({ themeVariables: {} }), +})); +vi.mock("./BrowserBar", () => ({ + BrowserChrome: (props: { + children: (page: { topInset: number; onScrollDirection: () => void }) => ReactNode; + }) => <>{props.children({ topInset: 0, onScrollDirection: () => {} })}, +})); +vi.mock("./TunnelWebView", () => ({ + TunnelWebView: ({ url }: { url: string }) => { + loaded.push(url); + return null; + }, +})); + +import { LocalPreviewRouteScreen } from "./LocalPreviewRouteScreen"; + +it("gives the webview only web addresses from the route, on open and on a later link", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const show = (url: string) => { + loaded.length = 0; + act(() => + root.render(), + ); + return loaded.at(-1); + }; + + try { + expect(show("http://0.0.0.0:5173/app")).toBe("http://localhost:5173/app"); + expect(show("javascript:document.title='x'")).toBe(""); + expect(show("https://example.com/docs")).toBe("https://example.com/docs"); + expect(show("file:///data/local/tmp/a.html")).toBe(""); + expect(show("intent://example.com#Intent;scheme=http;end")).toBe(""); + } finally { + act(() => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx index 8cfd22142698a..91fdc8e644e02 100644 --- a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx +++ b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx @@ -14,7 +14,7 @@ import { useEnvironmentPreviewTunnelOff } from "../../state/entities"; import { useEnvironments } from "../../state/environments"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { BrowserChrome } from "./BrowserBar"; -import { loopbackUrlForDevice } from "./browserTabs"; +import { localPreviewUrlForDevice } from "./browserTabs"; import { TunnelWebView, type TunnelNavigation, type TunnelWebViewRef } from "./TunnelWebView"; type LocalPreviewRouteScreenProps = StaticScreenProps<{ @@ -231,9 +231,9 @@ function hostOf(value: string): string { } } -// The unspecified address would name the phone itself, so it becomes the environment's localhost. +// A route URL that is not a web address opens the preview empty, ready for one to be typed. function forDevice(url: string): string { - return loopbackUrlForDevice(url) ?? url; + return localPreviewUrlForDevice(url) ?? ""; } function normalizedOrNull(value: string): string | null { diff --git a/apps/mobile/src/features/browser/browserTabs.test.ts b/apps/mobile/src/features/browser/browserTabs.test.ts index 394b3fd404fb1..c4e892782f458 100644 --- a/apps/mobile/src/features/browser/browserTabs.test.ts +++ b/apps/mobile/src/features/browser/browserTabs.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { loopbackUrlForDevice } from "./browserTabs"; +import { localPreviewUrlForDevice, loopbackUrlForDevice } from "./browserTabs"; describe("loopbackUrlForDevice", () => { it("opens only the environment's loopback pages on this device", () => { @@ -18,3 +18,14 @@ describe("loopbackUrlForDevice", () => { expect(loopbackUrlForDevice("")).toBeNull(); }); }); + +describe("localPreviewUrlForDevice", () => { + it("loads http and https addresses and nothing else", () => { + expect(localPreviewUrlForDevice("http://0.0.0.0:3000/")).toBe("http://localhost:3000/"); + expect(localPreviewUrlForDevice("https://example.com/docs")).toBe("https://example.com/docs"); + expect(localPreviewUrlForDevice(" JavaScript:void(0)")).toBeNull(); + expect(localPreviewUrlForDevice("file:///tmp/a.html")).toBeNull(); + expect(localPreviewUrlForDevice("data:text/html,hello")).toBeNull(); + expect(localPreviewUrlForDevice("")).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/browser/browserTabs.ts b/apps/mobile/src/features/browser/browserTabs.ts index 294d67ca8ce09..b27cd442c4f92 100644 --- a/apps/mobile/src/features/browser/browserTabs.ts +++ b/apps/mobile/src/features/browser/browserTabs.ts @@ -38,3 +38,15 @@ export function loopbackUrlForDevice(value: string): string | null { return null; } } + +/** The address a local preview loads for `value`: an http(s) URL, or null when it is anything else. */ +export function localPreviewUrlForDevice(value: string): string | null { + const loopback = loopbackUrlForDevice(value); + if (loopback !== null) return loopback; + try { + const url = new URL(value); + return /^https?:$/.test(url.protocol) ? url.toString() : null; + } catch { + return null; + } +} diff --git a/apps/mobile/src/features/connection/pairing.test.ts b/apps/mobile/src/features/connection/pairing.test.ts index 466fbfa7a282d..a3f2fab4861f5 100644 --- a/apps/mobile/src/features/connection/pairing.test.ts +++ b/apps/mobile/src/features/connection/pairing.test.ts @@ -1,3 +1,4 @@ +import { resolveRemotePairingTarget } from "@t3tools/shared/remote"; import { describe, expect, it } from "vite-plus/test"; import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing"; @@ -20,6 +21,20 @@ describe("buildPairingUrl", () => { "https://192.168.1.100:3773/#token=pairing-token", ); }); + + it("pairs with the address's own origin when the address carries a query", () => { + const pairingUrl = buildPairingUrl( + "https://remote.example.com/?host=https%3A%2F%2Fother.example.com", + "pairing-token", + ); + + expect(pairingUrl).toBe("https://remote.example.com/#token=pairing-token"); + expect(resolveRemotePairingTarget({ pairingUrl })).toEqual({ + credential: "pairing-token", + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + }); + }); }); describe("extractPairingUrlFromQrPayload", () => { diff --git a/apps/mobile/src/features/connection/pairing.ts b/apps/mobile/src/features/connection/pairing.ts index d596343d3f90e..2d9b129a0fc13 100644 --- a/apps/mobile/src/features/connection/pairing.ts +++ b/apps/mobile/src/features/connection/pairing.ts @@ -38,6 +38,8 @@ export function buildPairingUrl(host: string, code: string): string { try { const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`); + // The code goes to the address shown, so a query cannot name another destination. + url.search = ""; url.hash = new URLSearchParams([["token", c]]).toString(); return url.toString(); } catch { diff --git a/apps/mobile/src/features/files/FileMarkdownPreview.tsx b/apps/mobile/src/features/files/FileMarkdownPreview.tsx index 23035511a5c2d..2e8d030d2b2f8 100644 --- a/apps/mobile/src/features/files/FileMarkdownPreview.tsx +++ b/apps/mobile/src/features/files/FileMarkdownPreview.tsx @@ -16,7 +16,7 @@ import { import { NativeScrollView } from "../../native/NativeScrollViewMarker"; import { RefreshControl } from "../../components/ui/RefreshControl"; -import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; +import { tryOpenWebLink } from "../../lib/openExternalUrl"; import { FONT_FAMILIES } from "../../lib/fontFamilies"; import { resolveNativeMarkdownTypography } from "../../lib/appearancePreferences"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; @@ -228,7 +228,7 @@ export function FileMarkdownPreview(props: { openMedia(href, true); }; const onLinkPress = (href: string) => { - if (!openMedia(href)) void tryOpenExternalUrl(href, "markdown-link"); + if (!openMedia(href)) void tryOpenWebLink(href, "markdown-link"); }; const refreshControl = props.onRefresh ? ( diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index ba2e30479a32c..b1f9650990b94 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -594,6 +594,8 @@ function SwipeActionButton(props: { readonly menu?: ThreadSwipeAction["menu"]; readonly onPress: () => void; readonly rowHeight: number; + /** A trailing action slides left under the stretching action's pill on a full swipe. */ + readonly slidesUnderStretch: boolean; readonly stretchesOnFullSwipe: boolean; readonly translation: SharedValue; }) { @@ -601,6 +603,7 @@ function SwipeActionButton(props: { actionsWidth, entryRange: [entryRangeStart, entryRangeEnd], fullSwipeThreshold, + slidesUnderStretch, stretchesOnFullSwipe, translation, } = props; @@ -672,12 +675,18 @@ function SwipeActionButton(props: { }; }); const labelStyle = useAnimatedStyle(() => { + const reveal = Math.max(-translation.value, 0); + const stretch = Math.max(reveal - actionsWidth, 0); if (!stretchesOnFullSwipe) { - return { opacity: 1 }; + // The pill covers this action's circle but not its label, so hide the label before its + // circle reaches the pill; otherwise it runs into the stretching action's label. + return { + opacity: slidesUnderStretch + ? interpolate(stretch, [0, ACTION_ITEM_WIDTH - circleSize], [1, 0], Extrapolation.CLAMP) + : 1, + }; } - const reveal = Math.max(-translation.value, 0); - const stretch = Math.max(reveal - actionsWidth, 0); return { opacity: interpolate( reveal, @@ -850,6 +859,7 @@ function ThreadSwipeActions(props: { label={props.primaryAction.label} onPress={props.primaryAction.onPress} rowHeight={props.rowHeight} + slidesUnderStretch={false} stretchesOnFullSwipe={fullSwipeIsPrimary} translation={props.translation} /> @@ -866,6 +876,7 @@ function ThreadSwipeActions(props: { menu={secondaryAction.menu} onPress={secondaryAction.onPress} rowHeight={props.rowHeight} + slidesUnderStretch={fullSwipeIsPrimary} stretchesOnFullSwipe={!fullSwipeIsPrimary} translation={props.translation} /> diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts index 135cf4e1d85a7..fe02cc50a6fd2 100644 --- a/apps/mobile/src/features/home/useThreadListActions.test.ts +++ b/apps/mobile/src/features/home/useThreadListActions.test.ts @@ -351,37 +351,46 @@ describe("pinned thread operation permissions", () => { }); describe("thread reorder connection availability", () => { - it.each(["active", "pinned"] as const)( - "rejects %s materialization involving a cached capable offline neighbor", - async (section) => { - const moved = makeThread({ - pinnedAt: section === "pinned" ? "2026-09-02T00:00:00.000Z" : null, - }); - state.shells = [ - moved, - makeThread({ - id: ThreadId.make("offline-neighbor"), - environmentId: otherEnvironmentId, - createdAt: "2026-09-02T00:00:00.000Z", - pinnedAt: moved.pinnedAt, - }), - ]; - state.scopes.get(otherEnvironmentId)?.add(AuthOrchestrationOperateScope); - state.connectedEnvironmentIds = [primaryEnvironmentId]; + const offlineNeighborCase = (pinnedAt: string | null) => { + const moved = makeThread({ pinnedAt }); + state.shells = [ + moved, + makeThread({ + id: ThreadId.make("offline-neighbor"), + environmentId: otherEnvironmentId, + createdAt: "2026-09-02T00:00:00.000Z", + pinnedAt, + }), + ]; + state.scopes.get(otherEnvironmentId)?.add(AuthOrchestrationOperateScope); + state.connectedEnvironmentIds = [primaryEnvironmentId]; + return moved; + }; - const { moveThread } = useThreadListActions(); - expect(await moveThread(moved, "up")).toBe(false); - expect(state.requests).toEqual([]); + it("rejects pinned materialization involving a cached capable offline neighbor", async () => { + const moved = offlineNeighborCase("2026-09-02T00:00:00.000Z"); - state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; + const { moveThread } = useThreadListActions(); + expect(await moveThread(moved, "up")).toBe(false); + expect(state.requests).toEqual([]); - expect(await moveThread(moved, "up")).toBe(true); - expect(state.requests).toHaveLength(2); - expect(new Set(state.requests.map(({ environmentId }) => environmentId))).toEqual( - new Set([primaryEnvironmentId, otherEnvironmentId]), - ); - }, - ); + state.connectedEnvironmentIds = [primaryEnvironmentId, otherEnvironmentId]; + + expect(await moveThread(moved, "up")).toBe(true); + expect(state.requests).toHaveLength(2); + expect(new Set(state.requests.map(({ environmentId }) => environmentId))).toEqual( + new Set([primaryEnvironmentId, otherEnvironmentId]), + ); + }); + + it("moves an active thread past a cached offline neighbor by writing only itself", async () => { + const moved = offlineNeighborCase(null); + + expect(await useThreadListActions().moveThread(moved, "up")).toBe(true); + expect(state.requests).toEqual([ + expect.objectContaining({ action: "reorderActive", environmentId: primaryEnvironmentId }), + ]); + }); it.each(["active", "pinned"] as const)( "uses the latest connection state in a retained %s move callback", diff --git a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx index 99ad80b80074e..11e92266cc327 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestControls.tsx @@ -119,6 +119,8 @@ export function PullRequestActionToolbar(props: { readonly pr: PullRequestDetail | null; readonly params: PullRequestParams; readonly filePath?: string; + /** The head of the diff on screen, when the screen shows one. */ + readonly reviewedHeadSha?: string | undefined; /** The screen's actions menu; the vertical bar shows it here with the toolbar's tools. */ readonly menu: AppBarMenu; readonly onOpenFiles?: () => void; @@ -152,7 +154,11 @@ export function PullRequestActionToolbar(props: { const chooseThread = agent.chooseThread; const agentActions = agent.actions.filter((action) => action.task !== "ask"); const open = (mode: "review" | "comment") => - navigation.navigate("PullRequestReview", { ...props.params, mode }); + navigation.navigate("PullRequestReview", { + ...props.params, + mode, + reviewedHeadSha: props.reviewedHeadSha ?? props.pr?.headSha, + }); const primaryPress = () => (pendingReview ? open("review") : agent.start("ask")); const threadMenuItems = agent.threadActions("ask"); const openFiles = diff --git a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx index 42894c06b3785..6ff51d23cf3b2 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestMergeControls.tsx @@ -152,13 +152,23 @@ export function PullRequestMergeControls(props: { ? { label: gt("Checking stack…"), icon: PullRequestGlyph.merged } : null; const autoAction = pr.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge"; + // A stack auto-merge request on this layer also covers the open layers below it. + const stackAutoMerge = + stack.stack !== null && + stack.supportsStackActions && + stack.isFresh && + pr.capabilities.stackAutoMerge === true; const canAutoMerge = !busy && - (autoAction === "disable-auto-merge" || (!stack.stack && canMergeSingle)) && + (autoAction === "disable-auto-merge" || + (stack.stack ? stackAutoMerge && scope !== null && !scope.reason : canMergeSingle)) && permissions.canWrite && canPerformPullRequestAction(pr, autoAction); - const perform = async (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => { + const perform = async ( + action: "merge" | "enable-auto-merge" | "disable-auto-merge", + shownHeadSha: string | undefined, + ) => { if ( pending.current || (action !== "disable-auto-merge" && !method) || @@ -172,33 +182,47 @@ export function PullRequestMergeControls(props: { input: { ...target.input, action, - ...(action === "merge" && method && stack.stack && scope - ? { - stackNumber: stack.stack.number, - expectedStackHeads: scope.heads, - mergeMethod: method, - } - : action === "merge" && method + // A merge lands the head on screen and refuses one that moved; a stack pins its other layers. + ...(action !== "disable-auto-merge" && shownHeadSha + ? { expectedHeadSha: shownHeadSha } + : {}), + // A cancel needs no pinned heads, so it keeps the stack scope even while the stack refreshes. + ...(stack.stack && + ((action === "enable-auto-merge" && stackAutoMerge) || + (action === "disable-auto-merge" && + stack.supportsStackActions && + pr.capabilities.stackAutoMerge === true)) + ? { stackNumber: stack.stack.number } + : {}), + ...(action === "enable-auto-merge" && method && stackAutoMerge && scope + ? { expectedStackHeads: scope.heads, mergeMethod: method } + : action === "merge" && method && stack.stack && scope ? { - resolveMergeMethod: (fresh) => { - if ( - !canPerformPullRequestAction(fresh, "merge") || - !allowedMergeMethods(fresh).includes(method) - ) - throw new Error( - gt( - "The {term, select, mr {merge request} cr {change request} other {pull request}} changed. Refresh before merging.", - { - term: changeRequestTermKind(terminology), - }, - ), - ); - return method; - }, + stackNumber: stack.stack.number, + expectedStackHeads: scope.heads, + mergeMethod: method, } - : action === "enable-auto-merge" && method - ? { mergeMethod: method } - : {}), + : action === "merge" && method + ? { + resolveMergeMethod: (fresh) => { + if ( + !canPerformPullRequestAction(fresh, "merge") || + !allowedMergeMethods(fresh).includes(method) + ) + throw new Error( + gt( + "The {term, select, mr {merge request} cr {change request} other {pull request}} changed. Refresh before merging.", + { + term: changeRequestTermKind(terminology), + }, + ), + ); + return method; + }, + } + : action === "enable-auto-merge" && method + ? { mergeMethod: method } + : {}), }, }); // A stack can partly merge before the provider reports a failure. @@ -218,6 +242,8 @@ export function PullRequestMergeControls(props: { } }; const confirm = (action: "merge" | "enable-auto-merge" | "disable-auto-merge") => { + // The overview refreshes on focus, so the alert merges the head it was opened on. + const shownHeadSha = pr.headSha; const title = action === "merge" ? scope && scope.layers.length > 1 @@ -244,27 +270,37 @@ export function PullRequestMergeControls(props: { number: pr.number, }, ) - : action === "enable-auto-merge" + : action === "enable-auto-merge" && stackAutoMerge && scope ? gt( - "Merge #{number} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} when its requirements are met. This may happen immediately.", - { number: pr.number, kind: mergeMethodKind(method), method: method ?? "" }, + "Merge {layers} into {base} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} once their requirements are met. This may happen immediately.", + { + layers: scope.layers.map((layer) => `#${layer.number}`).join(" → "), + base: stack.stack?.base ?? "", + kind: mergeMethodKind(method), + method: method ?? "", + }, ) - : action === "disable-auto-merge" + : action === "enable-auto-merge" ? gt( - "Stop the provider from automatically merging this {term, select, mr {merge request} cr {change request} other {pull request}}.", - { - term: changeRequestTermKind(terminology), - }, + "Merge #{number} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} when its requirements are met. This may happen immediately.", + { number: pr.number, kind: mergeMethodKind(method), method: method ?? "" }, ) - : gt( - "Merge #{number} into {branch} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}}.", - { - number: pr.number, - branch: pr.baseBranch, - kind: mergeMethodKind(method), - method: method ?? "", - }, - ); + : action === "disable-auto-merge" + ? gt( + "Stop the provider from automatically merging this {term, select, mr {merge request} cr {change request} other {pull request}}.", + { + term: changeRequestTermKind(terminology), + }, + ) + : gt( + "Merge #{number} into {branch} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}}.", + { + number: pr.number, + branch: pr.baseBranch, + kind: mergeMethodKind(method), + method: method ?? "", + }, + ); Dialog.alert(title, message, [ { text: gt("Cancel"), style: "cancel" }, { @@ -274,7 +310,7 @@ export function PullRequestMergeControls(props: { : action === "enable-auto-merge" ? gt("Enable auto-merge") : gt("Disable auto-merge"), - onPress: () => void perform(action), + onPress: () => void perform(action, shownHeadSha), }, ]); }; diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx index ec45e5f3a33ca..8bf3c0290b45d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx @@ -70,7 +70,13 @@ const VERDICTS = [ export function PullRequestReviewSheet({ route, -}: StaticScreenProps) { +}: StaticScreenProps< + PullRequestParams & { + readonly mode: "review" | "comment"; + /** The head the opening screen showed; this sheet's own read can run ahead of it. */ + readonly reviewedHeadSha?: string | undefined; + } +>) { const params = route.params; const gt = useGT(); const m = useMessages(); @@ -97,6 +103,7 @@ export function PullRequestReviewSheet({ onChangeValue: setBody, support: result.data?.capabilities ?? null, }); + const reviewedHeadSha = params.reviewedHeadSha ?? result.data?.headSha; const stale = store.draft.comments.some((comment) => comment.headSha !== result.data?.headSha); const [requestedVerdict, setRequestedVerdict] = useState("comment"); const offered = VERDICTS.filter((option) => permissions.verdicts.includes(option.value)); @@ -130,6 +137,7 @@ export function PullRequestReviewSheet({ ...target, input: { ...target.input, + ...(reviewedHeadSha ? { expectedHeadSha: reviewedHeadSha } : {}), verdict: verdict.value, body, comments: submitted.comments.map( @@ -150,8 +158,8 @@ export function PullRequestReviewSheet({ pullRequestParams(route.params), [route.params]); usePullRequestEnvironmentFallback(params); const connected = usePullRequestConnected(params.environmentId); const [chosenSection, setSection] = useState<"overview" | "activity" | "guide">(() => { @@ -626,7 +628,11 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps - navigation.navigate("PullRequestReview", { ...params, mode: "review" }), + navigation.navigate("PullRequestReview", { + ...params, + mode: "review", + reviewedHeadSha: pr?.headSha, + }), }, ] : []), @@ -1271,6 +1277,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { navigation.navigate("PullRequestReview", { ...route.params, mode: "review", + reviewedHeadSha: diffHead.sha ?? undefined, }), }, ] @@ -1503,6 +1510,7 @@ function PullRequestFileRouteContent({ route }: PullRequestFileRouteProps) { navigation.navigate("PullRequestFiles", route.params)} diff --git a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx index 852ba3932323e..97e35e7739f8e 100644 --- a/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx +++ b/apps/mobile/src/features/pull-requests/guide/PullRequestGuideScreen.tsx @@ -283,6 +283,7 @@ export function PullRequestGuideStopScreen({ route }: StaticScreenProps ({ diff: vi.fn() })); vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } })); -import { usePullRequestDiff, usePullRequestDiffEntry } from "./usePullRequestDiff"; +import { + pullRequestParams, + usePullRequestDiff, + usePullRequestDiffEntry, +} from "./usePullRequestDiff"; import * as reviewModel from "../review/reviewModel"; import { getCachedNativeReviewDiffData } from "../review/nativeReviewDiffAdapter"; @@ -290,3 +294,17 @@ it("holds further pages back until a pull to refresh has reread page one", async expect(screen.current.patch).toContain("+pushed"); expect(screen.current.canLoadMore).toBe(true); }); + +it("keeps only the pull request a route names", () => { + const pullRequest = { + environmentId: "environment", + projectId: "project", + repository: "owner/repo", + number: 1, + host: "git.example.com", + navigationUrl: "https://git.example.com/owner/repo/pull/1#discussion_r1", + navigationId: 2, + }; + const routeParams = { ...pullRequest, commit: "abc1234", path: "src/index.ts" }; + expect(pullRequestParams(routeParams)).toEqual(pullRequest); +}); diff --git a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts index 5cf121b7f5660..85527e491c93a 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestDiff.ts @@ -34,6 +34,20 @@ export type PullRequestParams = { export type PullRequestDiffParams = PullRequestParams & { readonly commit?: string }; +/** The pull request a route names, without whatever else arrived on that route. */ +export function pullRequestParams(params: PullRequestParams): PullRequestParams { + return { + environmentId: params.environmentId, + projectId: params.projectId, + repository: params.repository, + number: params.number, + ...(params.host === undefined ? {} : { host: params.host }), + ...(params.navigationUrl === undefined ? {} : { navigationUrl: params.navigationUrl }), + ...(params.navigationId === undefined ? {} : { navigationId: params.navigationId }), + ...(params.initialSummary === undefined ? {} : { initialSummary: params.initialSummary }), + }; +} + export function pullRequestTarget(params: PullRequestParams) { return { environmentId: EnvironmentId.make(params.environmentId), diff --git a/apps/mobile/src/features/settings/CloudVoiceSection.tsx b/apps/mobile/src/features/settings/CloudVoiceSection.tsx index 3e782d2457fa3..1e32e2585e072 100644 --- a/apps/mobile/src/features/settings/CloudVoiceSection.tsx +++ b/apps/mobile/src/features/settings/CloudVoiceSection.tsx @@ -8,6 +8,7 @@ import { secretRequestReference, } from "@t3tools/client-runtime/secret-request"; import { + AuthProvidersManageScope, AuthSettingsWriteScope, CLOUD_SPEECH_LABELS, CLOUD_SPEECH_PROVIDER_NAMES, @@ -188,6 +189,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const keys = useAtomValue(cloudVoiceKeysAtom(id)); const reload = useAtomRefresh(cloudVoiceKeysAtom(id)); const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); + const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope); const [editing, setEditing] = useState<{ provider: CloudSpeechProvider; enable: boolean; @@ -199,6 +201,7 @@ function CloudChoices({ environment, active, onClose }: Props & { onClose: () => const [model, setModel] = useState(""); const [sourceId, setSourceId] = useState(null); const sources = + canUseReferences && hasFeatureFlag(environment.serverConfig, "secretProviders") && environment.serverConfig?.secretReferences ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) diff --git a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx index 8e5cf5f500856..86641489f35cd 100644 --- a/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx +++ b/apps/mobile/src/features/settings/EnvironmentRoutesSection.tsx @@ -3,6 +3,7 @@ import { Button } from "../../components/ui/Button"; import * as Dialog from "../../components/ui/Dialog"; import { useAtomValue } from "@effect/atom-react"; import { + canRemoveRoute, type ConnectionRoute, type ConnectionRouteKind, connectionRouteAddress, @@ -225,10 +226,7 @@ export function EnvironmentRoutesSection({ if (!cancelled) move(index, dropIndex(index, translation)); }} onStep={(direction) => move(index, direction === "up" ? index - 1 : index + 1)} - // A learned route would be learned again, so it is only reordered. - onRemove={ - routes.length > 1 && !isLearned(route) ? () => confirmRemove(route) : undefined - } + onRemove={canRemoveRoute(routes, route) ? () => confirmRemove(route) : undefined} /> ); })} diff --git a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx index 134e92e62f43a..dcfc3b99643b6 100644 --- a/apps/mobile/src/features/sharing/IncomingShareProvider.tsx +++ b/apps/mobile/src/features/sharing/IncomingShareProvider.tsx @@ -18,7 +18,7 @@ import { CommonActions } from "@react-navigation/native"; import { buildIncomingShareDraft, - isShareFileUriUnderOwnedRoots, + isOwnedShareFileUri, selectIncomingShareAttachmentsForServer, type IncomingShareDestination, type IncomingShareDraft, @@ -98,19 +98,25 @@ async function readFileSize(uri: string): Promise { return new File(uri).size ?? null; } -async function removeOwnedFile(uri: string): Promise { +/** `persisted` marks a copy this app saved itself, which needs no ownership check. */ +async function removeOwnedFile(uri: string, persisted = false): Promise { if (!uri.startsWith("file:")) { return; } try { const { File, Paths } = await import("expo-file-system"); // Delete only app-owned files; iOS open-in-place shares can reference the sender's original. - const ownedRootUris = [ - Paths.document.uri, - Paths.cache.uri, - ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri), - ]; - if (!isShareFileUriUnderOwnedRoots(uri, ownedRootUris)) { + const owned = + persisted || + isOwnedShareFileUri(uri, { + platform: Platform.OS, + cacheUri: Paths.cache.uri, + otherRootUris: [ + Paths.document.uri, + ...Object.values(Paths.appleSharedContainers ?? {}).map((directory) => directory.uri), + ], + }); + if (!owned) { return; } const file = new File(uri); @@ -142,7 +148,7 @@ async function removeReplayedPayloadFiles(payloads: ReadonlyArray) uris.add(payload.contentUri); } } - await Promise.all([...uris].map(removeOwnedFile)); + await Promise.all([...uris].map((uri) => removeOwnedFile(uri))); } // Share the queue across remounts so lifecycle notifications cannot ingest one handoff twice. @@ -187,10 +193,12 @@ const incomingShareInbox = new IncomingShareInbox({ return { draft, cleanup: async () => { - await Promise.all([...cleanupUris].map(removeOwnedFile)); + await Promise.all( + [...cleanupUris].map((uri) => removeOwnedFile(uri, persistedUris.has(uri))), + ); }, rollback: async () => { - await Promise.all([...persistedUris].map(removeOwnedFile)); + await Promise.all([...persistedUris].map((uri) => removeOwnedFile(uri, true))); }, }; }, diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 7ca92b23c3208..7cab7a84da14e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -8,6 +8,7 @@ import type { ResolvedSharePayload, SharePayload } from "expo-sharing"; import { buildIncomingShareDraft, hasIncomingShareContent, + isOwnedShareFileUri, isShareFileUriUnderOwnedRoots, selectIncomingShareAttachments, selectIncomingShareAttachmentsForServer, @@ -671,6 +672,34 @@ describe("share cleanup ownership", () => { ).toBe(false); }); + it("deletes only the resolver's share copies on Android", () => { + const data = "file:///data/user/0/codes.t3.app"; + const owned = (uri: string, platform = "android") => + isOwnedShareFileUri(uri, { + platform, + cacheUri: `${data}/cache/`, + otherRootUris: [`${data}/files/`], + }); + const copy = `${data}/cache/shared-0b0e3f0c-6c1d-4b53-9d0a-2f6f1c3a9e11`; + expect(owned(`file:${copy.slice("file://".length)}/report.pdf`)).toBe(true); + expect( + owned( + "file:///data/data/codes.t3.app/cache/shared-0b0e3f0c-6c1d-4b53-9d0a-2f6f1c3a9e11/a.png", + ), + ).toBe(true); + for (const uri of [ + `${data}/files/t3-composer-attachments/id-report.pdf`, + `${data}/files/SQLite/state.db`, + `${data}/cache/http-cache/journal`, + `${data}/cache/shared-notes/notes.txt`, + `${copy}/..%2F..%2Ffiles%2FSQLite%2Fstate.db`, + copy, + ]) { + expect(owned(uri)).toBe(false); + } + expect(owned(`${data}/files/SQLite/state.db`, "ios")).toBe(true); + }); + it("refuses non-file URIs and the owned root itself", () => { expect(isShareFileUriUnderOwnedRoots("content://shared/report", ownedRoots)).toBe(false); expect( diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 86c17c6059e0e..30a334ca46aaf 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -93,6 +93,34 @@ export function isShareFileUriUnderOwnedRoots( }); } +/** + * On Android only the native resolver's `shared-` copies are this app's to delete; other + * shared URIs are not copies. + */ +export function isOwnedShareFileUri( + uri: string, + owned: { + readonly platform: string; + readonly cacheUri: string; + readonly otherRootUris: ReadonlyArray; + }, +): boolean { + if (owned.platform !== "android") { + return isShareFileUriUnderOwnedRoots(uri, [owned.cacheUri, ...owned.otherRootUris]); + } + // The resolver reports its copy by canonical path, where `/data/user/0` is `/data/data`. + const canonical = (fileUri: string) => + normalizedFileUriPath(fileUri)?.replace(/^\/data\/user\/0\//, "/data/data/"); + const path = canonical(uri); + const cachePath = canonical(owned.cacheUri)?.replace(/\/*$/, "/"); + return ( + path !== undefined && + cachePath !== undefined && + path.startsWith(cachePath) && + /^shared-[\da-f-]{36}\/[^/]+$/i.test(path.slice(cachePath.length)) + ); +} + export interface IncomingShareFileReader { readonly readBase64: (uri: string) => Promise; readonly removeOwnedFile: (uri: string) => Promise | void; diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx new file mode 100644 index 0000000000000..018f3e27ebf6a --- /dev/null +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx @@ -0,0 +1,61 @@ +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const harness = vi.hoisted(() => ({ + openedLinks: [] as string[], + openWindow: null as ((event: { nativeEvent: { targetUrl: string } }) => void) | null, +})); + +type Children = { children?: ReactNode }; + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, + View: ({ children }: Children) =>
{children}
, + Pressable: ({ children }: Children) =>
{children}
, +})); +vi.mock("react-native-webview", () => ({ + WebView: (props: { onOpenWindow: typeof harness.openWindow }) => { + harness.openWindow = props.onOpenWindow; + return null; + }, +})); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); +vi.mock("../../components/ui/AppText", () => ({ + AppText: ({ children }: Children) => {children}, +})); +vi.mock("../../lib/htmlRenderTheme", () => ({ + mobileHtmlRenderTheme: () => ({ variables: {} }), +})); +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({}), +})); +vi.mock("../../state/assets", () => ({ + useAssetUrlState: () => ({ _tag: "Initial" }), + useRefreshAssetUrl: () => async () => null, +})); +vi.mock("../../native/useOpenPullRequest", () => ({ + useOpenPullRequest: () => async (url: string) => { + harness.openedLinks.push(url); + return true; + }, +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); + +import { HtmlRenderWebView } from "./HtmlRenderWebView"; + +it("opens a render's issue link the way the thread's own links open", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + await act(async () => + root.render(), + ); + + const issueUrl = "https://github.com/pingdotgg/t3code/issues/41939"; + await act(async () => harness.openWindow?.({ nativeEvent: { targetUrl: issueUrl } })); + + expect(harness.openedLinks).toEqual([issueUrl]); + await act(async () => root.unmount()); +}); diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx index d756e3f3e7918..8f3c76eb507a1 100644 --- a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx @@ -17,7 +17,7 @@ import { WebView, type WebViewMessageEvent } from "react-native-webview"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; -import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; +import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; @@ -83,6 +83,7 @@ export function HtmlRenderWebView(props: { readonly onLoadError?: () => void; }) { const theme = useHtmlRenderTheme(); + const openLink = useOpenPullRequest(); const [initialTheme] = useState(theme); const [generation, setGeneration] = useState(0); const [loaded, setLoaded] = useState(false); @@ -144,7 +145,7 @@ export function HtmlRenderWebView(props: { } onOpenWindow={(event) => { const url = event.nativeEvent.targetUrl; - if (/^https?:/i.test(url)) void tryOpenExternalUrl(url, "html-render"); + if (/^https?:/i.test(url)) void openLink(url); }} onLoadEnd={() => { setLoaded(true); diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsx index 996851e37fbca..17d8c87423233 100644 --- a/apps/mobile/src/features/threads/McpAppWebView.tsx +++ b/apps/mobile/src/features/threads/McpAppWebView.tsx @@ -15,6 +15,7 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { CommandId, MessageId } from "@t3tools/contracts"; import { + MCP_APP_DOCUMENT_MESSAGE, mcpAppAllowAttribute, mcpAppFileName, mcpAppReferencesEqual, @@ -57,14 +58,21 @@ const ROW_BOTTOM_MARGIN = 8; function outerDocument(src: string, allow: string, secret: string) { const attribute = (value: string) => value.replace(/&/g, "&").replace(/"/g, """).replace(/ `; } diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index c6fa629d18b43..ba759225ea7f6 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -32,7 +32,7 @@ import { import { useEffect, useRef, useState } from "react"; import { Platform, Pressable, View } from "react-native"; import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; -import { KeyboardController } from "react-native-keyboard-controller"; +import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller"; import { AuthOrchestrationOperateScope, @@ -1014,30 +1014,32 @@ export function NewTaskDraftScreen(props: { if (!flow.selectedModel) { return ( }> - - {environmentControl} - - {environmentConnected && selectedEnvironmentServerConfig ? ( - - Your draft is saved on this device. {selectedEnvironmentLabel} has no - model available. Install or sign in to a provider there to choose one. - - ) : ( - - Your draft is saved on this device. Connect to an environment to choose its first - model. - - )} - - - + + + {environmentControl} + + {environmentConnected && selectedEnvironmentServerConfig ? ( + + Your draft is saved on this device. {selectedEnvironmentLabel} has no + model available. Install or sign in to a provider there to choose one. + + ) : ( + + Your draft is saved on this device. Connect to an environment to choose its first + model. + + )} + + + + ); } diff --git a/apps/mobile/src/features/threads/SecretRequestCard.tsx b/apps/mobile/src/features/threads/SecretRequestCard.tsx index e52fae8ce659f..24b0a1aa81d67 100644 --- a/apps/mobile/src/features/threads/SecretRequestCard.tsx +++ b/apps/mobile/src/features/threads/SecretRequestCard.tsx @@ -16,10 +16,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { useGT, useMessages } from "gt-react-native"; @@ -31,6 +32,7 @@ import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/ import { SecretTextInput } from "../../components/ui/SecretTextInput"; import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { Button } from "../../components/ui/Button"; @@ -91,10 +93,13 @@ function PendingSecretRequestForm(props: { const inputs = secretRequestInputs(item, m); const multiple = item.fields !== undefined; const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId)); + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(props.environmentId, AuthProvidersManageScope); // A reference answers one value, so a card with fields is always typed. - const sources = multiple - ? NO_SOURCES - : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); + const sources = + multiple || !canUseReferences + ? NO_SOURCES + : secretRequestSources(config, config?.settings.secretProviders ?? {}, m); const [sourceId, setSourceId] = useState(null); const source = sources.find((candidate) => candidate.id === sourceId) ?? null; const [values, setValues] = useState>>({}); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 29aedee000f53..61c8cc314cf5f 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -65,9 +65,6 @@ import { resolveUserMessagePresentation, } from "@t3tools/client-runtime/user-message"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; -import { turnChanges } from "@t3tools/client-runtime/state/thread-repositories"; -import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { AuthFilesystemReadScope, @@ -87,7 +84,12 @@ import { } from "@t3tools/contracts"; import type { ToolCallVisibility } from "@t3tools/contracts/settings"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; -import { hasThreadLinks, hostedThreadLink, parseThreadLinkHref } from "@t3tools/shared/threadLinks"; +import { + hasThreadLinks, + hostedThreadLink, + parseThreadLinkHref, + threadLinkRefs, +} from "@t3tools/shared/threadLinks"; import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks"; import { parseComposerContextHref, @@ -211,8 +213,6 @@ import { type MediaVideoPreviewSource, } from "../../lib/videoPreviewSource"; import { CopyTextButton } from "./CopyTextButton"; -import { getReviewSectionIdForCheckpoint } from "../review/reviewModel"; -import { setReviewSelectedSectionId } from "../review/reviewState"; import { Menu } from "../../components/ui/Menu"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; import { useBarInset, useContentTopInset } from "../../components/ui/useBarInset"; @@ -344,6 +344,11 @@ import { } from "./threadFeedEndFollow"; import { useMessageTimeFormatter } from "./useMessageTimeFormatter"; +const linkedThreadEnvironmentIds = (markdown: string, environmentId: EnvironmentId) => + hasThreadLinks(markdown) + ? threadLinkRefs(markdown, environmentId).map((ref) => ref.environmentId) + : []; + const WIDE_MARKDOWN_BLOCK_OPTIONS = { // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width. includeBlockquotes: Platform.OS === "ios", @@ -1317,7 +1322,10 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { const liveMarkdown = useLiveThreadLinkLabels( props.markdown, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.markdown) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.markdown) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.markdown, props.environmentId), + ), ); const [quoteSelection, setQuoteSelection] = useState<{ markdown: string; @@ -1986,7 +1994,6 @@ function renderFeedEntry( readonly onToggleWorkRow: (rowId: string, anchorKey?: string, groupId?: string) => void; readonly onToggleUserMessage: (rowId: string, anchorKey: string) => void; readonly onToggleTurnFold: (runId: RunId) => void; - readonly onOpenTurnDiff: (checkpoint: ThreadCheckpointSummary) => void; readonly onPressPreview: (source: FilePreviewSource) => void; readonly onPlaybackStart: () => void; readonly markdownLinkHandlers: MarkdownLinkHandlers; @@ -2081,12 +2088,6 @@ function renderFeedEntry( onOpenDetails={props.onOpenSetupDetails} /> ) : null} - {entry.checkpointSummary ? ( - - ) : null} ); } @@ -2178,14 +2179,6 @@ function renderFeedEntry( hasFailure={entry.hasFailure} shimmer={entry.shimmer} thought={entry.thought} - trailing={ - entry.checkpointSummary ? ( - - ) : null - } onToggle={() => props.onToggleWorkGroup(entry.groupId, entry.id)} /> ); @@ -2698,12 +2691,6 @@ function renderFeedEntry( onPressPreview={props.onPressPreview} onPlaybackStart={props.onPlaybackStart} /> - {showAssistantMeta && message.checkpointSummary ? ( - - ) : null} {showAssistantMeta ? ( void; -}) { - const gt = useGT(); - const { repositories, rootFiles, totals } = turnChanges(props.checkpoint); - const { additions, deletions } = totals; - const folderCount = repositories.length + (rootFiles.length > 0 ? 1 : 0); - const repositoriesLabel = - repositories.length === 0 - ? null - : folderCount === 1 - ? repositories[0]!.name - : gt("{count} repos", { count: folderCount }); - const changedIn = - repositories.length === 0 - ? null - : [ - ...(rootFiles.length > 0 ? [gt("this folder")] : []), - ...repositories.map((repository) => repository.name), - ].join(", "); - return ( - props.onOpenTurnDiff(props.checkpoint)} - className="min-h-11 shrink-0 flex-row items-center gap-2 px-2 active:bg-subtle" - > - {repositoriesLabel ? ( - - {repositoriesLabel} - - ) : null} - - +{formatDiffCount(additions)} - - - −{formatDiffCount(deletions)} - - - - ); -} - type UserMessageContentProps = { readonly text: string; readonly environmentId: EnvironmentId; @@ -2829,7 +2762,10 @@ function UserMessageContent(props: UserMessageContentProps) { const liveText = useLiveThreadLinkLabels( props.text, props.environmentId, - useLinkedEnvironments(hasThreadLinks(props.text) ? props.environmentId : null), + useLinkedEnvironments( + hasThreadLinks(props.text) ? props.environmentId : null, + linkedThreadEnvironmentIds(props.text, props.environmentId), + ), ); const threadIcons = useThreadChipIcons(props.environmentId, liveText, props.context?.records); const text = replaceComposerContextReferences(liveText, (ref) => { @@ -3172,19 +3108,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const [retainedMediaRowId, setRetainedMediaRowId] = useState(null); const focused = useIsFocused(); if (!focused && retainedMediaRowId !== null) setRetainedMediaRowId(null); - const onOpenTurnDiff = useCallback( - (checkpoint: ThreadCheckpointSummary) => { - setReviewSelectedSectionId( - scopedThreadKey(props.environmentId, props.threadId), - getReviewSectionIdForCheckpoint(checkpoint), - ); - navigation.navigate("ThreadReview", { - environmentId: props.environmentId, - threadId: props.threadId, - }); - }, - [navigation, props.environmentId, props.threadId], - ); const { themeAppearance } = useAppearancePreferences(); const copyFeedbackTimeoutRef = useRef | null>(null); const headerMaterialVisibleRef = useRef(false); @@ -4202,7 +4125,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (entry.type === "html-render") { return htmlRenderRowHeight(htmlRenderFrameHeight(entry.render, contentWidth)); } - if (workRowSizing.fixedRowHeight === undefined || entry.checkpointSummary) { + if (workRowSizing.fixedRowHeight === undefined) { return undefined; } switch (entry.type) { @@ -4313,7 +4236,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onToggleWorkRow, onToggleUserMessage, onToggleTurnFold, - onOpenTurnDiff, onPressPreview, onPlaybackStart: onInlinePlaybackStart, markdownLinkHandlers, diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts new file mode 100644 index 0000000000000..1538540949880 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.test.ts @@ -0,0 +1,9 @@ +import { expect, it } from "vite-plus/test"; + +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; + +it("keeps emoji whole at both cuts of a long branch name", () => { + expect(compactMenuBranchLabel("feature/abc😀-long-branch-name-😀-for-menus")).toBe( + "feature/abc…-for-menus", + ); +}); diff --git a/apps/mobile/src/features/threads/ThreadGitControls.logic.ts b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts new file mode 100644 index 0000000000000..a3441835b5951 --- /dev/null +++ b/apps/mobile/src/features/threads/ThreadGitControls.logic.ts @@ -0,0 +1,17 @@ +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; + +function truncateMiddle(value: string, maxLength: number): string { + if (value.length <= maxLength) { + return value; + } + + const headLength = Math.ceil((maxLength - 1) / 2); + const tailStart = value.length - Math.floor((maxLength - 1) / 2); + const headEnd = splitsSurrogatePair(value, headLength) ? headLength - 1 : headLength; + const tailFrom = splitsSurrogatePair(value, tailStart) ? tailStart + 1 : tailStart; + return `${value.slice(0, headEnd)}…${value.slice(tailFrom)}`; +} + +export function compactMenuBranchLabel(branch: string): string { + return truncateMiddle(branch, 24); +} diff --git a/apps/mobile/src/features/threads/ThreadGitControls.tsx b/apps/mobile/src/features/threads/ThreadGitControls.tsx index 5e67fb0181ad5..9e7ab388ccee4 100644 --- a/apps/mobile/src/features/threads/ThreadGitControls.tsx +++ b/apps/mobile/src/features/threads/ThreadGitControls.tsx @@ -30,20 +30,7 @@ import { type TerminalMenuSession, } from "../terminal/terminalMenu"; import { projectScriptMenuLabel } from "@t3tools/shared/projectScriptsCopy"; - -function truncateMiddle(value: string, maxLength: number): string { - if (value.length <= maxLength) { - return value; - } - - const headLength = Math.ceil((maxLength - 1) / 2); - const tailLength = Math.floor((maxLength - 1) / 2); - return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`; -} - -function compactMenuBranchLabel(branch: string): string { - return truncateMiddle(branch, 24); -} +import { compactMenuBranchLabel } from "./ThreadGitControls.logic"; function compactMenuStatus(gitStatus: VcsStatusResult | null, resolve: MessageResolver): string { if (!gitStatus) { @@ -237,8 +224,6 @@ function useThreadGitControlModel(props: ThreadGitMenuProps) { environmentId: String(environmentId), threadId: String(threadId), confirmAction: confirmableAction, - branchName, - includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"), }); return; } diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index 4f5b799f82879..41aed6dfd3d9f 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -39,6 +39,7 @@ import { useQuietThreadShell } from "../../state/entities"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { assetImageSource } from "../../lib/assetImageSource"; +import { appAtomRegistry } from "../../state/atom-registry"; import { beginQueuedRunEdit, useQueuedRunEdit } from "../../state/queued-run-edit"; import { environmentThreadDetails, threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -181,6 +182,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { runId, messageId: entry.messageId, originalText: entry.text, + modelSelection: entry.message?.followsThreadSelection + ? (appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(target))?.projection + .thread.modelSelection ?? entry.run.modelSelection) + : entry.run.modelSelection, + followsThreadSelection: entry.message?.followsThreadSelection === true, existingAttachments: entry.attachments, ...(entry.context ? { context: entry.context } : {}), }, diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx index 51fe125bf087e..fc14b7f172997 100644 --- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx +++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx @@ -1502,10 +1502,11 @@ export function ExistingThreadSettingsRouteScreen({ const structure = useQuietThreadStructure(selectedThreadDetailRef); const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef); const threadKey = scopedThreadKey(route.params.environmentId, route.params.threadId); - const draftSettings = useComposerDraftSettings(threadKey); const queuedRunEdit = useQueuedRunEdit(threadKey); // A queued edit can end while the sheet is open; the prompt then belongs to the thread's draft. const draftKey = activeComposerDraftKey(threadKey, route.params.draftKey, queuedRunEdit); + const draftSettings = useComposerDraftSettings(draftKey); + const threadDraftSettings = useComposerDraftSettings(threadKey); const prompt = useComposerDraft(draftKey).text; if (!selectedThread) { @@ -1567,7 +1568,7 @@ export function ExistingThreadSettingsRouteScreen({ rememberModelOptions(modelSelection.instanceId, modelSelection.model, options ?? []); updateModelSelection({ ...modelSelection, options }); }} - runtimeMode={draftSettings.runtimeMode ?? selectedThread.runtimeMode} + runtimeMode={threadDraftSettings.runtimeMode ?? selectedThread.runtimeMode} onUpdateRuntimeMode={(runtimeMode) => updateComposerDraftSettings(threadKey, { runtimeMode })} onClose={() => navigation.goBack()} /> diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx new file mode 100644 index 0000000000000..90b9580fd48bc --- /dev/null +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.test.tsx @@ -0,0 +1,124 @@ +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +type ActionProps = { label: string; disabled?: boolean; onPress: () => void }; +type IntroProps = { title: string; description: string }; +const state = vi.hoisted(() => ({ + refName: null as string | null, + intro: null as IntroProps | null, + actions: [] as ActionProps[], + ran: [] as object[], +})); + +vi.mock("react-native", () => ({ + View: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ goBack: () => {} }), +})); +vi.mock("../../../components/ui/SheetHeader", () => ({ SheetHeader: () => null })); +vi.mock("../../../components/ui/FitSheet", () => ({ + FitSheet: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../../components/ui/SheetIntro", () => ({ + SheetIntro: (props: IntroProps) => { + state.intro = props; + return null; + }, +})); +vi.mock("../../../state/query", () => ({ + useEnvironmentQuery: () => ({ + data: state.refName === null ? undefined : { refName: state.refName }, + }), +})); +vi.mock("../../../state/use-thread-selection", () => ({ + useThreadSelection: () => ({ + selectedThread: { environmentId: "environment" }, + selectedThreadProject: null, + }), +})); +vi.mock("../../../state/use-selected-thread-worktree", () => ({ + useSelectedThreadWorktree: () => ({ selectedThreadCwd: "/repo" }), +})); +vi.mock("../../../state/use-selected-thread-git-state", () => ({ + useSelectedThreadGitState: () => ({ selectedThreadBranches: [] }), +})); +vi.mock("../../../state/use-selected-thread-git-actions", () => ({ + useSelectedThreadGitActions: () => ({ + canWriteSourceControl: true, + canCreateFeatureBranch: true, + onRunSelectedThreadGitAction: (input: object) => { + state.ran.push(input); + return Promise.resolve(null); + }, + }), +})); +vi.mock("../../../state/vcs", () => ({ vcsEnvironment: { status: () => null } })); +vi.mock("../thread-inspector-navigation", () => ({ useReturnToThread: () => () => {} })); +vi.mock("./gitSheetComponents", () => ({ + SheetActionButton: (props: ActionProps) => { + state.actions.push(props); + return null; + }, +})); + +import { GitConfirmSheet } from "./GitConfirmSheet"; + +function setup(refName: string | null, params: Record) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + state.refName = refName; + state.intro = null; + state.actions = []; + state.ran = []; + const root = createRoot(document.createElement("div")); + act(() => { + root.render( + , + ); + }); + // Each render registers Continue first, then the feature branch button. + const [continueButton, featureBranchButton] = state.actions.slice(-2); + return { + continueButton: continueButton!, + featureBranchButton: featureBranchButton!, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("describes the action it runs on the branch that is checked out", async () => { + using screen = setup("main", { + confirmAction: "commit_push", + branchName: "docs", + includesCommit: "false", + commitMessage: "from the route", + filePaths: "a.ts,b.ts", + }); + expect(state.intro).toMatchObject({ + title: "Commit & push to default branch?", + description: expect.stringContaining('commit and push changes on "main"'), + }); + expect(screen.continueButton.label).toBe("Commit & push to main"); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([ + { action: "commit_push" }, + { action: "commit_push", featureBranch: true }, + ]); +}); + +it.each([ + ["an action it does not confirm", "main", "commit"], + ["no checked out branch", null, "push"], +])("runs nothing for %s", async (_case, refName, confirmAction) => { + using screen = setup(refName, { confirmAction }); + expect(screen.continueButton.disabled).toBe(true); + expect(screen.featureBranchButton.disabled).toBe(true); + await act(async () => screen.continueButton.onPress()); + await act(async () => screen.featureBranchButton.onPress()); + expect(state.ran).toEqual([]); +}); diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index 1da0ec450a572..32a6fcbe22c2a 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -1,4 +1,7 @@ -import { resolveDefaultBranchActionDialogCopy } from "@t3tools/client-runtime/state/vcs"; +import { + resolveDefaultBranchActionDialogCopy, + type DefaultBranchConfirmableAction, +} from "@t3tools/client-runtime/state/vcs"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; @@ -13,6 +16,7 @@ import { FitSheet } from "../../../components/ui/FitSheet"; import { SheetIntro } from "../../../components/ui/SheetIntro"; import { useSelectedThreadGitActions } from "../../../state/use-selected-thread-git-actions"; import { useSelectedThreadGitState } from "../../../state/use-selected-thread-git-state"; +import { useSelectedThreadWorktree } from "../../../state/use-selected-thread-worktree"; import { useThreadSelection } from "../../../state/use-thread-selection"; import { useEnvironmentQuery } from "../../../state/query"; import { @@ -28,13 +32,16 @@ type GitConfirmSheetProps = StaticScreenProps< readonly environmentId: string; readonly threadId: string; readonly confirmAction?: string; - readonly branchName?: string; - readonly includesCommit?: string; - readonly commitMessage?: string; - readonly filePaths?: string; } & GitRepositoryRouteParams >; +const CONFIRMABLE_ACTIONS: ReadonlyArray = [ + "push", + "create_pr", + "commit_push", + "commit_push_pr", +]; + export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); @@ -45,37 +52,35 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gitActions = useSelectedThreadGitActions(repository); const { canWriteSourceControl, canCreateFeatureBranch } = gitActions; const { selectedThread, selectedThreadProject } = useThreadSelection(); - // The overview that opened this sheet already holds the repository's status subscription. - const repositoryStatus = useEnvironmentQuery( - repository !== undefined && selectedThread !== null + const threadWorktree = useSelectedThreadWorktree(); + const selectedThreadCwd = repository?.cwd ?? threadWorktree.selectedThreadCwd; + // The Git controls that opened this sheet already hold the checkout's status subscription. + const gitStatus = useEnvironmentQuery( + selectedThread !== null && selectedThreadCwd !== null ? vcsEnvironment.status({ environmentId: selectedThread.environmentId, - input: { cwd: repository.cwd }, + input: { cwd: selectedThreadCwd }, }) : null, ); const terminology = sourceControlClients.get( repository === undefined ? selectedThreadProject?.repositoryIdentity?.provider - : repositoryStatus.data?.sourceControlProvider?.kind, + : gitStatus.data?.sourceControlProvider?.kind, ).changeRequest; const params = props.route.params; - const confirmAction = params.confirmAction as - | "push" - | "create_pr" - | "commit_push" - | "commit_push_pr" - | undefined; - const branchName = params.branchName ?? ""; - const includesCommit = params.includesCommit === "true"; + // The route only names the action; what the sheet says about it comes from the checkout. + const confirmAction = CONFIRMABLE_ACTIONS.find((action) => action === params.confirmAction); + const branchName = gitStatus.data?.refName ?? null; + const includesCommit = confirmAction === "commit_push" || confirmAction === "commit_push_pr"; const environmentId = params.environmentId ?? ""; const threadId = params.threadId ?? ""; const copy = useMemo( () => - confirmAction + confirmAction && branchName ? resolveDefaultBranchActionDialogCopy( { action: confirmAction, @@ -90,26 +95,17 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { ); const continuePendingAction = async () => { - if (!canWriteSourceControl || !confirmAction) return; + if (!canWriteSourceControl || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction }); }; const movePendingActionToFeatureBranch = useCallback(async () => { - if (!canCreateFeatureBranch || !confirmAction) return; + if (!canCreateFeatureBranch || !confirmAction || !copy) return; returnToThread({ environmentId, threadId }); if (includesCommit) { - await gitActions.onRunSelectedThreadGitAction({ - action: confirmAction, - featureBranch: true, - ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), - ...(params.filePaths ? { filePaths: params.filePaths.split(",") } : {}), - }); + await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, featureBranch: true }); return; } @@ -129,10 +125,10 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { }, [ canCreateFeatureBranch, confirmAction, + copy, gitActions, gitState.selectedThreadBranches, includesCommit, - params, returnToThread, environmentId, threadId, @@ -153,13 +149,13 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { void continuePendingAction()} /> void movePendingActionToFeatureBranch()} /> diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx index 0ab21904489e1..4c7225f5cbb4d 100644 --- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx @@ -247,10 +247,6 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) { threadId: String(threadId), ...repositoryParams, confirmAction: confirmableAction, - branchName, - includesCommit: String( - input.action === "commit_push" || input.action === "commit_push_pr", - ), }), ); return; diff --git a/apps/mobile/src/features/threads/thread-provider-instance.test.ts b/apps/mobile/src/features/threads/thread-provider-instance.test.ts index 56ddec3ab1542..a8f8c7723356e 100644 --- a/apps/mobile/src/features/threads/thread-provider-instance.test.ts +++ b/apps/mobile/src/features/threads/thread-provider-instance.test.ts @@ -208,13 +208,22 @@ describe("thread list reorder availability", () => { : current.activeReorderEnvironmentIds, }; }; - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2); + // Active rows sort by an implied key, so moving past an unarranged row writes only the mover. + const expectMoveDown = (neighborWritable: boolean) => { + const movable = section === "active" || neighborWritable; + expect(createThreadMovePlanner(plannerInput())(movedId, "down")?.length).toBe( + movable ? (section === "active" ? 1 : 2) : undefined, + ); + expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe( + movable, + ); + }; + expectMoveDown(true); const before = registry.get(environments); registry.set(connected, [onlineId]); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false); + expectMoveDown(false); expect(registry.get(environments).pinningEnvironmentIds.has(offlineId)).toBe(true); expect(registry.get(environments).settlementEnvironmentIds.has(offlineId)).toBe(true); expect(registry.get(environments).providersByEnvironmentId.get(offlineId)).toBe( @@ -260,7 +269,7 @@ describe("thread list reorder availability", () => { ); expect(updated.pinReorderEnvironmentIds.has(offlineId)).toBe(false); expect(updated.activeReorderEnvironmentIds.has(offlineId)).toBe(false); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); + expectMoveDown(false); registry.set( configs, @@ -284,16 +293,14 @@ describe("thread list reorder availability", () => { registry.set(connected, [onlineId, offlineId]); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toHaveLength(2); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(true); + expectMoveDown(true); expect(registry.get(environments).snoozePresetsByEnvironmentId.get(offlineId)).toBe( updated.snoozePresetsByEnvironmentId.get(offlineId), ); registry.set(configs, new Map([[onlineId, config]])); - expect(createThreadMovePlanner(plannerInput())(movedId, "down")).toBeNull(); - expect(computeThreadMoveAvailability(plannerInput()).get(movedId)?.canMoveDown).toBe(false); + expectMoveDown(false); } finally { registry.dispose(); } diff --git a/apps/mobile/src/features/threads/thread-work-log.tsx b/apps/mobile/src/features/threads/thread-work-log.tsx index eb81b4f641c78..e9178663e6e9a 100644 --- a/apps/mobile/src/features/threads/thread-work-log.tsx +++ b/apps/mobile/src/features/threads/thread-work-log.tsx @@ -1420,7 +1420,6 @@ export function ThreadWorkGroupToggle(props: { readonly hasFailure: boolean; readonly shimmer: boolean; readonly thought?: string | undefined; - readonly trailing?: ReactNode; readonly onToggle: () => void; }) { const gt = useGT(); @@ -1510,7 +1509,6 @@ export function ThreadWorkGroupToggle(props: { /> - {props.trailing} ); diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts index 171d73a148597..e0771be61c5eb 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.test.ts @@ -64,10 +64,15 @@ describe("resolveSubagentRowPresentation", () => { it("falls back to a trimmed prompt when the agent has no title", () => { const long = resolveSubagentRowPresentation({ ...base, prompt: "x".repeat(200) }); + const emoji = resolveSubagentRowPresentation({ + ...base, + prompt: `${"x".repeat(76)}😀 and more`, + }); const titled = resolveSubagentRowPresentation({ ...base, title: "Subagent: /root/my_worker" }); expect(long.title).toHaveLength(80); expect(long.title.endsWith("...")).toBe(true); + expect(emoji.title).toBe(`${"x".repeat(76)}...`); expect(titled.title).toBe("My Worker"); }); diff --git a/apps/mobile/src/features/threads/threadAgentsPresentation.ts b/apps/mobile/src/features/threads/threadAgentsPresentation.ts index 270cc1f3d7fbe..a5af5b0e6c5ed 100644 --- a/apps/mobile/src/features/threads/threadAgentsPresentation.ts +++ b/apps/mobile/src/features/threads/threadAgentsPresentation.ts @@ -7,6 +7,7 @@ import { } from "@t3tools/client-runtime/state/subagent-display"; import { isActiveSubagentStatus, + promptTitle, type RuntimeSubagent, type SubagentWorkflowGroup, } from "@t3tools/client-runtime/state/subagentRuntime"; @@ -22,8 +23,6 @@ import { msg } from "gt-react-native"; import { m, type MessageResolver } from "../../i18n/messages"; -const PROMPT_TITLE_LIMIT = 80; - export type SubagentRowTone = "working" | "completed" | "failed" | "stopped"; export interface SubagentRowPresentation { @@ -82,9 +81,7 @@ function rowTitle( if (title) return formatSubagentDisplayTitle(title); const prompt = subagent.prompt.trim(); if (prompt.length === 0) return resolve(msg("Subagent")); - return prompt.length > PROMPT_TITLE_LIMIT - ? `${prompt.slice(0, PROMPT_TITLE_LIMIT - 3)}...` - : prompt; + return promptTitle(prompt); } function rowTone(status: OrchestrationV2Subagent["status"]): SubagentRowTone { diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index 29f6e97b047b4..36f1005791401 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -1199,11 +1199,12 @@ describe("thread drag destinations", () => { assignments, }); expect(pending.orderedIds).toEqual([ids[3], ids[0], ids[1], ids[2]]); + const field = section === "pinned" ? "pinOrderKey" : "activeOrderKey"; const confirmed = ordered.map((row) => ({ ...row, - [section === "pinned" ? "pinOrderKey" : "activeOrderKey"]: assignments.find( - (a) => a.id === `${row.environmentId}:${row.id}`, - )!.orderKey, + [field]: + assignments.find((a) => a.id === `${row.environmentId}:${row.id}`)?.orderKey ?? + row[field], })); expect( getThreadListV2OrderedSection({ threads: confirmed, section, now: NOW }).map( @@ -1216,7 +1217,7 @@ describe("thread drag destinations", () => { }, ); - it("refuses a drop that would need to rewrite an old server's keyless row", () => { + it("moves past an old server's keyless row by writing only the moved row", () => { const old = EnvironmentId.make("old-server"); const ordered = [environmentId, old, environmentId].map((env, index) => makeThread({ @@ -1231,11 +1232,11 @@ describe("thread drag destinations", () => { section: "active", reorderableEnvironmentIds: new Set([environmentId]), })(`${environmentId}:2`, { targetId: `${environmentId}:0`, placement: "before" }), - ).toBeNull(); + ).toEqual([{ id: `${environmentId}:2`, orderKey: expect.any(String) }]); }); }); -it("allows a long drop past an old server even when both adjacent moves fail", () => { +it("moves past an old server one step or in a long drop", () => { const old = EnvironmentId.make("old-server"); const ordered = [ makeThread({ id: ThreadId.make("a"), title: "a" }), @@ -1250,7 +1251,7 @@ it("allows a long drop past an old server even when both adjacent moves fail", ( }); const movedId = `${environmentId}:a`; expect(planner(movedId, "up")).toBeNull(); - expect(planner(movedId, "down")).toBeNull(); + expect(planner(movedId, "down")?.map(({ id }) => id)).toEqual([movedId]); const assignments = planner(movedId, { targetId: `${environmentId}:d`, placement: "after" }); expect(assignments).toHaveLength(1); expect(assignments![0]!.id).toBe(movedId); diff --git a/apps/mobile/src/features/threads/threadOrder.ts b/apps/mobile/src/features/threads/threadOrder.ts index f7654e910f3dd..ed5f87ef8ab90 100644 --- a/apps/mobile/src/features/threads/threadOrder.ts +++ b/apps/mobile/src/features/threads/threadOrder.ts @@ -1,5 +1,6 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { + activeThreadSortKey, generateSpreadPinOrderKeys, pinOrderKeyBetween, planPinnedReorder, @@ -72,9 +73,13 @@ function rowId(row: OrderRow): string { return `${row.environmentId}:${row.id}`; } +function storedKey(row: OrderRow, section: PendingThreadOrder["section"]) { + return (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null; +} + function rowOrder(row: OrderRow, section: PendingThreadOrder["section"]) { return { - key: (section === "pinned" ? row.pinOrderKey : row.activeOrderKey) ?? null, + key: section === "pinned" ? storedKey(row, section) : activeThreadSortKey(row), anchor: section === "pinned" ? (row.pinnedAt ?? "") : (row.unsettledAt ?? row.createdAt), }; } @@ -86,12 +91,13 @@ export function createThreadMovePlanner(input: { readonly reorderableEnvironmentIds: ReadonlySet; }) { const orderedIds = input.ordered.map(rowId); - const keysById = new Map( - (input.allThreads ?? input.ordered).map((row) => [ - rowId(row), - rowOrder(row, input.section).key, - ]), - ); + // Hidden rows keep their stored key: only stored keys can collide with a write. + const keysById = new Map([ + ...(input.allThreads ?? input.ordered).map( + (row) => [rowId(row), storedKey(row, input.section)] as const, + ), + ...input.ordered.map((row) => [rowId(row), rowOrder(row, input.section).key] as const), + ]); const writableIds = new Set( (input.allThreads ?? input.ordered) .filter((row) => input.reorderableEnvironmentIds.has(row.environmentId)) @@ -141,9 +147,10 @@ export function computeThreadMoveAvailability(input: { const writableIds = new Set(); for (const row of input.allThreads ?? input.ordered) { const id = rowId(row); - keysById.set(id, rowOrder(row, input.section).key); + keysById.set(id, storedKey(row, input.section)); if (input.reorderableEnvironmentIds.has(row.environmentId)) writableIds.add(id); } + for (const row of rows) keysById.set(rowId(row), rowOrder(row, input.section).key); const reservedKeys = new Set(); keysById.forEach((key, id) => { if (key != null && !indexById.has(id)) reservedKeys.add(key); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 1116dd8895c6e..d97b521b536fa 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} hat auf keiner gespeicherten Route geantwortet.", "b0dd3cd876937ca8": "Verbindungsprofil {connectionId} ist nicht verfügbar.", "5ce46783e79ca9d1": "Zugangsdaten der Verbindung {connectionId} sind nicht verfügbar.", - "0bda0cac7f5acc20": "Die verbundene Umgebung {actual} stimmt nicht mit {expected} überein.", + "b39d1428ec8b23f5": "Unter dieser Adresse läuft jetzt eine andere T3 Code-Installation ({actual}, nicht {expected}). Entferne diese Verbindung und füge sie erneut hinzu.", "ea0d3e4e51d5706f": "Die Zugangsdaten der Umgebung sind ungültig.", "7283ebfd16d09677": "Die Zugangsdaten der Umgebung gewähren nicht den erforderlichen Zugriff.", "d3e9a9cb543b4b7b": "Die Umgebung hat die Authentifizierungsanfrage abgelehnt.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", "fedaa29ff8815a77": "{provider}-Hooks werden geladen", "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "1cbfbcad9f0d04fe": "{provider}-Sitzung wird fortgesetzt", "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", "f1d27d127ab27ac6": "Wird gestartet", @@ -1512,7 +1513,7 @@ "88b831780dfddb26": "Dieser Entwurf hat zu viel Kontext zum Senden. Entferne einige Kontextelemente und versuch es erneut.", "0df5fa81eb1674de": "Diese Kontextauswahl ist zu groß zum Kopieren. Wähle weniger Elemente aus.", "d80f9b03a38cc473": "Entferne einige Kontextelemente aus dem Entwurf, bevor du weitere einfügst.", - "62cb87ddfea69267": "Anhangslimit erreicht", + "62cb87ddfea69267": "Anhanglimit erreicht", "17daf9945d4378c7": "Erneut mit der Quellumgebung verbinden", "02c1fea7edd167cc": "Anhang-URL nicht verfügbar", "433237d7492c5401": "Die Zwischenablage ist leer.", @@ -1526,8 +1527,8 @@ "cb7049baa8fdacc4": "Videoanhänge sind hier nicht verfügbar.", "6c5e9cc01a8fd18f": "Nicht unterstützter Dateityp für ''{name}''.", "a8c3d59b323e4d6b": "''{name}'' konnte nicht gelesen werden.", - "1dc797c5c01c5d70": "''{name}'' überschreitet das Anhangslimit von 10 MB.", - "e4991173a9124f38": "Ein eingefügtes Bild überschreitet das Anhangslimit von 10 MB.", + "1dc797c5c01c5d70": "''{name}'' überschreitet das Anhanglimit von 10 MB.", + "e4991173a9124f38": "Ein eingefügtes Bild überschreitet das Anhanglimit von 10 MB.", "218c111b4aa6e029": "Ein eingefügtes Bild konnte nicht gelesen werden.", "ce88bed3d928cf6b": "Dieser Anhang ist nicht mehr verfügbar. Hänge die Datei erneut an.", "232298a82d027b3d": "Details", @@ -1889,7 +1890,7 @@ "6bf09d4b7e4ba53b": "T3 Code auf {environment} aktualisieren", "663465f828e70345": "Keine Verbindung zu {environment}", "d14ca43d8ae95c78": "{host} nicht erreichbar", - "b42f0ff267623384": "Auf {environment} läuft eine T3 Code-Version, die ihre localhost-Seiten nicht auf diesem Gerät öffnen kann. Aktualisiere sie dort und versuche es dann erneut.", + "b42f0ff267623384": "Auf {environment} läuft eine T3-Code-Version, die ihre localhost-Seiten nicht auf diesem Gerät öffnen kann. Aktualisiere sie dort und versuche es dann erneut.", "69e9c247d0266e9f": "Seiten auf dem localhost von {environment} laden über dessen Verbindung. Versuche es erneut, sobald die Verbindung wieder steht.", "301045c720839f4d": "Auf {environment} lauscht nichts auf Port {port}. Starte dort den Server und versuche es dann erneut.", "0b16434dff468d30": "Der Upload wurde abgelehnt.", @@ -3095,7 +3096,7 @@ "7b4c64fffd3019e3": "{term, select, mr {Merge Request schließen} cr {Änderungsanfrage schließen} other {Pull Request schließen}}", "c946b24a4da6aa7a": "{term, select, mr {Merge Request wieder öffnen} cr {Änderungsanfrage wieder öffnen} other {Pull Request wieder öffnen}}", "37948395ebd6d50d": "Branch aktualisieren", - "4812cf02a34c9a05": "{term, select, mr {Revert-Merge Request erstellen} cr {Revert-Änderungsanfrage erstellen} other {Revert-Pull Request erstellen}}", + "4812cf02a34c9a05": "{term, select, mr {Revert-Merge-Request erstellen} cr {Revert-Änderungsanfrage erstellen} other {Revert-Pull-Request erstellen}}", "e91d7bcfc952ecdc": "Branch löschen", "80cde74d5241204f": "{term, select, mr {Dieser Merge Request wurde gemergt.} cr {Diese Änderungsanfrage wurde gemergt.} other {Dieser Pull Request wurde gemergt.}}", "c62311139918f880": "{term, select, mr {Öffne diesen Merge Request vor dem Mergen wieder.} cr {Öffne diese Änderungsanfrage vor dem Mergen wieder.} other {Öffne diesen Pull Request vor dem Mergen wieder.}}", @@ -4651,10 +4652,6 @@ "ccde552cdff4a9e5": "Doppeltippen, um den Prompt anzuzeigen.", "630df4f8b78ab8d3": "Arbeitet seit {duration}", "01deb1ae9f51d3e0": "Arbeit konnte nicht geladen werden. Tippe, um es erneut zu versuchen.", - "868ed4fea1a3273c": "{count} Repos", - "c887abfd190d8b40": "diesem Ordner", - "275b5fe6040f2c1c": "{files, plural, one {{files} geänderte Datei prüfen, {additions} Hinzufügungen, {deletions} Löschungen} other {{files} geänderte Dateien prüfen, {additions} Hinzufügungen, {deletions} Löschungen}}", - "c4a35456c7bdc3a1": "{files, plural, one {{files} geänderte Datei in {folders} prüfen, {additions} Hinzufügungen, {deletions} Löschungen} other {{files} geänderte Dateien in {folders} prüfen, {additions} Hinzufügungen, {deletions} Löschungen}}", "7a13ae3b70a050fb": "{label} (nicht verfügbar)", "8f033834a0194c33": "Kontext nicht verfügbar", "4031ea1541b3ec2b": "Kontext öffnen", @@ -4856,7 +4853,7 @@ "6b2294cfd43aee15": "{name} (Gast)", "93ac0c76ae6a2a3b": "Die geteilten Inhalte sind nicht mehr im Posteingang.", "72e35523181b36eb": "Die Anhangsunterstützung des Servers wird noch geladen.", - "100ddd593ab0b485": "{count, plural, one {{count} geteilte Datei wurde übersprungen, weil dieser Entwurf das Anhangslimit erreicht hat.} other {{count} geteilte Dateien wurden übersprungen, weil dieser Entwurf das Anhangslimit erreicht hat.}}", + "100ddd593ab0b485": "{count, plural, one {{count} geteilte Datei wurde übersprungen, weil dieser Entwurf das Anhanglimit erreicht hat.} other {{count} geteilte Dateien wurden übersprungen, weil dieser Entwurf das Anhanglimit erreicht hat.}}", "a9d0457b171de12d": "Aktueller Worktree", "731c754897f77b89": "{term, select, mr {Aus MR #{number}} cr {Aus Änderungsanfrage #{number}} other {Aus PR #{number}}}", "3a05fec4b1d0f0a0": "Branch wählen", @@ -5006,10 +5003,10 @@ "2a6969164260cdee": "Pull Requests sind für dieses Projekt nicht verfügbar.", "a0ce478324829283": "{term, select, mr {Dieser Merge Request konnte nicht verknüpft werden} cr {Diese Änderungsanfrage konnte nicht verknüpft werden} other {Dieser Pull Request konnte nicht verknüpft werden}}", "962d13f9565f189b": "{term, select, mr {Die Verknüpfung dieses Merge Requests konnte nicht aufgehoben werden} cr {Die Verknüpfung dieser Änderungsanfrage konnte nicht aufgehoben werden} other {Die Verknüpfung dieses Pull Requests konnte nicht aufgehoben werden}}", - "0f9053e44ef763ec": "{term, select, mr {Füge eine Merge Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} cr {Füge eine Änderungsanfrage-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} other {Füge eine Pull Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.}}", - "e8c0bb0c1d4f43fe": "{term, select, mr {Merge Request-URL oder #42} cr {Änderungsanfrage-URL oder #42} other {Pull Request-URL oder #42}}", + "0f9053e44ef763ec": "{term, select, mr {Füge eine Merge-Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} cr {Füge eine Änderungsanfrage-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.} other {Füge eine Pull-Request-URL ein oder gib 123 / #123 für das Repository dieses Threads ein.}}", + "e8c0bb0c1d4f43fe": "{term, select, mr {Merge-Request-URL oder #42} cr {Änderungsanfrage-URL oder #42} other {Pull-Request-URL oder #42}}", "1ed642782ae61c57": "Verknüpfen", - "be61723be45aacfd": "{term, select, mr {Verwende eine Merge Request-URL, 123 oder #123.} cr {Verwende eine Änderungsanfrage-URL, 123 oder #123.} other {Verwende eine Pull Request-URL, 123 oder #123.}}", + "be61723be45aacfd": "{term, select, mr {Verwende eine Merge-Request-URL, 123 oder #123.} cr {Verwende eine Änderungsanfrage-URL, 123 oder #123.} other {Verwende eine Pull-Request-URL, 123 oder #123.}}", "ed09d936d8ba9792": "Beobachtung beenden", "af6adbd67cef13b1": "Auf Änderungen beobachten", "13eb3e529a3e9bff": "Aus dem Thread entfernen", @@ -5618,5 +5615,6 @@ "856812e7e1fc445e": "Tool-Aufrufe im Chat", "8d545d54c0a9e950": "Die Befehle, Bearbeitungen und Suchen ausblenden, die Agenten ausführen. „Erfolgreiche ausblenden“ behält Fehler. „Zen“ zeigt nur endgültige Antworten. Genehmigungen, Fragen und Fehler werden immer angezeigt.", "99d51127f573296b": "Weiteres Konto", - "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer." + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "892f08d21b8e48a9": "{layers} per {kind, select, squash {Squash} merge {Merge} rebase {Rebase} fastForward {Fast-Forward} other {{method}}} in {base} mergen, sobald die Anforderungen erfüllt sind. Das kann sofort passieren." } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index d9c7d08df765b..840b055813d48 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} did not answer on any saved route.", "b0dd3cd876937ca8": "Connection profile {connectionId} is unavailable.", "5ce46783e79ca9d1": "Connection credential {connectionId} is unavailable.", - "0bda0cac7f5acc20": "Connected environment {actual} does not match {expected}.", + "b39d1428ec8b23f5": "This address now runs a different T3 Code install ({actual}, not {expected}). Remove this connection and add it again.", "ea0d3e4e51d5706f": "The environment credential is invalid.", "7283ebfd16d09677": "The environment credential does not grant the required access.", "d3e9a9cb543b4b7b": "The environment rejected the authentication request.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "Starting {provider} MCP servers", "fedaa29ff8815a77": "Loading {provider} hooks", "57025ae4de5beb57": "Loading {provider} rules and skills", + "1cbfbcad9f0d04fe": "Resuming {provider} session", "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", "f1d27d127ab27ac6": "Starting", @@ -4653,10 +4654,6 @@ "ccde552cdff4a9e5": "Double tap to show the prompt.", "630df4f8b78ab8d3": "Working for {duration}", "01deb1ae9f51d3e0": "Couldn't load work. Tap to retry.", - "868ed4fea1a3273c": "{count} repos", - "c887abfd190d8b40": "this folder", - "275b5fe6040f2c1c": "{files, plural, one {Review {files} file changed, {additions} additions, {deletions} deletions} other {Review {files} files changed, {additions} additions, {deletions} deletions}}", - "c4a35456c7bdc3a1": "{files, plural, one {Review {files} file changed in {folders}, {additions} additions, {deletions} deletions} other {Review {files} files changed in {folders}, {additions} additions, {deletions} deletions}}", "7a13ae3b70a050fb": "{label} (unavailable)", "8f033834a0194c33": "Context unavailable", "4031ea1541b3ec2b": "Open context", @@ -5620,5 +5617,6 @@ "856812e7e1fc445e": "Tool calls in chat", "8d545d54c0a9e950": "Hide the commands, edits, and searches agents run. Hide successful keeps failures. Zen shows only final answers. Approvals, questions, and errors always show.", "99d51127f573296b": "Another account", - "8ec2c57414669b79": "Connect a second {tracker} workspace or user." + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "892f08d21b8e48a9": "Merge {layers} into {base} using {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} once their requirements are met. This may happen immediately." } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 8ceac2b26a722..4f315bafcfa0c 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} no respondió en ninguna de las rutas guardadas.", "b0dd3cd876937ca8": "El perfil de conexión {connectionId} no está disponible.", "5ce46783e79ca9d1": "La credencial de conexión {connectionId} no está disponible.", - "0bda0cac7f5acc20": "El entorno conectado {actual} no coincide con {expected}.", + "b39d1428ec8b23f5": "Esta dirección ahora ejecuta otra instalación de T3 Code ({actual}, no {expected}). Elimina esta conexión y vuelve a añadirla.", "ea0d3e4e51d5706f": "La credencial del entorno no es válida.", "7283ebfd16d09677": "La credencial del entorno no concede el acceso necesario.", "d3e9a9cb543b4b7b": "El entorno rechazó la solicitud de autenticación.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", "fedaa29ff8815a77": "Cargando hooks de {provider}", "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "1cbfbcad9f0d04fe": "Reanudando la sesión de {provider}", "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", "f1d27d127ab27ac6": "Iniciando", @@ -4644,10 +4645,6 @@ "ccde552cdff4a9e5": "Toca dos veces para mostrar el prompt.", "630df4f8b78ab8d3": "Trabajando durante {duration}", "01deb1ae9f51d3e0": "No se pudo cargar el trabajo. Toca para reintentar.", - "868ed4fea1a3273c": "{count} repos", - "c887abfd190d8b40": "esta carpeta", - "275b5fe6040f2c1c": "{files, plural, one {Revisar {files} archivo modificado, {additions} adiciones, {deletions} eliminaciones} other {Revisar {files} archivos modificados, {additions} adiciones, {deletions} eliminaciones}}", - "c4a35456c7bdc3a1": "{files, plural, one {Revisar {files} archivo modificado en {folders}, {additions} adiciones, {deletions} eliminaciones} other {Revisar {files} archivos modificados en {folders}, {additions} adiciones, {deletions} eliminaciones}}", "7a13ae3b70a050fb": "{label} (no disponible)", "8f033834a0194c33": "Contexto no disponible", "4031ea1541b3ec2b": "Abrir contexto", @@ -5612,5 +5609,6 @@ "856812e7e1fc445e": "Llamadas a herramientas en el chat", "8d545d54c0a9e950": "Oculta los comandos, ediciones y búsquedas que ejecutan los agentes. Ocultar las correctas mantiene los fallos. Zen solo muestra las respuestas finales. Las aprobaciones, preguntas y errores siempre se muestran.", "99d51127f573296b": "Otra cuenta", - "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}." + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "892f08d21b8e48a9": "Fusionar {layers} en {base} con {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} cuando se cumplan sus requisitos. Puede ocurrir de inmediato." } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index a6904b69d7f73..c9258e0220c62 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} n’a répondu sur aucune route enregistrée.", "b0dd3cd876937ca8": "Le profil de connexion {connectionId} n’est pas disponible.", "5ce46783e79ca9d1": "Les identifiants de connexion {connectionId} ne sont pas disponibles.", - "0bda0cac7f5acc20": "L’environnement connecté {actual} ne correspond pas à {expected}.", + "b39d1428ec8b23f5": "Cette adresse exécute désormais une autre installation de T3 Code ({actual}, et non {expected}). Supprimez cette connexion et ajoutez-la à nouveau.", "ea0d3e4e51d5706f": "Les identifiants de l’environnement ne sont pas valides.", "7283ebfd16d09677": "Les identifiants de l’environnement n’accordent pas l’accès requis.", "d3e9a9cb543b4b7b": "L’environnement a rejeté la demande d’authentification.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", "fedaa29ff8815a77": "Chargement des hooks de {provider}", "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "1cbfbcad9f0d04fe": "Reprise de la session de {provider}", "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", "f1d27d127ab27ac6": "Démarrage", @@ -4645,10 +4646,6 @@ "ccde552cdff4a9e5": "Touchez deux fois pour afficher le prompt.", "630df4f8b78ab8d3": "Au travail depuis {duration}", "01deb1ae9f51d3e0": "Impossible de charger le travail. Touchez pour réessayer.", - "868ed4fea1a3273c": "{count} dépôts", - "c887abfd190d8b40": "ce dossier", - "275b5fe6040f2c1c": "{files, plural, one {Relire {files} fichier modifié, {additions} ajouts, {deletions} suppressions} other {Relire {files} fichiers modifiés, {additions} ajouts, {deletions} suppressions}}", - "c4a35456c7bdc3a1": "{files, plural, one {Relire {files} fichier modifié dans {folders}, {additions} ajouts, {deletions} suppressions} other {Relire {files} fichiers modifiés dans {folders}, {additions} ajouts, {deletions} suppressions}}", "7a13ae3b70a050fb": "{label} (indisponible)", "8f033834a0194c33": "Contexte indisponible", "4031ea1541b3ec2b": "Ouvrir le contexte", @@ -5612,5 +5609,6 @@ "856812e7e1fc445e": "Appels d’outils dans la discussion", "8d545d54c0a9e950": "Masque les commandes, modifications et recherches lancées par les agents. Masquer les réussis garde les échecs. Zen n’affiche que les réponses finales. Les approbations, questions et erreurs s’affichent toujours.", "99d51127f573296b": "Autre compte", - "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}." + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "892f08d21b8e48a9": "Fusionner {layers} dans {base} avec {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} dès que leurs conditions sont remplies. Cela peut se produire immédiatement." } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 3ce3515fae73b..f0707be16a61a 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} は保存されたどのルートでも応答しませんでした。", "b0dd3cd876937ca8": "接続プロファイル {connectionId} は利用できません。", "5ce46783e79ca9d1": "接続の資格情報 {connectionId} は利用できません。", - "0bda0cac7f5acc20": "接続した環境 {actual} が {expected} と一致しません。", + "b39d1428ec8b23f5": "このアドレスでは別の T3 Code が動作しています({expected} ではなく {actual})。この接続を削除して、もう一度追加してください。", "ea0d3e4e51d5706f": "環境の資格情報が無効です。", "7283ebfd16d09677": "環境の資格情報に必要なアクセス権がありません。", "d3e9a9cb543b4b7b": "環境が認証リクエストを拒否しました。", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", "fedaa29ff8815a77": "{provider} のフックを読み込み中", "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "1cbfbcad9f0d04fe": "{provider} のセッションを再開中", "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", "f1d27d127ab27ac6": "起動中", @@ -4625,10 +4626,6 @@ "ccde552cdff4a9e5": "ダブルタップでプロンプトを表示します。", "630df4f8b78ab8d3": "{duration} 作業中", "01deb1ae9f51d3e0": "作業を読み込めませんでした。タップして再試行してください。", - "868ed4fea1a3273c": "{count} 件のリポジトリ", - "c887abfd190d8b40": "このフォルダー", - "275b5fe6040f2c1c": "{files, plural, other {{files} 個の変更ファイルをレビュー、{additions} 行追加、{deletions} 行削除}}", - "c4a35456c7bdc3a1": "{files, plural, other {{folders} の {files} 個の変更ファイルをレビュー、{additions} 行追加、{deletions} 行削除}}", "7a13ae3b70a050fb": "{label} (利用不可)", "8f033834a0194c33": "コンテキストを利用できません", "4031ea1541b3ec2b": "コンテキストを開く", @@ -5592,5 +5589,6 @@ "856812e7e1fc445e": "チャット内のツール呼び出し", "8d545d54c0a9e950": "エージェントが実行するコマンド、編集、検索を非表示にします。「成功したものを非表示」では失敗は表示されます。Zen では最終的な回答だけを表示します。承認、質問、エラーは常に表示されます。", "99d51127f573296b": "別のアカウント", - "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。" + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "892f08d21b8e48a9": "要件が満たされたら、{layers} を{kind, select, squash {スカッシュ} merge {マージ} rebase {リベース} fastForward {早送り} other {{method}}}で {base} にマージします。すぐにマージされる場合があります。" } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 484ab67231b2e..d90f0d02dd0bb 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host}이(가) 저장된 경로 중 어디에서도 응답하지 않았습니다.", "b0dd3cd876937ca8": "연결 프로필 {connectionId}을(를) 사용할 수 없습니다.", "5ce46783e79ca9d1": "연결 자격 증명 {connectionId}을(를) 사용할 수 없습니다.", - "0bda0cac7f5acc20": "연결된 환경 {actual}이(가) {expected}과(와) 일치하지 않습니다.", + "b39d1428ec8b23f5": "이 주소에서 이제 다른 T3 Code 설치가 실행 중입니다({expected}이(가) 아닌 {actual}). 이 연결을 삭제한 후 다시 추가하세요.", "ea0d3e4e51d5706f": "환경 자격 증명이 올바르지 않습니다.", "7283ebfd16d09677": "환경 자격 증명에 필요한 액세스 권한이 없습니다.", "d3e9a9cb543b4b7b": "환경에서 인증 요청을 거부했습니다.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "{provider} MCP 서버 시작 중", "fedaa29ff8815a77": "{provider} 훅 불러오는 중", "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "1cbfbcad9f0d04fe": "{provider} 세션 재개 중", "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", "f1d27d127ab27ac6": "시작 중", @@ -4630,10 +4631,6 @@ "ccde552cdff4a9e5": "두 번 탭하여 프롬프트를 표시합니다.", "630df4f8b78ab8d3": "{duration} 동안 작업 중", "01deb1ae9f51d3e0": "작업을 불러올 수 없습니다. 탭하여 다시 시도하세요.", - "868ed4fea1a3273c": "저장소 {count}개", - "c887abfd190d8b40": "이 폴더", - "275b5fe6040f2c1c": "{files, plural, other {변경된 파일 {files}개 검토, 추가 {additions}줄, 삭제 {deletions}줄}}", - "c4a35456c7bdc3a1": "{files, plural, other {{folders}에서 변경된 파일 {files}개 검토, 추가 {additions}줄, 삭제 {deletions}줄}}", "7a13ae3b70a050fb": "{label}(사용할 수 없음)", "8f033834a0194c33": "컨텍스트를 사용할 수 없음", "4031ea1541b3ec2b": "컨텍스트 열기", @@ -5598,5 +5595,6 @@ "856812e7e1fc445e": "채팅의 도구 호출", "8d545d54c0a9e950": "에이전트가 실행하는 명령, 편집, 검색을 숨깁니다. 성공한 항목 숨기기는 실패를 남겨 둡니다. Zen은 최종 답변만 표시합니다. 승인, 질문, 오류는 항상 표시됩니다.", "99d51127f573296b": "다른 계정", - "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다." + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "892f08d21b8e48a9": "요구 사항이 충족되면 {layers}을(를) {kind, select, squash {스쿼시} merge {병합} rebase {리베이스} fastForward {빨리 감기} other {{method}}} 방식으로 {base}에 병합합니다. 바로 병합될 수도 있습니다." } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 4959be9c365b1..bc9eee45bdcb3 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} não respondeu em nenhuma rota salva.", "b0dd3cd876937ca8": "O perfil de conexão {connectionId} não está disponível.", "5ce46783e79ca9d1": "A credencial de conexão {connectionId} não está disponível.", - "0bda0cac7f5acc20": "O ambiente conectado {actual} não corresponde a {expected}.", + "b39d1428ec8b23f5": "Este endereço agora executa outra instalação do T3 Code ({actual}, não {expected}). Remova esta conexão e adicione-a novamente.", "ea0d3e4e51d5706f": "A credencial do ambiente é inválida.", "7283ebfd16d09677": "A credencial do ambiente não concede o acesso necessário.", "d3e9a9cb543b4b7b": "O ambiente rejeitou a solicitação de autenticação.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", "fedaa29ff8815a77": "Carregando hooks do {provider}", "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "1cbfbcad9f0d04fe": "Retomando a sessão do {provider}", "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", "f1d27d127ab27ac6": "Iniciando", @@ -4645,10 +4646,6 @@ "ccde552cdff4a9e5": "Toque duas vezes para mostrar o prompt.", "630df4f8b78ab8d3": "Trabalhando há {duration}", "01deb1ae9f51d3e0": "Não foi possível carregar o trabalho. Toque para tentar novamente.", - "868ed4fea1a3273c": "{count} repos", - "c887abfd190d8b40": "esta pasta", - "275b5fe6040f2c1c": "{files, plural, one {Revisar {files} arquivo alterado, {additions} adições, {deletions} exclusões} other {Revisar {files} arquivos alterados, {additions} adições, {deletions} exclusões}}", - "c4a35456c7bdc3a1": "{files, plural, one {Revisar {files} arquivo alterado em {folders}, {additions} adições, {deletions} exclusões} other {Revisar {files} arquivos alterados em {folders}, {additions} adições, {deletions} exclusões}}", "7a13ae3b70a050fb": "{label} (indisponível)", "8f033834a0194c33": "Contexto indisponível", "4031ea1541b3ec2b": "Abrir contexto", @@ -5612,5 +5609,6 @@ "856812e7e1fc445e": "Chamadas de ferramentas no chat", "8d545d54c0a9e950": "Oculta os comandos, edições e pesquisas que os agentes executam. \"Ocultar bem-sucedidas\" mantém as falhas. Zen mostra só as respostas finais. Aprovações, perguntas e erros sempre aparecem.", "99d51127f573296b": "Outra conta", - "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}." + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "892f08d21b8e48a9": "Mesclar {layers} em {base} usando {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} quando os requisitos forem atendidos. Isso pode acontecer imediatamente." } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 7987d3d16485a..9decfe25c2132 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} не ответил ни по одному сохранённому маршруту.", "b0dd3cd876937ca8": "Профиль подключения {connectionId} недоступен.", "5ce46783e79ca9d1": "Учётные данные подключения {connectionId} недоступны.", - "0bda0cac7f5acc20": "Подключённое окружение {actual} не совпадает с {expected}.", + "b39d1428ec8b23f5": "По этому адресу теперь работает другая установка T3 Code ({actual}, а не {expected}). Удалите это подключение и добавьте его снова.", "ea0d3e4e51d5706f": "Учётные данные окружения недействительны.", "7283ebfd16d09677": "Учётные данные окружения не дают нужного доступа.", "d3e9a9cb543b4b7b": "Окружение отклонило запрос аутентификации.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "Запуск MCP-серверов {provider}", "fedaa29ff8815a77": "Загрузка хуков {provider}", "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "1cbfbcad9f0d04fe": "Возобновление сессии {provider}", "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", "f1d27d127ab27ac6": "Запуск", @@ -4723,10 +4724,6 @@ "ccde552cdff4a9e5": "Дважды нажмите, чтобы показать промпт.", "630df4f8b78ab8d3": "Работает {duration}", "01deb1ae9f51d3e0": "Не удалось загрузить работу. Нажмите, чтобы повторить.", - "868ed4fea1a3273c": "Репозиториев: {count}", - "c887abfd190d8b40": "эта папка", - "275b5fe6040f2c1c": "{files, plural, one {Ревью: изменён {files} файл, добавлений: {additions}, удалений: {deletions}} few {Ревью: изменено {files} файла, добавлений: {additions}, удалений: {deletions}} many {Ревью: изменено {files} файлов, добавлений: {additions}, удалений: {deletions}} other {Ревью: изменено {files} файла, добавлений: {additions}, удалений: {deletions}}}", - "c4a35456c7bdc3a1": "{files, plural, one {Ревью: изменён {files} файл в: {folders}, добавлений: {additions}, удалений: {deletions}} few {Ревью: изменено {files} файла в: {folders}, добавлений: {additions}, удалений: {deletions}} many {Ревью: изменено {files} файлов в: {folders}, добавлений: {additions}, удалений: {deletions}} other {Ревью: изменено {files} файла в: {folders}, добавлений: {additions}, удалений: {deletions}}}", "7a13ae3b70a050fb": "{label} (недоступно)", "8f033834a0194c33": "Контекст недоступен", "4031ea1541b3ec2b": "Открыть контекст", @@ -5692,5 +5689,6 @@ "856812e7e1fc445e": "Вызовы инструментов в чате", "8d545d54c0a9e950": "Скрывать команды, правки и поиски, которые выполняют агенты. «Скрывать успешные» оставляет ошибки. «Дзен» показывает только итоговые ответы. Запросы подтверждения, вопросы и ошибки показываются всегда.", "99d51127f573296b": "Другой аккаунт", - "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}." + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "892f08d21b8e48a9": "Слить {layers} в {base} методом {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}}, когда будут выполнены требования. Это может произойти сразу." } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 38f2f3c80172c..505ae5682fdba 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} svarade inte på någon sparad rutt.", "b0dd3cd876937ca8": "Anslutningsprofilen {connectionId} är inte tillgänglig.", "5ce46783e79ca9d1": "Autentiseringsuppgiften för anslutningen {connectionId} är inte tillgänglig.", - "0bda0cac7f5acc20": "Den anslutna miljön {actual} matchar inte {expected}.", + "b39d1428ec8b23f5": "Den här adressen kör nu en annan T3 Code-installation ({actual}, inte {expected}). Ta bort anslutningen och lägg till den igen.", "ea0d3e4e51d5706f": "Miljöns autentiseringsuppgift är ogiltig.", "7283ebfd16d09677": "Miljöns autentiseringsuppgift ger inte den åtkomst som krävs.", "d3e9a9cb543b4b7b": "Miljön avvisade autentiseringsbegäran.", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "Startar MCP-servrar för {provider}", "fedaa29ff8815a77": "Läser in hooks för {provider}", "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "1cbfbcad9f0d04fe": "Återupptar sessionen för {provider}", "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", "f1d27d127ab27ac6": "Startar", @@ -4651,10 +4652,6 @@ "ccde552cdff4a9e5": "Dubbeltryck för att visa prompten.", "630df4f8b78ab8d3": "Har arbetat i {duration}", "01deb1ae9f51d3e0": "Kunde inte läsa in arbetet. Tryck för att försöka igen.", - "868ed4fea1a3273c": "{count} repon", - "c887abfd190d8b40": "den här mappen", - "275b5fe6040f2c1c": "{files, plural, one {Granska {files} ändrad fil, {additions} tillägg, {deletions} borttagningar} other {Granska {files} ändrade filer, {additions} tillägg, {deletions} borttagningar}}", - "c4a35456c7bdc3a1": "{files, plural, one {Granska {files} ändrad fil i {folders}, {additions} tillägg, {deletions} borttagningar} other {Granska {files} ändrade filer i {folders}, {additions} tillägg, {deletions} borttagningar}}", "7a13ae3b70a050fb": "{label} (inte tillgänglig)", "8f033834a0194c33": "Kontexten är inte tillgänglig", "4031ea1541b3ec2b": "Öppna kontext", @@ -5618,5 +5615,6 @@ "856812e7e1fc445e": "Verktygsanrop i chatten", "8d545d54c0a9e950": "Dölj kommandon, redigeringar och sökningar som agenter kör. Dölj lyckade behåller misslyckanden. Zen visar bara slutliga svar. Godkännanden, frågor och fel visas alltid.", "99d51127f573296b": "Ett konto till", - "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare." + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "892f08d21b8e48a9": "Merga {layers} in i {base} med {kind, select, squash {squash} merge {merge} rebase {rebase} fastForward {fast-forward} other {{method}}} när kraven är uppfyllda. Det kan ske direkt." } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index e673d0e56ba1b..1388de0add451 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} 在所有已保存的路由上均无响应。", "b0dd3cd876937ca8": "连接配置 {connectionId} 不可用。", "5ce46783e79ca9d1": "连接凭据 {connectionId} 不可用。", - "0bda0cac7f5acc20": "已连接的环境 {actual} 与 {expected} 不一致。", + "b39d1428ec8b23f5": "此地址现在运行的是另一个 T3 Code 安装({actual},而非 {expected})。请移除此连接后重新添加。", "ea0d3e4e51d5706f": "环境凭据无效。", "7283ebfd16d09677": "环境凭据未授予所需的访问权限。", "d3e9a9cb543b4b7b": "环境拒绝了身份验证请求。", @@ -817,6 +817,7 @@ "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", "fedaa29ff8815a77": "正在加载 {provider} 钩子", "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "1cbfbcad9f0d04fe": "正在恢复 {provider} 会话", "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", "f1d27d127ab27ac6": "正在启动", @@ -4634,10 +4635,6 @@ "ccde552cdff4a9e5": "轻点两下以显示提示词。", "630df4f8b78ab8d3": "已工作 {duration}", "01deb1ae9f51d3e0": "无法加载工作内容。轻点以重试。", - "868ed4fea1a3273c": "{count} 个仓库", - "c887abfd190d8b40": "此文件夹", - "275b5fe6040f2c1c": "{files, plural, other {审查 {files} 个已更改的文件,新增 {additions} 行,删除 {deletions} 行}}", - "c4a35456c7bdc3a1": "{files, plural, other {审查 {folders} 中 {files} 个已更改的文件,新增 {additions} 行,删除 {deletions} 行}}", "7a13ae3b70a050fb": "{label}(不可用)", "8f033834a0194c33": "上下文不可用", "4031ea1541b3ec2b": "打开上下文", @@ -5602,5 +5599,6 @@ "856812e7e1fc445e": "聊天中的工具调用", "8d545d54c0a9e950": "隐藏智能体执行的命令、编辑和搜索。“隐藏成功的调用”仍保留失败项;“专注模式”仅显示最终回答。审批、提问和错误始终显示。", "99d51127f573296b": "其他账号", - "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。" + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "892f08d21b8e48a9": "满足要求时使用{kind, select, squash {压缩合并} merge {合并} rebase {变基} fastForward {快进} other {{method}}}方式将 {layers} 合并到 {base}。这可能会立即发生。" } diff --git a/apps/mobile/src/lib/appLinking.test.ts b/apps/mobile/src/lib/appLinking.test.ts index 75db18a2337b8..09db1de62056a 100644 --- a/apps/mobile/src/lib/appLinking.test.ts +++ b/apps/mobile/src/lib/appLinking.test.ts @@ -91,6 +91,16 @@ describe("draft deep links", () => { }); }); + it.each(["/new/draft", "/new/draft/branch"])("drops the checkout a %s link names", (path) => { + const project = { environmentId: "env-1", projectId: "project-1" }; + const linked = { ...project, branch: "other", worktreePath: "/elsewhere" }; + const name = path === "/new/draft" ? "Thread" : "NewTaskBranch"; + expect(restoreDraftLinkState({ routes: [{ name, params: linked }] }, path)?.routes[0]).toEqual({ + name: "Thread", + params: { draft: project }, + }); + }); + it("leaves live-thread and project-selection links unchanged", () => { const state = { routes: [{ name: "Thread", params: { threadId: "thread-1" } }] }; expect(restoreDraftLinkState(state, "/threads/env-1/thread-1")).toBe(state); diff --git a/apps/mobile/src/lib/appLinking.ts b/apps/mobile/src/lib/appLinking.ts index 570c86b36abf4..fc448b4d02ac4 100644 --- a/apps/mobile/src/lib/appLinking.ts +++ b/apps/mobile/src/lib/appLinking.ts @@ -35,7 +35,14 @@ export function restoreDraftLinkState( if (!state || !pathname || !/^new\/draft(?:\/|$)/.test(pathname)) return state; const target = state.routes.at(-1); if (!target) return state; - const draft = target.params ?? {}; + // The draft screen checks out its branch on mount; the checkout comes from the draft, not the link. + const { + branch: _branch, + worktreePath: _worktreePath, + ...draft + } = (target.params ?? {}) as { + readonly [param: string]: unknown; + }; const routes = state.routes.slice(0, -1); routes.push({ name: "Thread", params: { draft } }); if (pathname !== "new/draft") routes.push(target); diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index b44b96fca49b8..c11d00bc9aae0 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -498,13 +498,44 @@ function markdownWithWindowsPathDestinations(markdown: string): string { return applyMarkdownEdits(markdown, edits); } +const isImage = (node: MarkdownNode) => node.type === "image" || node.type === "imageReference"; +const isSpace = (node: MarkdownNode) => + node.type === "break" || (node.type === "text" && node.value.trim() === ""); + +// Native Markdown sizes an image as a block only when it is its paragraph's only child. +function markdownWithImageParagraphs(markdown: string): string { + // Skips the extra parse unless a line ending sits between two images. + if (!/[\])][ \t]*\\?(?:\r\n?|\n)[ \t]*!\[/.test(markdown)) return markdown; + const edits: MarkdownEdit[] = []; + for (const block of parser.parse(markdown).children) { + if ( + block.type !== "paragraph" || + !block.children.every((child) => isImage(child) || isSpace(child)) + ) + continue; + const images = block.children.filter(isImage); + for (const [index, image] of images.slice(1).entries()) { + const start = images[index]!.position?.end.offset; + const end = image.position?.start.offset; + if (start === undefined || end === undefined) continue; + const ending = /\r\n?|\n/.exec(markdown.slice(start, end)); + if (ending) edits.push({ start, end, content: ending[0].repeat(2) }); + } + } + return applyMarkdownEdits(markdown, edits); +} + // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. -export function markdownForNativeParsing(markdown: string): string { +function normalizedMarkdown(markdown: string): string { return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); } +export function markdownForNativeParsing(markdown: string): string { + return markdownWithImageParagraphs(normalizedMarkdown(markdown)); +} + export function parseMarkdownDocument(markdown: string): Root { - return parser.parse(markdownForNativeParsing(markdown)); + return parser.parse(normalizedMarkdown(markdown)); } export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string { diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 64c5d02df3532..6cce7f84b475c 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; import { + markdownForNativeParsing, markdownForNativeRendering, markdownHtmlContent, markdownWithHtml, @@ -303,6 +304,30 @@ describe("file embeds in native thread and file Markdown", () => { } }); + it("gives each image on its own line its own native paragraph", async () => { + const images = + "![before](./before.png)\n![after light](./after-light.png) \\\n![after dark][dark]"; + const source = `Shots:\n\n${images}\n\n![a](./a.svg) ![b](./b.svg)\n![c](./c.svg)\n\nNext\n\n[dark]: ./after-dark.png`; + const paragraphs = ( + await parseMarkdown(markdownForNativeRendering(source, ENRICHED_INLINE_FILE_LINK_REGEX)) + ).children?.map((block) => block.children?.map((child) => child.type).join(" ")); + expect(paragraphs).toEqual([ + "Text", + "Image", + "Image", + "Image", + "Image Text Image", + "Image", + "Text", + ]); + expect(markdownForNativeParsing("![a](./a.png)\r\n![b](./b.png)")).toBe( + "![a](./a.png)\r\n\r\n![b](./b.png)", + ); + expect(markdownForNativeParsing("![a](./a.png)\r![b](./b.png)")).toBe( + "![a](./a.png)\r\r![b](./b.png)", + ); + }); + it("retains standalone audio players and image/video embeds in threads", () => { const source = "![sound](./sound.mp3)\n\n![image](./image.png)\n\n![clip](./clip.mp4)\n\ninline ![photo](./photo.png)"; diff --git a/apps/mobile/src/lib/markdownLinks.test.ts b/apps/mobile/src/lib/markdownLinks.test.ts index 101a064b8e61f..142d084c56dae 100644 --- a/apps/mobile/src/lib/markdownLinks.test.ts +++ b/apps/mobile/src/lib/markdownLinks.test.ts @@ -70,6 +70,13 @@ describe("resolveMarkdownLinkPresentation", () => { }); }); + it("shows CommonJS sources with the JavaScript icon", () => { + expect(resolveMarkdownLinkPresentation("scripts/build.cjs")).toMatchObject({ + kind: "file", + icon: "javascript", + }); + }); + // regression: #8098 open agent file links in the file viewer it("recognizes spaced relative paths", () => { expect(resolveMarkdownLinkPresentation("docs/My%20Folder/checklist.xml")).toMatchObject({ diff --git a/apps/mobile/src/lib/markdownLinks.ts b/apps/mobile/src/lib/markdownLinks.ts index 55030cf03b859..77e5135484220 100644 --- a/apps/mobile/src/lib/markdownLinks.ts +++ b/apps/mobile/src/lib/markdownLinks.ts @@ -150,6 +150,7 @@ const FILE_ICON_BY_EXTENSION: Readonly> = { bz2: "zip", c: "c", cc: "cpp", + cjs: "javascript", cpp: "cpp", cxx: "cpp", css: "css", diff --git a/apps/mobile/src/lib/openExternalUrl.test.ts b/apps/mobile/src/lib/openExternalUrl.test.ts index 1dd1ff7db002b..f14037d99205f 100644 --- a/apps/mobile/src/lib/openExternalUrl.test.ts +++ b/apps/mobile/src/lib/openExternalUrl.test.ts @@ -1,7 +1,7 @@ import { Linking } from "react-native"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import { tryOpenExternalUrl } from "./openExternalUrl"; +import { tryOpenExternalUrl, tryOpenWebLink } from "./openExternalUrl"; vi.mock("react-native", () => ({ Linking: { openURL: vi.fn() }, @@ -34,3 +34,16 @@ describe("tryOpenExternalUrl", () => { expect(diagnostics).not.toContain("43123"); }); }); + +describe("tryOpenWebLink", () => { + it("opens web, mail and phone links only", async () => { + openURL.mockResolvedValue(undefined); + for (const url of ["https://example.com/a", "HTTP://example.com", "mailto:a@example.com"]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(true); + } + for (const url of ["otherapp://open", "intent://x#Intent;end", "/owner/repo", ""]) { + await expect(tryOpenWebLink(url, "pull-request")).resolves.toBe(false); + } + expect(openURL).toHaveBeenCalledTimes(3); + }); +}); diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index 962769b184e33..2821d6bb78f96 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -6,7 +6,6 @@ const ExternalUrlTarget = Schema.Literals([ "markdown-link", "pull-request", "provider-auth", - "html-render", "mcp-app", "secret-request", "external-link", @@ -61,3 +60,14 @@ export async function tryOpenExternalUrl( return false; } } + +/** + * For a link in rendered text, such as a pull request body: opens web, mail and phone links + * only. + */ +export async function tryOpenWebLink( + url: string, + target: ExternalUrlTarget = "external-link", +): Promise { + return /^(?:https?|mailto|tel):/i.test(url) && (await tryOpenExternalUrl(url, target)); +} diff --git a/apps/mobile/src/lib/projectThreadStartTurn.test.ts b/apps/mobile/src/lib/projectThreadStartTurn.test.ts index a4b21fec19448..d01a79e32ac47 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.test.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.test.ts @@ -5,6 +5,7 @@ import { serializeComposerMessageForServer } from "./composerContext"; import { buildProjectThreadStartTurnInput, + deriveThreadTitleFromPrompt, type ProjectThreadStartTurnSpec, } from "./projectThreadStartTurn"; @@ -98,4 +99,10 @@ describe("project thread title", () => { repositories: [{ path: "/workspace/api" }], }); }); + + it("shortens a long prompt without splitting an emoji", () => { + expect(deriveThreadTitleFromPrompt(`${"a".repeat(68)}😀 and the rest of the prompt`)).toBe( + `${"a".repeat(68)}...`, + ); + }); }); diff --git a/apps/mobile/src/lib/projectThreadStartTurn.ts b/apps/mobile/src/lib/projectThreadStartTurn.ts index c7e89d8c6e600..e4b550f6b5cd4 100644 --- a/apps/mobile/src/lib/projectThreadStartTurn.ts +++ b/apps/mobile/src/lib/projectThreadStartTurn.ts @@ -13,6 +13,7 @@ import { deriveThreadTitleSeed, threadTitleTextFromPrompt, } from "@t3tools/client-runtime/operations"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import { msg } from "gt-react-native"; import { m } from "../i18n/messages"; @@ -95,5 +96,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe export function deriveThreadTitleFromPrompt(value: string): string { const title = threadTitleTextFromPrompt(value, m) || m(msg("New thread")); - return title.length <= 72 ? title : `${title.slice(0, 69).trimEnd()}...`; + if (title.length <= 72) return title; + const end = splitsSurrogatePair(title, 69) ? 68 : 69; + return `${title.slice(0, end).trimEnd()}...`; } diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 8d66dfaf5c520..41248bf9c1e88 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1,8 +1,5 @@ import { MessageId, - CheckpointId, - CheckpointRef, - CheckpointScopeId, RuntimeRequestId, NodeId, ProviderInstanceId, @@ -17,9 +14,7 @@ import { type OrchestrationV2ProjectedTurnItem, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; -import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; import { summarizeToolGroup } from "@t3tools/client-runtime/work-log/presentation"; -import { getReviewSectionIdForCheckpoint } from "../features/review/reviewModel"; import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; @@ -568,144 +563,6 @@ describe("buildThreadFeed", () => { }, ); - it.each([false, true])( - "carries a late checkpoint to only the final answer without changing cached messages (cache: %s)", - (cached) => { - const cache = cached ? createThreadFeedCache() : undefined; - const earlier = { - ...assistantMessage(), - id: TurnItemId.make("earlier-item"), - messageId: MessageId.make("earlier-message"), - text: "Working on the files", - }; - const final = assistantMessage("2026-06-20T00:00:04.000Z"); - const rows = [projected(earlier, 0), projected(final, 1)]; - const before = buildThreadFeed(rows, { cache }); - const [summary] = deriveThreadCheckpointSummaries({ - messages: [earlier, final].map((message) => ({ - ...message, - id: message.messageId, - role: "assistant", - createdBy: "agent", - creationSource: "provider", - attachments: [], - createdAt: message.startedAt, - })), - checkpoints: [ - { - id: CheckpointId.make("checkpoint-final"), - threadId, - scopeId: CheckpointScopeId.make("scope"), - runId, - nodeId: NodeId.make("node"), - parentCheckpointId: null, - ordinalWithinScope: 1, - appRunOrdinal: 2, - ref: CheckpointRef.make("checkpoint-ref"), - status: "ready", - capturedAt: final.updatedAt, - files: [ - { path: "src/one.ts", kind: "modified", additions: 10, deletions: 2 }, - { path: "src/two.ts", kind: "added", additions: 5, deletions: 0 }, - ], - }, - ], - }); - expect(summary).toBeDefined(); - if (!summary) return; - const after = buildThreadFeed(rows, { checkpointSummaries: [summary], cache }); - expect(after[0]).toBe(before[0]); - expect(after[1]).toMatchObject({ - type: "message", - message: { id: final.messageId, checkpointSummary: summary }, - }); - expect(before[1]).not.toHaveProperty("message.checkpointSummary"); - expect(getReviewSectionIdForCheckpoint(summary)).toBe("turn:2"); - // A plain folder's own checkpoint is missing every turn; its repositories still changed. - const inRepository = { - ...summary, - status: "missing" as const, - files: [], - repositories: [ - { - scopeId: CheckpointScopeId.make("scope-api"), - name: "api", - repositoryPath: "/work/api", - cwd: "/work/api", - files: summary.files, - baselineMissing: false, - }, - ], - }; - expect(buildThreadFeed(rows, { checkpointSummaries: [inRepository] })[1]).toMatchObject({ - message: { checkpointSummary: inRepository }, - }); - const fallback = deriveThreadFeedPresentation( - [after.at(-1)!], - null, - new Set(), - new Set(), - null, - false, - cache, - ); - expect(fallback.at(-1)).toMatchObject({ message: { checkpointSummary: summary } }); - const workRows = [ - projected(userMessage(), 0), - projected(command(), 1), - projected({ ...command(), id: TurnItemId.make("second-command") }, 2), - projected(final, 3), - ]; - const workBefore = buildThreadFeed(workRows, { cache }); - deriveThreadFeedPresentation(workBefore, null, new Set(), new Set(), null, false, cache); - const workAfter = buildThreadFeed(workRows, { checkpointSummaries: [summary], cache }); - for (const expanded of [new Set(), new Set([runId])]) { - const presented = deriveThreadFeedPresentation( - workAfter, - null, - expanded, - new Set(), - null, - false, - cache, - ); - expect(presented.find((entry) => entry.type === "run-fold")).toMatchObject({ - checkpointSummary: summary, - }); - expect(presented.at(-1)).not.toHaveProperty("message.checkpointSummary"); - } - const active = deriveThreadFeedPresentation( - workAfter, - { - runId, - status: "running", - startedAt: "2026-06-20T00:00:00.000Z", - completedAt: null, - }, - new Set(), - new Set(), - null, - false, - cache, - ); - expect(active.find((entry) => entry.type === "work-toggle")).toMatchObject({ - checkpointSummary: summary, - }); - expect(active.at(-1)).not.toHaveProperty("message.checkpointSummary"); - expect(workBefore.at(-1)).not.toHaveProperty("message.checkpointSummary"); - - for (const checkpoint of [ - { ...summary, files: [] }, - ...(["missing", "error", "stale"] as const).map((status) => ({ ...summary, status })), - { ...summary, runId: RunId.make("another-run") }, - { ...summary, assistantMessageId: MessageId.make("unloaded-message") }, - ]) { - expect(buildThreadFeed(rows, { checkpointSummaries: [checkpoint], cache })).toEqual(before); - } - expect(buildThreadFeed(rows, { cache })).toEqual(before); - }, - ); - it("omits cached tool output and patch bodies from expanded and copied activity", () => { const rawOutput = "RAW_TOOL_OUTPUT"; const items: OrchestrationV2TurnItem[] = [ @@ -1483,6 +1340,73 @@ describe("buildThreadFeed", () => { expect(presented.some((entry) => entry.type === "thinking")).toBe(false); }); + // regression: #40551 a finished status after the children is the parent parking, not new work + it("keeps waiting on running subagents after the parent's finished status", () => { + const child = ( + id: string, + ordinal: number, + status: "running" | "completed", + ): OrchestrationV2TurnItem => ({ + ...base(id, `2026-06-20T00:00:0${ordinal}.000Z`, ordinal), + status, + completedAt: + status === "running" ? null : DateTime.makeUnsafe(`2026-06-20T00:00:0${ordinal}.000Z`), + type: "subagent", + subagentId: NodeId.make(id), + origin: "provider_native", + driver: ProviderDriverKind.make("antigravity"), + providerInstanceId: ProviderInstanceId.make("antigravity"), + childThreadId: null, + prompt: `Read ${id}`, + result: null, + }); + const startedAt = "2026-06-20T00:00:01.000Z"; + const latestRun = { runId, status: "running" as const, startedAt, completedAt: null }; + const present = (tail: ReadonlyArray) => + deriveThreadFeedPresentation( + buildThreadFeed([ + projected(userMessage(), 0), + projected(child("a", 2, "running"), 1), + projected(child("b", 3, "completed"), 2), + projected(child("c", 4, "running"), 3), + ...tail.map((item, index) => projected(item, index + 4)), + ]), + latestRun, + new Set(), + new Set(), + startedAt, + ); + const thinkingLabel = (rows: ReadonlyArray) => { + const row = rows.find((entry) => entry.type === "thinking"); + return row?.type === "thinking" ? row.label : undefined; + }; + expect( + thinkingLabel( + present([ + { + ...assistantMessage("2026-06-20T00:00:05.000Z"), + id: TurnItemId.make("status"), + messageId: MessageId.make("status"), + text: "Subagents launched; waiting for them to report back.", + }, + ]), + ), + ).toBe("Waiting on 2 subagents"); + expect( + thinkingLabel( + present([ + { + ...assistantMessage("2026-06-20T00:00:05.000Z"), + id: TurnItemId.make("foreign"), + messageId: MessageId.make("foreign"), + runId: RunId.make("run-2"), + text: "Earlier answer.", + }, + ]), + ), + ).toBeUndefined(); + }); + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const startedAt = "2026-04-01T00:00:01.000Z"; const run = { runId, status: "running" as const, startedAt, completedAt: null }; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index e180927aa3c90..50e87752574b3 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -4,8 +4,6 @@ import type { } from "@t3tools/client-runtime/state/thread-requests"; import { linkRequestTargetName } from "@t3tools/client-runtime/link-request"; import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; -import { turnHasChanges } from "@t3tools/client-runtime/state/thread-repositories"; import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { isLiveSubagentTurnItem, @@ -157,7 +155,6 @@ export interface ThreadFeedMessage { readonly createdAt: string; readonly updatedAt: string; readonly projectedItem?: OrchestrationV2ProjectedTurnItem; - readonly checkpointSummary?: ThreadCheckpointSummary; } export interface LocalThreadMessage { @@ -213,7 +210,6 @@ type RawThreadFeedEntry = export type ThreadFeedEntry = ThreadFeedEntryContent & { readonly continuesWorkLog?: boolean; - readonly checkpointSummary?: ThreadCheckpointSummary; }; type ThreadFeedEntryContent = @@ -1998,39 +1994,6 @@ export function deriveThreadFeedPresentation( ), ); } - const checkpointByRunId = new Map(); - for (const entry of sourceFeed) { - if (entry.type === "message" && entry.message.checkpointSummary) { - checkpointByRunId.set(entry.message.checkpointSummary.runId, entry.message.checkpointSummary); - } - } - const workRowByRunId = new Map(); - for (let index = tailStart; index < result.length; index += 1) { - const row = result[index]!; - if ( - (row.type === "run-fold" || row.type === "work-toggle") && - row.runId !== null && - checkpointByRunId.has(row.runId) && - (row.type === "run-fold" || !workRowByRunId.has(row.runId)) - ) { - workRowByRunId.set(row.runId, index); - } - } - for (const [runId, index] of workRowByRunId) { - result[index] = { ...result[index]!, checkpointSummary: checkpointByRunId.get(runId)! }; - } - for (let index = tailStart; index < result.length; index += 1) { - const row = result[index]!; - if ( - row.type !== "message" || - !row.message.checkpointSummary || - !workRowByRunId.has(row.message.checkpointSummary.runId) - ) - continue; - const message = { ...row.message }; - delete message.checkpointSummary; - result[index] = { ...row, message }; - } // Reused rows are final: the user message after them never continues a work log. for (let index = tailStart; index < result.length; index += 1) { const row = result[index]!; @@ -2106,6 +2069,15 @@ function runningSubagentsAtRunTail(feed: ReadonlyArray, runId: let running = 0; for (let index = feed.length - 1; index >= 0; index -= 1) { const entry = feed[index]!; + // The run's own finished reply is the parent parking on the children, not new work. + if ( + entry.type === "message" && + entry.message.role === "assistant" && + !entry.message.streaming && + entry.message.runId === runId + ) { + continue; + } if (entry.type !== "activity-group" || entry.runId !== runId) break; const items = entry.activities.map((activity) => activity.projectedItem.item); if (items.some((item) => item.type !== "subagent")) break; @@ -2477,7 +2449,6 @@ interface ThreadFeedBuild { readonly locale: string | undefined; readonly attempts: ReadonlyArray | undefined; readonly nodes: ReadonlyArray | undefined; - readonly checkpointSummaries: ReadonlyArray | undefined; readonly foldedAnswerRunIdByMessageId: ReadonlyMap; readonly delegatedChildrenByRun: ReadonlyMap>; readonly feed: ReadonlyArray; @@ -2504,31 +2475,6 @@ function setsEqual(left: ReadonlySet, right: ReadonlySet): boolean { return true; } -// Summaries are re-derived whenever messages change, including streamed text, -// so a new array often holds the same checkpoints. -function checkpointSummariesEqual( - left: ReadonlyArray | undefined, - right: ReadonlyArray | undefined, -): boolean { - if (left === right) return true; - if (left === undefined || right === undefined || left.length !== right.length) return false; - return left.every((summary, index) => { - const other = right[index]!; - return ( - summary.checkpointId === other.checkpointId && - summary.scopeId === other.scopeId && - summary.runId === other.runId && - summary.checkpointTurnCount === other.checkpointTurnCount && - summary.checkpointRef === other.checkpointRef && - summary.completedAt === other.completedAt && - summary.status === other.status && - summary.files === other.files && - summary.repositories === other.repositories && - summary.assistantMessageId === other.assistantMessageId - ); - }); -} - function mapsEqual(left: ReadonlyMap, right: ReadonlyMap): boolean { if (left.size !== right.size) return false; for (const [key, value] of left) { @@ -2563,7 +2509,6 @@ export function buildThreadFeed( readonly anchoredMessages?: ReadonlyArray; readonly attempts?: ReadonlyArray; readonly nodes?: ReadonlyArray; - readonly checkpointSummaries?: ReadonlyArray; readonly cache?: ThreadFeedCache; readonly resolve?: MessageResolver; /** Keys the caches; text comes from `resolve`. */ @@ -2617,7 +2562,6 @@ export function buildThreadFeed( previous.locale === locale && previous.attempts === options?.attempts && previous.nodes === options?.nodes && - checkpointSummariesEqual(previous.checkpointSummaries, options?.checkpointSummaries) && mapsEqual(previous.foldedAnswerRunIdByMessageId, foldedAnswerRunIdByMessageId) && setMapsEqual(previous.delegatedChildrenByRun, delegatedChildrenByRun) ) { @@ -2813,23 +2757,8 @@ export function buildThreadFeed( if (insertionIndex === -1) entries.push(entry); else entries.splice(insertionIndex, 0, entry); } - const checkpointByMessageId = new Map( - (options?.checkpointSummaries ?? []) - // A plain folder holding repositories never has a ready checkpoint of its own. - .filter( - (checkpoint) => - (checkpoint.status === "ready" || checkpoint.repositories !== undefined) && - turnHasChanges(checkpoint), - ) - .map((checkpoint) => [checkpoint.assistantMessageId, checkpoint]), - ); const grouped = groupAdjacentActivities( - entries.map((entry) => { - if (entry.type !== "message" || entry.message.role !== "assistant") return entry; - const checkpointSummary = checkpointByMessageId.get(entry.message.id); - if (!checkpointSummary || checkpointSummary.runId !== entry.message.runId) return entry; - return { ...entry, message: { ...entry.message, checkpointSummary } }; - }), + entries, delegatedChildrenByRun, // Anchored messages shift entries away from their rows; such a build is not reused. anchoredMessages.length > 0 @@ -2850,7 +2779,6 @@ export function buildThreadFeed( locale, attempts: options?.attempts, nodes: options?.nodes, - checkpointSummaries: options?.checkpointSummaries, foldedAnswerRunIdByMessageId, delegatedChildrenByRun, feed, diff --git a/apps/mobile/src/native/useOpenPullRequest.ts b/apps/mobile/src/native/useOpenPullRequest.ts index b492ece6fbef5..aac80fb3004a4 100644 --- a/apps/mobile/src/native/useOpenPullRequest.ts +++ b/apps/mobile/src/native/useOpenPullRequest.ts @@ -7,7 +7,7 @@ import { import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useProjects, useThreadShell } from "../state/entities"; -import { tryOpenExternalUrl } from "../lib/openExternalUrl"; +import { tryOpenWebLink } from "../lib/openExternalUrl"; import { appAtomRegistry } from "../state/atom-registry"; import { environmentServerConfigsAtom } from "../state/server"; import { issueTrackerEnvironment } from "../state/issueTrackers"; @@ -59,7 +59,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean trackers: connections?._tag === "Success" ? connections.value : undefined, }) : null; - if (!issue || !environmentId) return tryOpenExternalUrl(url, "pull-request"); + if (!issue || !environmentId) return tryOpenWebLink(url, "pull-request"); const candidate = pullRequestCandidateForIssueLink(url, issue.ref); if (candidate) { const preview = await readPreview({ environmentId, input: candidate.target }); @@ -76,7 +76,7 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean return true; } // A dropped connection says nothing about what the link names; the browser knows. - if (isAtomCommandInterrupted(preview)) return tryOpenExternalUrl(url, "pull-request"); + if (isAtomCommandInterrupted(preview)) return tryOpenWebLink(url, "pull-request"); } const issueParams = { environmentId, diff --git a/apps/mobile/src/state/linkedThread.ts b/apps/mobile/src/state/linkedThread.ts index ff4c75b9ac1ac..8a0adc790940e 100644 --- a/apps/mobile/src/state/linkedThread.ts +++ b/apps/mobile/src/state/linkedThread.ts @@ -27,16 +27,14 @@ export function useLinkedThreadReach( const own = presentationById.get(id); return own && { connected: own.connection.phase === "connected" }; }; - const links = useLinkedEnvironments( - subagents.some( - (subagent) => - subagent.childThreadId === null && - subagent.remoteChild !== undefined && - ownConnection(subagent.remoteChild.environmentId)?.connected !== true, - ) - ? environmentId - : null, + const remote = subagents.flatMap((subagent) => + subagent.childThreadId === null && + subagent.remoteChild !== undefined && + ownConnection(subagent.remoteChild.environmentId)?.connected !== true + ? [subagent.remoteChild.environmentId] + : [], ); + const links = useLinkedEnvironments(remote.length > 0 ? environmentId : null, remote); return { ownConnection, isLinked: (id: EnvironmentId) => links.has(id) }; } diff --git a/apps/mobile/src/state/peerLinks.ts b/apps/mobile/src/state/peerLinks.ts index 40a13f2150234..ae403a4e72068 100644 --- a/apps/mobile/src/state/peerLinks.ts +++ b/apps/mobile/src/state/peerLinks.ts @@ -1,4 +1,4 @@ -import { useAtomValue } from "@effect/atom-react"; +import { RegistryContext, useAtomValue } from "@effect/atom-react"; import { linkableMachines, linkedEnvironmentNames, @@ -6,7 +6,7 @@ import { } from "@t3tools/client-runtime/link-request"; import { createPeerLinkEnvironmentAtoms } from "@t3tools/client-runtime/state/peerLinks"; import type { EnvironmentId } from "@t3tools/contracts"; -import { useEffect, useEffectEvent, useMemo } from "react"; +import { useContext, useEffect, useEffectEvent, useMemo } from "react"; import { connectionAtomRuntime } from "../connection/runtime"; import { useEnvironments } from "./environments"; @@ -19,19 +19,36 @@ export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtom /** * The machines `environmentId` links to, by name, while it offers links, and none otherwise. * Its agents can read threads there, and so can a client allowed to read threads on it. + * A `wanted` machine this app is not connected to and the names lack makes them reread. */ export function useLinkedEnvironments( environmentId: EnvironmentId | null, + wanted: ReadonlyArray = [], ): ReadonlyMap { const { environments } = useEnvironments(); const offered = offersLinkedEnvironments( environments.find((environment) => environment.environmentId === environmentId)?.serverConfig, ); + const queried = offered ? environmentId : null; const links = useEnvironmentQuery( - offered && environmentId !== null - ? peerLinkEnvironment.names({ environmentId, input: {} }) - : null, + queried === null ? null : peerLinkEnvironment.names({ environmentId: queried, input: {} }), ); + const connected = new Set( + environments + .filter((environment) => environment.connection.phase === "connected") + .map((environment) => environment.environmentId), + ); + const missing = [...new Set(wanted)].filter((id) => id !== environmentId && !connected.has(id)); + const refreshKey = + queried === null || missing.length === 0 ? "" : [queried, ...[...missing].sort()].join(" "); + const registry = useContext(RegistryContext); + const refreshLacking = useEffectEvent(() => { + if (queried !== null) peerLinkEnvironment.refreshNamesLacking(registry, queried, missing); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links made outside this app are not pushed, so meeting an unknown machine asks the server again + useEffect(() => { + if (refreshKey !== "") refreshLacking(); + }, [refreshKey]); return useMemo( () => linkedEnvironmentNames({ links: offered ? (links.data?.links ?? []) : [], environments }), [environments, links.data, offered], diff --git a/apps/mobile/src/state/queued-run-edit.test.ts b/apps/mobile/src/state/queued-run-edit.test.ts index 8a6176c1140c0..b2c06709518be 100644 --- a/apps/mobile/src/state/queued-run-edit.test.ts +++ b/apps/mobile/src/state/queued-run-edit.test.ts @@ -8,14 +8,20 @@ import { ChatAttachmentId, ComposerContextId, MessageId, + EnvironmentId, + ThreadId, + ProviderInstanceId, RunId, type ChatAttachment, type OrchestrationMessageContext, } from "@t3tools/contracts"; +import { selectThreadModel } from "./thread-model-selection"; +import { scopedThreadKey } from "../lib/scopedEntities"; import { appAtomRegistry } from "./atom-registry"; import { activeComposerDraftKey, + startQueuedRunEditSave, beginQueuedRunEdit, getQueuedRunEdit, queuedEditDraftKey, @@ -31,6 +37,13 @@ import { waitForComposerDraftsLoaded, } from "./use-composer-drafts"; +vi.mock("../components/ui/Dialog", () => ({ alert: vi.fn() })); +vi.mock("./session", () => ({ readEnvironmentScope: () => false })); +vi.mock("./threads", () => ({ + environmentThreadShells: { threadShellAtom: () => Atom.make(null) }, + threadEnvironment: { setModelSelection: {} }, +})); + vi.mock("expo-file-system", () => ({ Directory: class { create() {} @@ -266,3 +279,27 @@ describe("activeComposerDraftKey", () => { expect(activeComposerDraftKey(threadKey, editKey, null)).toBe(threadKey); }); }); + +it("blocks model and option picks while a queued edit save is in flight", () => { + const ref = { + environmentId: EnvironmentId.make("env-model-save"), + threadId: ThreadId.make("thread"), + }; + const threadKey = scopedThreadKey(ref.environmentId, ref.threadId); + const originalSelection = { instanceId: ProviderInstanceId.make("codex"), model: "original" }; + const edited = { ...edit([]), modelSelection: originalSelection }; + const draftKey = queuedEditDraftKey(threadKey, edited.runId); + const runs = Atom.make([{ id: edited.runId, status: "queued" }]); + beginQueuedRunEdit(threadKey, edited, runs); + const finishSave = startQueuedRunEditSave(threadKey)!; + const changed = { + ...originalSelection, + model: "changed", + options: [{ id: "effort", value: "high" }], + }; + selectThreadModel({ ...ref, draftKey }, changed); + expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(originalSelection); + finishSave(false); + selectThreadModel({ ...ref, draftKey }, changed); + expect(getComposerDraftSnapshot(draftKey).modelSelection).toEqual(changed); +}); diff --git a/apps/mobile/src/state/queued-run-edit.ts b/apps/mobile/src/state/queued-run-edit.ts index 3c046f847f29f..2ab7a6729165b 100644 --- a/apps/mobile/src/state/queued-run-edit.ts +++ b/apps/mobile/src/state/queued-run-edit.ts @@ -1,10 +1,12 @@ import type { ChatAttachment, MessageId, + ModelSelection, OrchestrationMessageContext, RunId, UploadChatAttachment, } from "@t3tools/contracts"; +import * as Equal from "effect/Equal"; import { useAtomValue } from "@effect/atom-react"; import { msg } from "gt-react-native"; import { stripAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences"; @@ -26,9 +28,12 @@ import { mergeComposerDraftContent, setComposerDraftContext, setComposerDraftText, + updateComposerDraftSettings, } from "./use-composer-drafts"; export interface QueuedRunEdit { + readonly modelSelection?: ModelSelection; + readonly followsThreadSelection?: boolean; readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; @@ -47,6 +52,9 @@ export { queuedEditDraftKey } from "./queued-edit-draft-key"; export const getQueuedRunEdit = queuedRunEdits.get; +export const isQueuedRunEditSaving = (threadKey: string): boolean => + appAtomRegistry.get(queuedRunEdits.savingAtom)[threadKey] === true; + /** * The draft a sheet opened for `requestedKey` should edit now: a queued edit's * draft only while that edit is still open, else the thread's own draft. @@ -77,8 +85,12 @@ function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void { const editDraft = getComposerDraftSnapshot(editDraftKey); const threadDraft = getComposerDraftSnapshot(threadKey); const editRestorable = editDraft.text.trim().length > 0 || editDraft.attachments.length > 0; + const modelChanged = + editDraft.modelSelection !== undefined && + !Equal.equals(editDraft.modelSelection, edit.modelSelection); const recovery = resolveQueuedEditExit({ editChanged: + modelChanged || editDraft.text !== edit.originalText || editDraft.attachments.length > 0 || edit.removedExistingAttachment === true, @@ -89,6 +101,8 @@ function exitQueuedRunEdit(threadKey: string, edit: QueuedRunEdit): void { threadDraft.attachments.length === 0, }); if (recovery === "kept") { + if (modelChanged) + updateComposerDraftSettings(threadKey, { modelSelection: editDraft.modelSelection }); // The merge publishes the draft before writing it, so a failed write only delays persistence to the next one. mergeComposerDraftContent(threadKey, { text: editDraft.text, @@ -124,6 +138,8 @@ export function beginQueuedRunEdit( const originalText = stripAttachmentOnlyBootstrapPrompt(edit.originalText); clearComposerDraft(draftKey); setComposerDraftText(draftKey, originalText); + if (edit.modelSelection && !edit.followsThreadSelection) + updateComposerDraftSettings(draftKey, { modelSelection: edit.modelSelection }); setComposerDraftContext(draftKey, edit.context); queuedRunEdits.begin( threadKey, diff --git a/apps/mobile/src/state/thread-model-selection.ts b/apps/mobile/src/state/thread-model-selection.ts index fd6bca2dd6a4c..aa0ed03e07a2f 100644 --- a/apps/mobile/src/state/thread-model-selection.ts +++ b/apps/mobile/src/state/thread-model-selection.ts @@ -12,6 +12,7 @@ import * as Dialog from "../components/ui/Dialog"; import { msg } from "gt-react-native"; import { m } from "../i18n/messages"; import { appAtomRegistry } from "./atom-registry"; +import { activeComposerDraftKey, getQueuedRunEdit, isQueuedRunEditSaving } from "./queued-run-edit"; import { readEnvironmentScope } from "./session"; import { environmentThreadShells, threadEnvironment } from "./threads"; import { @@ -21,13 +22,24 @@ import { /** Sets an existing thread's pick on the thread, so any next turn runs on it. */ export function selectThreadModel( - ref: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }, + ref: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly draftKey?: string; + }, value: ModelSelection, ): void { const threadKey = scopedThreadKey(ref.environmentId, ref.threadId); // Its own object, so an older reply for an equal pick cannot release this one. const modelSelection = { ...value }; - updateComposerDraftSettings(threadKey, { modelSelection }); + const draftKey = activeComposerDraftKey( + threadKey, + ref.draftKey ?? threadKey, + getQueuedRunEdit(threadKey), + ); + if (draftKey !== threadKey && isQueuedRunEditSaving(threadKey)) return; + updateComposerDraftSettings(draftKey, { modelSelection }); + if (draftKey !== threadKey) return; const thread = appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref)); // Another instance replaces the live session, which may hold an open question; that pick // still waits for a sent message. diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index a26af21009c05..5033ef4e8e894 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -7,7 +7,6 @@ import { readEnvironmentScope } from "./session"; import { useAtomValue } from "@effect/atom-react"; import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window"; import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; -import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; import { @@ -154,7 +153,6 @@ function setKeepFullHistory(threadKey: string, keep: boolean) { appAtomRegistry.set(fullHistoryThreadKeysAtom, keep ? { ...rest, [threadKey]: true } : rest); } -const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make>([]); const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0); export function appendReviewCommentToDraft(input: { @@ -294,11 +292,6 @@ export function useThreadComposerState(input: { messages: selectedThreadMessages, }); }, [acknowledgedMessages, selectedThreadKey, selectedThreadSequence, selectedThreadMessages]); - const checkpointSummaries = useAtomValue( - selectedThreadDetailRef === null - ? EMPTY_CHECKPOINT_SUMMARIES_ATOM - : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef), - ); // A thread whose creation has not delivered its turn yet: the prompt only // exists in the outbox, so it is appended to whatever the server has. The // detail is usually present but empty during a worktree checkout, so this @@ -315,7 +308,6 @@ export function useThreadComposerState(input: { anchoredMessages: pendingCreation, attempts: selectedThreadAttempts, nodes: selectedThreadNodes, - checkpointSummaries, cache: feedCache, resolve, locale, @@ -349,7 +341,8 @@ export function useThreadComposerState(input: { : queuedRunEdit === null ? selectedThreadKey : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId); - const selectedDraft = useComposerDraftSettings(selectedThreadKey); + const selectedDraft = useComposerDraftSettings(composerDraftKey); + const threadDraftSettings = useComposerDraftSettings(selectedThreadKey); const selectedThreadQueueCount = selectedThreadQueuedMessages.length; const selectedThread = selectedThreadShell; const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; @@ -361,7 +354,7 @@ export function useThreadComposerState(input: { : modelSelection, serverConfig?.providers ?? [], ); - const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null; + const runtimeMode = threadDraftSettings.runtimeMode ?? selectedThread?.runtimeMode ?? null; // Plan mode is not offered to users; every send runs in build mode. const interactionMode = selectedThread ? DEFAULT_PROVIDER_INTERACTION_MODE : null; const canSwitchThreadProvider = threadAllowsProviderSwitch({ @@ -372,7 +365,7 @@ export function useThreadComposerState(input: { ? deriveThreadRuntime(selectedThreadProjection.projection) : (selectedThreadShell?.runtime ?? null); const selectedThreadActivityRun = selectedThreadProjection - ? deriveThreadActivityRun(selectedThreadProjection.projection) + ? deriveThreadActivityRun(selectedThreadProjection.projection, serverConfig?.providers) : (selectedThreadShell?.latestRun ?? null); const selectedThreadAnnouncedRun = announcedRun( selectedThreadActivityRun, @@ -590,6 +583,9 @@ export function useThreadComposerState(input: { threadId: thread.id, runId: edit.runId, text: restoreAttachmentOnlyBootstrapPrompt(text, payload.attachments.length > 0), + ...(!edit.followsThreadSelection || draft.modelSelection + ? { modelSelection: draft.modelSelection ?? thread.modelSelection } + : {}), edit: { messageId: edit.messageId, attachments: payload.attachments, diff --git a/apps/mobile/src/widgets/AgentActivity.test.ts b/apps/mobile/src/widgets/AgentActivity.test.ts new file mode 100644 index 0000000000000..9ad17d330f5ac --- /dev/null +++ b/apps/mobile/src/widgets/AgentActivity.test.ts @@ -0,0 +1,83 @@ +import type { LiveActivityLayout } from "expo-widgets"; +import { describe, expect, it, vi } from "vite-plus/test"; + +vi.mock("@expo/ui/swift-ui", () => ({ + HStack: "HStack", + Image: "Image", + Spacer: "Spacer", + Text: "Text", + VStack: "VStack", + ZStack: "ZStack", +})); + +vi.mock("@expo/ui/swift-ui/modifiers", () => { + const modifier = (value: unknown) => value; + return { + accessibilityElement: modifier, + accessibilityLabel: modifier, + activityBackgroundTint: modifier, + font: modifier, + foregroundStyle: modifier, + frame: modifier, + layoutPriority: modifier, + lineLimit: modifier, + minimumScaleFactor: modifier, + padding: modifier, + resizable: modifier, + widgetURL: modifier, + }; +}); + +// Hand back the layout function so the test can render it with a chosen environment. +vi.mock("expo-widgets", () => ({ + createLiveActivity: (_name: string, layout: unknown) => layout, +})); + +import AgentActivity, { + type AgentActivityProps, + type AgentActivityRowProps, +} from "./AgentActivity"; + +const render = AgentActivity as unknown as ( + props: AgentActivityProps, + environment: unknown, +) => LiveActivityLayout; + +function row(overrides: Partial): AgentActivityRowProps { + return { + environmentId: "env-1", + threadId: "thread-1", + projectTitle: "Project", + threadTitle: "Thread", + modelTitle: "Model", + phase: "running", + status: "Working", + updatedAt: "2026-01-01T00:00:00.000Z", + deepLink: "/threads/env-1/thread-1", + ...overrides, + }; +} + +describe("AgentActivity", () => { + it("drops the agent count from the expanded Dynamic Island once the activity is stale", () => { + const layout = render( + { + title: "Agents", + subtitle: "", + activeCount: 2, + updatedAt: "2026-01-01T00:00:00.000Z", + activities: [row({}), row({ threadId: "thread-2", phase: "starting" })], + }, + { + colorScheme: "dark", + isLuminanceReduced: false, + isLiquidGlassAvailable: false, + isStale: true, + widgetRenderingMode: "fullColor", + }, + ); + const expandedLeading = JSON.stringify(layout.expandedLeading); + expect(expandedLeading).not.toContain('"children":"2"'); + expect(expandedLeading).toContain('"children":"Out of date"'); + }); +}); diff --git a/apps/mobile/src/widgets/AgentActivity.tsx b/apps/mobile/src/widgets/AgentActivity.tsx index 0c1017272f895..2def7e7e75f20 100644 --- a/apps/mobile/src/widgets/AgentActivity.tsx +++ b/apps/mobile/src/widgets/AgentActivity.tsx @@ -389,7 +389,7 @@ function AgentActivity( {renderLogo(15, tint)} - {allDone ? doneLabel : `${props.activeCount}`} + {allDone || environment.isStale ? activeLabel : `${props.activeCount}`} ), diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 436cea63f4f28..792c881c76b8a 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -4,10 +4,12 @@ import { defineConfig, normalizePath } from "vite-plus"; import "vite-plus/test/config"; const reactTests = [ + "src/features/browser/LocalPreviewRouteScreen.test.tsx", "src/features/threads/LinkedThreadSheet.test.tsx", "src/features/threads/ThreadGuestShareSheet.test.tsx", "src/features/threads/useSubmitAfterNativeImages.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", + "src/features/threads/git/GitConfirmSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/threads/NewTaskRouteScreen.test.tsx", "src/features/layout/workspace/workspace-tabs-state.test.ts", @@ -39,6 +41,7 @@ const reactTests = [ "src/components/ui/FilePreviewSession.test.tsx", "src/features/threads/UsageLimitRecoveryCard.test.tsx", "src/features/threads/PendingUserInputCard.test.tsx", + "src/features/threads/HtmlRenderWebView.test.tsx", "src/features/threads/NewTaskDraftRouteScreen.test.tsx", "src/native/NativeHeaderToolbar.test.tsx", "src/components/ComposerEditor.ios.test.tsx", diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index 64831512a9ef7..e70be7cb9f1fc 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -755,7 +755,7 @@ describe("AssetAccess", () => { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped({ prefix: "t3-link-" })); - yield* fs.writeFileString(path.join(root, "payload.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); yield* fs.writeFileString(path.join(root, "real.pdf"), "%PDF-1.4"); const link = path.join(root, "report.pdf"); const issue = issueAssetUrl({ @@ -772,7 +772,7 @@ describe("AssetAccess", () => { return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); }; - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); yield* fs.remove(link); @@ -783,7 +783,7 @@ describe("AssetAccess", () => { }); yield* fs.remove(link); - yield* fs.symlink(path.join(root, "payload.xhtml"), link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); expect(yield* resolveIssued(issued.relativeUrl)).toBeNull(); }).pipe(Effect.provide(layerTest)), ); @@ -1306,8 +1306,16 @@ describe("AssetAccess", () => { const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-asset-revision-" }); const pages = path.join(root, "pages"); yield* fileSystem.makeDirectory(pages); + // Coarse kernel clocks can stamp two quick same-size writes alike, so each edit gets its own mtime. + let editedAt = 1_000; const write = (name: string, text: string) => - fileSystem.writeFileString(path.join(pages, name), text); + fileSystem + .writeFileString(path.join(pages, name), text) + .pipe( + Effect.andThen( + Effect.promise(() => NodeFSP.utimes(path.join(pages, name), ++editedAt, editedAt)), + ), + ); yield* write("a.html", ''); yield* write("a.css", "body { color: red; }"); yield* write("b.html", "

b

"); @@ -1799,6 +1807,51 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect.skipIf(!symlinksSupported)("refuses a favicon link whose target is not an image", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-" }), + ); + const pictures = yield* fs.realPath( + yield* fs.makeTempDirectoryScoped({ prefix: "t3-asset-favicon-link-pictures-" }), + ); + yield* fs.writeFileString(path.join(root, "page.xhtml"), ""); + yield* fs.writeFileString(path.join(root, "real.svg"), ""); + const resolveIssued = (relativeUrl: string) => { + const suffix = relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + return resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)); + }; + for (const link of [path.join(root, "favicon.svg"), path.join(pictures, "custom.svg")]) { + const issue = issueAssetUrl({ + resource: { _tag: "project-favicon", cwd: root }, + ...(link.startsWith(pictures) ? { projectFaviconPath: link } : {}), + }); + + yield* fs.symlink(path.join(root, "page.xhtml"), link); + expect((yield* issue.pipe(Effect.flip))._tag).toBe("AssetPreviewTypeValidationError"); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "real.svg"), link); + const issued = yield* issue; + expect(yield* resolveIssued(issued.relativeUrl)).toEqual({ + kind: "file", + path: path.join(root, "real.svg"), + }); + + yield* fs.remove(link); + yield* fs.symlink(path.join(root, "page.xhtml"), link); + // An outside icon's URL names its target, so repointing the link cannot change it. + expect(yield* resolveIssued(issued.relativeUrl)).toEqual( + link.startsWith(pictures) ? { kind: "file", path: path.join(root, "real.svg") } : null, + ); + yield* fs.remove(link); + } + }).pipe(Effect.provide(layerTest)), + ); + it.effect("ignores a client favicon path hint", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 2b8f1029ae3a3..d91975114e6eb 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -287,6 +287,8 @@ const readToolOutputImage = Effect.fn("AssetAccess.readToolOutputImage")(functio const projectFaviconAsset = Effect.fn("AssetAccess.projectFaviconAsset")(function* ( filePath: string, ) { + // Checked again here: a link can be repointed after its URL was issued. + if (!isProjectFaviconPath(filePath)) return null; if (!filePath.toLowerCase().endsWith(".icns")) { return { kind: "file", path: filePath } satisfies ResolvedAsset; } @@ -824,6 +826,10 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i resource: input.resource, }); } + // A favicon link must resolve to an image file. + if (canonicalFaviconPath && !isProjectFaviconPath(canonicalFaviconPath)) { + return yield* new AssetPreviewTypeValidationError({ resource: input.resource }); + } claims = isExternalOverride && canonicalFaviconPath ? { diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 6eceb824a8cba..352ca586783d2 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -17,6 +17,7 @@ import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import * as PairingGrantStore from "./PairingGrantStore.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as SessionStore from "./SessionStore.ts"; @@ -916,6 +917,49 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( ), ); + it.effect("issues no session to an exchange that revoking all others overtook", () => + Effect.gen(function* () { + const pairingLinks = yield* PairingGrantStore.PairingGrantStore; + let afterSpend: Effect.Effect = Effect.void; + const serverAuth = yield* EnvironmentAuth.make.pipe( + Effect.provideService(PairingGrantStore.PairingGrantStore, { + ...pairingLinks, + consume: (credential, input) => + pairingLinks.consume(credential, input).pipe(Effect.tap(() => afterSpend)), + }), + Effect.provide( + Layer.merge( + ManagedPolicy.layerTest(), + ServerSecretStore.layer.pipe(Layer.provideMerge(layerServerConfig())), + ), + ), + ); + const owner = yield* serverAuth.issueSession(); + const succeeded = { onFailure: () => false, onSuccess: () => true }; + const exchanges = [ + (credential: string) => + serverAuth + .createBrowserSession(credential, requestMetadata) + .pipe(Effect.match(succeeded)), + (credential: string) => + serverAuth + .exchangeBootstrapCredentialForAccessToken(credential, undefined, requestMetadata) + .pipe(Effect.match(succeeded)), + ]; + for (const exchange of exchanges) { + const pairing = yield* serverAuth.issuePairingCredential(); + afterSpend = serverAuth.revokeOtherClientSessions(owner.sessionId).pipe(Effect.orDie); + const exchanged = yield* exchange(pairing.credential); + afterSpend = Effect.void; + + expect(exchanged).toBe(false); + expect((yield* serverAuth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + } + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + it.effect("accepts cookie sessions on socket upgrades only from the app's own origins", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index da8bd2cc86887..c5a19e0ca3736 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -35,6 +35,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Redacted from "effect/Redacted"; +import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; @@ -640,18 +641,25 @@ export class EnvironmentAuth extends Context.Service< readonly revokeMcpClientToken: ( token: string, ) => Effect.Effect; + /** How many times "revoke all others" has run since this server started. */ + readonly otherSessionRevocationCount: Effect.Effect; readonly issueMcpClientSession: (input: { readonly label: string; readonly access: AuthMcpClientAccess; readonly peerLink: boolean; readonly client: AuthClientMetadata; + /** + * `otherSessionRevocationCount` read before the sign-in was approved. The session is + * refused when "revoke all others" has run since. + */ + readonly approvedAtRevocationCount?: number; }) => Effect.Effect< { readonly sessionId: AuthSessionId; readonly token: string; readonly expiresAt: DateTime.DateTime; }, - ServerAuthInternalError + ServerAuthInvalidCredentialError | ServerAuthInternalError >; /** * Spends a code covering all granted scopes and returns the level it approves. A level-bound @@ -941,6 +949,28 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.getSessionState"), ); + // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints + // at once would open two requests with one code, and a revoke landing between an exchange + // spending its credential and trusting the key would be undone by that exchange. + const connectTrustLock = yield* Semaphore.make(1); + + // Counts "revoke all others" runs. An exchange or sign-in approval that began before a run + // issues its session here, under the lock the run holds, so it cannot leave a session behind. + const otherSessionRevocations = yield* Ref.make(0); + const issueUnlessOthersRevokedSince = (since: number, issue: Effect.Effect) => + Ref.get(otherSessionRevocations).pipe( + Effect.flatMap((count): Effect.Effect => + count === since + ? issue + : Effect.fail( + new ServerAuthInvalidCredentialError({ + diagnostic: "All other sessions were revoked before this one was issued.", + }), + ), + ), + connectTrustLock.withPermits(1), + ); + const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn( "EnvironmentAuth.createBrowserSession", )(function* (credential, requestMetadata, previousSessionToken) { @@ -968,6 +998,7 @@ export const make = Effect.gen(function* () { Effect.withSpan("EnvironmentAuth.createBrowserSession"), ); } + const revocationsAtStart = yield* Ref.get(otherSessionRevocations); const previousSession = previousSessionToken === undefined ? undefined @@ -978,20 +1009,23 @@ export const make = Effect.gen(function* () { const grant = yield* bootstrapCredentials .consume(credential) .pipe(Effect.mapError(toBootstrapExchangeError)); - const session = yield* sessions - .issue({ - method: "browser-session-cookie", - subject: grant.subject, - scopes: grant.scopes, - ...(previousSession?.method === "browser-session-cookie" - ? { replaceSessionId: previousSession.sessionId } - : {}), - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))); + const session = yield* issueUnlessOthersRevokedSince( + revocationsAtStart, + sessions + .issue({ + method: "browser-session-cookie", + subject: grant.subject, + scopes: grant.scopes, + ...(previousSession?.method === "browser-session-cookie" + ? { replaceSessionId: previousSession.sessionId } + : {}), + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause }))), + ); return { response: { authenticated: true, @@ -1063,11 +1097,6 @@ export const make = Effect.gen(function* () { ); }; - // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints - // at once would open two requests with one code, and a revoke landing between an exchange - // spending its credential and trusting the key would be undone by that exchange. - const connectTrustLock = yield* Semaphore.make(1); - const toAccessTokenResult = (session: SessionStore.IssuedSession) => DateTime.now.pipe( Effect.map( @@ -1107,63 +1136,71 @@ export const make = Effect.gen(function* () { const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] = (credential, requestedScopes, requestMetadata, input) => { - return resolveBootstrapGrant(credential, { - ...input, - requestMetadata, - ...(requestedScopes !== undefined ? { requestedScopes } : {}), - }).pipe( - // Every T3 Connect key that gets in is remembered, so turning approval on later - // keeps the devices already in use and lists them for review. - Effect.tap((grant) => - grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint - ? bootstrapCredentials - .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) - .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) - : Effect.void, - ), - Effect.flatMap((grant) => - Effect.gen(function* () { - const grantedScopes = - requestedScopes === undefined - ? grant.scopes - : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); - if (grantedScopes.length === 0) { - return yield* new ServerAuthScopeNotGrantedError({}); - } - // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep - // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. - const renewable = - input?.proofKeyThumbprint !== undefined && - grant.method === "one-time-token" && - grant.subject === PAIRING_LINK_SUBJECT; - return yield* sessions - .issue({ - method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", - subject: grant.subject, - scopes: grantedScopes, - ...(input?.proofKeyThumbprint - ? { - proofKeyThumbprint: input.proofKeyThumbprint, - ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), - } - : {}), - ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), - replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", - client: { - ...requestMetadata, - ...(grant.label ? { label: grant.label } : {}), - }, - }) - .pipe( - Effect.mapError( - (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), - ), - ); - }), - ), - Effect.flatMap(toAccessTokenResult), - (exchange) => - input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + const exchangeSince = (revocationsAtStart: number) => + resolveBootstrapGrant(credential, { + ...input, + requestMetadata, + ...(requestedScopes !== undefined ? { requestedScopes } : {}), + }).pipe( + // Every T3 Connect key that gets in is remembered, so turning approval on later + // keeps the devices already in use and lists them for review. + Effect.tap((grant) => + grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint + ? bootstrapCredentials + .trustConnectDevice(input.proofKeyThumbprint, requestMetadata) + .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))) + : Effect.void, + ), + Effect.flatMap((grant) => + Effect.gen(function* () { + const grantedScopes = + requestedScopes === undefined + ? grant.scopes + : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope)); + if (grantedScopes.length === 0) { + return yield* new ServerAuthScopeNotGrantedError({}); + } + // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep + // their own lifetimes, so unlinking Connect or rotating a credential still cuts off. + const renewable = + input?.proofKeyThumbprint !== undefined && + grant.method === "one-time-token" && + grant.subject === PAIRING_LINK_SUBJECT; + const issue = sessions + .issue({ + method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token", + subject: grant.subject, + scopes: grantedScopes, + ...(input?.proofKeyThumbprint + ? { + proofKeyThumbprint: input.proofKeyThumbprint, + ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1), + } + : {}), + ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}), + replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap", + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }), + ), + ); + // A proof-key exchange holds the lock from before it spends its credential. + return yield* input?.proofKeyThumbprint + ? issue + : issueUnlessOthersRevokedSince(revocationsAtStart, issue); + }), + ), + Effect.flatMap(toAccessTokenResult), + (exchange) => + input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange, + ); + return Ref.get(otherSessionRevocations).pipe( + Effect.flatMap(exchangeSince), Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"), ); }; @@ -1488,7 +1525,12 @@ export const make = Effect.gen(function* () { .revokeConnectDevicesExcept(Option.getOrNull(currentProofKey)) .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))); return yield* revokeOtherSessionsExcept(currentSessionId); - }).pipe(connectTrustLock.withPermits(1)); + }).pipe( + // Counted last, after unspent links and session rows are gone, so whatever reads the + // new count can no longer use either. + Effect.ensuring(Ref.update(otherSessionRevocations, (count) => count + 1)), + connectTrustLock.withPermits(1), + ); }); const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) => @@ -1661,8 +1703,8 @@ export const make = Effect.gen(function* () { return yield* revokeSession(session.value.sessionId); }); - const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => - sessions + const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) => { + const issue = sessions .issue({ subject: MCP_CLIENT_SUBJECT, method: "bearer-access-token", @@ -1679,8 +1721,13 @@ export const make = Effect.gen(function* () { expiresAt: issued.expiresAt, })), Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })), - Effect.withSpan("EnvironmentAuth.issueMcpClientSession"), ); + return ( + input.approvedAtRevocationCount === undefined + ? issue + : issueUnlessOthersRevokedSince(input.approvedAtRevocationCount, issue) + ).pipe(Effect.withSpan("EnvironmentAuth.issueMcpClientSession")); + }; const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = ( code, @@ -1744,6 +1791,7 @@ export const make = Effect.gen(function* () { issueStartupPairingUrl, authenticateMcpClient, revokeMcpClientToken, + otherSessionRevocationCount: Ref.get(otherSessionRevocations), issueMcpClientSession, consumeMcpApprovalCode, }); diff --git a/apps/server/src/auth/McpOAuth.test.ts b/apps/server/src/auth/McpOAuth.test.ts index f66d0b1c6e81c..ea321bcf0241c 100644 --- a/apps/server/src/auth/McpOAuth.test.ts +++ b/apps/server/src/auth/McpOAuth.test.ts @@ -27,6 +27,7 @@ import * as CloudLink from "../cloud/CloudLink.ts"; import * as ServerConfig from "../config.ts"; import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as Sqlite from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; @@ -75,6 +76,7 @@ const makeLayerRoutes = ( ), ), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), ), ).pipe( Layer.provideMerge(layerEnvironmentAuth), @@ -216,6 +218,26 @@ it.effect("derives discovery metadata from the origin the client reached", () => ), ); +it.effect("answers 413 to a body over the API limit", () => + withRoutes((handler) => + Effect.gen(function* () { + const body = "x".repeat(ServerHttp.API_MAX_BODY_BYTES + 1); + for (const [path, contentType] of [ + ["/api/auth/browser-session", "application/json"], + ["/oauth/token", "application/x-www-form-urlencoded"], + ["/oauth/mcp/register", "application/json"], + ]) { + const init = { method: "POST", headers: { "content-type": contentType! } }; + expect((yield* handler(at(path!, { ...init, body }))).status, path).toBe(413); + // A chunked body declares no length, so the reader itself has to stop. + const chunked = new Blob([body]).stream(); + const streamed = at(path!, { ...init, body: chunked, duplex: "half" } as RequestInit); + expect((yield* handler(streamed)).status, `${path} chunked`).toBe(413); + } + }), + ), +); + it.effect("registers loopback and https clients and never redirects for an unverified client", () => withRoutes((handler) => Effect.gen(function* () { @@ -516,6 +538,44 @@ it.live("signs in Gemini, which registers six user-bound redirect URIs for one c ), ); +it.live("issues no session for a sign-in approved before all other sessions were revoked", () => + withRoutes((handler, auth) => + Effect.gen(function* () { + const clientId = yield* registeredClientId(handler); + const params = authorizeParams(clientId); + const approved = yield* decide(handler, params, { + _tag: "pairing-code", + access: "approval-required", + code: (yield* auth.issuePairingCredential()).credential, + }); + const code = new URL(approved.redirectTo!).searchParams.get("code")!; + const owner = yield* auth.issueSession(); + yield* auth.revokeOtherClientSessions(owner.sessionId); + + const response = yield* handler( + at( + "/oauth/mcp/token", + form({ + grant_type: "authorization_code", + code, + redirect_uri: params.redirect_uri, + client_id: clientId, + code_verifier: verifier, + }), + ), + ); + expect(response.status).toBe(400); + expect(yield* json(response)).toEqual({ + error: "invalid_grant", + error_description: "The authorization code is invalid or expired.", + }); + expect((yield* auth.listSessions()).map((session) => session.sessionId)).toEqual([ + owner.sessionId, + ]); + }), + ), +); + it.live("rejects a wrong PKCE verifier and spends the code", () => withRoutes((handler, auth) => Effect.gen(function* () { diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index e63c600ae1b2d..7c6cdc677cc3c 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -197,6 +197,7 @@ interface PendingCode { readonly codeChallenge: string; readonly resource: string; readonly access: AuthMcpClientAccess; + readonly approvedAtRevocationCount: number; readonly expiresAtMs: number; } @@ -445,6 +446,7 @@ const make = Effect.gen(function* () { const mintCode = Effect.fn("McpOAuth.mintCode")(function* ( authorization: AuthorizationRequest, access: AuthMcpClientAccess, + approvedAtRevocationCount: number, ) { const now = yield* Clock.currentTimeMillis; const code = Buffer.from(yield* random.randomBytes(32)).toString("base64url"); @@ -458,6 +460,7 @@ const make = Effect.gen(function* () { codeChallenge: authorization.codeChallenge, resource: authorization.resource, access, + approvedAtRevocationCount, expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS, }); return next; @@ -467,6 +470,9 @@ const make = Effect.gen(function* () { const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { const { decision } = input; + // Read before the approver is checked: "revoke all others" then ends this sign-in whether + // it lands before the check or after the code is handed out. + const approvedAtRevocationCount = yield* environmentAuth.otherSessionRevocationCount; let access = decision.access; if (decision._tag === "pairing-code") { // An approval code is for one app's sign-in, never for linking another environment. @@ -502,7 +508,7 @@ const make = Effect.gen(function* () { }); } } - const code = yield* mintCode(input.authorization, access); + const code = yield* mintCode(input.authorization, access, approvedAtRevocationCount); yield* Effect.logInfo("Approved an MCP client sign-in.", { client: input.authorization.client.name, access, @@ -567,14 +573,17 @@ const make = Effect.gen(function* () { access: pending.access, peerLink: pending.peerLink, client: deriveAuthClientMetadata({ request }), + approvedAtRevocationCount: pending.approvedAtRevocationCount, }) .pipe( Effect.catch((cause) => - Effect.logError("Could not issue an MCP client session.", { cause }).pipe( - Effect.andThen( - Effect.fail(fail("invalid_grant", "The session could not be issued.")), - ), - ), + cause._tag === "ServerAuthInvalidCredentialError" + ? Effect.fail(fail("invalid_grant", "The authorization code is invalid or expired.")) + : Effect.logError("Could not issue an MCP client session.", { cause }).pipe( + Effect.andThen( + Effect.fail(fail("invalid_grant", "The session could not be issued.")), + ), + ), ), ); return { diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 750ff136ac07d..2319216f64d60 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -355,6 +355,76 @@ it.effect("pairs a client with a linked environment only for one that may hand o }).pipe(Effect.scoped), ); +it.effect("hands out a link code or a guest link only within what the session itself holds", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.peerLinksPairLink | typeof WS_METHODS.guestShareCreate + > => tag !== WS_METHODS.peerLinksPairLink && tag !== WS_METHODS.guestShareCreate, + ), + ); + let handled = 0; + const environmentId = EnvironmentId.make("environment-box"); + const threadId = ThreadId.make("thread-1"); + const handlers = Layer.mergeAll( + group.toLayerHandler(WS_METHODS.peerLinksPairLink, () => + Effect.sync(() => { + handled++; + return { + type: "unsupported" as const, + reason: "link_access" as const, + environmentId, + label: "Box", + urls: [], + }; + }), + ), + group.toLayerHandler(WS_METHODS.guestShareCreate, () => + Effect.sync(() => handled++).pipe(Effect.andThen(Effect.die("no share in this test"))), + ), + ); + const clientWith = (scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handlers, RpcAuthorization.layer(scopes))), + ); + + // Managing access alone is not running agents or reading threads. + const manager = yield* clientWith([AuthAccessWriteScope]); + expect( + yield* manager[WS_METHODS.peerLinksPairLink]({ environmentId, access: "read-only" }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + expect( + yield* manager[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationReadScope }); + + const supervisor = yield* clientWith([ + AuthAccessWriteScope, + AuthOrchestrationReadScope, + AuthOrchestrationOperateScope, + ]); + expect( + yield* supervisor[WS_METHODS.peerLinksPairLink]({ + environmentId, + access: "full-access", + }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthSettingsWriteScope }); + expect(handled).toBe(0); + + expect( + (yield* supervisor[WS_METHODS.peerLinksPairLink]({ environmentId, access: "auto" })).type, + ).toBe("unsupported"); + expect(handled).toBe(1); + yield* supervisor[WS_METHODS.guestShareCreate]({ threadId }).pipe(Effect.exit); + expect(handled).toBe(2); + }).pipe(Effect.scoped), +); + it.effect.each([WS_METHODS.subscribeVcsBranch, WS_METHODS.subscribeVcsStatus] as const)( "enforces read permission on stream %s", (method) => @@ -538,6 +608,66 @@ describe("settings mutation authorization", () => { }), ); + it.effect("saving project scripts needs task operation as well as the settings grant", () => + Effect.gen(function* () { + const projectId = ProjectId.make("project-1"); + const scripts = [ + { + id: "setup", + name: "Setup", + command: "pnpm install", + icon: "play" as const, + runOnWorktreeCreate: true, + }, + ]; + const update = (scopes: Parameters[0]) => { + let handled = 0; + return RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.mergeAll( + group.toLayerHandler(WS_METHODS.serverUpdateSettings, () => + Effect.sync(() => { + handled++; + return DEFAULT_SERVER_SETTINGS; + }), + ), + RpcAuthorization.layer(scopes), + ), + ), + Effect.map((client) => ({ client, handled: () => handled })), + ); + }; + const patches = [ + { defaultProjectScripts: scripts }, + { projectScriptOverrides: { [projectId]: scripts } }, + { projectSettingsOverrides: { [projectId]: { defaultProjectScripts: scripts } } }, + ]; + + const settingsOnly = yield* update([AuthSettingsWriteScope]); + for (const patch of patches) { + expect( + yield* settingsOnly.client[WS_METHODS.serverUpdateSettings]({ patch }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + } + expect(settingsOnly.handled()).toBe(0); + // Settings that carry no script stay with the settings grant alone. + yield* settingsOnly.client[WS_METHODS.serverUpdateSettings]({ + patch: { + defaultAutoPull: true, + projectScriptOverrides: { [projectId]: null }, + projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } }, + }, + }); + expect(settingsOnly.handled()).toBe(1); + + const operator = yield* update([AuthSettingsWriteScope, AuthOrchestrationOperateScope]); + for (const patch of patches) { + yield* operator.client[WS_METHODS.serverUpdateSettings]({ patch }); + } + expect(operator.handled()).toBe(patches.length); + }), + ); + it.effect("does not let a settings grant send a named secret to a gateway it picks", () => Effect.gen(function* () { const group = WsRpcGroup.omit( @@ -587,6 +717,67 @@ describe("settings mutation authorization", () => { ); }); +it.effect("answering a secret request with a reference needs provider management", () => + Effect.gen(function* () { + const group = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RPC_REQUIRED_SCOPES, + typeof WS_METHODS.secretsAnswerRequest + > => tag !== WS_METHODS.secretsAnswerRequest, + ), + ); + const handled: string[] = []; + const handler = group.toLayerHandler(WS_METHODS.secretsAnswerRequest, ({ answer }) => + Effect.sync(() => { + handled.push(answer.type); + }), + ); + const clientWith = (...scopes: Parameters[0]) => + RpcTest.makeClient(group).pipe( + Effect.provide(Layer.merge(handler, RpcAuthorization.layer(scopes))), + ); + const request = { threadId: ThreadId.make("thread"), turnItemId: TurnItemId.make("item") }; + const reference = { + type: "reference" as const, + reference: { + provider: SecretProviderId.make("personal"), + reference: "op://Private/OpenAI/credential", + }, + }; + + const operate = yield* clientWith(AuthOrchestrationOperateScope); + expect( + yield* operate[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthProvidersManageScope }); + expect(handled).toEqual([]); + // Typed values stay with the scope that runs the thread, whatever the fields are called. + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", secret: "typed-value" }, + }); + yield* operate[WS_METHODS.secretsAnswerRequest]({ + ...request, + answer: { type: "save", values: { provider: "personal", reference: "typed-value" } }, + }); + expect(handled).toEqual(["save", "save"]); + + const manage = yield* clientWith(AuthOrchestrationOperateScope, AuthProvidersManageScope); + yield* manage[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }); + expect(handled).toEqual(["save", "save", "reference"]); + const manageOnly = yield* clientWith(AuthProvidersManageScope); + expect( + yield* manageOnly[WS_METHODS.secretsAnswerRequest]({ ...request, answer: reference }).pipe( + Effect.flip, + ), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + }), +); + it.effect("requires task permission before attaching a prepared worktree to a thread", () => Effect.gen(function* () { const group = WsRpcGroup.omit( diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index f7ba41e2c450f..0aa0ebef9f923 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -13,6 +13,7 @@ import { requiredScopesForServerSettingsPatch, requiredScopesForProjectMutation, ProjectMutation, + SecretRequestAnswerInput, AuthSettingsWriteScope, AuthProvidersManageScope, AuthEnvironmentMaintainScope, @@ -287,6 +288,7 @@ const requiredScopesForSettingsUpdate = (payload: unknown) => { const decodeProjectMutation = Schema.decodeUnknownSync(ProjectMutation); const decodeAssetCreateUrlInput = Schema.decodeUnknownSync(AssetCreateUrlInput); +const decodeSecretRequestAnswer = Schema.decodeUnknownSync(SecretRequestAnswerInput); /** * A queued edit that omits `attachments` keeps the queued ones, which a payload cannot show; @@ -342,6 +344,14 @@ const requiredScopesForRpcCall = ( ) { return [AuthSettingsWriteScope, AuthProvidersManageScope]; } + // A reference answer has the server read a secret the caller names, as a saved reference does. + // Typed values can use any field names, so the answer's type decides, not its shape. + if ( + method === WS_METHODS.secretsAnswerRequest && + decodeSecretRequestAnswer(payload).answer.type === "reference" + ) { + return [AuthOrchestrationOperateScope, AuthProvidersManageScope]; + } if (method === WS_METHODS.projectsMutate) { return requiredScopesForProjectMutation(decodeProjectMutation(payload)); } diff --git a/apps/server/src/background/KeepAwake.test.ts b/apps/server/src/background/KeepAwake.test.ts index 8984102729cec..628590930e470 100644 --- a/apps/server/src/background/KeepAwake.test.ts +++ b/apps/server/src/background/KeepAwake.test.ts @@ -34,3 +34,12 @@ describe("KeepAwake.holdWhileWanted", () => { }), ); }); + +describe("KeepAwake.inhibitorCommand", () => { + it("runs PowerShell by its System32 path on Windows", () => { + expect( + KeepAwake.inhibitorCommand("win32", 1, false, { SYSTEMROOT: String.raw`D:\Windows` }) + ?.command, + ).toBe(String.raw`D:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`); + }); +}); diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index f9d2cf3da7532..72e5c1fbf031b 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -14,6 +14,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { forkParked } from "../serverActivation.ts"; import * as Settings from "../serverSettings.ts"; @@ -27,10 +28,11 @@ const WINDOWS_HOLD_SCRIPT = `$t = Add-Type -Name Power -Namespace T3 -PassThru - * Each command writes a line to stdout once it holds its inhibitor, holds it until it exits, and * exits on its own if the server dies. */ -function inhibitorCommand( +export function inhibitorCommand( platform: NodeJS.Platform, serverPid: number, isWsl: boolean, + env: NodeJS.ProcessEnv, ): | { readonly command: string; @@ -77,7 +79,7 @@ function inhibitorCommand( }; case "win32": return { - command: "powershell.exe", + command: windowsPowerShellPath(env), args: [ "-NoProfile", "-NonInteractive", @@ -145,7 +147,7 @@ export const layer = Layer.effectDiscard( Effect.map((release) => release.toLowerCase().includes("microsoft")), Effect.orElseSucceed(() => false), )); - const command = inhibitorCommand(platform, process.pid, isWsl); + const command = inhibitorCommand(platform, process.pid, isWsl, yield* HostProcess.Environment); if (command === undefined) return; const settings = yield* Settings.ServerSettingsService; const events = yield* OrchestrationEventStore.OrchestrationEventStore; diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 7b980e01b5fa7..4bbc5801d2c83 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -53,6 +53,10 @@ if ( const launcherOptions = launcher?.parseServiceLauncherArgs(process.argv.slice(3)); if (launcher !== undefined && launcherOptions !== undefined) { await launcher.runServiceLauncherCli(launcherOptions); + } else if (process.argv[2] === "__process-launcher") { + // Single executables host the launcher here; other builds start process-launcher.mjs directly. + const { runProcessLauncher } = await import("./process/processLauncherWorker.ts"); + runProcessLauncher(); } else { const { runCliCommand } = await loadCliMain(); await runCliCommand(); diff --git a/apps/server/src/cli/automaticPort.test.ts b/apps/server/src/cli/automaticPort.test.ts index 1f7805569744f..b39c94720cbc8 100644 --- a/apps/server/src/cli/automaticPort.test.ts +++ b/apps/server/src/cli/automaticPort.test.ts @@ -34,6 +34,7 @@ interface Scenario { readonly tcpv6ExitCode?: number; readonly wslpathMissing?: boolean; readonly reservedPorts?: ReadonlyArray; + readonly host?: string; } const select = (scenario: Scenario) => { @@ -92,7 +93,7 @@ const select = (scenario: Scenario) => { ); return Effect.gen(function* () { const selectAutomaticPort = yield* AutomaticPort.make; - const port = yield* selectAutomaticPort(3773); + const port = yield* selectAutomaticPort(3773, scenario.host); return { port, commands }; }).pipe(Effect.provide(layer)); }; @@ -149,12 +150,13 @@ describe("automatic port selection", () => { }), ); - it.effect("never queries Windows outside WSL", () => + it.effect("never queries Windows outside WSL or for a specific bind address", () => Effect.gen(function* () { for (const scenario of [ { kernelRelease: "6.8.0-45-generic\n" }, // macOS and Windows have no kernel release file. {}, + { kernelRelease: WSL_KERNEL, windowsPorts: [3773], host: "100.64.0.7" }, ] satisfies ReadonlyArray) { const result = yield* select(scenario); expect(result.port).toBe(3773); diff --git a/apps/server/src/cli/automaticPort.ts b/apps/server/src/cli/automaticPort.ts index 354de65d2519b..70e8bad6c8b05 100644 --- a/apps/server/src/cli/automaticPort.ts +++ b/apps/server/src/cli/automaticPort.ts @@ -1,3 +1,4 @@ +import { listensOnLoopback } from "@t3tools/shared/hostClassification"; import * as NetService from "@t3tools/shared/Net"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -44,14 +45,17 @@ export const make = Effect.gen(function* () { return new Set(listeners.map((listener) => listener.port)); }).pipe(Effect.orElseSucceed(() => null)); - return Effect.fn("automaticPort.select")(function* (preferred: number) { - if (!(yield* isWsl)) return yield* net.findAvailablePort(preferred); + return Effect.fn("automaticPort.select")(function* (preferred: number, host: string | undefined) { + // Windows localhost forwarding reaches only WSL listeners on loopback or a wildcard address. + if (!listensOnLoopback(host) || !(yield* isWsl)) { + return yield* net.findAvailablePort(preferred, host); + } const windows = yield* readWindowsHostListeners; if (windows === null) { yield* Effect.logWarning( "Could not list Windows TCP listeners from WSL; Windows may be unable to reach the selected port. Pass --port to choose one.", ); - return yield* net.findAvailablePort(preferred); + return yield* net.findAvailablePort(preferred, host); } if (!windows.has(preferred) && (yield* net.isPortAvailableOnLoopback(preferred))) { return preferred; diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts index 9d1ffb5c1298a..bbd13c1132953 100644 --- a/apps/server/src/cli/config.test.ts +++ b/apps/server/src/cli/config.test.ts @@ -872,15 +872,16 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { const baseDir = yield* FileSystem.FileSystem.pipe( Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })), ); - const selected: number[] = []; - const selectAutomaticPort = (preferred: number) => + const selected: Array = []; + const selectAutomaticPort = (preferred: number, host: string | undefined) => Effect.sync(() => { - selected.push(preferred); + selected.push([preferred, host]); return 50_123; }); const resolvePort = (flags: { readonly mode?: Option.Option<"web" | "desktop">; readonly port: Option.Option; + readonly host?: Option.Option; }) => resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), { selectAutomaticPort, @@ -895,12 +896,18 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { ); expect(yield* resolvePort({ port: Option.none() })).toBe(50_123); - expect(selected).toEqual([3773]); + expect(yield* resolvePort({ port: Option.none(), host: Option.some("100.64.0.7") })).toBe( + 50_123, + ); + expect(selected).toEqual([ + [3773, undefined], + [3773, "100.64.0.7"], + ]); expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788); expect( yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }), ).toBe(3773); - expect(selected).toEqual([3773]); + expect(selected).toHaveLength(2); }), ); diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts index a62682772bcce..0d4e26b3806ac 100644 --- a/apps/server/src/cli/config.ts +++ b/apps/server/src/cli/config.ts @@ -271,6 +271,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct readonly rejectRunningServer?: boolean; readonly selectAutomaticPort?: ( preferred: number, + host: string | undefined, ) => Effect.Effect; }, ) { @@ -310,22 +311,6 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct () => "web", ); - const port = yield* Option.match( - resolveOptionPrecedence( - normalizedFlags.port, - Option.fromUndefinedOr(env.port), - Option.fromUndefinedOr(bootstrap?.port), - ), - { - onSome: (value) => Effect.succeed(value), - onNone: () => { - if (mode === "desktop") { - return Effect.succeed(ServerConfig.DEFAULT_PORT); - } - return selectAutomaticPort(ServerConfig.DEFAULT_PORT); - }, - }, - ); const devUrl = Option.getOrElse( resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)), () => undefined, @@ -390,6 +375,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct ); const desktopBootstrapToken = bootstrap?.desktopBootstrapToken; const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret; + const desktopReadinessSecret = bootstrap?.desktopReadinessSecret; const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared; const desktopTelemetryFd = bootstrap?.desktopTelemetryFd; const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd; @@ -451,6 +437,22 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct const host = Option.getOrElse(explicitHost, () => privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined, ); + const port = yield* Option.match( + resolveOptionPrecedence( + normalizedFlags.port, + Option.fromUndefinedOr(env.port), + Option.fromUndefinedOr(bootstrap?.port), + ), + { + onSome: (value) => Effect.succeed(value), + onNone: () => { + if (mode === "desktop") { + return Effect.succeed(ServerConfig.DEFAULT_PORT); + } + return selectAutomaticPort(ServerConfig.DEFAULT_PORT, host); + }, + }, + ); const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel); const otel = yield* OtelEnvironment.load; @@ -524,6 +526,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct startupPresentation, desktopBootstrapToken, ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }), + ...(desktopReadinessSecret === undefined ? {} : { desktopReadinessSecret }), ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }), desktopTelemetryFd, desktopTelemetryControlFd, diff --git a/apps/server/src/cli/policy.test.ts b/apps/server/src/cli/policy.test.ts index d06998ff42882..04e29808078c1 100644 --- a/apps/server/src/cli/policy.test.ts +++ b/apps/server/src/cli/policy.test.ts @@ -9,6 +9,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { Command } from "effect/cli"; +import * as TestConsole from "effect/testing/TestConsole"; import { cli } from "../binCli.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; @@ -85,4 +86,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))((it) => { ); }), ); + + it.effect("check reads a ~/ policy file from the home directory", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-policy-check-" }); + const file = path.join(home, "policy.json"); + yield* fs.writeFileString( + file, + JSON.stringify({ schemaVersion: 1, organization: "Tilde Corp" }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })(["policy", "check", "~/policy.json"]).pipe( + Effect.provideService(HostProcess.HomeDirectory, home), + Effect.provide(NetService.layer), + ); + + assert.include((yield* TestConsole.logLines).join("\n"), `Managed by Tilde Corp (${file}`); + }).pipe(Effect.provide(Layer.fresh(TestConsole.layer))), + ); }); diff --git a/apps/server/src/cli/policy.ts b/apps/server/src/cli/policy.ts index c48e2bc535a6f..e8badd9123615 100644 --- a/apps/server/src/cli/policy.ts +++ b/apps/server/src/cli/policy.ts @@ -96,14 +96,15 @@ const checkCommand = Command.make("check", { Command.withDescription("Validate a policy file before deploying it."), Command.withHandler( Effect.fn("cli.policy.check")(function* ({ file }) { + const policyFile = yield* expandHomePath(file); // Startup treats a missing file as no policy; a draft that is not there checks nothing. - if (!(yield* (yield* FileSystem.FileSystem).exists(file))) { + if (!(yield* (yield* FileSystem.FileSystem).exists(policyFile))) { return yield* new CliError.UserError({ cause: file, userMessage: `No policy file at ${file}.`, }); } - const policy = yield* ManagedPolicy.load(file); + const policy = yield* ManagedPolicy.load(policyFile); yield* Console.log(describePolicy(policy, yield* ManagedPolicy.loadedPolicy(policy))); }), ), diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts index 303402d46c2b4..73383888c7dfd 100644 --- a/apps/server/src/cli/server.ts +++ b/apps/server/src/cli/server.ts @@ -8,7 +8,7 @@ import * as CliError from "effect/cli/CliError"; import { awaitServiceLauncherStop } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; -import { awaitLauncherLoss } from "../launcherWatch.ts"; +import { stopOnLauncherLoss } from "../launcherWatch.ts"; import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as AutomaticPort from "./automaticPort.ts"; @@ -41,13 +41,7 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* ( ), ); if (config.mode !== "desktop" || config.desktopBootstrapToken === undefined) return yield* run; - return yield* Effect.raceFirst( - run, - awaitLauncherLoss().pipe( - // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit). - Effect.andThen(Effect.interrupt), - ), - ); + return yield* stopOnLauncherLoss(run); }); export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand")(function* ( diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts index ada548ba2bf39..70907ab446a09 100644 --- a/apps/server/src/cli/service.test.ts +++ b/apps/server/src/cli/service.test.ts @@ -288,6 +288,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands const { service, uninstalls } = makeTestService({ ...status, installedBaseDir: input.otherHome ? "/home/me/.t3" : baseDir, + ...(input.otherHome ? { otherBaseDir: "/home/me/.t3" } : {}), }); vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index fc2aa8d0889aa..4c55d1fa329da 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -325,19 +325,14 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags). flags, Effect.gen(function* () { const service = yield* BootService.BootService; - const path = yield* Path.Path; - const { baseDir } = yield* ServerConfig.ServerConfig; // An unreadable unit stays removable; only a unit known to serve another home is kept. - const installedBaseDir = yield* service.status.pipe( - Effect.map((status) => status.installedBaseDir), + const otherBaseDir = yield* service.status.pipe( + Effect.map((status) => status.otherBaseDir), Effect.orElseSucceed(() => undefined), ); - if ( - installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(baseDir) - ) { + if (otherBaseDir !== undefined) { yield* Console.log( - `The T3 Code service serves ${installedBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(installedBaseDir)}\` to remove it.`, + `The T3 Code service serves ${otherBaseDir}, so it was not removed. Pass \`${BootService.formatBootServiceBaseDirOption(otherBaseDir)}\` to remove it.`, ); return; } diff --git a/apps/server/src/cli/theme.test.ts b/apps/server/src/cli/theme.test.ts index b81cf6926c57e..d2e72dd7e1cc8 100644 --- a/apps/server/src/cli/theme.test.ts +++ b/apps/server/src/cli/theme.test.ts @@ -30,6 +30,17 @@ const runCli = (args: ReadonlyArray) => ), ); +const runCliIn = (cwd: string, args: ReadonlyArray) => + Effect.acquireUseRelease( + Effect.sync(() => { + const previous = process.cwd(); + process.chdir(cwd); + return previous; + }), + () => runCli(args), + (previous) => Effect.sync(() => process.chdir(previous)), + ); + const makeBaseDir = () => NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3code-theme-cli-")); const settingsPathFor = (baseDir: string) => NodePath.join(baseDir, "userdata", "settings.json"); @@ -136,6 +147,77 @@ describe("t3 theme", () => { }), ); + it.effect("publishes the file named with a leading space, not its trimmed sibling", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + NodeFS.mkdirSync(NodePath.join(baseDir, " palettes")); + NodeFS.mkdirSync(NodePath.join(baseDir, "palettes")); + NodeFS.writeFileSync( + NodePath.join(baseDir, " palettes", "nightfall.json"), + NIGHTFALL_THEME_JSON, + ); + NodeFS.writeFileSync(NodePath.join(baseDir, "palettes", "nightfall.json"), JUNK_THEME_JSON); + + yield* runCliIn(baseDir, ["theme", "set", " palettes/nightfall.json", "--base-dir", "."]); + + const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json"); + assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON); + assert.equal(readSettings(baseDir).defaultTheme, "nightfall"); + }), + ); + + // Win32 resolves both names to one file. + it.effect.skipIf(windowsHost)("publishes a file whose name ends in a space", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + NodeFS.writeFileSync(NodePath.join(baseDir, "nightfall.json "), NIGHTFALL_THEME_JSON); + NodeFS.writeFileSync(NodePath.join(baseDir, "nightfall.json"), JUNK_THEME_JSON); + + yield* runCliIn(baseDir, [ + "theme", + "set", + "nightfall.json ", + "--id", + "nightfall", + "--base-dir", + ".", + ]); + + const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json"); + assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON); + }), + ); + + // Simulates Win32 on other hosts; on Windows itself the two fixtures would be one file. + it.effect.skipIf(windowsHost)("drops trailing spaces from the path on Windows", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + const themeFile = NodePath.join(baseDir, "nightfall.json"); + NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON); + NodeFS.writeFileSync(`${themeFile} `, JUNK_THEME_JSON); + + yield* runCli(["theme", "set", `${themeFile} `, "--base-dir", baseDir]).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + ); + + const published = NodePath.join(baseDir, "userdata", "themes", "nightfall.json"); + assert.equal(NodeFS.readFileSync(published, "utf8"), NIGHTFALL_THEME_JSON); + }), + ); + + it.effect("still trims a path that only names a file once trimmed", () => + Effect.gen(function* () { + const baseDir = makeBaseDir(); + const themeFile = NodePath.join(baseDir, "palettes", "nightfall.json"); + NodeFS.mkdirSync(NodePath.dirname(themeFile)); + NodeFS.writeFileSync(themeFile, NIGHTFALL_THEME_JSON); + NodeFS.mkdirSync(NodePath.join(baseDir, " palettes", "nightfall.json"), { recursive: true }); + + yield* runCliIn(baseDir, ["theme", "set", " palettes/nightfall.json", "--base-dir", "."]); + assert.equal(readSettings(baseDir).defaultTheme, "nightfall"); + }), + ); + it.effect("refuses to publish over a directory with the theme's file name", () => Effect.gen(function* () { const baseDir = makeBaseDir(); diff --git a/apps/server/src/cli/theme.ts b/apps/server/src/cli/theme.ts index 26048240d5248..ba9e89c17a2b5 100644 --- a/apps/server/src/cli/theme.ts +++ b/apps/server/src/cli/theme.ts @@ -22,6 +22,7 @@ import * as Schema from "effect/Schema"; import { Argument, Command, Flag } from "effect/cli"; import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ServerConfig from "../config.ts"; import { MAX_THEME_FILE_BYTES, @@ -455,7 +456,7 @@ const themeSetCommand = Command.make("set", { Command.withHandler((flags) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const target = yield* expandHomePath(flags.theme.trim()); + let target = yield* expandHomePath(flags.theme.trim()); if (target.length === 0) { return yield* new ThemeTargetMissingError(); } @@ -467,6 +468,17 @@ const themeSetCommand = Command.make("set", { target.includes("/") || target.includes("\\") || target.startsWith("~"); + if (looksLikePath) { + // Spaces stay part of the path when the argument names a file as typed. Win32 drops + // trailing spaces from ordinary paths, so only leading ones can name another file there. + const expanded = yield* expandHomePath(flags.theme); + const asTyped = + (yield* HostProcess.Platform) === "win32" && !expanded.startsWith("\\\\?\\") + ? expanded.replace(/ +$/, "") + : expanded; + const info = yield* fs.stat(asTyped).pipe(Effect.option); + if (Option.isSome(info) && info.value.type === "File") target = asTyped; + } const targetIsFile = looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false))); let themeId: string; diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index 7bb1046199c4e..c78f8a5df9c2c 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -2,7 +2,6 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; -import * as Config from "effect/Config"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -28,84 +27,115 @@ vi.mock("node:child_process", { spy: true }); afterEach(() => vi.restoreAllMocks()); -it.live("reports failure when the Windows cleanup shell cannot start", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" }); - const runtimeDir = path.join(baseDir, "runtime"); - yield* fs.makeDirectory(runtimeDir); - vi.spyOn(BootService, "layer").mockReturnValue( - Layer.succeed( - BootService.BootService, - BootService.BootService.of({ - status: Effect.succeed({ - supported: false, - installed: false, - current: false, - unitPath: "", - logPath: "", +it.live( + "runs the Windows cleanup from System32 and reports failure when its shell cannot start", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" }); + const runtimeDir = path.join(baseDir, "runtime"); + yield* fs.makeDirectory(runtimeDir); + vi.spyOn(BootService, "layer").mockReturnValue( + Layer.succeed( + BootService.BootService, + BootService.BootService.of({ + status: Effect.succeed({ + supported: false, + installed: false, + current: false, + unitPath: "", + logPath: "", + }), + withStopped: (operation) => operation, + restart: Effect.die("unexpected restart"), + install: () => Effect.die("unexpected install"), + uninstall: Effect.die("unexpected uninstall"), }), - withStopped: (operation) => operation, - restart: Effect.die("unexpected restart"), - install: () => Effect.die("unexpected install"), - uninstall: Effect.die("unexpected uninstall"), - }), - ), - ); - const actual = yield* Effect.promise(() => - vi.importActual("node:child_process"), - ); - const spawn = actual.spawn; - const failedSpawn = new Promise((resolve) => { - vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => { - const child = spawn(...args); - // Observe the real spawn error without letting it terminate the test runner. - child.once("error", resolve); - return child; + ), + ); + const actual = yield* Effect.promise(() => + vi.importActual("node:child_process"), + ); + const spawn = actual.spawn; + const spawned: Array> = []; + const failedSpawn = new Promise((resolve) => { + vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => { + spawned.push(args); + const child = spawn(...args); + // Observe the real spawn error without letting it terminate the test runner. + child.once("error", resolve); + return child; + }); }); - }); - const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([ - "--base-dir", - baseDir, - "--yes", - ]).pipe( - Effect.result, - Effect.provideService(HostProcess.Environment, { - ComSpec: path.join(baseDir, "missing-cmd.exe"), - }), - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(HostProcess.IsExecutable, false), - Effect.provide( - Layer.mergeAll( - ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), - Layer.fresh(TestConsole.layer), + const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([ + "--base-dir", + baseDir, + "--yes", + ]).pipe( + Effect.result, + Effect.provideService(HostProcess.Environment, { + ComSpec: path.join(baseDir, "missing-cmd.exe"), + SystemRoot: String.raw`C:\Windows`, + }), + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + Layer.fresh(TestConsole.layer), + ), ), - ), - ); - yield* Effect.promise(() => failedSpawn); - expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure"); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))), + ); + yield* Effect.promise(() => failedSpawn); + expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure"); + const [, args, options] = spawned[0]!; + expect(args.at(-1)).toBe( + '""%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""', + ); + expect(options).toMatchObject({ + cwd: String.raw`C:\Windows\System32`, + env: { + T3_UNINSTALL_PING: String.raw`C:\Windows\System32\ping.exe`, + T3_UNINSTALL_RUNTIME: runtimeDir, + }, + }); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))), ); it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { - it.effect("names another home's service it leaves installed", () => + it.effect.each([ + { + label: "names another home's service it leaves installed", + otherFromRead: 1, + removed: [], + output: "--base-dir '/home/me/.t3'", + }, + { + label: "leaves a service that serves another home by the time it is removed", + otherFromRead: 2, + removed: [], + output: "Left the background service: it now serves another T3 home.", + }, + ])("$label", (input) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-cli-test-" }); const uninstalls: Array = []; + let reads = 0; vi.spyOn(BootService, "layer").mockReturnValue( Layer.succeed( BootService.BootService, BootService.BootService.of({ - status: Effect.succeed({ + status: Effect.sync(() => ({ supported: true, installed: true, current: true, installedBaseDir: "/home/me/.t3", + ...(++reads >= input.otherFromRead ? { otherBaseDir: "/home/me/.t3" } : {}), unitPath: "/home/me/.config/systemd/user/t3code.service", logPath: "/home/me/.t3/userdata/logs/boot-service.log", - }), + })), withStopped: (operation) => operation, restart: Effect.die("unexpected restart"), install: () => Effect.die("unexpected install"), @@ -133,8 +163,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall com ), ), ); - assert.deepStrictEqual(uninstalls, []); - assert.include(output, "--base-dir '/home/me/.t3'"); + assert.deepStrictEqual(uninstalls, input.removed); + assert.include(output, input.output); }), ); }); @@ -262,7 +292,7 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { }); it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( - "t3 uninstall has cmd.exe remove the runtime directory, preserving spaces and literal environment-variable syntax", + "t3 uninstall has cmd.exe remove the runtime directory with System32 tools, preserving spaces and literal environment-variable syntax", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -272,10 +302,19 @@ it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true }); yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3.exe"), ""); - const child = spawnWindowsRemoval( - yield* Config.String("ComSpec").pipe(Config.withDefault("cmd.exe")), - runtimeDir, + // The directory `t3 uninstall` is run from holds its own `ping`, which must stay unused. + const marker = path.join(root, "ping-ran.txt"); + yield* fs.writeFileString(path.join(root, "ping.cmd"), '@echo ran>"%~dp0ping-ran.txt"\r\n'); + yield* Effect.acquireRelease( + Effect.sync(() => { + const previous = process.cwd(); + process.chdir(root); + return previous; + }), + (previous) => Effect.sync(() => process.chdir(previous)), ); + + const child = spawnWindowsRemoval(yield* HostProcess.Environment, runtimeDir); yield* Effect.callback((resume) => { child.once("error", (error) => resume(Effect.fail(error))); child.once("exit", (code) => @@ -284,5 +323,6 @@ it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( }); assert.isFalse(yield* fs.exists(runtimeDir)); + assert.isFalse(yield* fs.exists(marker)); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index 5624e6c2a894c..e1f535d7cd7a6 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off // Windows cleanup must outlive this executable to delete its directory; scoped ChildProcess kills children on exit. import * as NodeChildProcess from "node:child_process"; +import * as NodePath from "node:path"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; @@ -23,6 +24,7 @@ import { import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import * as CliService from "./service.ts"; import { awaitDetachedSpawn } from "../process/windowsVerbatimSpawn.ts"; +import { windowsSystem32Path } from "@t3tools/shared/windowsSystem"; import { findWindowsShim } from "./update.ts"; export class CliUninstallError extends Schema.TaggedError()( @@ -125,19 +127,22 @@ export const findRecordedLaunchers = Effect.fn("cli.uninstall.find_recorded_laun return owned; }); -// cmd.exe needs verbatim quoting and a literal path, with delayed expansion disabled. -export function spawnWindowsRemoval(comspec: string, dir: string) { +// cmd.exe needs verbatim quoting and literal paths, with delayed expansion disabled. The shell +// starts in System32 and runs ping from there, whatever directory `t3 uninstall` was run in. +export function spawnWindowsRemoval(environment: NodeJS.ProcessEnv, dir: string) { + const ping = windowsSystem32Path(environment, "ping.exe"); return NodeChildProcess.spawn( - comspec, + environment["ComSpec"] ?? environment["COMSPEC"] ?? windowsSystem32Path(environment, "cmd.exe"), [ "/d", "/v:off", "/s", "/c", - '"ping -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""', + '""%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""', ], { - env: { ...process.env, T3_UNINSTALL_RUNTIME: dir }, + cwd: NodePath.win32.dirname(ping), + env: { ...process.env, T3_UNINSTALL_PING: ping, T3_UNINSTALL_RUNTIME: dir }, windowsVerbatimArguments: true, detached: true, stdio: "ignore", @@ -155,9 +160,7 @@ const planUninstall = Effect.fn("cli.uninstall.plan")(function* (input: { const status = yield* service.status; const installedBaseDir = status.supported && status.installed ? status.installedBaseDir : undefined; - const servesThisHome = - installedBaseDir !== undefined && - path.resolve(installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = installedBaseDir !== undefined && status.otherBaseDir === undefined; const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir); const runtimeDir = path.dirname(versionsDir); const launchedAs = (yield* HostProcess.IsExecutable) ? yield* resolveLauncherPath : undefined; @@ -258,12 +261,14 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { } } - if (plan.service) { + // The prompt can wait a long time; keep a service or launcher that changed hands meanwhile. + if (plan.service && (yield* service.status).otherBaseDir !== undefined) { + yield* Console.log("Left the background service: it now serves another T3 home."); + } else if (plan.service) { yield* service.uninstall; yield* Console.log("Removed the background service."); } for (const launcher of plan.launchers) { - // The prompt can wait a long time; never delete a file that replaced the launcher meanwhile. if (!(yield* ownsLauncher(launcher, plan.versionsDir))) { yield* Console.log(`Left ${launcher}: it no longer runs this t3.`); continue; @@ -281,12 +286,11 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { // Windows refuses to unlink this running executable; a detached shell removes it after exit. if (platform === "win32") { const runtimeDir = plan.runtimeDir; - const comspec = environment["ComSpec"] ?? environment["COMSPEC"] ?? "cmd.exe"; const notScheduled = () => new CliUninstallError({ reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, }); - yield* awaitDetachedSpawn(() => spawnWindowsRemoval(comspec, runtimeDir)).pipe( + yield* awaitDetachedSpawn(() => spawnWindowsRemoval(environment, runtimeDir)).pipe( Effect.mapError(notScheduled), ); yield* Console.log(`${runtimeDir} will be removed once t3 exits.`); diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 07f3458fb3b66..dc798afdaa4da 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -423,9 +423,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { const status = yield* service.status; // Service names are per user, so another home's unit belongs to a different install. - const servesThisHome = - status.installedBaseDir !== undefined && - path.resolve(status.installedBaseDir) === path.resolve(input.baseDir); + const servesThisHome = status.installedBaseDir !== undefined && status.otherBaseDir === undefined; const serviceInstalled = status.supported && status.installed && servesThisHome; const foreground = yield* findForegroundServer({ serverRuntimeStatePath: input.serverRuntimeStatePath, diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index ad926f2b5154d..535e2cfed313f 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -22,6 +22,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { decodeServiceUnit, disabledServiceTask, @@ -52,6 +53,8 @@ vi.mock("node:fs", async (importOriginal) => { }; }); +const SCHTASKS = "D:\\WinNT\\System32\\schtasks.exe"; + const windowsTaskOptions = { userId: "PC\\theo", homeDir: "C:\\Users\\theo", @@ -250,13 +253,13 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( command === "systemctl --user disable --now t3code.service" || command === "systemctl --user restart --no-block t3code.service" || command.startsWith("launchctl bootout --wait ") || - (input.command === "schtasks" && input.args[0] === "/End") + (input.command === SCHTASKS && input.args[0] === "/End") ) { markersAtStop.push(yield* fs.exists(marker)); } if ( command === "systemctl --user daemon-reload" || - (input.command === "schtasks" && input.args[0] === "/Create") + (input.command === SCHTASKS && input.args[0] === "/Create") ) { markersAtPreparation.push(yield* fs.exists(marker)); } @@ -275,8 +278,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( } if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; const taskMissing = - input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; - if (input.command === "schtasks" && !failed) { + input.command === SCHTASKS && input.args[0] !== "/Create" && control.task === undefined; + if (input.command === SCHTASKS && !failed) { if (input.args[0] === "/Create") { const xml = decodeServiceUnit(yield* fs.readFile(input.args[2] ?? "")); control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; @@ -317,7 +320,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( }) : input.args[0] === "--version" ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n` - : input.command === "schtasks" && input.args.includes("/XML") + : input.command === SCHTASKS && input.args.includes("/XML") ? control.task?.enabled === false ? disabledServiceTask(control.task.xml) : (control.task?.xml ?? "") @@ -396,6 +399,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( USERPROFILE: home, LOCALAPPDATA: path.join(home, "AppData", "Local"), USERDOMAIN: "PC", + windir: "D:\\WinNT", USERNAME: "theo", ...(environmentPath === undefined || environmentPath === "" ? {} @@ -1307,6 +1311,28 @@ process.disconnect(); }), ); + it.effect("treats a symlinked T3 home path as the same home", () => + Effect.gen(function* () { + const { service, fs, baseDir, commands, makeService } = yield* makeHarness(); + yield* service.install(); + const path = yield* Path.Path; + const linkDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-symlink-home-" }); + const aliasDir = path.join(linkDir, "a$$b"); + yield* fs.symlink(baseDir, aliasDir); + + const alias = yield* makeService(undefined, "1.2.3", aliasDir); + expect(yield* alias.status).toMatchObject({ current: true }); + expect((yield* alias.status).otherBaseDir).toBeUndefined(); + expect(yield* alias.restart).toBe("restarted"); + commands.length = 0; + yield* alias.withStopped(Effect.void); + expect(commands).toContain("systemctl --user stop t3code.service"); + expect((yield* alias.install()).baseDir).toBe(aliasDir); + expect(yield* service.status).toMatchObject({ current: true }); + expect((yield* service.status).otherBaseDir).toBeUndefined(); + }), + ); + it.effect("hands the whole install to systemd without changing the running service", () => Effect.gen(function* () { const { fs, commands, invocations, control, makeService } = yield* makeHarness(); @@ -1406,6 +1432,7 @@ process.disconnect(); const outcome = yield* inside.restart; expect(commands).toEqual([ "systemctl --user daemon-reload", + `/bin/sh -c ${RESTORE_OOMD_WATCH_SCRIPT}`, "systemctl --user enable t3code.service", "systemctl --user reset-failed t3code.service", "systemctl --user restart --no-block t3code.service", @@ -1557,9 +1584,9 @@ process.disconnect(); protocol: SERVICE_LAUNCHER_PROTOCOL, activeVersion: "1.2.3", }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /Run /TN t3code-PC-theo", + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual([ + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); // No launcher holds the lock here. expect(yield* service.status).toMatchObject({ @@ -1569,7 +1596,7 @@ process.disconnect(); }); // A task that Task Scheduler refuses to delete stays installed, so a retry finds it. - control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F"; + control.failCommand = `${SCHTASKS} /Delete /TN t3code-PC-theo /F`; expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); expect((yield* service.status).installed).toBe(true); control.failCommand = undefined; @@ -1577,9 +1604,9 @@ process.disconnect(); commands.length = 0; expect(yield* service.uninstall).toBe(true); expect(commands).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", - "schtasks /Delete /TN t3code-PC-theo /F", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Delete /TN t3code-PC-theo /F`, ]); expect(control.task).toBeUndefined(); expect((yield* service.status).installed).toBe(false); @@ -1619,11 +1646,11 @@ process.disconnect(); commands.length = 0; yield* service.withStopped(Effect.sync(() => commands.push("repair"))); expect(commands.filter((command) => !command.includes("/Query"))).toEqual([ - "schtasks /Change /TN t3code-PC-theo /DISABLE", - "schtasks /End /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /DISABLE`, + `${SCHTASKS} /End /TN t3code-PC-theo`, "repair", - "schtasks /Change /TN t3code-PC-theo /ENABLE", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Change /TN t3code-PC-theo /ENABLE`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]); }), ); @@ -1644,14 +1671,14 @@ process.disconnect(); const inside = yield* makeService(undefined, "1.2.4", undefined, true); const relayMarker = `${plan.baseDir}/runtime/${DESKTOP_UPDATE_RESTART_MARKER_FILE}`; const handoff = [ - `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, - "schtasks /End /TN t3code-PC-theo", - "schtasks /Run /TN t3code-PC-theo", + `${SCHTASKS} /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + `${SCHTASKS} /End /TN t3code-PC-theo`, + `${SCHTASKS} /Run /TN t3code-PC-theo`, ]; commands.length = 0; expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath }); - expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff); + expect(commands.filter((command) => command.startsWith(`${SCHTASKS} `))).toEqual(handoff); expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4"); expect( yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`), diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 4f81ec8641931..11a1978b01830 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -19,6 +19,7 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; import { serviceLauncherIsRunning, serviceLauncherLockPath, @@ -329,12 +330,21 @@ function systemdManager(input: { command: "systemctl", args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], }; - const prepareActivation = [ + const reload = [ { step: "reloading systemd user units", command: "systemctl", args: ["--user", "daemon-reload"], }, + { + step: "restoring systemd-oomd's watch on the user manager", + optional: true, + command: "/bin/sh", + args: ["-c", RESTORE_OOMD_WATCH_SCRIPT], + }, + ]; + const prepareActivation = [ + ...reload, { step: "enabling the service", command: "systemctl", @@ -388,13 +398,7 @@ function systemdManager(input: { timeout: STOP_STEP_TIMEOUT, }, ], - finalize: [ - { - step: "reloading systemd user units", - command: "systemctl", - args: ["--user", "daemon-reload"], - }, - ], + finalize: reload, }; } @@ -478,6 +482,8 @@ interface WindowsTaskSteps { readonly remove: Effect.Effect; } +const schtasksPath = (systemRoot: string) => `${systemRoot}\\System32\\schtasks.exe`; + function schtasksManager(input: { readonly path: Path.Path; readonly homeDir: string; @@ -485,13 +491,14 @@ function schtasksManager(input: { readonly steps: WindowsTaskSteps; }): BootServiceManager { const unitPath = scheduledTaskPath(input.path, input.session.localAppData); + const schtasks = schtasksPath(input.session.systemRoot); const task = ["/TN", input.session.taskName]; const register = { step: "registering the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Create", "/XML", unitPath, ...task, "/F"], }; - const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] }; + const run = { step: "starting the service", command: schtasks, args: ["/Run", ...task] }; const stop: ReadonlyArray = [ { step: "disabling the scheduled task", run: input.steps.disable }, { @@ -515,7 +522,7 @@ function schtasksManager(input: { restart: [ { step: "enabling the scheduled task", - command: "schtasks", + command: schtasks, args: ["/Change", ...task, "/ENABLE"], }, { ...run, step: "restarting the service after a failed update" }, @@ -527,7 +534,7 @@ function schtasksManager(input: { restart: [ { step: "ending the scheduled task", - command: "schtasks", + command: schtasks, args: ["/End", ...task], optional: true, }, @@ -891,7 +898,8 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { yield* windowsVariable("USERDOMAIN"), yield* windowsVariable("USERNAME"), ), - systemRoot: (yield* windowsVariable("SystemRoot")) || "C:\\Windows", + systemRoot: + (yield* windowsVariable("SystemRoot")) || (yield* windowsVariable("windir")) || "C:\\Windows", }; // The unit is per user, so the launcher to stop is the one serving the installed unit's home. const launcherLockPath = (unit: Option.Option) => @@ -899,6 +907,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir, ); const windowsTask = ["/TN", windowsSession.taskName]; + const schtasks = schtasksPath(windowsSession.systemRoot); /** Runs a command that changes the task; a task that is not registered has nothing to change. */ const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* ( step: string, @@ -907,12 +916,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const toError = (cause: unknown) => new BootServiceCommandError({ step, cause }); const changed = yield* runner - .run({ command: "schtasks", args: [verb, ...windowsTask, flag] }) + .run({ command: schtasks, args: [verb, ...windowsTask, flag] }) .pipe(Effect.mapError(toError)); if (changed.code === 0) return; const queried = yield* runner .run({ - command: "schtasks", + command: schtasks, args: ["/Query", ...windowsTask, "/HRESULT"], timeout: Duration.seconds(5), }) @@ -947,14 +956,14 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { unit: string, ) { const register = (xmlPath: string) => - runStep("registering the scheduled task", "schtasks", [ + runStep("registering the scheduled task", schtasks, [ "/Create", "/XML", xmlPath, ...windowsTask, "/F", ]); - const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]); + const registered = yield* probe(schtasks, ["/Query", ...windowsTask, "/XML"]); if ( Option.isSome(registered) && registered.value.code === 0 && @@ -977,7 +986,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // Task Scheduler then reports the task stopped at once, so the lock says when it really is. const stopWindowsLauncher = Effect.gen(function* () { const unit = yield* readUnit().pipe(Effect.option); - yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore); + yield* runner.run({ command: schtasks, args: ["/End", ...windowsTask] }).pipe(Effect.ignore); yield* Effect.tryPromise({ try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal), catch: (cause) => @@ -1020,12 +1029,15 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { let { manager: detectedManager, unitPath, plan } = resolveTarget(systemdUnitDir); const statePath = path.join(input.baseDir, "runtime", SERVICE_STATE_FILE); const restartPendingPath = path.join(input.baseDir, "runtime", SERVICE_RESTART_PENDING_FILE); + const canonicalPath = (dir: string) => + fs.realPath(dir).pipe(Effect.orElseSucceed(() => path.resolve(dir))); + const isThisHome = (dir: string) => + Effect.zipWith(canonicalPath(dir), canonicalPath(input.baseDir), (a, b) => a === b); const otherBaseDirOf = (unit: string) => { const installedBaseDir = bootServiceBaseDirOf(unit); - return installedBaseDir !== undefined && - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ? installedBaseDir - : undefined; + return installedBaseDir === undefined + ? Effect.undefined + : Effect.map(isThisHome(installedBaseDir), (same) => (same ? undefined : installedBaseDir)); }; const writeDurably = (filePath: string, contents: string | Uint8Array) => Effect.scoped( @@ -1208,7 +1220,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ) { const [task, running] = yield* Effect.all( [ - probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]), + probe(schtasks, ["/Query", "/TN", windowsSession.taskName, "/XML"]), Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))), ], { concurrency: "unbounded" }, @@ -1257,7 +1269,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const refuseOtherBaseDir = Effect.gen(function* () { const existingUnit = yield* readUnit().pipe(Effect.option); const installedBaseDir = Option.isSome(existingUnit) - ? otherBaseDirOf(existingUnit.value) + ? yield* otherBaseDirOf(existingUnit.value) : undefined; if (installedBaseDir !== undefined) { return yield* new BootServiceOtherBaseDirError({ @@ -1487,10 +1499,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return "skipped" as const; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return "skipped" as const; } // Writes no state, and the launcher lets an update transition in flight @@ -1520,10 +1529,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = yield* readUnit().pipe(Effect.option); if (Option.isNone(unit)) return yield* operation; const installedBaseDir = bootServiceBaseDirOf(unit.value); - if ( - installedBaseDir === undefined || - path.resolve(installedBaseDir) !== path.resolve(input.baseDir) - ) { + if (installedBaseDir === undefined || !(yield* isThisHome(installedBaseDir))) { return yield* operation; } // `is-active` misses crash-looping systemd units; launchd can be loaded without a pid. @@ -1603,7 +1609,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? serviceStateActiveVersion(stateText.value) : undefined; const installedBaseDir = bootServiceBaseDirOf(unit); - const otherBaseDir = otherBaseDirOf(unit); + const otherBaseDir = yield* otherBaseDirOf(unit); + // Another spelling of this home is current; repairing it would flip the unit between spellings. + const thisHomeUnit = + installedBaseDir !== undefined && otherBaseDir === undefined + ? unit.replaceAll(installedBaseDir, () => input.baseDir) + : unit; const normalizeUnit = (contents: string) => manager.kind === "launchd" ? contents.replace(/(PATH<\/key>\n\s*)[^<]*(<\/string>)/, "$1$2") @@ -1625,7 +1636,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { current: problems.length === 0 && !(manager.kind === "systemd" && systemdUnsafeValue(planForUnit(unit))) && - normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && + normalizeUnit(thisHomeUnit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && runtimeSentinel.value.trim() === input.cliVersion && diff --git a/apps/server/src/cloud/http.test.ts b/apps/server/src/cloud/http.test.ts index 5115a27e63012..852be24a22200 100644 --- a/apps/server/src/cloud/http.test.ts +++ b/apps/server/src/cloud/http.test.ts @@ -31,6 +31,7 @@ import * as AuthHttp from "../auth/http.ts"; import * as ServerSecretStore from "../auth/ServerSecretStore.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as ServerHttp from "../http.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as AgentAwarenessRelay from "../relay/AgentAwarenessRelay.ts"; import * as CliTokenManager from "./CliTokenManager.ts"; @@ -78,6 +79,7 @@ const layerConfig = Layer.effect( const layerLinkProofRoutes = HttpApiBuilder.layer(LinkProofTestApi).pipe( Layer.provide([AuthHttp.layer, ConnectHttp.layer]), Layer.provide(AuthHttp.layerAuthenticatedAuth), + Layer.provide(ServerHttp.layerApiBodyLimit), Layer.provide(CloudLink.layer), Layer.provide(ServerSettings.ServerSettingsService.layerTest()), Layer.provide(EnvironmentKeys.layer), @@ -303,4 +305,14 @@ describe("link proof over a non-loopback transport", () => { expect(response.status).toBe(401); }), ); + + it.effect("answers 413 to a relay proof body over the API limit", () => + Effect.gen(function* () { + const { post } = yield* linkProofClient; + const payload = { proof: "x".repeat(ServerHttp.API_MAX_BODY_BYTES) }; + for (const path of ["/api/t3-connect/health", "/api/t3-connect/mint-credential"]) { + expect((yield* post(path, payload)).status, path).toBe(413); + } + }), + ); }); diff --git a/apps/server/src/cloud/pinnedRuntime.ts b/apps/server/src/cloud/pinnedRuntime.ts index e544852ef3dcc..06e320bc314ad 100644 --- a/apps/server/src/cloud/pinnedRuntime.ts +++ b/apps/server/src/cloud/pinnedRuntime.ts @@ -25,6 +25,7 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import * as ProcessRunner from "../processRunner.ts"; +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; import { isExactServiceVersion, parseServiceState, SERVICE_STATE_FILE } from "./serviceProtocol.ts"; const PINNED_RUNTIME_DIR = "runtime"; @@ -792,7 +793,7 @@ const runningExecutables = Effect.fn("cloud.pinned_runtime.running_executables") .run({ ...(platform === "win32" ? { - command: "powershell.exe", + command: windowsPowerShellPath(yield* HostProcess.Environment), args: [ "-NoProfile", "-NonInteractive", diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 85661360020f6..1a98b7b2703f5 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -6,6 +6,7 @@ import * as PlatformError from "effect/PlatformError"; import { assert, expect, it } from "@effect/vitest"; 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 { @@ -83,11 +84,42 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( }; const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending }); host.env["HOME"] = root; - const client = yield* makeClient(host, "1.1.0"); + // The launcher reloads the user manager after commit, so oomd's watch must already be mirrored. + const bin = path.join(root, "bin"); + const calls = path.join(root, "systemctl-calls"); + yield* fs.makeDirectory(bin); + yield* fs.writeFileString( + path.join(bin, "systemctl"), + [ + "#!/bin/sh", + `echo "$*" >>'${calls}'`, + 'case "$*" in', + " *ControlGroup*) echo /user.slice/user-1000.slice/user@1000.service ;;", + " *ManagedOOMMemoryPressureLimit*) echo 0 ;;", + " *ManagedOOMMemoryPressure\\ *) echo kill ;;", + "esac", + "", + ].join("\n"), + ); + yield* fs.chmod(path.join(bin, "systemctl"), 0o755); + host.env["PATH"] = `${bin}:/usr/bin:/bin`; + const sentPrepared = yield* Deferred.make(); + const send = host.send; + host.send = (message, callback) => { + Deferred.doneUnsafe(sentPrepared, Effect.void); + return send(message, callback); + }; + const client = yield* makeClient(host, "1.1.0").pipe( + Effect.provideService(HostProcess.Platform, "linux"), + ); const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), { startImmediately: true, }); - yield* Effect.yieldNow; + yield* Deferred.await(sentPrepared); + // Nothing runs systemctl after "prepared", so the log is what ran before it. + expect(yield* fs.readFileString(calls)).toContain( + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill", + ); expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]); assert.equal(yield* fs.readLink(installed), exe("1.0.0")); @@ -327,8 +359,13 @@ it.layer(NodeServices.layer)("self-update launchers", (it) => { ); it.effect.each([ - { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, - { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + // The working-directory t3 is checked by its execute bits, which Windows hosts do not set. + ...(HostProcess.Platform.defaultValue() === "win32" + ? [] + : [ + { name: "leading", searchPath: (missing: string) => `:${missing}`, moved: true }, + { name: "trailing", searchPath: (missing: string) => `${missing}:`, moved: true }, + ]), { name: "whole", searchPath: () => "", moved: false }, ])("treats a $name empty PATH entry like the shell does", ({ searchPath, moved }) => Effect.gen(function* () { diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index 3e7f4abfc2d57..50b596b0e30d5 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -8,6 +8,8 @@ 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 ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import packageJson from "../../package.json" with { type: "json" }; import { @@ -24,6 +26,7 @@ import { type ServiceLauncherParentMessage, type SupportedLauncherProtocol, } from "./serviceProtocol.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; export class ServiceLauncherClientError extends Schema.TaggedError()( "ServiceLauncherClientError", @@ -264,6 +267,22 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o const path = yield* Path.Path; const environment = yield* HostProcess.Environment; const platform = yield* HostProcess.Platform; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // The launcher that commits a remote update is the old one; its reload after commit + // keeps oomd's watch only if the policy is mirrored before it. + const keepOomdWatch = + platform === "linux" + ? spawner + .exitCode( + ChildProcess.make("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + env: environment, + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + }), + ) + .pipe(Effect.timeout("30 seconds"), Effect.ignore) + : Effect.void; const exchange = ( message: ServiceLauncherChildMessage, @@ -343,28 +362,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o : context.update; const prepareTrial = (input: { readonly baseDir: string }) => pending !== undefined - ? exchange( - { type: "prepared", updateId: pending.id }, - (reply) => reply.type === "committed" && reply.updateId === pending.id, - ).pipe( - Effect.flatMap((reply) => - reply.type !== "committed" - ? Effect.die("service launcher returned an impossible prepared response") - : repointLaunchers({ - baseDir: input.baseDir, - targetVersion: pending.targetVersion, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fs), - Effect.provideService(Path.Path, path), - Effect.provideService(HostProcess.Environment, environment), - Effect.provideService(HostProcess.Platform, platform), - Effect.as({ - id: pending.id, - fromVersion: pending.fromVersion, + ? Effect.andThen( + keepOomdWatch, + exchange( + { type: "prepared", updateId: pending.id }, + (reply) => reply.type === "committed" && reply.updateId === pending.id, + ).pipe( + Effect.flatMap((reply) => + reply.type !== "committed" + ? Effect.die("service launcher returned an impossible prepared response") + : repointLaunchers({ + baseDir: input.baseDir, targetVersion: pending.targetVersion, - status: "committed" as const, - }), - ), + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, platform), + Effect.as({ + id: pending.id, + fromVersion: pending.fromVersion, + targetVersion: pending.targetVersion, + status: "committed" as const, + }), + ), + ), ), ) : Effect.succeed(outcome); diff --git a/apps/server/src/cloud/serviceProtection.ts b/apps/server/src/cloud/serviceProtection.ts index 48790bcf6cc05..a8952ce299fd9 100644 --- a/apps/server/src/cloud/serviceProtection.ts +++ b/apps/server/src/cloud/serviceProtection.ts @@ -8,6 +8,7 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as ProcessRunner from "../processRunner.ts"; import { BOOT_SERVICE_UNIT_FILE } from "./bootService.ts"; +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; const PROTECT_DROP_IN = "90-t3code-protect.conf"; const SYSTEM_UNIT_DIR = "/etc/systemd/system"; @@ -210,10 +211,12 @@ export const detectRemoteAccessUnits = run("list remote-access services", "syste Effect.withSpan("ServiceProtection.detectRemoteAccessUnits"), ); -const reloadUserManager = run("reload systemd user units", "systemctl", [ - "--user", - "daemon-reload", -]); +const reloadUserManager = Effect.andThen( + run("reload systemd user units", "systemctl", ["--user", "daemon-reload"]), + run("restore systemd-oomd's watch", "/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT]).pipe( + Effect.ignore, + ), +); const writeDropIns = Effect.fn("ServiceProtection.writeDropIns")(function* ( dropIns: ReadonlyArray, diff --git a/apps/server/src/cloud/userManagerOom.test.ts b/apps/server/src/cloud/userManagerOom.test.ts new file mode 100644 index 0000000000000..67c0e51e11639 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.test.ts @@ -0,0 +1,72 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { expect, it } from "vite-plus/test"; + +import { RESTORE_OOMD_WATCH_SCRIPT } from "./userManagerOom.ts"; + +const userService = "/user.slice/user-1001.slice/user@1001.service"; + +it.each([ + [ + "mirrors the system manager's kill policy onto the user manager's root slice", + { cgroup: userService, mode: "kill", limit: "4252017622", duration: "" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=99.00%", + ], + [ + "keeps a custom duration and an unset limit", + { cgroup: userService, mode: "kill", limit: "0", duration: "20s" }, + "--user set-property --runtime -- -.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=0.00% ManagedOOMMemoryPressureDurationSec=20s", + ], + [ + "leaves the slice alone when oomd is not told to kill", + { cgroup: userService, mode: "auto", limit: "0", duration: "infinity" }, + undefined, + ], + [ + "leaves the slice alone outside a user@ service", + { cgroup: "/system.slice/foo.service", mode: "kill", limit: "0", duration: "infinity" }, + undefined, + ], +])("%s", (_name, system, expected) => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-oomd-")); + try { + const calls = NodePath.join(root, "calls"); + NodeFS.writeFileSync( + NodePath.join(root, "systemctl"), + [ + "#!/bin/sh", + 'echo "$*" >>"$CALLS"', + 'case "$*" in', + ' *ControlGroup*) echo "$CGROUP" ;;', + ' *ManagedOOMMemoryPressureLimit*) echo "$LIMIT" ;;', + ' *ManagedOOMMemoryPressureDurationUSec*) echo "$DURATION" ;;', + ' *ManagedOOMMemoryPressure\\ *) echo "$MODE" ;;', + "esac", + "", + ].join("\n"), + { mode: 0o755 }, + ); + const result = NodeChildProcess.spawnSync("/bin/sh", ["-c", RESTORE_OOMD_WATCH_SCRIPT], { + encoding: "utf8", + env: { + PATH: `${root}:/usr/bin:/bin`, + CALLS: calls, + CGROUP: system.cgroup, + MODE: system.mode, + LIMIT: system.limit, + DURATION: system.duration, + }, + }); + expect(result.stderr).toBe(""); + expect(result.status).toBe(0); + const setProperty = NodeFS.readFileSync(calls, "utf8") + .split("\n") + .find((call) => call.includes("set-property")); + expect(setProperty).toBe(expected); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/apps/server/src/cloud/userManagerOom.ts b/apps/server/src/cloud/userManagerOom.ts new file mode 100644 index 0000000000000..6f23427b83999 --- /dev/null +++ b/apps/server/src/cloud/userManagerOom.ts @@ -0,0 +1,22 @@ +/** + * Run after `systemctl --user daemon-reload`. The user manager's -.slice shares the cgroup of + * user@.service and reports it to systemd-oomd as `auto` on reload, which drops the system + * manager's `kill` watch (systemd/systemd#43174). Mirroring that policy onto -.slice restores the + * watch and keeps it through later reloads. Best effort: exits 0 when there is nothing to mirror. + */ +export const RESTORE_OOMD_WATCH_SCRIPT = [ + "unit=$(systemctl --user show --property=ControlGroup --value -- -.slice) || exit 0", + "unit=${unit##*/}", + "case $unit in user@*.service) ;; *) exit 0 ;; esac", + 'show() { systemctl show --property="$1" --value "$unit"; }', + '[ "$(show ManagedOOMMemoryPressure)" = kill ] || exit 0', + "limit=$(show ManagedOOMMemoryPressureLimit)", + "case $limit in '' | *[!0-9]*) exit 0 ;; esac", + // The limit is a fraction of 2^32; set-property takes a percentage. + "p=$(( (limit * 10000 + 2147483648) / 4294967296 ))", + 'set -- ManagedOOMMemoryPressure=kill "ManagedOOMMemoryPressureLimit=$((p / 100)).$(printf %02d $((p % 100)))%"', + "duration=$(show ManagedOOMMemoryPressureDurationUSec)", + 'case $duration in "" | infinity) ;; *) set -- "$@" "ManagedOOMMemoryPressureDurationSec=$duration" ;; esac', + 'exec systemctl --user set-property --runtime -- -.slice "$@"', + "", +].join("\n"); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 9076aadd47381..c1ee36ea1c485 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -100,6 +100,7 @@ export class ServerConfig extends Context.Service< readonly startupPresentation: StartupPresentation; readonly desktopBootstrapToken: string | undefined; readonly desktopBootstrapSecret?: string | undefined; + readonly desktopReadinessSecret?: string | undefined; readonly shellEnvironmentPrepared?: boolean | undefined; readonly desktopTelemetryFd?: number | undefined; readonly desktopTelemetryControlFd?: number | undefined; diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.ts index 898b028c4329c..aaf858cecbcad 100644 --- a/apps/server/src/device/DeviceHost.ts +++ b/apps/server/src/device/DeviceHost.ts @@ -67,6 +67,8 @@ export class AgentDeviceStartError extends Schema.TaggedError export const makeDeviceHubOperations = (options: { readonly hostId: DeviceHostId; readonly origin: string; + readonly token?: string | undefined; readonly http: HttpClient.HttpClient; readonly run: DeviceHostReady["run"]; /** Android gates listing AVDs, which the hub does not report until they boot. */ readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect; }): DeviceOperations => { const { hostId, origin, run } = options; - const httpClient = options.http.pipe(HttpClient.withScope); + const { token } = options; + const httpClient = ( + token === undefined + ? options.http + : options.http.pipe(HttpClient.mapRequest(HttpClientRequest.bearerToken(token))) + ).pipe(HttpClient.withScope); const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* ( request: HttpClientRequest.HttpClientRequest, @@ -290,11 +299,26 @@ export const makeDeviceHubOperations = (options: { ? attachIosStream(device.id, "open").pipe(Effect.asVoid) : Effect.void; + // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an + // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer + // lists its serial in any state. + const emulatorExited = (serial: string) => + /^emulator-\d+$/.test(serial) + ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe( + Effect.map( + ({ code, stdout }) => + code === 0 && + !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial), + ), + Effect.orElseSucceed(() => false), + ) + : Effect.succeed(false); + const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")( function* (device) { - const postShutdown = (path: string, body: Record) => + const postShutdown = (path: string, body: Record, timeout?: Duration.Input) => postJson(path, body, "shutdown").pipe( - Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")), + Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)), Effect.flatMap((result) => result.ok ? Effect.void @@ -323,7 +347,23 @@ export const makeDeviceHubOperations = (options: { ), ), ) - : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id }); + : postShutdown( + "/api/devices/shutdown", + { platform: device.platform, id: device.id }, + ANDROID_SHUTDOWN_TIMEOUT, + ).pipe( + Effect.catch((cause) => + emulatorExited(device.id).pipe( + Effect.flatMap((exited) => + exited + ? Effect.logInfo("Android emulator has exited", { + deviceId: device.id, + }) + : Effect.fail(cause), + ), + ), + ), + ); }, ); diff --git a/apps/server/src/device/DeviceHubProxy.test.ts b/apps/server/src/device/DeviceHubProxy.test.ts index d7fee1a2271df..ef4ebd0372034 100644 --- a/apps/server/src/device/DeviceHubProxy.test.ts +++ b/apps/server/src/device/DeviceHubProxy.test.ts @@ -44,7 +44,14 @@ const fixture = ( if (fail) return yield* Effect.die(new Error("upstream failed")); return HttpClientResponse.fromWeb( request, - new Response(stream ?? "frame", { headers: { "set-cookie": "upstream=1" } }), + new Response(stream ?? "frame", { + headers: { + "set-cookie": "upstream=1", + "clear-site-data": '"*"', + "content-type": "text/html", + "content-security-policy": "script-src *", + }, + }), ); }), ); @@ -69,7 +76,7 @@ const fixture = ( Effect.succeed({ hostId: hostId ?? LOCAL_DEVICE_HOST_ID, nodePath: "node", - hub: { origin: "http://hub.test" }, + hub: { origin: "http://hub.test", token: "hub-token" }, devices: { list: unexpectedOperation, boot: () => unexpectedOperation, @@ -122,6 +129,11 @@ describe("device hub proxy", () => { ); expect(response.status).toBe(200); expect(await response.text()).toBe("frame"); + expect(response.headers.get("set-cookie")).toBeNull(); + expect(response.headers.get("clear-site-data")).toBeNull(); + // Opened as a page, a hub response gets an opaque origin and no script. + expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox"); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); expect(requests).toEqual(["http://hub.test/api/devices"]); expect(finalized()).toBe(1); }); @@ -214,6 +226,7 @@ describe("device hub proxy", () => { await response.text(); expect(headers).toHaveLength(1); expect(headers[0]?.origin).toBe("http://hub.test"); + expect(headers[0]?.authorization).toBe("Bearer hub-token"); expect(headers[0]).not.toHaveProperty("x-forwarded-proto"); }); diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 9778cf084b017..90c5743a26050 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -164,11 +164,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const headers: Record = {}; for (const [name, value] of Object.entries(response.headers)) { // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. + // Clear-Site-Data likewise applies to the origin that serves it. if ( name === "content-encoding" || name === "transfer-encoding" || name === "connection" || - name === "set-cookie" + name === "set-cookie" || + name === "clear-site-data" ) { continue; } @@ -176,6 +178,9 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( } // Long-lived MJPEG and AVCC responses must not be buffered by compression. headers["cache-control"] = "no-store, no-transform"; + // Hub responses are data and streams; none renders as a page on this origin. + headers["x-content-type-options"] = "nosniff"; + headers["content-security-policy"] = "default-src 'none'; sandbox"; const body = headers["content-type"]?.startsWith("multipart/x-mixed-replace") ? repeatStillFrame(response.stream) : response.stream; @@ -245,18 +250,21 @@ const handler = Effect.gen(function* () { return HttpServerResponse.text("Not Found", { status: 404 }); } const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`; + const upstreamHeaders = + routed?.headers ?? + (ready.hub.token === undefined ? undefined : { authorization: `Bearer ${ready.hub.token}` }); if (upgrade) { return yield* Effect.raceFirst( proxyWebSocket( request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols, - routed?.headers, + upstreamHeaders, ), invalidated.pipe(Effect.as(HttpServerResponse.empty())), ); } - return yield* proxyHttp(request, upstreamUrl, invalidated, routed?.headers); + return yield* proxyHttp(request, upstreamUrl, invalidated, upstreamHeaders); }); export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler); diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 00e942f1e6df5..972a9a2b150b2 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -18,6 +18,7 @@ import { SshCommandError } from "@t3tools/ssh/errors"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; @@ -192,7 +193,14 @@ const fixture = Effect.fn("fixture")(function* ( const listing = { hangs: false, requested: yield* Deferred.make() }; let booted = false; let shutDown = false; - const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false }; + const connection = { + online: true, + kind: "local" as "local" | "ssh", + failShutdown: false, + shutdownDelay: undefined as Duration.Input | undefined, + adbDevices: undefined as { code: number; stdout: string; stderr: string } | undefined, + }; + const shutdownRequested = yield* Deferred.make(); const http = HttpClient.make((request) => Effect.gen(function* () { requests.push(request.url); @@ -230,6 +238,8 @@ const fixture = Effect.fn("fixture")(function* ( return HttpClientResponse.fromWeb(request, new Response(yield* Ref.get(screenshotBody))); } if (request.url.endsWith("/shutdown")) { + yield* Deferred.succeed(shutdownRequested, undefined); + if (connection.shutdownDelay !== undefined) yield* Effect.sleep(connection.shutdownDelay); if (connection.failShutdown) return HttpClientResponse.fromWeb(request, Response.json({ ok: false })); shutDown = true; @@ -283,10 +293,19 @@ const fixture = Effect.fn("fixture")(function* ( ); }), ); - const run = (command: string) => + const run = (command: string, args: ReadonlyArray) => command === "emulator" ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }) - : Ref.get(encoderResult); + : command === "adb" && args.join(" ") === "devices" + ? Effect.sync( + () => + connection.adbDevices ?? { + code: 0, + stdout: `List of devices attached\n${booted ? "emulator-5554\tdevice\n" : ""}`, + stderr: "", + }, + ) + : Ref.get(encoderResult); const ready: DeviceHost.DeviceHostReady = { nodePath: process.execPath, hub: { origin: "http://device.test" }, @@ -426,6 +445,7 @@ const fixture = Effect.fn("fixture")(function* ( iosAvailable, listing, endDevice, + shutdownRequested, }; }); @@ -1574,6 +1594,66 @@ it.effect.each([ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); +describe("Android close with shutdown", () => { + const openEmulator = Effect.fn("openEmulator")(function* () { + const harness = yield* fixture(); + yield* harness.service.configure({ enabled: true }); + const threadId = ThreadId.make("android-close"); + const session = yield* harness.service.open({ + threadId, + deviceId: "Pixel_API_35", + platform: "android", + }); + expect(session.deviceId).toBe("emulator-5554"); + return { ...harness, threadId }; + }); + + it.effect("closes the session on a retry once the emulator has exited", () => + Effect.gen(function* () { + const { service, connection, endDevice, threadId } = yield* openEmulator(); + // The hub's `adb emu kill` fails once the serial is gone, so every attempt is rejected. + connection.failShutdown = true; + const first = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(first)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + + endDevice(); + yield* service.close({ threadId, shutdown: true }); + expect((yield* service.state).sessions).toEqual([]); + }), + ); + + it.effect.each([ + { + adb: "lists it offline", + result: { code: 0, stdout: "List of devices attached\nemulator-5554\toffline\n", stderr: "" }, + }, + { adb: "fails", result: { code: 1, stdout: "", stderr: "adb: no server" } }, + ])("keeps the session after a rejected shutdown when adb $adb", ({ result }) => + Effect.gen(function* () { + const { service, connection, threadId } = yield* openEmulator(); + connection.failShutdown = true; + connection.adbDevices = result; + const exit = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(exit)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + }), + ); + + it.effect("waits for an emulator the hub takes longer than 15 seconds to see exit", () => + Effect.gen(function* () { + const { service, connection, shutdownRequested, threadId } = yield* openEmulator(); + // The hub allows the emulator 30 seconds to leave adb after the kill. + connection.shutdownDelay = Duration.seconds(25); + const closing = yield* Effect.forkChild(service.close({ threadId, shutdown: true })); + yield* Deferred.await(shutdownRequested); + yield* TestClock.adjust(Duration.seconds(25)); + expect(Exit.isSuccess(yield* Fiber.await(closing))).toBe(true); + expect((yield* service.state).sessions).toEqual([]); + }), + ); +}); + it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( "retains hub inventory on %s when AVD enumeration fails and recovers on retry", (hostId) => diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index c1bbcbc347ea0..320aa8daf545c 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -55,6 +55,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( cameraHelp: "", cameraProbes: 0, spawnedEnvironments: [] as Array, + spawnedArgs: [] as Array>, }; const daemonStopRequested = yield* Deferred.make>(); const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata")); @@ -93,22 +94,25 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ) : Effect.addFinalizer(() => hub.cleanup).pipe( Effect.tap(() => - Effect.sync(() => - hub.spawnedEnvironments.push( + Effect.sync(() => { + if (command._tag === "StandardCommand") hub.spawnedArgs.push(command.args); + return hub.spawnedEnvironments.push( ( command as unknown as { readonly options: { readonly env?: NodeJS.ProcessEnv }; } ).options.env, - ), - ), + ); + }), ), Effect.as( ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(123), stdout: Stream.empty, stderr: Stream.empty, - all: Stream.empty, + all: Stream.encodeText( + Stream.make(" Local: http://localhost:1/?token=hub-token\n"), + ), exitCode: Effect.never, isRunning: Effect.sync(() => hub.running), kill: () => Effect.void, @@ -190,6 +194,82 @@ describe("AgentDevice startup", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + // regression: #41190 a daemon left by the previous pin keeps answering /health + it.effect("hands a daemon recorded at another agent-device version to the pinned client", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const previous = { httpPort: 12345, token: "previous-token", version: "0.21.36" }; + const { host, runs } = yield* agentFixture( + (stateDir) => + fs + .writeFileString( + `${stateDir}/daemon.json`, + JSON.stringify({ + httpPort: 23456, + token: "next-token", + version: AGENT_DEVICE_VERSION, + }), + ) + .pipe(Effect.orDie, Effect.as(processOutput(0))), + processOutput(0), + previous, + ); + const ready = yield* host.ensureAgentReady(() => Effect.void); + expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1); + expect(ready.agentDevice).toMatchObject({ + baseUrl: "http://127.0.0.1:23456", + token: "next-token", + }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps a busy daemon from another version that the pinned client leaves running", () => + Effect.gen(function* () { + const previous = { httpPort: 12345, token: "previous-token", version: "0.21.36" }; + const { host, runs } = yield* agentFixture( + () => Effect.succeed(processOutput(1)), + processOutput(0), + previous, + ); + const ready = yield* host.ensureAgentReady(() => Effect.void); + expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1); + expect(ready.agentDevice).toMatchObject({ + baseUrl: "http://127.0.0.1:12345", + token: "previous-token", + }); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reports a stopped daemon a failed replacement left registered", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + let health: Ref.Ref | undefined; + const previous = { + httpPort: 12345, + token: "previous-token", + pid: process.pid, + version: "0.21.36", + }; + const { host, stateDir, runs, daemonHealthy } = yield* agentFixture( + () => (health ? Ref.set(health, false) : Effect.void).pipe(Effect.as(processOutput(1))), + processOutput(0), + previous, + ); + health = daemonHealthy; + const error = yield* host.ensureAgentReady(() => Effect.void).pipe(Effect.flip); + expect(runs.filter((run) => run.args.includes("devices"))).toHaveLength(1); + expect(error).toMatchObject({ + _tag: "AgentDeviceStartError", + reason: "command_failed", + exitCode: 1, + }); + expect(yield* fs.readFileString(path.join(stateDir, "daemon.json"))).toContain( + previous.token, + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("uses the SDK a later shell environment selects", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -384,6 +464,18 @@ describe("AgentDevice startup", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + it.effect("starts the hub requiring a session token and keeps the one it prints", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const { host, hub, baseDir } = yield* agentFixture(() => Effect.succeed(processOutput(0))); + expect(hub.spawnedArgs[0]).toContain("--require-token"); + expect(hub.spawnedEnvironments[0]?.EXPO_DEVICE_HUB_STATE_DIR).toBe( + path.join(baseDir, "userdata", "device", "hub"), + ); + expect((yield* host.current)?.hub.token).toBe("hub-token"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + it.effect("keeps releasing agent sessions while a dead hub fails to restart and after", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index d7443d1a4b88b..7fd2816e3c17c 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -17,6 +17,7 @@ import { import * as NetService from "@t3tools/shared/Net"; import { isCommandAvailable } from "@t3tools/shared/shell"; 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 Exit from "effect/Exit"; @@ -53,6 +54,7 @@ import { } from "./DeviceToolchain.ts"; const HUB_READY_TIMEOUT_MS = 30_000; +const HUB_TOKEN_PATTERN = /\btoken=([\w.~-]+)/; const DAEMON_READY_TIMEOUT_MS = 30_000; const DAEMON_POLL_MS = 100; const HUB_RESTART_STABLE_UPTIME_MS = 60_000; @@ -93,6 +95,7 @@ interface HubProcess { readonly child: ChildProcessSpawner.ChildProcessHandle; readonly scope: Scope.Closeable; readonly origin: string; + readonly token: string; readonly startedAtMillis: number; readonly emulatorExtraArgs: string | undefined; readonly emulatorStamp: string | undefined; @@ -430,6 +433,9 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { yield* fs .makeDirectory(agentDeviceStateDir(path, config.stateDir), { recursive: true }) .pipe(Effect.ignore); + // The hub records its token in this folder, kept with the rest of the server's state. + const hubStateDir = path.join(config.stateDir, "device", "hub"); + yield* fs.makeDirectory(hubStateDir, { recursive: true, mode: 0o700 }).pipe(Effect.ignore); const port = yield* net.reserveLoopbackPort("127.0.0.1").pipe( Effect.mapError( (cause) => @@ -454,6 +460,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { String(port), "--host", "127.0.0.1", + // Only the server, which reads the token the hub prints, talks to the hub. + "--require-token", "--hide-sidebar", "--hide-boot-device", ...hubPlatformArguments(hostPlatform), @@ -464,7 +472,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { shell: false, stdout: "pipe", stderr: "pipe", - env, + env: { ...env, EXPO_DEVICE_HUB_STATE_DIR: hubStateDir }, }, ), ) @@ -480,16 +488,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ), ); const startedAtMillis = yield* Clock.currentTimeMillis; - const hub: HubProcess = { - child, - scope, - origin, - startedAtMillis, - nodePath, - emulatorExtraArgs: env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS, - emulatorStamp: stamp, - }; - yield* Effect.forkIn(observeHubOutput(hub), scope); + const announcedToken = yield* Deferred.make(); + yield* Effect.forkIn(observeHubOutput(child, announcedToken), scope); yield* waitForHttpReady({ baseUrl: origin, path: "/readyz", @@ -501,21 +501,56 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { cause: info.cause, }), }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)); + const token = yield* Deferred.await(announcedToken).pipe( + Effect.timeoutOrElse({ + duration: Duration.millis(HUB_READY_TIMEOUT_MS), + orElse: () => + Effect.fail( + new DeviceHost.DeviceHostError({ + hostId, + step: "reading the device hub's session token", + cause: new Error("The device hub did not print a session token."), + }), + ), + }), + ); + const hub: HubProcess = { + child, + scope, + origin, + token, + startedAtMillis, + nodePath, + emulatorExtraArgs: env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS, + emulatorStamp: stamp, + }; yield* recordHub(hub, hubTool); yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port }); return hub; }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore))); }); - const observeHubOutput = (hub: HubProcess) => - hub.child.all.pipe( + // The hub generates its session token and prints it in its startup link; keep it out of logs. + const observeHubOutput = ( + child: ChildProcessSpawner.ChildProcessHandle, + announcedToken: Deferred.Deferred, + ) => + child.all.pipe( Stream.decodeText(), Stream.splitLines, Stream.map((line) => line.trim()), Stream.filter((line) => line.length > 0), - Stream.runForEach((line) => - Effect.logDebug("Device hub output", { pid: Number(hub.child.pid), output: line }), - ), + Stream.runForEach((line) => { + const token = HUB_TOKEN_PATTERN.exec(line)?.[1]; + return (token === undefined ? Effect.void : Deferred.succeed(announcedToken, token)).pipe( + Effect.andThen( + Effect.logDebug("Device hub output", { + pid: Number(child.pid), + output: line.replace(HUB_TOKEN_PATTERN, "token="), + }), + ), + ); + }), Effect.ignoreCause, ); @@ -590,19 +625,25 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { token: file.token, entryPath: agentTool.entryPath, }); - if (existing._tag === "Some") { - const alive = yield* HttpClient.withScope(httpClient) - .get(`http://127.0.0.1:${existing.value.httpPort}/health`) + const daemonAnswersHealth = (httpPort: number) => + HttpClient.withScope(httpClient) + .get(`http://127.0.0.1:${httpPort}/health`) .pipe( - Effect.timeout(Duration.seconds(2)), Effect.flatMap((response) => response.arrayBuffer.pipe(Effect.as(response.status === 200)), ), + Effect.timeout(Duration.seconds(2)), Effect.scoped, Effect.orElseSucceed(() => false), ); - if (alive) return toEndpoint(existing.value); - yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore); + if (existing._tag === "Some") { + const alive = yield* daemonAnswersHealth(existing.value.httpPort); + const samePin = + existing.value.version === undefined || existing.value.version === AGENT_DEVICE_VERSION; + if (alive && samePin) return toEndpoint(existing.value); + // A live daemon from another pin may speak another RPC protocol. Keep its registration so + // the pinned CLI retires it, which that CLI does only while the daemon holds no work. + if (!alive) yield* fs.remove(daemonFilePath(), { force: true }).pipe(Effect.ignore); } // No `daemon start` exists; `devices` is the cheapest command that starts and awaits it. const runResult = yield* runner @@ -614,9 +655,16 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { timeoutBehavior: "timedOutResult", }) .pipe(Effect.result); - // Discovery may fail after startup; accept a published endpoint or preserve the CLI failure. + // A failed run can stop the previous daemon and leave its file. Keep that registration + // only while it still answers; a successful run has published the endpoint it reached. const started = yield* readDaemonFile().pipe(Effect.option); - if (started._tag === "Some") return toEndpoint(started.value); + if (started._tag === "Some") { + const runSucceeded = + runResult._tag === "Success" && !runResult.success.timedOut && runResult.success.code === 0; + if (runSucceeded || (yield* daemonAnswersHealth(started.value.httpPort))) { + return toEndpoint(started.value); + } + } if (runResult._tag === "Failure") { return yield* new DeviceHost.DeviceHostError({ hostId, @@ -892,10 +940,14 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ); const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({ - hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint, + hub: { + origin: running.hub.origin, + token: running.hub.token, + } satisfies DeviceHost.DeviceHubEndpoint, devices: makeDeviceHubOperations({ hostId, origin: running.hub.origin, + token: running.hub.token, http: httpClient, run, platformAvailable: (platform) => diff --git a/apps/server/src/device/SshDeviceHost.test.ts b/apps/server/src/device/SshDeviceHost.test.ts index cab2784a6b243..54b7d03c480f3 100644 --- a/apps/server/src/device/SshDeviceHost.test.ts +++ b/apps/server/src/device/SshDeviceHost.test.ts @@ -78,6 +78,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ nodePath: "/node", platforms: [{ platform: "ios", available: true }], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, ...(mode === "agent-start" ? { daemonPort: 1235, token: "fixture", entryPath: "/agent.mjs" } @@ -222,6 +223,7 @@ it.effect("releases the forward of a bootstrap interrupted before its hub answer nodePath: "/node", platforms: [{ platform: "ios", available: true }], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, }); return ChildProcessSpawner.makeHandle({ @@ -324,6 +326,7 @@ it.effect("lists Android devices without probing the host again once it reports { platform: "android", available: androidInstalled }, ], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, }); } @@ -422,6 +425,7 @@ it.effect( nodePath: "/node", platforms: [{ platform: "ios", available: true }], hubPort: 1234, + hubToken: "hub-token", helpers: { serveSimAxSettings: null, serveSimCli: null }, }); return ChildProcessSpawner.makeHandle({ diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts index d6946b419429a..c85607a17d616 100644 --- a/apps/server/src/device/SshDeviceHost.ts +++ b/apps/server/src/device/SshDeviceHost.ts @@ -76,6 +76,7 @@ const Probe = Schema.Struct({ const Started = Schema.Struct({ ...Probe.fields, hubPort: Schema.Int, + hubToken: Schema.String, daemonPort: Schema.optionalKey(Schema.Int), token: Schema.optionalKey(Schema.String), entryPath: Schema.optionalKey(Schema.String), @@ -438,10 +439,12 @@ export const make = Effect.fn("SshDeviceHost.make")(function* ( const hubOrigin = `http://127.0.0.1:${hubPort}`; const next = { nodePath: remote.nodePath, - hub: { origin: hubOrigin }, + // The forward and the remote hub both require the hub's token. + hub: { origin: hubOrigin, token: remote.hubToken }, devices: makeDeviceHubOperations({ hostId: config.id, origin: hubOrigin, + token: remote.hubToken, http, run, // Keep probing negative reports so tooling installed after connecting is still found. diff --git a/apps/server/src/device/deviceToolMaintenance.ts b/apps/server/src/device/deviceToolMaintenance.ts index 2832071d099d0..7ff3a961eee9d 100644 --- a/apps/server/src/device/deviceToolMaintenance.ts +++ b/apps/server/src/device/deviceToolMaintenance.ts @@ -65,7 +65,7 @@ function pruneTools(root, specs, flat) { return withToolMaintenance(root, () => { // Keep installs used by any running helper, including older T3 releases. const scan = process.platform === 'win32' - ? require('node:child_process').spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) + ? require('node:child_process').spawnSync((process.env.SystemRoot || process.env.windir || 'C:\\Windows') + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Get-CimInstance Win32_Process | Select-Object -ExpandProperty CommandLine'], { encoding: 'utf8', timeout: 10000 }) : require('node:child_process').spawnSync('ps', ['-ax', '-o', 'command='], { encoding: 'utf8', timeout: 10000 }); if (scan.status !== 0 || !scan.stdout) return; for (const [name, required] of specs) { diff --git a/apps/server/src/device/sshDeviceScript.test.ts b/apps/server/src/device/sshDeviceScript.test.ts index 8fd592c20c546..9cfa6f27e01ed 100644 --- a/apps/server/src/device/sshDeviceScript.test.ts +++ b/apps/server/src/device/sshDeviceScript.test.ts @@ -7,6 +7,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeUtil from "node:util"; +import { DEVICE_HUB_VERSION } from "./DeviceToolchain.ts"; import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts"; const exec = NodeUtil.promisify(NodeChildProcess.execFile); @@ -239,3 +240,59 @@ it.effect("keeps a daemon record its missing agent CLI cannot stop", () => }); }), ); + +it.effect("starts the hub requiring a session token and reports the one it printed", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + yield* Effect.promise(async () => { + const home = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-ssh-hub-")); + const run = (mode: "start" | "stop") => + NodeChildProcess.spawnSync(process.execPath, [], { + input: remoteDeviceScript("owner", mode), + env: { + HOME: home, + PATH: `${NodePath.join(home, "bin")}:/usr/bin:/bin`, + ANDROID_HOME: NodePath.join(home, "sdk"), + }, + encoding: "utf8", + }); + try { + const state = NodePath.join(home, ".t3/device/hosts/owner"); + const install = NodePath.join( + home, + ".t3/device/tools", + `expo-device-hub@${DEVICE_HUB_VERSION}`, + ); + const entry = NodePath.join(install, "node_modules/expo-device-hub/dist/server/cli.mjs"); + await completeSdk(NodePath.join(home, "sdk")); + await NodeFSP.mkdir(NodePath.dirname(entry), { recursive: true }); + await NodeFSP.writeFile(NodePath.join(install, ".install-complete"), DEVICE_HUB_VERSION); + // Stands in for the hub: it serves /readyz and prints its startup link. + await NodeFSP.writeFile( + entry, + `import * as http from "node:http"; +const args = process.argv.slice(2); +const token = args.includes("--require-token") ? "printed-token" : undefined; +http.createServer((_request, response) => response.end("ok")).listen(Number(args[args.indexOf("--port") + 1]), "127.0.0.1", () => { + console.log(" Local: http://localhost/" + (token ? "?token=" + token : "")); + console.log("state-dir=" + process.env.EXPO_DEVICE_HUB_STATE_DIR); +});`, + ); + + const started = run("start"); + expect(started.stderr).toBe(""); + expect(JSON.parse(started.stdout).hubToken).toBe("printed-token"); + expect( + JSON.parse(await NodeFSP.readFile(NodePath.join(state, "hub.json"), "utf8")).token, + ).toBe("printed-token"); + expect((await NodeFSP.stat(NodePath.join(state, "hub.log"))).mode & 0o077).toBe(0); + expect(await NodeFSP.readFile(NodePath.join(state, "hub.log"), "utf8")).toContain( + `state-dir=${state}\n`, + ); + } finally { + run("stop"); + await NodeFSP.rm(home, { recursive: true, force: true }); + } + }); + }), +); diff --git a/apps/server/src/device/sshDeviceScript.ts b/apps/server/src/device/sshDeviceScript.ts index 7a32640766a8f..cc3c147fa9b70 100644 --- a/apps/server/src/device/sshDeviceScript.ts +++ b/apps/server/src/device/sshDeviceScript.ts @@ -207,13 +207,20 @@ async function install(name, version, entry) { }) : []; const emulatorExtraArgs = [cameraArgs.join(' '), process.env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS].filter(Boolean).join(' '); let hub = read(hubFile); - if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || hub.emulatorExtraArgs !== emulatorExtraArgs || !await healthy(hub.port, '/readyz')) { + // A hub recorded without a token predates --require-token and is replaced. + if (!hub || hub.owner !== owner || !hub.token || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || hub.emulatorExtraArgs !== emulatorExtraArgs || !await healthy(hub.port, '/readyz')) { stopHub(hub); for (let attempt = 0; attempt < 5; attempt++) { const hubPort = await port(); - const log = fs.openSync(path.join(state, 'hub.log'), 'a'); - const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], { - cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: emulatorExtraArgs, FORCE_COLOR: '0', NO_COLOR: '1' }, + // The hub prints the session token it generates, so its log is private and read from here on. + // It also records the token in its state folder, kept in this host's private folder. + const logFile = path.join(state, 'hub.log'); + const log = fs.openSync(logFile, 'a', 0o600); + fs.fchmodSync(log, 0o600); + const logStart = fs.fstatSync(log).size; + const announcedToken = () => /\btoken=([\w.~-]+)/.exec(fs.readFileSync(logFile, 'utf8').slice(logStart))?.[1]; + const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--require-token', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], { + cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, EXPO_DEVICE_HUB_STATE_DIR: state, EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: emulatorExtraArgs, FORCE_COLOR: '0', NO_COLOR: '1' }, }); try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); } finally { fs.closeSync(log); } @@ -223,7 +230,7 @@ async function install(name, version, entry) { const deadline = Date.now() + 30000; let listening = false; while (child.exitCode === null && child.signalCode === null) { - if (await healthy(hub.port, '/readyz')) { listening = true; break; } + if (await healthy(hub.port, '/readyz') && (hub.token = announcedToken())) { write(hubFile, hub); listening = true; break; } if (Date.now() > deadline) { stopHub(hub); throw Error('Device hub did not become ready. See ' + path.join(state, 'hub.log')); } await sleep(200); } @@ -258,7 +265,7 @@ async function install(name, version, entry) { const vendor = path.resolve(path.dirname(hubEntry), '../../vendor/serve-sim/dist'); const optional = file => fs.existsSync(file) ? file : null; await pruneTools(path.join(root, 'tools'), [['expo-device-hub', hubVersion], ...(mode === 'agent-start' ? [['agent-device', agentVersion]] : [])], true).catch(() => {}); - console.log(JSON.stringify({ nodePath: process.execPath, platforms, tools: versions(), hubPort: hub.port, ...agentResult, + console.log(JSON.stringify({ nodePath: process.execPath, platforms, tools: versions(), hubPort: hub.port, hubToken: hub.token, ...agentResult, helpers: { serveSimAxSettings: optional(path.join(vendor, 'simax/serve-sim-ax-settings')), serveSimCli: optional(path.join(vendor, 'serve-sim.js')) } })); } finally { releaseHost(); } })().catch(error => { console.error(error.message); process.exitCode = 1; }); diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 2bb7078ad4a25..49222ecdac528 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -79,7 +79,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen it.effect("publishes proven install ownership only for manually updated servers", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const baseDir = yield* fs.makeTempDirectoryScoped(); + const platform = yield* HostProcess.Platform; + const baseDir = yield* fs.realPath(yield* fs.makeTempDirectoryScoped()); const prefix = `${baseDir}/node`; const entry = `${prefix}/lib/node_modules/t3/dist/bin.mjs`; yield* fs.makeDirectory(`${prefix}/lib/node_modules/t3/dist`, { recursive: true }); @@ -105,11 +106,10 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen ), Effect.provideService(HostProcess.Arguments, ["node", entry]), Effect.provideService(HostProcess.IsExecutable, false), - Effect.provideService(HostProcess.Platform, "linux"), Effect.provideService(HostProcess.Environment, {}), ); expect(descriptor.capabilities.serverInstallation).toEqual( - mode === "web" ? { kind: "npm-global", prefix } : undefined, + mode === "web" && platform !== "win32" ? { kind: "npm-global", prefix } : undefined, ); expect(descriptor.capabilities.serverSelfUpdate).toBe( mode === "web" ? undefined : "desktop-managed", diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 1bce13cb0f020..507642520f436 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -29,6 +29,7 @@ import type { GitActionProgressEvent, GitPreparePullRequestThreadInput, ModelSelection, + ServerProvider, } from "@t3tools/contracts"; import { @@ -647,6 +648,7 @@ function makeManager(input?: { pullRequests?: Partial; sourceControlProvider?: SourceControlProvider["Service"]; textGeneration?: Partial; + providers?: ReadonlyArray; serverSettings?: Parameters[0]; setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]; gitConfigReads?: string[]; @@ -755,7 +757,7 @@ function makeManager(input?: { Layer.succeed(TextGeneration.TextGeneration, textGeneration), Layer.mock(PullRequestService.PullRequestService)(input?.pullRequests ?? {}), Layer.mock(ProviderRegistry.ProviderRegistry)({ - getProviders: Effect.succeed([]), + getProviders: Effect.succeed(input?.providers ?? []), }), Layer.succeed( ProjectSetupScriptRunner.ProjectSetupScriptRunner, @@ -4880,6 +4882,273 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + const claudeWorkProvider: ServerProvider = { + instanceId: ProviderInstanceId.make("claude_work"), + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Work account", + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-09-27T00:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + }; + + const seedPrThread = Effect.fnUntraced(function* (input: { + readonly threadId: ThreadId; + readonly worktreePath: string; + readonly forkedFrom?: { readonly threadId: ThreadId; readonly runId: RunId }; + readonly runs: ReadonlyArray<{ + readonly modelSelection: ModelSelection; + readonly text: string; + readonly status?: "rolled_back"; + }>; + }) { + const store = yield* ProjectionStore.ProjectionStoreV2; + const { threadId } = input; + const createdAt = DateTime.makeUnsafe("2026-09-27T00:00:00.000Z"); + const modelSelection = input.runs[0]!.modelSelection; + yield* store.apply({ + id: EventId.make(`event:${threadId}:thread`), + type: "thread.created", + threadId, + providerInstanceId: modelSelection.instanceId, + occurredAt: createdAt, + payload: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project:pr-thread-model"), + title: "PR thread model", + providerInstanceId: modelSelection.instanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: input.worktreePath, + activeProviderThreadId: null, + lineage: input.forkedFrom + ? { + parentThreadId: input.forkedFrom.threadId, + relationshipToParent: "fork", + rootThreadId: input.forkedFrom.threadId, + } + : { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: input.forkedFrom ? { type: "run", ...input.forkedFrom } : null, + createdAt, + updatedAt: createdAt, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + for (const [index, spec] of input.runs.entries()) { + const ordinal = index + 1; + const runId = RunId.make(`run:${threadId}:${ordinal}`); + const messageId = MessageId.make(`message:${threadId}:${ordinal}`); + yield* store.apply({ + id: EventId.make(`event:${threadId}:run:${ordinal}`), + type: "run.updated", + threadId, + runId, + occurredAt: createdAt, + payload: { + id: runId, + threadId, + ordinal, + providerInstanceId: spec.modelSelection.instanceId, + modelSelection: spec.modelSelection, + providerThreadId: null, + userMessageId: messageId, + rootNodeId: null, + activeAttemptId: null, + status: spec.status ?? "completed", + requestedAt: createdAt, + startedAt: createdAt, + completedAt: createdAt, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* store.apply({ + id: EventId.make(`event:${threadId}:item:${ordinal}`), + type: "turn-item.updated", + threadId, + runId, + occurredAt: createdAt, + payload: { + id: TurnItemId.make(`item:${threadId}:${ordinal}`), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: createdAt, + completedAt: createdAt, + updatedAt: createdAt, + type: "user_message", + messageId, + createdBy: "user", + creationSource: "web", + inputIntent: "turn_start", + text: spec.text, + attachments: [], + }, + }); + } + }); + + const createPrPrompt = Effect.fnUntraced(function* ( + seed: ( + worktreePath: string, + ) => Effect.Effect< + void, + ProjectionStore.ProjectionStoreV2Error, + ProjectionStore.ProjectionStoreV2 + >, + threadId: ThreadId, + ) { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/thread-model"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "thread-model.txt"), "model\n"); + yield* runGit(repoDir, ["add", "thread-model.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Thread model"]); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + let generatedPrompt = ""; + const writer = fromRunner("test", (request) => { + generatedPrompt = request.prompt; + return decodeJsonReply(request, "test", '{"title":"Thread model","body":"Body"}'); + }); + const { manager } = yield* makeManager({ + serverSettings: { + textGenerationModelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-6.1-terra", + }, + }, + textGeneration: { generatePrContent: writer.generatePrContent }, + providers: [claudeWorkProvider], + seed: seed(repoDir), + }); + yield* manager.runStackedAction({ + actionId: "test-action-id", + cwd: repoDir, + action: "create_pr", + threadId, + }); + return generatedPrompt; + }); + + it.effect("create_pr tells the writer which model and harness made the change", () => + Effect.gen(function* () { + const threadId = ThreadId.make("thread:pr-thread-model"); + const instanceId = claudeWorkProvider.instanceId; + const prompt = yield* createPrPrompt( + (worktreePath) => + seedPrThread({ + threadId, + worktreePath, + runs: [ + { + modelSelection: { instanceId, model: "claude-opus-5-5" }, + text: "Add the thread model file", + }, + { + modelSelection: { instanceId, model: "claude-haiku-5-5" }, + text: "Undo that", + status: "rolled_back", + }, + { + modelSelection: { + instanceId: ProviderInstanceId.make("claude_removed"), + model: "claude-sonnet-5-5", + }, + text: "Polish the file", + }, + ], + }), + threadId, + ); + + expect(prompt).toContain("Add the thread model file"); + expect(prompt).toContain('- model "claude-opus-5-5", harness Claude\n'); + expect(prompt).toContain('- model "claude-sonnet-5-5", harness unknown\n'); + expect(prompt).not.toContain("Work account"); + expect(prompt).not.toContain("claude_removed"); + expect(prompt).not.toContain("claude-haiku-5-5"); + }), + ); + + it.effect("create_pr credits the models a fork inherited its history from", () => + Effect.gen(function* () { + const sourceThreadId = ThreadId.make("thread:pr-fork-source"); + const forkThreadId = ThreadId.make("thread:pr-fork"); + const prompt = yield* createPrPrompt( + (worktreePath) => + Effect.gen(function* () { + yield* seedPrThread({ + threadId: sourceThreadId, + worktreePath, + runs: [ + { + modelSelection: { + instanceId: claudeWorkProvider.instanceId, + model: "claude-opus-5-5", + }, + text: "Implement the thread model file", + }, + ], + }); + yield* seedPrThread({ + threadId: forkThreadId, + worktreePath, + forkedFrom: { + threadId: sourceThreadId, + runId: RunId.make(`run:${sourceThreadId}:1`), + }, + runs: [ + { + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-6.2", + }, + text: "Review the change", + }, + ], + }); + // Rolling the source back afterwards leaves the work the fork inherited in place. + const store = yield* ProjectionStore.ProjectionStoreV2; + const [sourceRun] = (yield* store.getThreadRecords(sourceThreadId, ["runs"])).runs; + yield* store.apply({ + id: EventId.make(`event:${sourceThreadId}:rollback`), + type: "run.updated", + threadId: sourceThreadId, + runId: sourceRun!.id, + occurredAt: sourceRun!.requestedAt, + payload: { ...sourceRun!, status: "rolled_back" }, + }); + }), + forkThreadId, + ); + + expect(prompt).toContain("Implement the thread model file"); + expect(prompt).toContain('- model "claude-opus-5-5", harness Claude\n'); + expect(prompt).toContain('- model "gpt-6.2", harness Codex\n'); + }), + ); + it.effect.each(["commit", "short-commit", "tag", "revision"] as const)( "creates a PR against the default branch with a legacy %s base setting", (kind) => diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 4b23f8cd6c66f..8e4a98e0ca798 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -38,6 +38,8 @@ import { ModelSelection, type OrchestrationV2TurnItem, type ProjectId, + PROVIDER_DISPLAY_NAMES, + ProviderDriverKind, SourceControlProviderError, type SourceControlWritingStyleSettings, type ThreadId, @@ -237,6 +239,7 @@ const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); // cannot fill the git and forge process slots that foreground work also needs. const BRANCH_PR_LOOKUP_CONCURRENCY = 4; const PR_THREAD_CONTEXT_BYTES = 16_000; +const NO_THREAD_CONTEXT = { history: undefined, producedBy: undefined }; const PR_THREAD_COMMAND_OUTPUT_CHARS = 2_000; const isSourceControlProviderError = Schema.is(SourceControlProviderError); @@ -842,8 +845,8 @@ export const make = Effect.gen(function* () { }); const readThreadContext = Effect.fnUntraced( function* (threadId: ThreadId | undefined) { - if (threadId === undefined) return undefined; - const { visibleTurnItems } = yield* threads.getThreadProjection(threadId); + if (threadId === undefined) return NO_THREAD_CONTEXT; + const { thread, runs, visibleTurnItems } = yield* threads.getThreadProjection(threadId); const selected = selectHistory({ messages: visibleTurnItems.flatMap( ({ item }) => historicalMessage(limitCommandOutput(item)) ?? [], @@ -851,9 +854,47 @@ export const make = Effect.gen(function* () { coverage: "Digest of the thread that made this change, oldest first.", budget: PR_THREAD_CONTEXT_BYTES, }); - return selected.messages.length === 0 - ? undefined - : renderHistory(selected.messages, selected.context); + // A thread can switch models mid-way, and a fork inherits its ancestors' history; credit + // every model behind a turn still visible here. Ancestor runs are best-effort. + const visibleRunIds = new Set(visibleTurnItems.flatMap(({ item }) => item.runId ?? [])); + const ancestorRuns = yield* Effect.forEach( + new Set( + visibleTurnItems.flatMap(({ item }) => (item.threadId === threadId ? [] : item.threadId)), + ), + (ancestorId) => + threads.getThreadRecords(ancestorId, ["runs"]).pipe( + Effect.map((records) => records.runs), + Effect.orElseSucceed(() => []), + ), + ); + // Visibility already hides local rollbacks; an ancestor's later rollback leaves the fork's + // inherited work in place. A queued run shows its message before it starts. + const runSelections = [...runs, ...ancestorRuns.flat()] + .filter((run) => visibleRunIds.has(run.id) && run.startedAt !== null) + .map((run) => run.modelSelection); + const providers = yield* providerRegistry.getProviders; + const producedBy = Arr.dedupeWith( + (runSelections.length > 0 ? runSelections : [thread.modelSelection]).map( + ({ instanceId, model }) => { + // The instance's displayName is a user label (often an account), not the harness. + // Default instances are named after their driver; a removed custom one names nothing. + const harness = + PROVIDER_DISPLAY_NAMES[ + providers.find((provider) => provider.instanceId === instanceId)?.driver ?? + ProviderDriverKind.make(instanceId) + ]; + return harness === undefined ? { model } : { model, harness }; + }, + ), + (left, right) => left.model === right.model && left.harness === right.harness, + ); + return { + producedBy, + history: + selected.messages.length === 0 + ? undefined + : renderHistory(selected.messages, selected.context), + }; }, (effect, threadId) => effect.pipe( @@ -861,7 +902,7 @@ export const make = Effect.gen(function* () { Effect.logWarning("GitManager.readThreadContext failed", { threadId, errorTag: error._tag, - }).pipe(Effect.as(undefined)), + }).pipe(Effect.as(NO_THREAD_CONTEXT)), ), ), ); @@ -2873,7 +2914,7 @@ export const make = Effect.gen(function* () { yield* provider.readChangeRequestTemplate({ cwd, treeish: baseRangeRef }), ) : undefined; - const threadContext = yield* readThreadContext(threadId); + const { history: threadContext, producedBy } = yield* readThreadContext(threadId); return yield* textGeneration.generatePrContent({ cwd, @@ -2884,6 +2925,7 @@ export const make = Effect.gen(function* () { diffPatch: limitContext(rangeContext.diffPatch, 60_000), ...(changeRequestTemplate ? { changeRequestTemplate } : {}), ...(threadContext ? { threadContext } : {}), + producedBy, ...(policy ? { policy } : {}), modelSelection: settings.modelSelection, projectId: settings.projectId, diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 363c9d84d4e2c..cb68cece707d8 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -546,6 +546,52 @@ it.effect("gives the guest a command's detail and output, but no file diffs", () }).pipe(Effect.provide(layerTest)), ); +it.effect("gives the guest a failed edit without the text it tried to write", () => + Effect.gen(function* () { + const { orchestrator, guestShares, credential } = yield* shareThread; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + const failedEdit = (id: string) => + writeItem(id, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }); + const before = yield* failedEdit("item:failed-before"); + + const events = yield* guestShares.stream(session); + const during = yield* failedEdit("item:failed-during"); + const detail = (yield* guestShares.item(session, before)).item; + yield* orchestrator.dispatch({ + type: "thread.guest-share.close", + commandId: CommandId.make("close-after-failed-edit"), + threadId, + }); + const received = Array.from(yield* Stream.runCollect(events)); + const changes = received.flatMap((event) => { + if (event.type !== "thread") return []; + if (event.item.kind === "snapshot") { + return [ + ...event.item.projection.turnItems, + ...event.item.projection.visibleTurnItems.map((row) => row.item), + ]; + } + return event.item.kind === "event" && event.item.event.type === "turn-item.updated" + ? [event.item.event.payload] + : []; + }); + const failed = changes.filter((item) => item.type === "file_change"); + assert.includeMembers( + failed.map((item) => item.id), + [before, during], + ); + for (const change of [...failed, detail]) { + assert.deepInclude(change, { status: "failed", fileName: "src/auth.ts" }); + assert.doesNotHaveAnyKeys(change, ["diffStr", "oldStr", "newStr"]); + } + }).pipe(Effect.provide(layerTest)), +); + it.effect("gives a fork's guest the commands the fork shows from its source thread", () => Effect.gen(function* () { const { orchestrator, guestShares } = yield* shareThread; @@ -656,13 +702,19 @@ it.effect("pages the guest back through turns older than the stream's snapshot", }); yield* eventSink.write({ events: [ - turnItem("item:old-image", 1, { + turnItem("item:old-edit", 1, { + type: "file_change", + status: "failed", + fileName: "src/auth.ts", + diffStr: "-const token = 1;\n+const token = 2;\n", + }), + turnItem("item:old-image", 2, { type: "assistant_message", text: `![Old](${shot})`, streaming: false, }), ...Array.from({ length: 30 }, (_, index) => - turnItem(`item:ask-${index}`, index + 2, { + turnItem(`item:ask-${index}`, index + 3, { type: "user_message", text: `Ask ${index}`, createdBy: "user", @@ -694,9 +746,10 @@ it.effect("pages the guest back through turns older than the stream's snapshot", while (cursor !== null) { const page: OrchestrationV2ThreadHistoryPage = yield* guestShares.history(session, cursor); older.push(...ids(page.items)); + for (const { item } of page.items) assert.notProperty(item, "diffStr"); cursor = page.hasMoreHistory ? page.nextCursor : null; } - assert.include(older, "item:old-image"); + assert.includeMembers(older, ["item:old-image", "item:old-edit"]); assert.deepStrictEqual(yield* guestShares.media(session, shot), { path: shot, mimeType: "image/png", diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index b5b21a7af2ae7..5ff7ae22770e2 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -52,7 +52,6 @@ import { coalesceThreadLiveStream } from "../orchestration-v2/ThreadLiveEventCoa import { buildBoundedThreadStreamSnapshot } from "../orchestration-v2/ThreadStream.ts"; import { projectTurnItemForDetail, - projectTurnItemForWire, threadStreamEventItem, } from "../orchestration-v2/WireProjection.ts"; import * as DocumentText from "../provider/DocumentText.ts"; @@ -218,6 +217,16 @@ const threadOf = (event: OrchestrationV2DomainEvent): OrchestrationV2AppThread | } }; +/** A guest sees that a file changed, never the text of the change, whatever its status. */ +const withoutFileText = (item: OrchestrationV2TurnItem): OrchestrationV2TurnItem => { + if (item.type !== "file_change") return item; + const { diffStr: _diff, oldStr: _old, newStr: _new, ...shown } = item; + return shown; +}; +const rowWithoutFileText = ( + row: Row, +): Row => ({ ...row, item: withoutFileText(row.item) }); + const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const commandOutputs = yield* CommandOutputHub.CommandOutputHub; @@ -566,12 +575,16 @@ const make = Effect.gen(function* () { if (item.kind !== "event") return []; if (endsShare(item.event)) return [ended]; if (item.event.type === "turn-item.updated") rememberSent(share.id, [item.event.payload]); + const shown = + item.event.type === "turn-item.updated" + ? { ...item, event: { ...item.event, payload: withoutFileText(item.event.payload) } } + : item; const updated = threadOf(item.event); const view = updated === null ? null : viewOf(updated); return view === null - ? [{ type: "thread", item }] + ? [{ type: "thread", item: shown }] : [ - { type: "thread", item }, + { type: "thread", item: shown }, { type: "view", view }, ]; }), @@ -585,7 +598,11 @@ const make = Effect.gen(function* () { ); const openingSnapshot = buildBoundedThreadStreamSnapshot({ snapshotSequence: snapshot.snapshotSequence, - projection: snapshot.projection, + projection: { + ...snapshot.projection, + turnItems: snapshot.projection.turnItems.map(withoutFileText), + visibleTurnItems: snapshot.projection.visibleTurnItems.map(rowWithoutFileText), + }, }); const opening: ReadonlyArray = [ { type: "view", view: initialView }, @@ -669,10 +686,7 @@ const make = Effect.gen(function* () { const item = Effect.fn("GuestShareService.item")(function* (session: string, itemId: string) { const { item } = yield* threadItem(session, itemId); - return { - item: - item.type === "file_change" ? projectTurnItemForWire(item) : projectTurnItemForDetail(item), - }; + return { item: projectTurnItemForDetail(withoutFileText(item)) }; }); const history = Effect.fn("GuestShareService.history")(function* ( @@ -687,7 +701,7 @@ const make = Effect.gen(function* () { share.id, page.items.map((row) => row.item), ); - return page; + return { ...page, items: page.items.map(rowWithoutFileText) }; }); const commandOutput = Effect.fn("GuestShareService.commandOutput")(function* ( diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 6e011aef39d26..0bfd8b652272e 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -1,5 +1,6 @@ import { expect, it } from "@effect/vitest"; import { describe, vi } from "vite-plus/test"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform"; import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -20,10 +21,15 @@ import { openMediaFile } from "./assets/MediaFile.ts"; import { injectMcpAppCsp, injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, injectMcpAppThemeBootstrap, MCP_APP_MAX_HTML_BYTES, } from "@t3tools/shared/mcpApp"; import { ORCHESTRATION_PROTOCOL_HEADER } from "@t3tools/contracts"; +import { + DESKTOP_READINESS_PROOF_PATH, + isValidDesktopReadinessProof, +} from "@t3tools/shared/desktopReadinessProof"; import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; import * as ServerConfig from "./config.ts"; @@ -54,7 +60,9 @@ describe("MCP app asset responses", () => { method, ), ); - const expected = injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)); + const expected = injectMcpAppDocumentBootstrap( + injectMcpAppCookieBootstrap(injectMcpAppThemeBootstrap(html)), + ); expect(response.status).toBe(200); expect(response.headers.get("content-length")).toBe( String(new TextEncoder().encode(expected).byteLength), @@ -234,6 +242,69 @@ describe("browser API CORS", () => { }); }); +describe("desktop readiness proof", () => { + // Request handlers read these from the app's own context. + const serveRoute = (overrides: Partial) => + Effect.acquireRelease( + Effect.sync(() => + HttpRouter.toWebHandler( + ServerHttp.layerDesktopReadinessProofRoute.pipe( + Layer.provideMerge( + Layer.effect( + ServerConfig.ServerConfig, + Effect.map(ServerConfig.ServerConfig, (config) => ({ ...config, ...overrides })), + ).pipe( + Layer.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "http-readiness-test-" }), + ), + ), + ), + Layer.provideMerge(NodeCrypto.layerMac), + Layer.provide(NodeServices.layer), + ), + { disableLogger: true }, + ), + ), + ({ dispose }) => Effect.promise(() => dispose()), + ).pipe( + Effect.map( + ({ handler }) => + (query: string) => + Effect.promise(() => + handler( + new Request(`http://172.20.84.98:3773${DESKTOP_READINESS_PROOF_PATH}${query}`), + ), + ), + ), + ); + + it.effect("answers a challenge with a proof bound to the launch's readiness secret", () => + Effect.gen(function* () { + const get = yield* serveRoute({ desktopReadinessSecret: "launch-secret" }); + + const response = yield* get("?challenge=abc123"); + const proof = yield* Effect.promise(() => response.text()); + + expect(response.status).toBe(200); + expect(yield* isValidDesktopReadinessProof("launch-secret", "abc123", proof)).toBe(true); + expect(yield* isValidDesktopReadinessProof("launch-secret", "other", proof)).toBe(false); + expect(yield* isValidDesktopReadinessProof("another-launch", "abc123", proof)).toBe(false); + expect(proof).not.toContain("launch-secret"); + + expect((yield* get("")).status).toBe(404); + expect((yield* get(`?challenge=${"a".repeat(129)}`)).status).toBe(404); + }).pipe(Effect.scoped, Effect.provide(NodeCrypto.layerMac)), + ); + + it.effect("does not answer on a server launched without a readiness secret", () => + Effect.gen(function* () { + const get = yield* serveRoute({}); + + expect((yield* get("?challenge=abc123")).status).toBe(404); + }).pipe(Effect.scoped), + ); +}); + describe("untraced requests", () => { it.effect("starts a separate trace for each request, not the server's lifetime trace", () => Effect.gen(function* () { @@ -842,7 +913,7 @@ describe("video asset byte ranges", () => { }); describe("assetResponseHeaders", () => { - it("sandboxes SVG assets", () => { + it("sandboxes SVG and other XML assets", () => { expect(assetResponseHeaders("/attachments/user-image.svg")).toMatchObject({ "Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", "X-Content-Type-Options": "nosniff", @@ -850,6 +921,15 @@ describe("assetResponseHeaders", () => { expect(assetResponseHeaders("/attachments/user-image.SVG")).toHaveProperty( "Content-Security-Policy", ); + for (const name of ["page.xhtml", "page.XHT", "feed.xml", "sheet.xsl", "feed.rss"]) { + expect(assetResponseHeaders(`/workspace/${name}`)).toHaveProperty( + "Content-Security-Policy", + "default-src 'none'; style-src 'unsafe-inline'; sandbox", + ); + } + expect(assetResponseHeaders("/workspace/photo.png")).not.toHaveProperty( + "Content-Security-Policy", + ); }); it("serves inline attachment documents with their declared mime type", () => { expect( diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index acec877a45c55..258a99887e8d0 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -5,8 +5,18 @@ import { EnvironmentHttpApi, } from "@t3tools/contracts"; import { isDevProxiedPath } from "@t3tools/shared/devProxy"; -import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp"; +import { + injectMcpAppCookieBootstrap, + injectMcpAppDocumentBootstrap, + injectMcpAppThemeBootstrap, +} from "@t3tools/shared/mcpApp"; import { FILE_PREVIEW_SCROLL_SCRIPT } from "@t3tools/shared/htmlRender"; +import { + DESKTOP_READINESS_CHALLENGE_MAX_LENGTH, + DESKTOP_READINESS_CHALLENGE_PARAM, + DESKTOP_READINESS_PROOF_PATH, + desktopReadinessProof, +} from "@t3tools/shared/desktopReadinessProof"; import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as ByteSize from "effect/ByteSize"; import * as Context from "effect/Context"; @@ -29,6 +39,7 @@ import { HttpServerRequest, HttpServerRespondable, } from "effect/http"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { OtlpTracer, OtlpSerialization } from "effect/observability"; @@ -77,6 +88,13 @@ const isSafeInlineMediaMimeType = (mimeType: string): boolean => const isSafeInlineDocumentMimeType = (mimeType: string): boolean => mimeType.toLowerCase() === "application/pdf" || mimeType.toLowerCase() === "text/html"; +// XML types render as documents, so they get the same policy as SVG. +const isScriptableXmlPath = (filePath: string): boolean => + Option.match(Mime.getType(filePath), { + onNone: () => false, + onSome: (mimeType) => /(?:\/xml(?:$|-)|\+xml$)/.test(mimeType), + }); + export function downloadContentDisposition(fileName?: string): string { if (fileName === undefined) { return "attachment"; @@ -134,7 +152,7 @@ export function assetResponseHeaders( "Content-Security-Policy": HTML_CONTENT_SECURITY_POLICY, } : {}), - ...(!options?.download && lowerPath.endsWith(".svg") + ...(!options?.download && isScriptableXmlPath(lowerPath) ? { "Content-Security-Policy": SVG_CONTENT_SECURITY_POLICY } : {}), }; @@ -189,6 +207,8 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( new TextDecoder().decode(bytes), injectMcpAppThemeBootstrap, injectMcpAppCookieBootstrap, + // Applied last so it is the document's first script. + injectMcpAppDocumentBootstrap, (html) => new TextEncoder().encode(html), ); headers["Content-Length"] = String(body.byteLength); @@ -271,6 +291,12 @@ export const assetFileResponse = Effect.fn("assetFileResponse")(function* ( return yield* HttpServerResponse.file(asset.path, { status, offset, bytesToRead, headers }); }); +// The default body limit for API routes. Routes that take more set their own limit. +export const API_MAX_BODY_BYTES = 1024 * 1024; +export const layerApiBodyLimit = HttpRouter.middleware( + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(API_MAX_BODY_BYTES)), +).layer; + export const layerHttpCompression = HttpRouter.middleware(HttpMiddleware.compression(), { global: true, }); @@ -387,6 +413,29 @@ export const layerServerEnvironmentHttpApi = HttpApiBuilder.group( }), ); +// Answers only for a launch that was handed a readiness secret, so the desktop app can tell the +// backend it started from any other listener at the same address. +export const layerDesktopReadinessProofRoute = HttpRouter.add( + "GET", + DESKTOP_READINESS_PROOF_PATH, + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const request = yield* HttpServerRequest.HttpServerRequest; + const secret = config.desktopReadinessSecret; + const challenge = Option.getOrUndefined(requestUrl(request))?.searchParams.get( + DESKTOP_READINESS_CHALLENGE_PARAM, + ); + if ( + secret === undefined || + !challenge || + challenge.length > DESKTOP_READINESS_CHALLENGE_MAX_LENGTH + ) { + return HttpServerResponse.empty({ status: 404 }); + } + return HttpServerResponse.text(yield* desktopReadinessProof(secret, challenge)); + }), +); + class DecodeOtlpTraceRecordsError extends Schema.TaggedError()( "DecodeOtlpTraceRecordsError", { cause: Schema.Defect() }, diff --git a/apps/server/src/httpResponseErrorGuard.test.ts b/apps/server/src/httpResponseErrorGuard.test.ts index 7227e03dade0a..6569829879e84 100644 --- a/apps/server/src/httpResponseErrorGuard.test.ts +++ b/apps/server/src/httpResponseErrorGuard.test.ts @@ -2,7 +2,10 @@ // @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 * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; +import * as Effect from "effect/Effect"; +import * as HttpServerResponse from "effect/http/HttpServerResponse"; +import { afterEach, describe, expect, it } from "@effect/vitest"; import * as HttpResponseErrorGuard from "./httpResponseErrorGuard.ts"; @@ -239,4 +242,30 @@ describe("rejectRequestsUntilServing", () => { expect(servingUpgrade.headers["retry-after"]).toBeUndefined(); expect(writeErrors).toEqual([]); }); + + it.effect( + "rejects early requests on NodeHttpServer, which adds its own listener before listening", + () => + Effect.scoped( + Effect.gen(function* () { + const server = yield* NodeHttpServer.make( + () => + HttpResponseErrorGuard.rejectRequestsUntilServing( + HttpResponseErrorGuard.keepIdleConnections( + guardHttpResponseWriteErrors(NodeHttp.createServer()), + ), + ), + { host: "127.0.0.1", port: 0 }, + ); + const port = (server.address as { readonly port: number }).port; + + const early = yield* Effect.promise(() => fetchResponse(port, "/")); + expect(early.statusCode).toBe(503); + expect(early.headers["retry-after"]).toBe("1"); + + yield* server.serve(Effect.succeed(HttpServerResponse.empty({ status: 204 }))); + expect(yield* Effect.promise(() => fetchStatus(port, "/"))).toBe(204); + }), + ), + ); }); diff --git a/apps/server/src/httpResponseErrorGuard.ts b/apps/server/src/httpResponseErrorGuard.ts index c75ccae660a55..b4596c16cd17f 100644 --- a/apps/server/src/httpResponseErrorGuard.ts +++ b/apps/server/src/httpResponseErrorGuard.ts @@ -25,7 +25,6 @@ export function guardHttpResponseWriteErrors( // into a closed connection, and a slow client reconnects in the middle of a connect. const HTTP_KEEP_ALIVE_TIMEOUT_MS = 95_000; -/** Install before `rejectRequestsUntilServing`, whose handoff starts at the next request listener. */ export function keepIdleConnections(server: T): T { server.keepAliveTimeout = HTTP_KEEP_ALIVE_TIMEOUT_MS; // `close` drops only the connections idle at that moment. One that finishes @@ -48,8 +47,8 @@ export function keepIdleConnections(server: T): T { /** * 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. + * between would hang. Its own pre-listen fallback stays silent while any other + * request listener exists, so only a listener added after listening takes over. */ export function rejectRequestsUntilServing(server: T): T { const rejectRequest = (_request: NodeHttp.IncomingMessage, response: NodeHttp.ServerResponse) => { @@ -64,6 +63,7 @@ export function rejectRequestsUntilServing(server: T) server.on("upgrade", rejectUpgrade); // Node emits newListener before adding the handler, making the handoff synchronous. server.on("newListener", function onNewListener(event) { + if (!server.listening) return; if (event === "request") server.off("request", rejectRequest); if (event === "upgrade") server.off("upgrade", rejectUpgrade); if ( diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 26d02c06bfe66..f658c26f6c63c 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -349,6 +349,27 @@ describe("IssueService", () => { }), ); + it.effect( + "does not call a GitHub issue URL unbrowsable when no project is a GitHub checkout", + () => + Effect.gen(function* () { + // A plain folder project, while GitHub itself is a supported tracker. + const service = yield* makeService({ + projects: [project({ id: "folder" })], + trackers: [fakeTracker()], + }); + const resolved = yield* service + .resolveUrl("https://github.com/acme/web/issues/1", "folder" as ProjectId) + .pipe(Effect.result); + if (resolved._tag === "Failure") { + expect(resolved.failure).not.toMatchObject({ + _tag: "IssueUnavailableError", + reason: "tracker-unsupported", + }); + } + }), + ); + it.effect("resolves both legacy Azure work item URLs through the bound project", () => Effect.gen(function* () { const tracker = IssueTrackerKind.make("azure-devops"); diff --git a/apps/server/src/issue/IssueService.ts b/apps/server/src/issue/IssueService.ts index 01d8b47382eef..1a913c9b0725f 100644 --- a/apps/server/src/issue/IssueService.ts +++ b/apps/server/src/issue/IssueService.ts @@ -824,7 +824,10 @@ const make = Effect.gen(function* () { if (standalone === null) { const found = serve(onTracker); if (found === null) { - return yield* new IssueUnavailableError({ reason: "tracker-unsupported" }); + return yield* new IssueOperationError({ + operation: "resolveUrl", + detail: `No project in T3 Code is on ${link.host}. Add any ${link.host} project to read its issues.`, + }); } return found.resolved; } diff --git a/apps/server/src/launcherWatch.test.ts b/apps/server/src/launcherWatch.test.ts index 1482804c61e0e..87592b2c4d588 100644 --- a/apps/server/src/launcherWatch.test.ts +++ b/apps/server/src/launcherWatch.test.ts @@ -1,9 +1,11 @@ -import { it } from "@effect/vitest"; +import { assert, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; 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"; +import { awaitLauncherLoss, stopOnLauncherLoss } from "./launcherWatch.ts"; const launcherPid = 4100; // Orphans are adopted by init or a subreaper, so the new parent is not always 1. @@ -21,3 +23,26 @@ it.effect("notices a launcher that was already gone when the watch began", () => yield* Fiber.join(fiber); }), ); + +it.effect("exits when shutdown after launcher loss outlasts the grace period", () => + Effect.gen(function* () { + let exits = 0; + const cleanupDone = yield* Deferred.make(); + const stuckCleanup = Effect.never.pipe(Effect.onInterrupt(() => Deferred.await(cleanupDone))); + const fiber = yield* Effect.forkChild( + stopOnLauncherLoss(stuckCleanup, { + launcherPid, + getParentPid: () => subreaperPid, + shutdownGrace: "5 seconds", + exit: () => void exits++, + }).pipe(Effect.provideService(HostProcess.Platform, "linux")), + ); + yield* Effect.yieldNow; + yield* TestClock.adjust("4 seconds"); + assert.strictEqual(exits, 0); + yield* TestClock.adjust("1 second"); + assert.strictEqual(exits, 1); + yield* Deferred.succeed(cleanupDone, undefined); + yield* Fiber.await(fiber); + }), +); diff --git a/apps/server/src/launcherWatch.ts b/apps/server/src/launcherWatch.ts index ca109422c95a8..fc2479e2e297a 100644 --- a/apps/server/src/launcherWatch.ts +++ b/apps/server/src/launcherWatch.ts @@ -3,20 +3,26 @@ import * as Effect from "effect/Effect"; import * as HostProcess from "@t3tools/shared/HostProcess"; const DEFAULT_POLL_INTERVAL = Duration.seconds(2); +// The desktop's SIGTERM grace before it escalates to SIGKILL; a lost launcher cannot escalate. +const DEFAULT_SHUTDOWN_GRACE = Duration.seconds(5); // Capture before config and bootstrap reads to detect launcher loss during startup. const startupParentPid = process.ppid; +interface LauncherWatchOptions { + readonly launcherPid?: number; + readonly getParentPid?: () => number; + readonly interval?: Duration.Input; +} + /** * 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 = Effect.fn("launcherWatch.awaitLauncherLoss")(function* (options?: { - readonly launcherPid?: number; - readonly getParentPid?: () => number; - readonly interval?: Duration.Input; -}): Effect.fn.Return { +export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(function* ( + options?: LauncherWatchOptions, +): Effect.fn.Return { const platform = yield* HostProcess.Platform; const launcherPid = options?.launcherPid ?? startupParentPid; const getParentPid = options?.getParentPid ?? (() => process.ppid); @@ -33,3 +39,30 @@ export const awaitLauncherLoss = Effect.fn("launcherWatch.awaitLauncherLoss")(fu }); return yield* poll; }); + +/** + * Interrupts `run` when the launcher is lost, and exits the process if shutdown outlasts the + * grace period: a stuck cleanup step would otherwise keep holding the T3 home's ownership lock. + */ +export const stopOnLauncherLoss = ( + run: Effect.Effect, + options?: LauncherWatchOptions & { + readonly shutdownGrace?: Duration.Input; + readonly exit?: () => void; + }, +) => + Effect.raceFirst( + run, + awaitLauncherLoss(options).pipe( + Effect.andThen( + Effect.forkDetach( + Effect.sleep(options?.shutdownGrace ?? DEFAULT_SHUTDOWN_GRACE).pipe( + Effect.andThen(Effect.logWarning("backend shutdown timed out after launcher loss")), + Effect.andThen(Effect.sync(options?.exit ?? (() => process.exit(1)))), + ), + ), + ), + // End like SIGTERM does (interrupt-only exit, so the runtime forces process exit). + Effect.andThen(Effect.interrupt), + ), + ); diff --git a/apps/server/src/legacyServerOwner.ts b/apps/server/src/legacyServerOwner.ts index 9ed24c9c838f2..0b0b195ad38e7 100644 --- a/apps/server/src/legacyServerOwner.ts +++ b/apps/server/src/legacyServerOwner.ts @@ -1,9 +1,14 @@ // Effect-free so the service launcher shares the pre-lock owner identity check with server startup. +import { windowsPowerShellPath } from "@t3tools/shared/windowsSystem"; -export const legacyOwnerStartTimeCommand = (pid: number, platform: NodeJS.Platform) => { +export const legacyOwnerStartTimeCommand = ( + pid: number, + platform: NodeJS.Platform, + hostEnv: NodeJS.ProcessEnv, +) => { const windows = platform === "win32"; return { - command: windows ? "powershell.exe" : "ps", + command: windows ? windowsPowerShellPath(hostEnv) : "ps", args: windows ? [ "-NoProfile", diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 5949d1a3cf612..550ca4fddcd51 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -57,6 +57,9 @@ import * as McpToolAccess from "./McpToolAccess.ts"; import { forkMcpTools } from "./forkMcpTools.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; import * as McpWebhookTransport from "./McpWebhookTransport.ts"; +import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; +import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput"; +import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; @@ -1219,6 +1222,67 @@ const withToolAnalytics = return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer)); }); +/** + * ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on + * completion. Recording each thread-scoped call's compact result before returning lets adapters + * recover sent messages, IDs, counts, and error flags without depending on output passthrough. + */ +const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(function* ( + registration: Effect.Effect, +) { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions); + if (Option.isNone(mcpSessions)) { + return yield* registration; + } + const capturingServer = McpServer.McpServer.of({ + ...server, + addTool: Effect.fn("McpServer.addTool")(function (options) { + const toolName = options.tool.name; + // html_render tracks its own path/hash recovery with publish cleanup in HtmlRender. + if (toolName === HTML_RENDER_TOOL_NAME) { + return server.addTool(options); + } + return server.addTool({ + ...options, + // Untraced: withToolSpans already opens a span per tool call. + handle: Effect.fnUntraced(function* (payload) { + const scopeOption = yield* Effect.serviceOption( + McpInvocationContext.McpInvocationContext, + ); + const thread = Option.getOrUndefined(scopeOption)?.thread; + const epoch = + thread === undefined + ? undefined + : yield* mcpSessions.value.toolResultEpoch(thread.threadId); + return yield* options.handle(payload).pipe( + Effect.onExit((exit) => { + if (thread === undefined) return Effect.void; + if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) { + return Effect.void; + } + if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) { + return Effect.void; + } + const output = + exit._tag === "Success" + ? compactT3McpToolOutput(toolName, exit.value) + : { isError: true }; + return output === undefined + ? Effect.void + : mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, { + providerSessionId: thread.providerSessionId, + epoch, + }); + }), + ); + }), + }); + }), + }); + return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer)); +}); + /** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */ const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* ( registration: Effect.Effect, @@ -1301,8 +1365,10 @@ export const toolkitRegistration = , EX, ) => Layer.effectDiscard( withToolAnalytics( - withToolSpans( - withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + withToolResultCapture( + withToolSpans( + withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))), + ), ), ), ).pipe( @@ -1319,7 +1385,7 @@ const imageToolRegistration = , A, E, R, register: Effect.Effect, handlers: McpToolAccess.HandlersLayer, ) => - Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe( + Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe( Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)), ); @@ -1351,7 +1417,7 @@ export const layerOrchestratorToolkit = toolkitRegistration( export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer); -const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); +export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts index 96c71fcd773f9..19769a840a8c8 100644 --- a/apps/server/src/mcp/McpInvocationContext.test.ts +++ b/apps/server/src/mcp/McpInvocationContext.test.ts @@ -94,4 +94,14 @@ it("acts at an administrator's ceiling for a client approved above it", () => { ).toEqual({ runtimeMode: "approval-required", interactionMode: "plan" }); expect(modes(scope("auto-accept-edits"), "auto").runtimeMode).toBe("auto-accept-edits"); expect(modes(scope("full-access")).runtimeMode).toBe("full-access"); + // The scope says what the ceiling is, for a thread caller too. + expect( + McpInvocationContext.withRuntimeModeCeiling(scope("full-access"), "auto").runtimeModeCeiling, + ).toBe("auto"); + expect( + McpInvocationContext.withRuntimeModeCeiling( + { ...scope("full-access"), client: undefined }, + "auto", + ).runtimeModeCeiling, + ).toBe("auto"); }); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 0ba10af2d8c45..9bd2f08f37445 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -126,10 +126,12 @@ export const withRuntimeModeCeiling = ( scope: McpInvocationScope, ceiling: RuntimeMode | undefined, ): McpInvocationScope => { - if (ceiling === undefined || scope.client === undefined) return scope; + if (ceiling === undefined) return scope; + if (scope.client === undefined) return { ...scope, runtimeModeCeiling: ceiling }; const asked = scope.client.narrowedTo; return { ...scope, + runtimeModeCeiling: ceiling, client: { ...scope.client, narrowedTo: { @@ -155,6 +157,8 @@ export interface McpInvocationScope { readonly linkedEnvironments?: boolean; /** The Agent feedback mode here; `/mcp` reads it per request. Unset is off. */ readonly agentFeedback?: AgentFeedbackMode; + /** The broadest runtime mode an administrator lets a thread run in here. Unset is full access. */ + readonly runtimeModeCeiling?: RuntimeMode | undefined; /** True while Labs → Workflows is on here; `/mcp` reads it per request. Unset is off. */ readonly workflows?: boolean; /** diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts index 6cfd86bd3d836..cd1d28d37d4cf 100644 --- a/apps/server/src/mcp/McpToolAccess.test.ts +++ b/apps/server/src/mcp/McpToolAccess.test.ts @@ -137,6 +137,7 @@ const ProbeToolkit = Toolkit.make( }), }), Tool.make("writes_environment", probe), + Tool.make("writes_owner_work", probe), ); const ran = Effect.succeed({ ran: "ran" }); const probeHandlers: McpToolAccess.Handlers = { @@ -155,6 +156,7 @@ const probeHandlers: McpToolAccess.Handlers = { "stamped", ), writes_environment: McpToolAccess.writesEnvironment(() => ran), + writes_owner_work: McpToolAccess.writesOwnerWork("drive owner work", () => ran), }; const layerProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, probeHandlers); @@ -194,6 +196,7 @@ export const refusedAtCompileTime = () => { writes_threads: unchecked, starts_threads: unchecked, writes_environment: unchecked, + writes_owner_work: unchecked, }), ); }; @@ -249,6 +252,15 @@ const fullAccessLinkedClient: McpInvocationContext.McpInvocationScope = { ...fullAccessClient, client: { ...fullAccessClient.client!, linked: true }, }; +// An administrator's ceiling narrows every client to it. +const atCeilingClient: McpInvocationContext.McpInvocationScope = { + ...fullAccessClient, + runtimeModeCeiling: "auto", + client: { + ...fullAccessClient.client!, + narrowedTo: { runtimeMode: "auto", interactionMode: "default" }, + }, +}; const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) }; it.effect.each([ @@ -321,6 +333,18 @@ it.effect.each([ ["writes_environment", plan, {}, "capability_denied"], ["writes_environment", fullAccessClient, {}, "ran"], ["writes_environment", supervisedClient, {}, "capability_denied"], + + ["writes_owner_work", fullAccess, {}, "ran"], + ["writes_owner_work", supervised, {}, "capability_denied"], + ["writes_owner_work", plan, {}, "capability_denied"], + ["writes_owner_work", ended, {}, "parent_not_active"], + ["writes_owner_work", fullAccessClient, {}, "ran"], + ["writes_owner_work", supervisedClient, {}, "capability_denied"], + ["writes_owner_work", readOnlyClient, {}, "capability_denied"], + ["writes_owner_work", linkedClient, {}, "capability_denied"], + ["writes_owner_work", fullAccessLinkedClient, {}, "ran"], + ["writes_owner_work", atCeilingClient, {}, "ran"], + ["writes_environment", atCeilingClient, {}, "capability_denied"], ] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) => call(tool, scope, args).pipe( Effect.map((outcome) => expect(outcome).toBe(expected)), diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index d088b26ec182f..3d31698494c3f 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -33,6 +33,7 @@ import { import * as McpInvocationContext from "./McpInvocationContext.ts"; import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts"; import { + assertBroadestAccess, assertFullAccess, assertLiveCaller, assertTargetWithinLimits, @@ -192,6 +193,24 @@ export const writes = ( () => orchestratingCaller, ); +/** + * Drives work that runs for this environment's owner in modes its definition picks, such as a + * workflow run. `what` names it in a refusal, after "can" or "cannot". + */ +export const writesOwnerWork = ( + what: string, + handle: (params: P) => Effect.Effect, +) => { + const check = orchestratingCaller.pipe( + Effect.tap((caller) => assertNotLinked(caller, what)), + Effect.tap((caller) => assertBroadestAccess(caller, what)), + ); + return declare( + (params: P) => check.pipe(Effect.flatMap(() => handle(params))), + () => check, + ); +}; + /** Requires handler capability checks, not thread control; linked work is refused the same way. */ export const writesWithCapability = (handle: (params: P) => Effect.Effect) => declare( diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index fa65d75bf95f8..7c4a0f00eccfe 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -311,6 +311,8 @@ it("readThread preserves caller access errors and prefers activity-run status ov it("readThread pages cut-off text without splitting an emoji across pages", async () => { const text = "a😀bc"; const itemId = TurnItemId.make("turn-item-mcp-reasoning"); + const webhookToolItemId = TurnItemId.make("turn-item-mcp-webhook-tool"); + const webhookToken = "wJalrXUtnFEMI_K7MDENG-bPxRfiCYEXAMPLEKEY1234"; const projection = { thread: baseThread({ threadId: parentThreadId, @@ -349,6 +351,27 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn sourceItemId: TurnItemId.make(`turn-item-mcp-${index}`), item: { ...row.item, text: "x".repeat(600) }, })), + { + ...row, + position: 12, + sourceItemId: webhookToolItemId, + item: { + ...row.item, + type: "dynamic_tool", + toolName: "schedule_task", + input: { + prompt: "Triage {{body.action}}", + schedule: { + type: "webhook", + signature: { header: "x-hub-signature-256", encoding: "hex", prefix: "", secret: "s3" }, + }, + }, + output: { + webhookUrl: `https://relay.test/v1/hooks/0123456789abcdef/task-1/${webhookToken}`, + path: `/api/hooks/task-1/${webhookToken}`, + }, + }, + }, ]; const layer = layerOrchestratorService.pipe( @@ -429,6 +452,18 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }); expect(first.items).toHaveLength(10); expect(first).toMatchObject({ nextPosition: 9, hasMore: true }); + + const webhookTool = yield* service.readThread(makeScope(), { + threadId: parentThreadId, + view: "activity", + itemId: webhookToolItemId, + maxCharsPerItem: 2_000, + }); + const webhookToolText = webhookTool.items[0]?.text ?? ""; + expect(webhookToolText).toContain("/v1/hooks/0123456789abcdef/task-1/[withheld]"); + expect(webhookToolText).toContain("/api/hooks/task-1/[withheld]"); + expect(webhookToolText).not.toContain(webhookToken); + expect(webhookToolText).not.toContain('"s3"'); }).pipe(Effect.provide(layer), Effect.runPromise); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 551a84109cfa2..c99f9b0a6e1ad 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3950,6 +3950,8 @@ describe("OrchestratorMcpService provider resolution", () => { boundThread: OrchestrationV2ThreadShell | null, upserted: Ref.Ref, saved: ScheduledTask = tasks[0]!, + /** Stores each keyed create under the id its key derives, as the real service does. */ + created?: Ref.Ref>, ) => OrchestratorMcpService.layer.pipe( Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), @@ -3984,9 +3986,24 @@ describe("OrchestratorMcpService provider resolution", () => { Layer.mock(SecretRequests.SecretRequests)({}), Layer.mock(RemoteDelegation.RemoteDelegation)({}), Layer.mock(ScheduledTaskService.ScheduledTaskService)({ - list: () => Effect.succeed({ tasks }), - upsert: () => - Ref.update(upserted, (count) => count + 1).pipe(Effect.as({ task: saved })), + list: () => + created === undefined + ? Effect.succeed({ tasks }) + : Ref.get(created).pipe(Effect.map((stored) => ({ tasks: stored }))), + upsert: (input) => + Ref.update(upserted, (count) => count + 1).pipe( + Effect.andThen( + created === undefined || input.commandId === undefined + ? Effect.void + : Ref.set(created, [ + { + ...saved, + id: ScheduledTaskService.scheduledTaskIdForCommand(input.commandId), + }, + ]), + ), + Effect.as({ task: saved }), + ), }), ), ), @@ -4084,6 +4101,39 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect( + "refuses to replay a creation over a task whose thread now runs above the caller", + () => + Effect.gen(function* () { + const upserted = yield* Ref.make(0); + const created = yield* Ref.make>([]); + const bound = task({ threadId: boundThreadId }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + [bound], + liveThreadShell(boundThreadId, { runtimeMode: "full-access" }), + upserted, + bound, + created, + ), + ), + ); + const create = (prompt: string) => + mcp.scheduleTask(supervisedClient, { + projectId, + prompt, + schedule: { type: "webhook" }, + freshSession: true, + clientRequestId: "nightly", + }); + yield* create("Check the build"); + const error = yield* create("Something else").pipe(Effect.flip); + assert.equal(error.code, "runtime_mode_escalation_denied"); + assert.equal(yield* Ref.get(upserted), 1); + }), + ); + it.effect("reports a saved task even when its bound thread cannot be read", () => Effect.gen(function* () { const upserted = yield* Ref.make(0); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 1af1c7c254619..35f6312679712 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -138,6 +138,7 @@ import { taskPrompt, } from "./delegatedTaskModes.ts"; import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts"; +import { WITHHELD, withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts"; import * as SecretRequests from "../secrets/SecretRequests.ts"; import { sourceRefForMcpCaller } from "../identity/stampSource.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; @@ -1126,6 +1127,19 @@ function jsonText(value: unknown): string { } } +// Thread reads show a webhook's signing secret as withheld. + +const asRecord = (value: unknown) => + typeof value === "object" && value !== null ? (value as Readonly>) : null; + +function withoutWebhookSigningSecret(toolInput: unknown): unknown { + const input = asRecord(toolInput); + const schedule = asRecord(input?.schedule); + const signature = asRecord(schedule?.signature); + if (typeof signature?.secret !== "string") return toolInput; + return { ...input, schedule: { ...schedule, signature: { ...signature, secret: WITHHELD } } }; +} + function turnItemText(item: OrchestrationV2TurnItem): string | null { switch (item.type) { case "notification": @@ -1191,7 +1205,11 @@ function turnItemText(item: OrchestrationV2TurnItem): string | null { case "subagent": return item.result ?? item.progress ?? item.prompt; case "dynamic_tool": - return jsonText({ toolName: item.toolName, input: item.input, output: item.output }); + return jsonText({ + toolName: item.toolName, + input: withoutWebhookSigningSecret(item.input), + output: item.output, + }); } } @@ -1210,7 +1228,8 @@ function timelineItem(input: { readonly textOffset?: number; readonly messagesByThreadId: ReadonlyMap; }): OrchestratorMcpThreadTimelineItem { - const text = turnItemText(input.row.item); + const itemText = turnItemText(input.row.item); + const text = itemText === null ? null : withoutWebhookUrlToken(itemText); const offset = input.textOffset ?? 0; const end = textPageEnd(text, offset, input.maxChars); const textTruncated = text !== null && text.length > end; @@ -2370,6 +2389,21 @@ const make = Effect.gen(function* () { }, ); + const requireScheduledTaskWithinLimits = Effect.fn( + "OrchestratorMcpService.requireScheduledTaskWithinLimits", + )(function* ( + task: ScheduledTask, + limits: { + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + }, + ) { + for (const modes of yield* scheduledTaskRunModes(task)) { + yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); + yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); + } + }); + /** * A scheduled task the caller may change: one whose runs execute at modes no * broader than the caller's own, so editing its prompt cannot run work above @@ -2393,10 +2427,7 @@ const make = Effect.gen(function* () { if (task === undefined) { return yield* failure("task_not_found", `Scheduled task ${scheduledTaskId} was not found.`); } - for (const modes of yield* scheduledTaskRunModes(task)) { - yield* resolveRuntimeMode(limits.runtimeMode, modes.runtimeMode); - yield* resolveInteractionMode(limits.interactionMode, modes.interactionMode); - } + yield* requireScheduledTaskWithinLimits(task, limits); return task; }); @@ -2424,6 +2455,16 @@ const make = Effect.gen(function* () { .slice(0, 80) .replace(/[\uD800-\uDBFF]$/, ""); const title = input.title ?? (derivedTitle.length > 0 ? derivedTitle : "Scheduled task"); + // Scope the idempotency key by provider session so two callers + // reusing the same clientRequestId cannot collide on one task row. + const commandId = + input.clientRequestId === undefined + ? undefined + : stableCommandId({ + scope, + requestKey: input.clientRequestId, + operation: "schedule-task", + }); const upsertInput: ScheduledTaskUpsertInput = { title, prompt: input.prompt, @@ -2442,18 +2483,22 @@ const make = Effect.gen(function* () { interactionMode: limits.interactionMode, createdBy: "agent", creationSource: "mcp", - // Scope the idempotency key by provider session so two callers - // reusing the same clientRequestId cannot collide on one task row. - ...(input.clientRequestId === undefined - ? {} - : { - commandId: stableCommandId({ - scope, - requestKey: input.clientRequestId, - operation: "schedule-task", - }), - }), + ...(commandId === undefined ? {} : { commandId }), }; + // A replayed key rewrites the task it created, which its user may since have raised or + // rebound: that is an edit of the task as it now stands. + if (commandId !== undefined) { + const replayedId = ScheduledTaskService.scheduledTaskIdForCommand(commandId); + const { tasks } = yield* scheduledTasks + .list() + .pipe( + Effect.mapError((error) => + failure("orchestration_error", `Could not load scheduled task: ${error.message}`), + ), + ); + const replayed = tasks.find((candidate) => candidate.id === replayedId); + if (replayed !== undefined) yield* requireScheduledTaskWithinLimits(replayed, limits); + } const { task } = yield* scheduledTasks .upsert(upsertInput) .pipe( diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index 0f86dfafa1a3c..ce64d5bf60d24 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -1109,3 +1109,178 @@ it.effect("keeps each thread's current tab when threads share a provider session expect(routed[0]!.agentSessionId).not.toBe(routed[1]!.agentSessionId); }), ); + +const connectTabHost = Effect.fn("connectTabHost")(function* ( + broker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], +) { + const openTabs: PreviewTabId[] = []; + const routed: RoutedRequest[] = []; + const connected = yield* Deferred.make(); + const requests = requestsFrom( + yield* broker.connect(makeHost({ supportedOperations: ["open", "snapshot", "close"] })), + () => Deferred.doneUnsafe(connected, Effect.void), + ); + yield* Stream.runForEach(requests, (request) => { + routed.push(request); + const reply = { clientId: "client-1", connectionId: request.connectionId }; + if (request.operation === "open") { + const tabId = PreviewTabId.make(`tab-${routed.length}`); + openTabs.push(tabId); + return broker.respond({ + ...reply, + requestId: request.requestId, + ok: true, + result: { tabId }, + }); + } + const tabId = request.tabId ?? openTabs.at(-1); + if (tabId === undefined || !openTabs.includes(tabId)) { + return broker.respond({ + ...reply, + requestId: request.requestId, + ok: false, + error: { _tag: "PreviewAutomationTabNotFoundError", message: "No tab." }, + }); + } + if (request.operation === "close") openTabs.splice(openTabs.indexOf(tabId), 1); + return broker.respond({ ...reply, requestId: request.requestId, ok: true, result: {} }); + }).pipe(Effect.forkScoped); + yield* Deferred.await(connected); + return { routed, openTabs }; +}); + +const openTwoTabs = Effect.fn("openTwoTabs")(function* ( + broker: PreviewAutomationBroker.PreviewAutomationBroker["Service"], +) { + const first = yield* broker.invoke<{ tabId: PreviewTabId }>({ + scope, + operation: "open", + input: {}, + }); + const second = yield* broker.invoke<{ tabId: PreviewTabId }>({ + scope, + operation: "open", + input: { reuseExistingTab: false }, + }); + return [first.tabId, second.tabId] as const; +}); + +it.effect("forgets a current tab that closed elsewhere instead of naming it", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const { routed, openTabs } = yield* connectTabHost(broker); + yield* broker.invoke({ scope, operation: "open", input: {} }); + openTabs.splice(0); + + const error = yield* broker + .invoke({ scope, operation: "snapshot", input: {} }) + .pipe(Effect.flip); + yield* broker.invoke({ scope, operation: "snapshot", input: {} }).pipe(Effect.ignore); + + expect(error.message).toBe( + "No active preview tab was found for snapshot. Call preview_open first.", + ); + expect(routed.at(-1)?.tabId).toBeUndefined(); + }), + ), +); + +it.effect("closing the current tab leaves implicit calls to the remaining tab", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const { routed } = yield* connectTabHost(broker); + const [, second] = yield* openTwoTabs(broker); + yield* broker.invoke({ scope, operation: "close", input: {}, tabId: second }); + + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + + expect(routed.at(-1)?.tabId).toBeUndefined(); + }), + ), +); + +it.effect("closing another tab keeps the current tab", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const { routed } = yield* connectTabHost(broker); + const [first, second] = yield* openTwoTabs(broker); + yield* broker.invoke({ scope, operation: "close", input: {}, tabId: first }); + + yield* broker.invoke({ scope, operation: "snapshot", input: {} }); + + expect(routed.at(-1)?.tabId).toBe(second); + }), + ), +); + +it.effect("a late tab-not-found reply keeps a tab another call made current", () => + Effect.scoped( + Effect.gen(function* () { + const broker = yield* makeBroker; + const tabA = PreviewTabId.make("tab-a"); + const tabB = PreviewTabId.make("tab-b"); + const connected = yield* Deferred.make(); + const explicitSeen = yield* Deferred.make(); + const implicitSeen = yield* Deferred.make(); + const releaseExplicit = yield* Deferred.make(); + const releaseImplicit = yield* Deferred.make(); + const events = yield* broker.connect(makeHost()); + yield* Stream.runForEach(events, (event) => { + if (event.type === "connected") return Deferred.succeed(connected, undefined); + const request = event.request; + const reply = { + clientId: "client-1", + connectionId: event.connectionId, + requestId: request.requestId, + }; + const marker = (request.input as { marker?: string }).marker; + return Effect.gen(function* () { + if (marker === "explicit") { + yield* Deferred.succeed(explicitSeen, undefined); + yield* Deferred.await(releaseExplicit); + yield* broker.respond({ ...reply, ok: true, result: { url: "tab-b" } }); + } else if (marker === "implicit") { + yield* Deferred.succeed(implicitSeen, undefined); + yield* Deferred.await(releaseImplicit); + yield* broker.respond({ + ...reply, + ok: false, + error: { _tag: "PreviewAutomationTabNotFoundError", message: "Tab A closed." }, + }); + } else { + yield* broker.respond({ + ...reply, + ok: true, + result: { url: request.tabId ?? "host-default" }, + }); + } + }).pipe(Effect.forkScoped, Effect.asVoid); + }).pipe(Effect.forkScoped); + yield* Deferred.await(connected); + yield* broker.invoke({ scope, operation: "snapshot", input: {}, tabId: tabA }); + const explicit = yield* broker + .invoke({ scope, operation: "snapshot", input: { marker: "explicit" }, tabId: tabB }) + .pipe(Effect.forkScoped); + yield* Deferred.await(explicitSeen); + const implicit = yield* broker + .invoke({ scope, operation: "snapshot", input: { marker: "implicit" } }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Deferred.await(implicitSeen); + yield* Deferred.succeed(releaseExplicit, undefined); + yield* Fiber.join(explicit); + yield* Deferred.succeed(releaseImplicit, undefined); + yield* Fiber.join(implicit); + + const result = yield* broker.invoke<{ url: string }>({ + scope, + operation: "snapshot", + input: {}, + }); + + expect(result.url).toBe("tab-b"); + }), + ), +); diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index cc3230e5b68b5..793daedc6d82b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -678,35 +678,56 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { onSome: (value) => Effect.succeed(value as A), }); }); - const result = yield* awaitResponse().pipe(Effect.ensuring(removePending)); - if (input.updateCurrentTab === false) return result; - const responseTabId = readResultTabId(result); - const resultTabId = responseTabId === undefined ? input.tabId : responseTabId; - if (resultTabId === undefined) return result; const assignmentKey = hostAssignmentKey(input.scope); - yield* SynchronizedRef.update(state, (current) => { - const assignment = current.assignments.get(assignmentKey); - if ( - !assignment || - assignment.connectionId !== connection.connectionId || - assignment.queue !== connection.queue || - (assignment.tabSequence ?? -1) > requestSequence - ) { - return current; - } - const assignments = new Map(current.assignments); - if (resultTabId === null) { + const rememberCurrentTab = (tabId: PreviewTabId | null, replacing?: PreviewTabId) => + SynchronizedRef.update(state, (current) => { + const assignment = current.assignments.get(assignmentKey); + if ( + !assignment || + assignment.connectionId !== connection.connectionId || + assignment.queue !== connection.queue || + (assignment.tabSequence ?? -1) > requestSequence || + (replacing !== undefined && assignment.tabId !== replacing) + ) { + return current; + } const { tabId: _tabId, ...withoutTabId } = assignment; - assignments.set(assignmentKey, { ...withoutTabId, tabSequence: requestSequence }); - } else { + const assignments = new Map(current.assignments); assignments.set(assignmentKey, { - ...assignment, - ...(resultTabId === undefined ? {} : { tabId: resultTabId }), + ...withoutTabId, + ...(tabId === null ? {} : { tabId }), tabSequence: requestSequence, }); - } - return { ...current, assignments }; - }); + return { ...current, assignments }; + }); + const result = yield* awaitResponse().pipe( + Effect.ensuring(removePending), + Effect.catchTags({ + PreviewAutomationTabNotFoundError: (error) => { + if (input.tabId !== undefined || error.tabId === undefined) return Effect.fail(error); + // The tab came from the assignment, so neither name it nor keep targeting it. + const { tabId: _tabId, ...fields } = error; + const implicitError = new PreviewAutomationTabNotFoundError({ + ...fields, + cause: error.cause, + }); + return input.updateCurrentTab === false + ? Effect.fail(implicitError) + : rememberCurrentTab(null, error.tabId).pipe( + Effect.andThen(Effect.fail(implicitError)), + ); + }, + }), + ); + if (input.updateCurrentTab === false) return result; + if (input.operation === "close") { + // A closed tab never becomes current; closing the current one leaves none. + if (requestContext.tabId !== undefined) yield* rememberCurrentTab(null, requestContext.tabId); + return result; + } + const responseTabId = readResultTabId(result); + const resultTabId = responseTabId === undefined ? input.tabId : responseTabId; + if (resultTabId !== undefined) yield* rememberCurrentTab(resultTabId); return result; }); diff --git a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts index aff11dacad26e..b2e9a90bb7d3c 100644 --- a/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts +++ b/apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts @@ -378,7 +378,7 @@ const cancelBackgroundOnlyTask = ( (event) => event.type === "run.updated" && event.payload.id === child.turn.runId && - event.payload.status === "waiting", + event.payload.status === "completed", ); const nativeSubagentEvents = [ { @@ -560,7 +560,8 @@ const cancelBackgroundOnlyTask = ( } const before = yield* service.taskStatus(scope, task.id); assert.equal(before.status, "running"); - assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working"); + // The child's run completes when its turn ends, before its checkpoint capture runs. + assert.equal(before.workState, cancelAt === "turn" ? "working" : "waiting_for_children"); const parentTask = Effect.map(orchestrator.getThreadProjection(parentThreadId), (parent) => parent.subagents.find((entry) => entry.id === task.id), @@ -592,7 +593,8 @@ const cancelBackgroundOnlyTask = ( event.payload.type === "run_interrupt_request", ), ); - assert.equal((yield* parentTask)?.status, "running"); + // The child's turn already ended, so the cancel settles its finished run in this commit. + assert.equal((yield* parentTask)?.status, "interrupted"); return { scope, taskId: task.id, settled: undefined }; } if (cancelAt === "refused") { @@ -651,7 +653,11 @@ const cancelBackgroundOnlyTask = ( // Stop reached the provider turn that owns the shell. if (background === "command") assert.deepEqual(interrupted, [["bg-sleep"]]); assert.equal(childAfter.runs.length, cancelAt === "monitor" || cancelAt === "turn" ? 2 : 1); - assert.equal(childAfter.runs[0]!.status, "completed"); + // A Stop accepted before the run's checkpoint settled it ends that run as interrupted. + assert.equal( + childAfter.runs.find((run) => run.id === child.turn.runId)?.status, + cancelAt === "checkpoint" || cancelAt === "turn" ? "interrupted" : "completed", + ); assert.deepEqual( childAfter.runtimeRequests.map((request) => [request.id, request.status]), [ diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 7105f3a0e2923..0d0c551252887 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -179,6 +179,7 @@ const make = Effect.gen(function* () { const project = yield* loadProject(scope, projection.thread.projectId); const projectCwd = project.workspaceRoot; + const projectCommands = TaskFolders.linkRunsProjectCommands(projection.thread.linkOrigin); // A project that tracks repositories moves into a task folder: its own folder, which need // not be a repository, and a worktree of each tracked one. @@ -284,6 +285,7 @@ const make = Effect.gen(function* () { projectStart: { refName: worktreeBaseRef, baseRefName }, baseBranch: input.baseRef, startFromOrigin, + projectCommands, }) .pipe( Effect.map((created) => { @@ -332,6 +334,7 @@ const make = Effect.gen(function* () { root: worktree.taskFolder, force: true, forget: true, + projectCommands, deleteBranch: worktree.refName, }), ).pipe(Effect.ignoreCause({ log: true })); diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index d21495f0ff7c7..abcb7fcd29e05 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -5,6 +5,7 @@ import type { import { CommandId, type EnvironmentId, + isRuntimeModeAbove, OrchestratorMcpFailure, type ProjectId, type ProviderInstanceId, @@ -220,6 +221,23 @@ export const assertFullAccess = (context: Caller, message: string) => ? Effect.void : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message })); +/** + * For work whose definition picks its own modes: the caller must hold the broadest modes a + * thread may run in here, full access or an administrator's ceiling below it. + */ +export const assertBroadestAccess = (context: Caller, what: string) => { + const broadest = context.scope.runtimeModeCeiling ?? "full-access"; + return !isRuntimeModeAbove(broadest, context.limits.runtimeMode) && + context.limits.interactionMode === "default" + ? Effect.void + : Effect.fail( + new OrchestratorMcpFailure({ + code: "capability_denied", + message: `Only a caller with ${broadest}/default access can ${what}, because that work picks its own modes. This caller is limited to ${context.limits.runtimeMode}/${context.limits.interactionMode}.`, + }), + ); +}; + export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) => projectId !== undefined ? Effect.succeed(projectId) diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 33c356af4e7e1..c1d35ace86940 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -416,6 +416,47 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both ), ); +it.effect("captures send_to_user results for providers that drop MCP outputs", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const draft = "### Status\n\nAll checks passed."; + const result = yield* server + .callTool({ name: "send_to_user", arguments: { message: draft } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect(result.isError).not.toBe(true); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toEqual( + { sentMessage: draft }, + ); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toBe( + undefined, + ); + + const invalid = yield* server + .callTool({ name: "send_to_user", arguments: { message: "" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provideService(McpSchema.McpServerClient, client), + Effect.flip, + ); + expect(invalid).toMatchObject({ _tag: "InvalidParams" }); + expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: "" })).toEqual({ + isError: true, + }); + }).pipe( + Effect.provide( + McpHttpServer.layerMessageToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provideMerge(McpProviderSessions.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + ), + ), + ), +); + it.effect("records only failed calls of tools that hand off no work", () => { // Recording runs detached from the tool response, so the first event is awaited. const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>(); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index d03b038ee0780..a40d15252fbb8 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - a directory junction needs no privilege on Windows. +import * as NodeFSP from "node:fs/promises"; import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; import { expect, it } from "@effect/vitest"; import { @@ -567,10 +569,14 @@ it.effect("a launch binds only an existing checkout that is one of the project's Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }); + // Git registers resolved paths, and a launch keeps the registered one. + const root = yield* fileSystem.realPath( + yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-launch-worktree-" }), + ); const repo = path.join(root, "repo"); const worktree = path.join(root, "feature"); const outside = path.join(root, "outside"); + const alias = path.join(root, "alias"); yield* fileSystem.makeDirectory(repo); yield* fileSystem.makeDirectory(outside); @@ -615,9 +621,13 @@ it.effect("a launch binds only an existing checkout that is one of the project's code: "invalid_request", }); } + // The thread keeps the registered worktree path when launched through a link to it. + yield* Effect.promise(() => NodeFSP.symlink(worktree, alias, "junction")); + expect((yield* launchInto(alias)).at(-1)?.result).toMatchObject({ projectId }); expect(launched.map((launch) => launch.workspaceStrategy)).toEqual([ { type: "existing_worktree", worktreePath: worktree }, { type: "existing_worktree", worktreePath: repo }, + { type: "existing_worktree", worktreePath: worktree }, ]); yield* fileSystem.remove(worktree, { recursive: true }); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 9406e4f593b43..8bf099bc20a0e 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -88,24 +88,29 @@ function worktreeCheckHint( }`; } -/** Require project worktrees so launches cannot target arbitrary host directories. */ -const assertProjectWorktree = Effect.fn("mcp.assertProjectWorktree")(function* ( +/** + * Require project worktrees so launches cannot target arbitrary host directories. Returns the + * path Git registered, so the thread stays bound to that worktree. + */ +const projectWorktreePath = Effect.fn("mcp.assertProjectWorktree")(function* ( workspaceRoot: string, worktreePath: string, ) { const git = yield* GitVcsDriver.GitVcsDriver; const fileSystem = yield* FileSystem.FileSystem; const real = (path: string) => fileSystem.realPath(path).pipe(Effect.orElseSucceed(() => path)); - const worktrees = yield* git.listWorktreePaths(workspaceRoot).pipe( - Effect.flatMap((paths) => Effect.forEach(paths, real)), - Effect.orElseSucceed((): ReadonlyArray => []), - ); - if (!worktrees.includes(yield* real(worktreePath))) - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: - "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", - }); + const registered = yield* git + .listWorktreePaths(workspaceRoot) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const requested = yield* real(worktreePath); + for (const candidate of registered) { + if ((yield* real(candidate)) === requested) return candidate; + } + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: + "worktreePath must be one of the project's git worktrees. t3_worktree_list shows them.", + }); }); /** The composer falls back to the project's t3.json when no setting picks the mode. */ @@ -308,15 +313,23 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { }), ), ); - if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") - yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); + const workspaceStrategy = + project !== undefined && input.workspaceStrategy?.type === "existing_worktree" + ? { + ...input.workspaceStrategy, + worktreePath: yield* projectWorktreePath( + project.workspaceRoot, + input.workspaceStrategy.worktreePath, + ), + } + : input.workspaceStrategy; if (!replaying && input.modelSelection !== undefined) { const { instanceId, model } = input.modelSelection; const registry = yield* ProviderRegistry.ProviderRegistry; // The thread runs in this folder, whose own provider config can add models. const cwd = - input.workspaceStrategy?.type === "existing_worktree" - ? input.workspaceStrategy.worktreePath + workspaceStrategy?.type === "existing_worktree" + ? workspaceStrategy.worktreePath : project?.workspaceRoot; const requireModel = ( providers: ReadonlyArray, @@ -358,14 +371,14 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { // An outside caller that names no workspace follows the new-threads-in-a-worktree // default, as the composer does. const requestedStrategy = - input.workspaceStrategy === undefined && + workspaceStrategy === undefined && caller === undefined && project !== undefined && projectSettings !== undefined && (projectSettings.defaultThreadEnvMode ?? (yield* projectFileThreadEnvMode(project.workspaceRoot))) === "worktree" ? yield* defaultWorktreeStrategy(project.workspaceRoot) - : input.workspaceStrategy; + : workspaceStrategy; // An omitted startFromOrigin follows the new-worktree setting, as the composer and // t3_worktree_handoff do. Otherwise a stale local branch silently becomes the base. const strategy = diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index f0b9db206bbb6..95f816f151b9d 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -944,6 +944,40 @@ describe("source control tools", () => { }), ); + it.effect("reads an Azure DevOps PR by number at its organization and project", () => + Effect.gen(function* () { + const asked: Array = []; + const harness = yield* makeHarness({ + project: makeProject({ + canonicalKey: "dev.azure.com/contoso/project/_git/repo", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://contoso@dev.azure.com/contoso/project/_git/repo", + }, + provider: SourceControlProviderKind.make("azure-devops"), + displayName: "contoso/project/_git/repo", + owner: "contoso", + name: "repo", + }), + pullRequests: { + detail: (ref) => Effect.sync(() => asked.push(ref)).pipe(Effect.as(detail)), + activity: () => Effect.succeed(activity), + }, + }); + const result = yield* harness.call("pull_request_read", { number: 123 }); + expect(result).toMatchObject({ + host: "dev.azure.com", + repository: "contoso/project/_git/repo", + number: 123, + url: "https://dev.azure.com/contoso/project/_git/repo/pullrequest/123", + }); + expect(asked).toMatchObject([ + { host: "dev.azure.com", repository: "contoso/project/_git/repo", number: 123 }, + ]); + }), + ); + it.effect("pages a long conversation and the PR list through the cursors they return", () => Effect.gen(function* () { const comment = (body: string) => diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index c1cd42c4567d9..646f94de8e541 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -421,10 +421,8 @@ const make = Effect.gen(function* () { // Layers below the target are pinned to the heads read here; the host refuses if any moved. const stackMergeScope = Effect.fnUntraced(function* ( ref: PullRequestRef, - input: { readonly expectedHeadSha: string; readonly auto?: boolean | undefined }, + input: { readonly expectedHeadSha: string }, ) { - if (input.auto === true) - return yield* new PullRequestForgeError({ detail: "A stack merge cannot wait with auto." }); const stack = yield* pullRequests .stack(ref, { bypassCache: true }) .pipe(Effect.mapError(forgeFailure)); diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 5b213706aba97..446b300b9a40b 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -799,7 +799,7 @@ const MergePullRequestTool = Tool.make("pull_request_merge", { ), stack: Schema.optional( Schema.Boolean.annotate({ - description: "Merge this PR and every open stack layer below it at once. Not with auto.", + description: "Merge this PR and every open stack layer below it at once.", }), ), }), diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index 77b7036681ad6..cc7a7242ddfd6 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -12,7 +12,13 @@ import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import * as WorkflowHandlers from "./handlers.ts"; import { WorkflowToolkit } from "./tools.ts"; -const handlersWith = (workflows: Partial) => +const fullAccess = { sessionId: "session-1", label: "t3 CLI", access: "full-access" } as const; +const supervised = { sessionId: "session-2", label: "Bot", access: "approval-required" } as const; + +const handlersWith = ( + workflows: Partial, + scope: Partial = {}, +) => McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( Layer.provideMerge( Layer.mergeAll( @@ -22,9 +28,10 @@ const handlersWith = (workflows: Partial) => environmentId: EnvironmentId.make("environment:workflow"), requestNamespace: "client:workflow", thread: undefined, - client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + client: fullAccess, capabilities: new Set(["orchestration" as const]), issuedAt: 0, + ...scope, }), Layer.mock(Workflows.Workflows)(workflows), ), @@ -100,3 +107,93 @@ it.effect("signal refuses a run destination mixed with a channel destination", ( expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); }), ); + +const emptyRun = { run: undefined, steps: [], references: [] } as never; +const call = (input: Record) => + Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* toolkit.handle("t3_workflow", input as never).pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ); + }); + +const changes = [ + { action: "start", workflow: "release", idempotencyKey: "trial" }, + { action: "signal", runId: "run-1", wait: "review", value: { choice: "yes" } }, + { action: "resume", runId: "run-1" }, + { action: "cancel", runId: "run-1" }, + { action: "store_set", key: "switch", value: true }, + { action: "store_delete", key: "switch" }, +]; + +it.effect("a caller below the broadest mode reads runs but does not start or change them", () => + Effect.gen(function* () { + const reached: Array = []; + const reach = (name: string) => () => Effect.sync(() => void reached.push(name)); + const results = yield* Effect.forEach( + [...changes, { action: "list" }, { action: "questions" }], + call, + ).pipe( + Effect.provide( + handlersWith( + { + start: () => Effect.sync(() => (reached.push("start"), { runId: "run-1" })), + signal: () => Effect.sync(() => (reached.push("signal"), "delivered" as const)), + resume: reach("resume"), + cancel: reach("cancel"), + storeSet: reach("storeSet"), + storeDelete: reach("storeDelete"), + stored: () => Effect.succeed([]), + get: () => Effect.succeed(emptyRun), + list: () => Effect.succeed([]), + questions: Effect.succeed([]), + }, + { client: supervised }, + ), + ), + ); + for (const result of results.slice(0, changes.length)) { + expect(result).toMatchObject({ code: "capability_denied" }); + } + expect(reached).toEqual([]); + expect(results.slice(changes.length)).toEqual([{ runs: [] }, { questions: [] }]); + }), +); + +it.effect("hook paths go only to a caller at the broadest mode", () => + Effect.gen(function* () { + const hooks = [{ workflow: "release", name: "push", path: "/api/hooks/wf-release.push/token" }]; + const read = (client: McpInvocationContext.McpClientCaller) => + call({ action: "hooks" }).pipe( + Effect.provide(handlersWith({ hooks: Effect.succeed(hooks as never) }, { client })), + ); + expect(yield* read(fullAccess)).toEqual({ hooks }); + const refused = yield* read(supervised); + expect(refused).toMatchObject({ code: "capability_denied" }); + expect(JSON.stringify(refused)).not.toContain("token"); + }), +); + +it.effect("under an administrator's ceiling, a caller at the ceiling starts runs", () => + Effect.gen(function* () { + const start = { action: "start", workflow: "release", idempotencyKey: "trial" }; + const workflows = { + start: () => Effect.succeed({ runId: "run-1" }), + get: () => Effect.succeed(emptyRun), + }; + const narrowedTo = (runtimeMode: "auto" | "approval-required") => ({ + runtimeModeCeiling: "auto" as const, + client: { ...fullAccess, narrowedTo: { runtimeMode, interactionMode: "default" as const } }, + }); + expect( + yield* call(start).pipe(Effect.provide(handlersWith(workflows, narrowedTo("auto")))), + ).not.toMatchObject({ code: "capability_denied" }); + expect( + yield* call(start).pipe( + Effect.provide(handlersWith(workflows, narrowedTo("approval-required"))), + ), + ).toMatchObject({ code: "capability_denied" }); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index 7ebc6ac0cf7a4..0bc0c97d8e9fa 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -41,7 +41,7 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { return yield* workflows.get(runId).pipe(Effect.mapError(refused)); }), ), - McpToolAccess.writes((input) => + McpToolAccess.writesOwnerWork("start or change workflow runs, or read hook paths", (input) => Effect.gen(function* () { const workflows = yield* Workflows.Workflows; // A hook's path holds its secret, and posting to it starts a run. diff --git a/apps/server/src/mcp/toolkits/workflow/tools.test.ts b/apps/server/src/mcp/toolkits/workflow/tools.test.ts index 7dad64df1fa73..929d205cce874 100644 --- a/apps/server/src/mcp/toolkits/workflow/tools.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/tools.test.ts @@ -3,10 +3,12 @@ import * as Schema from "effect/Schema"; import { WorkflowToolkit } from "./tools.ts"; -it("keeps exact wait names and store keys", () => { +it("keeps exact wait names, store keys and channels", () => { const decode = Schema.decodeUnknownSync(WorkflowToolkit.tools.t3_workflow.parametersSchema); expect(decode({ action: "signal", runId: "run-1", wait: "review " }).wait).toBe("review "); expect(() => decode({ action: "signal", runId: "run-1", wait: " " })).toThrow(); expect(decode({ action: "store", key: "team " }).key).toBe("team "); expect(() => decode({ action: "store_set", key: " ", value: 1 })).toThrow(); + expect(decode({ action: "signal", workflow: "w", channel: "review " }).channel).toBe("review "); + expect(() => decode({ action: "signal", workflow: "w", channel: " " })).toThrow(); }); diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts index 847c0b191dd35..40f6cb36ffccc 100644 --- a/apps/server/src/mcp/toolkits/workflow/tools.ts +++ b/apps/server/src/mcp/toolkits/workflow/tools.ts @@ -10,7 +10,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; export const WORKFLOW_READ_ACTIONS = ["list", "read", "questions", "store"] as const; -// Wait names and store keys match exactly, so they keep their spaces. +// Wait names, store keys and channels match exactly, so they keep their spaces. const ExactName = Schema.String.check( Schema.makeFilter((name: string) => name.trim().length > 0, { expected: "a non-blank string" }), ); @@ -36,7 +36,7 @@ const WorkflowTool = Tool.make("t3_workflow", { status: Schema.optional(WorkflowRunStatus), wait: Schema.optional(ExactName), key: Schema.optional(ExactName), - channel: Schema.optional(TrimmedNonEmptyString), + channel: Schema.optional(ExactName), value: Schema.optional(Schema.Json), signalId: Schema.optional( TrimmedNonEmptyString.annotate({ diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 54c1137870e73..f4ff952bf888d 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -2959,10 +2959,161 @@ describe("AcpAdapterV2", () => { (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, ProviderAdapter.ProviderCompactionUnsupportedError, ); + assert.isTrue( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + ); } }).pipe(Effect.provide(layerTest)), ); + // A start that cannot reopen its session may be on a session the agent lost. It is not a refusal + // before the prompt, so the server's recovery for an unusable session still runs. + it.live("does not mark a start whose session failed to reopen as refused before its prompt", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-reopen-failure"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment: () => ({ T3_ACP_FAIL_LOAD_SESSION: "1" }), + }), + }, + selfInvocation, + }); + const threadId = ThreadId.make("thread-acp-reopen-failure"); + 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-reopen-failure"), + modelSelection, + runtimePolicy, + }); + const thread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy }); + const lostThread: OrchestrationV2ProviderThread = { + ...thread, + nativeThreadRef: { driver: ACP_TEST_DRIVER, nativeId: "lost-session", strength: "strong" }, + }; + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread: lostThread, + instanceId, + runtimePolicy, + now, + ordinal: 1, + }), + ) + .pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.notEqual( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + true, + ); + const methods = yield* pollProtocolMethods(protocolEvents); + assert.isTrue(methods.includes("session/load") || methods.includes("session/resume")); + assert.notInclude(methods, "session/prompt"); + }).pipe(Effect.provide(layerTest)), + ); + + // Only refusals that leave the session usable mark a start as refused before its prompt. A setup + // step other than the model can fail because the session is gone. + it.live("does not mark a start whose session setup failed as refused before its prompt", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const mockAgentPath = yield* bundledMockAgentPath; + const protocolEvents = yield* Queue.unbounded(); + const instanceId = ProviderInstanceId.make("acp-test-setup-failure"); + const threadId = ThreadId.make("thread-acp-setup-failure"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + protocolEvents, + environment: { T3_ACP_FAIL_SET_MODE_CONFIG_OPTION: "1" }, + }), + }, + selfInvocation: yield* resolveSelfInvocation(), + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const opened = { instanceId, model: "composer-2" } as const; + const withMode = { + instanceId, + model: "composer-2", + options: [{ id: ACP_SESSION_MODE_OPTION_ID, value: "code" }], + } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-setup-failure"), + modelSelection: opened, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: opened, + runtimePolicy, + }); + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal: 1, + modelSelection: withMode, + }), + ) + .pipe(Effect.flip); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError); + assert.notInstanceOf( + (error as ProviderAdapter.ProviderAdapterTurnStartError).cause, + ProviderAdapter.ProviderCompactionUnsupportedError, + ); + assert.notEqual( + (error as ProviderAdapter.ProviderAdapterTurnStartError).refusedBeforePrompt, + true, + ); + // The start reached the mode step the agent rejected, and sent no prompt. + const outgoing = Array.from(yield* Queue.takeAll(protocolEvents)).filter( + (event) => event.direction === "outgoing", + ); + assert.isTrue( + outgoing.some( + (event) => + rawProtocolMethod(event) === "session/set_config_option" && + rawProtocolRequestParam(event, "configId") === "mode", + ), + ); + assert.notInclude(outgoing.map(rawProtocolMethod), "session/prompt"); + }).pipe(Effect.provide(layerTest)), + ); + it.live("reapplies a selection after a switch away from it failed partway", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -5806,12 +5957,26 @@ describe("AcpAdapterV2", () => { now: yield* DateTime.now, }), ); - yield* runtime.events.pipe( - Stream.filter((event) => event.type === "turn.terminal"), - Stream.runHead, + const startup = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.filter( + (event) => + event.type === "provider_session.updated" || + (event.type === "provider_turn.updated" && event.providerTurn.status === "running"), + ), + Stream.runCollect, ); assert.equal(runtimeOrdinalSeen, 2); assert.lengthOf(runtimeInputs, 2); + // Loading the thread into the replacement agent is reported, and cleared before the turn runs. + assert.deepEqual( + Array.from(startup, (event) => + event.type === "provider_session.updated" + ? (event.providerSession.startupPhase ?? null) + : "turn running", + ).slice(0, 3), + ["resume", null, "turn running"], + ); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 5cbb4975e5e57..3d98f79f8fb8a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -13,7 +13,12 @@ import { ThreadId, } from "@t3tools/contracts"; import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { + compactDynamicToolOutput, + htmlRenderFromToolItem, + previewRecordingIdFromToolItem, + sentMessageFromToolItem, +} from "@t3tools/shared/toolOutput"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -989,6 +994,329 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); }).pipe(Effect.provide(layerSession)), ); + + it.effect( + "recovers T3 MCP tool results across omitted outputs, replays, errors, and turn boundaries", + () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + let promptIndex = 0; + let turn1Epoch = 0; + const instanceId = ProviderInstanceId.make("antigravity-mcp-result-test"); + const threadId = ThreadId.make("thread-antigravity-mcp-result"); + const statusUpdate = "### Current Status\n\nAll checks are passing."; + const inProgressText = "Streamed while running."; + const lateText = "Confirmed on a later completion."; + const lateErrorText = "Late explicit error."; + const unfinishedText = "Still running when turn ended."; + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Effect.gen(function* () { + promptIndex += 1; + const send = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdate === undefined + ? Effect.die("the adapter must handle session updates") + : sessionUpdate( + normalizeAntigravitySessionUpdate({ + sessionId: "mock-session-1", + update, + }), + ); + const startTool = ( + toolCallId: string, + toolName: string, + rawInput: Record, + ) => + send({ + sessionUpdate: "tool_call", + toolCallId, + title: `Run mcp_t3-code_${toolName}`, + kind: "other", + status: "in_progress", + rawInput, + }); + const updateTool = ( + toolCallId: string, + status: "in_progress" | "completed" | "failed", + rawOutput?: unknown, + ) => + send({ + sessionUpdate: "tool_call_update", + toolCallId, + status, + ...(rawOutput === undefined ? {} : { rawOutput }), + }); + const recordSend = (message: string) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ); + + if (promptIndex === 2) { + // A Turn 1 handler finishing after Turn 1 closed must be rejected by epoch. + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: unfinishedText }, + { sentMessage: unfinishedText }, + { epoch: turn1Epoch }, + ); + yield* startTool("turn2-leaked-check", "send_to_user", { + message: unfinishedText, + }); + yield* updateTool("turn2-leaked-check", "completed", "Summary of turn 2"); + return { stopReason: "end_turn" as const }; + } + + turn1Epoch = yield* mcpSessions.toolResultEpoch(threadId); + + // agy 1.5.x adds toolSummary and omits output on completion, then may replay. + yield* startTool("send-empty", "send_to_user", { + message: statusUpdate, + toolSummary: "Send status update", + }); + yield* recordSend(statusUpdate); + yield* updateTool("send-empty", "completed"); + yield* updateTool("send-empty", "in_progress"); + yield* updateTool("send-empty", "completed", "Summary replay"); + + // Streaming output during in_progress still drains on completion. + yield* startTool("send-streaming", "send_to_user", { message: inProgressText }); + yield* recordSend(inProgressText); + yield* updateTool("send-streaming", "in_progress", { + sentMessage: inProgressText, + }); + yield* updateTool("send-streaming", "completed", { + sentMessage: inProgressText, + }); + yield* startTool("send-streaming-unpublished", "send_to_user", { + message: inProgressText, + }); + yield* updateTool("send-streaming-unpublished", "completed"); + + // Explicit MCP error preserves diagnostic content across summary replays. + yield* startTool("send-errored", "send_to_user", { message: "Denied" }); + yield* updateTool("send-errored", "completed", { + result: { + isError: true, + structuredContent: { sentMessage: "Denied" }, + content: [{ type: "text", text: "Denied by policy" }], + }, + }); + yield* updateTool("send-errored", "completed", "Summary of denied"); + + // Initial miss -> late explicit success or error still drains its new record. + yield* startTool("send-late", "send_to_user", { message: lateText }); + yield* updateTool("send-late", "completed"); + yield* recordSend(lateText); + yield* updateTool("send-late", "completed", { sentMessage: lateText }); + yield* startTool("send-late-unpublished", "send_to_user", { + message: lateText, + }); + yield* updateTool("send-late-unpublished", "completed"); + + yield* startTool("send-late-error", "send_to_user", { message: lateErrorText }); + yield* updateTool("send-late-error", "completed"); + yield* mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message: lateErrorText }, + { isError: true }, + ); + yield* updateTool("send-late-error", "completed", { + result: { isError: true, content: [{ type: "text", text: "Denied late" }] }, + }); + yield* startTool("send-late-error-sibling", "send_to_user", { + message: lateErrorText, + }); + yield* updateTool("send-late-error-sibling", "completed"); + + // Empty-input completion that misses still recovers once a later completion brings arguments, + // and replacing arguments on the same call ID re-matches against the new arguments. + yield* startTool("send-late-args", "send_to_user", {}); + yield* recordSend("First args"); + yield* updateTool("send-late-args", "completed"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "First args" }, + }); + yield* recordSend("Second args"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "send-late-args", + status: "completed", + rawInput: { message: "Second args" }, + rawOutput: "Summary of second", + }); + + // Bare failure without reported output must not consume a sibling call's cached result. + yield* startTool("send-bare-fail", "send_to_user", { message: "Shared ready" }); + yield* startTool("send-bare-fail-sibling", "send_to_user", { + message: "Shared ready", + }); + yield* recordSend("Shared ready"); + yield* updateTool("send-bare-fail", "failed"); + yield* updateTool("send-bare-fail-sibling", "completed"); + + // preview_recording_stop recovers its recording id. + yield* startTool("recording-stop", "preview_recording_stop", { + toolSummary: "Stop preview recording", + }); + yield* mcpSessions.recordToolResult( + threadId, + "preview_recording_stop", + {}, + { id: `${threadId}-rec-1` }, + ); + yield* updateTool("recording-stop", "completed"); + + // Unfinished call projected at turn end must not claim or leak to Turn 2. + yield* startTool("send-unfinished", "send_to_user", { + message: unfinishedText, + }); + yield* recordSend(unfinishedText); + + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-mcp-result"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* session.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const runTurn = (ordinal: number) => + Effect.gen(function* () { + yield* session.startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now, + ordinal, + modelSelection, + }), + ); + return Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + }); + const turn1Events = yield* runTurn(1); + const turn2Events = yield* runTurn(2); + const toolIn = (events: ReadonlyArray<(typeof turn1Events)[number]>, nativeId: string) => { + const event = events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === nativeId, + ); + return event?.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? event.turnItem + : undefined; + }; + const tool = (nativeId: string) => toolIn(turn1Events, nativeId); + + const sendEmptyUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-empty" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.deepEqual( + sendEmptyUpdates.map((update) => sentMessageFromToolItem(update)), + [statusUpdate, statusUpdate], + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming")!), inProgressText); + assert.strictEqual(sentMessageFromToolItem(tool("send-streaming-unpublished")!), undefined); + const erroredUpdates = turn1Events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.type === "dynamic_tool" && + event.turnItem.nativeItemRef?.nativeId === "send-errored" && + event.turnItem.status === "completed" + ? [event.turnItem] + : [], + ); + assert.strictEqual(erroredUpdates.length, 2); + for (const update of erroredUpdates) { + assert.strictEqual(compactDynamicToolOutput(update.output)?.isError, true); + assert.include(JSON.stringify(update.output), "Denied by policy"); + assert.strictEqual(sentMessageFromToolItem(update), undefined); + } + assert.strictEqual(sentMessageFromToolItem(tool("send-late")!), lateText); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-unpublished")!), undefined); + const lateErrorSibling = tool("send-late-error-sibling"); + assert.isDefined(lateErrorSibling); + assert.strictEqual(lateErrorSibling.status, "completed"); + assert.strictEqual(lateErrorSibling.output, undefined); + assert.strictEqual(sentMessageFromToolItem(tool("send-late-args")!), "Second args"); + assert.strictEqual( + sentMessageFromToolItem(tool("send-bare-fail-sibling")!), + "Shared ready", + ); + assert.strictEqual(sentMessageFromToolItem(tool("send-unfinished")!), undefined); + assert.strictEqual( + sentMessageFromToolItem(toolIn(turn2Events, "turn2-leaked-check")!), + undefined, + ); + assert.strictEqual( + previewRecordingIdFromToolItem(tool("recording-stop")!), + `${threadId}-rec-1`, + ); + }).pipe(Effect.provide(layerSession)), + ); }); /** @@ -2624,3 +2952,167 @@ describe("AntigravityAdapterV2 session system prompt", () => { }).pipe(Effect.provide(layerSession)), ); }); + +describe("AntigravityAdapterV2 update_steps checklist", () => { + it.effect("shows agy's update_steps calls as the thread's task list, not tool rows", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const crypto = yield* SecureRandom.SecureRandom; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdate: Parameters[0] | undefined; + const instanceId = ProviderInstanceId.make("antigravity-update-steps-test"); + const threadId = ThreadId.make("thread-antigravity-update-steps"); + const adapter = yield* makeAntigravityAdapterV2({ + instanceId, + selfInvocation: yield* resolveSelfInvocation(), + makeRuntime: (input) => + makeAntigravityAcpRuntime({ + ...input, + childProcessSpawner, + spawn: { + command: process.execPath, + args: [mockAgentPath], + cwd: input.cwd, + env: { T3_ACP_ANTIGRAVITY: "1" }, + }, + }).pipe( + Effect.provideService(SecureRandom.SecureRandom, crypto), + Effect.map((runtime): RuntimeService => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdate = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + // agy 1.5.15/1.5.16 report the checklist only as tool calls, never as ACP `plan`. + 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 = [ + [ + { title: "Create a.txt", status: "in_progress" }, + { title: "Create b.txt", status: "pending" }, + ], + [ + { title: "Create a.txt", status: "done" }, + { title: "Create b.txt", status: "in_progress" }, + ], + ]; + for (const [index, steps] of calls.entries()) { + const toolCallId = `update-steps-${index + 1}`; + yield* send({ + sessionUpdate: "tool_call", + toolCallId, + title: "Run update_steps", + kind: "other", + status: "in_progress", + rawInput: { steps }, + }); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId, + status: "completed", + }); + } + return { stopReason: "end_turn" as const }; + }), + })), + ), + withProcess: (_stop, task) => task, + defaultModel: Effect.undefined, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "gemini-test-low" } as const; + const session = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-update-steps"), + 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-update-steps"), + title: "Antigravity update_steps", + providerInstanceId: instanceId, + modelSelection, + 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-update-steps"), + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: RunAttemptId.make("attempt-antigravity-update-steps"), + rootNodeId: NodeId.make("node-antigravity-update-steps"), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-antigravity-update-steps"), + text: "create a.txt and b.txt", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const events = Array.from( + yield* session.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ), + ); + + const toolRows = events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? [event.turnItem.toolName] + : [], + ); + assert.deepEqual(toolRows, []); + const plans = events.flatMap((event) => + event.type === "plan.updated" && event.plan.kind === "todo_list" + ? [event.plan.steps.map((step) => [step.text, step.status])] + : [], + ); + assert.deepEqual(plans.at(-1), [ + ["Create a.txt", "completed"], + ["Create b.txt", "running"], + ]); + }).pipe(Effect.provide(layerSession)), + ); +}); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index c20afa04e31b8..9534a50829fa1 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -46,6 +46,7 @@ import { classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, makeAntigravityReadRepair, + makeAntigravityUpdateStepsPlans, makeAntigravityUserInputResponse, normalizeAntigravityToolCall, } from "../../provider/acp/AntigravityProtocol.ts"; @@ -164,6 +165,7 @@ export function makeAntigravityAcpAdapterFlavor( .pipe(Effect.provideService(Scope.Scope, scope)); // Repair keeps state across updates, so each runtime must have one session-update handler. const reads = makeAntigravityReadRepair(); + const plans = makeAntigravityUpdateStepsPlans(); // Served reads are reported from the read handler, so they take turns with agent updates. const updates = yield* Semaphore.make(1); let projectUpdate: Parameters[0] | undefined; @@ -194,9 +196,10 @@ export function makeAntigravityAcpAdapterFlavor( Effect.sync(reads.reset).pipe(Effect.andThen(runtime.prompt(payload, promptOptions))), handleSessionUpdate: (handler) => { projectUpdate = handler; - return runtime.handleSessionUpdate((notification) => - updates.withPermit(handler(reads.repair(notification))), - ); + return runtime.handleSessionUpdate((notification) => { + const update = plans(reads.repair(notification)); + return update === undefined ? Effect.void : updates.withPermit(handler(update)); + }); }, start: () => runtime diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index f423a9c40d335..faa96e3720645 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -1794,9 +1794,10 @@ describe("ClaudeAdapterV2 provider installation gate", () => { }), queryRunner: { allocateSessionId: Effect.succeed("native-thread-claude-gate"), - open: () => - Effect.sync(() => { + open: (input) => + Effect.gen(function* () { log.push("open query"); + if (input.onStartupPhase !== undefined) yield* input.onStartupPhase("mcp"); return { messages: Stream.never, offer: () => Effect.void, @@ -1815,7 +1816,7 @@ describe("ClaudeAdapterV2 provider installation gate", () => { stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, - }; + } satisfies ClaudeAdapterV2.ClaudeAgentSdkQuerySession; }), forkSession: () => Effect.die("unused"), subagentLaunchToolUseId: () => Effect.succeed(null), @@ -1855,6 +1856,25 @@ describe("ClaudeAdapterV2 provider installation gate", () => { ); assert.deepStrictEqual(log, [`enter ${instanceId}`, "open query", "exit"]); + // The step reported while the process opens is cleared before the turn runs. + const startup = yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "provider_session.updated" || event.type === "provider_turn.updated", + ), + Stream.take(3), + Stream.runCollect, + ); + assert.deepStrictEqual( + Array.from(startup, (event) => + event.type === "provider_session.updated" + ? (event.providerSession.startupPhase ?? null) + : event.type === "provider_turn.updated" + ? event.providerTurn.status + : null, + ), + ["mcp", null, "running"], + ); }).pipe( Effect.provide( Layer.mergeAll( @@ -4543,6 +4563,58 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("reports connecting while a turn's first API request is unanswered", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions(); + const status = (uuid: string) => + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "requesting", + uuid, + session_id: WAKE_NATIVE_SESSION, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: DateTime.makeUnsafe(0), + attemptId: RunAttemptId.make("connecting-phase"), + text: "Hello", + attachments: [], + }), + ); + // Init lands before the request and must not count as its answer. + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(status("00000000-0000-4000-8000-000000000901")); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000902", text: "Hi." }), + ); + // A later request in the same turn is the model working, not startup. + yield* harness.offerAndWait(status("00000000-0000-4000-8000-000000000903")); + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "provider_session.updated" + ? [event.providerSession.startupPhase ?? null] + : [], + ), + ["connecting", null], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("resumes the session a /clear selected after the Claude process is replaced", () => Effect.gen(function* () { const harness = yield* makeWakeHarnessWithOptions({ @@ -10601,6 +10673,76 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ); + it.effect("measures Claude context from the last main-model pass in an advisor response", () => + 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-advisor-context"), + text: "Continue.", + attachments: [], + }), + ); + const usage = { + input_tokens: 4, + cache_read_input_tokens: 1087272, + cache_creation_input_tokens: 1222, + output_tokens: 711, + iterations: [ + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543529, + cache_creation_input_tokens: 214, + output_tokens: 268, + }, + { type: "advisor_message", input_tokens: 545497, output_tokens: 3144 }, + { + type: "message", + input_tokens: 2, + cache_read_input_tokens: 543743, + cache_creation_input_tokens: 1008, + output_tokens: 443, + }, + ], + }; + for (const frame of [ + usageStreamFrame({ + type: "message_start", + message: { id: "msg_advisor", usage: zeroUsage }, + }), + usageStreamFrame({ + type: "message_delta", + delta: { stop_reason: "end_turn", stop_sequence: null }, + usage, + }), + usageSnapshotFrame("msg_snapshot_only", "00000000-0000-4000-8000-000000000690", { + ...zeroUsage, + iterations: [ + ...usage.iterations, + { type: "advisor_message", input_tokens: 547000, output_tokens: 25 }, + ], + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000691", result: "Done." }), + ]) + yield* Queue.offer(harness.sdkMessages, frame); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual(reportedContextTokens(harness.events), [545196, 545196]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("reports context from final stream usage when the request starts at zero", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; @@ -19798,6 +19940,128 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("keeps a background subagent's card on the turn that launched it", () => + Effect.gen(function* () { + const FIRST_TASK = "task-card-turn-a"; + const FIRST_TOOL = "toolu-card-turn-a"; + const SECOND_TASK = "task-card-turn-b"; + const SECOND_TOOL = "toolu-card-turn-b"; + 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-card-turn-1"), + text: "Audit in the background.", + attachments: [], + }), + ); + for (const frame of [ + makeSubagentTaskStartedFrame({ + taskId: FIRST_TASK, + toolUseId: FIRST_TOOL, + uuid: "00000000-0000-4000-8000-000000000a51", + }), + makeSubagentTaskStartedFrame({ + taskId: SECOND_TASK, + toolUseId: SECOND_TOOL, + uuid: "00000000-0000-4000-8000-000000000a52", + }), + claudeSdkFrame({ + type: "system", + subtype: "background_tasks_changed", + tasks: [ + { task_id: FIRST_TASK, task_type: "local_agent", description: "Audit" }, + { task_id: SECOND_TASK, task_type: "local_agent", description: "Audit" }, + ], + uuid: "00000000-0000-4000-8000-000000000a53", + session_id: WAKE_NATIVE_SESSION, + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a54", + result: "Auditing in the background.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + yield* Queue.offer( + harness.sdkMessages, + makeSubagentNotificationFrame({ + taskId: FIRST_TASK, + toolUseId: FIRST_TOOL, + summary: "Audit done.", + uuid: "00000000-0000-4000-8000-000000000a55", + }), + ); + yield* harness.awaitContinuation(1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-card-turn-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + for (const frame of [ + claudeSdkFrame({ + type: "system", + subtype: "task_progress", + task_id: SECOND_TASK, + description: "Reading the last commits", + uuid: "00000000-0000-4000-8000-000000000a56", + session_id: WAKE_NATIVE_SESSION, + }), + makeSubagentNotificationFrame({ + taskId: SECOND_TASK, + toolUseId: SECOND_TOOL, + summary: "Audit done.", + uuid: "00000000-0000-4000-8000-000000000a57", + }), + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a58", + result: "Both auditors finished.", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(2); + + const cards = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "subagent" + ? [event.turnItem] + : [], + ); + const turnIds = harness.events.flatMap((event) => + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [], + ); + assert.equal(new Set(turnIds).size, 2); + assert.equal(new Set(cards.map((card) => card.subagentId)).size, 2); + assert.equal(cards.filter((card) => card.status === "completed").length, 2); + assert.deepEqual( + [...new Set(cards.map((card) => card.providerTurnId))], + [cards[0]?.providerTurnId], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // Claude reports a background subagent `completed` when its turn ends while // its own background shell still runs. When that shell finishes, Claude // resumes the subagent with a new task_started for the same task and launch @@ -21645,27 +21909,13 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("records a forked skill's model from its transcript instead of the parent's", () => - Effect.gen(function* () { - const harness = yield* makeWakeHarnessWithOptions({ - subagentModel: "claude-haiku-4-5-20251001", - }); - const now = yield* DateTime.now; - const parentModel = "claude-opus-4-6"; - yield* harness.runtime.startTurn( - makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now, - attemptId: RunAttemptId.make("attempt-forked-skill-model"), - text: "/fork-probe go", - attachments: [], - modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: parentModel }, - }), - ); + it.effect.each([ + { + launch: "forked skill", + text: "/fork-probe go", // A `context: fork` skill has no Agent call and streams none of its own replies: // task_started carries no tool_use_id, and only its prompt echo names the fork. - for (const frame of [ + frames: [ claudeSdkFrame({ type: "system", subtype: "task_started", @@ -21696,28 +21946,93 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000000233", session_id: WAKE_NATIVE_SESSION, }), - makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), - ]) { - yield* Queue.offer(harness.sdkMessages, frame); - } - yield* Queue.take(harness.terminalReceipts); + ], + }, + { + launch: "foreground Agent call with no streamed reply", + text: "Ask a subagent one thing.", + frames: [ + claudeSdkFrame({ + type: "assistant", + parent_tool_use_id: null, + message: { + model: "claude-opus-4-6", + id: "msg_unstreamed_model_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu-unstreamed-model", + name: "Agent", + input: { description: "One thing", prompt: "Check one thing." }, + }, + ], + }, + uuid: "00000000-0000-4000-8000-000000000235", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: "task-unstreamed-model", + tool_use_id: "toolu-unstreamed-model", + description: "One thing", + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000236", + session_id: WAKE_NATIVE_SESSION, + }), + makeSubagentNotificationFrame({ + taskId: "task-unstreamed-model", + toolUseId: "toolu-unstreamed-model", + summary: "OK", + uuid: "00000000-0000-4000-8000-000000000237", + }), + ], + }, + ])( + "records the model of a $launch from its transcript instead of the parent's", + ({ text, frames }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ + subagentModel: "claude-haiku-4-5-20251001", + }); + const now = yield* DateTime.now; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-transcript-model"), + text, + attachments: [], + modelSelection: { ...CLAUDE_TEST_MODEL_SELECTION, model: "claude-opus-4-6" }, + }), + ); + for (const frame of [ + ...frames, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000234", result: "OK" }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* Queue.take(harness.terminalReceipts); - const fork = harness.events - .filter((event) => event.type === "subagent.updated") - .at(-1)?.subagent; - assert.equal(fork?.status, "completed"); - assert.equal(fork?.model, "claude-haiku-4-5"); - assert.equal(fork?.modelSelection?.model, "claude-haiku-4-5"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, + const subagent = harness.events + .filter((event) => event.type === "subagent.updated") + .at(-1)?.subagent; + assert.equal(subagent?.status, "completed"); + assert.equal(subagent?.model, "claude-haiku-4-5"); + assert.equal(subagent?.modelSelection?.model, "claude-haiku-4-5"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), - ), ); it.effect.each([ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 57844a5c38d5c..ae91877646c51 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -316,6 +316,7 @@ function claudeMessageInputTokens(usage: { export function claudeProviderTurnTokenUsage( usage: { + readonly iterations?: SDKAssistantMessage["message"]["usage"]["iterations"] | undefined; readonly input_tokens?: number | null | undefined; readonly cache_creation_input_tokens?: number | null | undefined; readonly cache_read_input_tokens?: number | null | undefined; @@ -327,9 +328,11 @@ export function claudeProviderTurnTokenUsage( autoCompactWindow = "", requestedAt?: DateTime.Utc, ) { - const inputTokens = claudeMessageInputTokens(usage); - const outputTokens = optionalClaudeUsageTokenCount(usage.output_tokens) ?? 0; - const cachedInputTokens = optionalClaudeUsageTokenCount(usage.cache_read_input_tokens) ?? 0; + // After an advisor call, the response totals can count the same context twice. + const sample = usage.iterations?.findLast((iteration) => iteration.type === "message") ?? usage; + const inputTokens = claudeMessageInputTokens(sample); + const outputTokens = optionalClaudeUsageTokenCount(sample.output_tokens) ?? 0; + const cachedInputTokens = optionalClaudeUsageTokenCount(sample.cache_read_input_tokens) ?? 0; const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation); // The cache lifetime starts with the request, not when its response ends. const promptCacheExpiresAt = @@ -355,15 +358,11 @@ 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 | undefined; - readonly cache_creation_input_tokens?: number | null | undefined; - readonly cache_read_input_tokens?: number | null | undefined; - readonly output_tokens?: number | null | undefined; - }, + delta: ClaudeMessageUsage, ): ClaudeMessageUsage { return { ...current, + iterations: delta.iterations ?? current.iterations, input_tokens: optionalClaudeUsageTokenCount(delta.input_tokens) ?? optionalClaudeUsageTokenCount(current.input_tokens) ?? @@ -776,6 +775,8 @@ export interface ClaudeAgentSdkQueryOpenInput { readonly options: ClaudeAgentSdkQueryOptions; readonly threadId: ThreadId; readonly providerSessionId: OrchestrationV2ProviderSession["id"]; + /** Reports the step the CLI is on before the turn can start, such as `mcp`; `undefined` ends it. */ + readonly onStartupPhase?: (phase: string | undefined) => Effect.Effect; } export interface ClaudeAgentSdkQuerySession { @@ -1860,6 +1861,8 @@ export const layerQueryRunner: Layer.Layer< orElse: timedOut("initialize"), }), ); + const onStartupPhase = input.onStartupPhase ?? (() => Effect.void); + yield* onStartupPhase("mcp"); // Errors and mcp_status can echo headers; log only server names. const failed = yield* Effect.tryPromise({ try: () => queryRuntime.setMcpServers(mcpServers), @@ -1871,6 +1874,8 @@ export const layerQueryRunner: Layer.Layer< duration: CLAUDE_MCP_REGISTRATION_TIMEOUT, orElse: timedOut("setMcpServers"), }), + // A timed-out registration reopens the CLI, which boots before it registers again. + Effect.ensuring(Effect.suspend(() => onStartupPhase(undefined))), ); if (failed.length > 0) { yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", { @@ -5460,6 +5465,8 @@ interface ActiveClaudeSubagent { readonly childRootNodeId: OrchestrationV2ExecutionNode["id"]; readonly turnItemId: OrchestrationV2TurnItem["id"]; readonly turnItemOrdinal: number; + // Clients group cards by launching turn; later updates can arrive during another turn. + readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly runToolUseId: string | null; readonly effort: string | undefined; nextChildItemOrdinal: number; @@ -6671,6 +6678,26 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return Queue.offer(events, event).pipe(Effect.asVoid); }; + let reportedStartupPhase: string | undefined; + const reportStartupPhase = Effect.fn("ClaudeAdapterV2.reportStartupPhase")(function* ( + phase: string | undefined, + ) { + if (phase === reportedStartupPhase) return; + reportedStartupPhase = phase; + yield* emitProviderEvent({ + type: "provider_session.updated", + driver: CLAUDE_PROVIDER, + providerSession: { + ...session, + ...(phase === undefined ? {} : { startupPhase: phase }), + updatedAt: yield* DateTime.now, + }, + }); + }); + // Only a turn's first API request is startup; later ones are the model at work. + const requestedTurns = new WeakSet(); + let connectingTurn: ActiveClaudeTurnContext | undefined; + const persistAttachmentBudget = Effect.fnUntraced(function* (nativeThreadId: string) { const providerThread = (yield* Ref.get(lastProviderThreadByNativeThread)).get( nativeThreadId, @@ -6714,8 +6741,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.autoCompactWindow, context.streamUsage?.requestedAt, ); - if (typeof usage !== "number") { - if (claudeMessageInputTokens(usage) <= 0) return; + if ("inputTokens" in tokenUsage) { + if (tokenUsage.inputTokens <= 0) return; context.compactionTokens = undefined; } yield* emitProviderEvent({ @@ -7650,9 +7677,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); }); - // A `context: fork` skill has no Agent call and streams none of its own frames; - // only its transcript records the model, written after the fork reports its outcome. - const forkedSkillModel = Effect.fnUntraced(function* ( + // A `context: fork` skill, or a foreground subagent whose replies were never streamed, + // leaves no model on any frame; only its transcript records it, written once it finishes. + const transcriptModel = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, nativeThreadId: string, taskId: string, @@ -7660,7 +7687,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const registered = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId); if ( registered === undefined || - registered.runToolUseId !== null || registered.task.model !== null || registered.task.status === "running" ) { @@ -7759,6 +7785,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resume.context, `task:${resume.taskId}:subagent`, ), + providerTurnId: resume.context.providerTurnId, runToolUseId: launchToolUseId, effort: undefined, nextChildItemOrdinal: 100, @@ -8410,6 +8437,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) : undefined)); const model = input.model ?? priorTask?.model ?? null; + const movesToCurrentRun = + input.reopen === true && input.status === "running" && existingSubagent !== undefined; const task = { ...(priorTask ?? { id: nodeId, @@ -8434,11 +8463,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( startedAt: now, }), status: input.status, - ...(input.reopen === true && - input.status === "running" && - existingSubagent !== undefined - ? { runId: input.context.input.runId } - : {}), + ...(movesToCurrentRun ? { runId: input.context.input.runId } : {}), ...(input.prompt === undefined ? {} : { prompt: input.prompt }), ...(input.title === undefined ? {} : { title: input.title }), model, @@ -8473,6 +8498,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( childRootNodeId, turnItemId: existingSubagent?.turnItemId ?? derivedIds.turnItemId, turnItemOrdinal, + providerTurnId: + existingSubagent === undefined || movesToCurrentRun + ? input.context.providerTurnId + : existingSubagent.providerTurnId, runToolUseId: existingSubagent === undefined ? (input.toolUseId ?? null) @@ -8660,7 +8689,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( runId: task.runId, nodeId: task.id, providerThreadId: input.context.input.providerThread.id, - providerTurnId: input.context.providerTurnId, + providerTurnId: subagent.providerTurnId, nativeItemRef: task.nativeTaskRef, parentItemId: null, ordinal: subagent.turnItemOrdinal, @@ -9762,6 +9791,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ? { ...requested, status: "failed" as const, failure: retryBudgetFailure } : requested; input.context.steersClosed = true; + if (connectingTurn === input.context) { + connectingTurn = undefined; + yield* reportStartupPhase(undefined); + } yield* reasoningDeltas.flushTurn(input.context.nativeTurnId); if (input.status === "completed") { yield* assistantDeltas.flushTurn(input.context.nativeTurnId); @@ -11186,6 +11219,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message.status === "requesting") || (lifecycle?.state === "started" && lifecycle.uuid === context.promptUuid) ) { + if ( + message.type === "system" && + message.subtype === "status" && + !requestedTurns.has(context) + ) { + requestedTurns.add(context); + connectingTurn = context; + yield* reportStartupPhase("connecting"); + } const since = yield* DateTime.now; context.unansweredRequestSince = since; const previousWatch = context.unansweredRequestWatch; @@ -11213,6 +11255,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { context.unansweredRequestSince = undefined; yield* clearUnansweredRequestWatch(context); + if (connectingTurn === context) { + connectingTurn = undefined; + yield* reportStartupPhase(undefined); + } } } const focusedPlugin = claudeFocusRequestedPanePlugin(message); @@ -12421,7 +12467,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return next; }); for (const taskId of context.subagentsByTaskId.keys()) { - const model = yield* forkedSkillModel(context, liveQuery.nativeThreadId, taskId); + const model = yield* transcriptModel(context, liveQuery.nativeThreadId, taskId); const status = (yield* Ref.get(sessionSubagentsByTaskId)).get(taskId)?.task.status; if ( model !== undefined && @@ -13647,8 +13693,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( providerSessionId: input.providerSessionId, options: queryOptions, ...(turnInput.resume ? { resume: true } : {}), + onStartupPhase: reportStartupPhase, }) - .pipe(Effect.map((querySession) => ({ program, querySession }))), + .pipe( + Effect.map((querySession) => ({ program, querySession })), + Effect.ensuring(Effect.suspend(() => reportStartupPhase(undefined))), + ), ), ); // The SDK spawns the CLI per turn, so only the open waits for a provider update. diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 76439d76924b5..cc1cf3e33b271 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -495,6 +495,38 @@ it.effect("cancels a stalled registration without retrying or retaining its prom }).pipe(Effect.provide(realQueryRunner)), ); +it.effect("reports MCP startup after the CLI boots, while it registers the servers", () => + Effect.gen(function* () { + const steps: Array = []; + const querySpy = vi.spyOn(ClaudeSdk, "query").mockImplementation( + () => + ({ + initializationResult: async () => { + steps.push("booted"); + return {}; + }, + setMcpServers: async () => { + steps.push("registered"); + return { added: ["t3-code"], removed: [], errors: {} }; + }, + close: vi.fn(), + [Symbol.asyncDispose]: async () => {}, + }) as unknown as ClaudeSdk.Query, + ); + yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); + const runner = yield* ClaudeAgentSdkQueryRunner; + const { resume, ...options } = resumedMcpQueryInput.options; + const session = yield* runner.open({ + ...resumedMcpQueryInput, + options: { ...options, sessionId: resume }, + onStartupPhase: (phase) => Effect.sync(() => steps.push(phase ?? "ended")), + }); + yield* session.close; + + assert.deepEqual(steps, ["booted", "mcp", "registered", "ended"]); + }).pipe(Effect.provide(realQueryRunner)), +); + it.effect("retries a fresh session once after MCP registration times out", () => Effect.gen(function* () { const registrationStarted = Promise.withResolvers(); @@ -516,15 +548,19 @@ it.effect("retries a fresh session once after MCP registration times out", () => yield* Effect.addFinalizer(() => Effect.sync(() => querySpy.mockRestore())); const runner = yield* ClaudeAgentSdkQueryRunner; const { resume, ...options } = resumedMcpQueryInput.options; + const phases: Array = []; const opening = yield* runner .open({ ...resumedMcpQueryInput, options: { ...options, sessionId: resume }, + onStartupPhase: (phase) => Effect.sync(() => phases.push(phase ?? "ended")), }) .pipe(Effect.result, Effect.forkChild); yield* Effect.promise(() => registrationStarted.promise); yield* TestClock.adjust("90 seconds"); const result = yield* Fiber.join(opening); + // The replacement CLI boots without the timed-out attempt's phase. + assert.deepEqual(phases, ["mcp", "ended", "mcp", "ended"]); assert.equal(result._tag, "Success"); if (result._tag === "Success") yield* result.success.close; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index e21c323ea709c..21943bb65935e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -15,6 +15,7 @@ import { type ModelSelection, NodeId, type OrchestrationV2AppThread, + type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, type OrchestrationV2RuntimeRequest, @@ -4076,6 +4077,121 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("reports MCP servers starting only until the thread's turn opens", () => + Effect.gen(function* () { + const nativeThreadId = "mcp-startup-phase-thread"; + const nativeTurnId = "mcp-startup-phase-turn"; + const status = (name: string, value: "starting" | "ready" | "failed") => + ({ + type: "emit_inbound", + label: `mcp-${name}-${value}`, + frame: { + method: "mcpServer/startupStatus/updated", + params: { + threadId: nativeThreadId, + name, + status: value, + error: value === "failed" ? "boom" : null, + failureReason: null, + }, + }, + }) satisfies CodexReplay.CodexAppServerReplayEntry; + const preamble = codexReplayPreamble({ + nativeThreadId, + nativeTurnId, + prompt: "use the tools", + }); + // Recorded Codex reports `starting` while turn/start is in flight and `ready` after the turn runs. + const turnStart = + preamble.findIndex( + (entry) => entry.type === "expect_outbound" && entry.label === "turn/start", + ) + 1; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-mcp-startup-phase", + entries: [ + ...preamble.slice(0, turnStart), + status("docs", "starting"), + status("search", "starting"), + ...preamble.slice(turnStart), + // Codex may answer without these, so once the turn is open they are not startup. + status("late", "starting"), + status("docs", "ready"), + status("search", "failed"), + { + type: "emit_inbound", + label: "complete", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + let runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime | undefined; + // Turn start republishes the session record, so it must carry the phase until the turn opens. + const reported = yield* Deferred.make(); + let republished: OrchestrationV2ProviderSession | undefined; + const harness = yield* makeCodexReplayHarness( + transcript, + (event) => + event.type === "provider_session.updated" && + event.providerSession.startupPhase !== undefined + ? Deferred.succeed(reported, undefined) + : Effect.void, + undefined, + undefined, + (entry) => + entry.label === "turn/start" + ? Deferred.await(reported).pipe( + Effect.andThen( + Effect.sync(() => { + republished = runtime?.providerSession; + }), + ), + ) + : Effect.void, + ); + runtime = harness.runtime; + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("mcp-startup-phase-attempt"), + text: "use the tools", + }), + ); + yield* harness.firstTerminal; + const updates = harness.events.flatMap((event) => + event.type === "provider_session.updated" + ? [ + event.providerSession.startupPhase === undefined + ? null + : `${event.providerSession.startupPhase} for ${event.providerSession.startupPhaseThreadId}`, + ] + : event.type === "provider_turn.updated" && event.providerTurn.status === "running" + ? ["turn running"] + : [], + ); + assert.deepEqual(updates, [`mcp for ${harness.threadId}`, null, "turn running"]); + assert.equal(republished?.startupPhase, "mcp"); + assert.equal(republished?.startupPhaseThreadId, harness.threadId); + assert.isUndefined(harness.runtime.providerSession.startupPhase); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("stops asking for commands the user allowed for the session", () => Effect.gen(function* () { const nativeThreadId = "session-approval-thread"; @@ -4879,9 +4995,18 @@ describe("CodexAdapterV2 post-settle continuation", () => { ], }); const resumeThreadEnvs: Array = []; + const startupPhases = yield* Queue.unbounded(); const harness = yield* makeCodexReplayHarness( transcript, - () => Effect.void, + (event) => + event.type === "provider_session.updated" + ? Queue.offer( + startupPhases, + event.providerSession.startupPhase === undefined + ? null + : `${event.providerSession.startupPhase} for ${event.providerSession.startupPhaseThreadId}`, + ) + : Effect.void, (method, params) => Effect.sync(() => { if (method === "thread/resume") resumeThreadEnvs.push(threadEnvOf(params)); @@ -4909,6 +5034,13 @@ describe("CodexAdapterV2 post-settle continuation", () => { assert.equal(resumed.status, "idle"); assert.equal(DateTime.toEpochMillis(resumed.updatedAt), 1782622450000); assert.deepEqual(resumeThreadEnvs, [harness.threadId, undefined, explicitThreadId]); + // Each resume is reported for its thread while Codex loads it; one with no app thread is not. + assert.deepEqual(Array.from(yield* Queue.takeN(startupPhases, 4)), [ + `resume for ${harness.threadId}`, + null, + `resume for ${explicitThreadId}`, + null, + ]); }).pipe( Effect.provide( Layer.mergeAll( @@ -5608,7 +5740,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { ); const completed = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -7435,9 +7567,9 @@ describe("CodexAdapterV2 post-settle continuation", () => { createdBy: "user", creationSource: "web", }); - const waiting = yield* orchestrator.streamDomainEvents.pipe( + const completed = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => event.type === "run.updated" && event.payload.status === "waiting", + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -7455,7 +7587,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); yield* worker.drain(); assert.isNull((yield* Ref.get(replayDriver.state)).failure); - yield* Fiber.join(waiting); + yield* Fiber.join(completed); yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(threadId); const run = projection.runs.at(-1)!; @@ -7558,9 +7690,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { }); const settled = yield* orchestrator.streamDomainEvents.pipe( Stream.filter( - (event) => - event.type === "run.updated" && - (event.payload.status === "waiting" || event.payload.status === "completed"), + (event) => event.type === "run.updated" && event.payload.status === "completed", ), Stream.runHead, Effect.forkChild({ startImmediately: true }), @@ -13153,6 +13283,120 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("shows what an approval grants apart from the reason the model gave", () => + Effect.gen(function* () { + const reason = "Needed to build the project."; + const permissions = { + fileSystem: { + write: ["/w/out"], + entries: [ + { access: "write", path: { type: "path", path: "/w/out" } }, + { access: "write", path: { type: "special", value: { kind: "root" } } }, + { access: "read", path: { type: "glob_pattern", pattern: "/w/docs/**/*.md" } }, + { access: "write", path: { type: "special", value: { kind: "unknown", path: "" } } }, + ], + }, + network: { enabled: true }, + } satisfies CodexSchema.PermissionsRequestApprovalParams["permissions"]; + const request = ( + id: number, + method: string, + params: Record, + result: Record, + ): Array => [ + { + type: "emit_inbound", + label: method, + frame: { + id, + method, + params: { threadId: nativeThreadId, turnId: nativeTurnId, startedAtMs: 2, ...params }, + }, + }, + { type: "expect_outbound", label: method, frame: { id, result } }, + ]; + const manyFiles = Array.from({ length: 21 }, (_, index) => ({ + ...addA, + path: `/w/${String(index).padStart(2, "0")}.ts`, + })); + const { harness, answerNext } = yield* startApprovalTurn("approval-scope", [ + ...request( + 0, + "item/permissions/requestApproval", + { itemId: "permissions", cwd: "/w", reason, permissions }, + { permissions, scope: "turn" }, + ), + ...request( + 1, + "item/commandExecution/requestApproval", + { + itemId: "command", + cwd: "/w/app", + reason, + command: "pnpm install", + networkApprovalContext: { host: "example.com", protocol: "https" }, + }, + { decision: "accept" }, + ), + fileChange("started", nativeTurnId, "patch", manyFiles), + ...request( + 2, + "item/fileChange/requestApproval", + { itemId: "patch", reason, grantRoot: "/w" }, + { decision: "accept" }, + ), + fileChange("completed", nativeTurnId, "patch", manyFiles), + ...request( + 3, + "execCommandApproval", + { + callId: "legacy", + conversationId: nativeThreadId, + command: ["pnpm", "run", "build"], + cwd: "/w/app", + parsedCmd: [], + reason, + }, + { decision: "approved" }, + ), + turnCompleted(nativeTurnId), + ]); + const requests = [ + yield* answerNext, + yield* answerNext, + yield* answerNext, + yield* answerNext, + ]; + yield* harness.firstTerminal; + + assert.deepEqual( + requests.map((pending) => { + const item = approvalItem(harness.events, pending); + return [item?.prompt, item?.reason]; + }), + [ + [ + "write /w/out\nwrite / (entire filesystem)\nread /w/docs/**/*.md\nwrite unknown path\nnetwork", + reason, + ], + ["pnpm install\ncwd /w/app\nnetwork https example.com", reason], + [[...manyFiles.map((file) => `add ${file.path}`), "write /w"].join("\n"), reason], + ["pnpm run build\ncwd /w/app", reason], + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("classifies permission requests that only list sandbox entries", () => Effect.gen(function* () { const permissionRequest = ( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 68f36f35ea88f..15b9635b77f68 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -210,25 +210,74 @@ function codexMultiFilePatch( .join(""); } +// The prompt states the operation being approved; Codex's `reason` goes to the item's `reason`. function codexFileChangeApprovalPrompt(input: { - readonly reason?: string | null; readonly grantRoot?: string | null; readonly fileChanges?: CodexFileChangeKinds; }): string | undefined { - const reason = input.reason?.trim(); - if (reason) return reason; const entries = Object.entries(input.fileChanges ?? {}).toSorted(([left], [right]) => left.localeCompare(right), ); - if (entries.length > 0) { - const described = entries.slice(0, 20).map(([path, change]) => { - const movePath = change.type === "update" ? change.move_path : undefined; - return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; - }); - const remaining = entries.length - described.length; - return remaining > 0 ? `${described.join("\n")}\n+${remaining} more` : described.join("\n"); + // The card scrolls, so every path is listed. + const described = entries.map(([path, change]) => { + const movePath = change.type === "update" ? change.move_path : undefined; + return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; + }); + const grantRoot = input.grantRoot?.trim(); + return [...described, ...(grantRoot ? [`write ${grantRoot}`] : [])].join("\n") || undefined; +} + +function codexCommandApprovalPrompt( + input: Pick< + CodexSchema.CommandExecutionRequestApprovalParams, + "command" | "cwd" | "networkApprovalContext" + >, +): string | undefined { + const network = input.networkApprovalContext; + return ( + [ + ...(input.command?.trim() ? [input.command] : []), + ...(input.cwd?.trim() ? [`cwd ${input.cwd}`] : []), + ...(network ? [`network ${network.protocol} ${network.host}`] : []), + ].join("\n") || undefined + ); +} + +function codexFileSystemPathLabel( + path: CodexSchema.PermissionsRequestApprovalParams__FileSystemPath, +): string { + if (path.type === "path") return path.path; + if (path.type === "glob_pattern") return path.pattern; + const special = path.value; + switch (special.kind) { + case "root": + return "/ (entire filesystem)"; + case "slash_tmp": + return "/tmp"; + case "tmpdir": + return "temporary directory"; + case "minimal": + return "minimal system paths"; + case "project_roots": + return ["project roots", special.subpath].filter(Boolean).join("/"); + case "unknown": + return [special.path, special.subpath].filter(Boolean).join("/") || "unknown path"; + } +} + +function codexPermissionsApprovalPrompt( + permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"], +): string | undefined { + // Codex may list a path both in the legacy `read`/`write` lists and in `entries`. + const lines = new Set(); + for (const access of ["read", "write"] as const) { + for (const path of permissions.fileSystem?.[access] ?? []) lines.add(`${access} ${path}`); } - return input.grantRoot?.trim() || undefined; + for (const entry of permissions.fileSystem?.entries ?? []) { + lines.add(`${entry.access} ${codexFileSystemPathLabel(entry.path)}`); + } + if (permissions.network?.enabled) lines.add("network"); + return [...lines].join("\n") || undefined; } export function normalizeCodexThreadLoadModelSelection(selection: ModelSelection): ModelSelection { @@ -2482,6 +2531,61 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); + // Every Codex thread shares this session, so a phase names the one thread it describes. + // Once a turn opens Codex may answer without its servers, so only a thread still + // starting counts its MCP servers. + const appThreadByNativeThread = new Map(); + const startingMcpServers = new Map>(); + const resumingThreads = new Set(); + let reportedStartupPhase: + | { readonly phase: string; readonly threadId: ThreadId } + | undefined; + const currentStartupPhase = () => { + const resuming = [...resumingThreads].at(-1); + if (resuming !== undefined) return { phase: "resume", threadId: resuming }; + for (const nativeThreadId of [...startingMcpServers.keys()].reverse()) { + const threadId = appThreadByNativeThread.get(nativeThreadId); + if (threadId !== undefined) return { phase: "mcp", threadId }; + } + return undefined; + }; + const withStartupPhase = (record: OrchestrationV2ProviderSession) => + reportedStartupPhase === undefined + ? record + : { + ...record, + startupPhase: reportedStartupPhase.phase, + startupPhaseThreadId: reportedStartupPhase.threadId, + }; + const reportStartupPhase = Effect.fn("CodexAdapterV2.reportStartupPhase")(function* () { + const next = currentStartupPhase(); + if ( + next?.phase === reportedStartupPhase?.phase && + next?.threadId === reportedStartupPhase?.threadId + ) { + return; + } + reportedStartupPhase = next; + yield* emitProviderEvent({ + type: "provider_session.updated", + driver: CODEX_PROVIDER, + providerSession: withStartupPhase({ ...session, updatedAt: yield* DateTime.now }), + }); + }); + const reportingResume = (threadId: ThreadId, resume: Effect.Effect) => + Effect.sync(() => { + resumingThreads.add(threadId); + }).pipe( + Effect.andThen(reportStartupPhase()), + Effect.andThen(resume), + Effect.ensuring( + Effect.suspend(() => { + resumingThreads.delete(threadId); + return reportStartupPhase(); + }), + ), + ); + const promptSuggestionsEnabled = input.promptSuggestions ?? Effect.succeed(false); // Best effort: older Codex lacks thread/sample, and a sample fails once the user sends again. // Delegated threads share this session but have no one typing, so they never sample. @@ -2667,6 +2771,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (existing !== undefined) { return existing; } + const openingNativeThreadId = input.turnInput.providerThread.nativeThreadRef?.nativeId; + if (openingNativeThreadId != null && startingMcpServers.delete(openingNativeThreadId)) { + yield* reportStartupPhase(); + } const providerTurnId = idAllocator.derive.providerTurn({ driver: CODEX_PROVIDER, nativeTurnId: input.nativeTurnId, @@ -4865,10 +4973,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly nativeRequestId: string; readonly requestKind: ProviderRequestKind; readonly prompt?: string | null; + readonly reason?: string | null | undefined; readonly appName?: string; readonly options?: ReadonlyArray; }) { const createdAt = yield* DateTime.now; + const reason = trimText(input.reason); const { owner, subagent } = approvalOwnerCodexTurn(input.context); const parentNodeId = subagent?.subagentNodeId ?? @@ -4948,6 +5058,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(input.prompt === null || input.prompt === undefined ? {} : { prompt: input.prompt }), + ...(reason === undefined ? {} : { reason }), ...(input.appName === undefined ? {} : { appName: input.appName }), ...(input.options === undefined ? {} : { options: input.options }), }; @@ -5266,6 +5377,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* client.handleServerNotification("mcpServer/startupStatus/updated", (payload) => Effect.gen(function* () { if (payload.threadId == null) return; + const starting = startingMcpServers.get(payload.threadId) ?? new Set(); + if (payload.status === "starting") starting.add(payload.name); + else starting.delete(payload.name); + const turnOpen = + (yield* findActiveTurnByNativeThreadId(payload.threadId)) !== undefined; + if (starting.size === 0 || turnOpen) startingMcpServers.delete(payload.threadId); + else startingMcpServers.set(payload.threadId, starting); + yield* reportStartupPhase(); const failures = mcpStartupFailures.get(payload.threadId) ?? new Map(); if (payload.status === "failed") { @@ -6130,9 +6249,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId, requestKind: "command", - ...((payload.reason ?? payload.command) === undefined - ? {} - : { prompt: payload.reason ?? payload.command }), + prompt: codexCommandApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6205,6 +6323,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...payload, fileChanges: context.fileChangeKindsByItem.get(payload.itemId) ?? {}, }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6267,7 +6386,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.itemId, nativeRequestId: payload.itemId, requestKind, - ...(payload.reason === undefined ? {} : { prompt: payload.reason }), + prompt: codexPermissionsApprovalPrompt(payload.permissions) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6418,7 +6538,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeItemId: payload.callId, nativeRequestId, requestKind: "command", - prompt: payload.reason ?? payload.command.join(" "), + prompt: + codexCommandApprovalPrompt({ + command: payload.command.join(" "), + cwd: payload.cwd, + }) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -6487,6 +6612,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeRequestId: payload.callId, requestKind: "file-change", prompt: codexFileChangeApprovalPrompt(payload) ?? null, + reason: payload.reason, }); const decision = yield* Deferred.make(); yield* Ref.update(pendingRuntimeRequests, (current) => { @@ -7800,6 +7926,11 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( codexInput: ReadonlyArray, ) { const threadId = yield* getNativeThreadId(turnInput.providerThread); + // A thread can reach its first turn without ensureThread or resumeThread, like a fork. + if (!appThreadByNativeThread.has(threadId)) { + appThreadByNativeThread.set(threadId, turnInput.threadId); + yield* reportStartupPhase(); + } const mcpSession = yield* mcpSessions.read(turnInput.threadId); const models = adapterOptions.models === undefined ? [] : yield* adapterOptions.models; const configuredReasoningSummary = yield* client @@ -8159,7 +8290,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( instanceId: adapterOptions.instanceId, driver: CODEX_PROVIDER, providerSessionId: input.providerSessionId, - providerSession: session, + // Turn start republishes this record, so it carries the step MCP startup is still on. + get providerSession() { + return withStartupPhase(session); + }, events: Stream.fromEffectRepeat(Queue.take(events)), canReuseContextUsage: canReuseCodexContextUsage, normalizeThreadLoadModelSelection: normalizeCodexThreadLoadModelSelection, @@ -8235,6 +8369,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( : {}), }), ), + Effect.tap((response) => { + appThreadByNativeThread.set(response.thread.id, threadInput.threadId); + return reportStartupPhase(); + }), Effect.map((response): OrchestrationV2ProviderThread => providerThreadFromCodexThread({ appThreadId: threadInput.threadId, @@ -8260,6 +8398,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* rejectIfRetired; const nativeThreadId = yield* getNativeThreadId(threadInput.providerThread); const appThreadId = threadInput.threadId ?? threadInput.providerThread.appThreadId; + if (appThreadId != null) appThreadByNativeThread.set(nativeThreadId, appThreadId); const resume = resumeNativeThread(nativeThreadId, { excludeTurns: true, ...codexThreadRuntimeParams({ @@ -8279,7 +8418,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( rootProviderThreads.set(nativeThreadId, threadInput.providerThread); goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( - Effect.andThen(resume), + Effect.andThen(appThreadId == null ? resume : reportingResume(appThreadId, resume)), withAppServerDeadline("thread/resume"), Effect.flatMap(decodeCodexResumeMetadata), // Stay registered: a lost or undecodable response may still have resumed the thread. diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 91a00fd60742f..a6a1056d1a95b 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -43,7 +43,7 @@ import { TestClock } from "effect/testing"; import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; -import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; +import { htmlRenderFromToolItem, sentMessageFromToolItem } from "@t3tools/shared/toolOutput"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import { @@ -1540,16 +1540,26 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { reply("session.interrupt", { interrupted: true }), event("session.execution.interrupted", { sessionID: SESSION }), ]); + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); const watch = yield* watchBackgroundTurn(runtime); yield* runtime.startTurn(withLineage(thread)); yield* watch.attached; + // The child's nested T3 MCP results live under the root thread and outlive its turn. + const childResult = { message: "Child note" }; + yield* mcpSessions.recordToolResult(threadId, "send_to_user", childResult, { + sentMessage: childResult.message, + }); yield* runtime.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId, }); assert.equal((yield* watch.terminal)?.status, "interrupted"); assert.isTrue(yield* runtime.hasPendingBackgroundWork!); - }), + assert.deepEqual(yield* mcpSessions.takeToolResult(threadId, "send_to_user", childResult), { + sentMessage: childResult.message, + }); + }).pipe(Effect.scoped), ); it.effect("stops background subagents on a user Stop", () => @@ -3253,6 +3263,75 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("answers an optional multiselect with none and keeps a minimum choice required", () => + Effect.gen(function* () { + const formID = "frm_0eb79ab35001fkvFECSh3wYNVE"; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + event("form.created", { + form: { + id: formID, + sessionID: SESSION, + title: "Setup", + fields: [ + { + key: "extras", + type: "multiselect", + title: "Extras", + options: [ + { value: "lint", label: "Lint" }, + { value: "tests", label: "Tests" }, + ], + }, + { + key: "targets", + type: "multiselect", + title: "Targets", + minItems: 1, + options: [{ value: "web", label: "Web" }], + }, + ], + }, + }), + out("session.form.reply", { + sessionID: SESSION, + formID, + answer: { extras: [], targets: ["web"] }, + }), + reply("session.form.reply", null), + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const shown = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "runtime_request.updated"), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const events = yield* Fiber.join(shown); + const questions = events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request" + ? event.turnItem.questions + : [], + ); + assert.deepEqual( + questions.map((question) => [question.id, question.required]), + [ + ["extras", undefined], + ["targets", true], + ], + ); + const request = events.find((event) => event.type === "runtime_request.updated"); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.respondToRuntimeRequest({ + requestId: request!.runtimeRequest.id, + answers: { extras: [], targets: ["web"] }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }).pipe(Effect.scoped), + ); + it.effect("asks a subagent's permission request on the parent thread's turn", () => Effect.gen(function* () { const child = "ses_f0e5aa64cffelFnoQRL0DAA9BH"; @@ -5321,6 +5400,188 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("shows send_to_user messages a Code Mode script sends without returning them", () => + Effect.gen(function* () { + const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + yield* Effect.addFinalizer(() => mcpSessions.clear(threadId)); + const server = "t3-code-thread_opencode2-adapter"; + const messages = ["First mid-turn note", "Second mid-turn note"]; + yield* Effect.forEach(messages, (message) => + mcpSessions.recordToolResult( + threadId, + "send_to_user", + { message }, + { sentMessage: message }, + ), + ); + const tool = { + sessionID: SESSION, + assistantMessageID: "msg_assistant", + id: "call-execute-send", + }; + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.tool.input.started", { ...tool, name: "execute" }), + event("session.tool.called", { ...tool, input: { code: "`; +const sizeChanged = (height: number) => + `parent.postMessage({ jsonrpc: "2.0", method: "ui/notifications/size-changed", params: { height: ${height} } }, "*");`; +// What the app's frame shows after the app follows a link: another page in the same window. +// Its nested frame keeps `load`, which stops the app, from firing before its message arrives. +const REPLACEMENT_URL = `data:text/html,${encodeURIComponent(``)}`; +// Served as the server serves an app: the document bootstrap is its first script. +const NAVIGATING_APP_HTML = injectMcpAppDocumentBootstrap(``); + +const asset = vi.hoisted(() => ({ html: "" })); +const setup = (html: string) => { + asset.html = html; +}; + vi.mock(import("~/assets/longLivedAssetUrls"), () => ({ useLongLivedAssetUrl: () => ({ _tag: "Success", - url: `data:text/html,${encodeURIComponent(APP_HTML)}`, + url: `data:text/html,${encodeURIComponent(asset.html)}`, expiresAt: Date.now() + 60 * 60_000, }), })); @@ -44,6 +65,7 @@ const nextInitializedFrom = () => describe("McpAppFrame", () => { it("keeps a reopened app when the old document's second teardown finishes late", async () => { + setup(APP_HTML); const firstInitialized = nextInitializedFrom(); await using screen = await render( { expect(screen.getByRole("button", { name: "Show app" }).query()).toBeNull(); await expect.element(screen.getByTitle("Demo app")).toBeInTheDocument(); }); + + it("ignores a page the app's frame navigated to", async () => { + setup(NAVIGATING_APP_HTML); + const element = () => ( + + ); + await using screen = await render(element()); + const frame = screen.getByTitle("Demo app").element() as HTMLIFrameElement; + const row = frame.parentElement!.parentElement!; + // The app resizes only after the host's answer reached it, so the bridge works both ways. + await expect.element(row).toHaveStyle({ height: "321px" }); + + // A tool update hands the row an equal app in a new object, which re-attaches the host. + await screen.rerender(element()); + frame.contentWindow!.postMessage("leave", "*"); + await expect + .element(screen.getByText("The Demo app left its page and was stopped")) + .toBeInTheDocument(); + expect(row.style.height).toBe("321px"); + }); }); diff --git a/apps/web/src/components/chat/McpAppFrame.tsx b/apps/web/src/components/chat/McpAppFrame.tsx index c0893c2d6f7c3..3d90a688f717c 100644 --- a/apps/web/src/components/chat/McpAppFrame.tsx +++ b/apps/web/src/components/chat/McpAppFrame.tsx @@ -38,6 +38,7 @@ import { useTurnItemDetail } from "~/state/queries"; import { mcpAppEnvironment } from "~/state/mcpApps"; import { useAtomCommand } from "~/state/use-atom-command"; import { observeResize } from "~/lib/observeResize"; +import { attachMcpAppDocumentLink } from "./mcpAppDocumentLink"; import { useNativeTitlebarHeight } from "~/lib/windowControlsOverlay"; const commandFailure = (result: { @@ -269,16 +270,15 @@ export function McpAppFrame(props: { } return approved; }; - const target = () => frameRef.current?.contentWindow ?? null; const scope = () => { const { environmentId, threadId, itemId } = readLive().props; return { environmentId, input: { threadId, itemId } }; }; + const documentLink = attachMcpAppDocumentLink(frame, (data) => host.receive(data)); const host = makeMcpAppHost({ app, hostVersion: APP_VERSION, - // Opaque origins require "*"; the window reference scopes delivery to this frame. - post: (message) => target()?.postMessage(message, "*"), + post: documentLink.post, hostContext, callTool: async ({ name, arguments: args }) => { const { environmentId, input } = scope(); @@ -401,12 +401,9 @@ export function McpAppFrame(props: { }, }); hostRef.current = host; - const receive = (event: MessageEvent) => { - if (event.source !== null && event.source === target()) host.receive(event.data); - }; - window.addEventListener("message", receive); + window.addEventListener("message", documentLink.receive); return () => { - window.removeEventListener("message", receive); + window.removeEventListener("message", documentLink.receive); void host.teardown(); hostRef.current = null; frameRef.current = null; diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index bce13bb454379..222f498e7123a 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -1,6 +1,5 @@ import { injectHtmlRenderBootstrap } from "@t3tools/shared/htmlRender"; import { HtmlRenderDocument } from "../files/BrowserDocumentFrame"; -import { flushSync } from "react-dom"; import { AudioPreview } from "../files/AudioPreview"; import { cdp, page, userEvent } from "vite-plus/test/browser"; import { @@ -18,7 +17,7 @@ import { ThreadId, type OrchestrationV2Subagent, } from "@t3tools/contracts"; -import { LegendList, type LegendListRef } from "@legendapp/list/react"; +import { type LegendListRef } from "@legendapp/list/react"; import { createRef, Profiler, @@ -35,7 +34,6 @@ import "~/index.css"; import { environmentThreadDetails } from "../../state/threads"; import { act, fakeTimers, render, stubGlobal } from "../../../test/render"; -import { ChangedFilesCard } from "./ChangedFilesTree"; import { MessagesTimeline } from "./MessagesTimeline"; import { createWorkspaceFocusController, workspaceAreaProps } from "../../lib/workspaceFocus"; import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic"; @@ -78,15 +76,17 @@ vi.mock(import("~/state/query"), async (original) => ({ })) as never, })); -const stubbedAsset = vi.hoisted(() => ({ url: "" })); +const stubbedAsset = vi.hoisted(() => ({ url: "", failed: false })); vi.mock(import("~/assets/assetUrls"), async (original) => { const actual = await original(); return { ...actual, useAssetUrlState: ((...args: Parameters) => - stubbedAsset.url - ? { _tag: "Success", url: stubbedAsset.url } - : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState, + stubbedAsset.failed + ? { _tag: "Failure" } + : stubbedAsset.url + ? { _tag: "Success", url: stubbedAsset.url } + : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState, useAssetUrls: ((...args: Parameters) => stubbedAsset.url ? args[1].map(() => stubbedAsset.url) @@ -110,7 +110,6 @@ function baseProps(): Omit { turnDiffSummaries: [], runs: [], routeThreadKey: `environment-local:thread-${Math.random().toString(36).slice(2)}`, - onOpenTurnDiff: () => {}, onOpenThread: () => {}, onForkFromRun: async () => {}, supportsConversationRollback: false, @@ -816,6 +815,51 @@ describe("MessagesTimeline messages", () => { expectItemOrder(); }); + it("opens a working parent thread at its end without landing short", async () => { + setup(); + const props = baseProps(); + const parent = Array.from({ length: 30 }, (_, index) => + message( + `Parent turn ${index}:\n\n${"x ".repeat(200)}`, + { role: index % 2 === 0 ? "user" : "assistant" }, + `parent-${index}`, + ), + ); + await using screen = await renderElement( + {} }} + timelineEntries={[message("Short child reply.", { role: "assistant" }, "child-0")]} + />, + ); + expect(screen.text()).toContain("Subagent of"); + const viewport = props.listRef.current!.getScrollableNode()!; + const end = () => viewport.scrollHeight - viewport.clientHeight; + // Distance from the end as each scroll lands, against the content height at that moment. + const shortfalls: number[] = []; + viewport.addEventListener("scroll", () => + shortfalls.push(Math.round(end() - viewport.scrollTop)), + ); + + // A working parent's footer (queued turns, its subagents) is taller than the child's. + await screen.rerender( + Waiting on 4 subagents} + isWorking + />, + ); + await vi.waitFor(() => { + expect(screen.text()).toContain("Parent turn 29:"); + expect(end() - viewport.scrollTop).toBeLessThanOrEqual(1); + }); + + expect(shortfalls.length).toBeGreaterThan(0); + expect(shortfalls).toEqual(shortfalls.map(() => 0)); + }); + it("puts rows back in item order soon after a continuous scroll stops", async () => { setup(); const props = baseProps(); @@ -1359,6 +1403,37 @@ describe("MessagesTimeline citations", () => { }); }); + it("keeps the citation highlight through an IME Escape", async () => { + await using _screen = await renderTimeline( + [ + message("A question", {}, "question"), + message("the cited answer", { role: "assistant" }, "cited"), + ], + { citationRequest: CITATION_REQUEST, citationHistory: { _tag: "found" } }, + ); + const highlighted = () => document.querySelector("[data-citation-highlighted]"); + await vi.waitFor(() => expect(highlighted()).not.toBeNull()); + const pressEscape = (init: KeyboardEventInit, prevented = false) => + act(() => { + const event = new KeyboardEvent("keydown", { + key: "Escape", + ...init, + bubbles: true, + cancelable: true, + }); + // The composer's editor prevents every plain Escape before it reaches the document. + if (prevented) event.preventDefault(); + document.body.dispatchEvent(event); + }); + + for (const init of [{ isComposing: true }, { keyCode: 229 }]) { + await pressEscape(init); + expect(highlighted()).not.toBeNull(); + } + await pressEscape({ keyCode: 27 }, true); + expect(highlighted()).toBeNull(); + }); + it("opens the superseded attempt that folds the cited response", async () => { const runId = RunId.make("run-steered"); const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({ @@ -1842,6 +1917,47 @@ describe("MessagesTimeline attachments", () => { ); }); + it("keeps an unavailable viewed image inside the 10rem work-log strip", async () => { + stubbedAsset.failed = true; + onTestFinished(() => { + stubbedAsset.failed = false; + }); + await using screen = await renderElement( + + + , + ); + const frame = await vi.waitFor(() => { + const element = screen.container.querySelector( + '[data-image-gallery] [role="alert"]', + ); + expect(element).toBeTruthy(); + return element!; + }); + const size = await vi.waitFor(() => { + const rect = frame.getBoundingClientRect(); + expect(rect.width).toBeGreaterThan(0); + return rect; + }); + expect(size.height).toBeLessThanOrEqual(161); + expect(size.width).toBeLessThanOrEqual(285); + expect(Math.abs(size.width / size.height - 16 / 9)).toBeLessThan(0.02); + }); + it("opens an image from an expanded tool row as a gallery of the turn's viewed images", async () => { stubbedAsset.url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; @@ -2262,73 +2378,6 @@ it("renders automatic compaction as one live divider that finishes with its reas expect(container.textContent).not.toContain("Compacting before"); }); -function TimelineChangedFilesCard() { - const [expanded, setExpanded] = useState(true); - return ( - ({ - path, - kind: "modified", - additions: 1, - deletions: 0, - }))} - totals={{ count: 3, additions: 3, deletions: 0 }} - allDirectoriesExpanded={expanded} - resolvedTheme="light" - onToggleAllDirectories={() => setExpanded((value) => !value)} - onOpenTurnDiff={() => {}} - /> - ); -} - -function ChangedFilesTimeline() { - return ( - item} - estimatedItemSize={100} - recycleItems={false} - className="h-[600px]" - renderItem={({ item }) => - item === "files" ? :
After
- } - /> - ); -} - -describe("ChangedFilesCard", () => { - it.each(["folder", "all folders"])( - "measures %s collapse and expansion in the same commit", - async (toggle) => { - await using screen = await render(); - const after = () => - screen.container.querySelector('[data-testid="after"]')!.getBoundingClientRect().top; - const cardBottom = () => - screen.container.querySelector("[data-changed-files-state]")!.getBoundingClientRect() - .bottom; - await vi.waitFor(() => expect(after()).toBe(cardBottom())); - const topBefore = after(); - const button = () => - screen.container.querySelector( - toggle === "folder" - ? '[data-changed-file-row="src"] button' - : 'button[aria-label$="all folders"]', - )!; - await act(() => { - flushSync(() => button().click()); - expect(screen.container.textContent).not.toContain("a.ts"); - expect(after()).toBe(topBefore - 3 * 28); - }); - await act(() => { - flushSync(() => button().click()); - expect(screen.container.textContent).toContain("a.ts"); - expect(after()).toBe(topBefore); - }); - }, - ); -}); - it("keeps concurrent approvals actionable outside collapsed work and restores settled rows", async () => { setup(); const fixture = makeStreamingTimelineFixture(); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index f1726cbbb92b2..649d6fe289494 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1084,8 +1084,8 @@ describe("deriveMessagesTimelineRows", () => { expect(assistantRows[1]?.showAssistantCopyButton).toBe(true); }); - it("projects assistant diffs and rewinds the first visible run to thread start after a rewind", () => { - const assistantTurnDiffSummary = { + it("rewinds the first visible run to thread start after a rewind", () => { + const checkpoint = { runId: "turn-1" as never, completedAt: "2026-01-01T00:00:30Z", assistantMessageId: "assistant-1" as never, @@ -1129,7 +1129,7 @@ describe("deriveMessagesTimelineRows", () => { ], isWorking: false, activeTurnStartedAt: null, - turnDiffSummaries: [assistantTurnDiffSummary], + turnDiffSummaries: [checkpoint], supportsConversationRollback: true, threadStartCheckpointAvailable: true, }); @@ -1138,13 +1138,7 @@ describe("deriveMessagesTimelineRows", () => { (row): row is Extract<(typeof rows)[number], { kind: "message" }> => row.kind === "message" && row.message.role === "user", ); - const assistantRow = rows.find( - (row): row is Extract<(typeof rows)[number], { kind: "message" }> => - row.kind === "message" && row.message.role === "assistant", - ); - expect(userRow?.revertTurnCount).toBe(0); - expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary); }); it("folds the first assistant message and settled work before the terminal response", () => { @@ -5087,6 +5081,20 @@ describe("parent run waiting on foreground subagents", () => { expect(liveRow([], "hideAll")).toEqual({ ...thinking, label: "Waiting on 2 subagents" }); }); + // regression: #40551 a finished status after the children is the parent parking, not new work + it("names the running children when the parent's finished status message follows them", () => { + const status: OrchestrationV2TurnItem = { + ...base("status", 5), + status: "completed", + type: "assistant_message", + messageId: MessageId.make("status"), + text: "Subagents launched; waiting for them to report back.", + streaming: false, + }; + expect(liveRow([status])).toEqual({ ...thinking, label: "Waiting on 2 subagents" }); + expect(liveRow([{ ...status, runId: RunId.make("other-run") }])).toEqual(thinking); + }); + it("keeps Thinking when a hidden newer parent command follows the children", () => { const command: OrchestrationV2TurnItem = { ...base("command", 5), diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 6bd30f1ac3212..d6f260e1dbabf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -639,7 +639,6 @@ type MessagesTimelineRowContent = suppressEmptyResponse?: boolean; showAssistantCopyButton: boolean; assistantCopyStreaming: boolean; - assistantTurnDiffSummary?: TurnDiffSummary | undefined; revertTurnCount?: number | undefined; /** Another of your messages follows directly, so the two sit closer together. */ groupedWithNext?: boolean; @@ -1519,6 +1518,15 @@ function runningSubagentsAtRunTail(entries: ReadonlyArray, runId: let running = 0; for (let index = entries.length - 1; index >= 0; index -= 1) { const entry = entries[index]!; + // The run's own finished reply is the parent parking on the children, not new work. + if ( + entry.kind === "message" && + entry.message.role === "assistant" && + !entry.message.streaming && + entry.message.runId === runId + ) { + continue; + } if (entry.kind !== "event") break; const { item } = entry.projectedItem; if (item.type !== "subagent" || item.runId !== runId) break; @@ -1647,12 +1655,6 @@ export function deriveMessagesTimelineRows( input.pendingApprovalRequestIds?.has(item.requestId) === true ); }; - const turnDiffSummaryByAssistantMessageId = new Map(); - for (const summary of input.turnDiffSummaries) { - if (summary.assistantMessageId) { - turnDiffSummaryByAssistantMessageId.set(summary.assistantMessageId, summary); - } - } const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null, input.runningRunId ?? null); const revertTurnCountByUserMessageId = input.supportsConversationRollback ? deriveRevertTurnCountByUserMessageId({ @@ -2329,10 +2331,6 @@ export function deriveMessagesTimelineRows( embeddedResultRunIds.has(timelineEntry.message.runId), showAssistantCopyButton: showAssistantMeta, assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress, - assistantTurnDiffSummary: - timelineEntry.message.role === "assistant" - ? turnDiffSummaryByAssistantMessageId.get(timelineEntry.message.id) - : undefined, revertTurnCount: timelineEntry.message.role === "user" ? revertTurnCountByUserMessageId.get(timelineEntry.message.id) @@ -2919,7 +2917,6 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.suppressEmptyResponse === bm.suppressEmptyResponse && a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && - a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && a.revertTurnCount === bm.revertTurnCount && a.groupedWithNext === bm.groupedWithNext && a.groupedWithPrevious === bm.groupedWithPrevious && diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 24085461995cf..30860aa4c81fd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -272,7 +272,6 @@ interface MessagesTimelineProps { /** Off where another region already speaks the thread's status, like a subagent's bar. */ announceTurnStatus?: boolean; onOpenToolDiff?: (target: ToolCallDiffTarget) => void; - onOpenTurnDiff?: (runId: RunId, filePath?: string) => void; onOpenThread: ( threadId: OrchestrationV2TurnItem["threadId"], environmentId?: EnvironmentId, @@ -398,7 +397,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ displayThreadKey, announceTurnStatus = true, onOpenToolDiff, - onOpenTurnDiff, onOpenThread, renderHtmlRender, turnItemSource, @@ -1146,7 +1144,6 @@ const ConversationTimeline = memo(function ConversationTimeline({ onFileDownload, openPullRequest, onOpenToolDiff, - onOpenTurnDiff, onOpenThread, renderHtmlRender, turnItemSource, @@ -1404,7 +1401,8 @@ const ConversationTimeline = memo(function ConversationTimeline({ >
@@ -1511,10 +1509,10 @@ const ConversationTimeline = memo(function ConversationTimeline({ ? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH : TIMELINE_MAINTAIN_SCROLL_AT_END } + // A restore owns the scroll position until it lands. Anchoring would + // move it for the previous thread's header as the list swaps threads. maintainVisibleContentPosition={ - findActive || - citationPositioning || - (restoringThreadPosition && rememberedPosition?.atEnd === false) + findActive || citationPositioning || restoringThreadPosition ? false : maintainVisibleContentPosition } diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index cc246a1f9967c..51d06370dd838 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -66,6 +66,7 @@ vi.mock(import("../../remoteOpen"), async (importOriginal) => ({ })); import { OpenInPicker } from "./OpenInPicker"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { registerOpenFavoriteEditorCommand, useOpenFavoriteEditorShortcut, @@ -98,7 +99,7 @@ async function setup() { async function renderPicker( availableEditors: readonly EditorId[] = editors, panel = false, - { openInCwd = "/work/project", revealFileManager = false } = {}, + { openInCwd = "/work/project", fileManagerAction = "open" as FileManagerAction } = {}, ) { await act(async () => { for (const listener of state.listeners) listener(); @@ -108,7 +109,7 @@ async function setup() { keybindings={DEFAULT_RESOLVED_KEYBINDINGS} availableEditors={availableEditors} openInCwd={openInCwd} - revealFileManager={revealFileManager} + fileManagerAction={fileManagerAction} displayMode={panel ? "panel" : "toolbar"} compact={!panel} /> @@ -189,6 +190,34 @@ describe("host editor access", () => { }); }); +describe("file manager", () => { + it("waits for the path's type, then shows a file in its folder", async () => { + await using fixture = await setup(); + const { renderPicker, primaryButton, click, pressOpenFavorite } = fixture; + state.allowed.add(selected); + const openInCwd = "/work/project/notes.md"; + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "unavailable" }); + + expect(primaryButton().disabled).toBe(true); + await click(primaryButton()); + expect((await pressOpenFavorite()).defaultPrevented).toBe(false); + expect(state.run).not.toHaveBeenCalled(); + + // A failed open is not announced, so no timer outlives the test. + state.run.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("No file manager")))); + await renderPicker(["file-manager"], false, { openInCwd, fileManagerAction: "reveal" }); + await click(primaryButton()); + expect(state.run.mock.calls).toEqual([ + [ + { + environmentId: selected, + input: { cwd: openInCwd, editor: "file-manager", reveal: true }, + }, + ], + ]); + }); +}); + describe("remote editor links", () => { it("opens the link from the fallback when the picker is not mounted", async () => { await using fixture = await setup(); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.test.ts b/apps/web/src/components/chat/OpenInPicker.logic.test.ts index 10595e2f8cdbe..3b5536c78f396 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.test.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.test.ts @@ -1,7 +1,7 @@ import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { shouldShowOpenInPicker } from "./OpenInPicker.logic"; +import { fileManagerActionForPath, shouldShowOpenInPicker } from "./OpenInPicker.logic"; describe("shouldShowOpenInPicker", () => { it("shows both local environments when the primary has a separate WSL home", () => { @@ -24,3 +24,16 @@ describe("shouldShowOpenInPicker", () => { } }); }); + +describe("fileManagerActionForPath", () => { + it("opens only folders and shows a file once its read settled on a server that can", () => { + for (const [isFolder, isSettled, canReveal, action] of [ + [true, false, false, "open"], + [false, false, true, "unavailable"], + [false, true, false, "unavailable"], + [false, true, true, "reveal"], + ] as const) { + expect(fileManagerActionForPath({ isFolder, isSettled, canReveal })).toBe(action); + } + }); +}); diff --git a/apps/web/src/components/chat/OpenInPicker.logic.ts b/apps/web/src/components/chat/OpenInPicker.logic.ts index b7b21e47b2ea0..7e0408343b7a0 100644 --- a/apps/web/src/components/chat/OpenInPicker.logic.ts +++ b/apps/web/src/components/chat/OpenInPicker.logic.ts @@ -20,3 +20,18 @@ export function shouldShowOpenInPicker(input: { } return input.remoteOpenMode !== "local-exec"; } + +export type FileManagerAction = "open" | "reveal" | "unavailable"; + +/** + * The file manager opens folders and shows files in their folder. A path whose read has not + * settled may be either, and a file needs the server's reveal support, so both wait. + */ +export function fileManagerActionForPath(input: { + readonly isFolder: boolean; + readonly isSettled: boolean; + readonly canReveal: boolean; +}): FileManagerAction { + if (input.isFolder) return "open"; + return input.isSettled && input.canReveal ? "reveal" : "unavailable"; +} diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 711f1e4cb3e63..a4b7322aa5dda 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -10,6 +10,7 @@ import { T, useGT, useMessages, Var } from "gt-react"; import { memo, use, useRef } from "react"; import { BackgroundThreadContext } from "./backgroundThread"; import { shortcutLabelForCommand } from "../../keybindings"; +import type { FileManagerAction } from "./OpenInPicker.logic"; import { OPEN_FAVORITE_EDITOR_ATTRIBUTE } from "./OpenInPickerShortcut"; import { usePreferredEditor } from "../../editorPreferences"; import { editorLabelForPlatform } from "../../editorLabels"; @@ -21,7 +22,7 @@ import { useRemoteOpenState, } from "../../remoteOpen"; import { useEnvironment } from "../../state/environments"; -import { ChevronDownIcon, FolderClosedIcon, SquareArrowOutUpRightIcon } from "lucide-react"; +import { ChevronDownIcon, SquareArrowOutUpRightIcon } from "lucide-react"; import { Group, GroupSeparator } from "../ui/group"; import { @@ -36,35 +37,9 @@ import { MenuTrigger, } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; -import { - AntigravityIcon, - CursorIcon, - FileExplorerIcon, - FinderIcon, - Icon, - KiroIcon, - TraeIcon, - VisualStudioCode, - VisualStudioCodeInsiders, - VSCodium, - Zed, -} from "../Icons"; -import { - AquaIcon, - CLionIcon, - DataGripIcon, - DataSpellIcon, - GoLandIcon, - IntelliJIdeaIcon, - PhpStormIcon, - PyCharmIcon, - RiderIcon, - RubyMineIcon, - RustRoverIcon, - WebStormIcon, -} from "../JetBrainsIcons"; +import { type EditorIconOption, editorIconOptions } from "../editorIcons"; import { announce } from "~/lib/announce"; -import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils"; +import { cn } from "~/lib/utils"; import { shellEnvironment } from "~/state/shell"; import { useAtomCommand } from "~/state/use-atom-command"; import { @@ -77,131 +52,15 @@ import { import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; import { useComposerMenuState } from "./useComposerMenuState"; -type OpenInOption = { - label: string; - Icon: Icon; - value: EditorId; - kind: "brand" | "generic"; -}; +type OpenInOption = EditorIconOption & { label: string }; const resolveOpenInOptions = ( platform: string, availableEditors: ReadonlyArray, resolve: MessageResolver, -) => { - const baseOptions: ReadonlyArray> = [ - { - Icon: CursorIcon, - value: "cursor", - kind: "brand", - }, - { - Icon: TraeIcon, - value: "trae", - kind: "brand", - }, - { - Icon: KiroIcon, - value: "kiro", - kind: "brand", - }, - { - Icon: VisualStudioCode, - value: "vscode", - kind: "brand", - }, - { - Icon: VisualStudioCodeInsiders, - value: "vscode-insiders", - kind: "brand", - }, - { - Icon: VSCodium, - value: "vscodium", - kind: "brand", - }, - { - Icon: Zed, - value: "zed", - kind: "brand", - }, - { - Icon: AntigravityIcon, - value: "antigravity", - kind: "brand", - }, - { - Icon: IntelliJIdeaIcon, - value: "idea", - kind: "brand", - }, - { - Icon: AquaIcon, - value: "aqua", - kind: "brand", - }, - { - Icon: CLionIcon, - value: "clion", - kind: "brand", - }, - { - Icon: DataGripIcon, - value: "datagrip", - kind: "brand", - }, - { - Icon: DataSpellIcon, - value: "dataspell", - kind: "brand", - }, - { - Icon: GoLandIcon, - value: "goland", - kind: "brand", - }, - { - Icon: PhpStormIcon, - value: "phpstorm", - kind: "brand", - }, - { - Icon: PyCharmIcon, - value: "pycharm", - kind: "brand", - }, - { - Icon: RiderIcon, - value: "rider", - kind: "brand", - }, - { - Icon: RubyMineIcon, - value: "rubymine", - kind: "brand", - }, - { - Icon: RustRoverIcon, - value: "rustrover", - kind: "brand", - }, - { - Icon: WebStormIcon, - value: "webstorm", - kind: "brand", - }, - { - Icon: isMacPlatform(platform) - ? FinderIcon - : isWindowsPlatform(platform) - ? FileExplorerIcon - : FolderClosedIcon, - value: "file-manager", - kind: isMacPlatform(platform) || isWindowsPlatform(platform) ? "brand" : "generic", - }, - ]; +): ReadonlyArray => { const availableEditorSet = new Set(availableEditors); - return baseOptions + return editorIconOptions(platform) .filter((option) => availableEditorSet.has(option.value)) .map((option) => ({ ...option, @@ -223,7 +82,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact = false, enableShortcut = true, displayMode = "toolbar", - revealFileManager = false, + fileManagerAction = "open", }: { environmentId: EnvironmentId; keybindings: ResolvedKeybindingsConfig; @@ -234,7 +93,7 @@ export const OpenInPicker = memo(function OpenInPicker({ compact?: boolean; enableShortcut?: boolean; displayMode?: "toolbar" | "panel"; - revealFileManager?: boolean; + fileManagerAction?: FileManagerAction; }) { const gt = useGT(); const messages = useMessages(); @@ -253,11 +112,13 @@ export const OpenInPicker = memo(function OpenInPicker({ // Remote editors run on the viewing machine; only desktop can probe that PATH. const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors; const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors); + const isEditorUnavailable = (editor: EditorId | null) => + editor === "file-manager" && fileManagerAction === "unavailable"; const openInEditor = async (editorId: EditorId | null): Promise => { if (!openInCwd) return false; const editor = editorId ?? preferredEditor; - if (!editor) return false; + if (!editor || isEditorUnavailable(editor)) return false; if (remote.mode === "remote-unavailable") return false; if (remote.mode === "remote-links") { const url = buildRemoteOpenUrl({ @@ -281,7 +142,7 @@ export const OpenInPicker = memo(function OpenInPicker({ input: { cwd: openInCwd, editor, - ...(revealFileManager && editor === "file-manager" ? { reveal: true } : {}), + ...(fileManagerAction === "reveal" && editor === "file-manager" ? { reveal: true } : {}), }, }); setPreferredEditor(editor); @@ -329,7 +190,11 @@ export const OpenInPicker = memo(function OpenInPicker({ {options.map(({ label, Icon, value, kind }) => ( { if (presentation === "menu") { @@ -365,8 +230,7 @@ export const OpenInPicker = memo(function OpenInPicker({ {primaryOption && ( openInEditor(preferredEditor)} > @@ -403,7 +267,9 @@ export const OpenInPicker = memo(function OpenInPicker({ variant={isPanel ? "ghost" : "outline"} part="primary" panel={isPanel} - disabled={!preferredEditor || !openInCwd || !canOpenEditor} + disabled={ + !preferredEditor || !openInCwd || !canOpenEditor || isEditorUnavailable(preferredEditor) + } {...(enableShortcut && !backgroundThread ? { [OPEN_FAVORITE_EDITOR_ATTRIBUTE]: "" } : {})} onClick={() => { if (!preferredEditor) return; diff --git a/apps/web/src/components/chat/SecretRequestCard.tsx b/apps/web/src/components/chat/SecretRequestCard.tsx index 25c1fe59d5e6b..49dff6b6a1c16 100644 --- a/apps/web/src/components/chat/SecretRequestCard.tsx +++ b/apps/web/src/components/chat/SecretRequestCard.tsx @@ -18,10 +18,11 @@ import { isAtomCommandInterrupted, squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; -import type { - EnvironmentId, - OrchestrationV2ProjectedTurnItem, - SecretProviderId, +import { + AuthProvidersManageScope, + type EnvironmentId, + type OrchestrationV2ProjectedTurnItem, + type SecretProviderId, } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { hasFeatureFlag } from "@t3tools/client-runtime/state/server"; @@ -38,6 +39,7 @@ import { import { useId, useRef, useState, type FormEvent } from "react"; import { serverEnvironment } from "../../state/server"; +import { useEnvironmentScope } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; @@ -80,7 +82,9 @@ const NO_SOURCES: ReadonlyArray = []; function useSecretRequestSources(environmentId: EnvironmentId) { const config = useAtomValue(serverEnvironment.configValueAtom(environmentId)); const messages = useMessages(); - return hasFeatureFlag(config, "secretProviders") + // The server accepts a reference answer only with this scope; without it the card is typed. + const canUseReferences = useEnvironmentScope(environmentId, AuthProvidersManageScope); + return canUseReferences && hasFeatureFlag(config, "secretProviders") ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages) : NO_SOURCES; } diff --git a/apps/web/src/components/chat/SideThreadPane.tsx b/apps/web/src/components/chat/SideThreadPane.tsx index 9f32d90c4f8a7..516103c5415f0 100644 --- a/apps/web/src/components/chat/SideThreadPane.tsx +++ b/apps/web/src/components/chat/SideThreadPane.tsx @@ -1,4 +1,4 @@ -import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; import { sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { @@ -18,7 +18,12 @@ import { useClientSettings } from "../../hooks/useSettings"; import { releaseComposerDraftUploads } from "../../lib/composerDraftUploads"; import type { SideChatParentPanel } from "../../lib/sideChatPane"; import { readLocalApi } from "../../localApi"; -import { hostRightPanel, type ThreadSurface, useRightPanelStore } from "../../rightPanelStore"; +import { + hostRightPanel, + rightPanelHostRef, + type ThreadSurface, + useRightPanelStore, +} from "../../rightPanelStore"; import { useQuietThreadProjection, useQuietThreadShell } from "../../state/entities"; import { useEnvironmentScope } from "../../state/session"; import { useEnvironmentShellStatus } from "../../state/shell"; @@ -34,6 +39,7 @@ import { Button } from "../ui/button"; import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { BackgroundThreadContext } from "./backgroundThread"; +import { closeThreadFindIn } from "./threadFindStore"; /** * A side chat or a subagent as a tab: the thread's own chat, which decides its bottom, the @@ -51,11 +57,18 @@ export default function SideThreadPane(props: { const { threadId } = surface; const gt = useGT(); const threadRef = scopeThreadRef(parentRef.environmentId, threadId); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store - useEffect( - () => hostRightPanel(scopeThreadRef(parentRef.environmentId, threadId), parentRef), - [parentRef, threadId], - ); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the parent panel as host in the panel store, and closes this side chat's find with its pane + useEffect(() => { + const ref = scopeThreadRef(parentRef.environmentId, threadId); + const unhost = hostRightPanel(ref, parentRef); + return () => { + unhost(); + // Crossing the sheet breakpoint remounts the pane in the same commit, which re-hosts it. + queueMicrotask(() => { + if (rightPanelHostRef(ref) === ref) closeThreadFindIn(scopedThreadKey(ref)); + }); + }; + }, [parentRef, threadId]); const shell = useQuietThreadShell(threadRef); const bootstrapComplete = isThreadRouteSnapshotAuthoritative( useEnvironmentShellStatus(parentRef.environmentId), diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx index b17067affb96f..666bbccd13684 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.browser.test.tsx @@ -17,6 +17,7 @@ import { expect, it, vi } from "vite-plus/test"; const state = vi.hoisted(() => ({ issuesSupported: false, isDraft: false, + headSha: "shown-head", status: "success" as PullRequestCheck["status"], extraStatus: null as PullRequestCheck["status"] | null, mergeMethods: ["merge"] as Array<"merge" | "squash" | "rebase">, @@ -59,6 +60,7 @@ const queryData = () => ({ title: "Test PR", state: "open", isDraft: state.isDraft, + headSha: state.headSha, mergeability: "mergeable", headBranch: "feature", baseBranch: "main", @@ -178,19 +180,21 @@ it("merges with the last selected merge method", async () => { const { container } = screen; state.mergeMethods = ["merge", "squash"]; useUiStateStore.getState().setPullRequestMergeMethod("squash"); - await act(async () => { - await screen.rerender( - , - ); - }); + const rerender = () => + act(async () => { + await screen.rerender( + , + ); + }); + await rerender(); const clickMerge = async (scope: ParentNode) => await act(async () => { [...scope.querySelectorAll("button")] @@ -200,10 +204,17 @@ it("merges with the last selected merge method", async () => { await clickMerge(container); const dialog = document.querySelector('[role="alertdialog"]')!; expect(dialog.textContent).toContain("using squash"); + // A push that a background refresh picks up while the confirmation is open. + state.headSha = "pushed-head"; + await rerender(); await clickMerge(dialog); expect(state.perform).toHaveBeenCalledWith( expect.objectContaining({ - input: expect.objectContaining({ action: "merge", mergeMethod: "squash" }), + input: expect.objectContaining({ + action: "merge", + mergeMethod: "squash", + expectedHeadSha: "shown-head", + }), }), ); }); @@ -260,6 +271,7 @@ async function setup() { state.updateToast.mockReset(); state.issuesSupported = false; + state.headSha = "shown-head"; state.isDraft = false; state.status = "success"; state.extraStatus = null; diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 3b7836b32293d..dd3e93ca9a578 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -166,14 +166,19 @@ export function ThreadDetailsPrRow({ checks: detail?.checks ?? [], }); + const [armedMergeHead, setArmedMergeHead] = useState(); const { actionPending, pendingAction, perform } = usePullRequestActionRunner({ environmentId, reference, + // The row shows no diff, so a merge lands the head it had when the confirmation opened. + headSha: armedMergeHead ?? detail?.headSha, terminology, onSuccess: () => { checksQuery.refresh(); onActed?.(); }, + // A refused merge usually means the row is stale, so show what the host has now. + onFailure: () => detailQuery.refresh(), }); const { handoff, startHandoff } = usePullRequestHandoffs({ environmentId, detail }); const lastSelectedMergeMethod = useUiStateStore((state) => state.pullRequestMergeMethod); @@ -449,7 +454,10 @@ export function ThreadDetailsPrRow({ method: mergeMethodKey, }, ), - onClick: () => setConfirmingMerge(true), + onClick: () => { + setArmedMergeHead(detail?.headSha); + setConfirmingMerge(true); + }, } : null; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 666ce784b3afc..da8035c458d70 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -66,7 +66,7 @@ vi.mock(import("../../state/use-atom-command"), () => ({ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { render } from "../../../test/render"; +import { fakeTimers, render } from "../../../test/render"; import { isMacPlatform } from "../../lib/utils"; import { selectThreadRightPanelState, useRightPanelStore } from "../../rightPanelStore"; import { makeThreadProjectionFixture } from "../../test-fixtures"; @@ -405,6 +405,58 @@ it("shows a remote subagent's full title in its tooltip even when its environmen expect(screen.router?.state.location.pathname).toBe("/environment/fork"); }); +it("shows how long a running remote subagent has been running, as a local one does", async () => { + setup(); + const remoteTitle = "Remote subagent running on a linked machine"; + using _timers = fakeTimers(); + vi.setSystemTime(new Date("2026-11-23T12:12:00.000Z")); + const startedAt = DateTime.makeUnsafe("2026-11-23T12:00:00.000Z"); + state.projection = { + ...(state.projection as Record), + subagents: [ + { + id: NodeId.make("remote-agent"), + threadId, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "remote", + providerInstanceId: "provider", + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Run remote task", + title: remoteTitle, + model: null, + status: "running", + result: null, + startedAt, + completedAt: null, + updatedAt: startedAt, + remoteChild: { + environmentId: EnvironmentId.make("remote-env"), + threadId: ThreadId.make("remote-thread"), + label: "127x05", + }, + }, + ], + }; + await using screen = await render( + , + { router: "/environment/fork" }, + ); + + // Assert synchronously: expect.element polls on timers this test fakes. + const row = screen.getByRole("button", { name: new RegExp(remoteTitle) }); + expect(row.element().textContent).toContain("12m"); +}); + it("explains why Merge back is unavailable before the fork completes a run", async () => { setup(); state.projection = { ...(state.projection as Record), runs: [] }; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index b005fa877b745..0aefaa8cea2ab 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -307,6 +307,12 @@ function RemoteSubagentRow(props: { const { remoteChild } = props.agent; const status = props.agent.status; const failed = status === "failed"; + const timing = { + status, + startedAt: props.agent.startedAt ? DateTime.formatIso(props.agent.startedAt) : null, + completedAt: props.agent.completedAt ? DateTime.formatIso(props.agent.completedAt) : null, + }; + const showElapsed = !failed && deriveSubagentElapsedMs(timing, 0) !== null; const title = relationshipThreadTitle({ title: props.agent.title ?? gt("Subagent"), isSubagent: true, @@ -348,7 +354,14 @@ function RemoteSubagentRow(props: { on {remoteChild.label} - · {threadRelationshipStatusLabel(status, m)} + + ·{" "} + {showElapsed ? ( + + ) : ( + threadRelationshipStatusLabel(status, m) + )} + diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 72fcf79013e87..9692bbedad62a 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -1,10 +1,10 @@ import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights"; -import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts"; +import { MessageId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; import { T, useGT, useMessages } from "gt-react"; -import { memo, use, useState } from "react"; -import { type ChatMessage, type TurnDiffSummary } from "../../types"; +import { use, useState } from "react"; +import { type ChatMessage } from "../../types"; import ChatMarkdown from "../ChatMarkdown"; import { GitForkIcon, ReplyIcon } from "lucide-react"; import { captureAssistantMessageOpening } from "~/lib/assistantTextSelection"; @@ -13,36 +13,17 @@ import { Button } from "../ui/button"; import { ProposedPlanCard } from "./ProposedPlanCard"; import { HtmlRenderFrame } from "./HtmlRenderFrame"; import { McpAppFrame } from "./McpAppFrame"; -import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints"; -import { ChangedFilesCard, type ChangedFilesGroup } from "./ChangedFilesTree"; -import { - changedFileTotals, - turnChanges, - turnHasChanges, -} from "@t3tools/client-runtime/state/thread-repositories"; -import { useFileContextMenuHandler } from "../../fileContextMenu"; -import { - readResponseSubagents, - useAssistantMessageText, - useProject, - useQuietThreadShell, -} from "../../state/entities"; +import { readResponseSubagents, useAssistantMessageText } from "../../state/entities"; import { MessageCopyButton } from "./MessageCopyButton"; import { AssistantCitationSource } from "./AssistantCitationSource"; import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; -import { useUiStateStore } from "~/uiStateStore"; import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat"; import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; -import { useAtomValue } from "@effect/atom-react"; -import { AsyncResult, Atom } from "effect/reactivity"; -import { vcsEnvironment } from "../../state/vcs"; - -const NO_VCS_STATUS = Atom.make(AsyncResult.initial()); export function AssistantTimelineRow({ row }: { row: Extract }) { const ctx = use(TimelineRowCtx); @@ -88,14 +69,6 @@ export function AssistantTimelineRow({ row }: { row: Extract
- {ctx.onOpenTurnDiff ? ( - - ) : null} {!row.showAssistantMeta && row.projectedItem?.item.status === "interrupted" ? (
@@ -394,7 +367,7 @@ export function HtmlRenderTimelineRow({ return
{ctx.renderHtmlRender(row)}
; } return ( -
+
); } - -/** Subscribes directly to the UI state store for expand/collapse state, - * so toggling re-renders only this component — not the entire list. */ -const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({ - turnSummary, - routeThreadKey, - resolvedTheme, - onOpenTurnDiff, -}: { - turnSummary: TurnDiffSummary | undefined; - routeThreadKey: string; - resolvedTheme: "light" | "dark"; - displayThreadKey?: string; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; -}) { - if (!turnSummary) return null; - const checkpointFiles = turnSummary.files; - if (!turnHasChanges(turnSummary)) return null; - - return ( - - ); -}); - -function AssistantChangedFilesSectionInner({ - turnSummary, - checkpointFiles, - routeThreadKey, - resolvedTheme, - onOpenTurnDiff, -}: { - turnSummary: TurnDiffSummary; - checkpointFiles: TurnDiffSummary["files"]; - routeThreadKey: string; - resolvedTheme: "light" | "dark"; - displayThreadKey?: string; - onOpenTurnDiff: (runId: RunId, filePath?: string) => void; -}) { - const ctx = use(TimelineRowCtx); - const gt = useGT(); - const persistedExpanded = useUiStateStore( - (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId], - ); - const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded); - const allDirectoriesExpanded = persistedExpanded ?? false; - - const thread = useQuietThreadShell(ctx.threadRef); - const activeProject = useProject( - thread && thread.projectId - ? { environmentId: thread.environmentId, projectId: thread.projectId } - : null, - ); - const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId); - const repositoryRoot = useAtomValue( - ctx.workspaceRoot - ? vcsEnvironment.status({ - environmentId: ctx.activeThreadEnvironmentId, - input: { cwd: ctx.workspaceRoot }, - }) - : NO_VCS_STATUS, - (status) => AsyncResult.getOrElse(status, () => null)?.workingTree.rootPath, - ); - const repositories = turnSummary.repositories; - const rootGroupName = activeProject?.title ?? gt("Project folder"); - const groups: ReadonlyArray | undefined = - repositories === undefined - ? undefined - : [ - ...(checkpointFiles.length === 0 - ? [] - : [ - { - key: ".", - name: rootGroupName, - files: checkpointFiles, - totals: checkpointFileTotals(turnSummary), - relativePath: "", - }, - ]), - ...repositories.map((repository) => ({ - key: repository.scopeId, - name: repository.name, - files: repository.files, - totals: changedFileTotals(repository), - relativePath: repository.relativePath, - ...(repository.baselineMissing - ? { note: gt("This turn's changes in this repository cannot be listed.") } - : {}), - })), - ]; - const repositoryCwdByGroupKey = new Map( - repositories?.map((repository) => [repository.scopeId as string, repository.cwd]), - ); - - return ( - - setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded) - } - onOpenTurnDiff={onOpenTurnDiff} - onFileContextMenu={(filePath, event, group) => { - const repositoryCwd = group && repositoryCwdByGroupKey.get(group.key); - onFileContextMenu( - repositoryCwd === undefined - ? { - environmentId: ctx.activeThreadEnvironmentId, - filePath, - workspaceRoot: ctx.workspaceRoot, - repositoryRoot: - repositoryRoot ?? - (thread?.worktreePath == null - ? activeProject?.repositoryIdentity?.rootPath - : undefined), - } - : { - environmentId: ctx.activeThreadEnvironmentId, - filePath, - workspaceRoot: repositoryCwd, - }, - event, - ); - }} - /> - ); -} diff --git a/apps/web/src/components/chat/canvasStore.test.ts b/apps/web/src/components/chat/canvasStore.test.ts index c7620f1db5c87..f1e9d4160f2e4 100644 --- a/apps/web/src/components/chat/canvasStore.test.ts +++ b/apps/web/src/components/chat/canvasStore.test.ts @@ -17,6 +17,7 @@ const measurements = (width: number, height = 900): ChatCanvasMeasurements => ({ height, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 180, timelineGutter: 0, diff --git a/apps/web/src/components/chat/canvasStore.ts b/apps/web/src/components/chat/canvasStore.ts index 6b350cf95f22f..88811d1a41706 100644 --- a/apps/web/src/components/chat/canvasStore.ts +++ b/apps/web/src/components/chat/canvasStore.ts @@ -17,6 +17,7 @@ export interface ChatCanvasMeasurements { readonly height: number; readonly padding: number; readonly maxChatWidth: number; + readonly maxHtmlPreviewWidth: number; readonly minChatWidth: number; readonly composerHeight: number; readonly timelineGutter: number; @@ -36,6 +37,7 @@ const INITIAL_MEASUREMENTS: ChatCanvasMeasurements = { height: 0, padding: 48, maxChatWidth: 768, + maxHtmlPreviewWidth: 768, minChatWidth: 640, composerHeight: 0, timelineGutter: 0, @@ -52,6 +54,7 @@ const sameMeasurements = (a: ChatCanvasMeasurements, b: ChatCanvasMeasurements) a.height === b.height && a.padding === b.padding && a.maxChatWidth === b.maxChatWidth && + a.maxHtmlPreviewWidth === b.maxHtmlPreviewWidth && a.minChatWidth === b.minChatWidth && a.composerHeight === b.composerHeight && a.timelineGutter === b.timelineGutter && @@ -135,6 +138,7 @@ export function resolveChatCanvasModel({ preview, padding: measurements.padding, maxChatWidth: measurements.maxChatWidth, + maxHtmlPreviewWidth: measurements.maxHtmlPreviewWidth, minChatWidth: measurements.minChatWidth, composerHeight: measurements.composerHeight, detailsCard, diff --git a/apps/web/src/components/chat/chatCanvasLayout.test.ts b/apps/web/src/components/chat/chatCanvasLayout.test.ts index 2f9e82a9e600b..53ee3f6b1ac7b 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.test.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.test.ts @@ -326,6 +326,53 @@ describe("chat canvas layout", () => { }); }); +describe("html preview lane", () => { + const wide = ( + width: number, + options: Partial[0]> = {}, + maxHtmlPreviewWidth = 1152, + ) => + resolveChatCanvasLayout({ + container: { width, height: 900 }, + preview: null, + maxChatWidth: 736, + maxHtmlPreviewWidth, + composerHeight: 180, + ...options, + }); + it("matches the chat column unless the setting allows more", () => { + const result = wide(1600, {}, 736); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("widens around a chat column that stays where it was", () => { + const result = wide(1600); + expect(result.chat).toEqual(wide(1600, {}, 736).chat); + expect(result.htmlPreview).toEqual({ left: 224, width: 1152 }); + expect(wide(1200).htmlPreview).toEqual({ left: 48, width: 1104 }); + expect(wide(1600, {}, 1600).htmlPreview).toEqual({ left: 48, width: 1504 }); + }); + it("is never narrower than the chat column", () => { + const result = wide(1600, { maxChatWidth: 1600 }, 1152); + expect(result.htmlPreview).toEqual({ left: result.chat.left, width: result.chat.width }); + }); + it("stops short of the details card", () => { + const detailsCard = { left: 1308, right: 1588, bottom: 400 }; + const result = wide(1600, { detailsCard }); + expect(result.chat).toEqual(wide(1600, { detailsCard }, 736).chat); + expect(result.htmlPreview).toEqual({ left: 124, width: 1152 }); + expect(wide(1600, { detailsCard }, 1600).htmlPreview).toEqual({ left: 48, width: 1228 }); + }); + it("stops short of a mini player beside the chat and matches chat under one over it", () => { + const beside = wide(1900, { preview: { ...preview, position: { x: 1500, y: 600 } } }); + expect(beside.overlapsChat).toBe(false); + expect(beside.htmlPreview.left + beside.htmlPreview.width).toBe(beside.frame!.x - 12); + expect(beside.htmlPreview.width).toBeGreaterThan(beside.chat.width); + const over = wide(1000, { preview: { ...preview, position: { x: 12, y: 700 } } }); + expect(over.overlapsChat).toBe(true); + expect(over.htmlPreview).toEqual({ left: over.chat.left, width: over.chat.width }); + }); +}); + describe("workspace card beside chat", () => { const withCard = (width: number, player: ChatCanvasPreview | null = null, maxChatWidth = 736) => resolveChatCanvasLayout({ diff --git a/apps/web/src/components/chat/chatCanvasLayout.ts b/apps/web/src/components/chat/chatCanvasLayout.ts index 77e276ee817f4..a1fc0b54b4ab1 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.ts @@ -26,6 +26,7 @@ export function resolveChatCanvasLayout({ preview, padding = 48, maxChatWidth = 768, + maxHtmlPreviewWidth = maxChatWidth, minChatWidth = 640, composerHeight = 0, detailsCard = null, @@ -35,6 +36,7 @@ export function resolveChatCanvasLayout({ preview: ChatCanvasPreview | null; padding?: number; maxChatWidth?: number; + maxHtmlPreviewWidth?: number; minChatWidth?: number; composerHeight?: number; detailsCard?: PreviewMiniPlayerObstacles["detailsCard"]; @@ -176,5 +178,19 @@ export function resolveChatCanvasLayout({ frame.x + frame.width > detailsCard.left && frame.y < detailsCard.bottom, ); - return { chat, frame, overlapsChat, overlapsDetailsCard }; + // A wider HTML preview stays centered on the chat column while that fits, and + // clear of the details card and a mini player the chat column sits beside. + const laneEnd = frame ? Math.min(laneRight, frame.x - GAP) : laneRight; + const htmlPreviewWidth = overlapsChat ? 0 : Math.min(maxHtmlPreviewWidth, laneEnd - padding); + const htmlPreview = + htmlPreviewWidth > chat.width + ? { + left: Math.max( + padding, + Math.min(chat.left + (chat.width - htmlPreviewWidth) / 2, laneEnd - htmlPreviewWidth), + ), + width: htmlPreviewWidth, + } + : { left: chat.left, width: chat.width }; + return { chat, htmlPreview, frame, overlapsChat, overlapsDetailsCard }; } diff --git a/apps/web/src/components/chat/composerFocusRedirect.ts b/apps/web/src/components/chat/composerFocusRedirect.ts index cb187e73ea6a7..2fc544a31c9b4 100644 --- a/apps/web/src/components/chat/composerFocusRedirect.ts +++ b/apps/web/src/components/chat/composerFocusRedirect.ts @@ -12,6 +12,7 @@ const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ "button", "a[href]", "summary", + "video[controls]", '[role="application"]', '[role="button"]', '[role="checkbox"]', diff --git a/apps/web/src/components/chat/mcpAppDocumentLink.ts b/apps/web/src/components/chat/mcpAppDocumentLink.ts new file mode 100644 index 0000000000000..6982dd3e12a80 --- /dev/null +++ b/apps/web/src/components/chat/mcpAppDocumentLink.ts @@ -0,0 +1,67 @@ +import { MCP_APP_DOCUMENT_MESSAGE } from "@t3tools/shared/mcpApp"; + +const MAX_UNCONFIRMED_MESSAGES = 256; + +interface DocumentLink { + link: MessagePort | "window" | null; + nextProbe: number; + deliver: (data: unknown) => void; + readonly unconfirmed: Map; +} + +// Kept per frame, not per host: a host that re-attaches to the same frame must not take the +// frame's next message for a first one. +const documentLinks = new WeakMap(); + +/** + * Ties the bridge to the frame's first document. A frame's window outlives its document, so the + * bridge follows the port that document's bootstrap sends first, not the window. Servers without + * the bootstrap keep the plain window bridge. + */ +export function attachMcpAppDocumentLink( + frame: HTMLIFrameElement, + deliver: (data: unknown) => void, +) { + let state = documentLinks.get(frame); + if (state === undefined) { + state = { link: null, nextProbe: 0, deliver, unconfirmed: new Map() }; + documentLinks.set(frame, state); + } + const current = state; + current.deliver = deliver; + return { + receive: (event: MessageEvent) => { + if (event.source === null || event.source !== frame.contentWindow) return; + if (current.link === null) { + const port = event.data?.t3 === MCP_APP_DOCUMENT_MESSAGE ? (event.ports[0] ?? null) : null; + if (port !== null) { + current.link = port; + port.onmessage = (reply: MessageEvent) => { + const probe: unknown = reply.data?.alive; + if (typeof probe !== "number" || !current.unconfirmed.has(probe)) return; + const data = current.unconfirmed.get(probe); + current.unconfirmed.delete(probe); + current.deliver(data); + }; + return; + } + current.link = "window"; + } + if (current.link === "window") { + current.deliver(event.data); + return; + } + // Only the first document can answer, so a reply proves it sent this message. + if (current.unconfirmed.size >= MAX_UNCONFIRMED_MESSAGES) return; + current.unconfirmed.set(current.nextProbe, event.data); + // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin. + current.link.postMessage({ alive: current.nextProbe }); + current.nextProbe += 1; + }, + post: (message: unknown) => { + // Opaque origins require "*"; the window reference scopes delivery to this frame. + if (current.link === "window") frame.contentWindow?.postMessage(message, "*"); + else current.link?.postMessage({ message, origin: window.location.origin }); + }, + }; +} diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index 0ebfdacdbb607..b752b63ef0bbc 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -3,6 +3,7 @@ import { ComposerContextId, EnvironmentId, MessageId, + ProviderInstanceId, ThreadId, TurnItemId, } from "@t3tools/contracts"; @@ -27,6 +28,11 @@ import { const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); const editTarget = DraftId.make("queued-edit:test"); +const originalModelSelection = { + instanceId: ProviderInstanceId.make("codex"), + model: "original-model", +}; +const changedModelSelection = { ...originalModelSelection, model: "changed-model" }; const originalMessage = { editTarget, threadTarget, @@ -153,6 +159,20 @@ describe("queued message file edits", () => { }); it.each([ + { + edit: "changed model", + originalReplyTo: null, + replyTo: null, + modelSelection: changedModelSelection, + result: "kept", + }, + { + edit: "unchanged model", + originalReplyTo: null, + replyTo: null, + modelSelection: originalModelSelection, + result: "clean", + }, { edit: "added reply", originalReplyTo: null, @@ -169,13 +189,25 @@ describe("queued message file edits", () => { }, ])( "reports $result for a queued edit with $edit", - ({ originalReplyTo, replyTo, originalText = "Original message", result }) => { + ({ originalReplyTo, replyTo, originalText = "Original message", modelSelection, result }) => { const store = useComposerDraftStore.getState(); store.setPrompt(editTarget, originalText); store.setReplyTo(editTarget, replyTo); + if (modelSelection) store.setModelSelection(editTarget, modelSelection, { explicit: true }); expect( - recoverQueuedMessageEdit({ editTarget, threadTarget, originalText, originalReplyTo }), + recoverQueuedMessageEdit({ + editTarget, + threadTarget, + originalText, + originalReplyTo, + originalModelSelection, + }), ).toBe(result); + if (result === "kept" && modelSelection) { + expect( + store.getComposerDraft(threadTarget)?.modelSelectionByProvider[modelSelection.instanceId], + ).toEqual(modelSelection); + } expect(store.getComposerDraft(editTarget)).toBeNull(); expect(store.getComposerDraft(threadTarget)).toEqual( result === "kept" ? expect.objectContaining({ prompt: originalText, replyTo }) : null, diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index ca58777dcb44a..4ea76f7000dcf 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -6,6 +6,7 @@ import type { ComposerContextId, ComposerContextRecord, EnvironmentId, + ModelSelection, OrchestrationMessageContext, ResponseContextRecord, } from "@t3tools/contracts"; @@ -94,12 +95,14 @@ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { } } store.clearComposerContent(target); + store.clearDraftThread(target); } export function recoverQueuedMessageEdit(input: { readonly editTarget: ComposerThreadTarget; readonly threadTarget: ComposerThreadTarget; readonly originalText: string; + readonly originalModelSelection?: ModelSelection; readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; readonly existingAttachmentContextIds?: ReadonlyArray; @@ -117,8 +120,14 @@ export function recoverQueuedMessageEdit(input: { draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt ? { ...draft, prompt: strippedPrompt } : draft; + const modelSelection = draft?.activeProvider + ? draft.modelSelectionByProvider[draft.activeProvider] + : undefined; + const modelChanged = + modelSelection !== undefined && !Equal.equals(modelSelection, input.originalModelSelection); const recovery = resolveQueuedEditExit({ editChanged: + modelChanged || input.removedExistingAttachment === true || !Equal.equals(draft?.replyTo ?? null, input.originalReplyTo) || (draft !== null && @@ -133,7 +142,13 @@ export function recoverQueuedMessageEdit(input: { store.setPrompt(input.editTarget, strippedPrompt); } store.moveComposerContent(input.editTarget, input.threadTarget); + if (modelChanged) + store.setModelSelection(input.threadTarget, modelSelection, { + explicit: true, + replaceOptions: true, + }); store.clearComposerContent(input.editTarget); + store.clearDraftThread(input.editTarget); } else { discardQueuedEditDraft(input.editTarget); } diff --git a/apps/web/src/components/chat/runtimeModeConfig.test.ts b/apps/web/src/components/chat/runtimeModeConfig.test.ts new file mode 100644 index 0000000000000..580fe7e43a268 --- /dev/null +++ b/apps/web/src/components/chat/runtimeModeConfig.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { draftSupportedRuntimeModes, resolveCompatibleRuntimeMode } from "./runtimeModeConfig"; + +describe("draftSupportedRuntimeModes", () => { + const supervisedOnly = { + instanceId: "fx", + supportedRuntimeModes: ["approval-required"], + } as const; + const noAuto = { + instanceId: "muse", + supportedRuntimeModes: ["approval-required", "full-access"], + } as const; + const everyMode = { instanceId: "codex" }; + const providers = [supervisedOnly, noAuto, everyMode]; + + it.each([ + { label: "one provider that supports it", selections: [supervisedOnly, noAuto] }, + { label: "a provider that reports no modes", selections: [supervisedOnly, everyMode] }, + ])("shows Full access when a multi-model draft includes $label", ({ selections }) => { + const modes = draftSupportedRuntimeModes( + supervisedOnly.supportedRuntimeModes, + selections, + providers, + ); + expect(resolveCompatibleRuntimeMode("full-access", modes).mode).toBe("full-access"); + }); + + it("falls back only when no selected provider can run the mode", () => { + const modes = draftSupportedRuntimeModes(undefined, [supervisedOnly, noAuto], providers); + expect(resolveCompatibleRuntimeMode("auto", modes).mode).toBe("approval-required"); + }); +}); diff --git a/apps/web/src/components/chat/runtimeModeConfig.ts b/apps/web/src/components/chat/runtimeModeConfig.ts index b4f77f2ca5d62..89655258ff935 100644 --- a/apps/web/src/components/chat/runtimeModeConfig.ts +++ b/apps/web/src/components/chat/runtimeModeConfig.ts @@ -51,6 +51,31 @@ export function resolveCompatibleRuntimeMode( return { modes, mode: modes.includes(runtimeMode) ? runtimeMode : (modes[0] ?? runtimeMode) }; } +/** + * The modes a draft's send can run in. A multi-model send gives every thread the draft's mode + * and only that thread's provider narrows it, so the composer offers what any of them supports. + */ +export function draftSupportedRuntimeModes( + activeProviderModes: ReadonlyArray | undefined, + multipleModelSelections: ReadonlyArray<{ readonly instanceId: string }> | null, + providers: ReadonlyArray<{ + readonly instanceId: string; + readonly supportedRuntimeModes?: ReadonlyArray | undefined; + }>, +) { + if (multipleModelSelections === null || multipleModelSelections.length === 0) { + return activeProviderModes; + } + const supported = multipleModelSelections.map( + (selection) => + providers.find((provider) => provider.instanceId === selection.instanceId) + ?.supportedRuntimeModes ?? [], + ); + // A provider that reports no modes supports them all. + if (supported.some((modes) => modes.length === 0)) return undefined; + return runtimeModeOptions.filter((mode) => supported.some((modes) => modes.includes(mode))); +} + export function resolveRuntimeModeOption( mode: RuntimeMode, resolve: MessageResolver = m, diff --git a/apps/web/src/components/chat/threadFindStore.test.ts b/apps/web/src/components/chat/threadFindStore.test.ts index 3819d8a4110f7..78f65d411ea76 100644 --- a/apps/web/src/components/chat/threadFindStore.test.ts +++ b/apps/web/src/components/chat/threadFindStore.test.ts @@ -2,6 +2,8 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; +import { hostRightPanel } from "../../rightPanelStore"; + import { attachThreadFindTimeline, closeThreadFind, @@ -78,6 +80,25 @@ describe("thread find store", () => { retainThreadFindForRoute({ modalPage: false, threadRef: null }); expect(useThreadFindStore.getState().threadKey).toBeNull(); }); + + it("keeps a side chat's find on its parent's route while the side chat is shown there", () => { + setup(); + const unhost = hostRightPanel(otherRef, threadRef); + openThreadFindOnQuery("env-1:thread-2", { query: "x" }); + retainThreadFindForRoute({ modalPage: true, threadRef: null }); + retainThreadFindForRoute({ modalPage: false, threadRef }); + expect(useThreadFindStore.getState()).toMatchObject({ + threadKey: "env-1:thread-2", + query: "x", + }); + // A route to the side chat itself shows it too, even while its pane is still hosted. + retainThreadFindForRoute({ modalPage: false, threadRef: otherRef }); + expect(useThreadFindStore.getState().threadKey).toBe("env-1:thread-2"); + + unhost(); + retainThreadFindForRoute({ modalPage: false, threadRef }); + expect(useThreadFindStore.getState().threadKey).toBeNull(); + }); }); describe("findForMessageMatch", () => { diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.ts index e3004c64adda0..260c0b089928c 100644 --- a/apps/web/src/components/chat/threadFindStore.ts +++ b/apps/web/src/components/chat/threadFindStore.ts @@ -3,7 +3,7 @@ import type { OrchestrationV2SearchThreadResult, ScopedThreadRef, } from "@t3tools/contracts"; -import { scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { findSearchTokenRanges, messagePhrase, @@ -11,6 +11,7 @@ import { } from "@t3tools/shared/paletteSearch"; import { create } from "zustand"; import type { ThemeAppearance } from "~/themePalette"; +import { rightPanelHostRef } from "../../rightPanelStore"; import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind"; export interface ThreadFindLocalSelection { @@ -148,9 +149,15 @@ export function closeThreadFind(): void { useThreadFindStore.setState(CLOSED_THREAD_FIND); } +/** Closes find if it is open in `threadKey`, leaving another thread's find alone. */ +export function closeThreadFindIn(threadKey: string): void { + if (useThreadFindStore.getState().threadKey === threadKey) closeThreadFind(); +} + /** * Find belongs to the thread it was opened in: a route showing anything else - * closes it. Settings and Usage draw over the thread, so they keep it. + * closes it. Settings and Usage draw over the thread, so they keep it, and a + * side chat is shown by its parent's route while its pane is open there. */ export function retainThreadFindForRoute(route: { readonly modalPage: boolean; @@ -158,8 +165,11 @@ export function retainThreadFindForRoute(route: { }): void { if (route.modalPage) return; const { threadKey } = useThreadFindStore.getState(); + if (threadKey === null) return; const shownKey = route.threadRef ? scopedThreadKey(route.threadRef) : null; - if (threadKey !== null && threadKey !== shownKey) closeThreadFind(); + const findRef = parseScopedThreadKey(threadKey); + const hostKey = findRef ? scopedThreadKey(rightPanelHostRef(findRef)) : threadKey; + if (threadKey !== shownKey && hostKey !== shownKey) closeThreadFind(); } /** Whether find is open in `thread`, as long as find is available there. */ diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 2069e32968ec4..3e71f70ba8590 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -75,8 +75,6 @@ export interface TimelineRowSharedState { onImageExpand: (preview: ExpandedImagePreview) => void; displayThreadKey?: string; onOpenToolDiff: ((target: ToolCallDiffTarget) => void) | undefined; - /** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */ - onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined; /** * Draws a published HTML visual. Unset, the row loads it from the environment; the guest page * loads it through its own route. diff --git a/apps/web/src/components/chat/useAssistantCitationTarget.ts b/apps/web/src/components/chat/useAssistantCitationTarget.ts index e8dd083e62463..3c3e39b9b6dc9 100644 --- a/apps/web/src/components/chat/useAssistantCitationTarget.ts +++ b/apps/web/src/components/chat/useAssistantCitationTarget.ts @@ -89,6 +89,7 @@ export function useAssistantCitationTarget({ setSettlement({ target, dismissed: true }); }; const onKeyDown = (event: KeyboardEvent) => { + if (event.isComposing || event.keyCode === 229) return; if (event.key === "Escape") { dismiss(false); } else if ( diff --git a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx index 61127d1a9d9c8..d3d1b06871e98 100644 --- a/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx +++ b/apps/web/src/components/chat/useChatShortcuts.browser.test.tsx @@ -3,6 +3,8 @@ import { useEffect, useState } from "react"; import { expect, it } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; +import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings"; +import { isPreviewFocused } from "~/lib/previewFocus"; import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey"; import { render } from "../../../test/render"; import type { ChatComposerHandle } from "./ChatComposer"; @@ -20,6 +22,11 @@ const shortcutContext = { const focusOnMount = (element: HTMLElement | null) => element?.focus(); +const ctrl = (key: string, command: KeybindingCommand, shiftKey = false) => ({ + command, + shortcut: { key, metaKey: false, ctrlKey: true, shiftKey, altKey: false, modKey: false }, +}); + // Stands in for the right panel's launcher, which needs the whole app around it. Like the // real one it takes focus, advertises its letters in `data-surface-launcher-keys`, and // claims one from its own window capture listener unless the key was already handled. @@ -47,10 +54,14 @@ function Launcher(props: { keys: string; received: string[] }) { // The chat's shortcut listener registers when the chat mounts, so a launcher that opens // later registers after it. Tests mount the chat first and add the launcher by rerendering. -function Chat(props: { composerKeys: string[]; launcher?: { keys: string; received: string[] } }) { +function Chat(props: { + composerKeys: string[]; + launcher?: { keys: string; received: string[] }; + finds?: string[]; +}) { useChatShortcuts({ enabled: true, - keybindings: [], + keybindings: [ctrl("f", "chat.find")], scriptKeybindings: [], getShortcutContext: () => shortcutContext, threadFindActive: false, @@ -65,7 +76,7 @@ function Chat(props: { composerKeys: string[]; launcher?: { keys: string; receiv }, branchToolbarRef: { current: null }, closeThreadFind: () => {}, - commands: {}, + commands: { "chat.find": () => void props.finds?.push("main") }, fallback: () => undefined, }); return props.launcher ? : null; @@ -134,17 +145,23 @@ it.each([ expect(received).toEqual(launcher); }); -const ctrlShift = (key: string, command: KeybindingCommand) => ({ - command, - shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, modKey: false }, -}); const sideChatKeybindings: ResolvedKeybindingsConfig = [ - ctrlShift("m", "modelPicker.toggle"), - ctrlShift("x", "thread.stop"), + ctrl("m", "modelPicker.toggle", true), + ctrl("x", "thread.stop", true), + // The default find rule, with ctrl for mod so it matches on every platform. + ...compileResolvedKeybindingsConfig([ + { key: "ctrl+f", command: "chat.find", when: "!terminalFocus && !previewFocus" }, + ]), ]; -// A side chat in the main chat's panel: no window listeners, only its composer's own chords. -function SideChat(props: { toggles: string[]; stops: string[] }) { +// A side chat in the main chat's right panel: no window listeners, only its pane's find and its +// composer's own chords. Passing `findCloses` opens its find. +function SideChat(props: { + toggles: string[]; + stops: string[]; + finds?: string[]; + findCloses?: string[]; +}) { const [composerElement, setComposerElement] = useState(null); useChatShortcuts({ enabled: false, @@ -152,22 +169,33 @@ function SideChat(props: { toggles: string[]; stops: string[] }) { composerElement, keybindings: sideChatKeybindings, scriptKeybindings: [], - getShortcutContext: () => shortcutContext, - threadFindActive: false, + getShortcutContext: () => ({ ...shortcutContext, previewFocus: isPreviewFocused() }), + threadFindActive: props.findCloses !== undefined, composerRef: { current: { toggleModelPicker: () => props.toggles.push("model"), } as Partial as ChatComposerHandle, }, branchToolbarRef: { current: null }, - closeThreadFind: () => {}, - commands: { "thread.stop": () => void props.stops.push("stop") }, + closeThreadFind: () => void props.findCloses?.push("side"), + commands: { + "thread.stop": () => void props.stops.push("stop"), + "chat.find": () => void props.finds?.push("side"), + }, fallback: () => undefined, }); return ( <> -
-