diff --git a/.github/scripts/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs index 35d0c5bf56e73..5bebcb5202b91 100644 --- a/.github/scripts/workflow-credentials.test.cjs +++ b/.github/scripts/workflow-credentials.test.cjs @@ -226,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 = {}; diff --git a/.github/workflows/deploy-relay.yml b/.github/workflows/deploy-relay.yml index bbe7054666b7e..df54074cd15ae 100644 --- a/.github/workflows/deploy-relay.yml +++ b/.github/workflows/deploy-relay.yml @@ -80,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/mobile-eas-preview-fork.yml b/.github/workflows/mobile-eas-preview-fork.yml index 2953ac50b06bb..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,17 +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: read outputs: client: ${{ steps.build.outputs.link }} env: @@ -254,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. @@ -301,12 +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: read outputs: client: ${{ steps.build.outputs.link }} env: @@ -315,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. @@ -362,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: @@ -381,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/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 a81f877e69ddd..c8b067e7637dd 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -15,6 +15,17 @@ on: permissions: contents: read +# 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: name: Collect PR targets @@ -74,9 +85,6 @@ jobs: permissions: contents: read pull-requests: write - concurrency: - group: pr-vouch-${{ matrix.target.number }} - cancel-in-progress: true strategy: fail-fast: false matrix: 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/apps/desktop/package.json b/apps/desktop/package.json index 3a103c24a87ce..83a37e48eb626 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.118", + "version": "0.0.119", "private": true, "type": "module", "main": "dist-electron/boot.cjs", 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.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index b3f82e518af2e..29869e3beb144 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -94,6 +94,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", + "DO_NOT_TRACK", "T3CODE_FEATURE_FLAGS", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index ff9bd656d2f1c..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)); @@ -818,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<{ @@ -852,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), }); @@ -864,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( @@ -879,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, }), ), ), @@ -887,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)); @@ -894,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)); @@ -902,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), @@ -928,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 abc1238387682..bcbd3b486bfe9 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"; @@ -278,6 +282,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 { @@ -742,6 +749,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(); @@ -968,6 +976,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) { @@ -1012,6 +1022,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}`, @@ -1042,6 +1054,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 && @@ -1056,7 +1070,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, }); @@ -1072,12 +1089,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 114e3e83590ed..001fbd3600722 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -46,6 +46,7 @@ import { } from "./methods/updates.ts"; import { getAppBranding, + getDatabaseMigrationProgress, getLocalEnvironmentBootstraps, getLocalEnvironmentBearerToken, installRelayTelemetryEnabled, @@ -116,6 +117,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 da94d64fdc2cc..9da1b687c69ca 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 dc7152b3828ab..e02b682fb78fe 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/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 ba348a9c1c6ff..4cc0e23d19ea2 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -584,19 +584,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.63.tgz b/apps/mobile/deps/react-native-screens-5.0.0-t3.63.tgz new file mode 100644 index 0000000000000..2e187642ab7af Binary files /dev/null and b/apps/mobile/deps/react-native-screens-5.0.0-t3.63.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 94ee01c7f5581..d693fbf36212d 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -55,7 +55,7 @@ }, "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", @@ -126,18 +126,18 @@ "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.63.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,7 +148,7 @@ "@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:", @@ -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/PreviewStreamWebView.tsx b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx index 63de59e81096f..ca02e229a097a 100644 --- a/apps/mobile/src/features/browser/PreviewStreamWebView.tsx +++ b/apps/mobile/src/features/browser/PreviewStreamWebView.tsx @@ -10,6 +10,7 @@ import { type PreviewStreamDownload, type PreviewStreamFileChooser, type PreviewStreamInput, + type PreviewStreamSelectMenu, } from "@t3tools/client-runtime/preview/server-browser-stream"; import type { EnvironmentId, PreviewStreamHostSetup } from "@t3tools/contracts"; import { @@ -22,10 +23,13 @@ import { } from "react"; import { msg, useGT, useMessages } from "gt-react-native"; import { Platform, Pressable, TextInput, View } from "react-native"; +import { LegendList } from "@legendapp/list/react-native"; import { WebView } from "react-native-webview"; import * as Clipboard from "expo-clipboard"; import { AppText } from "../../components/ui/AppText"; +import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; +import { Sheet } from "../../components/ui/Sheet"; import { PdfPreview } from "../../components/PdfPreview"; import { m } from "../../i18n/messages"; import { downloadAndShareAttachment } from "../../lib/attachmentDownload"; @@ -272,6 +276,7 @@ function PreviewStreamDocumentView({ ), ); }; + const [selectMenu, setSelectMenu] = useState(null); const command = (input: PreviewStreamInput) => webView.current?.injectJavaScript( `window.T3PreviewStream?.command(${JSON.stringify(input)}); true;`, @@ -298,6 +303,7 @@ function PreviewStreamDocumentView({ onStreamingChange?.(false); setControl(null); setFileChooser(null); + setSelectMenu(null); onControl?.(null); setError(message); setStatus("error"); @@ -388,6 +394,7 @@ function PreviewStreamDocumentView({ switch (message.type) { case "control": { setControl(message); + if (message.controller !== "you") setSelectMenu(null); const previousDialog = dialogRef.current; dialogRef.current = message.dialog; setPromptText((draft) => previewPromptText(previousDialog, message.dialog, draft)); @@ -425,6 +432,9 @@ function PreviewStreamDocumentView({ case "fileChooser": setFileChooser(message.chooser); return; + case "selectMenu": + setSelectMenu(message.menu); + return; case "pictureInPicture": onPictureInPicture?.(message, message.detail); return; @@ -469,6 +479,40 @@ function PreviewStreamDocumentView({ ) : null} + {!compact && selectMenu && control?.controller === "you" ? ( + + setSelectMenu((current) => (current?.id === selectMenu.id ? null : current)) + } + > + {/* oxlint-disable-next-line t3code/require-registered-list-scroll -- Sheet content; the sheet keeps its own header handling. */} + String(index)} + extraData={selectMenu} + estimatedItemSize={48} + className="flex-1" + nestedScrollEnabled + contentInsetAdjustmentBehavior="automatic" + contentContainerStyle={{ padding: 16 }} + renderItem={({ item, index }) => ( + 0} + disabled={item.disabled} + onPress={() => { + setSelectMenu(null); + command({ type: "selectMenu", id: selectMenu.id, index }); + }} + /> + )} + /> + + ) : null} {!compact && control?.dialog ? ( {control.dialog.message} diff --git a/apps/mobile/src/features/browser/preview-stream-document.ts b/apps/mobile/src/features/browser/preview-stream-document.ts index 84989d8c44c05..68d6fd6fb39ca 100644 --- a/apps/mobile/src/features/browser/preview-stream-document.ts +++ b/apps/mobile/src/features/browser/preview-stream-document.ts @@ -4,6 +4,7 @@ import type { PreviewStreamControl, PreviewStreamDownload, PreviewStreamFileChooser, + PreviewStreamSelectMenu, } from "@t3tools/client-runtime/preview/server-browser-stream"; export interface PreviewStreamConfiguration { @@ -37,6 +38,7 @@ export type PreviewStreamMessage = | { readonly type: "clipboard"; readonly text: string } | ({ readonly type: "download" } & PreviewStreamDownload) | { readonly type: "fileChooser"; readonly chooser: PreviewStreamFileChooser | null } + | { readonly type: "selectMenu"; readonly menu: PreviewStreamSelectMenu | null } | { readonly type: "pictureInPicture"; readonly supported: boolean; diff --git a/apps/mobile/src/features/browser/preview-stream.browser.ts b/apps/mobile/src/features/browser/preview-stream.browser.ts index 748cecd982f93..91892d0f75982 100644 --- a/apps/mobile/src/features/browser/preview-stream.browser.ts +++ b/apps/mobile/src/features/browser/preview-stream.browser.ts @@ -176,6 +176,7 @@ export function start(configuration: PreviewStreamConfiguration) { onClipboard: (text) => post({ type: "clipboard", text }), onDownload: (download) => post({ type: "download", ...download }), onFileChooser: (chooser) => post({ type: "fileChooser", chooser }), + onSelectMenu: (menu) => post({ type: "selectMenu", menu }), onViewport: (page) => { if (viewport?.width === page.width && viewport.height === page.height) return; viewport = page; 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 dd3ae9102824b..fd6e21ceec72c 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -501,6 +501,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 68c266ff5598a..f799339454475 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -152,7 +152,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 = { @@ -165,7 +165,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"; @@ -232,10 +247,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}`; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index cc7d101f59ee6..0032c15430bfc 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -134,6 +134,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, @@ -3555,6 +3556,11 @@ export default function ChatView(props: ChatViewProps) { )} data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"} data-chat-column + style={ + { + "--chat-header-height": embedded ? "0px" : "var(--workspace-topbar-height)", + } as CSSProperties + } inert={rightPanelMaximized} onMouseUp={preventMiddleClickPasteOutsideEditable} > diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index 4592a62759964..f187e136dfb62 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -5,7 +5,7 @@ import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../test/render"; import { openCommandPalette } from "../commandPaletteBus"; -import { useCommandPaletteStore } from "../commandPaletteStore"; +import { dispatchCommandPalette, useCommandPaletteStore } from "../commandPaletteStore"; import { LAST_USED_PROJECT_STORAGE_KEY } from "../hooks/useHandleNewThread"; import { removeLocalStorageItem } from "../hooks/useLocalStorage"; import { makeThreadFixture } from "../test-fixtures"; @@ -304,4 +304,80 @@ describe("CommandPalette open intents", () => { }), ); }); + + 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 49bcb2cbc78cd..f7d6a50efaa5d 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -256,6 +256,7 @@ import { remoteProjectSourceIcon, sourceControlHostIcon, } from "./CommandPaletteAddProject"; +import { useCommandPaletteThreadActions } from "./CommandPaletteThreadActions"; import { useCommandPaletteThreadItems } from "./CommandPaletteThreadItems"; import { useCommandPaletteThemeItems } from "./CommandPaletteThemeItems"; import { @@ -343,6 +344,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" }); @@ -759,6 +765,10 @@ function OpenCommandPaletteDialog(props: { currentProjectId, ); const currentProjectCwd = currentProject?.workspaceRoot ?? null; + const currentThreadActionItems = useCommandPaletteThreadActions({ + threadRef: activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null, + projectCwd: currentProjectCwd, + }); const currentProjectCwdForBrowse = browseEnvironmentId && currentProjectEnvironmentId === browseEnvironmentId ? currentProjectCwd @@ -845,7 +855,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 }), @@ -1590,6 +1599,8 @@ function OpenCommandPaletteDialog(props: { }); } + actionItems.push(...currentThreadActionItems); + actionItems.push({ kind: "action", value: "action:open-file-picker", @@ -2347,7 +2358,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, @@ -2789,14 +2799,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/CommandPaletteThreadActions.tsx b/apps/web/src/components/CommandPaletteThreadActions.tsx new file mode 100644 index 0000000000000..80e0213026846 --- /dev/null +++ b/apps/web/src/components/CommandPaletteThreadActions.tsx @@ -0,0 +1,107 @@ +import type { ContextMenuItem, KeybindingCommand, ScopedThreadRef } from "@t3tools/contracts"; +import { + ArchiveIcon, + CircleCheckIcon, + ClockIcon, + CopyIcon, + FolderIcon, + FolderPlusIcon, + GitBranchIcon, + HashIcon, + type LucideIcon, + MailOpenIcon, + MessageSquareIcon, + MessageSquarePlusIcon, + PinIcon, + PinOffIcon, + RefreshCwIcon, + TimerIcon, + Trash2Icon, +} from "lucide-react"; + +import { useThreadActionMenu } from "../hooks/useThreadActionMenu"; +import { + ADDON_ICON_CLASS, + ITEM_ICON_CLASS, + type CommandPaletteActionItem, + type CommandPaletteSubmenuItem, +} from "./CommandPalette.logic"; +import type { ThreadActionMenuId } from "./threadActionMenu.logic"; + +const ICONS: Record = { + archive: ArchiveIcon, + "circle-check": CircleCheckIcon, + clock: ClockIcon, + copy: CopyIcon, + folder: FolderIcon, + "folder-plus": FolderPlusIcon, + "git-branch": GitBranchIcon, + hash: HashIcon, + "mail-open": MailOpenIcon, + "message-square": MessageSquareIcon, + "message-square-plus": MessageSquarePlusIcon, + pin: PinIcon, + "pin-off": PinOffIcon, + "refresh-cw": RefreshCwIcon, + timer: TimerIcon, + trash: Trash2Icon, +}; + +// The palette has its own rows for these, and no inline title editor for rename. +const SKIPPED: ReadonlySet = new Set(["rename", "project-settings"]); + +const SHORTCUTS: Partial> = { + settle: "thread.settle", + unsettle: "thread.settle", + pin: "thread.pin", + unpin: "thread.pin", + "regenerate-title": "thread.regenerateTitle", +}; + +/** The open thread's menu actions (settle, pin, snooze, archive...) as palette rows. */ +export function useCommandPaletteThreadActions(input: { + readonly threadRef: ScopedThreadRef | null; + readonly projectCwd: string | null; +}): Array { + const { readMenu } = useThreadActionMenu({ ...input, canShareWithGuest: false }); + const menu = readMenu(); + if (!menu) return []; + + const toPaletteItem = ( + item: ContextMenuItem, + ): CommandPaletteActionItem | CommandPaletteSubmenuItem | null => { + if (SKIPPED.has(item.id)) return null; + const Icon = item.icon ? ICONS[item.icon] : undefined; + const shared = { + value: `thread-action:${item.id}`, + searchTerms: [], + title: item.label, + icon: Icon ? : null, + ...(item.detail ? { description: item.detail } : {}), + ...(item.disabled ? { disabled: true } : {}), + }; + if (item.children) { + // Palette search lists children directly, so they inherit the parent's disabled state. + const children = item.children.flatMap( + (child) => toPaletteItem(item.disabled ? { ...child, disabled: true } : child) ?? [], + ); + if (children.length === 0) return null; + return { + ...shared, + kind: "submenu", + addonIcon: Icon ? : null, + groups: [{ value: shared.value, label: item.label, items: children }], + }; + } + const shortcutCommand = SHORTCUTS[item.id]; + return { + ...shared, + kind: "action", + ...(shortcutCommand ? { shortcutCommand } : {}), + ...(item.checked !== undefined ? { checked: item.checked } : {}), + run: () => menu.run(item.id), + }; + }; + + return menu.items.flatMap((item) => toPaletteItem(item) ?? []); +} 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/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 5047c88556353..5336227f69d90 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -1281,7 +1281,10 @@ describe("composer context undo lifetime", () => { const retained = composer.retained(); expect(retained.files.get(fileContextReference(file).contextId)?.file).toBe(file.file); + const editorBeforeSwitch = composer.editor(); await composer.show("b"); + // Thread switches swap the draft into the same editor rather than rebuilding it. + expect(composer.editor()).toBe(editorBeforeSwitch); expect(retained.files.size).toBe(0); await composer.undo(); expect(serializeEditorDoc(composer.editor().state.doc).value).toBe(destinationValue); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 1088e27f2a05d..d76758fd88149 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -20,7 +20,7 @@ import { useGT } from "gt-react"; import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands"; import { isHistoryTransaction } from "@tiptap/pm/history"; import { - type EditorState, + EditorState, NodeSelection, Plugin, PluginKey, @@ -826,11 +826,12 @@ export function ComposerPromptEditorTiptap(props: ComposerPromptEditorProps) { setSelection({ value, cursor, expandedCursor }); onPromptChange(value, cursor, expandedCursor, ...rest); }; - // Changing text mode remounts the editor. Its collapsed cursor cannot represent - // a caret inside unknown `$name` text, so retain the exact Markdown offset here. + // Changing text mode remounts the editor; switching drafts reuses it (see the controlled-value + // effect). Its collapsed cursor cannot represent a caret inside unknown `$name` text, so retain + // the exact Markdown offset here. return ( (null); const citationDraftRef = useRef<{ key: string; comment: string } | null>(null); const [isEmpty, setIsEmpty] = useState(value.length === 0); + const draftKey = props.draftKey ?? ""; + const [renderedDraftKey, setRenderedDraftKey] = useState(draftKey); + if (renderedDraftKey !== draftKey) { + setRenderedDraftKey(draftKey); + setOpenCitation(null); + setIsEmpty(value.length === 0); + } + const appliedDraftKeyRef = useRef(draftKey); const citationCommentActions = { openComment: openCitation, @@ -1717,7 +1726,11 @@ function ComposerPromptEditorTiptapInner( useLayoutEffect(() => { latestValueRef.current = value; if (!editor) return; - const initialSelection = !hasAppliedControlledSelectionRef.current; + // Switching threads swaps the draft in this same editor, which is far cheaper than rebuilding + // it. A fresh state keeps undo from reaching back into the previous thread's draft. + const draftChanged = appliedDraftKeyRef.current !== draftKey; + appliedDraftKeyRef.current = draftKey; + const initialSelection = !hasAppliedControlledSelectionRef.current || draftChanged; hasAppliedControlledSelectionRef.current = true; const normalizedCursor = clampEditorCursor(value, cursor); const previousSnapshot = snapshotRef.current; @@ -1748,8 +1761,21 @@ function ComposerPromptEditorTiptapInner( isApplyingControlledUpdateRef.current = true; const pendingCitation = - citationRequestRef.current?.value === value ? citationRequestRef.current : null; - if (previousSnapshot.value !== value) { + !draftChanged && citationRequestRef.current?.value === value + ? citationRequestRef.current + : null; + if (draftChanged) { + citationRequestRef.current = null; + citationDraftRef.current = null; + editor.view.updateState( + EditorState.create({ + doc: editor.schema.nodeFromJSON( + buildDocJson(value, skillLabelFor, { styling: richText, literalText, isKnownModel }), + ), + plugins: editor.state.plugins, + }), + ); + } else if (previousSnapshot.value !== value) { saveCitationDraft(editor, previousSnapshot.value); editor.commands.setContent( buildDocJson(value, skillLabelFor, { styling: richText, literalText, isKnownModel }), @@ -1793,6 +1819,7 @@ function ComposerPromptEditorTiptapInner( }, [ clampEditorCursor, cursor, + draftKey, editor, expandEditorCursor, initialExpandedCursor, diff --git a/apps/web/src/components/ConnectDeviceApprovalCoordinator.tsx b/apps/web/src/components/ConnectDeviceApprovalCoordinator.tsx index ae969f29c4aa4..64d6b1e7ce34a 100644 --- a/apps/web/src/components/ConnectDeviceApprovalCoordinator.tsx +++ b/apps/web/src/components/ConnectDeviceApprovalCoordinator.tsx @@ -6,10 +6,13 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { AuthAccessWriteScope, type EnvironmentId } from "@t3tools/contracts"; +import { unseenConnectDevices } from "@t3tools/client-runtime/connect-device-notices"; import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; import { useEffect, useRef, useState } from "react"; import { msg } from "gt-react"; +import { readLocalStorageValue, writeLocalStorageValue } from "../hooks/useLocalStorage"; import { m } from "../i18n/messages"; import { authEnvironment } from "../state/auth"; import { useEnvironments } from "../state/environments"; @@ -20,27 +23,145 @@ import { describeConnectDeviceClient } from "./settings/ConnectionsSettings.logi import { toastManager } from "./ui/toast"; import { stackedThreadToast } from "./ui/toastHelpers"; -/** Asks whoever can approve to look at T3 Connect devices waiting on an environment. */ +/** + * Asks whoever can approve to look at T3 Connect devices waiting on an environment, and tells + * them about devices that got in without approval. + */ export function ConnectDeviceApprovalCoordinator() { const { environments } = useEnvironments(); return environments.map((environment) => - 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 6a6d1f7fda109..3630e792c3d0d 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -380,17 +380,12 @@ function GitActionProgressButtonContent({ role="status" >