diff --git a/.github/actions/setup-apt-mirrors/action.yml b/.github/actions/setup-apt-mirrors/action.yml index 5beff201d188e..bf9fdd72c9864 100644 --- a/.github/actions/setup-apt-mirrors/action.yml +++ b/.github/actions/setup-apt-mirrors/action.yml @@ -17,6 +17,7 @@ runs: -exec sed -i -E \ 's#https?://(([^/]+\.)?archive|security)\.ubuntu\.com/ubuntu/?#mirror+file:/etc/apt/blacksmith-ubuntu-mirrors.txt#g' {} + - # Move on to a fallback before an unreachable server exhausts the job. - printf '%s\n' 'Acquire::http::Timeout "15";' 'Acquire::https::Timeout "15";' \ + # Move on to a fallback before an unreachable server exhausts the job. apt tries every + # file on a stalled server first and waits this long for each one. + printf '%s\n' 'Acquire::http::Timeout "5";' 'Acquire::https::Timeout "5";' \ | sudo tee /etc/apt/apt.conf.d/80-mirror-timeouts > /dev/null 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/ci.yml b/.github/workflows/ci.yml index 70208c7a16479..6672ca5ccea0b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -193,8 +193,10 @@ jobs: if: ${{ !cancelled() && needs.changes.outputs.build != 'false' }} timeout-minutes: 5 run: | - until test -s "$RUNNER_TEMP/apt-status"; do sleep 1; done + # Give up before the step timeout so a stuck install still prints its log. + for _ in $(seq 280); do test -s "$RUNNER_TEMP/apt-status" && break; sleep 1; done cat "$RUNNER_TEMP/apt.log" + test -s "$RUNNER_TEMP/apt-status" || { echo "::error::apt did not finish in 280s"; exit 1; } exit "$(cat "$RUNNER_TEMP/apt-status")" - name: Build desktop pipeline @@ -344,8 +346,10 @@ jobs: - name: Finish installing browser secret helper build libraries timeout-minutes: 5 run: | - until test -s "$RUNNER_TEMP/apt-status"; do sleep 1; done + # Give up before the step timeout so a stuck install still prints its log. + for _ in $(seq 280); do test -s "$RUNNER_TEMP/apt-status" && break; sleep 1; done cat "$RUNNER_TEMP/apt.log" + test -s "$RUNNER_TEMP/apt-status" || { echo "::error::apt did not finish in 280s"; exit 1; } exit "$(cat "$RUNNER_TEMP/apt-status")" # `changes` lists the affected packages, or nothing when all of them are. 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/apps/desktop/gt.config.json b/apps/desktop/gt.config.json index b77af550c763e..0ec7365310716 100644 --- a/apps/desktop/gt.config.json +++ b/apps/desktop/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["de", "es", "fr", "ja", "ko", "pt-BR", "ru", "sv", "zh"], + "locales": ["de", "es", "fr", "ja", "ko", "pl", "pt-BR", "ru", "sv", "zh"], "src": ["src/**/*.ts", "!**/*.test.ts"], "files": { "gt": { diff --git a/apps/desktop/resources/installer.nsh b/apps/desktop/resources/installer.nsh index 7f277fdcbf9c2..bff93bf0597d3 100644 --- a/apps/desktop/resources/installer.nsh +++ b/apps/desktop/resources/installer.nsh @@ -5,9 +5,13 @@ !else ${StrRep} !define T3StrRep '${StrRep}' + Var t3AppWasRunning !endif !macro customAppRunningMessages + !ifndef BUILD_UNINSTALLER + StrCpy $t3AppWasRunning 1 + !endif Push $0 Push $1 ${If} $IsPowerShellAvailable == 0 @@ -39,4 +43,12 @@ WinShell::SetLnkAUMI "$newStartMenuLink" "${APP_ID}" ${EndIf} !endif + + # The template relaunches after a silent install only with --force-run, which WinGet does not pass. + ${If} ${Silent} + ${AndIfNot} ${isForceRun} + ${AndIf} $t3AppWasRunning == 1 + HideWindow + ${StdUtils.ExecShellAsUser} $0 "$launchLink" "open" "" + ${EndIf} !macroend diff --git a/apps/desktop/src/app/DesktopAppActivation.test.ts b/apps/desktop/src/app/DesktopAppActivation.test.ts index 2bf1e716a99a8..bde215855b4a2 100644 --- a/apps/desktop/src/app/DesktopAppActivation.test.ts +++ b/apps/desktop/src/app/DesktopAppActivation.test.ts @@ -1,4 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off -- This adapter test binds a real local socket or Windows named pipe and verifies its cleanup. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as NodeEvents from "node:events"; import * as NodeFSP from "node:fs/promises"; import * as NodeNet from "node:net"; import * as NodeOS from "node:os"; @@ -14,9 +16,15 @@ import { resolveDesktopAppControlAddress } from "@t3tools/shared/desktopAppContr import * as HostProcess from "@t3tools/shared/HostProcess"; import { it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import { afterEach, describe, expect } from "vite-plus/test"; +import * as ElectronWindow from "../electron/ElectronWindow.ts"; +import { DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL } from "../ipc/channels.ts"; +import * as DesktopWindow from "../window/DesktopWindow.ts"; +import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import { startDesktopAppControlServer } from "./DesktopAppActivation.ts"; +import * as DesktopEnvironment from "./DesktopEnvironment.ts"; const openServers: Array<{ close: () => Promise }> = []; @@ -163,4 +171,65 @@ describe("desktop app control server", () => { }); }), ); + + it.effect("fails an in-flight request when the renderer process is gone", () => + Effect.gen(function* () { + const platform = yield* HostProcess.Platform; + const userId = yield* HostProcess.UserId; + const root = yield* Effect.acquireRelease( + Effect.promise(() => NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-app-crash-test-"))), + (dir) => Effect.promise(() => NodeFSP.rm(dir, { recursive: true, force: true })), + ); + const stateDir = NodePath.join(root, "userdata"); + const target = makeTarget(stateDir, platform, userId); + + let resolveDispatched: () => void = () => undefined; + const dispatched = new Promise((resolve) => { + resolveDispatched = resolve; + }); + const webContents = Object.assign(new NodeEvents.EventEmitter(), { + isDestroyed: () => false, + send: (channel: string) => { + if (channel === DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL) resolveDispatched(); + }, + }); + + const layer = DesktopAppActivation.layer.pipe( + Layer.provide( + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + stateDir, + platform, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + ), + Layer.provide( + Layer.succeed(DesktopWindow.DesktopWindow, { + activate: Effect.void, + } as unknown as DesktopWindow.DesktopWindow["Service"]), + ), + Layer.provide( + Layer.succeed(ElectronWindow.ElectronWindow, { + main: Effect.succeedSome({ webContents } as unknown as Electron.BrowserWindow), + } as unknown as ElectronWindow.ElectronWindow["Service"]), + ), + Layer.provide(NodeServices.layer), + ); + + yield* Effect.gen(function* () { + const activation = yield* DesktopAppActivation.DesktopAppActivation; + yield* activation.start; + yield* activation.setRendererReady(true); + + const response = exchange(target.address, request("before-crash", platform)); + yield* Effect.promise(() => dispatched); + webContents.emit("render-process-gone", {}, { reason: "crashed", exitCode: 1 }); + + expect(yield* Effect.promise(() => response)).toMatchObject({ + ok: false, + requestId: "before-crash", + code: "renderer-unavailable", + }); + expect(webContents.listenerCount("render-process-gone")).toBe(0); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), + ); }); diff --git a/apps/desktop/src/app/DesktopAppActivation.ts b/apps/desktop/src/app/DesktopAppActivation.ts index 00d1b0e954afb..0e747e5dc1e7c 100644 --- a/apps/desktop/src/app/DesktopAppActivation.ts +++ b/apps/desktop/src/app/DesktopAppActivation.ts @@ -374,9 +374,11 @@ export const make = Effect.gen(function* () { if (event.isMainFrame && !event.isSameDocument) clearRegisteredRenderer(); }; webContents.on("did-start-navigation", onNavigation); + webContents.on("render-process-gone", onUnavailable); webContents.once("destroyed", onUnavailable); detachRendererListeners = () => { webContents.removeListener("did-start-navigation", onNavigation); + webContents.removeListener("render-process-gone", onUnavailable); webContents.removeListener("destroyed", onUnavailable); }; } diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 7100227f92bc4..6084aa9775da1 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -53,11 +53,12 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { `if [ "$1" = --appimage-extract ]; then cp -R '${image}' squashfs-root; exit 0; fi`, '[ "$1" = --appimage-mount ] || exit 9', '[ -n "$APPIMAGE_EXTRACT_AND_RUN" ] && exit 8', - `echo $$ >'${root}/mounter.pid'`, - canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open. + // Trapped before the mount is announced, or the test's probe can arrive first and be lost. "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT", "trap 'echo mounted >&3 2>/dev/null' WINCH", + `echo $$ >'${root}/mounter.pid'`, + canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', "while :; do sleep 0.05; done", "", ].join("\n"), diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 5c2687d451a02..11f59fc2a6fff 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -118,13 +118,16 @@ export const renderCliShim = (input: { // The shell must outlive the CLI to unmount, so it forwards TERM and HUP; the terminal sends // Ctrl-C to the CLI directly. A background child would read /dev/null, so pass stdin on fd 9. // With stdin closed, `exec 9<&0` would end the shell; `command` makes it a normal error. + // Forwarding starts before the CLI does: a signal in between must not unmount under it. "{ command exec 9<&0; } 2>/dev/null || exec 9/dev/null; else pending=TERM; fi' TERM`, + `trap 'if [ -n "$cli" ]; then kill -HUP "$cli" 2>/dev/null; else pending=HUP; fi' HUP`, + "trap '' INT", `${run("$mount")} <&9 9<&- &`, "cli=$!", + '[ -z "$pending" ] || kill -"$pending" "$cli" 2>/dev/null', "exec 9<&-", - `trap 'kill -TERM "$cli" 2>/dev/null' TERM`, - `trap 'kill -HUP "$cli" 2>/dev/null' HUP`, - "trap '' INT", "status=0", 'wait "$cli" || status=$?', // A trapped signal interrupts wait; wait again for the CLI's own exit status. diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts index b58b583fd6cd5..40d1703f1a82f 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.test.ts @@ -3,12 +3,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ConnectionCatalogDocument } from "@t3tools/client-runtime/platform"; import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Base64 from "effect/encoding/Base64"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; @@ -28,22 +31,25 @@ const encodeLegacySavedEnvironments = Schema.encodeEffect( Schema.Struct({ version: Schema.Literal(1), records: Schema.Array(Schema.Unknown) }), ), ); -function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref | null = null) { +// `key` models Electron's os_crypt key: replacing it orphans everything encrypted before. +function layerSafeStorageFor(available: boolean, key: Ref.Ref | null = null) { + const prefix = Effect.gen(function* () { + return key === null ? "encrypted:" : `encrypted:${yield* Ref.get(key)}:`; + }); return Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, { isEncryptionAvailable: Effect.succeed(available), - encryptString: (value) => Effect.succeed(textEncoder.encode(`encrypted:${value}`)), + encryptString: (value) => + prefix.pipe(Effect.map((current) => textEncoder.encode(`${current}${value}`))), decryptString: (value) => { return Effect.gen(function* () { const decoded = textDecoder.decode(value); - if ( - !decoded.startsWith("encrypted:") || - (failDecrypt !== null && (yield* Ref.get(failDecrypt))) - ) { + const current = yield* prefix; + if (!decoded.startsWith(current)) { return yield* new ElectronSafeStorage.ElectronSafeStorageDecryptError({ cause: new Error("invalid encrypted catalog"), }); } - return decoded.slice("encrypted:".length); + return decoded.slice(current.length); }); }, selectedStorageBackend: Effect.succeedNone, @@ -53,7 +59,7 @@ function layerSafeStorageFor(available: boolean, failDecrypt: Ref.Ref | function layerFor( baseDir: string, encryptionAvailable = true, - failDecrypt: Ref.Ref | null = null, + key: Ref.Ref | null = null, fileSystemLayer: Layer.Layer = NodeServices.layer, ) { const layerEnvironment = DesktopEnvironment.layer({ @@ -71,7 +77,7 @@ function layerFor( Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), ), ); - const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, failDecrypt); + const layerSafeStorage = layerSafeStorageFor(encryptionAvailable, key); const layerDependencies = Layer.mergeAll( layerEnvironment, layerSafeStorage, @@ -102,6 +108,9 @@ const withStore = ( }).pipe(Effect.provide(NodeServices.layer)); describe("DesktopConnectionCatalogStore", () => { + const emptyCatalog = + '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}'; + it.effect("persists and reads an encrypted connection catalog", () => withStore( Effect.gen(function* () { @@ -265,44 +274,162 @@ describe("DesktopConnectionCatalogStore", () => { ), ); - it.effect("surfaces a catalog that can no longer be decrypted without deleting it", () => + it.effect("preserves a catalog encrypted with a lost key and starts a fresh one", () => Effect.gen(function* () { const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-connection-catalog-test-", }); - const failDecrypt = yield* Ref.make(false); - const layer = layerFor(baseDir, true, failDecrypt); + const key = yield* Ref.make("original-key"); const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( - Effect.provide(layer), + Effect.provide(layerFor(baseDir, true, key)), ); - + const stateDir = path.join(baseDir, "userdata"); + const catalogPath = path.join(stateDir, "connection-catalog.json"); assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}')); - yield* Ref.set(failDecrypt, true); + const original = yield* fileSystem.readFileString(catalogPath); + yield* Ref.set(key, "regenerated-key"); + + const results = yield* Effect.all([store.get, store.get], { concurrency: "unbounded" }); + assert.deepStrictEqual(results, [Option.none(), Option.none()]); + const findBackups = Effect.gen(function* () { + const backups: Array = []; + for (const name of yield* fileSystem.readDirectory(stateDir)) { + const entryPath = path.join(stateDir, name); + if ( + entryPath !== catalogPath && + (yield* fileSystem.readFileString(entryPath)) === original + ) { + backups.push(entryPath); + } + } + return backups; + }); + assert.equal((yield* findBackups).length, 1); + + const fresh = '{"schemaVersion":1,"targets":[],"profiles":[]}'; + assert.isTrue(yield* store.set(fresh)); + assert.deepStrictEqual(yield* store.get, Option.some(fresh)); + assert.equal((yield* findBackups).length, 1); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("preserves the undecryptable catalog even when a save replaces it mid-read", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-connection-catalog-test-", + }); + const key = yield* Ref.make("original-key"); + const writer = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide(layerFor(baseDir, true, key)), + ); + assert.isTrue(yield* writer.set(emptyCatalog)); + const stateDir = path.join(baseDir, "userdata"); + const catalogPath = path.join(stateDir, "connection-catalog.json"); + const original = yield* fileSystem.readFileString(catalogPath); + const readerKey = yield* Ref.make("regenerated-key"); + const preserving = yield* Deferred.make(); + const saved = yield* Deferred.make(); + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide( + layerFor( + baseDir, + true, + readerKey, + Layer.succeed(FileSystem.FileSystem, { + ...fileSystem, + exists: (entryPath) => + entryPath.endsWith(".undecryptable") + ? Deferred.succeed(preserving, undefined).pipe( + Effect.andThen(Deferred.await(saved)), + Effect.andThen(fileSystem.exists(entryPath)), + ) + : fileSystem.exists(entryPath), + }), + ), + ), + ); + const read = yield* Effect.forkChild(store.get); + yield* Deferred.await(preserving); + assert.isTrue(yield* writer.set(`${emptyCatalog}\n`)); + yield* Deferred.succeed(saved, undefined); + assert.deepStrictEqual(yield* Fiber.join(read), Option.none()); + + const backups = (yield* fileSystem.readDirectory(stateDir)).filter((name) => + name.endsWith(".undecryptable"), + ); + assert.equal(backups.length, 1); + assert.equal( + yield* fileSystem.readFileString(path.join(stateDir, backups[0] ?? "")), + original, + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps an undecryptable catalog in place when it cannot be preserved", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-desktop-connection-catalog-test-", + }); + const key = yield* Ref.make("original-key"); + const writable = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide(layerFor(baseDir, true, key)), + ); + const catalogPath = path.join(baseDir, "userdata", "connection-catalog.json"); + assert.isTrue(yield* writable.set('{"schemaVersion":1,"targets":[]}')); + const original = yield* fileSystem.readFileString(catalogPath); + const writeFailure = (method: string) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method, + pathOrDescriptor: catalogPath, + }), + ); + const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( + Effect.provide( + layerFor( + baseDir, + true, + key, + Layer.succeed(FileSystem.FileSystem, { + ...fileSystem, + copy: () => writeFailure("copy"), + copyFile: () => writeFailure("copyFile"), + link: () => writeFailure("link"), + remove: () => writeFailure("remove"), + rename: () => writeFailure("rename"), + writeFile: () => writeFailure("writeFile"), + writeFileString: () => writeFailure("writeFileString"), + }), + ), + ), + ); + yield* Ref.set(key, "regenerated-key"); + const error = yield* store.get.pipe(Effect.flip); assert.instanceOf( error, - DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError, + DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError, ); - assert.equal(error.operation, "decrypt-catalog"); - assert.equal(error.catalogPath, path.join(baseDir, "userdata", "connection-catalog.json")); - assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError); - const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError; - assert.instanceOf(decryptError.cause, Error); - assert.equal(decryptError.cause.message, "invalid encrypted catalog"); - assert.equal( - error.message, - `Desktop connection catalog protection failed during decrypt-catalog at ${path.join(baseDir, "userdata", "connection-catalog.json")}.`, + assert.equal(error.operation, "preserve-undecryptable-catalog"); + const saveError = yield* store.set(emptyCatalog).pipe(Effect.flip); + assert.equal(saveError.operation, "preserve-undecryptable-catalog"); + assert.isFalse( + (yield* fileSystem.readDirectory(path.dirname(catalogPath))).some((name) => + name.endsWith(".undecryptable"), + ), ); - assert.notEqual(error.message, decryptError.message); - yield* Ref.set(failDecrypt, false); - assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}')); + assert.equal(yield* fileSystem.readFileString(catalogPath), original); }).pipe(Effect.provide(NodeServices.layer)), ); - const emptyCatalog = - '{"schemaVersion":1,"targets":[],"profiles":[],"credentials":[],"remoteDpopTokens":[],"disabledEnvironmentIds":[]}'; const savedFilesHolding = Effect.fn(function* (stateDir: string, contents: string) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -338,28 +465,34 @@ describe("DesktopConnectionCatalogStore", () => { ), ); - it.effect("keeps a catalog that no longer decrypts when the next save replaces it", () => + it.effect("preserves the original catalog when saving after key loss without reading first", () => Effect.gen(function* () { const path = yield* Path.Path; const fileSystem = yield* FileSystem.FileSystem; const baseDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-desktop-connection-catalog-test-", }); - const failDecrypt = yield* Ref.make(false); + const key = yield* Ref.make("original-key"); const store = yield* DesktopConnectionCatalogStore.DesktopConnectionCatalogStore.pipe( - Effect.provide(layerFor(baseDir, true, failDecrypt)), + Effect.provide(layerFor(baseDir, true, key)), ); const stateDir = path.join(baseDir, "userdata"); - assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}')); - const original = yield* fileSystem.readFileString( - path.join(stateDir, "connection-catalog.json"), + const catalogPath = path.join(stateDir, "connection-catalog.json"); + assert.isTrue(yield* store.set(emptyCatalog)); + const original = JSON.stringify( + JSON.parse(yield* fileSystem.readFileString(catalogPath)), + null, + 2, ); + yield* fileSystem.writeFileString(catalogPath, original); - yield* Ref.set(failDecrypt, true); - yield* store.get.pipe(Effect.flip); + yield* Ref.set(key, "regenerated-key"); assert.isTrue(yield* store.set(emptyCatalog)); - assert.isNotEmpty(yield* savedFilesHolding(stateDir, original)); - }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), + const backups = yield* savedFilesHolding(stateDir, original); + assert.equal(backups.length, 1); + assert.isTrue(backups[0]?.endsWith(".undecryptable")); + assert.deepStrictEqual(yield* store.get, Option.some(emptyCatalog)); + }).pipe(Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts index 5db49e5f9504c..c394cf9c08d2c 100644 --- a/apps/desktop/src/app/DesktopConnectionCatalogStore.ts +++ b/apps/desktop/src/app/DesktopConnectionCatalogStore.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics nodeBuiltinImport:off - `node:crypto` names the backup of an undecryptable catalog by its content. +import * as NodeCrypto from "node:crypto"; + import { BearerConnectionCredential, BearerConnectionProfile, @@ -12,10 +15,10 @@ import { } from "@t3tools/client-runtime/platform"; import type { PersistedSavedEnvironmentRecord } from "@t3tools/contracts"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; -import * as Clock from "effect/Clock"; import * as Base64 from "effect/encoding/Base64"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -56,6 +59,7 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([ "create-directory", "write-temporary-file", "replace-catalog-file", + "preserve-undecryptable-catalog", "keep-unreadable-catalog", ]); @@ -69,7 +73,6 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([ const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([ "check-encryption-availability", "encrypt-catalog", - "decrypt-catalog", ]); export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedError()( @@ -161,6 +164,7 @@ export class DesktopConnectionCatalogStore extends Context.Service< | DesktopConnectionCatalogStoreDecodeError | DesktopConnectionCatalogStoreMigrationError | DesktopConnectionCatalogStoreProtectionError + | DesktopConnectionCatalogStoreWriteError >; readonly set: ( catalog: string, @@ -187,13 +191,7 @@ function decodeSecretBytes( ); } -const readDocument = ( - fileSystem: FileSystem.FileSystem, - catalogPath: string, -): Effect.Effect< - Option.Option, - DesktopConnectionCatalogStoreReadError | DesktopConnectionCatalogStoreDocumentDecodeError -> => +const readDocument = (fileSystem: FileSystem.FileSystem, catalogPath: string) => fileSystem.readFileString(catalogPath).pipe( Effect.catch((error) => error.reason._tag === "NotFound" @@ -207,8 +205,9 @@ const readDocument = ( ), Effect.flatMap((raw) => raw === null - ? Effect.succeed(Option.none()) + ? Effect.succeedNone : decodeEncryptedConnectionCatalogDocumentJson(raw).pipe( + Effect.map((document) => ({ document, raw })), Effect.asSome, Effect.mapError( (cause) => @@ -225,21 +224,11 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")( readonly fileSystem: FileSystem.FileSystem; readonly path: Path.Path; readonly catalogPath: string; - readonly document: EncryptedConnectionCatalogDocument; + readonly contents: string; readonly suffix: string; }): Effect.fn.Return { const directory = input.path.dirname(input.catalogPath); const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`; - const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreWriteError({ - operation: "encode-document", - path: input.catalogPath, - cause, - }), - ), - ); yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe( Effect.mapError( (cause) => @@ -251,7 +240,7 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")( ), ); yield* Effect.gen(function* () { - yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe( + yield* input.fileSystem.writeFileString(tempPath, input.contents).pipe( Effect.mapError( (cause) => new DesktopConnectionCatalogStoreWriteError({ @@ -400,41 +389,8 @@ export const make = Effect.gen(function* () { ), ); - const decryptDocument = (document: EncryptedConnectionCatalogDocument) => - decodeSecretBytes(catalogPath, document.encryptedCatalog).pipe( - Effect.flatMap((encryptedCatalog) => - safeStorage.decryptString(encryptedCatalog).pipe( - Effect.mapError( - (cause) => - new DesktopConnectionCatalogStoreProtectionError({ - operation: "decrypt-catalog", - catalogPath, - cause, - }), - ), - ), - ), - ); - - // A catalog this build cannot decrypt or decode may still hold another build's saved - // environments and credentials, so a save copies it aside instead of destroying it. - const keepUnreadableCatalog = Effect.gen(function* () { - const readable = yield* readDocument(fileSystem, catalogPath).pipe( - Effect.flatMap( - Option.match({ - onNone: () => Effect.succeed(true), - onSome: (document) => - decryptDocument(document).pipe( - Effect.flatMap(decodeRuntimeConnectionCatalogDocumentJson), - Effect.as(true), - ), - }), - ), - Effect.orElseSucceed(() => false), - ); - if (readable) { - return; - } + // An unreadable catalog may still hold another build's saved environments and credentials. + const keepUnreadableCatalogFile = Effect.gen(function* () { const keptPath = `${catalogPath}.unreadable-${yield* Clock.currentTimeMillis}`; yield* fileSystem.copyFile(catalogPath, keptPath).pipe( Effect.mapError( @@ -466,16 +422,100 @@ export const make = Effect.gen(function* () { ), ), ); + const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson({ + version: 1, + encryptedCatalog, + }).pipe( + Effect.mapError( + (cause) => + new DesktopConnectionCatalogStoreWriteError({ + operation: "encode-document", + path: catalogPath, + cause, + }), + ), + ); const suffix = (yield* random.uuidV4()).replace(/-/g, ""); yield* writeDocument({ fileSystem, path, catalogPath, - document: { version: 1, encryptedCatalog }, + contents: `${encoded}\n`, suffix, }); }); + // Electron regenerates its key when the OS keyring entry is lost, orphaning the catalog for + // good. Read it as empty so the user can reconnect, but keep a copy first: the catalog stays + // in place until the next save replaces it, and the content-derived name keeps repeated and + // concurrent reads to one backup. + const preserveUndecryptableCatalog = Effect.fn( + "desktop.connectionCatalogStore.preserveUndecryptableCatalog", + )(function* ( + contents: string, + encryptedCatalog: Uint8Array, + decryptError: ElectronSafeStorage.ElectronSafeStorageDecryptError, + ) { + const digest = NodeCrypto.createHash("sha256").update(encryptedCatalog).digest("hex"); + const backupPath = `${catalogPath}.${digest}.undecryptable`; + const preserveError = (cause: unknown) => + new DesktopConnectionCatalogStoreWriteError({ + operation: "preserve-undecryptable-catalog", + path: backupPath, + cause, + }); + if (!(yield* fileSystem.exists(backupPath).pipe(Effect.mapError(preserveError)))) { + const suffix = (yield* random.uuidV4()).replace(/-/g, ""); + // Back up the document that failed to decrypt, not the file at `catalogPath`: a + // concurrent `set` may already have replaced it. + yield* writeDocument({ fileSystem, path, catalogPath: backupPath, contents, suffix }).pipe( + Effect.mapError(preserveError), + ); + yield* Effect.logWarning( + "The desktop connection catalog can no longer be decrypted; starting a new one.", + { catalogPath, backupPath, reason: decryptError._tag }, + ); + } + }); + + const decryptDocument = Effect.fn("desktop.connectionCatalogStore.decryptDocument")( + function* (snapshot: { + readonly document: EncryptedConnectionCatalogDocument; + readonly raw: string; + }) { + const encryptedCatalog = yield* decodeSecretBytes( + catalogPath, + snapshot.document.encryptedCatalog, + ); + return yield* safeStorage.decryptString(encryptedCatalog).pipe( + Effect.asSome, + Effect.catchTags({ + ElectronSafeStorageDecryptError: (error) => + preserveUndecryptableCatalog(snapshot.raw, encryptedCatalog, error).pipe( + Effect.as(Option.none()), + ), + }), + ); + }, + ); + + const keepUnreadableCatalog = readDocument(fileSystem, catalogPath).pipe( + Effect.flatMap(Option.match({ onNone: () => Effect.succeedNone, onSome: decryptDocument })), + Effect.flatMap( + Option.match({ + onNone: () => Effect.void, + onSome: (catalog) => + decodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(Effect.asVoid), + }), + ), + Effect.catchTags({ + DesktopConnectionCatalogStoreReadError: () => keepUnreadableCatalogFile, + DesktopConnectionCatalogStoreDocumentDecodeError: () => keepUnreadableCatalogFile, + DesktopConnectionCatalogStoreDecodeError: () => keepUnreadableCatalogFile, + SchemaError: () => keepUnreadableCatalogFile, + }), + ); + const migrateLegacyCatalog = Effect.gen(function* () { if (!(yield* encryptionAvailable)) { return Option.none(); @@ -526,7 +566,7 @@ export const make = Effect.gen(function* () { if (!(yield* encryptionAvailable)) { return Option.none(); } - return Option.some(yield* decryptDocument(document.value)); + return yield* decryptDocument(document.value); }).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")), set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) { if (!(yield* encryptionAvailable)) { diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index b98546d585388..c2ebffd6ca454 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -58,6 +58,7 @@ export class DesktopEnvironment extends Context.Service< readonly clientAssetsDir: string; readonly backendCwd: string; readonly preloadPath: string; + readonly previewPickPreloadPath: string; readonly compileCachePath: string; readonly appUpdateYmlPath: string; readonly devServerUrl: Option.Option; @@ -204,6 +205,7 @@ const make = Effect.fn("desktop.environment.make")(function* ( clientAssetsDir: path.join(serverRoot, "apps/server/dist/client"), backendCwd: input.isPackaged ? homeDirectory : appRoot, preloadPath: path.join(input.dirname, "preload.cjs"), + previewPickPreloadPath: path.join(input.dirname, "preview-pick-preload.cjs"), compileCachePath: path.join(input.dirname, "compileCache.cjs"), appUpdateYmlPath: input.isPackaged ? path.join(resourcesPath, "app-update.yml") diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts index 397a757704835..86aff3a9ddc46 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.test.ts @@ -58,6 +58,23 @@ describe("tailscale endpoint provider", () => { }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), ); + it.effect("offers a VPN address when a stopped Tailscale still reports its last netmap", () => + Effect.gen(function* () { + const endpoints = yield* resolveTailscaleAdvertisedEndpoints({ + port: 3773, + networkInterfaces: { + tailscale0: [{ address: "fe80::294c:83fd:4ef:892b", family: "IPv6", internal: false }], + utun100: [{ address: "100.81.22.33", family: "IPv4", internal: false }], + }, + statusJson: `{"BackendState":"Stopped","Self":{"TailscaleIPs":["100.64.1.2"]}}`, + }); + assert.deepEqual( + endpoints.map((endpoint) => endpoint.httpBaseUrl), + ["http://100.81.22.33:3773/"], + ); + }).pipe(Effect.provide(layerUnusedTailscaleExternalServices)), + ); + it.effect( "recognizes a macOS Tailscale tunnel by its IPv6 address when status is unavailable", () => diff --git a/apps/desktop/src/backend/tailscaleEndpointProvider.ts b/apps/desktop/src/backend/tailscaleEndpointProvider.ts index 1b8d9dff4ed4d..ec498bdeacb52 100644 --- a/apps/desktop/src/backend/tailscaleEndpointProvider.ts +++ b/apps/desktop/src/backend/tailscaleEndpointProvider.ts @@ -27,6 +27,29 @@ const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { isAddon: true, }; +const VPN_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = { + id: "vpn", + label: "VPN", + kind: "private-network", + isAddon: true, +}; + +// CGNAT is shared with other VPNs; adapter identity works without current CLI status. A stopped +// Tailscale on Linux keeps tailscale0 with only a link-local address, so the name alone is not enough. +function isTailscaleInterface( + interfaceName: string, + interfaceAddresses: NonNullable, +): boolean { + return interfaceAddresses.some( + (address) => + !address.internal && + (address.family === "IPv6" + ? /^fd7a:115c:a1e0:/iu.test(address.address) + : /^tailscale(?:\d+|ipv[46])?$/iu.test(interfaceName) && + isTailscaleIpv4Address(address.address)), + ); +} + function resolveTailscaleIpAdvertisedEndpoints(input: { readonly port: number; readonly networkInterfaces: NetworkInterfaces; @@ -34,40 +57,53 @@ function resolveTailscaleIpAdvertisedEndpoints(input: { }): readonly AdvertisedEndpoint[] { const seen = new Set(); const endpoints: AdvertisedEndpoint[] = []; + const interfaces = Object.entries(input.networkInterfaces); - for (const [interfaceName, interfaceAddresses] of Object.entries(input.networkInterfaces)) { - if (!interfaceAddresses) continue; + // A stopped Tailscale still reports the netmap it had, so its addresses prove nothing. + const tailnetIpv4Addresses = + input.status?.running === false ? [] : (input.status?.tailnetIpv4Addresses ?? []); + // An unclaimed CGNAT address is offered as a VPN route only when the host shows no Tailscale + // identity; the address alone does not show which network it came from. + const hostRunsTailscale = + tailnetIpv4Addresses.length > 0 || + interfaces.some( + ([name, addresses]) => addresses !== undefined && isTailscaleInterface(name, addresses), + ); - // CGNAT is shared with other VPNs; adapter identity works without current CLI status. - const isTailscaleInterface = - /^tailscale(?:\d+|ipv[46])?$/iu.test(interfaceName) || - interfaceAddresses.some( - (address) => - !address.internal && - address.family === "IPv6" && - /^fd7a:115c:a1e0:/iu.test(address.address), - ); + for (const [interfaceName, interfaceAddresses] of interfaces) { + if (!interfaceAddresses) continue; + const onTailscaleInterface = isTailscaleInterface(interfaceName, interfaceAddresses); for (const address of interfaceAddresses) { if (address.internal) continue; if (address.family !== "IPv4") continue; if (!isTailscaleIpv4Address(address.address)) continue; - if (!isTailscaleInterface && !input.status?.tailnetIpv4Addresses.includes(address.address)) { - continue; - } if (seen.has(address.address)) continue; + const isTailscaleAddress = + onTailscaleInterface || tailnetIpv4Addresses.includes(address.address); + if (!isTailscaleAddress && hostRunsTailscale) continue; seen.add(address.address); + const httpBaseUrl = `http://${address.address}:${input.port}`; endpoints.push( createAdvertisedEndpoint({ - provider: TAILSCALE_ENDPOINT_PROVIDER, source: "desktop-addon", - id: `tailscale-ip:http://${address.address}:${input.port}`, - label: "Tailscale IP", - httpBaseUrl: `http://${address.address}:${input.port}`, + httpBaseUrl, reachability: "private-network", status: "available", - description: "Reachable from devices on the same Tailnet.", + ...(isTailscaleAddress + ? { + provider: TAILSCALE_ENDPOINT_PROVIDER, + id: `tailscale-ip:${httpBaseUrl}`, + label: "Tailscale IP", + description: "Reachable from devices on the same Tailnet.", + } + : { + provider: VPN_ENDPOINT_PROVIDER, + id: `vpn-ip:${httpBaseUrl}`, + label: "VPN IP", + description: "Reachable from devices on the same VPN.", + }), }), ); } diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 48b61dbefd025..950a4123453a9 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -24,6 +24,7 @@ export interface ElectronMenuTemplateInput { readonly window: Electron.BrowserWindow; readonly template: readonly Electron.MenuItemConstructorOptions[]; readonly frame?: Electron.WebFrameMain; + readonly source: Option.Option>; } const ElectronMenuOperation = Schema.Literals([ @@ -242,6 +243,7 @@ export const make = Effect.gen(function* () { Electron.Menu.buildFromTemplate([...input.template]).popup({ window: input.window, ...(input.frame ? { frame: input.frame } : {}), + ...(Option.isSome(input.source) ? { sourceType: input.source.value } : {}), }), catch: (cause) => new ElectronMenuOperationError({ diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index 0cc22bb4b1633..008cdf4fbbb54 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -1,10 +1,13 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Runs the same shell command electron-updater would, without blocking. +import * as NodeChildProcess from "node:child_process"; + import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; -import { AppImageUpdater, autoUpdater } from "electron-updater"; +import { AppImageUpdater, autoUpdater, DebUpdater } from "electron-updater"; type AutoUpdater = typeof autoUpdater; type SpawnLog = (cmd: string, args?: Array, ...rest: Array) => Promise; @@ -28,6 +31,108 @@ const relaunchWithoutInheritedDescriptors = (updater: AppImageUpdater) => { }; }; +interface DebUpdaterInternals { + readonly installerPath: string | null; + readonly downloadedUpdateHelper: { readonly downloadedFileInfo: unknown } | null; + quitAndInstallCalled: boolean; + readonly app: { relaunch: () => void }; + readonly _logger: { + info: (message: string) => void; + warn: (message: string) => void; + error: (message: string) => void; + }; + hasCommand: (cmd: string) => boolean; + detectPackageManager: (pms: Array) => string; + runCommandWithSudoIfNeeded: (commandWithArgs: Array) => string; + spawnSyncLog: (cmd: string, args?: Array, env?: object) => string; + sanitizeEnvPath: (envPath: string) => string; + doInstall: (options: { readonly isForceRunAfter: boolean }) => boolean; +} + +// DebUpdater runs pkexec/sudo and dpkg through spawnSync, which freezes the main thread for the +// whole polkit prompt and install. This resolves the exact command it would run (sudo choice, +// quoting, PATH sanitizing) and runs it asynchronously instead. +const runWithSudoInBackground = (updater: DebUpdaterInternals, commandWithArgs: Array) => { + let resolved: { cmd: string; args: Array } | undefined; + updater.spawnSyncLog = function (cmd, args = [], env) { + if (cmd === "command") return DebUpdater.prototype["spawnSyncLog"].call(this, cmd, args, env); + resolved = { cmd, args }; + return ""; + }; + try { + updater.runCommandWithSudoIfNeeded(commandWithArgs); + } finally { + delete (updater as Partial).spawnSyncLog; + } + const { cmd, args } = resolved!; + updater._logger.info(`Executing: ${cmd} with args: ${args}`); + return new Promise((resolve, reject) => { + const child = NodeChildProcess.spawn(cmd, args, { + env: { ...process.env, PATH: updater.sanitizeEnvPath(process.env.PATH ?? "") }, + shell: true, + stdio: ["ignore", "ignore", "pipe"], + }); + let stderr = ""; + child.stderr?.on("data", (chunk) => { + stderr += String(chunk); + }); + child.once("error", reject); + child.once("close", (status) => { + if (status === 0) return resolve(); + updater._logger.error(stderr); + reject(new Error(`Command ${cmd} exited with code ${status}`)); + }); + }); +}; + +const installDebInBackground = async ( + updater: DebUpdaterInternals, + isSilent: boolean, + isForceRunAfter: boolean, +) => { + if (updater.quitAndInstallCalled) return; + const installerPath = updater.installerPath; + if (installerPath === null || updater.downloadedUpdateHelper?.downloadedFileInfo == null) { + throw new Error("No update filepath provided, can't quit and install"); + } + if (!updater.hasCommand("dpkg") && !updater.hasCommand("apt")) { + throw new Error("Neither dpkg nor apt command found. Cannot install .deb package."); + } + // Only the first command is recorded: the runner never throws, so upstream's fallback never runs. + let install: Array | undefined; + DebUpdater.installWithCommandRunner( + updater.detectPackageManager(["dpkg", "apt"]) as "dpkg" | "apt", + installerPath, + (commandWithArgs) => { + install ??= commandWithArgs; + }, + updater._logger, + ); + updater.quitAndInstallCalled = true; + try { + await runWithSudoInBackground(updater, install!).catch((error) => { + if (install![0] !== "dpkg") throw error; + updater._logger.warn(String(error instanceof Error ? error.message : error)); + updater._logger.warn( + "dpkg installation failed, trying to fix broken dependencies with apt-get", + ); + return runWithSudoInBackground(updater, ["apt-get", "install", "-f", "-y"]); + }); + } finally { + updater.quitAndInstallCalled = false; + } + // The package is installed; let electron-updater's own quitAndInstall relaunch and quit. + updater.doInstall = function ({ isForceRunAfter }) { + if (isForceRunAfter) this.app.relaunch(); + return true; + }; + try { + (updater as unknown as DebUpdater).quitAndInstall(isSilent, isForceRunAfter); + } finally { + delete (updater as Partial).doInstall; + } +}; + export type ElectronUpdaterFeedUrl = Parameters[0]; export class ElectronUpdaterCheckForUpdatesError extends Schema.TaggedError()( @@ -174,6 +279,19 @@ export const make = ElectronUpdater.of({ return Effect.suspend(() => { const channel = autoUpdater.channel; if (autoUpdater instanceof AppImageUpdater) relaunchWithoutInheritedDescriptors(autoUpdater); + if (autoUpdater instanceof DebUpdater) { + const updater = autoUpdater as unknown as DebUpdaterInternals; + return Effect.tryPromise({ + try: () => installDebInBackground(updater, isSilent, isForceRunAfter), + catch: (cause) => + new ElectronUpdaterQuitAndInstallError({ + channel, + isSilent, + isForceRunAfter, + cause, + }), + }); + } return Effect.try({ try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter), catch: (cause) => diff --git a/apps/desktop/src/electron/ElectronUpdaterDeb.test.ts b/apps/desktop/src/electron/ElectronUpdaterDeb.test.ts new file mode 100644 index 0000000000000..d1b89a6f29f0d --- /dev/null +++ b/apps/desktop/src/electron/ElectronUpdaterDeb.test.ts @@ -0,0 +1,127 @@ +// @effect-diagnostics nodeBuiltinImport:off -- A synchronous fs watcher proves the main thread stays free. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { autoUpdater, DebUpdater } from "electron-updater"; +import * as NodeFS from "node:fs"; +import { vi } from "vite-plus/test"; + +// electron-updater requires Electron natively and picks its autoUpdater class from +// resources/package-type the first time the singleton is read. +const electronApp = vi.hoisted(() => { + const NodeModule = process.getBuiltinModule("node:module"); + const NodeEvents = process.getBuiltinModule("node:events"); + const NodeHoistedFS = process.getBuiltinModule("node:fs"); + const NodeOs = process.getBuiltinModule("node:os"); + const NodePath = process.getBuiltinModule("node:path"); + const require = NodeModule.createRequire(import.meta.url); + const electronPath = NodeModule.createRequire(require.resolve("electron-updater")).resolve( + "electron", + ); + const resourcesPath = NodeHoistedFS.mkdtempSync( + NodePath.join(NodeOs.tmpdir(), "t3-deb-resources-"), + ); + NodeHoistedFS.writeFileSync(NodePath.join(resourcesPath, "package-type"), "deb"); + Object.assign(process, { resourcesPath }); + const state = { relaunches: 0, onQuit: (): void => undefined }; + const electronModule = new NodeModule.Module(electronPath); + electronModule.filename = electronPath; + electronModule.loaded = true; + electronModule.exports = { + app: { + getVersion: () => "1.0.0", + getName: () => "T3 Code", + isPackaged: true, + relaunch: () => { + state.relaunches += 1; + }, + quit: () => state.onQuit(), + once: () => undefined, + }, + autoUpdater: new NodeEvents.EventEmitter(), + }; + require.cache[electronPath] = electronModule; + return state; +}); + +import * as ElectronUpdater from "./ElectronUpdater.ts"; + +const inheritedPath = process.env.PATH ?? ""; + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "ElectronUpdater .deb install", + () => { + it.live("keeps the main process responsive while dpkg installs, then quits", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-deb-install-" }); + const bin = path.join(dir, "bin"); + const startedPath = path.join(dir, "started"); + const releasedPath = path.join(dir, "released"); + const installedPath = path.join(dir, "installed"); + yield* fileSystem.makeDirectory(bin); + const tools = { + pkexec: '[ "$1" = --disable-internal-agent ] && shift\nexec "$@"', + // Blocks on one read of a FIFO that only the main event loop's watcher writes to. The + // read's bound only lets a blocked main thread (the bug) fail instead of hanging forever. + dpkg: `mkfifo '${releasedPath}'\nexec 3<>'${releasedPath}'\ntouch '${startedPath}'\nread -t 10 _ <&3 || exit 1\necho "$@" > '${installedPath}'`, + "apt-get": "exit 1", + }; + for (const [name, script] of Object.entries(tools)) { + yield* fileSystem.writeFileString(path.join(bin, name), `#!/bin/bash\n${script}\n`); + yield* fileSystem.chmod(path.join(bin, name), 0o755); + } + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("PATH", `${bin}:${inheritedPath}`)), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + + assert.instanceOf(autoUpdater, DebUpdater); + autoUpdater.logger = null; + Object.assign(autoUpdater, { + downloadedUpdateHelper: { + file: path.join(dir, "t3-code_1.0.1_amd64.deb"), + downloadedFileInfo: { isAdminRightsRequired: false }, + }, + }); + const quit = yield* Deferred.make(); + electronApp.onQuit = () => Deferred.doneUnsafe(quit, Effect.void); + + // The watcher fires only if the main thread is free while dpkg runs. + yield* Effect.acquireRelease( + Effect.sync(() => + NodeFS.watch(dir, (_event, name) => { + if (name !== "started") return; + // Non-blocking: once dpkg has given up there is no reader, and the open fails instead + // of wedging the main thread. + try { + const fifo = NodeFS.openSync( + releasedPath, + NodeFS.constants.O_WRONLY | NodeFS.constants.O_NONBLOCK, + ); + NodeFS.writeSync(fifo, "\n"); + NodeFS.closeSync(fifo); + } catch {} + }), + ), + (watcher) => Effect.sync(() => watcher.close()), + ); + + const electronUpdater = yield* ElectronUpdater.ElectronUpdater; + yield* electronUpdater.quitAndInstall({ isSilent: true, isForceRunAfter: true }); + yield* Deferred.await(quit); + + assert.strictEqual( + (yield* fileSystem.readFileString(installedPath)).trim(), + `-i ${path.join(dir, "t3-code_1.0.1_amd64.deb")}`, + ); + assert.strictEqual(electronApp.relaunches, 1); + }).pipe(Effect.provide([ElectronUpdater.layer, NodeServices.layer])), + ); + }, +); diff --git a/apps/desktop/src/i18n/messages.ts b/apps/desktop/src/i18n/messages.ts index 72fe7487796c3..0c9afa0a3b33f 100644 --- a/apps/desktop/src/i18n/messages.ts +++ b/apps/desktop/src/i18n/messages.ts @@ -16,6 +16,7 @@ const CATALOGS: Readonly Promise<{ readonly default: Catalo fr: () => import("./translations/fr.json", { with: { type: "json" } }), ja: () => import("./translations/ja.json", { with: { type: "json" } }), ko: () => import("./translations/ko.json", { with: { type: "json" } }), + pl: () => import("./translations/pl.json", { with: { type: "json" } }), "pt-BR": () => import("./translations/pt-BR.json", { with: { type: "json" } }), ru: () => import("./translations/ru.json", { with: { type: "json" } }), sv: () => import("./translations/sv.json", { with: { type: "json" } }), diff --git a/apps/desktop/src/i18n/translations/pl.json b/apps/desktop/src/i18n/translations/pl.json new file mode 100644 index 0000000000000..c4a242d5b597d --- /dev/null +++ b/apps/desktop/src/i18n/translations/pl.json @@ -0,0 +1,127 @@ +{ + "e92e3cb4b7e388b2": "Nie udało się uruchomić M3 Code", + "45e444e807bececb": "Ten katalog domowy T3 jest niedostępny", + "97665653aa9129ad": "Sprawdzanie, czy jest nowsza wersja…", + "dce25e68e60eb512": "Wersja {version} jest dostępna. Może zawierać poprawkę.", + "2f015e6d5459dce9": "Zaktualizuj do wersji {version}", + "08a2e73f43a48ded": "Pobieranie wersji {version}. M3 Code uruchomi się ponownie po zakończeniu pobierania.", + "e43d99397def819b": "Pobieranie wersji {version} ({percent}%). M3 Code uruchomi się ponownie po zakończeniu pobierania.", + "4b4cf6843a4e0aba": "Wersja {version} działała poprawnie na tym komputerze. Pobierz ją i zainstaluj, aby przywrócić starszą wersję.", + "b57c6134d74c0848": "Pobierz wersję {version}", + "1eeed583c2254507": "Inną wersję znajdziesz na stronie wydań.", + "4cd5b64eeb26e1ee": "Otwórz stronę wydań", + "2b0a0f8d837cfa70": "Zarządzana zasada Twojej organizacji zablokowała uruchomienie M3 Code. Przekaż poniższe szczegóły administratorowi IT.", + "e635f208a614b02f": "Nie udało się uruchomić M3 Code", + "4825d2a18a5fc093": "Skopiuj szczegóły", + "3874c9f538653a6d": "Zakończ", + "0eec8b51246f5e2c": "Serwer nie zwrócił żadnych komunikatów.", + "767a0a8a1f44e0c4": "Wersja {version}. M3 Code spróbuje ponownie w tle. Dzienniki: {logDir}", + "895f988b9de16f88": "Backend WSL nadal jest niedostępny", + "cef32a70d80330a9": "Przy tym uruchomieniu M3 Code użyje backendu Windows i spróbuje ponownie z WSL przy następnym starcie aplikacji.", + "b5435aa5b470bafd": "Nie udało się uruchomić backendu WSL", + "7db19d8fc59bb54a": "Przechodzimy na backend Windows, aby M3 Code mógł się otworzyć. Po naprawieniu dystrybucji WSL włącz ponownie backend WSL w Ustawienia > Udostępnianie i dostęp.", + "485124943cecf027": "Inny serwer M3 Code, na przykład usługa w tle, korzysta z tego katalogu danych albo jest dla niego skonfigurowana starsza usługa w tle. Zatrzymaj ten serwer lub wykonaj `t3 update`. Jeśli starszy program uruchamiający nie może się zaktualizować, wykonaj `t3 service uninstall`, a opcjonalnie zainstaluj ponownie poleceniem `t3 service install` z aktualnego interfejsu CLI. Użyj `npx t3@latest`, jeśli polecenie `t3` nie istnieje lub jest nieaktualne, i do każdego polecenia przekaż `--base-dir` z katalogiem domowym T3 usługi. Następnie otwórz M3 Code ponownie. Możesz też ustawić oddzielne T3CODE_HOME i sparować się z uruchomionym serwerem.", + "6a3b3098f3a260c6": "Usługa w tle M3 Code korzysta z tego katalogu domowego T3 (PID {pid}, port {port}, wersja {version}). Zatrzymaj ją poleceniem `t3 service uninstall`, przekazując `--base-dir` z tym katalogiem domowym T3, a następnie otwórz M3 Code ponownie. Możesz też ustawić oddzielne T3CODE_HOME i sparować się z uruchomionym serwerem.", + "0a43b2ea4eabbb80": "Usługa w tle M3 Code korzysta z tego katalogu domowego T3 (PID {pid}, port {port}). Zatrzymaj ją poleceniem `t3 service uninstall`, przekazując `--base-dir` z tym katalogiem domowym T3, a następnie otwórz M3 Code ponownie. Możesz też ustawić oddzielne T3CODE_HOME i sparować się z uruchomionym serwerem.", + "d1e26eb0257aa502": "Inny serwer M3 Code (na przykład `t3 serve` albo serwer uruchomiony przez SSH) korzysta z tego katalogu domowego T3 (PID {pid}, port {port}, wersja {version}). Jeśli aplikacja M3 Code na innym komputerze uruchomiła go przez SSH, ta aplikacja zrestartuje go ponownie: usuń lub rozłącz tam to środowisko SSH albo zamknij tę aplikację. Następnie zatrzymaj serwer i otwórz M3 Code ponownie. Możesz też ustawić oddzielne T3CODE_HOME i sparować się z uruchomionym serwerem.", + "5d64ab938343834a": "Inny serwer M3 Code (na przykład `t3 serve` albo serwer uruchomiony przez SSH) korzysta z tego katalogu domowego T3 (PID {pid}, port {port}). Jeśli aplikacja M3 Code na innym komputerze uruchomiła go przez SSH, ta aplikacja zrestartuje go ponownie: usuń lub rozłącz tam to środowisko SSH albo zamknij tę aplikację. Następnie zatrzymaj serwer i otwórz M3 Code ponownie. Możesz też ustawić oddzielne T3CODE_HOME i sparować się z uruchomionym serwerem.", + "6574442caf8bfd15": "Skonfiguruj nagrywanie ekranu", + "a8210440c691b062": "Skonfiguruj dostępność", + "0cbbbd8abd25f9d4": "Skonfiguruj pełny dostęp do dysku", + "4cd679200c978949": "Zamknij pomocnika uprawnień", + "2748937e18560082": "↑ Przeciągnij M3 Code na powyższą listę", + "5ad456e1d7311a33": "Przeciągnij M3 Code do Ustawień systemowych albo kliknij, aby pokazać go w Finderze", + "278648c9ff6fb9ce": "Tego certyfikatu nie wydał żaden zaufany urząd.", + "cf346dcfb658d4d3": "Ten certyfikat nie jest przeznaczony dla tego adresu.", + "20665d9b0c7c3e52": "Ten certyfikat wygasł albo jeszcze nie obowiązuje.", + "565970a378986341": "Otwórz", + "00ad8aeed0a6c461": "Anuluj", + "2107cc3e7c4ac833": "Otworzyć ten link {protocol}?", + "050db36de6624203": "Strona w przeglądarce chce otworzyć inną aplikację:\n\n{url}", + "c1d7515ac0214ca1": "Zaufaj i zapamiętaj", + "e89b5b30b1bc99bb": "{host} używa niezaufanego certyfikatu", + "16d4c8a1431bd8c2": "Wydany dla: {name}", + "5862c92e2dabefab": "Wydany przez: {name}", + "cf559f06dc2e5432": "Ważność: {start} – {end}", + "86fe6451f52e722a": "Odcisk: {fingerprint}", + "7b20c92539acb4b6": "Zaufaj, tylko jeśli wiesz, że ten certyfikat należy do tej witryny. Wyczyszczenie plików cookie tego profilu przeglądarki spowoduje utratę zaufania.", + "c67ec08c2c8d0cd9": "Nie udało się oznaczyć certyfikatu dla {host} jako zaufanego", + "329a2533583e987c": "M3 Code nie mógł zapisać tej zgody, więc strona pozostaje zablokowana. Sprawdź, czy dysk nie jest pełny i czy folder danych umożliwia zapis, a następnie spróbuj ponownie.", + "a0315d43e8e5be7e": "Zezwól", + "2ec823ca24387055": "Zablokuj", + "709219ff9ff49a4f": "{origin} chce poznać Twoją lokalizację", + "8fc0b116123fb50b": "{origin} chce zobaczyć tekst i obrazy skopiowane do schowka", + "c0f756221736393f": "Podgląd · {title}", + "6994444f4fec4070": "Podgląd w przeglądarce", + "49de6209699eb616": "Klucz dostępu bez nazwy", + "b4a5bb1075d95154": "Wybierz klucz dostępu", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stabilna", + "1f12213f4d809e89": "Masz najnowszą wersję!", + "1431b1e39f49fbda": "M3 Code {version} to obecnie najnowsza dostępna wersja.", + "b6e5b31255e011c5": "OK", + "2ee2077700686fbb": "Dostępna aktualizacja", + "56b8a4be1c33293b": "Dostępna jest nowa wersja M3 Code.", + "f4be083f34bdbc95": "Dostępny jest M3 Code {version}.", + "e15ed9d864e3c0f2": "Korzystasz z M3 Code {version}.", + "374b1cb8cb616d27": "Pobierz", + "b0d022fe9d78def7": "Później", + "b9a0301ee1348da9": "Pobieranie aktualizacji", + "7df965ef08b54dd7": "Nowa wersja M3 Code już się pobiera.", + "edc14868ee1061e4": "M3 Code {version} już się pobiera.", + "bd6818c7f005654c": "Aktualizacja gotowa", + "00e46030e40f1ad8": "Nowa wersja M3 Code jest gotowa do instalacji.", + "c15e118fbbb681d7": "M3 Code {version} jest gotowy do instalacji.", + "ae09be373a12dcd2": "M3 Code uruchomi się ponownie, aby ją zainstalować. Wszystkie uruchomione zadania zostaną przerwane.", + "2f0a8211a72e29aa": "Uruchom ponownie", + "116a21f6cc215e5f": "Nie udało się sprawdzić aktualizacji", + "32c88cd9421abf33": "Nie można sprawdzić aktualizacji.", + "9e5ada64a94c10de": "Ta kompilacja {build} nie może samodzielnie zaktualizować się z kanału {saved}. Przełącz kanał aktualizacji z powrotem na {build} albo użyj opcji Przejrzyj obok ustawienia Kanał aktualizacji, aby ponowić przełączenie na {saved}.", + "b37aca07d3c644d9": "Wystąpił nieznany błąd. Spróbuj ponownie później.", + "c8c23435e780a60c": "Aktualizacje niedostępne", + "aecf7c98b81bef7a": "Automatyczne aktualizacje są obecnie niedostępne.", + "835247f842c92bc9": "O aplikacji {appName}", + "959e09151d75e25b": "Sprawdź aktualizacje...", + "0c753e71e2dca0d0": "Ustawienia...", + "d510731926e3ceed": "Usługi", + "a9fad846cd549d96": "Ukryj {appName}", + "4bd5ee69cf690b2d": "Ukryj pozostałe", + "9d2c1417fb5f62ec": "Pokaż wszystkie", + "4b375f39bfce229e": "Zakończ {appName}", + "83506e64878b7b48": "Plik", + "b1f24efbd4e80225": "Zamknij narzędzia deweloperskie", + "2c85ee66be8b81b5": "Zamknij okno", + "a4bf583403a4125b": "Wyjście", + "35b959237c8b221c": "Zakończ", + "31bfa0ca146dc77f": "Edycja", + "8a6e013aa2aba5df": "Cofnij", + "ccae47bbef819830": "Ponów", + "228c600d0e283938": "Wytnij", + "30b1b78cffc780c2": "Kopiuj", + "7aced881395f74eb": "Wklej", + "ebf150404ed417d5": "Wklej jako tekst", + "983c993d804f0b29": "Usuń", + "efb0c6cb3adb0d8d": "Zaznacz wszystko", + "660715835d05ddca": "Mowa", + "f0995859f0a14a6b": "Rozpocznij czytanie", + "660e62472f879a5f": "Zatrzymaj czytanie", + "25994350fd047a38": "Widok", + "573a9e6b17f4e9e3": "Odśwież", + "826cb3059ebc7cc3": "Wymuś odświeżenie", + "8340487d05e832e8": "Przełącz narzędzia deweloperskie", + "a7ab66e786347118": "Rzeczywisty rozmiar", + "a4ad1b27fdc9032d": "Powiększ", + "df6ed2014f1737a8": "Zmniejsz", + "50fe114d093a5bc7": "Przełącz pełny ekran", + "d8c6d6d9845353da": "Okno", + "f184aa190588625e": "Minimalizuj", + "c20a9deaed71bd1c": "Powiększanie", + "d207ba3a23f94223": "Umieść wszystkie na wierzchu", + "7a72a6736dd09f82": "Pomoc", + "953979a4737f48fa": "Brak podpowiedzi", + "202e13f15a3dcd30": "Kopiuj link", + "8af79268f2349f4c": "Kopiuj adres e-mail", + "a9f9254d458e49fe": "Kopiuj obraz", + "9c1b20fbc881de5d": "Konfiguracja pulpitu", + "1b14230874f19eb9": "Obrazy" +} diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 9dc0465c1e55a..cb84223b73a07 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -39,6 +39,7 @@ import * as Schema from "effect/Schema"; import * as Option from "effect/Option"; import * as NodeURL from "node:url"; +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as ElectronWindow from "../../electron/ElectronWindow.ts"; import * as BrowserImport from "../../preview/BrowserImport/BrowserImport.ts"; import * as LoopbackTunnel from "../../preview/LoopbackTunnel.ts"; @@ -363,6 +364,7 @@ const getPreviewConfig = DesktopIpc.makeIpcMethod({ }) { const manager = yield* PreviewManager.PreviewManager; const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + const environment = yield* DesktopEnvironment.DesktopEnvironment; const { scope, persistent, namespace } = resolvePartitionScope(environmentId, profileId); // Session creation installs UA and permission handlers before a guest can attach. const session = yield* manager.getBrowserSession(scope, persistent, namespace); @@ -371,7 +373,7 @@ const getPreviewConfig = DesktopIpc.makeIpcMethod({ return { partition: yield* manager.getBrowserPartition(scope, persistent, namespace), webPreferences: PREVIEW_WEBVIEW_PREFERENCES, - preloadUrl: NodeURL.pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href, + preloadUrl: NodeURL.pathToFileURL(environment.previewPickPreloadPath).href, }; }), }); diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.test.ts index 28099a0e74f50..720ba29e37a7b 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 { }).pipe(Effect.provide(layer)), ); + it.effect("cuts a long certificate name without splitting an emoji", () => + 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); + + showMessageBox.mockReset(); + showMessageBox.mockReturnValue(1); + const longName = `${"a".repeat(119)}\u{1F600} dev certificate`; + const prompt = certificateError(browserSession, { + url: "https://localhost:18443/", + certificate: { ...selfSignedCertificate, subjectName: longName }, + }); + assert.isFalse(yield* prompt.trusted); + const detail = showMessageBox.mock.calls[0]?.[0].detail ?? ""; + const issuedTo = detail.split("\n").find((line) => line.startsWith("Issued to: ")); + assert.strictEqual(issuedTo, `Issued to: ${"a".repeat(119)}…`); + }).pipe(Effect.provide(layer)), + ); + it.effect("asks before trusting an untrusted certificate and remembers the approval", () => 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 6a7cba7c323c1..c520098539fca 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -163,7 +163,7 @@ const CERTIFICATE_APPROVALS_FILE = "t3code-certificate-approvals.json"; /** Server-chosen certificate names must not add lines or flood the prompt. */ const promptCertificateName = (name: string): string => { const flat = name.replace(/\s+/g, " ").trim(); - return flat.length > 120 ? `${flat.slice(0, 120)}…` : flat; + return flat.length > 120 ? `${flat.slice(0, 120).replace(/\p{Surrogate}$/u, "")}…` : flat; }; const promptCertificateDate = (seconds: number): string => diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 1eb6f00da37cb..20ee28c680740 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -1166,6 +1166,55 @@ describe("DesktopBrowserHost", () => { }), ); + // regression: #44003 agent typing into a cross-site iframe field was refused while the preview was unfocused + it.effect("types into the cross-site frame holding an unfocused guest's focus", () => + Effect.gen(function* () { + const host = yield* makeDrawnHost; + // The page's focus is an iframe whose document it cannot read; that frame focuses a field. + const debuggee = makeDebuggee({ + answer: (method, sessionId) => { + if (method === "Runtime.evaluate") { + return sessionId === undefined + ? { result: { type: "object", value: false, objectId: "FOCUSED-IFRAME" } } + : { result: { type: "undefined" } }; + } + if (method === "DOM.describeNode") return { node: { frameId: "FRAME" } }; + if (method === "Runtime.releaseObject") return {}; + return undefined; + }, + }); + host.attach(key, debuggee.tab); + const errors: Array = []; + yield* host.events.pipe( + Stream.map((line) => decodeEvent(new TextDecoder().decode(line))), + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type !== "cdp") return; + const { error } = decodeCdpError(event.message); + if (error) errors.push(error.message); + }), + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + debuggee.emit("Target.attachedToTarget", { + sessionId: "FRAME-SESSION", + targetInfo: { targetId: "FRAME", type: "iframe" }, + }); + + yield* command(host, 1, "Input.insertText"); + yield* settle; + debuggee.release(); + yield* settle; + + expect(errors).toEqual([]); + expect(debuggee.methods).toContain("Input.insertText"); + expect(debuggee.sessionIds[debuggee.methods.indexOf("Input.insertText")]).toBe( + "FRAME-SESSION", + ); + }).pipe(Effect.scoped), + ); + it.effect("fails mouse input whose frame detaches before taking it, then moves on", () => Effect.gen(function* () { const host = yield* makeDrawnHost; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index b0fe8509a51fa..7eb049ab8cdae 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -20,6 +20,7 @@ import { createCdpRelayConnection, type CdpRelayConnection } from "./CdpRelay.ts import { type FrameDetachWatch, type PointerRoute, + routeKeysToFrame, routeMouseToFrame, sendPageCommand, } from "./GuestInput.ts"; @@ -500,6 +501,7 @@ export const make = Effect.gen(function* () { if (tab.relay) return tab.relay; const { webContents, debugger: debuggee, cookiesCleared } = tab.debuggee; const routeHidden = routeMouseToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab)); + const routeKeys = routeKeysToFrame(debuggee, tab.frameSessions, watchFrameDetach(tab)); // Read when the pointer queue reaches the event: a guest the window shows routes its own input. const routeMouse: PointerRoute = (params) => shownTabs.get(keyOf(tab.key)) === true ? Promise.resolve(null) : routeHidden(params); @@ -521,6 +523,7 @@ export const make = Effect.gen(function* () { sessionId, routeMouse, refuseAnnotated, + routeKeys, ); if (method === "Network.clearBrowserCookies") await cookiesCleared?.(); return result; diff --git a/apps/desktop/src/preview/FaviconCapture.test.ts b/apps/desktop/src/preview/FaviconCapture.test.ts index 2163dc002b703..d3baefd7deecd 100644 --- a/apps/desktop/src/preview/FaviconCapture.test.ts +++ b/apps/desktop/src/preview/FaviconCapture.test.ts @@ -303,6 +303,28 @@ describe("captureFavicon", () => { expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2); }); + it("decodes percent-escaped base64 inline images like the unescaped form", async () => { + const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents(); + const base64 = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="; + + for (const payload of [base64, encodeURIComponent(base64)]) { + expect( + await captureFavicon({ + webContents, + pageUrl: "https://example.com/page", + candidates: [`data:image/png;base64,${payload}`], + signal: new AbortController().signal, + }), + ).toEqual({ kind: "captured", dataUrl: PNG }); + } + + const [plain, escaped] = executeJavaScriptInIsolatedWorld.mock.calls.map( + ([, scripts]) => scripts[0]?.code, + ); + expect(escaped).toBe(plain); + }); + it("tries the next candidate after an ordinary rejection", async () => { const { webContents, fetch } = makeWebContents({ fetch: async (url) => diff --git a/apps/desktop/src/preview/FaviconCapture.ts b/apps/desktop/src/preview/FaviconCapture.ts index 4716645c9defa..90565f0bcfd19 100644 --- a/apps/desktop/src/preview/FaviconCapture.ts +++ b/apps/desktop/src/preview/FaviconCapture.ts @@ -222,9 +222,12 @@ function parseInlineFavicon( let buffer: Buffer; try { if (base64) { - if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null; - buffer = Buffer.from(payload, "base64"); - if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) { + const encoded = decodeInlineFaviconPayload(payload)?.toString("latin1"); + if (!encoded || !/^[a-z0-9+/]*={0,2}$/i.test(encoded) || encoded.length % 4 === 1) { + return null; + } + buffer = Buffer.from(encoded, "base64"); + if (buffer.toString("base64").replace(/=+$/, "") !== encoded.replace(/=+$/, "")) { return null; } } else { diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 6ab33e3896e4e..0473450be3c61 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -20,9 +20,25 @@ const FOCUSED_DOCUMENT = `(() => { } })()`; +/** The cross-site frame element holding the document's focus, past same-site frames; null if none does. */ +const FOCUSED_CROSS_SITE_FRAME = `(() => { + let doc = document; + for (;;) { + const active = doc.activeElement; + if (active?.tagName !== "IFRAME" && active?.tagName !== "FRAME") return null; + if (!active.contentDocument) return active; + doc = active.contentDocument; + } +})()`; + /** Electron runs editing commands only for CDP keys; exclude clipboard commands to preserve the user's clipboard. */ const EDITING_COMMANDS = new Set(["selectAll", "undo", "redo"]); +const editingCommands = (params: Record) => + Array.isArray(params["commands"]) + ? params["commands"].filter((command) => EDITING_COMMANDS.has(command)) + : undefined; + const CROSS_SITE_FOCUS_MESSAGE = "The page's focus is inside a cross-site frame, which takes typed input only while the preview has focus. Click the field first."; @@ -152,7 +168,7 @@ interface FrameRoute { export type PointerRoute = (params: Record) => Promise; const FRAME_GONE_MESSAGE = - "The frame under the pointer went away before it took this input. Check the page before retrying."; + "The frame went away before it took this input. Check the page before retrying."; const MAX_FRAME_DEPTH = 8; const ROUTE_DEADLINE = "1 second"; @@ -182,6 +198,62 @@ export const routeMouseToFrame = return { ...routed, onDetach }; }; +/** Finds the cross-site frame holding an unfocused guest's focus, if it has a session; null when none does. */ +export type KeyRoute = (params: Record) => Promise; + +/** + * Direct input cannot reach a cross-site frame, and the page session's CDP keys follow window + * focus into the app. The focused frame's own session delivers them to that frame. + */ +export const routeKeysToFrame = + ( + debuggee: Electron.Debugger, + frameSessions: ReadonlyMap, + onDetach: FrameDetachWatch, + ): KeyRoute => + async (params) => { + if (frameSessions.size === 0) return null; + const sessionId = await Effect.runPromise( + Effect.promise(() => locateFocusedFrame(debuggee, frameSessions)).pipe( + Effect.timeoutOption(ROUTE_DEADLINE), + Effect.map(Option.getOrNull), + ), + ); + if (!sessionId) return null; + const commands = editingCommands(params); + return { params: commands ? { ...params, commands } : params, sessionId, onDetach }; + }; + +const locateFocusedFrame = async ( + debuggee: Electron.Debugger, + frameSessions: ReadonlyMap, +) => { + let sessionId: string | undefined; + for (let depth = 0; depth < MAX_FRAME_DEPTH; depth++) { + try { + const { result } = (await debuggee.sendCommand( + "Runtime.evaluate", + { expression: FOCUSED_CROSS_SITE_FRAME }, + sessionId, + )) as { readonly result: { readonly objectId?: string } }; + if (result.objectId === undefined) return sessionId ?? null; + const { objectId } = result; + const { node } = (await debuggee + .sendCommand("DOM.describeNode", { objectId }, sessionId) + .finally(() => { + debuggee.sendCommand("Runtime.releaseObject", { objectId }, sessionId).catch(() => {}); + })) as { readonly node: { readonly frameId?: string } }; + // A cross-site frame's target id is its frame id. + const frameSession = node.frameId === undefined ? undefined : frameSessions.get(node.frameId); + if (frameSession === undefined) return null; + sessionId = frameSession; + } catch { + return null; + } + } + return null; +}; + /** Chromium can drop the reply to input on a frame that detaches before acknowledging it. */ const sendToFrame = (debuggee: Electron.Debugger, method: string, route: FrameRoute) => new Promise((resolve, reject) => { @@ -296,6 +368,7 @@ export const sendPageCommand = async ( sessionId?: string, routeMouse?: PointerRoute, beforeDispatch?: () => void, + routeKeys?: KeyRoute, ): Promise => { if (method === "Input.dispatchMouseEvent") { return sendPointerCommand( @@ -334,7 +407,10 @@ export const sendPageCommand = async ( return debuggee.sendCommand(method, params); } if ((await evaluate(debuggee, `${FOCUSED_DOCUMENT} !== null`)) !== true) { - throw new Error(CROSS_SITE_FOCUS_MESSAGE); + const routed = routeKeys ? await routeKeys(params) : null; + if (!routed) throw new Error(CROSS_SITE_FOCUS_MESSAGE); + beforeDispatch?.(); + return sendToFrame(debuggee, method, routed); } beforeDispatch?.(); switch (method) { @@ -343,9 +419,7 @@ export const sendPageCommand = async ( return {}; case "Input.dispatchKeyEvent": { for (const event of toKeyboardInputEvents(params)) webContents.sendInputEvent(event); - const commands = Array.isArray(params["commands"]) - ? params["commands"].filter((command) => EDITING_COMMANDS.has(command)) - : []; + const commands = editingCommands(params) ?? []; // Runs after the page handles the keys, so the reply also waits for them. await evaluate( debuggee, diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 0144dc1f30b7f..4dff1836efec7 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -37,6 +37,7 @@ const PROBE_TIMEOUT = "3 seconds"; const MAX_FORWARD_CONNECTIONS = 64; const CONNECT_TIMEOUT = "10 seconds"; const OWNER_LOOKUP_TIMEOUT = "5 seconds"; +const EPHEMERAL_BIND_ATTEMPTS = 8; const REPLY_SUCCEEDED = 0; const REPLY_FAILURE = 1; @@ -575,12 +576,32 @@ const make = Effect.gen(function* () { return yield* new LoopbackTunnelSameMachineError({ environmentId, port: remotePort }); } const scope = yield* Scope.fork(listenerScope); - const bind = (port: number) => - NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(scope)); - const preferredPort = (yield* servedOverIpv6(remotePort)) ? 0 : remotePort; - const server = yield* bind(preferredPort).pipe( + const bind = (port: number, target: Scope.Scope = scope) => + NodeSocketServer.make({ port, host: "127.0.0.1" }).pipe(Scope.provide(target)); + // An ephemeral 127.0.0.1 port can be one an IPv6 server here already answers `localhost` + // on. Rejected binds stay open until one is kept so the kernel cannot hand them back. + // Only ::1 is probed: a dual-stack :: probe collides with this very 127.0.0.1 bind. + const bindEphemeral = Effect.gen(function* () { + const rejected = yield* Scope.fork(scope); + for (let attempt = 0; attempt < EPHEMERAL_BIND_ATTEMPTS; attempt++) { + const kept = yield* Scope.fork(scope); + const server = yield* bind(0, kept); + const port = (server.address as NetAddress.InetAddress).port; + if (yield* net.canListenOnHost(port, "::1")) { + yield* Scope.close(rejected, Exit.void); + return server; + } + yield* Scope.addFinalizer(rejected, Scope.close(kept, Exit.void)); + } + return yield* new NetService.NetError({ + message: "Every ephemeral port tried is already served over IPv6 here.", + }); + }); + const server = yield* ( + (yield* servedOverIpv6(remotePort)) ? bindEphemeral : bind(remotePort) + ).pipe( // Taken here, or privileged: any free port still reaches the environment's. - Effect.catch(() => bind(0)), + Effect.catch(() => bindEphemeral), Effect.onError(() => Scope.close(scope, Exit.void)), Effect.mapError( (cause) => new LoopbackTunnelForwardError({ environmentId, port: remotePort, cause }), diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts index d250d726e43e0..527f770fcdfdc 100644 --- a/apps/desktop/src/preview/PickPreload.test.ts +++ b/apps/desktop/src/preview/PickPreload.test.ts @@ -1,3 +1,4 @@ +import type { PreviewAnnotationPayload } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; import { ELEMENT_PICKED_CHANNEL, START_PICK_CHANNEL } from "./GuestProtocol.ts"; @@ -46,6 +47,33 @@ const startAnnotation = (): ShadowRoot => { return shadowRoot; }; +const pickAndAttach = async (element: Element) => { + ipcSend.calls.length = 0; + document.elementsFromPoint = () => [element]; + using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); + const shadowRoot = startAnnotation(); + element.dispatchEvent( + new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), + ); + const attach = Array.from(shadowRoot.querySelectorAll("button")).find( + (button) => button.textContent === "Attach", + ); + const listenerIndex = listeners.mock.contexts.findIndex( + (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", + ); + const listener = listeners.mock.calls[listenerIndex]?.[1]; + if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); + // The DOM test environment has no native input source. + listener.call(attach, { isTrusted: true } as MouseEvent); + + await vi.waitFor(() => + expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), + ); + const [, annotation] = + ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + return (annotation as PreviewAnnotationPayload | undefined)?.elements[0]?.element; +}; + it("switches tools from the keyboard after a toolbar button is clicked", () => { const shadowRoot = startAnnotation(); const region = Array.from(shadowRoot.querySelectorAll("button")).find( @@ -168,7 +196,6 @@ it.each([ ); it("keeps only the well-typed fields of what the page reports about an element", async () => { - ipcSend.calls.length = 0; pageElementContext.mockResolvedValueOnce({ selector: { toString: () => "#object" }, htmlPreview: "", @@ -177,32 +204,9 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [{ functionName: "Checkout", fileName: ["x"], lineNumber: "12", columnNumber: 4 }, 3], }); const card = document.body.appendChild(document.createElement("div")); - document.elementsFromPoint = () => [card]; - using listeners = vi.spyOn(HTMLButtonElement.prototype, "addEventListener"); - const shadowRoot = startAnnotation(); - card.dispatchEvent( - new PointerEvent("pointerdown", { button: 0, clientX: 100, clientY: 100, bubbles: true }), - ); - const attach = Array.from(shadowRoot.querySelectorAll("button")).find( - (button) => button.textContent === "Attach", - ); - const listenerIndex = listeners.mock.contexts.findIndex( - (target, index) => target === attach && listeners.mock.calls[index]?.[0] === "click", - ); - const listener = listeners.mock.calls[listenerIndex]?.[1]; - if (!attach || typeof listener !== "function") throw new Error("Attach listener not found"); - // The DOM test environment has no native input source. - listener.call(attach, { isTrusted: true } as MouseEvent); - - await vi.waitFor(() => - expect(ipcSend.calls.some(([channel]) => channel === ELEMENT_PICKED_CHANNEL)).toBe(true), - ); - const [, annotation] = - ipcSend.calls.find(([channel]) => channel === ELEMENT_PICKED_CHANNEL) ?? []; + const element = await pickAndAttach(card); const frame = { functionName: "Checkout", fileName: null, lineNumber: null, columnNumber: 4 }; - expect( - (annotation as { elements: Array<{ element: unknown }> }).elements[0]?.element, - ).toMatchObject({ + expect(element).toMatchObject({ selector: null, htmlPreview: "", componentName: null, @@ -211,3 +215,11 @@ it("keeps only the well-typed fields of what the page reports about an element", stack: [frame, { functionName: null, fileName: null, lineNumber: null, columnNumber: null }], }); }); + +it("drops a straddling surrogate pair when falling back to outerHTML preview", async () => { + pageElementContext.mockRejectedValueOnce(new Error("page lookup failed")); + const card = document.body.appendChild(document.createElement("div")); + card.textContent = `${"a".repeat(494)}🚀tail`; + expect(card.outerHTML.charCodeAt(499)).toBe(0xd83d); + expect((await pickAndAttach(card))?.htmlPreview).toBe(card.outerHTML.slice(0, 499)); +}); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index a227d5136b6c6..61e3c8070d722 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -494,10 +494,14 @@ async function captureElement(element: Element): Promise { }; } } catch {} + const html = element.outerHTML; + const before = html.charCodeAt(HTML_PREVIEW_MAX_CHARS - 1); + const after = html.charCodeAt(HTML_PREVIEW_MAX_CHARS); + const splitPair = before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff; return { ...base, selector: null, - htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS), + htmlPreview: html.slice(0, splitPair ? HTML_PREVIEW_MAX_CHARS - 1 : HTML_PREVIEW_MAX_CHARS), componentName: null, source: null, stack: [], diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 1c5d4d71713cd..9ad7a163101a3 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -643,6 +643,20 @@ describe("DesktopShellEnvironment", () => { }), ); + it.effect("keeps login-shell PATH entries that contain the capture end marker", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + + yield* runShellEnvironment({ + env, + platform: "darwin", + handler: () => envOutput({ PATH: "/opt/__T3CODE_ENV_PATH_END__/bin:/usr/bin" }), + }); + + assert.equal(env.PATH, "/opt/__T3CODE_ENV_PATH_END__/bin:/usr/bin"); + }), + ); + it.effect("does not mix login-shell locale categories into an inherited locale", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 89b5edecb5786..4e86337634109 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -253,13 +253,12 @@ const extractEnvironment = (output: string, names: ReadonlyArray): Envir if (start === -1) continue; const valueStart = start + startMarker(name).length; - const end = output.indexOf(endMarker(name), valueStart); - if (end === -1) continue; + const endLine = new RegExp(`\\r?\\n${endMarker(name)}(?=\\r?\\n|$)`, "g"); + endLine.lastIndex = valueStart; + const endMatch = endLine.exec(output); + if (endMatch === null) continue; - const value = output - .slice(valueStart, end) - .replace(/^\r?\n/, "") - .replace(/\r?\n$/, ""); + const value = output.slice(valueStart, endMatch.index).replace(/^\r?\n/, ""); if (value.length > 0) { environment[name] = value; } diff --git a/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts b/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts index e2a3b913e6487..2355c2cdb94f9 100644 --- a/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts +++ b/apps/desktop/src/snapShot/CaptureShortcutConfig.test.ts @@ -230,6 +230,14 @@ it("detects conflicts in included Niri configs without changing either file", as await expect(setup.preview(target(), install)).rejects.toThrow("already used"); expect((await NodeFSP.readdir(directory)).sort()).toEqual(["config.kdl", "keys.kdl"]); }); +it("ignores slash-dashed Niri include paths and checks the active one", async () => { + await NodeFSP.appendFile(path, 'include /-"old.kdl" "actual.kdl"\n'); + const actual = NodePath.join(directory, "actual.kdl"); + await NodeFSP.writeFile(actual, "layout { gaps 12; }\n"); + expect((await setup.preview(target(), install)).after).toContain("Ctrl+Shift+2"); + await NodeFSP.writeFile(actual, "binds { Shift+Ctrl+2 { quit; } }"); + await expect(setup.preview(target(), install)).rejects.toThrow("already used"); +}); it("does not edit Omarchy's shipped defaults", async () => { const defaults = NodePath.join(directory, "omarchy", "default", "hypr"); await NodeFSP.mkdir(defaults, { recursive: true }); diff --git a/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts b/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts index 78f41968ba636..9874e823e31aa 100644 --- a/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts +++ b/apps/desktop/src/snapShot/GlobalShiftShortcutWorker.ts @@ -11,19 +11,129 @@ if (!(SNAP_SHOT_MODIFIERS as readonly string[]).includes(requested ?? "")) { process.exit(1); } const [left, right] = WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS[requested as SnapShotModifier]; +const MODIFIER_VIRTUAL_KEYS = new Set([ + 0x10, + 0x11, + 0x12, + 0xff, + ...Object.values(WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS).flat(), +]); + +const HWND_MESSAGE = -3n; +const RIDEV_INPUTSINK = 0x100; +const WM_INPUT = 0x00ff; +const PM_REMOVE = 1; +const RID_INPUT = 0x10000003; +const RIM_TYPEKEYBOARD = 1; +const RI_KEY_BREAK = 1; +// x64/arm64 layouts: MSG is 48 bytes (lParam at 24), RAWINPUTHEADER is 24, RAWKEYBOARD follows it. +const MSG_SIZE = 48; +const RAW_INPUT_HEADER_SIZE = 24; + +// Raw Input queues every key event, so a keystroke between two polls is still seen. +async function openKeyboardActivity(): Promise<() => boolean> { + const { DataType, load, open } = await import("ffi-rs"); + const library = "t3-user32-raw-input"; + open({ library, path: "user32.dll" }); + const className = Buffer.from("STATIC\0", "utf16le"); + const window = load({ + library, + funcName: "CreateWindowExW", + retType: DataType.BigInt, + paramsType: [ + DataType.U32, + DataType.U8Array, + DataType.BigInt, + DataType.U32, + DataType.I32, + DataType.I32, + DataType.I32, + DataType.I32, + DataType.BigInt, + DataType.BigInt, + DataType.BigInt, + DataType.BigInt, + ], + paramsValue: [0, className, 0n, 0, 0, 0, 0, 0, HWND_MESSAGE, 0n, 0n, 0n], + }) as bigint; + if (window === 0n) throw new Error("CreateWindowExW failed"); + const device = Buffer.alloc(16); + device.writeUInt16LE(0x01, 0); + device.writeUInt16LE(0x06, 2); + device.writeUInt32LE(RIDEV_INPUTSINK, 4); + device.writeBigUInt64LE(window, 8); + const registered = load({ + library, + funcName: "RegisterRawInputDevices", + retType: DataType.Boolean, + paramsType: [DataType.U8Array, DataType.U32, DataType.U32], + paramsValue: [device, 1, device.byteLength], + }); + if (!registered) throw new Error("RegisterRawInputDevices failed"); + + const message = Buffer.alloc(MSG_SIZE); + const input = Buffer.alloc(64); + const inputSize = Buffer.alloc(4); + return () => { + let typed = false; + while ( + load({ + library, + funcName: "PeekMessageW", + retType: DataType.Boolean, + paramsType: [DataType.U8Array, DataType.BigInt, DataType.U32, DataType.U32, DataType.U32], + paramsValue: [message, window, WM_INPUT, WM_INPUT, PM_REMOVE], + }) + ) { + inputSize.writeUInt32LE(input.byteLength, 0); + const read = load({ + library, + funcName: "GetRawInputData", + retType: DataType.U32, + paramsType: [ + DataType.BigInt, + DataType.U32, + DataType.U8Array, + DataType.U8Array, + DataType.U32, + ], + paramsValue: [ + message.readBigUInt64LE(24), + RID_INPUT, + input, + inputSize, + RAW_INPUT_HEADER_SIZE, + ], + }); + if (read === 0xffffffff || input.readUInt32LE(0) !== RIM_TYPEKEYBOARD) continue; + const flags = input.readUInt16LE(RAW_INPUT_HEADER_SIZE + 2); + const virtualKey = input.readUInt16LE(RAW_INPUT_HEADER_SIZE + 6); + if ((flags & RI_KEY_BREAK) === 0 && !MODIFIER_VIRTUAL_KEYS.has(virtualKey)) typed = true; + } + return typed; + }; +} async function poll() { const api = await loadWindowsForegroundApi(); + const drainTyping = await openKeyboardActivity(); let active = false; + // A key typed since the pair was last fully up means the overlap came from typing (rolled + // Shifts for consecutive capitals), not a deliberate press, so it does not trigger. + let typed = false; process.send?.("ready"); const timer = setInterval(() => { - const pressed = api.isKeyDown(left) && api.isKeyDown(right); - if (pressed && !active) { + if (drainTyping()) typed = true; + const leftDown = api.isKeyDown(left); + const rightDown = api.isKeyDown(right); + const pressed = leftDown && rightDown; + if (pressed && !active && !typed) { try { process.send?.("trigger"); } catch {} } active = pressed; + if (!leftDown && !rightDown) typed = false; }, POLL_INTERVAL_MS); const shutdown = () => { clearInterval(timer); diff --git a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts index 117ffa652566b..0b4d7b569b887 100644 --- a/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts +++ b/apps/desktop/src/snapShot/MacModifierPairShortcutProcess.ts @@ -12,6 +12,8 @@ const MAC_MODIFIER_PAIR_DEVICE_MASKS: Record $.CGEventSourceCounterForEventType(0, $.kCGEventKeyDown); let active = false; + let idleKeyDowns = keyDowns(); console.log("ready"); while ($.getppid() !== 1) { - const pressed = ($.CGEventSourceFlagsState(0) & both) === both; - if (pressed && !active) console.log("trigger"); + const flags = $.CGEventSourceFlagsState(0); + const pressed = (flags & both) === both; + if (pressed && !active && keyDowns() === idleKeyDowns) console.log("trigger"); active = pressed; + if ((flags & both) === 0) idleKeyDowns = keyDowns(); delay(0.05); } return "orphaned"; diff --git a/apps/desktop/src/snapShot/captureConfigKdl.ts b/apps/desktop/src/snapShot/captureConfigKdl.ts index ca8527549174b..6307775445b5c 100644 --- a/apps/desktop/src/snapShot/captureConfigKdl.ts +++ b/apps/desktop/src/snapShot/captureConfigKdl.ts @@ -95,6 +95,11 @@ export function readKdlNodes(source: string): KdlNode[] { let cursor = 0; const is = (token: Token | undefined, value: string) => token && !token.quoted && token.value === value; + const skipValue = () => { + if (is(tokens[cursor], "(")) while (cursor < tokens.length && !is(tokens[cursor++], ")")); + const value = tokens[cursor++]; + if (!value || ["{", "}", ";", "\n", "=", "("].some((stop) => is(value, stop))) throw invalid(); + }; const nodes = (nested: boolean): KdlNode[] => { const result: KdlNode[] = []; while (cursor < tokens.length) { @@ -125,6 +130,15 @@ export function readKdlNodes(source: string): KdlNode[] { !is(tokens[cursor], "}") ) { const token = tokens[cursor++]!; + if (is(token, "/-") && !is(tokens[cursor], "{")) { + skipValue(); + if (is(tokens[cursor], "=")) { + cursor++; + skipValue(); + } + node.end = tokens[cursor - 1]!.end; + continue; + } if (is(token, "{")) { node.children = nodes(true); const close = tokens[cursor++]; diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index d85709634b455..82400d547482a 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1390,6 +1390,15 @@ describe("describeUpdateErrorCause", () => { cyclic.cause = cyclic; assert.include(DesktopUpdates.describeUpdateErrorCause(cyclic), "[truncated cause]"); assert.isAtMost(DesktopUpdates.describeUpdateErrorCause(cyclic).length, 1024); + + const describeCause = (outer: string, inner: string) => + DesktopUpdates.describeUpdateErrorCause( + Object.assign(new Error(outer), { cause: new Error(inner) }), + ); + const a = "a".repeat(512); + const b = "b".repeat(485); + assert.equal(describeCause(`${a.slice(1)}🚀`, "b"), `Error: ${a.slice(1)}; caused by Error: b`); + assert.equal(describeCause(a, `${b}🚀`), `Error: ${a}; caused by Error: ${b}`); }); it("does not serialize arbitrary payloads or let unreadable errors break logging", () => { @@ -1452,6 +1461,32 @@ describe("DesktopUpdates under a managed policy", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("shows the mirror's notes for a release name without its version", () => { + const harness = makeHarness({ + policy: managed({ feedUrl: "https://updates.example.com/t3code" }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + + harness.emit("update-available", { + version: "1.2.4", + releaseName: "December rollout", + releaseNotes: "- Fix startup", + }); + yield* flushCallbacks; + + const state = yield* updates.getState; + assert.equal(state.availableVersion, "1.2.4"); + assert.deepEqual(state.releaseNotes, [ + { version: "1.2.4", items: ["Fix startup"], totalItems: 1 }, + ]); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("refuses the nightly channel without nightly", () => { const harness = makeHarness({ policy: managed({ allowNightly: false }) }); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 1bd712997dcbd..33e9e0e3b7458 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -244,7 +244,8 @@ function redactMessage(message: string): string { /\b[\w-]*(?:token|password|secret|credential|api[_-]?key)[\w-]*\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi, "[redacted credential]", ) - .slice(0, 512); + .slice(0, 512) + .replace(/\p{Surrogate}$/u, ""); } function summarizeCause(cause: unknown, depth: number): string { @@ -281,7 +282,9 @@ function summarizeCause(cause: unknown, depth: number): string { export function describeUpdateErrorCause(cause: unknown): string { try { - return summarizeCause(cause, 0).slice(0, 1024); + return summarizeCause(cause, 0) + .slice(0, 1024) + .replace(/\p{Surrogate}$/u, ""); } catch { return "UnknownError"; } @@ -1142,7 +1145,8 @@ export const make = Effect.gen(function* () { const checkedAt = yield* currentIsoTimestamp; const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes( - releaseNotesOfOfferedVersion(info), + // A mirror's notes come from the offered version's own manifest, not a GitHub feed entry. + policy.feedUrl !== undefined ? info.releaseNotes : releaseNotesOfOfferedVersion(info), info.version, state.channel, info.releaseDate, diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts index a8fcc70ea355c..f1c5ffd07dc3f 100644 --- a/apps/desktop/src/updates/releaseNotes.test.ts +++ b/apps/desktop/src/updates/releaseNotes.test.ts @@ -299,4 +299,16 @@ describe("normalizeDesktopUpdateReleaseNotes", () => { omittedReleaseCount: 0, }); }); + + it("does not split a surrogate pair when truncating a long item", () => { + const result = normalizeDesktopUpdateReleaseNotes( + `- ${"a".repeat(215)} 🚀 trailing text`, + "1.2.3", + "latest", + ); + + const item = result.releaseNotes[0]?.items[0]; + expect(item).toBe(`${"a".repeat(215)}...`); + expect(item?.isWellFormed()).toBe(true); + }); }); diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index 30bfb9ace64b8..bf874062b7d7e 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -70,7 +70,10 @@ function stripMarkup(input: string, keepBold = false): string { function truncateReleaseNoteItem(item: string): string { if (item.length <= MAX_RELEASE_NOTE_ITEM_LENGTH) return item; - return `${item.slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3).trimEnd()}...`; + return `${item + .slice(0, MAX_RELEASE_NOTE_ITEM_LENGTH - 3) + .replace(/\p{Surrogate}$/u, "") + .trimEnd()}...`; } function normalizeReleaseNoteLine(line: string): string { diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 74a3a9b38130e..0ce83f0d3540b 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -77,6 +77,9 @@ function makeFakeBrowserWindow() { id: 1, session: { setPermissionRequestHandler: vi.fn(), + availableSpellCheckerLanguages: ["en-GB", "en-US"], + getSpellCheckerLanguages: vi.fn(() => ["en-US"]), + setSpellCheckerLanguages: vi.fn(), webRequest: { onBeforeSendHeaders: vi.fn(), }, @@ -1557,13 +1560,17 @@ describe("DesktopWindow", () => { if (!willAttachWebview) { return yield* Effect.die("will-attach-webview listener was not registered"); } - const webPreferences: Electron.WebPreferences = {}; + const webPreferences: Electron.WebPreferences = { preload: "/repo/elsewhere/other.cjs" }; willAttachWebview({ preventDefault: () => {} }, webPreferences, { partition: "persist:t3code-preview-test", }); assert.deepEqual(webPreferences.additionalArguments, expected); assert.isTrue(webPreferences.contextIsolation); + assert.equal( + webPreferences.preload, + "/repo/apps/desktop/dist-electron/preview-pick-preload.cjs", + ); }).pipe(Effect.provide(layer)); }), ); @@ -1674,6 +1681,46 @@ describe("DesktopWindow", () => { }), ); + it.effect("opens the edit context menu as a keyboard menu when the keyboard opened it", () => + Effect.gen(function* () { + const fakeWindow = makeFakeBrowserWindow(); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const popup = yield* Deferred.make(); + const layer = layerTest({ + window: fakeWindow.window, + createCount, + mainWindow, + onPopupTemplate: (input) => Deferred.succeed(popup, input), + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const contextMenu = fakeWindow.webContentsListeners.get("context-menu"); + if (!contextMenu) { + return yield* Effect.die("context-menu listener was not registered"); + } + contextMenu( + { preventDefault: vi.fn() }, + { + linkURL: "", + misspelledWord: "", + dictionarySuggestions: [], + mediaType: "none", + menuSourceType: "keyboard", + editFlags: { canCut: true, canCopy: true, canPaste: true, canSelectAll: true }, + }, + ); + + const input = yield* Deferred.await(popup); + // Electron's popup() selects the first item only when sourceType says the keyboard opened it. + assert.deepEqual(Reflect.get(input, "source"), Option.some("keyboard")); + }).pipe(Effect.provide(layer)); + }), + ); + it.effect("offers to copy the bare address when right-clicking a mailto link", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 424efab93ba72..d003c8faaeab8 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -45,6 +45,7 @@ import * as DesktopRendererHistory from "../hostMonitor/DesktopRendererHistory.t import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; +import { resolveSpellCheckerLanguages } from "./SpellCheckerLanguages.ts"; const TITLEBAR_HEIGHT = 40; @@ -631,6 +632,8 @@ export const make = Effect.gen(function* () { event.preventDefault(); return; } + // The guest always runs the app's own preload, whatever the element asked for. + webPreferences.preload = environment.previewPickPreloadPath; webPreferences.sandbox = true; webPreferences.nodeIntegration = false; webPreferences.nodeIntegrationInSubFrames = false; @@ -761,6 +764,7 @@ export const make = Effect.gen(function* () { window: ownerWindow, template: menuTemplate, ...(params.frame ? { frame: params.frame } : {}), + source: Option.some(params.menuSourceType), }), ); }); @@ -787,6 +791,16 @@ export const make = Effect.gen(function* () { window.webContents.session.setPermissionRequestHandler((_contents, permission, callback) => callback(permission !== "openExternal"), ); + // macOS's native checker follows the system languages; elsewhere Chromium keeps en-US. + if (environment.platform !== "darwin") { + const session = window.webContents.session; + const spellCheckerLanguages = resolveSpellCheckerLanguages( + session.getSpellCheckerLanguages(), + yield* electronApp.preferredSystemLanguages, + session.availableSpellCheckerLanguages, + ); + if (spellCheckerLanguages) session.setSpellCheckerLanguages(spellCheckerLanguages); + } window.webContents.on("will-navigate", (event, url) => { if ( isSameOriginRendererNavigation({ diff --git a/apps/desktop/src/window/SpellCheckerLanguages.test.ts b/apps/desktop/src/window/SpellCheckerLanguages.test.ts new file mode 100644 index 0000000000000..45a72091fb274 --- /dev/null +++ b/apps/desktop/src/window/SpellCheckerLanguages.test.ts @@ -0,0 +1,46 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveSpellCheckerLanguages } from "./SpellCheckerLanguages.ts"; + +// Chromium lists a bare "en" (the en-US dictionary) next to the regional ones. +const AVAILABLE = ["de-DE", "en", "en-AU", "en-GB", "en-US", "fr", "pt-BR", "pt-PT"]; + +describe("resolveSpellCheckerLanguages", () => { + it("replaces the packaged en-US default with the OS languages in order", () => { + expect(resolveSpellCheckerLanguages(["en-US"], ["en-GB", "pt-BR"], AVAILABLE)).toEqual([ + "en-GB", + "pt-BR", + ]); + }); + + it("normalizes POSIX locale names", () => { + expect(resolveSpellCheckerLanguages([], ["en_GB.UTF-8"], AVAILABLE)).toEqual(["en-GB"]); + }); + + it("falls back to a dictionary for the same base language", () => { + expect(resolveSpellCheckerLanguages(["en-US"], ["fr-CA", "de-AT"], AVAILABLE)).toEqual([ + "fr", + "de-DE", + ]); + }); + + it("does not add another regional dictionary for a generic base-language fallback", () => { + expect(resolveSpellCheckerLanguages(["en-US"], ["en_GB", "en"], AVAILABLE)).toEqual(["en-GB"]); + expect(resolveSpellCheckerLanguages(["en-US"], ["en", "en-GB"], AVAILABLE)).toEqual(["en-GB"]); + expect(resolveSpellCheckerLanguages(["en-US"], ["en-GB", "en-US"], AVAILABLE)).toEqual([ + "en-GB", + "en-US", + ]); + }); + + it("keeps a list the user already changed", () => { + expect(resolveSpellCheckerLanguages(["en-AU"], ["en-GB"], AVAILABLE)).toBeUndefined(); + expect(resolveSpellCheckerLanguages(["en-US", "fr"], ["en-GB"], AVAILABLE)).toBeUndefined(); + }); + + it("leaves the session alone when nothing changes or matches", () => { + expect(resolveSpellCheckerLanguages(["en-US"], ["en-US"], AVAILABLE)).toBeUndefined(); + expect(resolveSpellCheckerLanguages(["en-US"], ["tlh"], AVAILABLE)).toBeUndefined(); + expect(resolveSpellCheckerLanguages(["en-US"], [], AVAILABLE)).toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/window/SpellCheckerLanguages.ts b/apps/desktop/src/window/SpellCheckerLanguages.ts new file mode 100644 index 0000000000000..2eb6daa67e3a6 --- /dev/null +++ b/apps/desktop/src/window/SpellCheckerLanguages.ts @@ -0,0 +1,50 @@ +/** The only Chromium locale packaged builds ship, so Electron seeds the spellchecker with it. */ +const PACKAGED_DEFAULT_LANGUAGE = "en-US"; + +const normalizeLanguageTag = (tag: string): string => + tag.split(/[.@]/)[0]!.replace(/_/g, "-").toLowerCase(); + +const baseLanguage = (tag: string): string => tag.toLowerCase().split("-")[0]!; + +const findExactLanguage = (tag: string, available: ReadonlyArray): string | undefined => + available.find((language) => language.toLowerCase() === tag); + +const findBaseLanguage = (base: string, available: ReadonlyArray): string | undefined => + available.find((language) => language.toLowerCase() === base) ?? + available.find((language) => language.toLowerCase().startsWith(`${base}-`)); + +/** + * The dictionaries to use instead of the packaged en-US default, or undefined to leave the + * session alone. A list other than the seeded default is the user's own choice and is kept. + */ +export const resolveSpellCheckerLanguages = ( + current: ReadonlyArray, + preferredSystemLanguages: ReadonlyArray, + available: ReadonlyArray, +): string[] | undefined => { + if (current.length > 1 || (current[0] ?? PACKAGED_DEFAULT_LANGUAGE) !== PACKAGED_DEFAULT_LANGUAGE) + return undefined; + const tags = preferredSystemLanguages.map(normalizeLanguageTag); + // GLib follows en_GB with a generated "en", and Chromium's "en" is the en-US dictionary, so a tag + // without a region is only a fallback and must not add another dictionary for its language. + const exactMatches = tags.map((tag) => + tag.includes("-") ? findExactLanguage(tag, available) : undefined, + ); + const coveredBases = new Set( + exactMatches.flatMap((match) => (match ? [baseLanguage(match)] : [])), + ); + const languages: string[] = []; + tags.forEach((tag, index) => { + let match = exactMatches[index]; + if (!match) { + const base = baseLanguage(tag); + if (coveredBases.has(base)) return; + match = findBaseLanguage(base, available); + if (match) coveredBases.add(base); + } + if (match && !languages.includes(match)) languages.push(match); + }); + if (languages.length === 0) return undefined; + if (languages.length === 1 && languages[0] === PACKAGED_DEFAULT_LANGUAGE) return undefined; + return languages; +}; diff --git a/apps/desktop/src/wsl/DesktopWslBackend.test.ts b/apps/desktop/src/wsl/DesktopWslBackend.test.ts index 414eee9840a83..d75d728a79cb8 100644 --- a/apps/desktop/src/wsl/DesktopWslBackend.test.ts +++ b/apps/desktop/src/wsl/DesktopWslBackend.test.ts @@ -77,6 +77,7 @@ const layerBackendConfiguration = Layer.succeed( const layerNet = Layer.succeed(NetService.NetService, { canListenOnHost: () => Effect.succeed(true), + probeListenOnHost: () => Effect.succeed(true), isPortAvailableOnLoopback: () => Effect.succeed(true), hasListenerOnHost: () => Effect.succeed(false), reserveLoopbackPort: () => Effect.succeed(41773), diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 470091f334fb7..aab0f0b2f8eea 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -557,6 +557,7 @@ describe("parseResolvedPath", () => { const WSL_EXE = "/windows/System32/wsl.exe"; const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; +const SERVICES_ROOT = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.make((command) => @@ -570,7 +571,7 @@ const registrySpawner = (keys: ReadonlyArray) => ChildProcessSpawner.ExitCode( command._tag === "StandardCommand" && command.command === "reg.exe" && - keys.some((key) => command.args.includes(key)) + [SERVICES_ROOT, ...keys].some((key) => command.args.includes(key)) ? 0 : 1, ), @@ -608,6 +609,42 @@ describe("makeIsAvailable", () => { }), ); + it.effect("keeps WSL when registry tools are disabled by policy and reg.exe cannot answer", () => + Effect.gen(function* () { + const denied = new TextEncoder().encode( + "ERROR: Registry editing has been disabled by your administrator.\r\n", + ); + const blockedRegistry = ChildProcessSpawner.make(() => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.make(denied), + all: Stream.make(denied), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); + const available = yield* makeIsAvailable("win32", "/windows").pipe( + Effect.provide( + Layer.mergeAll( + FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }), + Path.layer, + DesktopManagedPolicy.layerTest(undefined), + ), + ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, blockedRegistry), + ); + assert.isTrue(available); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 54ddc15131c6d..72dc59babfb38 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1124,13 +1124,16 @@ const WSL_SERVICE_KEYS = [ "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", ] as const; +// Always present; when reg.exe cannot read it (e.g. "Prevent access to registry editing tools"), +// a failed service query says nothing about WSL, so fall back to trusting wsl.exe. +const SERVICES_ROOT_KEY = "HKLM\\SYSTEM\\CurrentControlSet\\Services"; const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); const wslServiceRegistered = Effect.scoped( Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const registered = yield* Effect.forEach( - WSL_SERVICE_KEYS, + const [rootReadable, ...servicesFound] = yield* Effect.forEach( + [SERVICES_ROOT_KEY, ...WSL_SERVICE_KEYS], (key) => spawner .spawn( @@ -1142,10 +1145,13 @@ const wslServiceRegistered = Effect.scoped( forceKillAfter: PROCESS_TERMINATE_GRACE, }), ) - .pipe(Effect.flatMap((handle) => handle.exitCode)), + .pipe( + Effect.flatMap((handle) => handle.exitCode), + Effect.map((exitCode) => (exitCode as unknown as number) === 0), + ), { concurrency: "unbounded" }, ); - return registered.some((exitCode) => (exitCode as unknown as number) === 0); + return rootReadable === false || servicesFound.includes(true); }), ).pipe( Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), diff --git a/apps/marketing/src/i18n/index.ts b/apps/marketing/src/i18n/index.ts index c62950cafe0c9..deed51721a9ee 100644 --- a/apps/marketing/src/i18n/index.ts +++ b/apps/marketing/src/i18n/index.ts @@ -4,6 +4,7 @@ import { es } from "./es"; import { fr } from "./fr"; import { ja } from "./ja"; import { ko } from "./ko"; +import { pl } from "./pl"; import type { Locale } from "./locales"; import { ptBR } from "./pt-BR"; import { ru } from "./ru"; @@ -18,6 +19,7 @@ const MESSAGES: Record = { de, ja, ko, + pl, ru, }; diff --git a/apps/marketing/src/i18n/locales.ts b/apps/marketing/src/i18n/locales.ts index 4a2935c8688c9..ceddb34e9597f 100644 --- a/apps/marketing/src/i18n/locales.ts +++ b/apps/marketing/src/i18n/locales.ts @@ -10,6 +10,7 @@ export const LOCALES = [ { code: "de", path: "de", name: "Deutsch" }, { code: "ja", path: "ja", name: "日本語" }, { code: "ko", path: "ko", name: "한국어" }, + { code: "pl", path: "pl", name: "Polski" }, { code: "ru", path: "ru", name: "Русский" }, ] as const; diff --git a/apps/marketing/src/i18n/pl.ts b/apps/marketing/src/i18n/pl.ts new file mode 100644 index 0000000000000..72abc53311a9f --- /dev/null +++ b/apps/marketing/src/i18n/pl.ts @@ -0,0 +1,103 @@ +// Polish. Same shape as `en` (see `Messages`). `{name}` placeholders survive translation. +import type { Messages } from "./en"; + +export const pl: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. Open source'owa płaszczyzna sterowania dla agentów kodujących.", + socialImageAlt: + "T3 Code: open source'owa płaszczyzna sterowania dla agentów kodujących, z Claude Code, Codex, Cursor, OpenCode, Grok i Antigravity.", + homeLabel: "Strona główna T3 Code", + download: "Pobierz", + starsLabel: "Oznacz T3 Code gwiazdką na GitHubie, {stars} gwiazdek", + githubStars: "{stars} gwiazdek na GitHubie", + language: "Język", + mitLicensed: "Licencja MIT", + iosApp: "Aplikacja na iOS", + androidApp: "Aplikacja na Androida", + terms: "Warunki", + privacy: "Prywatność", + security: "Bezpieczeństwo", + }, + home: { + title: "T3 Code | Open source'owa płaszczyzna sterowania dla agentów kodujących", + description: "T3 Code. Open source'owa płaszczyzna sterowania dla agentów kodujących.", + heroTitle: ["Open source'owa", "płaszczyzna sterowania", "dla agentów kodujących."], + heroSub: + "Orkiestruj Claude Code, Codex, Antigravity, OpenCode, Cursor i Grok z jednego miejsca. Używaj własnej subskrypcji. Sforkuj całość.", + downloadForMac: "Pobierz na macOS", + downloadForWindows: "Pobierz na Windows", + downloadForLinux: "Pobierz na Linuksa", + downloadForIos: "Pobierz na iOS", + downloadForAndroid: "Pobierz na Androida", + sourceLink: "Ukradnij nasz kod (legalnie)", + alsoOnPhone: "Dostępne też na telefonie:", + screenshotAlt: "T3 Code uruchamiający subagenty Claude, Codex, Muse i Gemini w jednym wątku", + endorsementsTitle: "Tolerowany przez ponad {users} programistów", + endorsementsSub: "Niektórzy nawet tweetowali o tym.", + endorsementsLabel: "Opinie programistów", + readPost: "Przeczytaj post {handle} na X", + harnessTitle: "Przynieś własną subskrypcję", + harnessBody: + "T3 Code nie odsprzedaje tokenów. Podłącz Claude Code, Codex, Antigravity, OpenCode, Cursor lub Grok z danymi uwierzytelniającymi, które już masz. My nimi orkiestrujemy, a Ty zachowujesz swój plan.", + googleSignIn: "Logowanie Google", + harnessPoints: [ + "Bez odsprzedaży kluczy. Bez limitów.", + "Zmieniaj modele w trakcie wątku.", + "Kolejne harnessy wypuszczamy co tydzień.", + ], + gitVisualLabel: + "Ilustracja przepływu Git w T3 Code: przegląd diffa, commit i push zmian oraz otwarcie pull requesta.", + prReady: "Gotowy", + prCommits: "3 commity", + viewDiff: "Zobacz diff", + openPullRequest: "Otwórz pull request", + commitPush: "Commit i push", + gitTitle: "Jeden przycisk: commit, push i PR.", + gitBody: + "Każdy wątek agenta pisze na własnej gałęzi. Gdy wszystko wygląda dobrze, jeden przycisk otwiera PR na GitHubie z wygenerowanym tytułem, opisem i listą zmian. Bez tańczenia w terminalu.", + gitPoints: [ + "Automatycznie generowane tytuły i opisy PR", + "Przegląd diffa przed pushem", + "Draft PR, stack PR, amend PR", + "Działa z Twoim istniejącym logowaniem do GitHuba", + ], + openTitle: "Nie podoba Ci się coś? Sforkuj to.", + openPoints: [ + { lead: "Zmień interfejs.", rest: "Przystosuj każdy ekran do własnego gustu." }, + { lead: "Dodaj agenta.", rest: "Podłącz własne narzędzia, modele i przepływy." }, + { + lead: "Wydaj własną wersję.", + rest: "Hostuj samodzielnie albo dystrybuuj jako swój produkt.", + }, + ], + stars: "{stars} gwiazdek", + forkOnGithub: "Forkuj na GitHubie", + browseSource: "Przeglądaj kod źródłowy", + ctaTitle: "Twoi agenci zasługują na coś lepszego niż terminal.", + ctaSub: + "T3 Code jest darmowy, open source i szybki. Zainstaluj go, podłącz harness, za który już płacisz, i pozwól agentom zabrać się do pracy.", + otherPlatforms: "Inne platformy", + }, + download: { + title: "Pobierz T3 Code na macOS, Windows i Linux | T3 Code", + description: + "Pobierz oficjalną aplikację desktopową T3 Code na macOS, Windows lub Linux albo pobierz aplikacje na iOS i Androida. t3.codes to jedyna oficjalna strona pobierania.", + breadcrumb: "Pobierz", + heading: "Pobierz T3 Code", + channelLabel: "Kanał wydań", + stable: "Stabilna", + nightly: "Nightly", + intelNote: "Masz Maca z Intelem? {link}.", + intelLink: "Pobierz wersję x64", + armNote: "Masz ARM? Pobierz arm64: {deb} lub {appimage}.", + mobile: "Mobile", + iphoneIpad: "iPhone i iPad", + terminal: "Terminal", + tryOnce: "Albo wypróbuj bez instalacji:", + allBuilds: "Wszystkie wersje znajdziesz na: {link}", + releasesPage: "stronie wydań na GitHubie", + builtAgo: "Zbudowano {age}", + releasesFallback: "Wydania", + }, +}; diff --git a/apps/mobile/gt.config.json b/apps/mobile/gt.config.json index 2bd924f11922b..bc0de9a567cf4 100644 --- a/apps/mobile/gt.config.json +++ b/apps/mobile/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["es", "zh", "pt-BR", "fr", "de", "ja", "ko", "ru", "sv"], + "locales": ["es", "zh", "pt-BR", "fr", "de", "ja", "ko", "pl", "ru", "sv"], "src": [ "src/**/*.{ts,tsx}", "../../packages/client-runtime/src/**/*.{ts,tsx}", 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 220ba4a75be51..341b5f1bc2d3b 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 @@ -48,6 +48,7 @@ object AgentNotifications { private const val ALERT_CHANNEL = "agent-alerts" private const val ACTIVITY_TAG = "t3-agent-activity" private const val ALERT_TAG = "t3-agent-alert" + private const val ALERT_THREAD_TAG = "$ALERT_TAG-thread:" private const val ACTIVITY_ID = 73001 private const val MAX_MESSAGE_AGE_MS = 10 * 60 * 1000L private const val RUNNING_LIFETIME_MS = 2 * 60 * 60 * 1000L @@ -87,6 +88,7 @@ object AgentNotifications { val manager = manager(context) manager.activeNotifications.filter { it.tag == ACTIVITY_TAG || it.tag == ALERT_TAG || + it.tag?.startsWith(ALERT_THREAD_TAG) == true || it.tag?.startsWith("$ALERT_TAG-summary:") == true } .forEach { manager.cancel(it.tag, it.id) } @@ -159,7 +161,8 @@ object AgentNotifications { ) val visibleThread = threadOnScreen val onScreen = resumed && visibleThread != null && data["alert_path"] == visibleThread - if (!onScreen) { + val current = advanceThreadAlert(prefs, data) + if (!onScreen && current) { postAlert(context, scheme, data, alertId) } prefs.edit().remove("seenAlerts").putString( @@ -167,7 +170,7 @@ object AgentNotifications { (seen.takeLast(63) + alertId).joinToString("\n") ).apply() // Android drops posts to a blocked channel, so that alert shows nothing. - return !onScreen && ( + return !onScreen && current && ( Build.VERSION.SDK_INT < 26 || manager(context).getNotificationChannel(ALERT_CHANNEL)?.importance != NotificationManager.IMPORTANCE_NONE @@ -185,36 +188,70 @@ object AgentNotifications { val title = data["alert_title"].orEmpty().take(120) // Grouped alerts list up to five 120-character thread titles. val body = data["alert_body"].orEmpty().take(608) - val id = alertId.hashCode() - val group = data["alert_group"]?.takeIf { it.isNotBlank() } ?: ALERT_TAG + val threadGroup = data["alert_group"]?.takeIf { it.isNotBlank() } + // alert_id is unique per turn; keying on the thread makes its next alert replace this one. + // The tag carries the whole group, since distinct groups can share a String hash. + val tag = threadGroup?.let { "$ALERT_THREAD_TAG$it" } ?: ALERT_TAG + val id = if (threadGroup != null) 0 else alertId.hashCode() + val group = threadGroup ?: ALERT_TAG val notification = base(context, ALERT_CHANNEL) .setContentTitle(title).setContentText(body) .setStyle(NotificationCompat.BigTextStyle().bigText(body)) .setAutoCancel(true) .setGroup(group) - .setContentIntent(contentIntent(context, scheme, data["alert_path"], id)) + .setContentIntent( + contentIntent(context, scheme, data["alert_path"], (threadGroup ?: alertId).hashCode()), + ) .build() - manager(context).notify(ALERT_TAG, id, notification) + manager(context).notify(tag, id, notification) + postGroupSummary(context, scheme, group, data) + } + + // updated_at is when the relay read the thread's current state, so unlike the turn's own + // time it never moves backward: a push stamped earlier than the thread's last alert is late. + private fun advanceThreadAlert(prefs: SharedPreferences, data: Map): Boolean { + val group = data["alert_group"]?.takeIf { it.isNotBlank() } + val at = data["updated_at"]?.toLongOrNull() + if (group == null || at == null) return true + val times = prefs.getString("threadAlertTimes", null)?.lines().orEmpty() + .mapNotNull { line -> + val parts = line.split('\t', limit = 2) + parts.getOrNull(1)?.let { key -> parts[0].toLongOrNull()?.let { key to it } } + } + .toMap() + val late = at < (times[group] ?: Long.MIN_VALUE) + if (!late) { + val kept = (times - group).entries.toList().takeLast(63).map { "${it.value}\t${it.key}" } + prefs.edit().putString("threadAlertTimes", (kept + "$at\t$group").joinToString("\n")).apply() + } + return !late + } + + private fun postGroupSummary( + context: Context, + scheme: String, + group: String, + data: Map + ) { val children = manager(context).activeNotifications.filter { it.tag == ALERT_TAG && it.notification.group == group } - if (children.size > 1) { - val style = NotificationCompat.InboxStyle() - children.forEach { - style.addLine(it.notification.extras.getCharSequence(android.app.Notification.EXTRA_TEXT)) - } - val summary = base(context, ALERT_CHANNEL) - .setContentTitle(title) - .setContentText(body) - .setStyle(style) - .setGroup(group) - .setGroupSummary(true) - .setSilent(true) - .setAutoCancel(true) - .setContentIntent(contentIntent(context, scheme, data["alert_path"], 0)) - .build() - manager(context).notify("$ALERT_TAG-summary:$group", 0, summary) + if (children.size <= 1) return + val style = NotificationCompat.InboxStyle() + children.forEach { + style.addLine(it.notification.extras.getCharSequence(android.app.Notification.EXTRA_TEXT)) } + val summary = base(context, ALERT_CHANNEL) + .setContentTitle(data["alert_title"].orEmpty().take(120)) + .setContentText(data["alert_body"].orEmpty().take(608)) + .setStyle(style) + .setGroup(group) + .setGroupSummary(true) + .setSilent(true) + .setAutoCancel(true) + .setContentIntent(contentIntent(context, scheme, data["alert_path"], 0)) + .build() + manager(context).notify("$ALERT_TAG-summary:$group", 0, summary) } /** 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 eb054f4d484fe..1f1694d0af2fb 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 @@ -78,7 +78,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { for (id in 1..64) AgentNotifications.receive(context, update("alert-$id", false)) assertTrue(manager.activeNotifications.isEmpty()) AgentNotifications.receive(context, update("alert-0", false)) - assertEquals("alert-0".hashCode(), manager.activeNotifications.single().id) + assertTrue(manager.activeNotifications.single().tag.startsWith("t3-agent-alert")) } @Test @@ -102,7 +102,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { lifecycle.currentState = Lifecycle.State.RESUMED AgentNotifications.setThreadOnScreen("/threads/environment/other") AgentNotifications.receive(context, update("elsewhere", false)) - assertEquals("t3-agent-alert", manager.activeNotifications.single().tag) + assertTrue(manager.activeNotifications.single().tag.startsWith("t3-agent-alert")) } @Test @@ -134,7 +134,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { AgentNotifications.receive(context, update("later-background-completion", false)) - assertEquals("later-background-completion".hashCode(), manager.activeNotifications.single().id) + assertTrue(manager.activeNotifications.single().tag.startsWith("t3-agent-alert")) } @Test @@ -142,22 +142,30 @@ class AgentNotificationsTest : AgentNotificationsFixture() { AgentNotifications.receive(context, update("background-completion", false)) lifecycle.currentState = Lifecycle.State.RESUMED - AgentNotifications.receive(context, update("foreground-completion", false)) + AgentNotifications.receive( + context, + update("foreground-completion", false) + ("alert_body" to "Suppressed in foreground") + ) - assertEquals("background-completion".hashCode(), manager.activeNotifications.single().id) + val alert = manager.activeNotifications.single().notification + val text = alert.extras.getCharSequence(Notification.EXTRA_TEXT).toString() + assertEquals("Done: Test project", text) } @Test - fun repeatedThreadAlertsHaveOneSilentSummaryAndClearTogether() { - AgentNotifications.receive(context, update("first", false) + ("alert_group" to "thread-group")) - AgentNotifications.receive(context, update("second", false) + ("alert_group" to "thread-group")) + fun repeatedThreadAlertsReplaceOneNotificationAndClear() { + val earlier = (System.currentTimeMillis() - 1000).toString() + val late = mapOf("alert_body" to "Late", "updated_at" to earlier) + AgentNotifications.receive(context, update("first", false)) + AgentNotifications.receive(context, update("second", false) + ("alert_body" to "Failed")) + AgentNotifications.receive(context, update("late", false) + late) - val summary = manager.activeNotifications.single { - it.notification.flags and Notification.FLAG_GROUP_SUMMARY != 0 - } - assertEquals("thread-group", summary.notification.group) - assertEquals(3, manager.activeNotifications.size) - assertEquals(null, summary.notification.sound) + val alert = manager.activeNotifications.single() + val text = alert.notification.extras.getCharSequence(Notification.EXTRA_TEXT).toString() + assertEquals("Failed", text) + manager.cancel(alert.tag, alert.id) + AgentNotifications.receive(context, update("late-after-swipe", false) + late) + assertTrue(manager.activeNotifications.isEmpty()) AgentNotifications.clear(context) assertTrue(manager.activeNotifications.isEmpty()) @@ -166,7 +174,8 @@ class AgentNotificationsTest : AgentNotificationsFixture() { @Test fun groupedAlertDisplaysEveryThreadAndRetriesStaySilent() { val titles = (1..5).map { "Thread $it " + "x".repeat(111) }.joinToString(", ") - val grouped = update("group-completion", false) + mapOf( + // The relay omits alert_group when one alert covers several threads. + val grouped = update("group-completion", false) - "alert_group" + mapOf( "alert_title" to "5 agents finished", "alert_body" to titles, "alert_path" to "/", @@ -186,20 +195,20 @@ class AgentNotificationsTest : AgentNotificationsFixture() { @Test fun foregroundGroupForOtherThreadsAlertsOnceAcrossBackgroundRetry() { - val grouped = update("group-attention", true) + mapOf( + val grouped = update("group-attention", true) - "alert_group" + mapOf( "alert_title" to "2 agents need attention", "alert_body" to "First thread, Second thread", "alert_path" to "/", ) lifecycle.currentState = Lifecycle.State.RESUMED AgentNotifications.receive(context, grouped) - assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-alert" }) + assertEquals(1, manager.activeNotifications.count { it.tag.startsWith("t3-agent-alert") }) lifecycle.currentState = Lifecycle.State.CREATED AgentNotifications.receive(context, grouped) assertEquals(2, manager.activeNotifications.size) assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) - assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-alert" }) + assertEquals(1, manager.activeNotifications.count { it.tag.startsWith("t3-agent-alert") }) } @Test @@ -211,7 +220,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { AgentNotifications.dismiss(context) AgentNotifications.configure(context, "device", "user", "t3code-dev", true) AgentNotifications.receive(context, message) - assertEquals("t3-agent-alert", manager.activeNotifications.single().tag) + assertTrue(manager.activeNotifications.single().tag.startsWith("t3-agent-alert")) } @Test @@ -524,7 +533,7 @@ class AgentNotificationsTest : AgentNotificationsFixture() { AgentNotifications.expire(context, expiresAt + 60_000) assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) AgentNotifications.expire(context, expiresAt + 2 * 60 * 60 * 1000L) - assertEquals(2, manager.activeNotifications.count { it.tag == "t3-agent-alert" }) + assertEquals(1, manager.activeNotifications.count { it.tag.startsWith("t3-agent-alert") }) assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) assertTrue(alarms.scheduledAlarms.isEmpty()) } @@ -552,7 +561,8 @@ class AgentNotificationsTest : AgentNotificationsFixture() { @Test fun alertsAndActivityUseVersionAppropriatePriorityAndPromotion() { AgentNotifications.receive(context, update("work", true)) - val alert = manager.activeNotifications.single { it.tag == "t3-agent-alert" }.notification + val alerts = manager.activeNotifications.filter { it.tag.startsWith("t3-agent-alert") } + val alert = alerts.single().notification val card = manager.activeNotifications.single { it.tag == "t3-agent-activity" }.notification if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { assertEquals(Notification.PRIORITY_HIGH, alert.priority) @@ -760,7 +770,7 @@ class AgentNotificationsCompletionTest : AgentNotificationsFixture() { AgentNotifications.receive(context, completion.filterKeys { !it.startsWith("alert_") }) val alert = manager.activeNotifications.single() - assertEquals("t3-agent-alert", alert.tag) + assertTrue(alert.tag.startsWith("t3-agent-alert")) assertEquals("Test thread", alert.notification.extras.getString(Notification.EXTRA_TITLE)) assertFalse(alert.notification.flags and Notification.FLAG_ONGOING_EVENT != 0) AgentNotifications.receive(context, update("next-run", true)) @@ -799,7 +809,7 @@ class AgentNotificationsCompletionTest : AgentNotificationsFixture() { context, finished("older-alert", now + 900000) + ("updated_at" to (now - 1000).toString()) ) - assertEquals(4, manager.activeNotifications.size) + assertEquals(2, manager.activeNotifications.size) assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) // A newer replay of a finish can show its card before the original alert lands. val finish = finished("finish", now + 960000) @@ -808,9 +818,13 @@ class AgentNotificationsCompletionTest : AgentNotificationsFixture() { finish.filterKeys { !it.startsWith("alert_") } + ("updated_at" to (now + 2000).toString()) ) assertEquals(1, manager.activeNotifications.count { it.tag == "t3-agent-activity" }) - AgentNotifications.receive(context, finish + ("updated_at" to (now + 1000).toString())) + AgentNotifications.receive( + context, + finish + mapOf("updated_at" to (now + 1000).toString(), "alert_body" to "Finished") + ) assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) - assertTrue(manager.activeNotifications.any { it.id == "finish".hashCode() }) + val alert = manager.activeNotifications.single().notification + assertEquals("Finished", alert.extras.getCharSequence(Notification.EXTRA_TEXT).toString()) AgentNotifications.receive( context, finished("previous-run", now + 900000) + ("updated_at" to now.toString()) @@ -822,6 +836,6 @@ class AgentNotificationsCompletionTest : AgentNotificationsFixture() { assertTrue(manager.activeNotifications.none { it.tag == "t3-agent-activity" }) shadowOf(manager).setNotificationsEnabled(false) AgentNotifications.receive(context, update("revoked-permission", true)) - assertEquals(5, manager.activeNotifications.size) + assertEquals(1, manager.activeNotifications.size) } } diff --git a/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt b/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt index ce722817dd131..1e2e726ccf650 100644 --- a/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt +++ b/apps/mobile/modules/t3-voice-transcription/android/src/main/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriber.kt @@ -24,7 +24,13 @@ internal class VoiceTranscriptionException( // ML Kit reports every mode UNAVAILABLE for tags with Unicode extensions, which Android adds // for regional preferences such as the temperature unit (en-US-u-mu-celsius). -internal fun speechLocale(systemLocale: Locale): Locale = systemLocale.stripExtensions() +internal fun speechLocale(systemLocale: Locale): Locale { + val locale = systemLocale.stripExtensions() + // ML Kit accepts cmn-Hans-CN for Simplified Chinese, not zh-CN or zh-Hans-CN. + val simplifiedChinese = locale.language == "zh" && + (locale.script == "Hans" || (locale.script.isEmpty() && locale.country == "CN")) + return if (simplifiedChinese) Locale.forLanguageTag("cmn-Hans-CN") else locale +} private val recognitionModes = listOf( SpeechRecognizerOptions.Mode.MODE_ADVANCED, diff --git a/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt b/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt index 445411bbb6957..e1eb1be2d5f0f 100644 --- a/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt +++ b/apps/mobile/modules/t3-voice-transcription/android/src/test/java/expo/modules/t3voicetranscription/GoogleVoiceTranscriberTest.kt @@ -21,6 +21,9 @@ class GoogleVoiceTranscriberTest { "en-US-u-mu-celsius" to "en-US", "en-GB-u-fw-mon-mu-celsius" to "en-GB", "ar-EG-u-nu-latn" to "ar-EG", + "zh-CN" to "cmn-Hans-CN", + "zh-Hans-CN" to "cmn-Hans-CN", + "zh-Hans-CN-u-fw-mon" to "cmn-Hans-CN", "zh-Hant-TW" to "zh-Hant-TW" )) { assertEquals(expected, speechLocale(Locale.forLanguageTag(system)).toLanguageTag()) diff --git a/apps/mobile/plugins/withAndroidWindowDisplayMetrics.cjs b/apps/mobile/plugins/withAndroidWindowDisplayMetrics.cjs index c8f584cd9a085..7b35df094fc5e 100644 --- a/apps/mobile/plugins/withAndroidWindowDisplayMetrics.cjs +++ b/apps/mobile/plugins/withAndroidWindowDisplayMetrics.cjs @@ -1,14 +1,35 @@ const { withMainActivity } = require("expo/config-plugins"); -// React Native measures text with application-display density, which differs -// from the activity on external displays. Expo constructs its root after -// onCreate, resetting those metrics; ReactHost resets them on configuration -// changes too. Rebind after both, before text is measured. +// React Native converts touches and measures text at the display's density, which can differ +// from the activity's: external displays, and One UI split screen (321 vs 420 dpi on a Galaxy +// Z Fold). Expo's root constructor and ReactHost configuration changes reset it, so rebind +// after both with the activity's density, which layout uses. const DISPLAY_METRICS_METHODS = ` // Expo constructs the root view after onCreate; its constructor resets metrics. override fun setContentView(view: View?) { super.setContentView(view) + bindWindowDisplayMetrics() + // After a rotation, ReactRootView's global layout listener resets metrics to the + // display's. Pre-draw runs after every global layout listener in that traversal. + window.decorView.viewTreeObserver.addOnPreDrawListener { + if (DisplayMetricsHolder.getScreenDisplayMetrics().densityDpi != resources.displayMetrics.densityDpi) { + bindWindowDisplayMetrics() + } + true + } + } + + private fun bindWindowDisplayMetrics() { DisplayMetricsHolder.initDisplayMetrics(this) + val activityMetrics = resources.displayMetrics + // Fabric measures text off the main thread; publish the corrected metrics whole. + DisplayMetricsHolder.setScreenDisplayMetrics( + DisplayMetrics().apply { + setTo(DisplayMetricsHolder.getScreenDisplayMetrics()) + density = activityMetrics.density + densityDpi = activityMetrics.densityDpi + }, + ) } `; @@ -41,10 +62,16 @@ module.exports = function withAndroidWindowDisplayMetrics(config) { if (nextConfig.modResults.language !== "kt") { throw new Error("withAndroidWindowDisplayMetrics: MainActivity must be Kotlin."); } - if (contents.includes("DisplayMetricsHolder.initDisplayMetrics(this)")) { + if (contents.includes("bindWindowDisplayMetrics()")) { return nextConfig; } + if (contents.includes("DisplayMetricsHolder.initDisplayMetrics(this)")) { + throw new Error( + "withAndroidWindowDisplayMetrics: MainActivity has an older version of this plugin's code; run expo prebuild with --clean.", + ); + } + contents = addImport(contents, "import android.util.DisplayMetrics"); contents = addImport(contents, "import android.view.View"); contents = addImport(contents, "import com.facebook.react.uimanager.DisplayMetricsHolder"); contents = insertAfter( @@ -63,7 +90,7 @@ module.exports = function withAndroidWindowDisplayMetrics(config) { insertAfter( contents.slice(overrideStart), "super.onConfigurationChanged(newConfig)", - "\n DisplayMetricsHolder.initDisplayMetrics(this)", + "\n bindWindowDisplayMetrics()", "the super call in the onConfigurationChanged override", ); } else { @@ -74,7 +101,7 @@ module.exports = function withAndroidWindowDisplayMetrics(config) { ` override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) - DisplayMetricsHolder.initDisplayMetrics(this) + bindWindowDisplayMetrics() } `, "the MainActivity class declaration", diff --git a/apps/mobile/plugins/withAndroidWindowDisplayMetrics.test.mjs b/apps/mobile/plugins/withAndroidWindowDisplayMetrics.test.mjs index c576738555dd2..2e15911c03ed6 100644 --- a/apps/mobile/plugins/withAndroidWindowDisplayMetrics.test.mjs +++ b/apps/mobile/plugins/withAndroidWindowDisplayMetrics.test.mjs @@ -59,19 +59,28 @@ describe("withAndroidWindowDisplayMetrics", () => { it("rebinds the generated activity after root installation and configuration changes, preserving orientation", async () => { const result = await prebuildMainActivity(template); + // ReactRootView's global layout listener resets metrics after a rotation; pre-draw follows it. expect(methodBody(result, "setContentView")).toMatch( - /^super\.setContentView\(view\)\s+DisplayMetricsHolder\.initDisplayMetrics\(this\)$/, + /^super\.setContentView\(view\)\s+bindWindowDisplayMetrics\(\)\s+\/\/ After a rotation, ReactRootView's global layout listener resets metrics to the\s+\/\/ display's\. Pre-draw runs after every global layout listener in that traversal\.\s+window\.decorView\.viewTreeObserver\.addOnPreDrawListener \{\s+if \(DisplayMetricsHolder\.getScreenDisplayMetrics\(\)\.densityDpi != resources\.displayMetrics\.densityDpi\) \{\s+bindWindowDisplayMetrics\(\)\s+\}\s+true\s+\}$/, ); expect(methodBody(result, "onConfigurationChanged")).toMatch( - /^super\.onConfigurationChanged\(newConfig\)\s+DisplayMetricsHolder\.initDisplayMetrics\(this\)\s+applyTabletOrientation\(\)$/, + /^super\.onConfigurationChanged\(newConfig\)\s+bindWindowDisplayMetrics\(\)\s+applyTabletOrientation\(\)$/, ); const onCreate = methodBody(result, "onCreate"); expect(onCreate).toContain("applyTabletOrientation()"); + expect(onCreate).not.toContain("bindWindowDisplayMetrics()"); expect(onCreate).not.toContain("DisplayMetricsHolder.initDisplayMetrics(this)"); expect(methodBody(result, "applyTabletOrientation")).toMatch( /requestedOrientation = if \(resources\.configuration\.smallestScreenWidthDp >= 600\) \{\s+ActivityInfo\.SCREEN_ORIENTATION_FULL_USER\s+\} else \{\s+ActivityInfo\.SCREEN_ORIENTATION_PORTRAIT\s+\}/, ); + // getRealMetrics reports the display's density; One UI split screen gives the activity a + // lower one, so touch and layout scales diverge unless the window's scale wins. + expect(methodBody(result, "bindWindowDisplayMetrics")).toMatch( + /^DisplayMetricsHolder\.initDisplayMetrics\(this\)\s+val activityMetrics = resources\.displayMetrics\s+\/\/ Fabric measures text off the main thread; publish the corrected metrics whole\.\s+DisplayMetricsHolder\.setScreenDisplayMetrics\(\s+DisplayMetrics\(\)\.apply \{\s+setTo\(DisplayMetricsHolder\.getScreenDisplayMetrics\(\)\)\s+density = activityMetrics\.density\s+densityDpi = activityMetrics\.densityDpi\s+\},\s+\)$/, + ); + + expect(result).toContain("import android.util.DisplayMetrics"); expect(result).toContain("import android.view.View"); expect(result).toContain("import com.facebook.react.uimanager.DisplayMetricsHolder"); expect(result.match(/^import android\.content\.res\.Configuration$/gm)).toHaveLength(1); @@ -81,9 +90,21 @@ describe("withAndroidWindowDisplayMetrics", () => { const once = await prebuildMainActivity(template); const twice = await prebuildMainActivity(once); - expect(methodBody(once, "setContentView")).toContain( - "DisplayMetricsHolder.initDisplayMetrics(this)", - ); + expect(methodBody(once, "setContentView")).toContain("bindWindowDisplayMetrics()"); expect(twice).toBe(once); }); + + it("refuses an activity generated by the previous plugin version instead of adding a second override", async () => { + const previous = template.replace( + "class MainActivity : ReactActivity() {", + `class MainActivity : ReactActivity() { + override fun setContentView(view: View?) { + super.setContentView(view) + DisplayMetricsHolder.initDisplayMetrics(this) + } +`, + ); + + await expect(prebuildMainActivity(previous)).rejects.toThrow(/run expo prebuild with --clean/); + }); }); diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 6d90afef123ff..a0e4ff4e842d4 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -19,6 +19,7 @@ import { useResolveClassNames } from "uniwind"; import { AppText as Text } from "./components/ui/AppText"; import { androidWorkspaceDestinationAnimation } from "./lib/android-workspace-navigation"; +import { FILE_PATH_LINK_PARAM } from "./lib/appLinking"; import { getCompactBrandHeaderOptions } from "./features/layout/workspace/brand-header-options"; import { WorkspaceConnectionStatusProvider } from "./features/home/WorkspaceConnectionTitle"; import { WorkspaceRootScreen } from "./features/layout/workspace/WorkspaceRootScreen"; @@ -717,7 +718,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ options: pageRoute({ header: "solid" }), }), NewTaskFile: createNativeStackScreen({ - linking: "new/draft/files/:path*", + linking: `new/draft/files/${FILE_PATH_LINK_PARAM}`, screen: ThreadFileScreen, options: pageRoute({ header: "solid" }), }), @@ -772,7 +773,7 @@ const RootStackConfig = createWorkspaceStackNavigator({ }), ThreadFile: createNativeStackScreen({ screen: ThreadFileScreen, - linking: `${THREAD_LINKING_PREFIX}/files/:path*`, + linking: `${THREAD_LINKING_PREFIX}/files/${FILE_PATH_LINK_PARAM}`, options: pageRoute(), }), ThreadMcpApp: createNativeStackScreen({ @@ -932,7 +933,7 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig return ( } - screenOptions={({ route, navigation }) => { + screenOptions={({ route, navigation, theme }) => { const title = route.name === "Home" ? getCompactBrandHeaderOptions(undefined, resolve).title @@ -941,6 +942,9 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig : resolve(ROUTE_TITLES[route.name]); return { ...(title === undefined ? {} : { title }), + // In release builds react-native-screens decides the iOS status bar style, and its + // "auto" style can follow the phone's appearance instead of the app's theme. + ...(Platform.OS === "ios" ? { statusBarStyle: theme.dark ? "light" : "dark" } : {}), ...(Platform.OS === "android" ? { animation: androidWorkspaceDestinationAnimation( diff --git a/apps/mobile/src/components/AssistantCitationSheet.tsx b/apps/mobile/src/components/AssistantCitationSheet.tsx index 3af99f8224bea..de65b9faf3aac 100644 --- a/apps/mobile/src/components/AssistantCitationSheet.tsx +++ b/apps/mobile/src/components/AssistantCitationSheet.tsx @@ -57,6 +57,7 @@ export function AssistantCitationSheet(props: { > { + expect(errorDetailsPreview(`${"a".repeat(299)}😀 more`)).toBe("a".repeat(299)); + expect(errorDetailsPreview(`${"a".repeat(298)}😀 more`)).toBe(`${"a".repeat(298)}😀`); + expect(errorDetailsPreview("TypeError: boom 🚀\n at render")).toBe("TypeError: boom 🚀"); +}); diff --git a/apps/mobile/src/components/RenderErrorBoundary.logic.ts b/apps/mobile/src/components/RenderErrorBoundary.logic.ts new file mode 100644 index 0000000000000..635b6b5fdcaaf --- /dev/null +++ b/apps/mobile/src/components/RenderErrorBoundary.logic.ts @@ -0,0 +1,11 @@ +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; + +const PREVIEW_LIMIT = 300; + +export function errorDetailsPreview(details: string) { + const firstLine = details.split("\n", 1)[0] ?? ""; + return firstLine.slice( + 0, + splitsSurrogatePair(firstLine, PREVIEW_LIMIT) ? PREVIEW_LIMIT - 1 : PREVIEW_LIMIT, + ); +} diff --git a/apps/mobile/src/components/RenderErrorBoundary.tsx b/apps/mobile/src/components/RenderErrorBoundary.tsx index d8538e9fa58e4..68d7ecb7f2655 100644 --- a/apps/mobile/src/components/RenderErrorBoundary.tsx +++ b/apps/mobile/src/components/RenderErrorBoundary.tsx @@ -5,6 +5,7 @@ import { ScrollView, View } from "react-native"; import { AppText as Text } from "./ui/AppText"; import { Button } from "./ui/Button"; import { copyTextWithHaptic } from "../lib/copyTextWithHaptic"; +import { errorDetailsPreview } from "./RenderErrorBoundary.logic"; interface RenderErrorBoundaryProps { readonly children: ReactNode; @@ -109,7 +110,7 @@ export function RenderFailureView( Try again. If it keeps happening, copy the details for a bug report. - {props.details.split("\n", 1)[0]?.slice(0, 300)} + {errorDetailsPreview(props.details)} + +
+ +
+
+ +
+
+ +
+ + , + ); + await expect.element(page.getByRole("dialog", { name: "Workspace panel" })).toBeVisible(); + page.getByRole("button", { name: "Next stop" }).element().focus(); + await userEvent.keyboard("j"); + await expect.element(page.getByText("Prose for the second stop.")).toBeVisible(); + + for (const [name, role, keyCode] of [ + ["Dialog action", "button", 0], + ["Menu action", "menuitem", 0], + ["Popup action", "button", 0], + ["Side chat action", "button", 0], + ["IME action", "button", 229], + ] as const) { + const target = page.getByRole(role, { name }).element(); + target.focus(); + for (const key of ["j", "k"]) { + const event = new KeyboardEvent("keydown", { key, keyCode, bubbles: true, cancelable: true }); + target.dispatchEvent(event); + expect(event.defaultPrevented, `${name}: ${key}`).toBe(false); + } + } + page.getByRole("button", { name: "Next stop" }).element().focus(); + await userEvent.keyboard("j"); + await expect.element(page.getByText("Prose for the third stop.")).toBeVisible(); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx index a962d2b442a1c..9a1b75bc29a65 100644 --- a/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestGuideTab.tsx @@ -129,9 +129,10 @@ export function PullRequestGuideTab({

{running - ? gt( + ? (query.error ?? + gt( "An agent is reading the change. A large one takes a few minutes. You can leave; you will be told when it is ready.", - ) + )) : failure === null ? (query.error ?? gt( diff --git a/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx index 29f0211eaef83..c8890fdac727b 100644 --- a/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestLinkPreview.browser.test.tsx @@ -1,4 +1,5 @@ import { EnvironmentId, ProjectId, type PullRequestSummary } from "@t3tools/contracts"; +import { getTranslationsSnapshot, GTProvider } from "gt-react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -17,12 +18,17 @@ const known = vi.hoisted( updatedAt: "2026-09-01T00:00:00Z", }) as PullRequestSummary, ); -const state = vi.hoisted(() => ({ restoredPreview: null as unknown })); +const state = vi.hoisted(() => ({ restoredPreview: null as unknown, activity: null as unknown })); vi.mock(import("~/state/query"), async (original) => ({ ...(await original()), // The host has not answered the preview read yet. useEnvironmentQuery: ((atom: unknown) => ({ - data: state.restoredPreview, + data: + atom === null + ? null + : typeof atom === "object" && "activity" in atom + ? state.activity + : state.restoredPreview, dataUpdatedAt: 0, error: null, failure: null, @@ -31,14 +37,28 @@ vi.mock(import("~/state/query"), async (original) => ({ refresh: () => undefined, })) as never, })); -vi.mock(import("~/state/pullRequests"), async (original) => ({ - ...(await original()), - useSharedPullRequestSummary: (() => known) as never, -})); +vi.mock(import("~/state/pullRequests"), async (original) => { + const actual = await original(); + return { + ...actual, + useSharedPullRequestSummary: (() => known) as never, + pullRequestEnvironment: { + ...actual.pullRequestEnvironment, + activity: ((target: unknown) => ({ activity: target })) as never, + }, + }; +}); +import { initializeI18n } from "~/i18n/initializeI18n"; import { render } from "../../../test/render"; import { PullRequestLinkPreview } from "./PullRequestLinkPreview"; +function setup(next: Partial = {}) { + Object.assign(state, { restoredPreview: null, activity: null }, next); + // GTProvider leaves its locale in a cookie; this sets it back to English. + initializeI18n(() => {}); +} + function renderPreview() { return render( { - state.restoredPreview = { - projectId: "project", - repository: "owner/repo", - number: 1, - title: "Renamed title", - url: known.url, - author: { login: "octocat" }, - state: "closed", - isDraft: false, - createdAt: "2026-08-01T00:00:00Z", - }; + setup({ + restoredPreview: { + projectId: "project", + repository: "owner/repo", + number: 1, + title: "Renamed title", + url: known.url, + author: { login: "octocat" }, + state: "closed", + isDraft: false, + createdAt: "2026-08-01T00:00:00Z", + }, + }); await using screen = await renderPreview(); await userEvent.hover(screen.getByRole("link")); @@ -74,7 +96,7 @@ it("keeps a refreshing preview's state and title over an older known summary", a }); it("shows the known summary while the preview loads", async () => { - state.restoredPreview = null; + setup(); await using screen = await render( #1} @@ -90,3 +112,42 @@ it("shows the known summary while the preview loads", async () => { await expect.element(page.getByText("Known title")).toBeVisible(); }); + +it("shows who commented on a linked comment in the active language", async () => { + const commentUrl = `${known.url}#issuecomment-2`; + setup({ + activity: { + comments: [ + { + id: "comment-2", + kind: "issue-comment", + author: { login: "octocat" }, + body: "Looks good", + createdAt: "2026-09-01T00:00:00Z", + url: commentUrl, + path: null, + reviewState: null, + }, + ], + reviewThreads: [], + commits: [], + }, + }); + const translations = await getTranslationsSnapshot("ja"); + await using screen = await render( + + #1} + originalUrl={commentUrl} + target={{ + environmentId: EnvironmentId.make("environment"), + input: { projectId: ProjectId.make("project"), repository: "owner/repo", number: 1 }, + }} + /> + , + ); + + await userEvent.hover(screen.getByRole("link")); + + await expect.element(page.getByText(/octocat\s*がコメントしました/)).toBeVisible(); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx b/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx index 029b6674734d6..13b0435572cac 100644 --- a/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx +++ b/apps/web/src/components/pullRequest/PullRequestLinkPreview.tsx @@ -1,6 +1,6 @@ import type { PreviewCard as PreviewCardPrimitive } from "@base-ui/react/preview-card"; import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime"; -import { useMessages } from "gt-react"; +import { T, useMessages, Var } from "gt-react"; import { parsePullRequestAnchor, pullRequestLinkCommit } from "@t3tools/shared/pullRequestAnchor"; import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts"; import { @@ -200,17 +200,24 @@ function LinkedComment({ subject: Extract, { kind: "comment" }>; }) { const outcome = pullRequestReviewOutcome(subject.reviewState); + const author = ( + + {actorLabel(subject.author)} + + ); return (

- - {actorLabel(subject.author)} - {outcome === null ? ( - commented + + {author} commented + ) : ( - + <> + {author} + + )} · diff --git a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx index 190475d4f1a46..bd806e469b8d3 100644 --- a/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListEmptyState.tsx @@ -72,7 +72,9 @@ export function PullRequestListEmptyState({ }) { const gt = useGT(); const shownQuery = - query.length > 48 ? `${query.slice(0, splitsSurrogatePair(query, 48) ? 47 : 48)}…` : query; + query.length > 48 + ? `${query.slice(0, splitsSurrogatePair(query, 48) ? 47 : 48).trimEnd()}…` + : query; if (!hasProjects) { return ( diff --git a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx index 58dc689343bd1..c02a0bde59336 100644 --- a/apps/web/src/components/pullRequest/PullRequestListFilters.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListFilters.tsx @@ -51,6 +51,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { pullRequestAuthorChoices, selectedPullRequestAuthor, + selectedPullRequestLabels, pullRequestLabelChoices, pullRequestLabelColor, type PullRequestAuthorFacet, @@ -352,7 +353,9 @@ function PullRequestAuthorChoices({ {option.actor.login} {option.mergedCount > 0 ? ( - {option.mergedCount} {option.mergedCount === 1 ? "merge" : "merges"} loaded + {gt("{count, plural, one {{count} merge loaded} other {{count} merges loaded}}", { + count: option.mergedCount, + })} ) : null} @@ -422,9 +425,9 @@ function PullRequestLabelChoices({ const selected = new Set(value.map((name) => name.toLowerCase())); const choices = pullRequestLabelChoices(options, hosted.labels, query); const visible = [ - ...value - .filter((name) => !choices.some((option) => option.name.toLowerCase() === name.toLowerCase())) - .map((name) => ({ name, color: null, count: 0 })), + ...selectedPullRequestLabels(options, hosted.labels, value).filter( + (label) => !choices.some((option) => option.name.toLowerCase() === label.name.toLowerCase()), + ), ...choices, ]; return ( diff --git a/apps/web/src/components/pullRequest/PullRequestListRow.tsx b/apps/web/src/components/pullRequest/PullRequestListRow.tsx index feec84fac0110..70c0d27b87dd0 100644 --- a/apps/web/src/components/pullRequest/PullRequestListRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestListRow.tsx @@ -19,6 +19,9 @@ import { export const PULL_REQUEST_ROW_CLASS = "group/pr-row flex w-full items-center gap-2 rounded-md py-1 pr-1 text-left"; +export const PULL_REQUEST_PAGE_ROW_CLASS = + "min-w-0 flex-1 cursor-pointer px-3 py-2.5 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring"; + export const PULL_REQUEST_ROW_NUMBER_CLASS = "shrink-0 font-mono text-xs tabular-nums text-muted-foreground"; diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx index 1f946c684f6b1..70d2c7fc009aa 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx @@ -1,5 +1,6 @@ import { act, render, type Screen } from "../../../test/render"; import { AuthSourceControlWriteScope, EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -49,6 +50,7 @@ vi.mock(import("~/state/pullRequests"), async (original) => ({ }), })); +import { RightPanelSheet } from "../RightPanelSheet"; import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor"; const secondary = EnvironmentId.make("secondary"); @@ -143,3 +145,43 @@ it("completes @mentions and !references on Enter, and Escape closes the list unt expect(onCancel).not.toHaveBeenCalled(); expect(onSave).not.toHaveBeenCalled(); }); + +it("Escape cancels the edit without closing the right panel sheet", async () => { + setup(); + permissions.allowed.add(secondary); + const onCloseSheet = vi.fn(); + function EditableComment() { + const [editing, setEditing] = useState(true); + if (!editing) return

Original description

; + return ( + { + onCancel(); + setEditing(false); + }} + /> + ); + } + await using _screen = await render( + + + , + ); + const textarea = page.getByRole("textbox", { name: "Pull request description" }); + await expect.element(textarea).toHaveFocus(); + + await userEvent.keyboard("{Escape}"); + await expect.element(textarea).not.toBeInTheDocument(); + expect(onCancel).toHaveBeenCalledTimes(1); + expect(onCloseSheet).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onCloseSheet).toHaveBeenCalledTimes(1); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx index 36a29fa4495a6..2e9f86ec945b5 100644 --- a/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx +++ b/apps/web/src/components/pullRequest/PullRequestMarkdownEditor.tsx @@ -79,6 +79,7 @@ export function PullRequestMarkdownEditor({ } if (event.key !== "Escape" || saving) return; event.preventDefault(); + event.stopPropagation(); onCancel(); }} > diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.browser.test.tsx index d94162a22f658..5cc62bd5520a1 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.browser.test.tsx @@ -1,9 +1,10 @@ import { EnvironmentId, ProjectId, type PullRequestReviewThread } from "@t3tools/contracts"; import { expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { registerCommands } from "~/shortcuts/dispatcher"; import { act, render } from "../../../test/render"; +import { RightPanelSheet } from "../RightPanelSheet"; import { ReviewThreadCard } from "./PullRequestReviewAnnotation"; const thread: PullRequestReviewThread = { @@ -80,10 +81,48 @@ it("leaves IME keys in a review reply to the composition", async () => { await userEvent.keyboard("{Escape}"); await expect.element(reply()).not.toBeInTheDocument(); - expect(heard).toEqual([{ key: "Escape", consumed: true }]); + expect(heard).toEqual([]); await screen.getByRole("button", { name: "Reply", exact: true }).click(); await reply().fill("Draft"); await userEvent.keyboard("{Control>}{Enter}{/Control}"); expect(onReply).toHaveBeenCalledExactlyOnceWith("Draft"); }); + +it("Escape cancels a review reply without closing the right panel sheet", async () => { + const onCloseSheet = vi.fn(); + await using _screen = await render( + + true} + onLoadMore={async () => null} + canEditComment={() => false} + onEditComment={async () => false} + onToggleResolved={() => {}} + onReacted={() => {}} + /> + , + ); + await act(() => + (page.getByRole("button", { name: "Reply", exact: true }).element() as HTMLElement).focus(), + ); + await userEvent.keyboard("{Enter}"); + const reply = page.getByRole("textbox", { name: "Reply to this conversation" }); + await reply.fill("Draft"); + + await userEvent.keyboard("{Escape}"); + await expect.element(reply).not.toBeInTheDocument(); + expect(onCloseSheet).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onCloseSheet).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index 43b5c90554809..e11a763be4148 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -61,6 +61,7 @@ function submitKeys(input: { } if (event.key === "Escape" && input.onCancel) { event.preventDefault(); + event.stopPropagation(); input.onCancel(); } if (isCommentSubmitShortcut(event, input.value, input.pending, input.allowEmpty)) { diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx index 872cd534de991..7b2d8d296b72a 100644 --- a/apps/web/src/components/pullRequest/PullRequestRow.tsx +++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx @@ -20,6 +20,7 @@ import { pullRequestPanelReference } from "./usePullRequestDetail"; import type { EnvironmentPullRequestEntry } from "./pullRequestList.logic"; import { openOnHostLabel, showPullRequestLinkContextMenu } from "./pullRequestLinkContextMenu"; import { + PULL_REQUEST_PAGE_ROW_CLASS, PULL_REQUEST_ROW_CLASS, PULL_REQUEST_ROW_NUMBER_CLASS, PullRequestRowAuthor, @@ -65,8 +66,6 @@ function PullRequestRowLabels({ labels }: { labels: EnvironmentPullRequestEntry[ ); } -const PAGE_ROW_CLASS = "px-3 py-2.5"; - export type PullRequestRowTarget = Pick< EnvironmentPullRequestEntry, "environmentId" | "projectId" | "host" | "repository" | "number" @@ -130,11 +129,7 @@ function PullRequestRowImpl({ onBlur={(event) => { if (!event.currentTarget.matches(":hover")) onIntent?.(null); }} - className={cn( - PULL_REQUEST_ROW_CLASS, - PAGE_ROW_CLASS, - "min-w-0 flex-1 cursor-pointer transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring", - )} + className={cn(PULL_REQUEST_ROW_CLASS, PULL_REQUEST_PAGE_ROW_CLASS)} > ({ + openLink: vi.fn(async () => {}), + useOpenLink: vi.fn(), +})); +vi.mock(import("~/browser/useOpenLink"), () => ({ + useOpenLink: (threadRef: unknown) => { + linkState.useOpenLink(threadRef); + return linkState.openLink; + }, +})); + import { render } from "../../../test/render"; import "../../index.css"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; @@ -158,6 +170,9 @@ it.each(["review", "issue-comment", "resolved-reply"] as const)( ); await expect.element(screen.getByText("Linked reply", { exact: true })).toBeVisible(); await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url)); + const target = screen.container.querySelector("[data-pr-link-target=true]"); + expect(target?.textContent).toContain("Linked reply"); + expect(document.activeElement).toBe(target); await screen.rerender(
{ + linkState.openLink.mockClear(); + linkState.useOpenLink.mockClear(); + const reviewUrl = `${detail.url}#pullrequestreview-1`; + const commentUrl = `${detail.url}#issuecomment-2`; + const threadRef = { + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread-1"), + }; + const commented: PullRequestDetailView = { + ...detail, + commits: [], + comments: [ + { + id: "review", + kind: "review", + author: { login: "bob", name: null, avatarUrl: null }, + body: "Looks good", + createdAt: "2026-10-01T00:00:00Z", + url: reviewUrl, + path: null, + reviewState: "APPROVED", + }, + { + id: "comment", + kind: "issue-comment", + author: { login: "alice", name: null, avatarUrl: null }, + body: "One question", + createdAt: "2026-10-01T00:01:00Z", + url: commentUrl, + path: null, + reviewState: null, + }, + ], + }; + await using screen = await render( +
+ {}} + detail={commented} + environmentId={threadRef.environmentId} + threadRef={threadRef} + reference={detail} + order="oldest" + onOpenCommit={() => {}} + onRefresh={() => {}} + /> +
, + ); + await userEvent.click(screen.getByRole("button", { name: "Open activity on host" })); + expect(linkState.useOpenLink).toHaveBeenCalledWith(threadRef); + expect(linkState.openLink).toHaveBeenLastCalledWith(reviewUrl, { + event: expect.objectContaining({ metaKey: false, ctrlKey: false }), + }); + + await userEvent.click(screen.getByRole("button", { name: /1 comment/ })); + const buttons = screen.getByRole("button", { name: "Open activity on host" }).all(); + await userEvent.click(buttons[1]!); + expect(linkState.openLink).toHaveBeenLastCalledWith(commentUrl, { + event: expect.objectContaining({ metaKey: false, ctrlKey: false }), + }); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx index 1853489d1d7bb..1db82d89ce871 100644 --- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx @@ -28,8 +28,8 @@ import { msg, T, useGT, useMessages, Var } from "gt-react"; import { m } from "~/i18n/messages"; import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react"; +import { useOpenLink } from "~/browser/useOpenLink"; import { cn } from "~/lib/utils"; -import { readLocalApi } from "~/localApi"; import { pullRequestEnvironment } from "~/state/pullRequests"; import { RelativeTime } from "~/components/RelativeTime"; @@ -219,7 +219,12 @@ function AddToChatButton({ ); } -function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) { +type OpenOnHost = ( + url: string, + event: { readonly metaKey: boolean; readonly ctrlKey: boolean; readonly button?: number }, +) => void; + +function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: OpenOnHost }) { const gt = useGT(); return url === null ? null : ( @@ -247,7 +252,7 @@ function ConversationCard({ event: PullRequestTimelineEvent; editable: PullRequestComment | null; cwd: string; - onOpen: (url: string) => void; + onOpen: OpenOnHost; reactions: ReactionSurface; showPath?: boolean; /** A reply goes with its conversation, from the card that heads it. */ @@ -402,7 +407,7 @@ function ConversationGroup({ events: ReadonlyArray; editable: ReadonlyMap; cwd: string; - onOpen: (url: string) => void; + onOpen: OpenOnHost; reactions: ReactionSurface; }) { const [open, setOpen] = useState( @@ -493,7 +498,7 @@ function ReviewThreadEvent({ detail: PullRequestDetailView; editable: ReadonlyMap; cwd: string; - onOpen: (url: string) => void; + onOpen: OpenOnHost; reactions: ReactionSurface; }) { const gt = useGT(); @@ -734,17 +739,30 @@ function ReviewVerdictEvent({ outcome: PullRequestReviewOutcome; stale: boolean; cwd: string; - onOpen: (url: string) => void; + onOpen: OpenOnHost; reactions: ReactionSurface; }) { const gt = useGT(); const resolve = useMessages(); const canReact = reactions.canReact(event); + const isTarget = + reactions.revealAnchor != null && + pullRequestAnchorMatchesUrl(reactions.revealAnchor, event.url); return ( -
+
} />
@@ -911,8 +929,9 @@ export function PullRequestTimelineTab({ }, [revealUrl, targetIndex]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab useEffect(() => () => stopHolding.current?.(), []); - const openOnHost = (url: string) => { - void readLocalApi()?.shell.openExternal(url); + const openLink = useOpenLink(threadRef); + const openOnHost: OpenOnHost = (url, event) => { + void openLink(url, { event }).catch(console.error); }; const rowKey = (row: PullRequestTimelineRow) => { diff --git a/apps/web/src/components/pullRequest/PullRequestTitleEditor.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestTitleEditor.browser.test.tsx new file mode 100644 index 0000000000000..f28548894fb51 --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestTitleEditor.browser.test.tsx @@ -0,0 +1,86 @@ +import { + EnvironmentId, + ProjectId, + SourceControlProviderKind, + type PullRequestDetail, +} from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { act, render } from "../../../test/render"; +import { RightPanelSheet } from "../RightPanelSheet"; +import { PullRequestTitleEditor } from "./PullRequestTitleEditor"; + +const detail: PullRequestDetail = { + provider: SourceControlProviderKind.make("github"), + projectId: ProjectId.make("project"), + projectTitle: "Project", + workspaceRoot: "/workspace", + repository: "owner/repo", + number: 1, + title: "Test pull request", + body: "", + url: "https://github.com/owner/repo/pull/1", + author: { login: "author", name: null, avatarUrl: null }, + viewer: "author", + state: "open", + isDraft: false, + mergeability: "mergeable", + additions: 1, + deletions: 0, + changedFiles: 1, + headBranch: "feature", + baseBranch: "main", + createdAt: "2026-09-01T00:00:00Z", + updatedAt: "2026-09-01T00:00:00Z", + mergedAt: null, + closedAt: null, + reviewers: [], + labels: [], + checks: [], + mergeCapabilities: { merge: false, squash: false, rebase: false }, + capabilities: { + diff: true, + comment: false, + search: true, + actions: [], + mergeMethods: [], + review: { inlineComment: false, reply: false, resolve: false, verdicts: [] }, + reviewers: { request: false, listCandidates: false }, + edit: { changeRequest: true, comment: false }, + }, + viewerPermissions: { + actions: [], + comment: false, + resolve: false, + verdicts: [], + requestReviewers: false, + }, +}; + +it("Escape cancels the title edit without closing the right panel sheet", async () => { + const onCloseSheet = vi.fn(); + await using _screen = await render( + + + , + ); + await act(() => + (page.getByRole("button", { name: "Edit title" }).element() as HTMLElement).click(), + ); + const input = page.getByRole("textbox", { name: "Pull request title" }); + await expect.element(input).toHaveFocus(); + + await userEvent.keyboard("{Escape}"); + await expect.element(input).not.toBeInTheDocument(); + expect(onCloseSheet).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onCloseSheet).toHaveBeenCalledTimes(1); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestTitleEditor.tsx b/apps/web/src/components/pullRequest/PullRequestTitleEditor.tsx index 21d791cd570dd..d0bce1b5b1a4a 100644 --- a/apps/web/src/components/pullRequest/PullRequestTitleEditor.tsx +++ b/apps/web/src/components/pullRequest/PullRequestTitleEditor.tsx @@ -109,6 +109,7 @@ export function PullRequestTitleEditor({ void saveTitle(titleDraft); } else if (event.key === "Escape") { event.preventDefault(); + event.stopPropagation(); setTitleScope(null); } }} diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx index fbf4c55d763c4..77c6785f07e78 100644 --- a/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.browser.test.tsx @@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; import { registerCommands } from "../../shortcuts/dispatcher"; +import { PullRequestChecksPopover } from "./PullRequestChecksPopover"; import { PullRequestSearchInput } from "./PullRequestListFilters"; import { PullRequestsColumn } from "./PullRequestsColumn"; @@ -36,14 +37,14 @@ function createColumn(maximizedAway: boolean, scrollRef: RefObject { .element(screen.getByRole("textbox", { name: "Search pull requests" })) .toHaveFocus(); }); + + it("ignores Cmd/Ctrl+F while a dialog is open", async () => { + const scrollRef = createRef(); + await using screen = await render( + <> + {createColumn(false, scrollRef)} +
+ +
+ , + ); + const dialogInput = screen.getByRole("textbox", { name: "View name" }); + await userEvent.click(dialogInput); + expect(dispatchFindShortcut(dialogInput.element()).defaultPrevented).toBe(false); + await expect.element(dialogInput).toHaveFocus(); + }); }); function CondensedSearchColumn({ @@ -165,3 +182,32 @@ describe("PullRequestsColumn condensed search", () => { .toBeInTheDocument(); }); }); + +describe("PullRequestChecksPopover", () => { + it("keeps clicks inside the popover from selecting the parent row", async () => { + const onSelect = vi.fn(); + await using screen = await render( + , + ); + + await userEvent.click( + screen.getByRole("button", { name: "Checks: Some checks were not successful" }), + ); + await userEvent.click(page.getByRole("button", { name: "Show all" })); + await expect.element(page.getByText("Test", { exact: true })).toBeInTheDocument(); + expect(onSelect).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + await userEvent.click(screen.getByText("Open PR", { exact: true })); + expect(onSelect).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx index 6cd38913860f2..f0e57ea3976a6 100644 --- a/apps/web/src/components/pullRequest/PullRequestsColumn.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsColumn.tsx @@ -74,6 +74,9 @@ function ExpandableSearch({ ); } +const FIND_BLOCKER_SELECTOR = + '[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open], [data-keybinding-capture]'; + export function PullRequestsColumn({ refreshing, onRefresh, @@ -147,6 +150,7 @@ export function PullRequestsColumn({ if (event.defaultPrevented) return; if (event.key.toLowerCase() !== "f" || !(event.metaKey || event.ctrlKey)) return; if (event.altKey || event.shiftKey) return; + if (event.target instanceof Element && event.target.closest(FIND_BLOCKER_SELECTOR)) return; event.preventDefault(); // A closed topbar search has no input yet; opening it mounts one that focuses itself. if (condensed) setSearchOpen(true); diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsx index 497560a627df3..44ae4372aa266 100644 --- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx +++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx @@ -2,7 +2,10 @@ import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; import { heldPullRequestListEntriesAtom } from "@t3tools/client-runtime/state/pull-requests"; import { AsyncResult, Atom } from "effect/reactivity"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; -import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query"; +import { + applyPullRequestFilterChange, + pullRequestMenuFilters, +} from "@t3tools/client-runtime/pull-request-query"; import { Spinner } from "~/components/ui/spinner"; import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions"; import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullRequestActions"; @@ -1383,13 +1386,9 @@ export function PullRequestsPage() { involvement={search.involvement} involvementOptions={resolveFilterOptions(INVOLVEMENT_TABS, resolve)} onInvolvement={(involvement) => updateListScope({ involvement })} - filters={ - typedParsed.filters.draft - ? { ...menuFilters, draft: typedParsed.filters.draft } - : menuFilters - } + filters={pullRequestMenuFilters(typedParsed.filters, menuFilters)} onFilters={(value) => { - const { query, filters: next } = applyPullRequestDraftFilterChange( + const { query, filters: next } = applyPullRequestFilterChange( typedQuery, menuFilters, value, diff --git a/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx b/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx index 95185c23ae263..58daac3fee589 100644 --- a/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx +++ b/apps/web/src/components/pullRequest/ThreadPullRequestsPanel.tsx @@ -458,6 +458,7 @@ function EnabledThreadPullRequestsPanel({ threadRef }: { threadRef: ScopedThread : pullRequestLinkPanelTarget({ url: link.url, environmentId: threadRef.environmentId, + projectId: thread?.projectId, primaryEnvironmentId, lendHostProject: true, }); diff --git a/apps/web/src/components/pullRequest/guide/GuideTour.tsx b/apps/web/src/components/pullRequest/guide/GuideTour.tsx index a4285f2fdef4e..340576526686e 100644 --- a/apps/web/src/components/pullRequest/guide/GuideTour.tsx +++ b/apps/web/src/components/pullRequest/guide/GuideTour.tsx @@ -4,6 +4,7 @@ import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "rea import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents"; import { isEditableFocused } from "~/lib/editableFocus"; +import { isInSideChatPane } from "~/lib/sideChatPane"; import { pullRequestEnvironment } from "~/state/pullRequests"; import { useAtomCommand } from "~/state/use-atom-command"; @@ -86,11 +87,19 @@ export function GuideTour({ const step = (delta: 1 | -1) => goTo(stepTourPosition(position, delta, stopCount)); const stepFromKey = useEffectEvent((event: KeyboardEvent) => { - if (event.defaultPrevented || event.isComposing || isCommandPaletteOpen()) return; + if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return; + if (isCommandPaletteOpen()) return; if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return; const key = event.key.toLowerCase(); if (key !== "j" && key !== "k") return; - if (isEditableFocused(event.target)) return; + if (isEditableFocused(event.target) || isInSideChatPane(event.target)) return; + const floatingLayer = + event.target instanceof Element + ? event.target.closest( + '[role="dialog"], [role="alertdialog"], [aria-modal="true"], [role="menu"], [role="combobox"], [data-slot$="popup"]', + ) + : null; + if (floatingLayer !== null && !floatingLayer.contains(scrollRef.current)) return; event.preventDefault(); step(key === "j" ? 1 : -1); }); diff --git a/apps/web/src/components/pullRequest/guide/useReviewGuideWriter.ts b/apps/web/src/components/pullRequest/guide/useReviewGuideWriter.ts index d04d0d714e191..d45770d40ff40 100644 --- a/apps/web/src/components/pullRequest/guide/useReviewGuideWriter.ts +++ b/apps/web/src/components/pullRequest/guide/useReviewGuideWriter.ts @@ -34,7 +34,8 @@ export function useReviewGuideWriter({ }); const [starting, setStarting] = useState(false); const data = query.data; - const running = starting || data?.run?._tag === "Running"; + // A failed read keeps the last good answer, whose Running run can no longer be confirmed. + const running = starting || (query.error === null && data?.run?._tag === "Running"); // A run reported by the server is watched where its answer lands (state/pullRequests.ts). const write = async () => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 4fd39e8169bda..58b917cf2938d 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -359,6 +359,20 @@ describe("pull request timeline", () => { kind: "comment", excerpt: "Looks good, see run()", }); + for (const [body, excerpt] of [ + ["Keep `[!NOTE]` in the file.", "Keep [!NOTE] in the file."], + ["> [!NOTE]\n> Real alert.", "Real alert."], + ["Keep [!WARNING] in prose.", "Keep [!WARNING] in prose."], + ] as const) { + expect( + pullRequestLinkSubject(`${pr}#issuecomment-5`, { + comments: [{ ...activity.comments[0]!, body }], + reviewThreads: [], + commits: [], + }), + body, + ).toMatchObject({ kind: "comment", excerpt }); + } // A review with no text of its own is shown through the comment it posted. expect(pullRequestLinkSubject(`${pr}#pullrequestreview-9`, activity)).toMatchObject({ kind: "comment", @@ -380,6 +394,14 @@ describe("pull request timeline", () => { const cut = pullRequestLinkSubject(`${pr}#issuecomment-5`, long); const excerpt = cut && "excerpt" in cut ? cut.excerpt : null; expect(excerpt).toMatch(/^(?:i ?)+…$/u); + const between = { + ...activity, + comments: [{ ...activity.comments[0]!, body: `${"a".repeat(278)} word` }], + }; + const cutBetween = pullRequestLinkSubject(`${pr}#issuecomment-5`, between); + expect(cutBetween && "excerpt" in cutBetween ? cutBetween.excerpt : null).toBe( + `${"a".repeat(278)}…`, + ); }); it("orders host timestamps by instant across offsets and fractional seconds", () => { @@ -780,6 +802,12 @@ describe("fix findings handoff", () => { checks: [], }); expect(emojiAtCut.reviewComments[1]?.text).toBe(`reviewer: ${"x".repeat(986)}...`); + const spaceAtCut = buildFixFindingsHandoff({ + ...base, + reviewThreads: [thread(`${"x".repeat(986)} and more of the review.${"y".repeat(100)}`)], + checks: [], + }); + expect(spaceAtCut.reviewComments[1]?.text).toBe(`reviewer: ${"x".repeat(986)}...`); }); it("keeps the newest threads and the failing checks when it has to cut", () => { @@ -798,6 +826,32 @@ describe("fix findings handoff", () => { expect(handoff.prompt).toContain("6 further findings were omitted"); }); + it("counts only threads with readable text toward the findings limit", () => { + const reviewThreads = Array.from({ length: 21 }, (_, index) => + thread(index === 0 ? "Fix wrong total" : "", { id: `t${index}` }), + ); + const handoff = buildFixFindingsHandoff({ ...base, reviewThreads, checks: [] }); + expect(handoff.reviewComments.slice(1).map((comment) => comment.text)).toEqual([ + "reviewer: Fix wrong total", + ]); + expect(handoff.prompt).not.toContain("further findings were omitted"); + + const hiddenRoot = reviewThreads[1]!; + const withReply = buildFixFindingsHandoff({ + ...base, + reviewThreads: [ + { + ...hiddenRoot, + comments: [...hiddenRoot.comments, ...thread("Fix wrong total").comments], + }, + ], + checks: [], + }); + expect(withReply.reviewComments.slice(1).map((comment) => comment.text)).toEqual([ + "reviewer: Fix wrong total", + ]); + }); + it("names a GitLab merge request as one", () => { const handoff = buildFixFindingsHandoff({ ...base, @@ -848,6 +902,18 @@ describe("findings that cannot be attached", () => { expect(handoff.prompt).not.toContain("No unresolved review findings"); }); + it("strips hidden HTML comments before bounding loose review remarks", () => { + const annotatedReview: PullRequestComment = { + ...review, + author: { login: "reviewer", name: null, avatarUrl: null }, + body: `\nFix wrong total`, + }; + const handoff = buildFixFindingsHandoff({ ...base, comments: [annotatedReview] }); + + expect(handoff.prompt).toContain("> reviewer: Fix wrong total"); + expect(handoff.prompt).not.toContain("\nFix wrong total`, + createdAt: "2026-07-01T00:00:00Z", + url: null, + path: null, + reviewState: "CHANGES_REQUESTED", + }, + }, + }); + + expect(handoff.prompt).toContain("> reviewer: Fix wrong total"); + expect(handoff.prompt).not.toContain("", options)).toBe("Thinking"); + expect( + wordsHtml("Checked the cache first[^1] and it was stale.\n\n[^1]: Redis TTL is 60s.", { + ...options, + extensions: { preview: { ...preview, maxLength: 120 } }, + }), + ).toBe("Checked the cache first and it was stale."); }); it("makes a saved file's Markdown inert", () => { @@ -296,6 +344,20 @@ describe("wordsHast", () => { expect(html).toContain('style="white-space:pre"> for '); }); + it("lays out inline math left to right inside a right-to-left paragraph", () => { + const hast = wordsHast("הקבועים הם $e$, $i$ ו-$\\pi$.", { ...ASSISTANT, math: true }); + const paragraph = hast.children[0] as Element; + expect(paragraph.properties.dir).toBe("rtl"); + const directions: Array = []; + const visit = (node: Element, ltr: boolean) => { + const own = ltr || node.properties.dir === "ltr"; + if (node.tagName === "svg") return void directions.push(own); + for (const child of node.children) if (child.type === "element") visit(child, own); + }; + for (const child of paragraph.children) if (child.type === "element") visit(child, false); + expect(directions).toEqual([true, true, true]); + }); + it("keeps control bytes, blank lines, unclosed blocks, shell vars, and table dollars intact in math", () => { const options = { ...ASSISTANT, math: true }; expect(toHtml(wordsHast("Pasted: $a\u001bb + c$", options))).toContain(" { '

Label
\nshot
\ncontinues

', '

Label
\nshot
\ncontinues

', ], + [ + "**Shot** (dark) ![a](https://x.dev/a.png) ![b](https://x.dev/b.png)", + '

Shot (dark)
\na b

', + '

Shot (dark)
\na b

', + ], + [ + "**A favicon ![i](https://x.dev/i.png)** stays inline", + '

A favicon i stays inline

', + '

A favicon i stays inline

', + ], [ 'Status\n\ncontinues', '

Status\n\ncontinues

', @@ -374,6 +446,28 @@ describe("wordsHast", () => { ).toEqual(["pick {a} or [b]"]); }); + it.each([ + [ + ':codex-followup[try :codex-followup[inner]{prompt="i"} then]{prompt="o"} end', + "try inner then end", + ], + [ + '😀 :codex-followup[[see :codex-file-citation[a]{path="a.ts"}][ref]]{prompt="o"} and :codex-followup[again]{prompt="a"} end\n\n[ref]: https://x.dev', + '😀 [see :codex-file-citation[a]{path="a.ts"}][ref] and again end\n\n[ref]: https://x.dev', + ], + [ + ':codex-followup[ read :codex-file-citation[a]{path="a.ts"} then]{prompt="o"} end', + " read [a.ts]() then end", + ], + [ + ':codex-followup[read :codex-file-citation[a]{path="a.ts"}] end', + ":codex-followup[read [a.ts]()] end", + ], + ])("copies nested directives without losing surrounding text: %s", (markdown, expected) => { + expect(renderCodexDirectivesForCopy(markdown)).toBe(expected); + expect(renderCodexInlineDirectivesAsMarkdown(markdown)).toBe(expected); + }); + it.each([ ["# Title\n[a]: https://x.dev", ["[a]: "]], ['> [a]:\n> https://x.dev "The\n> guide"', ['[a]: "The guide"']], @@ -381,10 +475,23 @@ describe("wordsHast", () => { ["
\n[a]: https://x.dev\n
", []], ["- ```\n [a]: https://x.dev\n ```", []], ["text\n[a]: https://x.dev", []], + ["[doc]: https://example.com\n\nSee [doc].\n\n```js\nx", ["[doc]: "]], + ["[a]: https://x.dev\n\n