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/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs index 87313178cd152..5bebcb5202b91 100644 --- a/.github/scripts/workflow-credentials.test.cjs +++ b/.github/scripts/workflow-credentials.test.cjs @@ -13,6 +13,7 @@ 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"); @@ -200,6 +201,15 @@ test("the version override token covers this repository only", () => { 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( @@ -216,16 +226,122 @@ test("the Vite+ toolchain is cached before the job installs or runs project code 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, -); +const forkPreview = jobs("workflows/mobile-eas-preview-fork.yml"); +const forkPreviewScript = (id) => + new (Object.getPrototypeOf(async () => {}).constructor)( + "github", + "context", + "core", + steps(forkPreview.request) + .find((step) => step.startsWith(`id: ${id}\n`)) + .split(/^ {10}script: \|\n/m)[1] + .split(/^ {0,11}\S/m)[0] + .replace(/^ {12}/gm, ""), + ); +const consume = forkPreviewScript("consume"); +const pin = forkPreviewScript("pin"); +const forkPreviewEnvironment = /^ {10}ENVIRONMENT: (\S+)$/m.exec(forkPreview.request)[1]; + +test("a fork preview is requested by a job that reads no secrets and checks out nothing", () => { + const { request } = forkPreview; + assert.doesNotMatch(request, /secrets\.|actions\/checkout|^ {4}environment:/m); + assert.ok(!runsProjectCode(request), "request runs project code"); + assert.match(request, /^ {6}sha: \$\{\{ steps\.pin\.outputs\.sha \}\}$/m); + const pinStep = steps(request).find((step) => step.startsWith("id: pin\n")); + assert.match(pinStep, /^ {8}if: steps\.consume\.outputs\.consumed == 'true'$/m); +}); + +test("every fork preview job that reads a secret or runs the PR's code waits in the environment and builds the requested commit", () => { + const { request: _request, comment, ...gated } = forkPreview; + assert.deepEqual(Object.keys(gated), ["preview", "android-build", "ios-build"]); + for (const [name, block] of Object.entries(gated)) { + assert.match(block, /^ {4}needs: (?:request|\[request, preview\])$/m, name); + assert.ok( + block.includes(`\n environment:\n name: ${forkPreviewEnvironment}\n`), + `${name} waits in ${forkPreviewEnvironment}`, + ); + assert.doesNotMatch(block, /github\.event\.pull_request\.head/, name); + const refs = Array.from(block.matchAll(/^ {10}ref: (.+)$/gm), (match) => match[1]); + assert.deepEqual(refs, ["${{ needs.request.outputs.sha }}"], name); + const jobSteps = steps(block); + assert.match(jobSteps[0], /^name: Confirm the PR is still open\n/, name); + assert.ok(jobSteps.findIndex((step) => /secrets\.|actions\/checkout/.test(step)) > 0, name); + } + assert.match(gated.preview, /^ {4}if: needs\.request\.outputs\.sha != ''$/m); + assert.doesNotMatch(comment, /secrets\.|^ +ref: |github\.event\.pull_request\.head/m); +}); + +async function runPin(environment, sha = "a".repeat(40)) { + const outputs = {}; + const written = { comments: [], summary: "", failed: "" }; + await pin( + { + async request(route, params) { + assert.equal(route, "GET /repos/{owner}/{repo}/environments/{environment_name}"); + assert.equal(params.environment_name, forkPreviewEnvironment); + if (!environment) throw Object.assign(new Error("missing"), { status: 404 }); + return { data: environment }; + }, + rest: { issues: { createComment: async ({ body }) => written.comments.push(body) } }, + }, + { + repo: { owner: "example", repo: "app" }, + serverUrl: "https://github.example", + runId: 99, + payload: { sender: { login: "labeler" }, pull_request: { number: 7, head: { sha } } }, + }, + { + setFailed: (message) => (written.failed = message), + setOutput: (name, value) => (outputs[name] = value), + summary: { + addRaw(text) { + written.summary += text; + return this; + }, + async write() {}, + }, + }, + ); + return { outputs, ...written }; +} + +test("a fork preview request names the commit where the reviewer reads it", async () => { + process.env.ENVIRONMENT = forkPreviewEnvironment; + const sha = "a".repeat(40); + const reviewers = { type: "required_reviewers", reviewers: [{ type: "Team" }] }; + const named = await runPin({ protection_rules: [{ type: "branch_policy" }, reviewers] }); + assert.deepEqual(named.outputs, { sha }); + assert.equal(named.failed, ""); + assert.deepEqual(named.comments, [named.summary]); + assert.ok(named.summary.includes(`https://github.example/example/app/pull/7/commits/${sha}`)); + assert.ok(named.summary.includes("https://github.example/example/app/actions/runs/99")); + // Quoted, or YAML would end the title at the " #". + assert.match( + read("workflows/mobile-eas-preview-fork.yml"), + /^run-name: "\$\{\{ .*format\('Mobile preview of #\{0\} at \{1\}', github\.event\.pull_request\.number, github\.event\.pull_request\.head\.sha\) \|\| '' \}\}"$/m, + ); +}); + +test("a fork preview request builds nothing unless the environment has required reviewers", async () => { + process.env.ENVIRONMENT = forkPreviewEnvironment; + for (const environment of [ + undefined, + {}, + { protection_rules: [] }, + { protection_rules: [{ type: "branch_policy" }, { type: "wait_timer", wait_timer: 5 }] }, + { protection_rules: [{ type: "required_reviewers", reviewers: [] }] }, + ]) { + const refused = await runPin(environment); + assert.deepEqual([refused.outputs, refused.comments, refused.summary], [{}, [], ""]); + assert.match(refused.failed, /no required reviewers/); + } + const noCommit = await runPin( + { protection_rules: [{ type: "required_reviewers", reviewers: [{ type: "User" }] }] }, + "main", + ); + assert.deepEqual([noCommit.outputs, noCommit.comments], [{}, []]); + assert.match(noCommit.failed, /no head commit/); +}); async function runConsume(permission, removeStatus, removed = []) { const outputs = {}; @@ -300,3 +416,35 @@ test("a version override rewrites only the app version", () => { } 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/deploy-relay.yml b/.github/workflows/deploy-relay.yml index da779c2783d4c..df54074cd15ae 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: @@ -78,6 +80,8 @@ jobs: PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }} AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} + # Unset leaves the Clerk account-deletion webhook route off. + CLERK_WEBHOOK_SIGNING_SECRET: ${{ secrets.CLERK_WEBHOOK_SIGNING_SECRET }} APNS_PRIVATE_KEY: ${{ secrets.APNS_PRIVATE_KEY }} FCM_SERVICE_ACCOUNT: ${{ secrets.FCM_SERVICE_ACCOUNT }} T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }} 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 index a7774c24bd0af..d344daeb76718 100644 --- a/.github/workflows/mobile-eas-preview-build.yml +++ b/.github/workflows/mobile-eas-preview-build.yml @@ -24,6 +24,9 @@ on: 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 diff --git a/.github/workflows/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index c0081d9d4f5eb..a32d2bd98fbf4 100644 --- a/.github/workflows/mobile-eas-preview-fork.yml +++ b/.github/workflows/mobile-eas-preview-fork.yml @@ -1,11 +1,18 @@ name: Mobile EAS Preview (Fork) +run-name: "${{ github.event.label.name == '🚀 Mobile Continuous Deployment' && github.event.pull_request.head.repo.full_name != github.repository && format('Mobile preview of #{0} at {1}', github.event.pull_request.number, github.event.pull_request.head.sha) || '' }}" # EAS previews for fork PRs. This runs the PR's code with an Expo token: the -# app config and plugins run on this runner; both clients build on Blacksmith -# with preview signing credentials. The label is the maintainer's sign-off -# that they reviewed that code, so it covers exactly the commit it was applied -# to: this pins that commit and consumes the label before running anything. A -# later push deploys nothing until the label is applied again. +# app config and plugins run on a runner; both clients build on Blacksmith +# with preview signing credentials. So every job that does waits for an +# approval in the `mobile-preview-fork` environment on every run. +# +# The label only requests a build, and counts only from someone with write +# access. The `request` job consumes it, pins the PR's head commit from the +# label event, and names that commit in the run title, the job summary and a +# PR comment. It reads no secrets and checks out nothing. The approval is the +# sign-off that the named commit was reviewed: the jobs after it build that +# commit and no other. A later push deploys nothing until the label is applied +# again and that run is approved. # # Same-repo PRs deploy on every push while labeled, via mobile-eas-preview.yml. @@ -17,31 +24,17 @@ permissions: contents: read jobs: - preview: - name: EAS Preview + request: + name: Preview request if: >- github.event.pull_request.head.repo.full_name != github.repository && github.event.label.name == '🚀 Mobile Continuous Deployment' - runs-on: blacksmith-8vcpu-ubuntu-2404 - concurrency: - group: mobile-eas-preview-fork-${{ github.event.pull_request.number }} - cancel-in-progress: true + runs-on: blacksmith-2vcpu-ubuntu-2404 permissions: contents: read pull-requests: write outputs: - ios_group: ${{ steps.ios_update.outputs.group }} - ios_client: ${{ steps.ios_client.outputs.link }} - group: ${{ steps.update.outputs.group }} - client: ${{ steps.client.outputs.link }} - ios_build: ${{ steps.ios_client.outputs.build }} - ios_fingerprint: ${{ steps.ios_client.outputs.fingerprint }} - build: ${{ steps.client.outputs.build }} - fingerprint: ${{ steps.client.outputs.fingerprint }} - env: - APP_VARIANT: preview - NODE_OPTIONS: --max-old-space-size=8192 - MOBILE_VERSION_POLICY: fingerprint + sha: ${{ steps.pin.outputs.sha }} steps: # 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 @@ -76,9 +69,96 @@ jobs: } core.setOutput("consumed", String(authorized)); + # The review screen of a pull_request_target run shows the base branch, + # so the commit is named here, where the reviewer reads it before + # approving. The jobs below take it from this job's output. Nothing is + # requested unless the environment exists with required reviewers: a + # workflow that names a missing environment creates it without any. + - id: pin + name: Name the commit to build + if: steps.consume.outputs.consumed == 'true' + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + env: + ENVIRONMENT: mobile-preview-fork + with: + script: | + const name = process.env.ENVIRONMENT; + let rules = []; + try { + const { data } = await github.request("GET /repos/{owner}/{repo}/environments/{environment_name}", { + owner: context.repo.owner, + repo: context.repo.repo, + environment_name: name, + }); + rules = data.protection_rules ?? []; + } catch (error) { + if (error.status !== 404) throw error; + } + if (!rules.some((rule) => rule.type === "required_reviewers" && rule.reviewers?.length > 0)) { + core.setFailed(`The ${name} environment has no required reviewers. Nothing built.`); + return; + } + const pull = context.payload.pull_request; + const sha = pull.head.sha; + if (!/^[0-9a-f]{40}$/.test(sha)) { + core.setFailed("The label event carries no head commit. Nothing built."); + return; + } + const repository = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`; + const body = [ + `Mobile preview requested by ${context.payload.sender.login} for commit [\`${sha}\`](${repository}/pull/${pull.number}/commits/${sha}).`, + "", + `It builds after an approval in the \`${name}\` environment: [review this run](${repository}/actions/runs/${context.runId}). Approving builds exactly this commit; a later push needs the label again.`, + ].join("\n"); + await core.summary.addRaw(body, true).write(); + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: pull.number, + body, + }); + core.setOutput("sha", sha); + + preview: + name: EAS Preview + needs: request + if: needs.request.outputs.sha != '' + runs-on: blacksmith-8vcpu-ubuntu-2404 + environment: + name: mobile-preview-fork + concurrency: + group: mobile-eas-preview-fork-${{ github.event.pull_request.number }} + cancel-in-progress: true + permissions: + contents: read + pull-requests: read + outputs: + ios_group: ${{ steps.ios_update.outputs.group }} + ios_client: ${{ steps.ios_client.outputs.link }} + group: ${{ steps.update.outputs.group }} + client: ${{ steps.client.outputs.link }} + ios_build: ${{ steps.ios_client.outputs.build }} + ios_fingerprint: ${{ steps.ios_client.outputs.fingerprint }} + build: ${{ steps.client.outputs.build }} + fingerprint: ${{ steps.client.outputs.fingerprint }} + env: + APP_VARIANT: preview + NODE_OPTIONS: --max-old-space-size=8192 + MOBILE_VERSION_POLICY: fingerprint + steps: + - name: Confirm the PR is still open + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + }); + if (pull.state !== "open") core.setFailed(`PR #${pull.number} is no longer open; not building.`); + - id: expo-token name: Check for EXPO_PREVIEW_TOKEN - if: steps.consume.outputs.consumed == 'true' env: EXPO_TOKEN: ${{ secrets.EXPO_PREVIEW_TOKEN }} run: | @@ -89,14 +169,14 @@ jobs: echo "EXPO_PREVIEW_TOKEN is not set; skipping EAS preview." fi - # The head SHA from the label event, not the branch, so a push after the - # label cannot swap in unreviewed code. No credentials stay in .git for - # the PR's scripts to read. + # The commit the request job named, not the branch, so a push after the + # label builds nothing. No credentials stay in .git for the PR's scripts + # to read. - name: Checkout reviewed commit if: steps.expo-token.outputs.present == 'true' uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ needs.request.outputs.sha }} fetch-depth: 0 # No sparse-checkout: see mobile-eas-preview.yml. @@ -233,18 +313,21 @@ 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" - # The reviewed commit's Android client, built cold: no sticky disk, because PR + # Each client job waits for its own approval in the environment, once the + # preview job has finished. The reviewed commit's Android client, built cold: no sticky disk, because PR # code could leave Gradle or ccache state that trusted builds would restore, and # no build record tag, so nobody else is served an APK a fork's code built. android-build: name: Android preview client - needs: preview + needs: [request, preview] if: needs.preview.outputs.build == 'true' runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 60 + environment: + name: mobile-preview-fork permissions: contents: read - pull-requests: write + pull-requests: read outputs: client: ${{ steps.build.outputs.link }} env: @@ -255,10 +338,21 @@ jobs: # Phones only: emulators use the development client from the native-client cache. ORG_GRADLE_PROJECT_reactNativeArchitectures: armeabi-v7a,arm64-v8a steps: + - name: Confirm the PR is still open + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + }); + if (pull.state !== "open") core.setFailed(`PR #${pull.number} is no longer open; not building.`); + - name: Checkout reviewed commit uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ needs.request.outputs.sha }} fetch-depth: 0 # Scripts and actions come from main, not from the PR. @@ -302,13 +396,15 @@ jobs: ios-build: name: iOS preview client - needs: preview + needs: [request, preview] if: needs.preview.outputs.ios_build == 'true' runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 + environment: + name: mobile-preview-fork permissions: contents: read - pull-requests: write + pull-requests: read outputs: client: ${{ steps.build.outputs.link }} env: @@ -317,10 +413,21 @@ jobs: MOBILE_VERSION_POLICY: fingerprint FINGERPRINT: ${{ needs.preview.outputs.ios_fingerprint }} steps: + - name: Confirm the PR is still open + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0 + with: + script: | + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + }); + if (pull.state !== "open") core.setFailed(`PR #${pull.number} is no longer open; not building.`); + - name: Checkout reviewed commit uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ needs.request.outputs.sha }} fetch-depth: 0 # Scripts and actions come from main, not from the PR. @@ -364,7 +471,7 @@ jobs: comment: name: Mobile preview comment - needs: [preview, android-build, ios-build] + needs: [request, preview, android-build, ios-build] if: always() && !cancelled() && needs.preview.result == 'success' runs-on: blacksmith-2vcpu-ubuntu-2404 concurrency: @@ -383,7 +490,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} PR: ${{ github.event.pull_request.number }} - PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_HEAD_SHA: ${{ needs.request.outputs.sha }} ANDROID_FINGERPRINT: ${{ needs.preview.outputs.fingerprint }} ANDROID_GROUP: ${{ needs.preview.outputs.group }} ANDROID_CLIENT: ${{ needs.android-build.outputs.client || needs.preview.outputs.client }} diff --git a/.github/workflows/mobile-eas-preview.yml b/.github/workflows/mobile-eas-preview.yml index 5aeb32d647763..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 }} diff --git a/.github/workflows/mobile-eas-production-build.yml b/.github/workflows/mobile-eas-production-build.yml index 54289e4dc7e72..766b9cb7c4c5d 100644 --- a/.github/workflows/mobile-eas-production-build.yml +++ b/.github/workflows/mobile-eas-production-build.yml @@ -31,6 +31,9 @@ on: 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. diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index 0bfe62444d81b..249150ff0951b 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -70,6 +70,9 @@ on: - .github/workflows/mobile-eas-production.yml - .github/workflows/mobile-eas-production-build.yml +permissions: + contents: read + jobs: production: name: EAS ${{ inputs.profile || 'production' }} ${{ github.event_name == 'push' && 'auto' || inputs.mode }} 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/pr-size.yml b/.github/workflows/pr-size.yml index 45f5c9b9f7760..41e4ccecb024d 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -7,6 +7,13 @@ on: permissions: contents: read +# Run-level, not job-level: runs join the group when their event arrives, so a newer push +# always supersedes an older one. A job-level group is joined when the job starts, which +# let an older run's slower job cancel the newer head's job and label from a stale diff. +concurrency: + group: pr-size-${{ github.event.pull_request.number }} + cancel-in-progress: true + jobs: prepare-config: name: Prepare PR size config @@ -120,9 +127,6 @@ jobs: contents: read issues: read pull-requests: write - concurrency: - group: pr-size-${{ github.event.pull_request.number }} - cancel-in-progress: true steps: # This pull_request_target job may fetch untrusted PR commits only as passive # git data. Do not add dependency installs, build/test scripts, or cache diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml index eb53c07894025..c8b067e7637dd 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -14,8 +14,17 @@ on: permissions: contents: read - issues: write - pull-requests: write + +# Per-PR events supersede each other at the run level, in arrival order (a job-level group +# is joined when the job starts, so an older run's slower job could cancel the newer one). +# Other comments and pushes get a unique group so they never cancel a PR's run. +concurrency: + group: >- + ${{ (github.event_name == 'pull_request_target' || + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '/recheck-vouch'))) + && format('pr-vouch-run-{0}', github.event.pull_request.number || github.event.issue.number) + || format('pr-vouch-run-{0}', github.run_id) }} + cancel-in-progress: true jobs: collect-targets: @@ -25,6 +34,8 @@ jobs: github.event_name != 'issue_comment' || (github.event.issue.pull_request && contains(github.event.comment.body, '/recheck-vouch')) runs-on: ubuntu-24.04 + permissions: + pull-requests: read outputs: targets: ${{ steps.collect.outputs.targets }} steps: @@ -71,9 +82,9 @@ jobs: needs: collect-targets if: ${{ needs.collect-targets.outputs.targets != '[]' }} runs-on: ubuntu-24.04 - concurrency: - group: pr-vouch-${{ matrix.target.number }} - cancel-in-progress: true + permissions: + contents: read + pull-requests: write strategy: fail-fast: false matrix: 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/relay-preview.yml b/.github/workflows/relay-preview.yml index daec319087759..1204a527347ed 100644 --- a/.github/workflows/relay-preview.yml +++ b/.github/workflows/relay-preview.yml @@ -79,5 +79,7 @@ jobs: PLANETSCALE_API_TOKEN: ${{ secrets.PLANETSCALE_API_TOKEN }} AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} + # Unset leaves the Clerk account-deletion webhook route off. + CLERK_WEBHOOK_SIGNING_SECRET: ${{ secrets.CLERK_WEBHOOK_SIGNING_SECRET }} # Unset by default, so previews keep the T3 Chat link off. T3CHAT_LINK_SECRET: ${{ secrets.T3CHAT_LINK_SECRET }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 92ec860dbe33c..6fe82ebcb0069 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1471,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' }} @@ -1478,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 @@ -1508,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 @@ -1541,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 7d3f1efd57c13..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,6 +38,9 @@ jobs: (github.event.action != 'labeled' || github.event.label.name == 'preview:web') runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 + permissions: + contents: read + pull-requests: write steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 diff --git a/AGENTS.md b/AGENTS.md index 9340734f36500..a257e1a84a4f0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,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 8ffafdeba06c9..84420f44885ab 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,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 @@ -113,7 +113,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 @@ -137,4 +137,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/src/app/ClerkTokenStore.test.ts b/apps/desktop/src/app/ClerkTokenStore.test.ts deleted file mode 100644 index 13f6bbf758a4f..0000000000000 --- a/apps/desktop/src/app/ClerkTokenStore.test.ts +++ /dev/null @@ -1,151 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- These tests assert real POSIX modes on a temporary directory. -import * as NodeFS from "node:fs"; -import * as NodeOS from "node:os"; -import * as NodePath from "node:path"; -import { assert, describe, it } from "@effect/vitest"; - -import { openClerkTokenStorage, type ClerkTokenStorage } from "./ClerkTokenStore.ts"; - -// oxlint-disable-next-line t3code/no-global-process-runtime -- Unix mode bits are the assertion; Windows reports them through ACLs. -const describePosix = describe.skipIf(process.platform === "win32"); - -const modeOf = (path: string): number => NodeFS.statSync(path).mode & 0o777; - -function writeLoose(path: string, contents: string): void { - NodeFS.writeFileSync(path, contents, { mode: 0o666 }); - NodeFS.chmodSync(path, 0o666); -} - -async function withStateDir(run: (stateDir: string) => Promise | void): Promise { - const stateDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-clerk-tokens-")); - try { - await run(stateDir); - } finally { - NodeFS.rmSync(stateDir, { recursive: true, force: true }); - } -} - -const idleStorage = (): ClerkTokenStorage => ({ - getItem: async () => null, - setItem: async () => undefined, - removeItem: () => undefined, -}); - -describePosix("ClerkTokenStore", () => { - it("keeps clerk tokens at 0600 inside a 0700 directory", async () => { - await withStateDir(async (stateDir) => { - NodeFS.chmodSync(stateDir, 0o755); - const directory = NodePath.join(stateDir, "clerk"); - const legacyPath = NodePath.join(stateDir, "clerk-tokens.json"); - const tokenPath = NodePath.join(directory, "clerk-tokens.json"); - NodeFS.mkdirSync(directory, { mode: 0o755 }); - NodeFS.chmodSync(directory, 0o755); - writeLoose(legacyPath, '{"__clerk_client_jwt":"enc:existing"}\n'); - - const opened: string[] = []; - const storage = openClerkTokenStorage(stateDir, (cwd) => { - opened.push(cwd); - return { - getItem: async () => { - writeLoose(tokenPath, "from-get"); - return "from-get"; - }, - setItem: (_key, value) => { - writeLoose(tokenPath, value); - }, - removeItem: () => { - NodeFS.rmSync(tokenPath, { force: true }); - }, - }; - }); - - assert.deepEqual(opened, [directory]); - assert.equal(modeOf(stateDir), 0o755); - assert.equal(modeOf(directory), 0o700); - assert.equal(modeOf(tokenPath), 0o600); - assert.equal(NodeFS.existsSync(legacyPath), false); - assert.equal( - NodeFS.readFileSync(tokenPath, "utf8"), - '{"__clerk_client_jwt":"enc:existing"}\n', - ); - - assert.equal(await storage.getItem("client"), "from-get"); - assert.equal(modeOf(tokenPath), 0o600); - await storage.setItem("client", "from-set"); - assert.equal(modeOf(tokenPath), 0o600); - assert.equal(NodeFS.readFileSync(tokenPath, "utf8"), "from-set"); - storage.removeItem("client"); - assert.equal(NodeFS.existsSync(tokenPath), false); - - writeLoose(tokenPath, "kept"); - writeLoose(legacyPath, "stale"); - NodeFS.chmodSync(directory, 0o755); - openClerkTokenStorage(stateDir, () => idleStorage()); - assert.equal(modeOf(directory), 0o700); - assert.equal(modeOf(tokenPath), 0o600); - assert.equal(NodeFS.existsSync(legacyPath), false); - assert.equal(NodeFS.readFileSync(tokenPath, "utf8"), "kept"); - }); - }); - - it("resolves a relative state directory before opening storage", async () => { - await withStateDir(async (stateDir) => { - const relativeStateDir = NodePath.relative(process.cwd(), stateDir); - const opened: string[] = []; - openClerkTokenStorage(relativeStateDir, (directory) => { - opened.push(directory); - return idleStorage(); - }); - - const directory = NodePath.join(stateDir, "clerk"); - assert.equal(NodePath.isAbsolute(relativeStateDir), false); - assert.deepEqual(opened, [directory]); - assert.equal(modeOf(directory), 0o700); - }); - }); - - it("migrates relative state paths from Electron userData, not the working directory", async () => { - await withStateDir((stateDir) => { - const relativeStateDir = NodePath.relative(process.cwd(), stateDir); - const userData = NodePath.join( - stateDir, - "electron", - ...relativeStateDir.split(NodePath.sep).map(() => "profile"), - ); - const legacyStateDir = NodePath.join(userData, relativeStateDir); - const legacyPath = NodePath.join(legacyStateDir, "clerk-tokens.json"); - NodeFS.mkdirSync(legacyStateDir, { recursive: true }); - writeLoose(legacyPath, "existing-session"); - const unrelatedPath = NodePath.join(stateDir, "clerk-tokens.json"); - writeLoose(unrelatedPath, "not-the-electron-session"); - - openClerkTokenStorage(relativeStateDir, idleStorage, userData); - - const tokenPath = NodePath.join(stateDir, "clerk", "clerk-tokens.json"); - assert.equal(NodeFS.readFileSync(tokenPath, "utf8"), "existing-session"); - assert.equal(modeOf(tokenPath), 0o600); - assert.equal(NodeFS.existsSync(legacyPath), false); - assert.equal(NodeFS.readFileSync(unrelatedPath, "utf8"), "not-the-electron-session"); - }); - }); - - it("does not follow a symlinked clerk directory or token file", async () => { - await withStateDir(async (stateDir) => { - const outsideDirectory = NodePath.join(stateDir, "outside-dir"); - NodeFS.mkdirSync(outsideDirectory, { mode: 0o755 }); - NodeFS.chmodSync(outsideDirectory, 0o755); - NodeFS.symlinkSync(outsideDirectory, NodePath.join(stateDir, "clerk")); - - assert.throws(() => openClerkTokenStorage(stateDir, idleStorage), /must be a real directory/); - assert.equal(modeOf(outsideDirectory), 0o755); - NodeFS.unlinkSync(NodePath.join(stateDir, "clerk")); - - const outsideFile = NodePath.join(stateDir, "outside.json"); - NodeFS.writeFileSync(outsideFile, "secret", { mode: 0o644 }); - NodeFS.chmodSync(outsideFile, 0o644); - NodeFS.symlinkSync(outsideFile, NodePath.join(stateDir, "clerk-tokens.json")); - assert.throws(() => openClerkTokenStorage(stateDir, idleStorage), /must be a regular file/); - assert.equal(modeOf(outsideFile), 0o644); - }); - }); -}); diff --git a/apps/desktop/src/app/ClerkTokenStore.ts b/apps/desktop/src/app/ClerkTokenStore.ts deleted file mode 100644 index 005736c97cb38..0000000000000 --- a/apps/desktop/src/app/ClerkTokenStore.ts +++ /dev/null @@ -1,117 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- The Clerk bridge must lock the token file down before startup can yield to Electron's ready event. -import * as NodeFS from "node:fs"; -import * as NodePath from "node:path"; - -// electron-store chmods every write to 0666; the private directory protects tokens during writes. -const CLERK_TOKEN_DIRECTORY_MODE = 0o700; -const CLERK_TOKEN_FILE_MODE = 0o600; -const CLERK_TOKEN_DIRECTORY_NAME = "clerk"; -const CLERK_TOKEN_FILE_NAME = "clerk-tokens.json"; - -type Awaitable = T | Promise; - -export interface ClerkTokenStorage { - readonly getItem: (key: string) => Awaitable; - readonly setItem: (key: string, value: string) => Awaitable; - readonly removeItem: (key: string) => Awaitable; -} - -function isErrno(error: unknown, code: string): boolean { - return typeof error === "object" && error !== null && "code" in error && error.code === code; -} - -function lstatIfExists(path: string): NodeFS.Stats | undefined { - try { - return NodeFS.lstatSync(path); - } catch (error) { - if (isErrno(error, "ENOENT")) return undefined; - throw error; - } -} - -function assertRegularFile(path: string, stat: NodeFS.Stats): void { - if (stat.isSymbolicLink() || !stat.isFile()) { - throw new Error(`Clerk token file "${path}" must be a regular file.`); - } -} - -function restrictClerkTokenFile(path: string): void { - const stat = lstatIfExists(path); - if (stat === undefined) return; - assertRegularFile(path, stat); - if ((stat.mode & 0o777) === CLERK_TOKEN_FILE_MODE) return; - NodeFS.chmodSync(path, CLERK_TOKEN_FILE_MODE); -} - -function migrateLegacyClerkTokenFile(stateDir: string, directory: string): void { - const legacyPath = NodePath.join(stateDir, CLERK_TOKEN_FILE_NAME); - const tokenPath = NodePath.join(directory, CLERK_TOKEN_FILE_NAME); - const legacy = lstatIfExists(legacyPath); - if (legacy !== undefined) { - assertRegularFile(legacyPath, legacy); - NodeFS.chmodSync(legacyPath, CLERK_TOKEN_FILE_MODE); - } - - const destination = lstatIfExists(tokenPath); - if (destination === undefined) { - if (legacy === undefined) return; - try { - NodeFS.copyFileSync(legacyPath, tokenPath, NodeFS.constants.COPYFILE_EXCL); - NodeFS.chmodSync(tokenPath, CLERK_TOKEN_FILE_MODE); - NodeFS.unlinkSync(legacyPath); - } catch (error) { - if (!isErrno(error, "ENOENT")) throw error; - } - return; - } - - assertRegularFile(tokenPath, destination); - NodeFS.chmodSync(tokenPath, CLERK_TOKEN_FILE_MODE); - if (legacy === undefined) return; - try { - NodeFS.unlinkSync(legacyPath); - } catch (error) { - if (!isErrno(error, "ENOENT")) throw error; - } -} - -function restrictAfter(run: () => Awaitable, tighten: () => void): Awaitable { - let result: Awaitable; - try { - result = run(); - } catch (error) { - tighten(); - throw error; - } - if (result instanceof Promise) return result.finally(tighten); - tighten(); - return result; -} - -/** Opens Clerk token storage in a private directory and keeps the file at `0600`. */ -export function openClerkTokenStorage( - stateDir: string, - createStorage: (directory: string) => ClerkTokenStorage, - userDataPath = ".", -): ClerkTokenStorage { - const absoluteStateDir = NodePath.resolve(stateDir); - const directory = NodePath.join(absoluteStateDir, CLERK_TOKEN_DIRECTORY_NAME); - NodeFS.mkdirSync(directory, { recursive: true, mode: CLERK_TOKEN_DIRECTORY_MODE }); - const stat = NodeFS.lstatSync(directory); - if (stat.isSymbolicLink() || !stat.isDirectory()) { - throw new Error(`Clerk token directory "${directory}" must be a real directory.`); - } - NodeFS.chmodSync(directory, CLERK_TOKEN_DIRECTORY_MODE); - // electron-store rebases relative paths under Electron userData, not the working directory. - migrateLegacyClerkTokenFile(NodePath.resolve(userDataPath, stateDir), directory); - const tokenPath = NodePath.join(directory, CLERK_TOKEN_FILE_NAME); - restrictClerkTokenFile(tokenPath); - - const storage = createStorage(directory); - const tighten = () => restrictClerkTokenFile(tokenPath); - return { - getItem: (key) => restrictAfter(() => storage.getItem(key), tighten), - setItem: (key, value) => restrictAfter(() => storage.setItem(key, value), tighten), - removeItem: (key) => restrictAfter(() => storage.removeItem(key), tighten), - }; -} diff --git a/apps/desktop/src/app/DesktopClerk.test.ts b/apps/desktop/src/app/DesktopClerk.test.ts index de687d41a4e68..c17cb00869a3b 100644 --- a/apps/desktop/src/app/DesktopClerk.test.ts +++ b/apps/desktop/src/app/DesktopClerk.test.ts @@ -64,9 +64,10 @@ const layerDesktopClerk = ( copyText: () => Effect.void, }, listeners = new Map void>(), + stateDir = clerkStateDir, ) => { const environment = DesktopEnvironment.DesktopEnvironment.of({ - stateDir: clerkStateDir, + stateDir, isDevelopment, appDataDirectory: "/tmp/app-data", platform, @@ -170,10 +171,25 @@ describe("DesktopClerk", () => { assert.deepEqual(storageMock.mock.calls, [ [{ path: NodePath.join(NodePath.resolve(clerkStateDir), "clerk") }], ]); - assert.notStrictEqual(createClerkBridgeMock.mock.calls[0]?.[0]?.storage, storageAdapter); + assert.strictEqual(createClerkBridgeMock.mock.calls[0]?.[0]?.storage, storageAdapter); }, ); + it.effect("keeps Clerk tokens under a relative state directory instead of userData", () => { + storageMock.mockReturnValue(storageAdapter); + createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true }); + + return Effect.sync(() => { + assert.deepEqual(storageMock.mock.calls, [ + [{ path: NodePath.resolve("relative-state", "clerk") }], + ]); + }).pipe( + Effect.provide( + layerDesktopClerk(true, [], "darwin", undefined, undefined, undefined, "relative-state"), + ), + ); + }); + it.effect.each(["before configure", "after configure"] as const)( "reveals the running window when a second instance launches %s", (entry) => { diff --git a/apps/desktop/src/app/DesktopClerk.ts b/apps/desktop/src/app/DesktopClerk.ts index 207aa17739e59..e84dea47208e9 100644 --- a/apps/desktop/src/app/DesktopClerk.ts +++ b/apps/desktop/src/app/DesktopClerk.ts @@ -5,6 +5,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -21,7 +22,6 @@ import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as DesktopUserData from "./DesktopUserData.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; -import { openClerkTokenStorage } from "./ClerkTokenStore.ts"; import * as DesktopWebLinks from "./DesktopWebLinks.ts"; declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined; @@ -85,13 +85,9 @@ export const desktopClerkFrontendApiHostname = resolveDesktopClerkFrontendApiHos : __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__, ); -function createDesktopClerkBridge(stateDir: string, isDevelopment: boolean, userDataPath: string) { +function createDesktopClerkBridge(tokenDirectory: string, isDevelopment: boolean) { return createClerkBridge({ - storage: openClerkTokenStorage( - stateDir, - (directory) => storage({ path: directory }), - userDataPath, - ), + storage: storage({ path: tokenDirectory }), manageSingleInstanceLock: false, passkeys: true, renderer: { @@ -106,6 +102,7 @@ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const electronApp = yield* ElectronApp.ElectronApp; const shell = yield* ElectronShell.ElectronShell; + const path = yield* Path.Path; // Must not yield: the bridge registers a scheme Electron rejects once ready. const userDataPath = yield* DesktopUserData.resolveUserDataPath(environment); @@ -142,7 +139,10 @@ export const make = Effect.gen(function* () { yield* Effect.acquireRelease( Effect.try({ try: () => - createDesktopClerkBridge(environment.stateDir, environment.isDevelopment, userDataPath), + createDesktopClerkBridge( + path.resolve(environment.stateDir, "clerk"), + environment.isDevelopment, + ), catch: (cause) => new DesktopClerkBridgeInitializationError({ stateDir: environment.stateDir, diff --git a/apps/desktop/src/app/DesktopState.ts b/apps/desktop/src/app/DesktopState.ts index f869fd335ab07..39d3dabdf7864 100644 --- a/apps/desktop/src/app/DesktopState.ts +++ b/apps/desktop/src/app/DesktopState.ts @@ -3,6 +3,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Ref from "effect/Ref"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import type { DatabaseMigrationProgress } from "@t3tools/contracts"; import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts"; @@ -20,6 +21,7 @@ export class DesktopState extends Context.Service< // Set by DesktopUpdates.configure, which runs before the first backend start. readonly canInstallUpdates: Ref.Ref; readonly primaryBackendStartup: SubscriptionRef.SubscriptionRef; + readonly databaseMigrationProgress: Ref.Ref; } >()("@t3tools/desktop/app/DesktopState") {} @@ -28,6 +30,7 @@ const make = Effect.all({ quitting: Ref.make(false), canInstallUpdates: Ref.make(false), primaryBackendStartup: SubscriptionRef.make({ _tag: "Starting" }), + databaseMigrationProgress: Ref.make(null), }); export const layer = Layer.effect(DesktopState, make); 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 6300e347a125f..ea263cd0144f7 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -142,6 +142,9 @@ interface MakeInstanceInput { readonly onReady?: Effect.Effect; readonly onShutdown?: Effect.Effect; readonly onStateDirOwned?: Effect.Effect; + readonly onMigrationProgress?: ( + progress: { current: number; total: number } | null, + ) => Effect.Effect; readonly onStartupFailure?: ( failure: DesktopBackendManager.BackendStartupFailure, ) => Effect.Effect; @@ -205,6 +208,7 @@ function makeTestInstance(input: MakeInstanceInput) { ...(input.onStateDirOwned ? { onStateDirOwned: () => input.onStateDirOwned! } : {}), ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}), ...(input.onStartupFailure ? { onStartupFailure: input.onStartupFailure } : {}), + ...(input.onMigrationProgress ? { onMigrationProgress: input.onMigrationProgress } : {}), }); return instance.pipe(Effect.provide(layerServices)); @@ -253,6 +257,60 @@ 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(); @@ -764,7 +822,8 @@ describe("DesktopBackendManager", () => { "reports exit $code with the server output after $exits exits", ({ code, exits, managedPolicy }) => Effect.gen(function* () { - const message = "Error: Cannot find module 'zod/v4' in /Users/René"; + const message = `${DATABASE_MIGRATION_PROGRESS_MESSAGE} (1 of 3)\n progress: 1 of 3\nError: Cannot find module 'zod/v4' in /Users/René`; + const progress: Array<{ current: number; total: number } | null> = []; let exitCount = 0; const firstExit = yield* Deferred.make(); const reports = yield* Queue.unbounded<{ @@ -798,6 +857,10 @@ describe("DesktopBackendManager", () => { return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid); }, }, + onMigrationProgress: (value) => + Effect.sync(() => { + progress.push(value); + }), onStartupFailure: (failure) => Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid), }); @@ -810,13 +873,21 @@ describe("DesktopBackendManager", () => { assert.equal(failure.managedPolicy, managedPolicy); assert.isTrue(failure.output.endsWith(message)); assert.isTrue(failure.output.isWellFormed()); + assert.isTrue(progress.some((value) => value?.current === 1 && value.total === 3)); + assert.isNull(progress.at(-1)); }).pipe(Effect.provide(TestClock.layer())), ); it.effect("waits out a slow startup and reports one that never becomes ready", () => Effect.gen(function* () { const reports = yield* Queue.unbounded(); - const startInstance = (status: Ref.Ref, onReady?: Effect.Effect, stdout = "") => + const progress: Array<{ current: number; total: number } | null> = []; + const outputProcessed = yield* Queue.unbounded(); + const startInstance = ( + status: Ref.Ref, + onReady?: Effect.Effect, + stdout: string | Stream.Stream = "", + ) => makeTestInstance({ config: pollingConfig, spawnerLayer: Layer.succeed( @@ -825,7 +896,10 @@ describe("DesktopBackendManager", () => { Effect.succeed( makeProcess({ exitCode: Effect.never, - stdout: Stream.make(new TextEncoder().encode(stdout)), + stdout: + typeof stdout === "string" + ? Stream.make(new TextEncoder().encode(stdout)) + : stdout, }), ), ), @@ -833,6 +907,13 @@ describe("DesktopBackendManager", () => { httpClientLayer: layerHttpClient((request) => Ref.get(status).pipe(Effect.map((code) => responseForRequest(request, code))), ), + backendOutputLog: { + writeOutputChunk: () => Queue.offer(outputProcessed, undefined).pipe(Effect.asVoid), + }, + onMigrationProgress: (value) => + Effect.sync(() => { + progress.push(value); + }), onStartupFailure: (failure) => Queue.offer(reports, failure).pipe(Effect.asVoid), ...(onReady ? { onReady } : {}), }).pipe(Effect.tap((instance) => instance.start)); @@ -840,6 +921,7 @@ describe("DesktopBackendManager", () => { const slowStatus = yield* Ref.make(503); const ready = yield* Deferred.make(); yield* startInstance(slowStatus, Deferred.succeed(ready, undefined).pipe(Effect.asVoid)); + yield* Queue.take(outputProcessed); yield* TestClock.adjust(Duration.seconds(66)); yield* Ref.set(slowStatus, 200); yield* TestClock.adjust(Duration.millis(100)); @@ -848,22 +930,56 @@ describe("DesktopBackendManager", () => { const migratingStatus = yield* Ref.make(503); const migrated = yield* Deferred.make(); + const output = yield* Queue.unbounded(); + const writeOutput = (text: string) => + Queue.offer(output, new TextEncoder().encode(text)).pipe( + Effect.andThen(Queue.take(outputProcessed)), + ); yield* startInstance( migratingStatus, Deferred.succeed(migrated, undefined).pipe(Effect.asVoid), + Stream.fromQueue(output), + ); + yield* writeOutput(`INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n`); + yield* TestClock.adjust(Duration.minutes(3)); + assert.isNull(progress.at(-1)); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + yield* writeOutput( // Enough progress lines that the start line scrolls out of the output tail. `INFO ${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n` + Array.from( { length: 80 }, (_, index) => - `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} migration=${index}_Migration progress="${index + 1} of 80"\n`, + `INFO ${DATABASE_MIGRATION_PROGRESS_MESSAGE} (${index + 1} of 80)\n migration: ${index}_Migration\n progress: ${index + 1} of 80\n`, ).join(""), ); yield* TestClock.adjust(Duration.minutes(10)); + assert.deepStrictEqual(progress.at(-1), { current: 80, total: 80 }); assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + const noise = "unrelated backend output\n".repeat(400); + yield* writeOutput(noise); + assert.deepStrictEqual(progress.at(-1), { current: 80, total: 80 }); + yield* writeOutput(noise); + assert.deepStrictEqual(progress.at(-1), { current: 80, total: 80 }); + yield* TestClock.adjust(Duration.minutes(3)); + assert.isTrue(Option.isNone(yield* Queue.poll(reports))); + yield* writeOutput(`${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${noise}`); + assert.isNull(progress.at(-1)); + yield* writeOutput(`${DATABASE_MIGRATION_PROGRESS_MESSAGE} (1 of 2)\n${noise}`); + assert.deepStrictEqual(progress.at(-1), { current: 1, total: 2 }); + yield* writeOutput(DATABASE_MIGRATIONS_FINISHED_MESSAGE.slice(0, 12)); + yield* writeOutput(`${DATABASE_MIGRATIONS_FINISHED_MESSAGE.slice(12)}\n${noise}`); + assert.isNull(progress.at(-1)); + yield* writeOutput(noise); + assert.isNull(progress.at(-1)); + yield* writeOutput( + `${DATABASE_MIGRATIONS_STARTED_MESSAGE}\n${DATABASE_MIGRATION_PROGRESS_MESSAGE} (1 of 1)\n`, + ); + assert.deepStrictEqual(progress.at(-1), { current: 1, total: 1 }); yield* Ref.set(migratingStatus, 200); yield* TestClock.adjust(Duration.millis(100)); yield* Deferred.await(migrated); + assert.isNull(progress.at(-1)); yield* startInstance( yield* Ref.make(503), @@ -874,6 +990,7 @@ describe("DesktopBackendManager", () => { assert.isTrue(Option.isNone(yield* Queue.poll(reports))); yield* TestClock.adjust(Duration.seconds(1)); const failure = yield* Queue.take(reports); + assert.isNull(progress.at(-1)); assert.equal(failure.reason, "The server started but did not become ready in time."); }).pipe(Effect.provide(TestClock.layer())), ); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index baf2e073f506f..91bdd2b33e13b 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -25,8 +25,12 @@ import { PRIMARY_LOCAL_ENVIRONMENT_ID, DesktopTelemetryControlMessage, type DesktopTelemetryControlMessage as DesktopTelemetryControlMessageValue, + type DatabaseMigrationProgress, } from "@t3tools/contracts"; -import { isRunningDatabaseMigrations } from "@t3tools/shared/databaseMigrationLog"; +import { + databaseMigrationProgress, + isRunningDatabaseMigrations, +} from "@t3tools/shared/databaseMigrationLog"; import { waitForHttpReady as waitForHttpReadyShared } from "@t3tools/shared/httpReadiness"; import * as DesktopObservability from "../app/DesktopObservability.ts"; @@ -72,6 +76,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 +92,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; @@ -265,6 +277,9 @@ export interface BackendInstanceSpec { readonly onStateDirOwned?: () => Effect.Effect; /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */ readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect; + readonly onMigrationProgress?: ( + progress: DatabaseMigrationProgress | null, + ) => Effect.Effect; } interface ActiveBackendRun { @@ -355,8 +370,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 +387,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 +411,7 @@ const pollHttpReady = ( cause, }), }); -}; +}); function drainBackendOutput( context: BackendProcessContext & { readonly pid: number }, @@ -607,10 +630,16 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( }; 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. + // 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 }) + ? waitForHttpReady({ + ...readinessContext, + timeout: readinessTimeout, + ...(options.readinessProbe === undefined + ? {} + : { readinessProbe: options.readinessProbe }), + }) : Deferred.await(serverReady).pipe( Effect.timeoutOrElse({ duration: readinessTimeout, @@ -715,6 +744,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( const state = yield* SubscriptionRef.make(initialState); const mutex = yield* Semaphore.make(1); const outputTail = yield* Ref.make(""); + const migrationProgress = yield* Ref.make(null); // One streaming decoder per stream keeps UTF-8 characters split across chunks intact. const makeOutputDecoders = () => ({ stdout: new TextDecoder(), stderr: new TextDecoder() }); let outputDecoders = makeOutputDecoders(); @@ -941,6 +971,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( ); if (isCurrentRun) { + yield* Ref.set(migrationProgress, null); + yield* spec.onMigrationProgress?.(null) ?? Effect.void; yield* desktopTelemetryPublisher.removeControlSource(spec.id); if (Option.isSome(pid)) { if (exitObserved && !stopRequested) { @@ -985,6 +1017,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( pid: Option.some(pid), })); yield* Ref.set(outputTail, ""); + yield* Ref.set(migrationProgress, null); + yield* spec.onMigrationProgress?.(null) ?? Effect.void; outputDecoders = makeOutputDecoders(); yield* backendOutputLog.beginSession({ details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`, @@ -1015,6 +1049,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( return; } + yield* Ref.set(migrationProgress, null); + yield* spec.onMigrationProgress?.(null) ?? Effect.void; yield* spec.onReady?.(config.value.httpBaseUrl, pid) ?? Effect.void; if ( config.value.runningDistro !== undefined && @@ -1029,7 +1065,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( }), onReadinessFailure: Effect.fn("desktop.backendInstance.onReadinessFailure")( function* (error) { - if (isRunningDatabaseMigrations(yield* Ref.get(outputTail))) { + if ( + (yield* Ref.get(migrationProgress)) !== null || + isRunningDatabaseMigrations(yield* Ref.get(outputTail)) + ) { yield* logInstanceWarning("backend is still migrating its database; waiting", { error: error.message, }); @@ -1045,12 +1084,31 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( }, ), onOutput: (streamName, chunk) => - Ref.update(outputTail, (tail) => - // A cut through a surrogate pair would make encodeURIComponent throw when rendering. - (tail + outputDecoders[streamName].decode(chunk, { stream: true })) - .slice(-STARTUP_FAILURE_OUTPUT_CHARS) - .toWellFormed(), - ).pipe(Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk))), + Ref.modify(outputTail, (tail) => { + const output = tail + outputDecoders[streamName].decode(chunk, { stream: true }); + return [ + output, + // A cut through a surrogate pair would make encodeURIComponent throw when rendering. + output.slice(-STARTUP_FAILURE_OUTPUT_CHARS).toWellFormed(), + ]; + }).pipe( + Effect.flatMap((output) => + Effect.gen(function* () { + const latest = yield* SubscriptionRef.get(state); + if ( + !latest.ready && + Option.isSome(latest.active) && + latest.active.value.id === runId + ) { + const progress = yield* Ref.updateAndGet(migrationProgress, (previous) => + databaseMigrationProgress(output, previous), + ); + yield* spec.onMigrationProgress?.(progress) ?? Effect.void; + } + }), + ), + Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk)), + ), }).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(HttpClient.HttpClient, httpClient), diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.ts index 7af3b0d21d0cf..4df80d8f7970e 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.ts @@ -6,6 +6,7 @@ import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Ref from "effect/Ref"; import * as Exit from "effect/Exit"; import * as FiberHandle from "effect/FiberHandle"; import * as Layer from "effect/Layer"; @@ -150,7 +151,7 @@ export const layer = Layer.effect( const electronDialog = yield* ElectronDialog.ElectronDialog; const electronApp = yield* ElectronApp.ElectronApp; const appSettings = yield* DesktopAppSettings.DesktopAppSettings; - const { primaryBackendStartup } = yield* DesktopState.DesktopState; + const { primaryBackendStartup, databaseMigrationProgress } = yield* DesktopState.DesktopState; const recovery = yield* makeRecovery; // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends. const layerScope = yield* Scope.Scope; @@ -276,6 +277,7 @@ export const layer = Layer.effect( ), onStartupFailure: (failure) => SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }), + onMigrationProgress: (progress) => Ref.set(databaseMigrationProgress, progress), onShutdown: () => FiberHandle.clear(updateMarkerWait).pipe( Effect.andThen(desktopWindow.handleBackendNotReady), diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 8e39e7585f60d..5f9a0fe9ee9ab 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "Keine vertrauenswürdige Stelle hat dieses Zertifikat ausgestellt.", "cf346dcfb658d4d3": "Dieses Zertifikat gilt nicht für diese Adresse.", "20665d9b0c7c3e52": "Dieses Zertifikat ist abgelaufen oder noch nicht gültig.", + "e632aac04674913c": "{origin} möchte deine Kamera und dein Mikrofon verwenden", + "379c230d24c9b5c5": "{origin} möchte dein Mikrofon verwenden", + "576ac67fdb145936": "{origin} möchte deine Kamera verwenden", + "d8d5fbd2529b6bd3": "macOS hat T3 Code den Zugriff auf deine Kamera und dein Mikrofon verweigert", + "65dff766a75b43d5": "macOS hat T3 Code den Zugriff auf dein Mikrofon verweigert", + "39e3d7326db9af25": "macOS hat T3 Code den Zugriff auf deine Kamera verweigert", "565970a378986341": "Öffnen", "00ad8aeed0a6c461": "Abbrechen", "2107cc3e7c4ac833": "Diesen {protocol}-Link öffnen?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Blockieren", "709219ff9ff49a4f": "{origin} möchte deinen Standort erfahren", "8fc0b116123fb50b": "{origin} möchte in die Zwischenablage kopierte Texte und Bilder sehen", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "Erlaube T3 Code unter Systemeinstellungen › Datenschutz & Sicherheit und starte T3 Code dann neu.", "c0f756221736393f": "Vorschau · {title}", "6994444f4fec4070": "Browservorschau", "49de6209699eb616": "Unbenannter Passkey", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Du bist auf dem neuesten Stand!", "c6399b55619e2f67": "T3 Code {version} ist derzeit die neueste verfügbare Version.", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "Update verfügbar", "d3104b65052b993b": "Eine neue Version von T3 Code ist verfügbar.", "35fff5a1cd1d6473": "T3 Code {version} ist verfügbar.", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 9a07ef060cbc9..bb88ca0fcf5d8 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "No trusted authority issued this certificate.", "cf346dcfb658d4d3": "This certificate is not for this address.", "20665d9b0c7c3e52": "This certificate has expired or is not valid yet.", + "e632aac04674913c": "{origin} wants to use your camera and microphone", + "379c230d24c9b5c5": "{origin} wants to use your microphone", + "576ac67fdb145936": "{origin} wants to use your camera", + "d8d5fbd2529b6bd3": "macOS blocked T3 Code from using your camera and microphone", + "65dff766a75b43d5": "macOS blocked T3 Code from using your microphone", + "39e3d7326db9af25": "macOS blocked T3 Code from using your camera", "565970a378986341": "Open", "00ad8aeed0a6c461": "Cancel", "2107cc3e7c4ac833": "Open this {protocol} link?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Block", "709219ff9ff49a4f": "{origin} wants to know your location", "8fc0b116123fb50b": "{origin} wants to see text and images copied to the clipboard", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "Allow T3 Code in System Settings › Privacy & Security, then restart T3 Code.", "c0f756221736393f": "Preview · {title}", "6994444f4fec4070": "Browser preview", "49de6209699eb616": "Unnamed passkey", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "You're up to date!", "c6399b55619e2f67": "T3 Code {version} is currently the newest version available.", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "Update available", "d3104b65052b993b": "A new version of T3 Code is available.", "35fff5a1cd1d6473": "T3 Code {version} is available.", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index f891e9eaf850b..07527e73b3ec6 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "Ninguna autoridad de confianza emitió este certificado.", "cf346dcfb658d4d3": "Este certificado no es para esta dirección.", "20665d9b0c7c3e52": "Este certificado ha caducado o aún no es válido.", + "e632aac04674913c": "{origin} quiere usar tu cámara y tu micrófono", + "379c230d24c9b5c5": "{origin} quiere usar tu micrófono", + "576ac67fdb145936": "{origin} quiere usar tu cámara", + "d8d5fbd2529b6bd3": "macOS ha impedido que T3 Code use tu cámara y tu micrófono", + "65dff766a75b43d5": "macOS ha impedido que T3 Code use tu micrófono", + "39e3d7326db9af25": "macOS ha impedido que T3 Code use tu cámara", "565970a378986341": "Abrir", "00ad8aeed0a6c461": "Cancelar", "2107cc3e7c4ac833": "¿Abrir este enlace {protocol}?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Bloquear", "709219ff9ff49a4f": "{origin} quiere conocer tu ubicación", "8fc0b116123fb50b": "{origin} quiere ver el texto y las imágenes copiados al portapapeles", + "b6e5b31255e011c5": "Aceptar", + "fb7c135eaced773b": "Permite T3 Code en Ajustes del Sistema › Privacidad y seguridad y, después, reinicia T3 Code.", "c0f756221736393f": "Vista previa · {title}", "6994444f4fec4070": "Vista previa del navegador", "49de6209699eb616": "Llave de acceso sin nombre", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Estable", "1f12213f4d809e89": "¡Estás al día!", "c6399b55619e2f67": "T3 Code {version} es la versión más reciente disponible.", - "b6e5b31255e011c5": "Aceptar", "2ee2077700686fbb": "Actualización disponible", "d3104b65052b993b": "Hay una nueva versión de T3 Code disponible.", "35fff5a1cd1d6473": "T3 Code {version} está disponible.", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 0bb5a47518581..2b6c643738266 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "Aucune autorité de confiance n’a émis ce certificat.", "cf346dcfb658d4d3": "Ce certificat ne correspond pas à cette adresse.", "20665d9b0c7c3e52": "Ce certificat a expiré ou n’est pas encore valide.", + "e632aac04674913c": "{origin} veut utiliser votre caméra et votre micro", + "379c230d24c9b5c5": "{origin} veut utiliser votre micro", + "576ac67fdb145936": "{origin} veut utiliser votre caméra", + "d8d5fbd2529b6bd3": "macOS a empêché T3 Code d’utiliser votre caméra et votre micro", + "65dff766a75b43d5": "macOS a empêché T3 Code d’utiliser votre micro", + "39e3d7326db9af25": "macOS a empêché T3 Code d’utiliser votre caméra", "565970a378986341": "Ouvrir", "00ad8aeed0a6c461": "Annuler", "2107cc3e7c4ac833": "Ouvrir ce lien {protocol} ?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Bloquer", "709219ff9ff49a4f": "{origin} souhaite connaître votre position", "8fc0b116123fb50b": "{origin} veut voir le texte et les images copiés dans le presse-papiers", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "Autorisez T3 Code dans Réglages Système › Confidentialité et sécurité, puis redémarrez T3 Code.", "c0f756221736393f": "Aperçu · {title}", "6994444f4fec4070": "Aperçu du navigateur", "49de6209699eb616": "Clé d’accès sans nom", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Vous êtes à jour !", "c6399b55619e2f67": "T3 Code {version} est actuellement la version la plus récente.", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "Mise à jour disponible", "d3104b65052b993b": "Une nouvelle version de T3 Code est disponible.", "35fff5a1cd1d6473": "T3 Code {version} est disponible.", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index df89efe466261..9e41de4072e12 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "この証明書は信頼された認証局によって発行されていません。", "cf346dcfb658d4d3": "この証明書はこのアドレス用ではありません。", "20665d9b0c7c3e52": "この証明書は期限切れか、まだ有効になっていません。", + "e632aac04674913c": "{origin} がカメラとマイクの使用を求めています", + "379c230d24c9b5c5": "{origin} がマイクの使用を求めています", + "576ac67fdb145936": "{origin} がカメラの使用を求めています", + "d8d5fbd2529b6bd3": "macOS により T3 Code のカメラとマイクの使用がブロックされました", + "65dff766a75b43d5": "macOS により T3 Code のマイクの使用がブロックされました", + "39e3d7326db9af25": "macOS により T3 Code のカメラの使用がブロックされました", "565970a378986341": "開く", "00ad8aeed0a6c461": "キャンセル", "2107cc3e7c4ac833": "この {protocol} リンクを開きますか?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "ブロック", "709219ff9ff49a4f": "{origin} が位置情報へのアクセスを求めています", "8fc0b116123fb50b": "{origin} がクリップボードにコピーされたテキストと画像の表示を求めています", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "システム設定 › プライバシーとセキュリティで T3 Code を許可してから、T3 Code を再起動してください。", "c0f756221736393f": "プレビュー · {title}", "6994444f4fec4070": "ブラウザープレビュー", "49de6209699eb616": "名前のないパスキー", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "安定版", "1f12213f4d809e89": "最新の状態です", "c6399b55619e2f67": "T3 Code {version} が現在利用できる最新バージョンです。", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "更新があります", "d3104b65052b993b": "T3 Code の新しいバージョンを利用できます。", "35fff5a1cd1d6473": "T3 Code {version} を利用できます。", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index 566724b9b91c1..5ed1d58f7c360 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "신뢰할 수 있는 기관에서 발급한 인증서가 아닙니다.", "cf346dcfb658d4d3": "이 주소용 인증서가 아닙니다.", "20665d9b0c7c3e52": "이 인증서는 만료되었거나 아직 유효하지 않습니다.", + "e632aac04674913c": "{origin}에서 카메라와 마이크를 사용하려고 합니다", + "379c230d24c9b5c5": "{origin}에서 마이크를 사용하려고 합니다", + "576ac67fdb145936": "{origin}에서 카메라를 사용하려고 합니다", + "d8d5fbd2529b6bd3": "macOS가 T3 Code의 카메라 및 마이크 사용을 차단했습니다", + "65dff766a75b43d5": "macOS가 T3 Code의 마이크 사용을 차단했습니다", + "39e3d7326db9af25": "macOS가 T3 Code의 카메라 사용을 차단했습니다", "565970a378986341": "열기", "00ad8aeed0a6c461": "취소", "2107cc3e7c4ac833": "이 {protocol} 링크를 열까요?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "차단", "709219ff9ff49a4f": "{origin}에서 위치 정보에 접근하려고 합니다", "8fc0b116123fb50b": "{origin}에서 클립보드에 복사된 텍스트와 이미지를 보려고 합니다", + "b6e5b31255e011c5": "확인", + "fb7c135eaced773b": "시스템 설정 › 개인정보 보호 및 보안에서 T3 Code를 허용한 다음 T3 Code를 다시 시작하세요.", "c0f756221736393f": "미리 보기 · {title}", "6994444f4fec4070": "브라우저 미리 보기", "49de6209699eb616": "이름 없는 패스키", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "최신 버전입니다!", "c6399b55619e2f67": "T3 Code {version}이(가) 현재 사용 가능한 최신 버전입니다.", - "b6e5b31255e011c5": "확인", "2ee2077700686fbb": "업데이트 사용 가능", "d3104b65052b993b": "새 버전의 T3 Code를 사용할 수 있습니다.", "35fff5a1cd1d6473": "T3 Code {version}을(를) 사용할 수 있습니다.", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 67f4eefd1c9ec..5768088235dde 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "Nenhuma autoridade confiável emitiu este certificado.", "cf346dcfb658d4d3": "Este certificado não é para este endereço.", "20665d9b0c7c3e52": "Este certificado expirou ou ainda não é válido.", + "e632aac04674913c": "{origin} quer usar sua câmera e seu microfone", + "379c230d24c9b5c5": "{origin} quer usar seu microfone", + "576ac67fdb145936": "{origin} quer usar sua câmera", + "d8d5fbd2529b6bd3": "O macOS impediu o T3 Code de usar sua câmera e seu microfone", + "65dff766a75b43d5": "O macOS impediu o T3 Code de usar seu microfone", + "39e3d7326db9af25": "O macOS impediu o T3 Code de usar sua câmera", "565970a378986341": "Abrir", "00ad8aeed0a6c461": "Cancelar", "2107cc3e7c4ac833": "Abrir este link {protocol}?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Bloquear", "709219ff9ff49a4f": "{origin} quer saber sua localização", "8fc0b116123fb50b": "{origin} quer ver textos e imagens copiados para a área de transferência", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "Permita o T3 Code em Ajustes do Sistema › Privacidade e Segurança e reinicie o T3 Code.", "c0f756221736393f": "Pré-visualização · {title}", "6994444f4fec4070": "Pré-visualização do navegador", "49de6209699eb616": "Chave de acesso sem nome", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Estável", "1f12213f4d809e89": "Você está atualizado!", "c6399b55619e2f67": "O T3 Code {version} é a versão mais recente disponível.", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "Atualização disponível", "d3104b65052b993b": "Há uma nova versão do T3 Code disponível.", "35fff5a1cd1d6473": "O T3 Code {version} está disponível.", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 46364dfabe488..97d7b3b07b7ce 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "Этот сертификат выдан недоверенным центром.", "cf346dcfb658d4d3": "Этот сертификат выдан не для этого адреса.", "20665d9b0c7c3e52": "Срок действия этого сертификата истёк или ещё не начался.", + "e632aac04674913c": "{origin} хочет использовать камеру и микрофон", + "379c230d24c9b5c5": "{origin} хочет использовать микрофон", + "576ac67fdb145936": "{origin} хочет использовать камеру", + "d8d5fbd2529b6bd3": "macOS запретила T3 Code использовать камеру и микрофон", + "65dff766a75b43d5": "macOS запретила T3 Code использовать микрофон", + "39e3d7326db9af25": "macOS запретила T3 Code использовать камеру", "565970a378986341": "Открыть", "00ad8aeed0a6c461": "Отмена", "2107cc3e7c4ac833": "Открыть эту ссылку {protocol}?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Блокировать", "709219ff9ff49a4f": "{origin} запрашивает ваше местоположение", "8fc0b116123fb50b": "{origin} хочет видеть текст и изображения, скопированные в буфер обмена", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "Разрешите доступ для T3 Code в разделе Системные настройки › Конфиденциальность и безопасность, затем перезапустите T3 Code.", "c0f756221736393f": "Предпросмотр · {title}", "6994444f4fec4070": "Предпросмотр в браузере", "49de6209699eb616": "Безымянный ключ доступа", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Стабильный", "1f12213f4d809e89": "У вас последняя версия!", "c6399b55619e2f67": "T3 Code {version} — новейшая доступная версия.", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "Доступно обновление", "d3104b65052b993b": "Доступна новая версия T3 Code.", "35fff5a1cd1d6473": "Доступна версия T3 Code {version}.", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index 67bcaf6a380aa..f0e6533731f4b 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "Ingen betrodd utfärdare utfärdade det här certifikatet.", "cf346dcfb658d4d3": "Det här certifikatet gäller inte den här adressen.", "20665d9b0c7c3e52": "Det här certifikatet har gått ut eller är inte giltigt än.", + "e632aac04674913c": "{origin} vill använda din kamera och mikrofon", + "379c230d24c9b5c5": "{origin} vill använda din mikrofon", + "576ac67fdb145936": "{origin} vill använda din kamera", + "d8d5fbd2529b6bd3": "macOS har blockerat T3 Code från att använda din kamera och mikrofon", + "65dff766a75b43d5": "macOS har blockerat T3 Code från att använda din mikrofon", + "39e3d7326db9af25": "macOS har blockerat T3 Code från att använda din kamera", "565970a378986341": "Öppna", "00ad8aeed0a6c461": "Avbryt", "2107cc3e7c4ac833": "Öppna den här {protocol}-länken?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "Blockera", "709219ff9ff49a4f": "{origin} vill veta var du befinner dig", "8fc0b116123fb50b": "{origin} vill se text och bilder som kopierats till urklipp", + "b6e5b31255e011c5": "OK", + "fb7c135eaced773b": "Tillåt T3 Code i Systeminställningar › Integritet och säkerhet och starta sedan om T3 Code.", "c0f756221736393f": "Förhandsvisning · {title}", "6994444f4fec4070": "Förhandsvisning i webbläsaren", "49de6209699eb616": "Namnlös lösenordsnyckel", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Du har den senaste versionen!", "c6399b55619e2f67": "T3 Code {version} är den senaste tillgängliga versionen.", - "b6e5b31255e011c5": "OK", "2ee2077700686fbb": "Uppdatering tillgänglig", "d3104b65052b993b": "En ny version av T3 Code är tillgänglig.", "35fff5a1cd1d6473": "T3 Code {version} är tillgänglig.", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 72122de01df62..f0797cc416d4a 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -34,6 +34,12 @@ "278648c9ff6fb9ce": "此证书并非由受信任的机构签发。", "cf346dcfb658d4d3": "此证书不适用于当前地址。", "20665d9b0c7c3e52": "此证书已过期或尚未生效。", + "e632aac04674913c": "{origin} 想使用你的摄像头和麦克风", + "379c230d24c9b5c5": "{origin} 想使用你的麦克风", + "576ac67fdb145936": "{origin} 想使用你的摄像头", + "d8d5fbd2529b6bd3": "macOS 已阻止 T3 Code 使用你的摄像头和麦克风", + "65dff766a75b43d5": "macOS 已阻止 T3 Code 使用你的麦克风", + "39e3d7326db9af25": "macOS 已阻止 T3 Code 使用你的摄像头", "565970a378986341": "打开", "00ad8aeed0a6c461": "取消", "2107cc3e7c4ac833": "要打开此 {protocol} 链接吗?", @@ -51,6 +57,8 @@ "2ec823ca24387055": "阻止", "709219ff9ff49a4f": "{origin} 想要获取你的位置", "8fc0b116123fb50b": "{origin} 想查看复制到剪贴板的文字和图片", + "b6e5b31255e011c5": "确定", + "fb7c135eaced773b": "请在“系统设置 › 隐私与安全性”中允许 T3 Code,然后重新启动 T3 Code。", "c0f756221736393f": "预览 · {title}", "6994444f4fec4070": "浏览器预览", "49de6209699eb616": "未命名通行密钥", @@ -59,7 +67,6 @@ "f3430cac09a505a0": "稳定版", "1f12213f4d809e89": "已是最新版本!", "c6399b55619e2f67": "T3 Code {version} 已是最新版本。", - "b6e5b31255e011c5": "确定", "2ee2077700686fbb": "有可用更新", "d3104b65052b993b": "T3 Code 有新版本可用。", "35fff5a1cd1d6473": "T3 Code {version} 可用。", diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index c88ddd0827df0..9ffc466d5a825 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -41,6 +41,7 @@ import { } from "./methods/updates.ts"; import { getAppBranding, + getDatabaseMigrationProgress, getLocalEnvironmentBootstraps, getLocalEnvironmentBearerToken, installRelayTelemetryEnabled, @@ -105,6 +106,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(takeLegacyLocalStorage); yield* ipc.handle(completeLegacyLocalStorage); yield* ipc.handleSync(getAppBranding); + yield* ipc.handle(getDatabaseMigrationProgress); yield* installRelayTelemetryEnabled(); yield* ipc.handleSync(getSystemLocale); yield* ipc.handleSync(getPreferredSystemLanguages); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 71d272333fdc7..d590591f595f5 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -35,6 +35,7 @@ export const CLI_COMMAND_INSTALL_CHANNEL = "desktop:cli-command-install"; export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall"; export const CLI_COMMAND_ADD_TO_PATH_CHANNEL = "desktop:cli-command-add-to-path"; export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; +export const GET_DATABASE_MIGRATION_PROGRESS_CHANNEL = "desktop:get-database-migration-progress"; export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled"; export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale"; export const GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL = "desktop:get-preferred-system-languages"; diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index ac69c40d4a917..ba465a4eb2f88 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -2,6 +2,7 @@ import { ContextMenuItemSchema, ContextMenuSource, DesktopAppBrandingSchema, + DatabaseMigrationProgress, DesktopEnvironmentBootstrapSchema, DesktopMediaReadSchema, DesktopThemeSchema, @@ -24,6 +25,8 @@ import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import * as Ref from "effect/Ref"; +import * as DesktopState from "../../app/DesktopState.ts"; import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts"; import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts"; @@ -73,6 +76,16 @@ function toWebSocketBaseUrl(httpBaseUrl: URL): string { return url.href; } +export const getDatabaseMigrationProgress = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.GET_DATABASE_MIGRATION_PROGRESS_CHANNEL, + payload: Schema.Void, + result: Schema.NullOr(DatabaseMigrationProgress), + handler: Effect.fn("desktop.ipc.window.getDatabaseMigrationProgress")(function* () { + const state = yield* DesktopState.DesktopState; + return yield* Ref.get(state.databaseMigrationProgress); + }), +}); + export const getAppBranding = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_APP_BRANDING_CHANNEL, result: Schema.NullOr(DesktopAppBrandingSchema), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index ac52fbc73d868..ab472baabe623 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -104,6 +104,8 @@ function unwrapEnsureSshEnvironmentResult(result: unknown) { } contextBridge.exposeInMainWorld("desktopBridge", { + getDatabaseMigrationProgress: () => + ipcRenderer.invoke(IpcChannels.GET_DATABASE_MIGRATION_PROGRESS_CHANNEL), getAppBranding: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_APP_BRANDING_CHANNEL); if (typeof result !== "object" || result === null) { diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts index 484ba6f9358f6..1d7da55db2a60 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts @@ -1,18 +1,43 @@ +import * as NodeSqlite from "node:sqlite"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; +import { BrowserImportSource } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import type { Session } from "electron"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Cipher from "effect/crypto/Cipher"; +import * as Digest from "effect/crypto/Digest"; +import * as Kdf from "effect/crypto/Kdf"; +import { vi } from "vite-plus/test"; import * as BrowserSession from "../BrowserSession.ts"; import { readManagedPolicyFile } from "@t3tools/shared/managedPolicyFile"; import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts"; import * as BrowserImport from "./BrowserImport.ts"; +import { LinuxBrowserSecretPath } from "./LinuxBrowserSecret.ts"; import { BROWSER_IMPORT_SOURCES, sourcePathContext } from "./Sources.ts"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; const helium = BROWSER_IMPORT_SOURCES.find((source) => source.id === "helium")!; +const decodeImportSource = Schema.decodeEffect(BrowserImportSource); +const chromiumKeychainSecret = "fixture-chromium-keychain-secret"; + +vi.mock("@napi-rs/keyring", () => ({ + AsyncEntry: class { + readonly getPassword: () => Promise; + + constructor(service: string, account: string) { + this.getPassword = async () => + service === "Chromium Safe Storage" && account === "Chromium" + ? chromiumKeychainSecret + : undefined; + } + }, +})); const cookie = { url: "https://rejected.example/path", @@ -67,6 +92,128 @@ const withImporter = Effect.fnUntraced(function* () { }); describe("BrowserImport.importCookies", () => { + it.effect.each([ + { platform: "linux", cookiePath: "Cookies" }, + { platform: "linux", cookiePath: "Network/Cookies" }, + { platform: "darwin", cookiePath: "Network/Cookies" }, + ] as const)( + "discovers and imports Chromium cookies on $platform from $cookiePath", + ({ platform, cookiePath }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-chromium-" }); + const root = + platform === "darwin" + ? `${home}/Library/Application Support/Chromium` + : `${home}/.config/chromium`; + yield* fileSystem.makeDirectory(`${root}/Default/Network`, { recursive: true }); + yield* fileSystem.writeFileString( + `${root}/Local State`, + JSON.stringify({ profile: { info_cache: { Default: { name: "Personal" } } } }), + ); + const kdf = yield* Kdf.Kdf; + const cipher = yield* Cipher.Cipher; + const keyBytes = yield* kdf.derive( + Kdf.pbkdf2({ hash: Digest.sha1, iterations: platform === "darwin" ? 1003 : 1 }), + Buffer.from(platform === "darwin" ? chromiumKeychainSecret : "peanuts"), + { salt: Buffer.from("saltysalt"), length: 16 }, + ); + const key = yield* Cipher.key(Cipher.aes128Cbc, keyBytes); + const ciphertext = yield* cipher.encrypt(key, Buffer.from("fixture-session"), { + iv: Buffer.alloc(16, 0x20), + }); + const value = Buffer.concat([Buffer.from("v10"), ciphertext]); + yield* Effect.sync(() => { + using database = new NodeSqlite.DatabaseSync(`${root}/Default/${cookiePath}`); + database.exec(` + create table meta (key text primary key, value text not null); + insert into meta values ('version', '23'); + create table cookies ( + host_key text, name text, value text, encrypted_value blob, path text, + expires_utc integer, is_secure integer, is_httponly integer, samesite integer, + top_frame_site_key text not null default '' + ); + `); + database + .prepare("insert into cookies values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)") + .run("chromium.example", "session", "", value, "/", 0, 1, 1, 1, ""); + }); + + const written: Electron.CookiesSetDetails[] = []; + let flushed = false; + const session = { + cookies: { + set: (cookie: Electron.CookiesSetDetails) => { + written.push(cookie); + return Promise.resolve(); + }, + flushStore: () => { + flushed = true; + return Promise.resolve(); + }, + }, + } as unknown as Session; + const importer = yield* BrowserImport.BrowserImport.pipe( + Effect.provide( + BrowserImport.layer.pipe( + Layer.provide( + Layer.succeed(BrowserSession.BrowserSession, { + getPartition: () => Effect.die("getPartition must not be reached"), + isPartition: () => false, + getSession: () => Effect.succeed(session), + clearCookies: () => Effect.die("clearCookies must not be reached"), + cookiesCleared: () => Effect.die("cookiesCleared must not be reached"), + clearCache: () => Effect.die("clearCache must not be reached"), + }), + ), + Layer.provide(DesktopManagedPolicy.layerTest()), + Layer.provide(Layer.succeed(HostProcess.Environment, { HOME: home })), + Layer.provide(Layer.succeed(HostProcess.Platform, platform)), + Layer.provide(Layer.succeed(HostProcess.ExecutablePath, "/fixture/t3code")), + Layer.provide(NodeServices.layer), + ), + ), + ); + const source = (yield* importer.listSources).find( + (candidate) => candidate.id === "chromium", + ); + assert.isDefined(source); + assert.deepEqual(yield* decodeImportSource(source!), { + id: "chromium", + name: "Chromium", + profiles: [{ directory: "Default", name: "Personal", cookieCount: 1 }], + }); + assert.deepEqual( + yield* importer.importCookies({ + input: { + sourceId: "chromium", + sourceProfileDirectory: "Default", + targetProfileId: "default", + }, + scope: "persist:t3code-preview-test", + persistent: true, + }), + { imported: 1, skipped: 0, skippedDomains: [] }, + ); + assert.deepEqual(written, [ + { + url: "https://chromium.example/", + name: "session", + value: "fixture-session", + path: "/", + secure: true, + httpOnly: true, + sameSite: "lax", + }, + ]); + assert.isTrue(flushed); + }).pipe( + Effect.provideService(LinuxBrowserSecretPath, undefined), + Effect.provide([NodeServices.layer, NodeCrypto.layerKdf, NodeCrypto.layerCipher]), + Effect.scoped, + ), + ); + it.effect("rejects a source profile the browser never reported", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts index 9b2c3cb26c8f7..54518f637c6c1 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts @@ -199,9 +199,17 @@ describe("chromiumProcessIsAlive", () => { }); describe("isSourceInstalled", () => { - it.effect.each([undefined, "", "relative-config", "relocated", "chrome-override"])( - "discovers Linux Chromium profiles with XDG_CONFIG_HOME=%s", - (configHome) => + it.effect.each([ + ["chrome", "google-chrome", undefined], + ["chrome", "google-chrome", ""], + ["chrome", "google-chrome", "relative-config"], + ["chrome", "google-chrome", "relocated"], + ["chrome", "google-chrome", "chrome-override"], + ["chromium", "chromium", "relocated"], + ["chromium", "chromium", "chrome-override"], + ] as const)( + "discovers Linux %s profiles in %s with config home %s", + ([sourceId, directory, configHome]) => run( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -212,7 +220,7 @@ describe("isSourceInstalled", () => { ? path.join(home, "config") : configHome; const chromeConfigHome = - configHome === "chrome-override" ? path.join(home, ".config") : undefined; + configHome === "chrome-override" ? path.join(home, "chrome-config") : undefined; const context = yield* sourcePathContext.pipe( Effect.provideService(HostProcess.Environment, { HOME: home, @@ -224,8 +232,8 @@ describe("isSourceInstalled", () => { const configRoot = chromeConfigHome ?? (configHome === "relocated" ? path.join(home, "config") : path.join(home, ".config")); - const source = BROWSER_IMPORT_SOURCES.find((source) => source.id === "chrome")!; - const root = path.join(configRoot, "google-chrome"); + const source = BROWSER_IMPORT_SOURCES.find((source) => source.id === sourceId)!; + const root = path.join(configRoot, directory); const database = path.join(root, "Default", "Network", "Cookies"); assert.isFalse(yield* isSourceInstalled(source, context)); yield* fileSystem.makeDirectory(path.dirname(database), { recursive: true }); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts index 6ecd546a1ad57..b8fc14f578700 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.ts @@ -71,7 +71,9 @@ const chromiumSource = (input: { } return input.linuxSegments ? context.path.join( - input.id === "chrome" ? context.linuxChromeConfigHome : context.linuxConfigHome, + input.id === "chrome" || input.id === "chromium" + ? context.linuxChromeConfigHome + : context.linuxConfigHome, ...input.linuxSegments, ) : undefined; @@ -89,6 +91,15 @@ export const BROWSER_IMPORT_SOURCES: ReadonlyArray ({ appListeners: new Map void>(), })); +const { getMediaAccessStatus, askForMediaAccess } = vi.hoisted(() => ({ + getMediaAccessStatus: vi.fn<(device: string) => string>(() => "granted"), + askForMediaAccess: vi.fn<(device: string) => Promise>(() => Promise.resolve(true)), +})); + vi.mock("electron", () => ({ app: { on: (eventName: string, listener: (...args: unknown[]) => void) => { @@ -49,6 +56,7 @@ vi.mock("electron", () => ({ session: { fromPartition, }, + systemPreferences: { getMediaAccessStatus, askForMediaAccess }, })); import * as ElectronApp from "../electron/ElectronApp.ts"; @@ -80,6 +88,18 @@ const layer = BrowserSession.layer.pipe( ), ); +const layerDarwin = BrowserSession.layer.pipe( + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + layerDialog, + ElectronApp.layer, + Layer.succeed(HostProcess.Platform, "darwin"), + ), + ), +); + const selfSignedCertificate = { fingerprint: "sha256/self-signed", subjectName: "localhost", @@ -241,12 +261,14 @@ describe("BrowserSession", () => { const calls = browserSession.webRequest.onBeforeSendHeaders.mock.calls; assert.strictEqual(calls.length, 1); const [filter, listener] = calls[0] ?? []; - assert.deepStrictEqual(filter, { - urls: ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"], - }); - const send = (requestHeaders: Record) => { + assert.deepStrictEqual(filter, { urls: ["http://*/*", "https://*/*"] }); + const send = ( + requestHeaders: Record, + url = "https://teams.microsoft.com/v2/", + resourceType = "xhr", + ) => { let response: { requestHeaders?: Record } | undefined; - listener({ requestHeaders }, (next: typeof response) => { + listener({ url, resourceType, requestHeaders }, (next: typeof response) => { response = next; }); return response; @@ -259,9 +281,60 @@ describe("BrowserSession", () => { assert.strictEqual(requestHeaders[key], nativeUserAgent); } assert.deepStrictEqual(send({ Accept: "*/*" }), {}); + assert.deepStrictEqual(send({ "User-Agent": nativeUserAgent }, "https://example.com/"), {}); + }).pipe(Effect.provide(layer)), + ); + + it.effect("adds the renderer's client hints to secure navigations, which Electron omits", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const [, listener] = + sessions.get(partition)?.webRequest.onBeforeSendHeaders.mock.calls[0] ?? []; + const send = (url: string, resourceType: string, requestHeaders: Record) => { + let response: { requestHeaders?: Record } | undefined; + listener({ url, resourceType, requestHeaders }, (next: typeof response) => { + response = next; + }); + return response; + }; + const hints = BrowserSession.lowEntropyClientHints( + process.versions.chrome ?? "", + yield* HostProcess.Platform, + ); + + for (const [url, resourceType] of [ + ["https://example.com/login", "mainFrame"], + ["http://localhost:3000/", "subFrame"], + ["http://127.0.0.1:3000/", "mainFrame"], + ] as const) { + assert.deepStrictEqual(send(url, resourceType, { Accept: "text/html" }), { + requestHeaders: { Accept: "text/html", ...hints }, + }); + } + // Chromium sends no hints to insecure origins, and subresources already carry the renderer's own. + assert.deepStrictEqual(send("http://example.com/", "mainFrame", {}), {}); + assert.deepStrictEqual(send("https://example.com/api", "xhr", {}), {}); + assert.deepStrictEqual( + send("https://example.com/", "mainFrame", { "Sec-CH-UA": '"Chromium";v="1"' }), + {}, + ); }).pipe(Effect.provide(layer)), ); + it("builds the client hints Electron 44's renderer sends", () => { + assert.deepStrictEqual(BrowserSession.lowEntropyClientHints("152.0.7977.169", "linux"), { + "sec-ch-ua": '"Not?A_Brand";v="24", "Chromium";v="152"', + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": '"Linux"', + }); + assert.strictEqual( + BrowserSession.lowEntropyClientHints("152.0.7977.169", "darwin")["sec-ch-ua-platform"], + '"macOS"', + ); + }); + it.effect("grants preview permissions through both the request and check handlers", () => Effect.gen(function* () { const browserSessions = yield* BrowserSession.BrowserSession; @@ -402,6 +475,317 @@ describe("BrowserSession", () => { }).pipe(Effect.provide(layer)), ); + it.effect("asks once per origin and device before a page uses the camera", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + assert.isDefined(browserSession); + const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0]; + const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0]; + + const requestMedia = (requestingUrl: string, mediaTypes: ReadonlyArray) => + Effect.callback((resume) => { + requestHandler(null, "media", (granted: boolean) => resume(Effect.succeed(granted)), { + requestingUrl, + securityOrigin: requestingUrl, + mediaTypes, + isMainFrame: true, + }); + }); + const checkMedia = (origin: string, mediaType: string): boolean => + checkHandler(null, "media", origin, { mediaType }) as boolean; + + showMessageBox.mockReset(); + showMessageBox.mockReturnValueOnce(0).mockReturnValueOnce(1).mockReturnValueOnce(1); + getMediaAccessStatus.mockReturnValue("granted"); + + assert.isFalse(checkMedia("https://allowed.test", "video")); + assert.isTrue(yield* requestMedia("https://allowed.test/scan", ["video"])); + assert.strictEqual( + showMessageBox.mock.calls[0]?.[0].message, + "https://allowed.test wants to use your camera", + ); + assert.isTrue(yield* requestMedia("https://allowed.test/again", ["video"])); + assert.isTrue(checkMedia("https://allowed.test", "video")); + assert.isFalse(checkMedia("https://allowed.test", "audio")); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + + assert.isFalse(yield* requestMedia("https://blocked.test/", ["video", "audio"])); + assert.isFalse(yield* requestMedia("https://blocked.test/", ["audio"])); + assert.isFalse(checkMedia("https://blocked.test", "video")); + assert.strictEqual(showMessageBox.mock.calls.length, 2); + + assert.isFalse(yield* requestMedia("https://allowed.test/", ["video", "audio"])); + assert.strictEqual( + showMessageBox.mock.calls[2]?.[0].message, + "https://allowed.test wants to use your microphone", + ); + assert.isTrue(yield* requestMedia("https://allowed.test/", ["video"])); + assert.isTrue(checkMedia("https://allowed.test", "video")); + assert.isFalse(yield* requestMedia("https://allowed.test/", [])); + }).pipe(Effect.provide(layer)), + ); + + it.effect("asks macOS for the device after the user allows a page", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const requestHandler = + sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0]; + assert.isFunction(requestHandler); + const requestMedia = (requestingUrl: string, mediaTypes: ReadonlyArray) => + Effect.callback((resume) => { + requestHandler(null, "media", (granted: boolean) => resume(Effect.succeed(granted)), { + requestingUrl, + securityOrigin: requestingUrl, + mediaTypes, + isMainFrame: true, + }); + }); + + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(0); + askForMediaAccess.mockReset(); + askForMediaAccess.mockResolvedValue(true); + getMediaAccessStatus.mockReset(); + getMediaAccessStatus.mockReturnValue("not-determined"); + + // A device macOS has not decided yet: ask the OS, which adds T3 Code to Privacy & Security. + assert.isTrue(yield* requestMedia("https://first.test/", ["video"])); + assert.deepStrictEqual(askForMediaAccess.mock.calls, [["camera"]]); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + + // macOS denied one of two devices: the page gets nothing and the user learns where to fix it. + askForMediaAccess.mockReset(); + getMediaAccessStatus.mockImplementation((device) => + device === "camera" ? "not-determined" : "denied", + ); + const recoveryShown = yield* Deferred.make(); + const recoveryAnswer = Promise.withResolvers(); + showMessageBox.mockImplementation((options) => { + if (options.message.startsWith("macOS blocked")) { + Deferred.doneUnsafe(recoveryShown, Effect.void); + return recoveryAnswer.promise; + } + return 0; + }); + assert.isFalse(yield* requestMedia("https://second.test/", ["video", "audio"])); + assert.strictEqual(askForMediaAccess.mock.calls.length, 0); + yield* Deferred.await(recoveryShown); + assert.strictEqual(showMessageBox.mock.calls.length, 3); + assert.strictEqual( + showMessageBox.mock.calls[1]?.[0].message, + "https://second.test wants to use your camera and microphone", + ); + // Only the microphone is blocked, so the message does not send the user looking for Camera. + assert.strictEqual( + showMessageBox.mock.calls[2]?.[0].message, + "macOS blocked T3 Code from using your microphone", + ); + assert.isFalse(yield* requestMedia("https://second.test/", ["video", "audio"])); + assert.strictEqual(showMessageBox.mock.calls.length, 3); + recoveryAnswer.resolve(0); + const checkHandler = sessions.get(partition)?.setPermissionCheckHandler.mock.calls[0]?.[0]; + assert.isFalse(checkHandler(null, "media", "https://second.test", { mediaType: "audio" })); + getMediaAccessStatus.mockReturnValue("granted"); + assert.isTrue(checkHandler(null, "media", "https://second.test", { mediaType: "audio" })); + }).pipe(Effect.provide(layerDarwin)), + ); + + it.effect("names both devices when macOS blocks both", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const requestHandler = + sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0]; + assert.isFunction(requestHandler); + + askForMediaAccess.mockReset(); + getMediaAccessStatus.mockReset(); + getMediaAccessStatus.mockReturnValue("denied"); + const recoveryShown = yield* Deferred.make(); + showMessageBox.mockReset(); + showMessageBox.mockImplementation((options) => { + if (options.message.startsWith("macOS blocked")) { + Deferred.doneUnsafe(recoveryShown, Effect.succeed(options.message)); + } + return 0; + }); + + const granted = yield* Effect.callback((resume) => { + requestHandler(null, "media", (value: boolean) => resume(Effect.succeed(value)), { + requestingUrl: "https://both.test/", + mediaTypes: ["video", "audio"], + isMainFrame: true, + }); + }); + assert.isFalse(granted); + assert.strictEqual(askForMediaAccess.mock.calls.length, 0); + assert.strictEqual( + yield* Deferred.await(recoveryShown), + "macOS blocked T3 Code from using your camera and microphone", + ); + }).pipe(Effect.provide(layerDarwin)), + ); + + it.effect("forgets camera answers when the profile's cookies are cleared", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const browserSession = sessions.get(partition); + assert.isDefined(browserSession); + const requestHandler = browserSession.setPermissionRequestHandler.mock.calls[0]?.[0]; + const checkHandler = browserSession.setPermissionCheckHandler.mock.calls[0]?.[0]; + const requestCamera = () => + Effect.callback((resume) => { + requestHandler(null, "media", (granted: boolean) => resume(Effect.succeed(granted)), { + requestingUrl: "https://page.test/", + mediaTypes: ["video"], + isMainFrame: true, + }); + }); + const checkCamera = (): boolean => + checkHandler(null, "media", "https://page.test", { mediaType: "video" }) as boolean; + + showMessageBox.mockReset(); + showMessageBox.mockReturnValueOnce(1).mockReturnValueOnce(0).mockReturnValueOnce(1); + getMediaAccessStatus.mockReset(); + getMediaAccessStatus.mockReturnValue("granted"); + + assert.isFalse(yield* requestCamera()); + assert.isFalse(yield* requestCamera()); + assert.strictEqual(showMessageBox.mock.calls.length, 1); + + // Clearing lets the user reconsider a block... + yield* browserSessions.clearCookies([partition]); + assert.isTrue(yield* requestCamera()); + assert.isTrue(checkCamera()); + assert.strictEqual(showMessageBox.mock.calls.length, 2); + + // ...and revokes an approval, including one cleared outside clearCookies. + yield* browserSessions.cookiesCleared(browserSession as unknown as Electron.Session); + assert.isFalse(checkCamera()); + assert.isFalse(yield* requestCamera()); + assert.strictEqual(showMessageBox.mock.calls.length, 3); + + yield* browserSessions.clearCookies([partition]); + showMessageBox.mockReturnValue(0); + assert.isTrue(yield* requestCamera()); + yield* browserSessions.getSession("scope-b"); + const otherPartition = yield* browserSessions.getPartition("scope-b"); + const otherRequest = + sessions.get(otherPartition)?.setPermissionRequestHandler.mock.calls[0]?.[0]; + const otherCheck = sessions.get(otherPartition)?.setPermissionCheckHandler.mock.calls[0]?.[0]; + assert.isTrue( + yield* Effect.callback((resume) => { + otherRequest(null, "media", (value: boolean) => resume(Effect.succeed(value)), { + requestingUrl: "https://page.test/", + mediaTypes: ["video"], + isMainFrame: true, + }); + }), + ); + browserSession.clearStorageData.mockRejectedValueOnce(new Error("clear failed")); + const pendingClear = Promise.withResolvers(); + sessions + .get(otherPartition) + ?.clearStorageData.mockImplementationOnce(() => pendingClear.promise); + const cleared = yield* Effect.result(browserSessions.clearCookies()); + assert.strictEqual(cleared._tag, "Failure"); + assert.isFalse(checkCamera()); + assert.isFalse(otherCheck(null, "media", "https://page.test", { mediaType: "video" })); + pendingClear.resolve(); + }).pipe(Effect.provide(layer)), + ); + + it.effect("a reset while a camera prompt is open neither grants nor remembers", () => + Effect.gen(function* () { + const browserSessions = yield* BrowserSession.BrowserSession; + const partition = yield* browserSessions.getPartition("scope-a"); + yield* browserSessions.getSession("scope-a"); + const requestHandler = + sessions.get(partition)?.setPermissionRequestHandler.mock.calls[0]?.[0]; + const checkHandler = sessions.get(partition)?.setPermissionCheckHandler.mock.calls[0]?.[0]; + const guest = Object.assign(new NodeEvents.EventEmitter(), { + hostWebContents: null, + isDestroyed: vi.fn<() => boolean>(() => false), + }); + const requestCamera = () => { + const granted = Deferred.makeUnsafe(); + requestHandler( + guest, + "media", + (value: boolean) => Deferred.doneUnsafe(granted, Effect.succeed(value)), + { requestingUrl: "https://page.test/", mediaTypes: ["video"], isMainFrame: true }, + ); + return Deferred.await(granted); + }; + const checkCamera = (): boolean => + checkHandler(null, "media", "https://page.test", { mediaType: "video" }) as boolean; + + // The user answers Allow only after cookies were cleared. + const asked = yield* Deferred.make(); + const answer = Promise.withResolvers(); + showMessageBox.mockReset(); + showMessageBox.mockImplementationOnce(() => { + Deferred.doneUnsafe(asked, Effect.void); + return answer.promise; + }); + getMediaAccessStatus.mockReset(); + getMediaAccessStatus.mockReturnValue("not-determined"); + askForMediaAccess.mockReset(); + askForMediaAccess.mockResolvedValue(true); + + const pending = yield* Effect.forkChild(requestCamera()); + yield* Deferred.await(asked); + yield* browserSessions.clearCookies([partition]); + answer.resolve(0); + assert.isFalse(yield* Fiber.join(pending)); + // With macOS allowing the camera, only a stored stale Allow could make this check pass. + getMediaAccessStatus.mockReturnValue("granted"); + assert.isFalse(checkCamera()); + getMediaAccessStatus.mockReturnValue("not-determined"); + assert.strictEqual(askForMediaAccess.mock.calls.length, 0); + + // The macOS check is still running when cookies are cleared. + const systemAsked = yield* Deferred.make(); + const systemAnswer = Promise.withResolvers(); + showMessageBox.mockReturnValue(0); + askForMediaAccess.mockImplementationOnce(() => { + Deferred.doneUnsafe(systemAsked, Effect.void); + return systemAnswer.promise; + }); + const pendingSystem = yield* Effect.forkChild(requestCamera()); + yield* Deferred.await(systemAsked); + yield* browserSessions.clearCookies([partition]); + systemAnswer.resolve(true); + assert.isFalse(yield* Fiber.join(pendingSystem)); + assert.isFalse(checkCamera()); + + const tabPromptShown = yield* Deferred.make(); + const tabAnswer = Promise.withResolvers(); + showMessageBox.mockImplementationOnce(() => { + Deferred.doneUnsafe(tabPromptShown, Effect.void); + return tabAnswer.promise; + }); + const pendingTab = yield* Effect.forkChild(requestCamera()); + yield* Deferred.await(tabPromptShown); + const promptSignal = showMessageBox.mock.lastCall?.[0].signal; + guest.isDestroyed.mockReturnValue(true); + guest.emit("destroyed"); + assert.isTrue(promptSignal?.aborted); + tabAnswer.resolve(0); + assert.isFalse(yield* Fiber.join(pendingTab)); + assert.isFalse(checkCamera()); + assert.strictEqual(askForMediaAccess.mock.calls.length, 1); + }).pipe(Effect.provide(layerDarwin)), + ); + it.effect("clears a partition whose session has not been opened yet", () => Effect.gen(function* () { const browserSessions = yield* BrowserSession.BrowserSession; diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.ts index d247fcbcd8266..1ecea4218196f 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -1,6 +1,6 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import type { Certificate, Session, WebContents } from "electron"; -import { BrowserWindow, session } from "electron"; +import { BrowserWindow, session, systemPreferences } from "electron"; import { msg } from "gt-i18n"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; @@ -64,7 +64,46 @@ const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => }; // Teams sends Electron User-Agents to an error page before sign-in. Electron allows one listener per session. -const TEAMS_URL_PATTERNS = ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"]; +const isTeamsUrl = (url: string): boolean => + url.startsWith("https://teams.cloud.microsoft/") || + url.startsWith("https://teams.microsoft.com/"); + +const GREASE_CHARS = [" ", "(", ":", "-", ".", "/", ")", ";", "=", "?", "_"]; +const GREASE_VERSIONS = ["8", "99", "24"]; + +/** + * The low-entropy User-Agent client hints the renderer sends on fetches. Mirrors Chromium's + * GenerateBrandVersionList with no embedder brand, as Electron builds it. + */ +export const lowEntropyClientHints = ( + chromeVersion: string, + platform: NodeJS.Platform, +): Record => { + const major = Number.parseInt(chromeVersion, 10); + const grease = `"Not${GREASE_CHARS[major % 11]}A${GREASE_CHARS[(major + 1) % 11]}Brand";v="${GREASE_VERSIONS[major % 3]}"`; + const chromium = `"Chromium";v="${major}"`; + return { + "sec-ch-ua": major % 2 === 0 ? `${grease}, ${chromium}` : `${chromium}, ${grease}`, + "sec-ch-ua-mobile": "?0", + "sec-ch-ua-platform": `"${platform === "darwin" ? "macOS" : platform === "win32" ? "Windows" : "Linux"}"`, + }; +}; + +const isPotentiallyTrustworthy = (rawUrl: string): boolean => { + try { + const { protocol, hostname } = new URL(rawUrl); + if (protocol === "https:") return true; + return ( + protocol === "http:" && + (hostname === "localhost" || + hostname.endsWith(".localhost") || + hostname === "[::1]" || + /^127\.\d+\.\d+\.\d+$/.test(hostname)) + ); + } catch { + return false; + } +}; const MAX_PROMPT_URL_LENGTH = 300; @@ -139,6 +178,58 @@ interface CertificateTrust { revocations: number; } +type MediaDevice = "camera" | "microphone"; + +const mediaDeviceFor = (mediaType: string | undefined): MediaDevice | null => + mediaType === "video" ? "camera" : mediaType === "audio" ? "microphone" : null; + +// Whole sentences per device set, so each language can phrase them its own way. +const mediaRequestMessage = (devices: ReadonlyArray, origin: string): string => + devices.length === 2 + ? m(msg("{origin} wants to use your camera and microphone"), { origin }) + : devices[0] === "microphone" + ? m(msg("{origin} wants to use your microphone"), { origin }) + : m(msg("{origin} wants to use your camera"), { origin }); + +const mediaBlockedMessage = (devices: ReadonlyArray): string => + devices.length === 2 + ? m(msg("macOS blocked T3 Code from using your camera and microphone")) + : devices[0] === "microphone" + ? m(msg("macOS blocked T3 Code from using your microphone")) + : m(msg("macOS blocked T3 Code from using your camera")); + +/** + * macOS gates capture devices per app and lists an app under Privacy & Security + * only after it asks, so ask the OS once the user allowed the page. + */ +/** Returns the devices macOS blocks, so the recovery message names only those; empty means allowed. */ +const ensureSystemMediaAccess = async ( + platform: NodeJS.Platform, + devices: ReadonlyArray, +): Promise> => { + if (platform !== "darwin") return []; + const statuses = devices.map((device) => systemPreferences.getMediaAccessStatus(device)); + const refused = devices.filter( + (_device, index) => statuses[index] !== "granted" && statuses[index] !== "not-determined", + ); + if (refused.length > 0) return refused; + const results = await Promise.all( + devices.map((device, index) => + statuses[index] === "granted" + ? true + : systemPreferences.askForMediaAccess(device).catch(() => false), + ), + ); + return devices.filter((_device, index) => !results[index]); +}; + +/** The camera and microphone answers given in one preview Session. */ +interface MediaConsent { + readonly decisions: Map; + /** Bumped by each reset, so an answer to an older prompt cannot restore a decision. */ + resets: number; +} + export class BrowserSessionPartitionDerivationError extends Schema.TaggedError()( "BrowserSessionPartitionDerivationError", { @@ -268,6 +359,7 @@ export const make = Effect.gen(function* BrowserSessionMake() { const runFork = Effect.runForkWith(yield* Effect.context()); // One prompt at a time, so a page cannot stack dialogs by looping a deep link. let permissionPromptOpen = false; + let mediaRecoveryOpen = false; /** Settles with `undefined` when the user gave no answer: another prompt was open or the dialog failed. */ const promptPermission = ( requester: WebContents | null, @@ -278,21 +370,26 @@ export const make = Effect.gen(function* BrowserSessionMake() { }, callback: (answer: boolean | undefined) => void, ): void => { - if (permissionPromptOpen) { + if (permissionPromptOpen || requester?.isDestroyed()) { callback(undefined); return; } permissionPromptOpen = true; + const dismiss = new AbortController(); + const abandon = () => dismiss.abort(); + requester?.once("destroyed", abandon); const settle = (answer: boolean | undefined) => Effect.sync(() => { permissionPromptOpen = false; - callback(answer); + requester?.off("destroyed", abandon); + callback(dismiss.signal.aborted || requester?.isDestroyed() ? undefined : answer); }); runFork( electronDialog .showMessageBox( { type: "question", + signal: dismiss.signal, buttons: [...prompt.buttons], // Default to deny so an Enter typed into the page cannot accept a prompt it raised. defaultId: 1, @@ -574,6 +671,15 @@ export const make = Effect.gen(function* BrowserSessionMake() { } }); + /** Camera and microphone answers by Session; clearing a profile's cookies forgets them too. */ + const mediaConsentBySession = new WeakMap(); + const forgetMediaDecisions = (browserSession: Session): void => { + const consent = mediaConsentBySession.get(browserSession); + if (consent === undefined) return; + consent.resets += 1; + consent.decisions.clear(); + }; + const sessionsRef = yield* SynchronizedRef.make>(new Map()); const getPartition = Effect.fn("BrowserSession.getPartition")(function* ( @@ -651,6 +757,105 @@ export const make = Effect.gen(function* BrowserSessionMake() { }, ); }; + // Camera and microphone ask once per origin and device, like clipboard reads. + const mediaConsent: MediaConsent = { decisions: new Map(), resets: 0 }; + mediaConsentBySession.set(browserSession, mediaConsent); + const mediaDecisions = mediaConsent.decisions; + const mediaKey = (origin: string, device: MediaDevice) => `${device} ${origin}`; + const confirmMedia = ( + requester: WebContents, + rawUrl: string | undefined, + mediaTypes: ReadonlyArray | undefined, + callback: (granted: boolean) => void, + ): void => { + const origin = permissionOrigin(rawUrl); + const devices = [ + ...new Set((mediaTypes ?? []).map(mediaDeviceFor).filter((d) => d !== null)), + ]; + if (origin === null || devices.length === 0) { + callback(false); + return; + } + // A reset while a prompt or the macOS check is pending must not grant or remember. + const resets = mediaConsent.resets; + const isStale = () => + mediaConsent.resets !== resets || requester?.isDestroyed() === true; + const finish = (granted: boolean) => { + if (!granted || isStale()) { + callback(false); + return; + } + void ensureSystemMediaAccess(platform, devices).then( + (blocked) => { + const systemGranted = blocked.length === 0; + if (isStale()) { + callback(false); + return; + } + if (!systemGranted && !mediaRecoveryOpen) { + mediaRecoveryOpen = true; + runFork( + electronDialog + .showMessageBox( + { + type: "info", + buttons: [m(msg("OK"))], + message: mediaBlockedMessage(blocked), + detail: m( + msg( + "Allow T3 Code in System Settings › Privacy & Security, then restart T3 Code.", + ), + ), + }, + previewHostWindow(requester), + ) + .pipe( + Effect.ignore, + Effect.ensuring( + Effect.sync(() => { + mediaRecoveryOpen = false; + }), + ), + ), + ); + } + callback(systemGranted); + }, + () => callback(false), + ); + }; + const remembered = devices.map((device) => + mediaDecisions.get(mediaKey(origin, device)), + ); + if (remembered.some((answer) => answer === false)) { + callback(false); + return; + } + if (remembered.every((answer) => answer === true)) { + finish(true); + return; + } + const undecided = devices.filter( + (device) => !mediaDecisions.has(mediaKey(origin, device)), + ); + promptPermission( + requester, + { + buttons: [ + m(msg("Allow", { $context: "button, grants a site permission" })), + m(msg("Block", { $context: "button, denies a site permission" })), + ], + message: mediaRequestMessage(undecided, truncateForPrompt(origin)), + }, + (answer) => { + if (answer !== undefined && !isStale()) { + for (const device of undecided) + mediaDecisions.set(mediaKey(origin, device), answer); + } + finish(answer === true); + }, + ); + }; // Rewriting Electron's native User-Agent makes Turnstile fail integrity checks with error 600010. browserSession.setPermissionRequestHandler( (webContents, permission, callback, details) => { @@ -671,29 +876,64 @@ export const make = Effect.gen(function* BrowserSessionMake() { ); return; } + if (permission === "media") { + confirmMedia( + webContents, + ("securityOrigin" in details ? details.securityOrigin : undefined) ?? + details.requestingUrl, + "mediaTypes" in details ? details.mediaTypes : undefined, + callback, + ); + return; + } callback(ALLOWED_PREVIEW_PERMISSIONS.has(permission)); }, ); - browserSession.setPermissionCheckHandler((_webContents, permission, requestingOrigin) => - permission === "clipboard-read" || permission === "geolocation" - ? permissionDecisions[permission].get(permissionOrigin(requestingOrigin) ?? "") === - true - : ALLOWED_PREVIEW_PERMISSIONS.has(permission), + browserSession.setPermissionCheckHandler( + (_webContents, permission, requestingOrigin, details) => { + if (permission === "clipboard-read" || permission === "geolocation") { + return ( + permissionDecisions[permission].get(permissionOrigin(requestingOrigin) ?? "") === + true + ); + } + if (permission === "media") { + const origin = permissionOrigin(requestingOrigin); + const device = mediaDeviceFor(details?.mediaType); + return ( + origin !== null && + device !== null && + mediaDecisions.get(mediaKey(origin, device)) === true && + (platform !== "darwin" || + systemPreferences.getMediaAccessStatus(device) === "granted") + ); + } + return ALLOWED_PREVIEW_PERMISSIONS.has(permission); + }, ); + const clientHints = lowEntropyClientHints(process.versions.chrome, platform); + // Electron adds client hints to subresources only; sites that compare them across a session reject navigations without them. browserSession.webRequest.onBeforeSendHeaders( - { urls: TEAMS_URL_PATTERNS }, - ({ requestHeaders }, callback) => { - const userAgent = Object.entries(requestHeaders).find( - ([name]) => name.toLowerCase() === "user-agent", - ); - if (userAgent === undefined) { - callback({}); - return; + { urls: ["http://*/*", "https://*/*"] }, + ({ url, resourceType, requestHeaders }, callback) => { + let next = requestHeaders; + if ( + (resourceType === "mainFrame" || resourceType === "subFrame") && + !Object.keys(requestHeaders).some((name) => name.toLowerCase() === "sec-ch-ua") && + isPotentiallyTrustworthy(url) + ) { + next = { ...next, ...clientHints }; + } + if (isTeamsUrl(url)) { + const userAgent = Object.entries(next).find( + ([name]) => name.toLowerCase() === "user-agent", + ); + if (userAgent !== undefined) { + const [name, value] = userAgent; + next = { ...next, [name]: value.replace(/ Electron\/\S+/, "") }; + } } - const [name, value] = userAgent; - callback({ - requestHeaders: { ...requestHeaders, [name]: value.replace(/ Electron\/\S+/, "") }, - }); + callback(next === requestHeaders ? {} : { requestHeaders: next }); }, ); return browserSession; @@ -727,8 +967,10 @@ export const make = Effect.gen(function* BrowserSessionMake() { getSession, clearCookies: Effect.fn("BrowserSession.clearCookies")(function* (partitions?) { const sessions = yield* SynchronizedRef.get(sessionsRef); + const selected = selectSessions(sessions, partitions); + for (const [, browserSession] of selected) forgetMediaDecisions(browserSession); yield* Effect.forEach( - selectSessions(sessions, partitions), + selected, ([partition, browserSession]) => Effect.gen(function* () { const cleared = yield* Effect.tryPromise({ @@ -758,7 +1000,9 @@ export const make = Effect.gen(function* BrowserSessionMake() { cookiesCleared: Effect.fn("BrowserSession.cookiesCleared")(function* (browserSession) { const sessions = yield* SynchronizedRef.get(sessionsRef); for (const [partition, candidate] of sessions) { - if (candidate === browserSession) yield* revokeCertificates(partition, browserSession); + if (candidate !== browserSession) continue; + forgetMediaDecisions(browserSession); + yield* revokeCertificates(partition, browserSession); } }), clearCache: Effect.fn("BrowserSession.clearCache")(function* (partitions?) { diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 97dc92729d234..1eb6f00da37cb 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -1599,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 f4faa1232d345..b0fe8509a51fa 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -34,6 +34,8 @@ 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"; @@ -57,6 +59,8 @@ 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}`; @@ -499,7 +503,16 @@ export const make = Effect.gen(function* () { // 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) => { + // 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, @@ -507,6 +520,7 @@ export const make = Effect.gen(function* () { params, sessionId, routeMouse, + refuseAnnotated, ); if (method === "Network.clearBrowserCookies") await cookiesCleared?.(); return result; @@ -532,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)) { diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index 878192673d4b8..47941de0bd27d 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -414,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 e163b39cd4c58..6ab33e3896e4e 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -259,15 +259,19 @@ const sendPointerCommand = async ( params: Record, sessionId: string | undefined, route: PointerRoute | undefined, + beforeDispatch: (() => void) | undefined, ) => { const previous = pointerCommands.get(webContents) ?? Promise.resolve(); const current = previous .catch(() => {}) .then(async () => { const routed = route && sessionId === undefined ? await route(params) : null; - const dispatch = routed - ? () => sendToFrame(debuggee, method, routed) - : () => debuggee.sendCommand(method, params, sessionId); + 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(); @@ -280,7 +284,10 @@ 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, @@ -288,12 +295,29 @@ export const sendPageCommand = async ( params: Record, sessionId?: string, routeMouse?: PointerRoute, + beforeDispatch?: () => void, ): Promise => { if (method === "Input.dispatchMouseEvent") { - return sendPointerCommand(webContents, debuggee, method, params, sessionId, routeMouse); + return sendPointerCommand( + webContents, + debuggee, + method, + params, + sessionId, + routeMouse, + beforeDispatch, + ); } if (method === "Input.dispatchTouchEvent") { - return sendPointerCommand(webContents, debuggee, method, params, sessionId, undefined); + 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. @@ -312,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 c8e75e841d7c8..ff5a9fd58d0b5 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -2499,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 9ca560b87e6c3..eaa2f51d52af4 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -2587,6 +2587,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/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index 8c83a8c83ccd0..d250d726e43e0 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -33,6 +33,12 @@ const startAnnotation = (): ShadowRoot => { // jsdom has no popover API. HTMLElement.prototype.showPopover ??= () => {}; HTMLElement.prototype.hidePopover ??= () => {}; + // jsdom has no adoptedStyleSheets. + for (const target of [Document.prototype, ShadowRoot.prototype]) { + if (!("adoptedStyleSheets" in target)) { + Object.defineProperty(target, "adoptedStyleSheets", { value: [], writable: true }); + } + } using attachShadow = vi.spyOn(Element.prototype, "attachShadow"); for (const listener of ipcListeners.get(START_PICK_CHANNEL) ?? []) listener({}, undefined, false); const shadowRoot = attachShadow.mock.results[0]?.value; diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 9c7c2901b1085..a227d5136b6c6 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -578,19 +578,21 @@ function startAnnotation( host.style.cssText = `position:fixed;inset:0;width:auto;height:auto;margin:0;border:0;padding:0;overflow:visible;background:transparent;color:inherit;z-index:${Z_INDEX_OVERLAY};pointer-events:none`; applyAnnotationTheme(host, annotationTheme); const shadowRoot = host.attachShadow({ mode: "closed" }); - const themeStyle = document.createElement("style"); - themeStyle.textContent = previewAnnotationStyles; - shadowRoot.appendChild(themeStyle); + // Constructed sheets are exempt from the page's CSP style-src;
Connecting to WSL…
`; + const message = progress + ? `Upgrading database (${progress.current} of ${progress.total})` + : "Connecting to WSL…"; + const html = `
${message}
`; return `data:text/html;charset=utf-8,${encodeURIComponent(html)}`; } @@ -1153,15 +1164,34 @@ export const make = Effect.gen(function* () { } yield* rendererHistory.register(splash.webContents, { surface: "splash" }); yield* Ref.set(splashWindowRef, Option.some(splash)); + let renderedUrl: string | undefined; + const progressFiber = runFork( + Effect.gen(function* () { + if (splash.isDestroyed() || (yield* Ref.get(desktopState.quitting))) return; + const progress = yield* Ref.get(desktopState.databaseMigrationProgress); + const url = buildConnectingSplashDataUrl(shouldUseDarkColors, progress); + if (url === renderedUrl) return; + const loaded = yield* Effect.promise(() => + splash.loadURL(url).then( + () => true, + () => false, + ), + ); + if (loaded) renderedUrl = url; + }).pipe(Effect.repeat(Schedule.spaced("1 second"))), + ); splash.once("closed", () => { - void runPromise(Ref.set(splashWindowRef, Option.none())); + runFork( + Fiber.interrupt(progressFiber).pipe( + Effect.andThen(Ref.set(splashWindowRef, Option.none())), + ), + ); }); splash.once("ready-to-show", () => { if (!splash.isDestroyed()) { splash.show(); } }); - void splash.loadURL(buildConnectingSplashDataUrl(shouldUseDarkColors)); yield* logWindowInfo("connecting splash shown"); }).pipe( Effect.catch((error) => diff --git a/apps/mobile/assets/file-icons/pierre_csharp.png b/apps/mobile/assets/file-icons/pierre_csharp.png new file mode 100644 index 0000000000000..d2d0db131ec96 Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_csharp.png differ diff --git a/apps/mobile/assets/file-icons/pierre_elixir.png b/apps/mobile/assets/file-icons/pierre_elixir.png new file mode 100644 index 0000000000000..0ec63a24c06f8 Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_elixir.png differ diff --git a/apps/mobile/assets/file-icons/pierre_javascript_test.png b/apps/mobile/assets/file-icons/pierre_javascript_test.png new file mode 100644 index 0000000000000..4e03ab5aa7b61 Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_javascript_test.png differ diff --git a/apps/mobile/assets/file-icons/pierre_kotlin.png b/apps/mobile/assets/file-icons/pierre_kotlin.png new file mode 100644 index 0000000000000..53d84dd47c99e Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_kotlin.png differ diff --git a/apps/mobile/assets/file-icons/pierre_objc.png b/apps/mobile/assets/file-icons/pierre_objc.png new file mode 100644 index 0000000000000..4df8a4b8e1165 Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_objc.png differ diff --git a/apps/mobile/assets/file-icons/pierre_pnpm.png b/apps/mobile/assets/file-icons/pierre_pnpm.png index f5bde9929ff82..11a5cf4ad036b 100644 Binary files a/apps/mobile/assets/file-icons/pierre_pnpm.png and b/apps/mobile/assets/file-icons/pierre_pnpm.png differ diff --git a/apps/mobile/assets/file-icons/pierre_rolldown.png b/apps/mobile/assets/file-icons/pierre_rolldown.png new file mode 100644 index 0000000000000..d91a2d18581fd Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_rolldown.png differ diff --git a/apps/mobile/assets/file-icons/pierre_typescript_test.png b/apps/mobile/assets/file-icons/pierre_typescript_test.png new file mode 100644 index 0000000000000..1615a3a22e670 Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_typescript_test.png differ diff --git a/apps/mobile/assets/file-icons/pierre_vitest.png b/apps/mobile/assets/file-icons/pierre_vitest.png new file mode 100644 index 0000000000000..dfc57b15483a0 Binary files /dev/null and b/apps/mobile/assets/file-icons/pierre_vitest.png differ diff --git a/apps/mobile/deps/README.md b/apps/mobile/deps/README.md index cf18ba81216d9..935cfb387b7ba 100644 --- a/apps/mobile/deps/README.md +++ b/apps/mobile/deps/README.md @@ -16,6 +16,6 @@ Push the commit and tag before submitting the app change, replace the old archiv ## `react-native-enriched-markdown` -Built from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`) and the iOS streaming memory bounds are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), iOS Copy as Markdown keeping bold spans whole ([#1143](https://github.com/software-mansion/enriched-markdown/pull/1143)), line breaks in copied table cells written as `
` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)). It also carries two fork-only changes: iOS code blocks too big for one backing store draw through tiles, so a tall block with long lines no longer shows an empty pane ([pingdotgg/enriched-markdown#15](https://github.com/pingdotgg/enriched-markdown/pull/15)), and a long-pressed iOS blockquote lifts on the background it sits on instead of drawing its text over the thread. +Built from Julius's [`fork/t3-mobile` branch](https://github.com/pingdotgg/enriched-markdown/tree/fork/t3-mobile). Its `t3-fork.json` records the exact source commit and upstream base. React block renderers, signed image sources, the `onLinksChange` link list (`renderers`, `resolveImageSource`, `onLinksChange`), the iOS streaming memory bounds, `onSelectionCopy` and iOS Copy as Markdown keeping bold spans whole are upstream. The fork carries only changes with an open upstream PR: clipboard link metadata ([#962](https://github.com/software-mansion/enriched-markdown/pull/962)), development-host autolinks ([#961](https://github.com/software-mansion/enriched-markdown/pull/961)) and hash-route link fragments ([mity/md4c#454](https://github.com/mity/md4c/pull/454), arriving through [md4c#7](https://github.com/software-mansion-labs/md4c/pull/7)), `md4cFlags.preserveWindowsPaths`, which keeps backslashes in Windows drive paths in prose ([#1105](https://github.com/software-mansion/enriched-markdown/pull/1105), after [mity/md4c#477](https://github.com/mity/md4c/pull/477)), GitHub's strikethrough rules for `~` ([md4c#6](https://github.com/software-mansion-labs/md4c/pull/6)), `\(…\)` and `\[…\]` math delimiters ([#1043](https://github.com/software-mansion/enriched-markdown/pull/1043), [md4c#4](https://github.com/software-mansion-labs/md4c/pull/4)), line breaks in copied table cells written as `
` ([#1144](https://github.com/software-mansion/enriched-markdown/pull/1144)), and Android measuring text in the span order its view draws it, so code blocks nested in list items no longer make a reply overlap the next message ([#1145](https://github.com/software-mansion/enriched-markdown/pull/1145)), iOS code blocks too big for one backing store drawing through tiles, so a tall block with long lines no longer shows an empty pane ([#1231](https://github.com/software-mansion/enriched-markdown/pull/1231)), and a long-pressed iOS blockquote lifting on the background it sits on instead of drawing its text over the thread ([#1232](https://github.com/software-mansion/enriched-markdown/pull/1232)). -To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.18-4287c5d3.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. +To replace it, commit the fork changes, run `yarn install --immutable` and `yarn workspace react-native-enriched-markdown prepare` in the fork checkout, then `node scripts/pack-t3.mjs /path/to/t3code/apps/mobile/deps`. Keep the package version aligned with Julius's `fork/t3-mobile` branch. Rename the archive to include the first eight characters of the source commit, such as `react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz`, so each build has a distinct dependency path without version bumps. Update the tarball path in `apps/mobile/package.json` and `pnpm-workspace.yaml`'s `allowBuilds`, and run `vp i` to update the lockfile. diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz deleted file mode 100644 index 10495faf6f9c2..0000000000000 Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz new file mode 100644 index 0000000000000..2b3b42ae4b7ad Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz deleted file mode 100644 index 57c09a0aecb72..0000000000000 Binary files a/apps/mobile/deps/react-native-screens-5.0.0-t3.61.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-screens-5.0.0-t3.62.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.62.tgz new file mode 100644 index 0000000000000..4743fa5fcb217 Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.62.tgz differ diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt index fdfd144ebb9cc..220ba4a75be51 100644 --- a/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt +++ b/apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt @@ -17,6 +17,7 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.ProcessLifecycleOwner import com.google.firebase.messaging.RemoteMessage import expo.modules.notifications.service.ExpoFirebaseMessagingService +import java.security.MessageDigest class AgentMessagingService : ExpoFirebaseMessagingService() { override fun onMessageReceived(remoteMessage: RemoteMessage) { @@ -120,9 +121,12 @@ object AgentNotifications { fun receive(context: Context, data: Map) { val prefs = context.getSharedPreferences(STORE, Context.MODE_PRIVATE) val updatedAt = data["updated_at"]?.toLongOrNull() ?: return + val deviceId = prefs.getString("deviceId", null) + val userId = prefs.getString("userId", null) val registered = prefs.getBoolean("enabled", false) && - data["device_id"] == prefs.getString("deviceId", null) && - data["user_id"] == prefs.getString("userId", null) + deviceId != null && userId != null && + data["device_id"] == deviceId && + data["user_hash"] == userHash(userId, deviceId) val fresh = System.currentTimeMillis() - updatedAt in -MAX_MESSAGE_AGE_MS..MAX_MESSAGE_AGE_MS if (registered && fresh && NotificationManagerCompat.from(context).areNotificationsEnabled()) { channels(context) @@ -132,6 +136,11 @@ object AgentNotifications { } } + // The relay sends this hash instead of the account id, which FCM would see. + private fun userHash(userId: String, deviceId: String): String = + MessageDigest.getInstance("SHA-256").digest("$userId:$deviceId".toByteArray()) + .joinToString("") { "%02x".format(it) } + private fun showAlert( context: Context, prefs: SharedPreferences, diff --git a/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt b/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt index 41224273d2ec4..eb054f4d484fe 100644 --- a/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt +++ b/apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt @@ -53,7 +53,7 @@ abstract class AgentNotificationsFixture { protected fun update(alertId: String, active: Boolean) = mapOf( "device_id" to "device", - "user_id" to "user", + "user_hash" to "60a4ea94a99303630c40fff23f4de5c06a8f978289a3889f31edfac3b89f85d7", "updated_at" to System.currentTimeMillis().toString(), "active" to active.toString(), "activity_title" to "1 active agent", @@ -664,7 +664,7 @@ class AgentNotificationChannelsTest { AgentNotifications.configure(context, "device", "user", "t3code-dev", true) val running = mapOf( "device_id" to "device", - "user_id" to "user", + "user_hash" to "60a4ea94a99303630c40fff23f4de5c06a8f978289a3889f31edfac3b89f85d7", "updated_at" to System.currentTimeMillis().toString(), "active" to "true", "activity_title" to "Agent activity" diff --git a/apps/mobile/package.json b/apps/mobile/package.json index d86ac2320328b..db02733470750 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -55,11 +55,11 @@ }, "dependencies": { "@clerk/expo": "catalog:", - "@clerk/expo-native-components": "0.4.4", + "@clerk/expo-native-components": "0.4.8", "@effect/atom-react": "catalog:", "@expo-google-fonts/dm-sans": "^0.4.2", "@expo/metro-runtime": "~58.0.17", - "@expo/ui": "58.0.27", + "@expo/ui": "58.0.29", "@formatjs/intl-displaynames": "6.8.13", "@formatjs/intl-getcanonicallocales": "2.5.6", "@formatjs/intl-locale": "4.2.13", @@ -83,61 +83,61 @@ "clsx": "^2.1.1", "diff": "8.0.3", "effect": "catalog:", - "expo": "58.0.23", + "expo": "58.0.26", "expo-application": "~58.1.2", - "expo-asset": "~58.0.20", - "expo-audio": "58.0.11", - "expo-auth-session": "~58.0.17", - "expo-blur": "58.0.5", + "expo-asset": "~58.0.21", + "expo-audio": "58.0.12", + "expo-auth-session": "~58.0.19", + "expo-blur": "58.0.6", "expo-build-properties": "~58.0.12", "expo-camera": "~58.0.14", "expo-clipboard": "~58.0.4", - "expo-constants": "~58.0.15", - "expo-crypto": "~58.0.7", - "expo-dev-client": "~58.0.18", + "expo-constants": "~58.0.16", + "expo-crypto": "~58.0.8", + "expo-dev-client": "~58.0.21", "expo-device": "~58.0.5", - "expo-document-picker": "~58.0.4", - "expo-file-system": "~58.0.13", - "expo-font": "~58.0.11", + "expo-document-picker": "~58.0.5", + "expo-file-system": "~58.0.14", + "expo-font": "~58.0.12", "expo-glass-effect": "58.0.5", - "expo-haptics": "~58.0.7", + "expo-haptics": "~58.0.8", "expo-image": "~58.0.18", "expo-image-manipulator": "~58.0.16", "expo-image-picker": "~58.0.10", - "expo-keep-awake": "~58.0.3", - "expo-linking": "~58.0.16", - "expo-network": "~58.0.4", - "expo-notifications": "~58.1.8", - "expo-observe": "~58.0.18", + "expo-keep-awake": "~58.0.4", + "expo-linking": "~58.0.17", + "expo-network": "~58.0.5", + "expo-notifications": "~58.1.9", + "expo-observe": "~58.0.19", "expo-paste-input": "^0.2.2", "expo-quick-actions": "^6.0.2", - "expo-secure-store": "~58.0.2", - "expo-sensors": "~58.0.4", - "expo-sharing": "58.0.22", - "expo-splash-screen": "~58.0.13", - "expo-sqlite": "~58.0.15", - "expo-symbols": "~58.0.4", - "expo-updates": "~58.0.21", - "expo-video": "58.0.13", - "expo-web-browser": "~58.0.7", - "expo-widgets": "58.0.27", + "expo-secure-store": "~58.0.3", + "expo-sensors": "~58.0.5", + "expo-sharing": "58.0.23", + "expo-splash-screen": "~58.0.14", + "expo-sqlite": "~58.0.18", + "expo-symbols": "~58.0.5", + "expo-updates": "~58.0.22", + "expo-video": "58.0.14", + "expo-web-browser": "~58.1.0", + "expo-widgets": "58.0.29", "gt-react-native": "11.4.18", "pele": "catalog:", "react": "catalog:", "react-dom": "catalog:", "react-native": "0.88.1", - "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz", + "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.19-a01cbf49.tgz", "react-native-gesture-handler": "~3.5.0", "react-native-image-viewing": "^0.2.2", "react-native-keyboard-controller": "1.23.0", "react-native-nitro-modules": "0.37.2", "react-native-pdf-jsi": "6.1.0", - "react-native-reanimated": "4.7.1", + "react-native-reanimated": "4.8.0", "react-native-safe-area-context": "~5.11.1", - "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.61.tgz", + "react-native-screens": "file:deps/react-native-screens-5.0.0-t3.62.tgz", "react-native-svg": "15.16.1", "react-native-webview": "14.0.1", - "react-native-worklets": "0.13.1", + "react-native-worklets": "0.14.0", "remark-gfm": "catalog:", "remark-parse": "catalog:", "tailwind-merge": "^3.5.0", @@ -148,12 +148,12 @@ "@babel/core": "^7.29.7", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", - "@pierre/trees": "1.0.0-beta.6", + "@pierre/trees": "catalog:", "@types/mdast": "^4.0.4", "@types/react": "catalog:", "@types/react-dom": "catalog:", "aws4fetch": "1.0.20", - "babel-preset-expo": "~58.0.24", + "babel-preset-expo": "~58.0.26", "gt": "2.27.0", "jsdom": "^30.0.1", "nitrogen": "0.37.2", @@ -196,7 +196,8 @@ }, "reanimated": { "staticFeatureFlags": { - "DISABLE_COMMIT_PAUSING_MECHANISM": true + "DISABLE_COMMIT_PAUSING_MECHANISM": true, + "ENABLE_SHARED_ELEMENT_TRANSITIONS": false } } } diff --git a/apps/mobile/scripts/sync-pierre-file-icons.mjs b/apps/mobile/scripts/sync-pierre-file-icons.mjs index edb0cb4675923..37f51bb26da99 100644 --- a/apps/mobile/scripts/sync-pierre-file-icons.mjs +++ b/apps/mobile/scripts/sync-pierre-file-icons.mjs @@ -31,10 +31,12 @@ const colors = { c: "#1a85d4", claude: "#d47628", cpp: "#1a85d4", + csharp: "#a631be", css: "#693acf", database: "#a631be", default: "#84848a", docker: "#1a85d4", + elixir: "#a631be", eslint: "#693acf", font: "#84848a", git: "#ff8c5b", @@ -43,16 +45,21 @@ const colors = { html: "#d47628", image: "#d32a61", javascript: "#d5a910", + javascript_test: "#d52c36", json: "#d47628", + kotlin: "#d32a61", markdown: "#199f43", mcp: "#17a5af", nextjs: "#84848a", npm: "#d52c36", + objc: "#d5512f", oxc: "#1ca1c7", + pnpm: "#d47628", postcss: "#d52c36", prettier: "#17a5af", python: "#1a85d4", react: "#1ca1c7", + rolldown: "#d5512f", ruby: "#d52c36", rust: "#d47628", sass: "#d32a61", @@ -66,8 +73,10 @@ const colors = { terraform: "#693acf", text: "#84848a", typescript: "#1a85d4", + typescript_test: "#d52c36", video: "#a631be", vite: "#a631be", + vitest: "#199f43", vscode: "#1a85d4", vue: "#199f43", wasm: "#693acf", @@ -79,8 +88,16 @@ const colors = { const customIcons = { agents: "t3-file-icon-agents", + csharp: "t3-file-icon-csharp", + elixir: "t3-file-icon-elixir", + javascript_test: "t3-file-icon-javascript-test", + kotlin: "t3-file-icon-kotlin", + objc: "t3-file-icon-objc", pnpm: "t3-file-icon-pnpm", + rolldown: "t3-file-icon-rolldown", + typescript_test: "t3-file-icon-typescript-test", video: "t3-file-icon-video", + vitest: "t3-file-icon-vitest", }; function symbolFromSprite(sprite, id) { diff --git a/apps/mobile/src/connection/environment-owned-data-cleanup.ts b/apps/mobile/src/connection/environment-owned-data-cleanup.ts index 28c6cda29a4d3..a41581b08c2d5 100644 --- a/apps/mobile/src/connection/environment-owned-data-cleanup.ts +++ b/apps/mobile/src/connection/environment-owned-data-cleanup.ts @@ -8,6 +8,7 @@ import * as Schema from "effect/Schema"; import { clearThreadComposerErrorsForEnvironment } from "../state/thread-composer-error"; import { clearThreadOutboxEnvironment } from "../state/thread-outbox-removal"; import { clearComposerDraftsEnvironment } from "../state/use-composer-drafts"; +import { mobileThreadTriageOutboxStore } from "../state/thread-triage-outbox-storage"; class EnvironmentOwnedDataClearError extends Schema.TaggedError()( "EnvironmentOwnedDataClearError", @@ -40,6 +41,7 @@ export const layer = Layer.succeed( settle("outbox", clearThreadOutboxEnvironment), settle("drafts", clearComposerDraftsEnvironment), Effect.sync(() => clearThreadComposerErrorsForEnvironment(environmentId)), + Effect.ignore(mobileThreadTriageOutboxStore.clearEnvironment(environmentId)), ], { concurrency: "unbounded", discard: true }, ); diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index 12d6bafe7c953..0ed1a8fa0b8e0 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -190,9 +190,8 @@ const layerCapabilities = Layer.effectContext( bearerToken: Effect.succeedNone, }), ), - // The relay device id already persists in secure storage; analytics only sends its hash. Context.add(ClientCapabilities.AnalyticsDevice, { - id: storage.loadOrCreateAgentAwarenessDeviceId.pipe(Effect.option), + id: storage.loadOrCreateAnalyticsDeviceId.pipe(Effect.option), }), Context.add( ClientCapabilities.RelayDeviceIdentity, diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.ts index 91a6ac71919da..b412fadede0d9 100644 --- a/apps/mobile/src/connection/storage.ts +++ b/apps/mobile/src/connection/storage.ts @@ -7,6 +7,7 @@ import { removeCatalogValue, replaceCatalogValue, Persistence, + ThreadTriageOutboxStore, } from "@t3tools/client-runtime/platform"; import { TokenStore } from "@t3tools/client-runtime/authorization"; import { @@ -21,6 +22,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import { mobileThreadTriageOutboxStore } from "../state/thread-triage-outbox-storage"; import * as CatalogStore from "./catalog-store"; function targetPersistenceError( @@ -164,6 +166,7 @@ export const layer = Layer.effectContext( Context.add(ProfileStore.ConnectionProfileStore, profileStore), Context.add(CredentialStore.ConnectionCredentialStore, credentialStore), Context.add(TokenStore.RemoteDpopAccessTokenStore, remoteTokenStore), + Context.add(ThreadTriageOutboxStore, mobileThreadTriageOutboxStore), ); }), ); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index 5f5a46b653b1b..54048d0234a8d 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -239,6 +239,7 @@ const layerPersistenceTest = Layer.merge( try: () => loadOrCreateAgentAwarenessDeviceId(), catch: storageFailure, }), + loadOrCreateAnalyticsDeviceId: Effect.succeed("analytics-device-1"), loadAgentAwarenessDeviceId: Effect.tryPromise({ try: () => loadAgentAwarenessDeviceId(), catch: storageFailure, 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/cloud/ConnectOnboardingRouteScreen.tsx b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx index ce1461f905eb1..a48b237880906 100644 --- a/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx +++ b/apps/mobile/src/features/cloud/ConnectOnboardingRouteScreen.tsx @@ -16,6 +16,10 @@ import { useRemoteConnections } from "../../state/use-remote-environment-registr import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows"; import { splitEnvironmentSections } from "../connection/environmentSections"; import { useConnectionController } from "../connection/useConnectionController"; +import { + ConnectionTracesSwitch, + connectionTracesAvailable, +} from "../observability/ConnectionTracesSwitch"; import { optOutOfConnectOnboarding } from "./connectOnboardingOptOut"; import { hasCloudPublicConfig } from "./publicConfig"; @@ -99,6 +103,19 @@ function ConfiguredConnectOnboardingRouteScreen() { )} + {isSignedIn && connectionTracesAvailable ? ( + + + + + + {gt( + "Helps the T3 Code team fix connection problems. Traces hold timings, error types, an ID for this app session, and the app version, never your threads, prompts, or code. You can change this in Settings > About T3 Code > Diagnostics.", + )} + + + ) : null} + {userId ? ( ; await using screen = await render(opener, { router: "/" }); @@ -67,4 +96,45 @@ describe("AppRouteModal", () => { await expect.element(settings).toHaveAttribute("data-open"); }); + + it("stays open when a held Esc repeats after closing a nested menu", async () => { + await using _screen = await render( + + + All providers + + Claude + + + , + { router: "/usage" }, + ); + const usage = page.getByRole("dialog", { name: "Usage" }); + const trigger = page.getByRole("button", { name: "All providers" }); + await expect.element(usage).toHaveFocus(); + + (trigger.element() as HTMLElement).focus(); + await userEvent.keyboard("{Enter}"); + await expect.element(page.getByRole("menu")).toBeVisible(); + + await userEvent.keyboard("{Escape}"); + await expect.element(page.getByRole("menu")).not.toBeInTheDocument(); + await expect.element(trigger).toHaveFocus(); + await expect.element(usage).toHaveAttribute("data-open"); + + await act(() => + trigger.element().dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + repeat: true, + bubbles: true, + cancelable: true, + }), + ), + ); + await expect.element(usage).toHaveAttribute("data-open"); + + await userEvent.keyboard("{Escape}"); + await expect.element(usage).not.toBeInTheDocument(); + }); }); diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 1414b198afdc4..bebaadad55055 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -1,7 +1,15 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; -import { useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { useRouter } from "@tanstack/react-router"; +import { + useEffect, + useRef, + useState, + type CSSProperties, + type ReactNode, + type RefObject, +} from "react"; import { getCommandPaletteOpener } from "../commandPaletteStore"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; @@ -17,7 +25,15 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; * backdrop returns to the page that opened it. Keyboard guards that skip dialogs exempt * `[data-app-modal]`, because these pages own their shortcuts. */ -export function AppRouteModal({ label, children }: { label: string; children: ReactNode }) { +export function AppRouteModal({ + label, + actionsRef, + children, +}: { + label: string; + actionsRef?: RefObject; + children: ReactNode; +}) { const closeAppModal = useCloseAppModal(); const [open, setOpen] = useState(true); // Text selection that ends on the backdrop is not a dismissal. @@ -35,14 +51,35 @@ export function AppRouteModal({ label, children }: { label: string; children: Re // buttons). Below sm the modal fills the window and leaves that strip empty; up to lg its // 1.5rem inset is shorter than the strip. const nativeTitlebarHeight = useNativeTitlebarHeight(); + const router = useRouter(); + // Leaving the page without closing (Navigation: Back) unmounts a focused field during a + // commit, when React no longer delivers its blur, so commit-on-blur rows would drop what was + // typed. Blur text fields before the navigation renders; other controls keep their focus. + // Not onBeforeNavigate: the router skips it while a past redirect is still recorded. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- router listener that blurs a field before navigation unmounts it + useEffect( + () => + router.subscribe("onBeforeLoad", ({ pathChanged }) => { + const focused = document.activeElement; + if (pathChanged && focused?.matches("input, textarea, [contenteditable]")) { + blurFocusedWithin(popupRef.current); + } + }), + [router], + ); return ( { if (nextOpen) return; + // Base UI's dismiss handler fires on held Esc repeats after a nested popup closes. + if (eventDetails.reason === "escape-key" && eventDetails.event.repeat) { + return eventDetails.cancel(); + } // Esc from a layer outside Base UI (Clerk's modals) is that layer's to handle. const target = eventDetails.event.target; if ( @@ -55,8 +92,7 @@ export function AppRouteModal({ label, children }: { label: string; children: Re } // Closing unmounts a focused field without a blur, so commit-on-blur rows would // drop what was typed. Blur first so they commit. - const focused = document.activeElement; - if (focused instanceof HTMLElement && popupRef.current?.contains(focused)) focused.blur(); + blurFocusedWithin(popupRef.current); setOpen(false); }} onOpenChangeComplete={(nextOpen) => { @@ -116,6 +152,11 @@ export function AppRouteModal({ label, children }: { label: string; children: Re ); } +function blurFocusedWithin(container: HTMLElement | null) { + const focused = document.activeElement; + if (focused instanceof HTMLElement && container?.contains(focused)) focused.blur(); +} + export function AppRouteModalClose() { const gt = useGT(); return ( diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index bbbeb3553c56d..d5a6e9b9fb6f9 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -507,6 +507,7 @@ export function AppSidebarLayout({ role="navigation" aria-label={gt("Threads")} resizable={{ + collapseOnResize: true, maxWidth: sidebarMaximumWidth, minWidth: sidebarMinimumWidth, shouldAcceptWidth: ({ currentWidth, nextWidth, wrapper }) => diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index 05e49aa667b88..d7d238ae5ca42 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -168,6 +168,12 @@ describe("deriveLocalBranchNameFromRemoteRef", () => { "upstream/feature/demo", ); }); + + it("strips the whole remote name when it is known", () => { + expect(deriveLocalBranchNameFromRemoteRef("team/origin/feature", "team/origin")).toBe( + "feature", + ); + }); }); describe("dedupeRemoteBranchesWithLocalMatches", () => { diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index ffdc526787394..432c421bb9920 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -508,7 +508,7 @@ export function BranchToolbarBranchSelector({ } const selectedBranchName = refName.isRemote - ? deriveLocalBranchNameFromRemoteRef(refName.name) + ? deriveLocalBranchNameFromRemoteRef(refName.name, refName.remoteName) : refName.name; runBranchAction(async () => { diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 13e7214751bd5..2d1c270e585d2 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -157,7 +157,7 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async url: "https://linear.app/example/issue/WEB-123/add-keyboard-support", source: "manual", linkedAt: "2026-01-01T00:00:00.000Z", - displayKey: issueRef.key, + displayKey: "#123", title: "Add keyboard support", }; const completed = { @@ -170,7 +170,22 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async const grouped = threadWithHistory("issue-grouped", 1); using _environment = installFakeEnvironment([ first, - { ...linked, issues: [issue] }, + { + ...linked, + issues: [issue], + pullRequests: [ + { + host: "github.com", + repository: "pingdotgg/t3code", + number: 124, + url: "https://github.com/pingdotgg/t3code/pull/124", + source: "manual", + linkedAt: "2026-01-01T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ], + }, { ...grouped, issues: [completed, issue] }, ]); const liveTitle = "Add keyboard shortcuts to the sidebar"; @@ -237,10 +252,21 @@ it("opens a linked Linear issue from an inactive thread's sidebar badge", async name: `Issue ${issue.displayKey}: ${issue.title}, Open`, }); await expect.element(badge).toBeVisible(); - expect(badge.element().querySelector("svg")).toHaveClass(/text-emerald-600/); + expect(badge.element().querySelector("span")).toHaveClass(/text-emerald-600/); + expect(badge.element()).toHaveTextContent("123"); + expect(badge.element()).not.toHaveTextContent("#"); + const prBadge = page.getByRole("link", { name: "PR #124, status pending" }); + await expect.element(prBadge).toHaveTextContent("124"); + for (const control of [badge, prBadge]) { + expect(control.element().querySelector("span")).toHaveClass( + "contents", + "text-xs", + "tabular-nums", + ); + } const groupedBadge = page.getByRole("button", { name: "2 linked issues" }); await vi.waitFor(() => - expect(groupedBadge.element().querySelector("svg")).toHaveClass(/text-emerald-600/), + expect(groupedBadge.element().querySelector("span")).toHaveClass(/text-emerald-600/), ); await userEvent.hover(badge); const issueName = `Issue ${issue.displayKey}: ${liveTitle}`; @@ -1090,3 +1116,44 @@ it("/side sends the draft's attachments and context, and keeps them when it does ]), ); }); + +it("opening Settings without a page event closes the composer model picker and permissions menu", async () => { + using _environment = installFakeEnvironment([]); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const draftId = DraftId.make("draft-29219"); + useComposerDraftStore + .getState() + .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { + threadId: ThreadId.make("thread-29219"), + }); + + const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] })); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + await expect.element(page.getByTestId("composer-editor")).toBeVisible(); + const trigger = document.querySelector("[data-chat-provider-model-picker]"); + if (!trigger) throw new Error("composer model picker trigger missing"); + await userEvent.click(trigger); + const search = page.getByPlaceholder("Search models..."); + await expect.element(search).toBeVisible(); + + // The desktop menu's open-settings accelerator navigates with no key or pointer event in the page. + await act(() => router.navigate({ to: "/settings" })); + await expect.element(page.getByRole("dialog", { name: "Settings" })).toBeVisible(); + await expect.element(search).not.toBeInTheDocument(); + + await act(() => router.navigate({ to: "/draft/$draftId", params: { draftId } })); + await page.getByRole("button", { name: /^Permissions: / }).click(); + // The modal Settings dialog aria-hides everything outside it, so match text, not role. + const permissions = page.getByText("Allow commands and edits without prompts.").last(); + await expect.element(permissions).toBeVisible(); + await act(() => router.navigate({ to: "/settings" })); + await expect.element(page.getByRole("dialog", { name: "Settings" })).toBeVisible(); + await expect.element(permissions).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 971fbbb6eb33f..2d58d3512e871 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -98,6 +98,7 @@ import { deriveRunlessWorkStartedAt, deriveThreadActivityRun, deriveLatestThreadRun, + presentProviderStarting, deriveThreadStructureRuntime, limitRecoveryOwnsSnooze, } from "@t3tools/client-runtime/state/thread-execution"; @@ -106,7 +107,6 @@ import { workflowOpeningParentThreadId, } from "@t3tools/client-runtime/state/subagentRuntime"; import { - getUserQueuedThreadRuns, threadCanSteer, threadSupportsProviderHandoff, } from "@t3tools/client-runtime/state/thread-workflows"; @@ -133,6 +133,7 @@ import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabelsCopy"; import { useAtomValue } from "@effect/atom-react"; import { + type CSSProperties, type MouseEvent as ReactMouseEvent, type SetStateAction, use, @@ -395,12 +396,19 @@ import { useWorkAreaChat } from "../fork/workArea/useWorkAreaChat"; import { terminalTabShown } from "../fork/workArea/drawerTerminals"; import { closeFocusedTab } from "../fork/workArea/workAreaCommands"; import { useChatViewOpener } from "../fork/workArea/chatFileOpener"; +import { findHasNoBar, registerFindBar } from "../fork/workArea/hostedChatFind"; import { ChatOpenScope } from "../fork/workArea/ChatOpenScope"; import { openThreadTab } from "../fork/workArea/chatOpenerContext"; import { useModeSurfaceActions } from "../fork/dashboard/dashboardSurface"; -import { REPLY_BOX_QUEUE_EDIT_BLOCKED, subThreadDraftId } from "../fork/subThreads/subThreadReply"; +import { subThreadDraftId } from "../fork/subThreads/subThreadReply"; import { useSubThreadCite } from "../fork/subThreads/subThreadCite"; import { SubThreadViewContext } from "../fork/subThreads/subThreadsState"; +import { + QUEUE_EDIT_OPEN_ELSEWHERE, + useGuestMessagesInView, + useQueuedRunsInView, + useQueueShortcutLabels, +} from "../fork/subThreads/queuedRunsScope"; import { useThreadShownView } from "../fork/displayMode/threadView"; import { ChatWorkingIndicator } from "../fork/displayMode/ChatWorkingIndicator"; import { @@ -428,6 +436,13 @@ import { } from "./ChatView.logic"; const EMPTY_PROVIDERS: ServerProvider[] = []; +const ACTIVE_RUN_STATUSES: ReadonlySet = new Set([ + "preparing", + "queued", + "starting", + "running", + "waiting", +]); const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = []; const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = []; import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates"; @@ -556,12 +571,14 @@ export default function ChatView(props: ChatViewProps) { const promptRef = useRef(""); const localComposerRef = useRef(null); const composerRef = useComposerHandleContext() ?? localComposerRef; + const queuedRunsInView = useQueuedRunsInView(routeThreadDetailRef, serverProjection); const queuedRunEdit = useQueuedRunEdit({ environmentId, routeThreadRef, threadDraftTarget: baseComposerDraftTarget, - activeThreadId: - (serverThread !== null || draftThread !== null) && subThreadDraft === null ? threadId : null, + activeThreadId: serverThread !== null || draftThread !== null ? threadId : null, + ownsEdit: queuedRunsInView.ownsEdit, + recoveryTarget: queuedRunsInView.recoveryTarget, serverProjection, promptRef, composerRef, @@ -864,7 +881,14 @@ export default function ChatView(props: ChatViewProps) { const serverLatestRun = serverProjection === null ? null : deriveLatestThreadRun(serverProjection); const serverActivityRun = - serverProjection === null ? null : deriveThreadActivityRun(serverProjection); + serverProjection === null + ? null + : deriveThreadActivityRun( + serverProjection, + serverThread === null + ? undefined + : providersByEnvironment.get(serverThread.environmentId), + ); const serverRuntime = serverProjection === null ? null : deriveThreadStructureRuntime(serverProjection); const runlessWorkStartedAt = @@ -1573,6 +1597,18 @@ export default function ChatView(props: ChatViewProps) { const activeWorkStartedAt = deriveActiveWorkStartedAt(activeActivityRun, activeRuntime, localDispatchStartedAt) ?? runlessWorkStartedAt; + // Until the server has the run, a send shows the provider it is starting, not the thinking brain. + const providerStartingRun = + activeActivityRun?.providerStartingLabelMsg !== undefined + ? activeActivityRun + : isSendBusy && + selectedProviderEntry !== undefined && + (activeActivityRun === null || !ACTIVE_RUN_STATUSES.has(activeActivityRun.status)) + ? presentProviderStarting({ + instanceId: selectedProviderEntry.instanceId, + driver: selectedProviderEntry.driverKind, + }) + : null; const activeRunPreparing = activeActivityRun?.status === "preparing"; const sendQueuesBehindSetup = isServerThread && (activeRunPreparing || activeActivityRun?.status === "starting"); @@ -2878,6 +2914,14 @@ export default function ChatView(props: ChatViewProps) { const threadFindEnabled = isServerThread && serverConfig?.threadFind === true; const isThreadFindActive = useThreadFindOpen(activeThreadRef, threadFindEnabled) && subThreadDraft === null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- counts the chats that show this thread's Find bar, so Find closes with the last one + useEffect( + () => + subThreadDraft === null && activeThreadKey !== null + ? registerFindBar(activeThreadKey) + : undefined, + [subThreadDraft, activeThreadKey], + ); const openThreadFindStable = useStableCallback((threadRef: ScopedThreadRef) => { if (threadFindEnabled && scopedThreadKey(threadRef) === activeThreadKey) { openThreadFind(activeThreadKey); @@ -2908,6 +2952,7 @@ export default function ChatView(props: ChatViewProps) { "chat.find": () => { if (!isServerThread || serverConfig?.threadFind !== true || activeThreadKey === null) return false; + if (subThreadDraft !== null && findHasNoBar(activeThreadKey)) return false; openThreadFind(activeThreadKey); }, "composer.cycleHost": ({ event }) => { @@ -3175,7 +3220,7 @@ export default function ChatView(props: ChatViewProps) { const onComposerCompactContextStable = useStableCallback(onCompactContext); // Read from the projection the footer renders, so the scroll below sees the new message. const pendingGuestMessageIds = - serverProjection?.thread.guestShare?.messages.flatMap((message) => + useGuestMessagesInView(serverProjection?.thread.guestShare?.messages)?.flatMap((message) => message.status === "pending" ? [message.id] : [], ) ?? []; const pendingGuestMessageCount = pendingGuestMessageIds.length; @@ -3206,28 +3251,25 @@ export default function ChatView(props: ChatViewProps) { openExpandedImagePreview(routeThreadKey, preview); }; const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); + const queueShortcutLabels = useQueueShortcutLabels(keybindings); const queuedRunsControl = isServerThread && activeThread ? ( <> { }), ); }); + + it("leaves a submenu only on a fresh, unmodified Backspace", async () => { + setup({ projects: [makeProject("Acme"), makeProject("Beta")] }); + await using _screen = await render({null}); + + openCommandPalette({}); + const rootInput = page.getByPlaceholder("Search commands, projects, and threads..."); + await expect.element(rootInput).toHaveFocus(); + await userEvent.keyboard("{ArrowDown}"); + await expect + .element(page.getByRole("option", { name: /^New thread in\.\.\./ })) + .toHaveAttribute("data-highlighted"); + await userEvent.keyboard("{Enter}"); + + const submenuInput = page.getByPlaceholder("Search..."); + await expect.element(submenuInput).toHaveFocus(); + + for (const init of [ + { repeat: true }, + { ctrlKey: true }, + { isComposing: true }, + ] satisfies ReadonlyArray) { + const event = new KeyboardEvent("keydown", { + key: "Backspace", + bubbles: true, + cancelable: true, + ...init, + }); + await act(() => submenuInput.element().dispatchEvent(event)); + expect(event.defaultPrevented).toBe(false); + await expect.element(submenuInput).toBeVisible(); + } + + await userEvent.keyboard("{Backspace}"); + await expect.element(rootInput).toHaveFocus(); + }); + + it("ignores repeated Escape keydowns after stepping back from file search", async () => { + setup(); + await using _screen = await render({null}); + + openCommandPalette({}); + const palette = page.getByTestId("command-palette"); + await expect.element(palette).toHaveAttribute("data-palette-mode", "command"); + + await act(() => { + dispatchCommandPalette({ + _tag: "OpenChildSearch", + mode: "files", + context: { query: "", linkedThreadSearch: null }, + }); + }); + await expect.element(palette).toHaveAttribute("data-palette-mode", "files"); + + await userEvent.keyboard("{Escape}"); + await expect.element(palette).toHaveAttribute("data-palette-mode", "command"); + await expect + .element(page.getByPlaceholder("Search commands, projects, and threads...")) + .toHaveFocus(); + + await act(() => { + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + repeat: true, + bubbles: true, + cancelable: true, + }), + ); + }); + expect(useCommandPaletteStore.getState().open).toBe(true); + await expect.element(palette).toHaveAttribute("data-palette-mode", "command"); + + await userEvent.keyboard("{Escape}"); + await expect.element(palette).not.toBeInTheDocument(); + }); }); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 4610ef7542890..eef8e844f0fed 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -342,6 +342,11 @@ export function CommandPalette({ children }: { children: ReactNode }) { { + // Held Escape emits repeat keydowns; only a fresh press should step back or close. + if (!open && eventDetails.reason === "escape-key" && eventDetails.event.repeat) { + eventDetails.cancel(); + return; + } if (!open && eventDetails.reason === "escape-key" && state.mode !== "command") { eventDetails.cancel(); dispatchCommandPalette({ _tag: "BackToCommand" }); @@ -843,7 +848,6 @@ function OpenCommandPaletteDialog(props: { ), ) : null; - // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) const now = new Date().toISOString(); const openableThreads = threads.filter( (thread) => thread.settledOverride !== "settled" && !effectiveSnoozed(thread, { now }), @@ -2345,7 +2349,6 @@ function OpenCommandPaletteDialog(props: { input: { projectId: newProjectId(), title: inferProjectTitleFromPath(destinationPath), - // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) createdAt: new Date().toISOString(), remoteUrl: addProjectCloneFlow.remoteUrl, destinationPath, @@ -2787,14 +2790,21 @@ function OpenCommandPaletteDialog(props: { return; } - if (event.key === "Backspace" && query === "" && isSubmenu) { + if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return; + + if ( + event.key === "Backspace" && + query === "" && + isSubmenu && + !event.repeat && + !event.nativeEvent.isComposing && + event.keyCode !== 229 + ) { event.preventDefault(); popView(); return; } - if (event.ctrlKey || event.shiftKey || event.altKey || event.metaKey) return; - if (event.key === "Tab" && isBrowsing && !relativePathNeedsActiveProject) { if (event.nativeEvent.isComposing || event.keyCode === 229) return; (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); diff --git a/apps/web/src/components/CommandPaletteThreadItems.tsx b/apps/web/src/components/CommandPaletteThreadItems.tsx index 48b9acfd2776c..1ec16a828c543 100644 --- a/apps/web/src/components/CommandPaletteThreadItems.tsx +++ b/apps/web/src/components/CommandPaletteThreadItems.tsx @@ -172,7 +172,6 @@ export function useCommandPaletteThreadItems(input: { const isOpen = activeThread?.environmentId === thread.environmentId && activeThread.id === thread.id; if (threadSearchQuery.trim().length > 0 && !threadSearchQuery.startsWith(">") && !isOpen) { - // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) claimThreadOpen(thread.environmentId, thread.id, Date.now()); } if ( diff --git a/apps/web/src/components/ComposerContextPermissions.tsx b/apps/web/src/components/ComposerContextPermissions.tsx index deaa59662f1d7..b6228ccdca805 100644 --- a/apps/web/src/components/ComposerContextPermissions.tsx +++ b/apps/web/src/components/ComposerContextPermissions.tsx @@ -1,13 +1,16 @@ import type { EnvironmentId, RuntimeMode } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; +import { use } from "react"; import { T, useGT, useMessages } from "gt-react"; import { shortcutLabelForCommand } from "../keybindings"; import { useManagedPolicy } from "../state/managedPolicy"; import { primaryServerKeybindingsAtom } from "../state/server"; +import { HiddenThreadContext } from "./chat/backgroundThread"; import { ComposerControl } from "./chat/ComposerControl"; import { ComposerPermissionsSection } from "./chat/ComposerFooterControls"; import { useComposerMenuProps } from "./chat/composerEventScope"; +import { useComposerMenuState } from "./chat/useComposerMenuState"; import { resolveCompatibleRuntimeMode, resolveRuntimeModeOptions, @@ -35,10 +38,11 @@ export function ComposerContextPermissions(props: { ); const options = resolveRuntimeModeOptions(modes, useManagedPolicy(props.environmentId), messages); const composerMenuProps = useComposerMenuProps(); + const [open, setOpen] = useComposerMenuState(use(HiddenThreadContext)); const { icon: Icon } = runtimeModeConfig[mode]; const label = messages(runtimeModeConfig[mode].label); return ( - + - environment.connection.phase === "connected" && - environment.serverConfig?.settings.requireConnectDeviceApproval === true ? ( - ) : null, ); } -function EnvironmentConnectDeviceRequests(props: { +function EnvironmentConnectDevices({ + approvalRequired, + ...props +}: { readonly environmentId: EnvironmentId; readonly environmentLabel: string; + readonly approvalRequired: boolean; }) { const canApprove = useEnvironmentScope(props.environmentId, AuthAccessWriteScope); - return canApprove ? : null; + if (!canApprove) return null; + return ( + <> + {approvalRequired ? : null} + + + ); +} + +const CONNECT_DEVICES_SEEN_KEY = "t3code:connect-devices-seen-through"; +const ConnectDevicesSeenThrough = Schema.Record(Schema.String, Schema.Number); + +/** Devices approved by hand are already known, so only `announce` hosts that skip approval. */ +function NewConnectDeviceToast({ + environmentId, + environmentLabel, + announce, +}: { + readonly environmentId: EnvironmentId; + readonly environmentLabel: string; + readonly announce: boolean; +}) { + const navigate = useNavigate(); + const access = useEnvironmentQuery(authEnvironment.accessChanges({ environmentId, input: null })); + // Older servers omit the list. + const devices = + access.data?.type === "snapshot" ? (access.data.payload.connectDevices ?? null) : null; + const shown = useRef<{ toastId: string; renderedKey: string } | null>(null); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens, updates and closes an imperative toastManager toast to match devices this client has not announced + useEffect(() => { + if (devices === null) return; + const seenThrough = readLocalStorageValue( + CONNECT_DEVICES_SEEN_KEY, + {}, + ConnectDevicesSeenThrough, + )[environmentId]; + const { unseen, newest } = unseenConnectDevices(devices, seenThrough); + const markSeen = () => + writeLocalStorageValue( + CONNECT_DEVICES_SEEN_KEY, + (current) => ({ + ...current, + [environmentId]: Math.max(current[environmentId] ?? 0, newest), + }), + {}, + ConnectDevicesSeenThrough, + ); + const close = () => { + if (shown.current) toastManager.close(shown.current.toastId); + shown.current = null; + }; + if (!announce || unseen.length === 0) { + close(); + if (seenThrough !== newest) markSeen(); + return; + } + const renderedKey = unseen.map((device) => device.proofKeyThumbprint).join(","); + if (shown.current?.renderedKey === renderedKey) return; + const [first] = unseen; + const options = stackedThreadToast({ + type: "warning", + title: m(msg("New device signed in to {environmentLabel}", { environmentLabel })), + description: + unseen.length === 1 && first + ? m( + msg("{device} connected through {product}. Not you? Review it.", { + device: describeConnectDeviceClient(first), + product: "T3 Connect", + }), + ) + : m( + msg( + "{count, plural, one {{count} device} other {{count} devices}} connected through {product}. Not you? Review them.", + { count: unseen.length, product: "T3 Connect" }, + ), + ), + timeout: 0, + actionProps: { + children: m(msg("Review", { $context: "verb, opens the device in settings" })), + onClick: () => { + markSeen(); + close(); + void navigate({ to: "/settings/access", search: { machine: environmentId } }); + }, + }, + data: { + hideCopyButton: true, + onClose: () => { + markSeen(); + // A dismissed toast is gone, so the next unseen device needs a new one. + if (shown.current?.renderedKey === renderedKey) shown.current = null; + }, + }, + }); + if (shown.current) { + toastManager.update(shown.current.toastId, options); + shown.current = { toastId: shown.current.toastId, renderedKey }; + } else { + shown.current = { toastId: toastManager.add(options), renderedKey }; + } + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes this environment's imperative toast when it goes away + useEffect( + () => () => { + if (shown.current) toastManager.close(shown.current.toastId); + }, + [], + ); + + return null; } /** Reports a failed command and says whether it failed, so its request can be offered again. */ diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 1c42f176d89b4..a7ab96d584a26 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -380,17 +380,12 @@ function GitActionProgressButtonContent({ role="status" >