diff --git a/.agents/skills/launch-video/SKILL.md b/.agents/skills/launch-video/SKILL.md new file mode 100644 index 0000000000000..82ef0bdd576d7 --- /dev/null +++ b/.agents/skills/launch-video/SKILL.md @@ -0,0 +1,167 @@ +--- +name: launch-video +description: Make a short launch video (1920x1080 MP4 plus an outro PNG) that demos a T3 Code feature, built from the real app with added motion, for an X/Twitter announcement or release thread. Use when asked for a launch video, demo video, feature teaser or announcement clip, or to add a video to a release tweet. +--- + +# Launch videos + +A launch video is 20–30 seconds: the app goes through one story in two or three beats, +the camera punches in on each, a caption names it, and an outro card closes. Frames are +rendered one by one in headless Chromium, so the result is deterministic. + +There are two ways to build one: + +- **Real app (default).** A staging script runs the real server and web client with fictional + data and the free replay agent, drives the flow in a browser, and freezes the page at each + beat into `beats/.html`. The story stacks those frozen pages and adds the motion: the + camera, cursor, pops, glows, typing and captions. The UI is whatever the app draws today, so + re-staging on main updates the video. `stagings/linked-environments/` is a finished example. +- **Mock.** `template/story.html` is a hand-built HTML copy of the app (the 0.1.11 tunnels + video). Use it only for what a staging can't produce, such as another app on the desktop or + a desktop-only screen. It drifts as the app changes. + +## Workflow (real app) + +1. **Learn the feature.** Read the PRs and the components it touches. Write down the one + thing a user can now do that they couldn't before, in the user's words. +2. **Write the story** before any code: who the user is, what they want, and two or three + beats that get them there. Show it to the maintainer if the angle is a guess. +3. **Stage it.** Copy `stagings/linked-environments/` to `stagings//`. + - `serve.mjs` builds fresh homes under `.t3/launch//` with `scripts/stage-env.mjs`. + Each home gets a fictional machine label, the replay agent, and no paid provider. + It starts the servers, creates projects, writes `/stage.json` and keeps running. + Run it in the background. + - `drive.mjs` opens the web client with `openBrowser()` (1440×720, dark, release + branding) and walks the flow. It calls `beat(name)` at each moment the video needs. + Re-run it as often as you like against the same servers. + - Agent turns: pass `claude: [turns]` to `prepareHome` and the real Claude provider runs + `scripts/fake-claude.mjs` as its CLI, so the video shows Claude's logo, models, thinking + and tool rows. Each turn is `{ match, steps }`: `think`, `text`, `bash` (+ `output`, `ms`), + `wait`, and `tool` (+ `input`), which calls that T3 MCP tool for real, e.g. + `delegate_task`. Match generated titles with a `{ match: "title", repeat: true }` turn. + `` is filled from the JSON file at `T3_DEV_REPLAY_VARS`, for ids that change + every run. `fake-claude.log` in the home records the protocol, for debugging. + - The free replay agent (`apps/server/scripts/dev-replay-agent.ts`) still works without + `claude`, but it shows as an ACP provider. +4. **Create the story:** `scripts/new.sh ~/launch-videos/`, then copy the beats in, or + pass that directory as the staging's ``. Add one ` + + + + + + + + + + + +
+ + + +
+ +
+
+ 1Delegate to another machine and it runs there. +
+
+ 2Watch it live without pairing. +
+
+ 3Connect to interact in one click. +
+ +
+
+ +

Linked environments
every machine, one app

+

Available now in T3 Code 0.1.12

+
t3.codes
+
+
+ + + + + diff --git a/.agents/skills/launch-video/template/real.html b/.agents/skills/launch-video/template/real.html new file mode 100644 index 0000000000000..99be36d95345c --- /dev/null +++ b/.agents/skills/launch-video/template/real.html @@ -0,0 +1,263 @@ + + + + + + + + +
+
+
+
+ + +
+
+
+ + + +
+
+
+
+ 1Lead phrase and the rest. +
+
+
+
+ +

Feature name
second line

+

Available now in T3 Code 0.0.0

+
t3.codes
+
+
+ + + + + diff --git a/.agents/skills/launch-video/template/story.html b/.agents/skills/launch-video/template/story.html new file mode 100644 index 0000000000000..85684dc7dcd2b --- /dev/null +++ b/.agents/skills/launch-video/template/story.html @@ -0,0 +1,2150 @@ + + + + + + + +
+
+
+
+
+
+ + + + +
T3 Code
+ + + + + + + + + +
+
+
+ MSacme/mugshotnow +
+
Spin up the dev stack
+
+ + devbox✳ +
+
+
+
+ MSacme/mugshot2h +
+
Fix avatar upload on Safari
+
+ + + + + fix/safari-avatar+42 + ✳ +
+
+
+
+ MSacme/mugshot5h +
+
Pricing page copy
+
+ + + + + copy/pricing+18 + + + ✳ +
+
+
+
+ INacme/infra1d +
+
Bump Postgres to 17
+
+ + + + + pg-17+7 + ✳ +
+
+
+
+ MSacme/mugshot2d +
+
Onboarding email tweaks
+
+ + + + + main + + + ✳ +
+
+
+
+ + + + + + + + + + + + + + +
+
+ +
+ MSmugshot/Spin up the dev stack +
+
+ + + + + + +
+ +
+
spin up the app and a postgres for it so I can poke at it
+
+
+ Working for 4sWorked for 9s +
+
+
+ + + + +
+ Running docker compose up -d dbRunning pnpm devRan 2 commands +
+
+
+ Both are up. The app is on localhost:3000, seeded from Postgres on + localhost:5432. +
+
+ +
+ Ask anything. @ files, $ skills, / commands +
+ spin up the app and a postgres for it so I can poke at it +
+
+ + + + ✳Opus 5.5 Medium + + + + + + + + +
+
+ +
+
+ + devbox + + + + + +
+
+ Dev + + +
+
+
+ + + + + main +
+
+ + + + + Changes Uncommitted+0 −0 +
+
+
Servers
+
+
+ + + + + +
+
localhost:5432
+
+ Agent · postgresForwarded to :5432 +
+
+
+
+ + + + + + + + + +
+
+
+
Forward to this machine, for any app here
+
+
+
+ + + + + +
+
localhost:3000
+
Agent · next-server
+
+
+
+
+ LimitsUnavailable +
+
+ +
+
+
+ + + + New tab + Mugshot admin✕ +
+
+ + +
+
+
+ + + + + + + + + +
+
+ + + + + + + + +
+ Search or enter a URLhttp://localhost:3000/admin +
+ + + + + + + + + + + +
+
+
+
+ +

Good morning.

+
+
+
Users
+
1,204+37 today
+
+
+
Mugs shot
+
8,911
+
+
+
+
NameEmailJoined
+
Ada Parkada@example.com2m ago
+
Sam Okaforsam@example.com14m ago
+
Lena Ruizlena@example.com1h ago
+
Mira Holtmira@example.com3h ago
+
+
+
+
✓
+
+
Forwarded port 5432
+
+ Apps on this machine reach it at localhost:5432. +
+
+
+
+
+
+ +
+
+
+ mugshot_dev — localhost:5432 + + on your Mac +
+
+
+
Tables
+
+ + + + users +
+
+ + + + mugs +
+
+ + + + sessions +
+
+ + + + _migrations +
+
+
+
+ users1,204 rowsLIMIT 300 +
+
+
+ idnameemailcreated_at +
+
+ 1204Ada Parkada@example.com2026-11-19 09:41 +
+
+ 1203Sam Okaforsam@example.com2026-11-19 09:29 +
+
+ 1202Lena Ruizlena@example.com2026-11-19 08:43 +
+
+ 1201Mira Holtmira@example.com2026-11-19 06:58 +
+
+ 1200Priya Nairpriya@example.com2026-11-18 22:10 +
+
+ 1199Jonas Bergjonas@example.com2026-11-18 19:37 +
+
+
+
+
New connection PostgreSQL
+
+ +
localhost
+
+
+ +
5432
+
+
+ +
app
+
+
+ +
mugshot_dev
+
+
+ TestConnect +
+
+
+
+ +
+ + + +
+
+ +
+
Ask an agent on a remote box to start your stack
+
+ 1Open a server + in the in-app browser. Tunnelled automatically. +
+
+ 2Forward a port and every app on your Mac can use it. +
+
+
+
+ +

Browser tunnels and
port forwarding

+

Available now in T3 Code 0.1.11

+
t3.codes
+
+
+ + + + diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000000000..b73b575006fcd --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,6 @@ +# Link the MSVC C runtime statically, so Windows binaries such as +# t3-resource-monitor.exe start on machines without the Visual C++ +# Redistributable. Cargo reads this file for every build started from the +# repository root, including `--manifest-path` builds of native/* crates. +[target.'cfg(all(windows, target_env = "msvc"))'] +rustflags = ["-C", "target-feature=+crt-static"] diff --git a/.github/scripts/check-nightly-release.cjs b/.github/scripts/check-nightly-release.cjs index a9502b26c8c81..4d2d039696322 100644 --- a/.github/scripts/check-nightly-release.cjs +++ b/.github/scripts/check-nightly-release.cjs @@ -124,7 +124,12 @@ async function resolveLatestNightlyCommit({ github, context, core }) { // The two places a nightly install looks for an update: the `update-feed` pointer, and // releases.atom, which holds the 10 newest git tags of any kind. Older installs take the first // nightly in the feed. Reports what each names beside the newest published nightly. -async function readNightlyUpdateFeed({ github, context, fetch = globalThis.fetch }) { +async function readNightlyUpdateFeed({ + github, + context, + fetch = globalThis.fetch, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), +}) { const latest = await findLatestNightly({ github, context }); if (!latest) return {}; @@ -150,19 +155,28 @@ async function readNightlyUpdateFeed({ github, context, fetch = globalThis.fetch // An unreadable feed leaves `feedTags` unset, so the pointer is still repaired. An error page // can answer HTTP 200, so only an Atom document counts as read. - let feedTags; - try { - const feed = await fetch(`${base}/releases.atom`, { signal: signal() }); - const body = feed.ok ? await feed.text() : ""; - if (/]/.test(body)) { - feedTags = Array.from(body.matchAll(/href="[^"]*\/releases\/tag\/([^"]+)"/g), (match) => + const readFeed = async () => { + try { + const feed = await fetch(`${base}/releases.atom`, { signal: signal() }); + const body = feed.ok ? await feed.text() : ""; + if (!/]/.test(body)) return {}; + const feedTags = Array.from(body.matchAll(/href="[^"]*\/releases\/tag\/([^"]+)"/g), (match) => decodeURIComponent(match[1]), ); + const feedNightly = feedTags.find((tag) => /^v?\d+\.\d+\.\d+-nightly\./.test(tag)); + return { feedTags, feedNightly }; + } catch { + return {}; } - } catch {} - const feedNightly = feedTags?.find((tag) => /^v?\d+\.\d+\.\d+-nightly\./.test(tag)); + }; + // The feed can lag a release published seconds ago, so read it again before calling it hidden. + let feed = await readFeed(); + for (let retry = 0; retry < 3 && feed.feedTags && feed.feedNightly !== latest.tagName; retry++) { + await sleep(30_000); + feed = await readFeed(); + } - return { tag: latest.tagName, pointerTag, feedNightly, feedTags }; + return { tag: latest.tagName, pointerTag, ...feed }; } module.exports = { diff --git a/.github/scripts/check-nightly-release.test.cjs b/.github/scripts/check-nightly-release.test.cjs index 2f3d385755ca6..82decf82747da 100644 --- a/.github/scripts/check-nightly-release.test.cjs +++ b/.github/scripts/check-nightly-release.test.cjs @@ -247,19 +247,33 @@ const atomFeed = (tags) => new Response(`${tags.map(atomEntry).join("")} url === "https://github.com/example/app/releases.atom" - ? feed + ? (feeds.length > 1 ? feeds.shift() : feeds[0]).clone() : url === "https://github.com/example/app/releases/download/update-feed/nightly.json" ? pointer : assert.fail(`unexpected fetch ${url}`); + options.sleeps = []; + options.sleep = async (ms) => void options.sleeps.push(ms); return options; } +test("update feed check waits for a nightly published moments ago to reach the feed", async () => { + const options = updateFeedFixture({ + feed: [atomFeed([OLDER]), atomFeed([NEWEST, OLDER])], + pointer: Response.json({ tag_name: NEWEST }), + }); + const { feedNightly } = await readNightlyUpdateFeed(options); + assert.equal(feedNightly, NEWEST); + assert.deepEqual(options.sleeps, [30_000]); +}); + const missing = () => new Response("Not Found", { status: 404 }); // HTTP 200, then the connection drops before the body arrives. const brokenBody = () => diff --git a/.github/triage/PLAYBOOK.md b/.github/triage/PLAYBOOK.md index cc922de448005..b11731e54e8f7 100644 --- a/.github/triage/PLAYBOOK.md +++ b/.github/triage/PLAYBOOK.md @@ -125,9 +125,20 @@ of `main` for that work, never the tag-pinned diagnosis clone. - Show the user the complete final issue text and get an explicit yes before posting. Never post without it. - Note at the end of the issue which model and agent produced it. -- Post with `gh issue create --repo pingdotgg/t3code --label via-triage` only - if `gh api repos/pingdotgg/t3code --jq .permissions.triage` prints `true`. -- Otherwise, or if `gh` is not authenticated, build a prefilled +- If `gh` is authenticated to github.com, post through the "Triage report" + issue template. It applies `via-triage` for every reporter, while + `gh issue create --label` drops the label without triage permission. Write + the approved title and body to files, the title without a trailing newline, + so the shell never parses their text. Then run: + + gh api --hostname github.com graphql -f repo="$(gh api --hostname github.com repos/pingdotgg/t3code --jq .node_id)" -f template="Triage report" -F title=@ -F body=@ -f query='mutation($repo:ID!,$template:String!,$title:String!,$body:String!){createIssue(input:{repositoryId:$repo,issueTemplate:$template,title:$title,body:$body}){issue{url labels(first:20){nodes{name}}}}}' + + Report the issue URL and whether its labels include `via-triage`. Never file a + second issue to repair a label. If you cannot tell whether the issue was + created, check the user's recent issues before you retry. + +- If `gh` is not authenticated, or the request was rejected and created + nothing, build a prefilled https://github.com/pingdotgg/t3code/issues/new?template=via-triage.yml URL. The form applies the label whoever submits it. Add `title` plus one URL-encoded query parameter per form field id: `what-happened`, `diagnosis`, diff --git a/.github/workflows/agent-context-budget.yml b/.github/workflows/agent-context-budget.yml index 5935fb4653c32..8ee0b42c178f4 100644 --- a/.github/workflows/agent-context-budget.yml +++ b/.github/workflows/agent-context-budget.yml @@ -25,15 +25,17 @@ jobs: with: sparse-checkout: apps/server/src/provider/agentContextBudget.json sparse-checkout-cone-mode: false + fetch-depth: 2 + # The checkout is the PR merged onto main; compare with that merge's main parent. A fresh + # fetch of main can be newer and lower, which reports the PR as growing what main just cut. - name: Compare with main run: | - git fetch --quiet --depth=1 origin main - if ! git cat-file -e "FETCH_HEAD:$BUDGET" 2>/dev/null; then + if ! git cat-file -e "HEAD^1:$BUDGET" 2>/dev/null; then echo "main has no agent context budget yet." exit 0 fi - git show "FETCH_HEAD:$BUDGET" > "$RUNNER_TEMP/main.json" + git show "HEAD^1:$BUDGET" > "$RUNNER_TEMP/main.json" grown=$(jq -r --slurpfile main "$RUNNER_TEMP/main.json" ' to_entries[] | select($main[0][.key] != null and .value > $main[0][.key]) diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 4252cb46e7a05..2d3a38168c79e 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -212,7 +212,7 @@ jobs: uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: native/resource-monitor/target/${{ inputs.rust_target }}/release/t3-resource-monitor${{ inputs.platform == 'win' && '.exe' || '' }} - key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }} + key: resource-monitor-${{ inputs.rust_target }}-${{ hashFiles('.cargo/config.toml', 'native/resource-monitor/Cargo.lock', 'native/resource-monitor/Cargo.toml', 'native/resource-monitor/src/**') }} - name: Cache Linux capture helpers if: inputs.platform == 'linux' diff --git a/AGENTS.md b/AGENTS.md index 6d788cd6c9e20..2ce4be8b77640 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,7 +80,7 @@ The most common defect in this repo is a change that works on the path you teste - `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run. - Setup runs in the background. While `.t3/setup-running` names a live PID, wait for it and do not run `vp i`. It ends with `.t3/setup-done` or `.t3/setup-failed` (with the error tail). With no marker at all, setup never ran here, so run `vp i` yourself. -- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins. +- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins. A plain `git clone` is not a worktree: it shares `~/.t3/dev` with the main checkout and is not seeded. To isolate one, run `vp run migrate-dev-db --base-dir /.t3`, then `vp run dev --home-dir /.t3`. - Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift. - Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, then give that full URL to an unpaired browser. Do not wire up `tailscale serve` by hand, open the URL yourself, or consume the user's pairing link. A browser with the reusable dev cookie can use the bare origin. If a normal one-time token was consumed, mint a fresh one with `node apps/server/src/bin.ts pair`. It carries standard scopes, while the startup URL carries admin scopes needed for Connections settings. - To reuse web dev auth across worktrees, configure one fixed `T3CODE_DEV_AUTH_TOKEN` in the main checkout's gitignored `.env`. The `t3.json` setup links that file into worktrees. Never commit or publish the token or a startup URL. See [Reusable dev credential](docs/operations/development.md#reusable-dev-credential). diff --git a/apps/desktop/package.json b/apps/desktop/package.json index d91a9ee5e4cfe..bd770e285e71b 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.10", + "version": "0.1.11", "private": true, "type": "module", "main": "dist-electron/boot.cjs", diff --git a/apps/desktop/scripts/build-apple-speech.mjs b/apps/desktop/scripts/build-apple-speech.mjs new file mode 100644 index 0000000000000..6334100ea386f --- /dev/null +++ b/apps/desktop/scripts/build-apple-speech.mjs @@ -0,0 +1,76 @@ +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeURL from "node:url"; +import * as NodeUtil from "node:util"; + +// oxlint-disable-next-line t3code/no-global-process-runtime -- The Swift compiler targets the actual host; this script has no Effect runtime. +const hostArch = process.arch; +// oxlint-disable-next-line t3code/no-global-process-runtime -- The Speech framework exists only in the macOS SDK. +const hostPlatform = process.platform; + +const { values } = NodeUtil.parseArgs({ + options: { output: { type: "string" }, arch: { type: "string", default: hostArch } }, +}); +// Packaging passes --output and must not ship without the helper; dev builds only lose the option. +const required = values.output !== undefined; + +if (hostPlatform !== "darwin") { + if (required) throw new Error("The Apple Speech helper can only be built on macOS."); +} else { + const targets = { arm64: ["arm64"], x64: ["x86_64"], universal: ["arm64", "x86_64"] }[ + values.arch + ]; + if (targets === undefined) throw new Error(`Unsupported macOS architecture: ${values.arch}`); + const root = NodeURL.fileURLToPath(new URL("../../../native/apple-speech/", import.meta.url)); + const sources = ["AppleSpeech.swift", "AppleSpeechEngine.swift"].map((file) => + NodePath.resolve(root, file), + ); + const output = values.output ?? NodePath.resolve(root, "build", values.arch, "t3-apple-speech"); + let current = false; + try { + current = + NodeFS.statSync(output).mtimeMs >= + Math.max( + ...sources.map((source) => NodeFS.statSync(source).mtimeMs), + NodeFS.statSync(NodeURL.fileURLToPath(import.meta.url)).mtimeMs, + ); + } catch {} + if (!current) { + NodeFS.mkdirSync(NodePath.dirname(output), { recursive: true }); + const temporary = `${output}.${process.pid}.tmp`; + const slices = targets.map((target) => `${temporary}.${target}`); + try { + targets.forEach((target, index) => + NodeChildProcess.execFileSync( + "xcrun", + [ + "swiftc", + "-O", + "-swift-version", + "5", + "-parse-as-library", + "-target", + `${target}-apple-macos26.0`, + ...sources, + "-o", + slices[index], + ], + { stdio: "inherit" }, + ), + ); + NodeChildProcess.execFileSync("xcrun", ["lipo", "-create", ...slices, "-output", temporary], { + stdio: "inherit", + }); + NodeFS.renameSync(temporary, output); + } catch (cause) { + if (required) + throw new Error("Building the Apple Speech helper requires Xcode 26 or later.", { cause }); + console.warn( + "Skipping the Apple Speech helper (needs Xcode 26 or later); on-device Mac dictation is unavailable in this build.", + ); + } finally { + for (const file of [temporary, ...slices]) NodeFS.rmSync(file, { force: true }); + } + } +} diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 122da3f0512e5..aca0bf3ea26f2 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -60,6 +60,11 @@ NodeChildProcess.execFileSync( [NodePath.join(desktopDir, "scripts/build-browser-secret.mjs")], { stdio: "inherit" }, ); +NodeChildProcess.execFileSync( + process.execPath, + [NodePath.join(desktopDir, "scripts/build-apple-speech.mjs")], + { stdio: "inherit" }, +); await waitForResources({ baseDir: desktopDir, diff --git a/apps/desktop/scripts/start-electron.mjs b/apps/desktop/scripts/start-electron.mjs index 5dde034121b8e..8cabe3e5069fe 100644 --- a/apps/desktop/scripts/start-electron.mjs +++ b/apps/desktop/scripts/start-electron.mjs @@ -8,6 +8,11 @@ NodeChildProcess.execFileSync( [NodePath.join(desktopDir, "scripts/build-browser-secret.mjs")], { stdio: "inherit" }, ); +NodeChildProcess.execFileSync( + process.execPath, + [NodePath.join(desktopDir, "scripts/build-apple-speech.mjs")], + { stdio: "inherit" }, +); const childEnv = { ...process.env }; delete childEnv.ELECTRON_RUN_AS_NODE; diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index cc5fca3f42ab4..360ed62ce306b 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -74,6 +74,7 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as LoopbackTunnel from "../preview/LoopbackTunnel.ts"; import * as PreviewManager from "../preview/Manager.ts"; +import * as AppleSpeech from "../speech/AppleSpeech.ts"; interface StubbedDesktop { readonly localEnvironmentEnabled: boolean; @@ -233,6 +234,7 @@ const runStubbedDesktop = (stub: StubbedDesktop) => Layer.mock(ElectronTheme.ElectronTheme, {}), Layer.mock(ElectronWindow.ElectronWindow, {}), Layer.mock(MacPermissions.MacPermissions, {}), + Layer.mock(AppleSpeech.AppleSpeech, {}), Layer.mock(LoopbackTunnel.LoopbackTunnel, {}), Layer.mock(PreviewManager.PreviewManager, { isBrowserPartition: () => { diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 565a50f193e0f..fd820a2c478d1 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -354,7 +354,12 @@ describe("DesktopBackendConfiguration", () => { }, ensureNodePty: (distro) => { observedDistros.push(distro); - return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; + return { + ok: true, + nodePath: "/usr/bin/node", + resolvedPath: "/usr/bin:/bin", + t3Home: null, + }; }, getDistroIp: (distro) => { observedDistros.push(distro); @@ -385,10 +390,12 @@ describe("DesktopBackendConfiguration", () => { windowsArchivePath: string; runtimeId: string; sha256: string; + t3Home: string | null; }> = []; let probeCount = 0; let legacyCleanupCount = 0; - const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64"; + const t3Home = "/home/test/.config/t3"; + const linuxAppRoot = `${t3Home}/wsl-runtime/1.2.3-x64`; const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin"; return withPackagedWslHarness( @@ -399,17 +406,18 @@ describe("DesktopBackendConfiguration", () => { legacyCleanupCount += 1; }), wsl: () => ({ - prepareRuntime: (_distro, archive) => { + prepareRuntime: (_distro, archive, archiveT3Home) => { observedArchives.push({ windowsArchivePath: archive.windowsPath, runtimeId: archive.runtimeId, sha256: archive.sha256, + t3Home: archiveT3Home, }); return { ok: true, linuxAppRoot }; }, probeRuntime: () => { probeCount += 1; - return { ok: true, resolvedPath }; + return { ok: true, resolvedPath, t3Home }; }, ensureNodePty: () => { throw new Error("the staged runtime must not probe for node-pty"); @@ -427,6 +435,7 @@ describe("DesktopBackendConfiguration", () => { windowsArchivePath: archivePath, runtimeId: `sha256-${archiveHash}`, sha256: archiveHash, + t3Home, }, ]); assert.equal(probeCount, 1); @@ -442,12 +451,14 @@ describe("DesktopBackendConfiguration", () => { "--exec", "env", `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`, + `T3CODE_HOME=${t3Home}`, `${linuxAppRoot}/t3`, "--bootstrap-fd", "0", ]); assert.notInclude(config.args, "/usr/bin/node"); assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`); + assert.equal(config.wslT3Home, t3Home); assert.equal(legacyCleanupCount, 1); assert.isTrue(Option.isNone(config.preflightFailure)); }), @@ -470,6 +481,7 @@ describe("DesktopBackendConfiguration", () => { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin", + t3Home: null, }), }), }, @@ -502,10 +514,14 @@ describe("DesktopBackendConfiguration", () => { archiveHash: "b".repeat(64), wsl: () => ({ prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }), - invalidateRuntime: () => Effect.die("failed staging must not invalidate a runtime"), ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); - return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; + return { + ok: true, + nodePath: "/usr/bin/node", + resolvedPath: "/usr/bin:/bin", + t3Home: null, + }; }, }), }, @@ -524,28 +540,30 @@ describe("DesktopBackendConfiguration", () => { ); }); - it.effect("resolveWsl retires a staged runtime whose launch probe fails", () => { + it.effect("resolveWsl does not stage a runtime when the login-shell probe fails", () => { const archiveHash = "c".repeat(64); const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`; let probeCount = 0; const observedNodePtyRoots: string[] = []; - const invalidatedRuntimeIds: string[] = []; return withPackagedWslHarness( { archiveHash, wsl: () => ({ - prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }), - invalidateRuntime: (_distro, runtimeId) => - Effect.sync(() => { - invalidatedRuntimeIds.push(runtimeId); - }), + prepareRuntime: () => { + throw new Error("a failed probe must not stage the runtime"); + }, probeRuntime: () => { probeCount += 1; return { ok: false, reason: "WSL login-shell PATH could not be resolved" }; }, ensureNodePty: (_distro, root) => { observedNodePtyRoots.push(root); - return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" }; + return { + ok: true, + nodePath: "/usr/bin/node", + resolvedPath: "/usr/bin:/bin", + t3Home: null, + }; }, }), }, @@ -562,23 +580,17 @@ describe("DesktopBackendConfiguration", () => { assert.equal(config.entryPath, mountedEntryPath); assert.isUndefined(config.wslRuntimeId); assert.isTrue(Option.isNone(config.preflightFailure)); - assert.deepEqual(invalidatedRuntimeIds, [`sha256-${archiveHash}`]); }), ); }); it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => { const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache"; - const invalidatedRuntimeIds: string[] = []; return withPackagedWslHarness( { archiveHash: "f".repeat(64), wsl: () => ({ prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }), - invalidateRuntime: (_distro, runtimeId) => - Effect.sync(() => { - invalidatedRuntimeIds.push(runtimeId); - }), probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }), ensureNodePty: () => ({ ok: false, @@ -596,7 +608,6 @@ describe("DesktopBackendConfiguration", () => { assert.isFalse(failure.fatal); assert.equal(failure.retryLimit, 12); assert.include(failure.reason, "timed out"); - assert.deepEqual(invalidatedRuntimeIds, []); }), ); }); @@ -633,7 +644,7 @@ describe("DesktopBackendConfiguration", () => { isAvailable: true, distros: [{ name: "Ubuntu", isDefault: true, version: 2 }], windowsToWslPath: () => Option.some(linuxAppRoot), - ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }), + ensureNodePty: () => ({ ok: true, nodePath, resolvedPath, t3Home: null }), getDistroIp: () => Option.some("172.27.0.99"), }), ), diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 82f0a30a40cd9..983c00a04c3fd 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -293,6 +293,7 @@ interface WslPreflightSuccess { readonly windowsEntryPath: string; readonly runtime: WslPreflightRuntime; readonly resolvedPath: string; + readonly t3Home: string | null; readonly runtimeId?: string; } @@ -412,7 +413,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f : ({ ok: true, windowsEntryPath, linuxAppRoot: mountedAppRoot.value } as const); }); - let stagedFailure: { readonly runtimeId?: string; readonly reason: string } | undefined; + let stagedFailure: { readonly reason: string } | undefined; const failedStaged = (failure: { readonly reason: string }) => ({ _tag: "Failed", @@ -421,11 +422,16 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f }) as const; if (input.runtimeArchive !== null) { - const runtime = yield* wslEnv.prepareRuntime(runningDistro, input.runtimeArchive); - if (runtime.ok) { - // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. - const stagedProbe = yield* wslEnv.probeRuntime(runningDistro); - if (stagedProbe.ok) { + // Staged runtimes bundle Node and node-pty; provider PATH discovery must not require them. + // Probe first: the runtime cache lives under the login shell's T3CODE_HOME. + const stagedProbe = yield* wslEnv.probeRuntime(runningDistro); + if (stagedProbe.ok) { + const runtime = yield* wslEnv.prepareRuntime( + runningDistro, + input.runtimeArchive, + stagedProbe.t3Home, + ); + if (runtime.ok) { yield* wslServerTree.cleanupLegacy; return { _tag: "Ready", @@ -433,20 +439,21 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f windowsEntryPath: environment.backendEntryPath, runtime: { kind: "executable", entryPath: `${runtime.linuxAppRoot}/t3` }, resolvedPath: stagedProbe.resolvedPath, + t3Home: stagedProbe.t3Home, runtimeId: input.runtimeArchive.runtimeId, } as const; } - yield* Effect.logWarning( - "The staged WSL runtime probe failed; retrying from the mounted server tree.", - { reason: stagedProbe.reason }, - ); - stagedFailure = { runtimeId: input.runtimeArchive.runtimeId, reason: stagedProbe.reason }; - } else { stagedFailure = { reason: runtime.reason }; yield* Effect.logWarning( "Could not stage the WSL runtime; launching from the mounted server tree instead.", { reason: runtime.reason }, ); + } else { + yield* Effect.logWarning( + "The staged WSL runtime probe failed; retrying from the mounted server tree.", + { reason: stagedProbe.reason }, + ); + stagedFailure = { reason: stagedProbe.reason }; } } @@ -469,10 +476,6 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f : failedNodePty(nodePtyResult); } - if (stagedFailure?.runtimeId) { - yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId); - } - return { _tag: "Ready", runningDistro, @@ -483,6 +486,7 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f linuxEntryPath: `${mounted.linuxAppRoot}/apps/server/dist/bin.mjs`, }, resolvedPath: nodePtyResult.resolvedPath, + t3Home: nodePtyResult.t3Home, } as const; }); @@ -745,13 +749,16 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl "--exec", "env", `PATH=${launchPath}`, + ...(preflight.t3Home === null ? [] : [`T3CODE_HOME=${preflight.t3Home}`]), ...command, "--bootstrap-fd", "0", ...devUrlArgs, ], preflightFailure: Option.none(), - ...(preflight.runtimeId === undefined ? {} : { wslRuntimeId: preflight.runtimeId }), + ...(preflight.runtimeId === undefined + ? {} + : { wslRuntimeId: preflight.runtimeId, wslT3Home: preflight.t3Home }), } satisfies DesktopBackendManager.DesktopBackendStartConfig; }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 8b4f154b5d4de..4f7e115a5456f 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -84,6 +84,7 @@ export interface DesktopBackendStartConfig extends BackendProcessContext { readonly preflightFailure: Option.Option; readonly runningDistro?: string; readonly wslRuntimeId?: string; + readonly wslT3Home?: string | null; } export interface PreflightFailure { @@ -992,6 +993,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( yield* wslEnvironment.pruneRuntimes( config.value.runningDistro, config.value.wslRuntimeId, + config.value.wslT3Home ?? null, ); } }), diff --git a/apps/desktop/src/i18n/translations/de.json b/apps/desktop/src/i18n/translations/de.json index 92f2ec88b3bdb..8e39e7585f60d 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Browservorschau", "49de6209699eb616": "Unbenannter Passkey", "b4a5bb1075d95154": "Passkey auswählen", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Du bist auf dem neuesten Stand!", "c6399b55619e2f67": "T3 Code {version} ist derzeit die neueste verfügbare Version.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Neu starten", "116a21f6cc215e5f": "Suche nach Updates fehlgeschlagen", "32c88cd9421abf33": "Es konnte nicht nach Updates gesucht werden.", + "9e5ada64a94c10de": "Dieser {build}-Build kann sich über den Kanal {saved} nicht selbst aktualisieren. Stelle den Update-Kanal wieder auf {build} um oder nutze Review neben Update-Kanal, um den Wechsel zu {saved} erneut zu versuchen.", "b37aca07d3c644d9": "Ein unbekannter Fehler ist aufgetreten. Bitte versuche es später erneut.", "c8c23435e780a60c": "Updates nicht verfügbar", "aecf7c98b81bef7a": "Automatische Updates sind derzeit nicht verfügbar.", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 964d6a7ed12f7..9a07ef060cbc9 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Browser preview", "49de6209699eb616": "Unnamed passkey", "b4a5bb1075d95154": "Choose a passkey", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "You're up to date!", "c6399b55619e2f67": "T3 Code {version} is currently the newest version available.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Restart", "116a21f6cc215e5f": "Update check failed", "32c88cd9421abf33": "Could not check for updates.", + "9e5ada64a94c10de": "This {build} build can't update from the {saved} track on its own. Switch the update track back to {build}, or use Review beside Update track to retry the switch to {saved}.", "b37aca07d3c644d9": "An unknown error occurred. Please try again later.", "c8c23435e780a60c": "Updates unavailable", "aecf7c98b81bef7a": "Automatic updates are not available right now.", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index c1a64c21e241d..f891e9eaf850b 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Vista previa del navegador", "49de6209699eb616": "Llave de acceso sin nombre", "b4a5bb1075d95154": "Elige una llave de acceso", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Estable", "1f12213f4d809e89": "¡Estás al día!", "c6399b55619e2f67": "T3 Code {version} es la versión más reciente disponible.", "b6e5b31255e011c5": "Aceptar", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Reiniciar", "116a21f6cc215e5f": "Error al buscar actualizaciones", "32c88cd9421abf33": "No se pudo buscar actualizaciones.", + "9e5ada64a94c10de": "Esta compilación {build} no puede actualizarse por sí sola desde el canal {saved}. Vuelve a poner el canal de actualizaciones en {build} o usa Revisar junto a Canal de actualizaciones para reintentar el cambio a {saved}.", "b37aca07d3c644d9": "Se produjo un error desconocido. Vuelve a intentarlo más tarde.", "c8c23435e780a60c": "Actualizaciones no disponibles", "aecf7c98b81bef7a": "Las actualizaciones automáticas no están disponibles ahora mismo.", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 4a0376ba9c94a..0bb5a47518581 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Aperçu du navigateur", "49de6209699eb616": "Clé d’accès sans nom", "b4a5bb1075d95154": "Choisir une clé d’accès", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Vous êtes à jour !", "c6399b55619e2f67": "T3 Code {version} est actuellement la version la plus récente.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Redémarrer", "116a21f6cc215e5f": "Échec de la recherche de mises à jour", "32c88cd9421abf33": "Impossible de rechercher des mises à jour.", + "9e5ada64a94c10de": "Cette version {build} ne peut pas se mettre à jour seule depuis le canal {saved}. Remettez le canal de mise à jour sur {build}, ou utilisez Consulter à côté de Canal de mise à jour pour relancer le passage à {saved}.", "b37aca07d3c644d9": "Une erreur inconnue s’est produite. Veuillez réessayer plus tard.", "c8c23435e780a60c": "Mises à jour indisponibles", "aecf7c98b81bef7a": "Les mises à jour automatiques ne sont pas disponibles pour le moment.", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index 4b5db0e253a42..df89efe466261 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "ブラウザープレビュー", "49de6209699eb616": "名前のないパスキー", "b4a5bb1075d95154": "パスキーを選択", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "安定版", "1f12213f4d809e89": "最新の状態です", "c6399b55619e2f67": "T3 Code {version} が現在利用できる最新バージョンです。", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "再起動", "116a21f6cc215e5f": "更新の確認に失敗しました", "32c88cd9421abf33": "更新を確認できませんでした。", + "9e5ada64a94c10de": "この {build} ビルドは {saved} トラックから単独では更新できません。更新トラックを {build} に戻すか、更新トラックの横にある「レビュー」を使って {saved} への切り替えを再試行してください。", "b37aca07d3c644d9": "不明なエラーが発生しました。しばらくしてからもう一度お試しください。", "c8c23435e780a60c": "更新を利用できません", "aecf7c98b81bef7a": "現在、自動更新は利用できません。", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index ccebba3366e84..566724b9b91c1 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "브라우저 미리 보기", "49de6209699eb616": "이름 없는 패스키", "b4a5bb1075d95154": "패스키 선택", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "최신 버전입니다!", "c6399b55619e2f67": "T3 Code {version}이(가) 현재 사용 가능한 최신 버전입니다.", "b6e5b31255e011c5": "확인", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "다시 시작", "116a21f6cc215e5f": "업데이트 확인 실패", "32c88cd9421abf33": "업데이트를 확인할 수 없습니다.", + "9e5ada64a94c10de": "이 {build} 빌드는 {saved} 트랙에서 스스로 업데이트할 수 없습니다. 업데이트 트랙을 다시 {build}(으)로 바꾸거나, 업데이트 트랙 옆의 검토를 사용해 {saved}(으)로 전환을 다시 시도하세요.", "b37aca07d3c644d9": "알 수 없는 오류가 발생했습니다. 나중에 다시 시도하세요.", "c8c23435e780a60c": "업데이트를 사용할 수 없음", "aecf7c98b81bef7a": "지금은 자동 업데이트를 사용할 수 없습니다.", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 11e80a2f667bb..67f4eefd1c9ec 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Pré-visualização do navegador", "49de6209699eb616": "Chave de acesso sem nome", "b4a5bb1075d95154": "Escolha uma chave de acesso", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Estável", "1f12213f4d809e89": "Você está atualizado!", "c6399b55619e2f67": "O T3 Code {version} é a versão mais recente disponível.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Reiniciar", "116a21f6cc215e5f": "Falha ao verificar atualizações", "32c88cd9421abf33": "Não foi possível verificar atualizações.", + "9e5ada64a94c10de": "Esta build {build} não consegue se atualizar sozinha pelo canal {saved}. Volte o canal de atualização para {build} ou use Revisar ao lado de Canal de atualização para tentar de novo a mudança para {saved}.", "b37aca07d3c644d9": "Ocorreu um erro desconhecido. Tente novamente mais tarde.", "c8c23435e780a60c": "Atualizações indisponíveis", "aecf7c98b81bef7a": "As atualizações automáticas não estão disponíveis no momento.", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index cdcf02d0648dd..46364dfabe488 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Предпросмотр в браузере", "49de6209699eb616": "Безымянный ключ доступа", "b4a5bb1075d95154": "Выберите ключ доступа", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Стабильный", "1f12213f4d809e89": "У вас последняя версия!", "c6399b55619e2f67": "T3 Code {version} — новейшая доступная версия.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Перезапустить", "116a21f6cc215e5f": "Ошибка проверки обновлений", "32c88cd9421abf33": "Не удалось проверить обновления.", + "9e5ada64a94c10de": "Эта сборка {build} не может сама обновиться с канала «{saved}». Верните канал обновлений на «{build}» или нажмите «Ревью» рядом с «Канал обновлений», чтобы повторить переход на «{saved}».", "b37aca07d3c644d9": "Произошла неизвестная ошибка. Повторите попытку позже.", "c8c23435e780a60c": "Обновления недоступны", "aecf7c98b81bef7a": "Автоматические обновления сейчас недоступны.", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index e2a204965fec2..67bcaf6a380aa 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "Förhandsvisning i webbläsaren", "49de6209699eb616": "Namnlös lösenordsnyckel", "b4a5bb1075d95154": "Välj en lösenordsnyckel", + "61aa0109862ff7ca": "Nightly", + "f3430cac09a505a0": "Stable", "1f12213f4d809e89": "Du har den senaste versionen!", "c6399b55619e2f67": "T3 Code {version} är den senaste tillgängliga versionen.", "b6e5b31255e011c5": "OK", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "Starta om", "116a21f6cc215e5f": "Sökningen efter uppdateringar misslyckades", "32c88cd9421abf33": "Kunde inte söka efter uppdateringar.", + "9e5ada64a94c10de": "Den här {build}-versionen kan inte uppdatera sig själv från spåret {saved}. Byt tillbaka uppdateringsspåret till {build}, eller använd Granska bredvid Uppdateringsspår för att försöka byta till {saved} igen.", "b37aca07d3c644d9": "Ett okänt fel inträffade. Försök igen senare.", "c8c23435e780a60c": "Uppdateringar är inte tillgängliga", "aecf7c98b81bef7a": "Automatiska uppdateringar är inte tillgängliga just nu.", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index 6a89cd600c37a..72122de01df62 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -55,6 +55,8 @@ "6994444f4fec4070": "浏览器预览", "49de6209699eb616": "未命名通行密钥", "b4a5bb1075d95154": "选择通行密钥", + "61aa0109862ff7ca": "Nightly 版", + "f3430cac09a505a0": "稳定版", "1f12213f4d809e89": "已是最新版本!", "c6399b55619e2f67": "T3 Code {version} 已是最新版本。", "b6e5b31255e011c5": "确定", @@ -74,6 +76,7 @@ "2f0a8211a72e29aa": "重启", "116a21f6cc215e5f": "检查更新失败", "32c88cd9421abf33": "无法检查更新。", + "9e5ada64a94c10de": "此 {build} 构建无法自行从 {saved} 通道更新。请将更新通道切回 {build},或使用“更新通道”旁的“查看”重新尝试切换到 {saved}。", "b37aca07d3c644d9": "发生未知错误,请稍后重试。", "c8c23435e780a60c": "更新不可用", "aecf7c98b81bef7a": "目前无法自动更新。", diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index fe65edd0ee1e9..c88ddd0827df0 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -2,6 +2,11 @@ import { startFileDrag } from "./methods/fileDrag.ts"; import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; +import { + appleSpeechAvailable, + appleSpeechPrepare, + appleSpeechTranscribe, +} from "./methods/appleSpeech.ts"; import * as DesktopIpc from "./DesktopIpc.ts"; import { installNotificationBadge } from "./methods/notificationBadge.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; @@ -161,6 +166,9 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(cancelProviderAuthCallback); yield* ipc.handle(openSystemSettings); yield* ipc.handle(checkSystemPermission); + yield* ipc.handle(appleSpeechAvailable); + yield* ipc.handle(appleSpeechPrepare); + yield* ipc.handle(appleSpeechTranscribe); yield* ipc.handle(pasteAsText); yield* ipc.handle(revealWindow); yield* ipc.handle(syncHtmlFullscreen); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index bb708a6ab7c88..71d272333fdc7 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -128,10 +128,18 @@ export const PREVIEW_OPEN_LINK_CHANNEL = "desktop:preview-open-link"; export const PREVIEW_FIND_RESULT_CHANNEL = "desktop:preview-find-result"; export const PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL = "desktop:preview-tunnel-access-request"; export const PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL = "desktop:preview-tunnel-access-resolve"; +export const PORT_FORWARD_START_CHANNEL = "desktop:port-forward-start"; +export const PORT_FORWARD_STOP_CHANNEL = "desktop:port-forward-stop"; +export const PORT_FORWARD_LIST_CHANNEL = "desktop:port-forward-list"; +export const PORT_FORWARD_CHANGE_CHANNEL = "desktop:port-forward-change"; +export const PORT_FORWARD_SHARES_LOOPBACK_CHANNEL = "desktop:port-forward-shares-loopback"; export const MAC_PERMISSION_HELPER_CHANNEL = "desktop:mac-permission-helper"; export const CHECK_SYSTEM_PERMISSION_CHANNEL = "desktop:check-system-permission"; +export const APPLE_SPEECH_AVAILABLE_CHANNEL = "desktop:apple-speech-available"; +export const APPLE_SPEECH_PREPARE_CHANNEL = "desktop:apple-speech-prepare"; +export const APPLE_SPEECH_TRANSCRIBE_CHANNEL = "desktop:apple-speech-transcribe"; export const PREVIEW_RECORDING_INPUT_CHANNEL = "desktop:preview-recording-input"; diff --git a/apps/desktop/src/ipc/methods/appleSpeech.ts b/apps/desktop/src/ipc/methods/appleSpeech.ts new file mode 100644 index 0000000000000..c2d631a00814e --- /dev/null +++ b/apps/desktop/src/ipc/methods/appleSpeech.ts @@ -0,0 +1,37 @@ +import { + DesktopAppleSpeechResultSchema, + DesktopAppleSpeechTranscribeInputSchema, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import * as AppleSpeech from "../../speech/AppleSpeech.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; + +export const appleSpeechAvailable = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.APPLE_SPEECH_AVAILABLE_CHANNEL, + payload: Schema.Void, + result: Schema.Array(Schema.String), + handler: Effect.fn("desktop.ipc.appleSpeech.available")(function* () { + return yield* (yield* AppleSpeech.AppleSpeech).supportedLocales; + }), +}); + +export const appleSpeechPrepare = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.APPLE_SPEECH_PREPARE_CHANNEL, + payload: Schema.String.check(Schema.isMaxLength(64)), + result: DesktopAppleSpeechResultSchema, + handler: Effect.fn("desktop.ipc.appleSpeech.prepare")(function* (locale) { + return yield* (yield* AppleSpeech.AppleSpeech).prepare(locale); + }), +}); + +export const appleSpeechTranscribe = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.APPLE_SPEECH_TRANSCRIBE_CHANNEL, + payload: DesktopAppleSpeechTranscribeInputSchema, + result: DesktopAppleSpeechResultSchema, + handler: Effect.fn("desktop.ipc.appleSpeech.transcribe")(function* ({ locale, pcm }) { + return yield* (yield* AppleSpeech.AppleSpeech).transcribe(locale, pcm); + }), +}); diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index f06c26014f40e..9dc0465c1e55a 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -23,6 +23,9 @@ import { DesktopPreviewCreateTabInputSchema, DesktopPreviewTabInputSchema, DesktopPreviewTunnelAccessResolutionInputSchema, + DesktopPortForwardInputSchema, + DesktopPortForwardSchema, + DesktopSharesLoopbackInputSchema, DesktopPreviewWebviewConfigSchema, PreviewAnnotationSubmissionResultSchema, PreviewCaptureFailure, @@ -66,6 +69,10 @@ export const installPreviewEventForwarding = Effect.fn( yield* manager.subscribeFindResults((event) => electronWindow.sendAll(IpcChannels.PREVIEW_FIND_RESULT_CHANNEL, event), ); + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + yield* tunnel.subscribeForwards((forwards) => + electronWindow.sendAll(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, forwards), + ); }); const setForwardedShortcuts = DesktopIpc.makeIpcMethod({ @@ -379,6 +386,46 @@ const resolveTunnelAccess = DesktopIpc.makeIpcMethod({ }), }); +const forwardPort = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_START_CHANNEL, + payload: DesktopPortForwardInputSchema, + result: DesktopPortForwardSchema, + handler: Effect.fn("desktop.ipc.preview.forwardPort")(function* (input) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.forward(input); + }), +}); + +const stopPortForward = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_STOP_CHANNEL, + payload: DesktopPortForwardInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.stopPortForward")(function* (input) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + yield* tunnel.stopForward(input); + }), +}); + +const listPortForwards = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_LIST_CHANNEL, + payload: Schema.Void, + result: Schema.Array(DesktopPortForwardSchema), + handler: Effect.fn("desktop.ipc.preview.listPortForwards")(function* () { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.forwards; + }), +}); + +const sharesLoopback = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PORT_FORWARD_SHARES_LOOPBACK_CHANNEL, + payload: DesktopSharesLoopbackInputSchema, + result: Schema.Boolean, + handler: Effect.fn("desktop.ipc.preview.sharesLoopback")(function* ({ environmentId }) { + const tunnel = yield* LoopbackTunnel.LoopbackTunnel; + return yield* tunnel.sharesLoopback(environmentId); + }), +}); + export const listBrowserImportSources = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL, payload: Schema.Void, @@ -523,6 +570,10 @@ export const methods = [ clearCache, getPreviewConfig, resolveTunnelAccess, + forwardPort, + stopPortForward, + listPortForwards, + sharesLoopback, setAnnotationTheme, setAnnotationSendEnabled, pickElement, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9c79b66d06ad9..8c32805a94463 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -71,6 +71,7 @@ import * as DesktopUpdatePolicy from "./updates/DesktopUpdatePolicy.ts"; import * as DesktopUpdates from "./updates/DesktopUpdates.ts"; import * as BrowserImport from "./preview/BrowserImport/BrowserImport.ts"; import * as LinuxBrowserSecret from "./preview/BrowserImport/LinuxBrowserSecret.ts"; +import * as AppleSpeech from "./speech/AppleSpeech.ts"; import * as BrowserSession from "./preview/BrowserSession.ts"; import * as DesktopBrowserHost from "./preview/DesktopBrowserHost.ts"; import * as LoopbackTunnel from "./preview/LoopbackTunnel.ts"; @@ -156,6 +157,7 @@ const layerDesktopFoundation = Layer.mergeAll( DesktopPrimaryPaste.layer, DesktopObservability.layer, DesktopRendererHistory.layer, + AppleSpeech.layer, ).pipe(Layer.provideMerge(layerDesktopEnvironment)); const layerDesktopSsh = layerDesktopSshEnvironment.pipe( diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index b413656a15241..ac52fbc73d868 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -262,6 +262,14 @@ contextBridge.exposeInMainWorld("desktopBridge", { readMedia: (url: string) => ipcRenderer.invoke(IpcChannels.READ_MEDIA_CHANNEL, url), checkSystemPermission: (pane: string) => ipcRenderer.invoke(IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL, pane), + appleSpeech: { + supportedLocales: () => + ipcRenderer.invoke(IpcChannels.APPLE_SPEECH_AVAILABLE_CHANNEL, undefined), + prepare: (locale: string) => + ipcRenderer.invoke(IpcChannels.APPLE_SPEECH_PREPARE_CHANNEL, locale), + transcribe: (input: { locale: string; pcm: Uint8Array }) => + ipcRenderer.invoke(IpcChannels.APPLE_SPEECH_TRANSCRIBE_CHANNEL, input), + }, openSystemSettings: (pane: string) => ipcRenderer.invoke(IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL, pane), probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined), @@ -449,6 +457,22 @@ contextBridge.exposeInMainWorld("desktopBridge", { }, resolveTunnelAccess: (requestId, url) => ipcRenderer.invoke(IpcChannels.PREVIEW_TUNNEL_ACCESS_RESOLVE_CHANNEL, { requestId, url }), + forwardPort: (environmentId, remotePort) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_START_CHANNEL, { environmentId, remotePort }), + stopPortForward: (environmentId, remotePort) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_STOP_CHANNEL, { environmentId, remotePort }), + listPortForwards: () => ipcRenderer.invoke(IpcChannels.PORT_FORWARD_LIST_CHANNEL), + sharesLoopback: (environmentId) => + ipcRenderer.invoke(IpcChannels.PORT_FORWARD_SHARES_LOOPBACK_CHANNEL, { environmentId }), + onPortForwards: (listener) => { + const wrappedListener = (_event: Electron.IpcRendererEvent, forwards: unknown) => { + if (!Array.isArray(forwards)) return; + listener(forwards); + }; + ipcRenderer.on(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, wrappedListener); + return () => + ipcRenderer.removeListener(IpcChannels.PORT_FORWARD_CHANGE_CHANNEL, wrappedListener); + }, setAnnotationTheme: (theme) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }), setAnnotationSendEnabled: (tabId, enabled) => diff --git a/apps/desktop/src/preview/LoopbackTunnel.test.ts b/apps/desktop/src/preview/LoopbackTunnel.test.ts index fb193e768e8d2..fe83817c0d5e8 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.test.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.test.ts @@ -1,5 +1,6 @@ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem"; import * as NodeWS from "@effect/platform-node/NodeWS"; +import { EnvironmentId } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { expect, it } from "@effect/vitest"; import * as NodeNet from "node:net"; @@ -8,6 +9,8 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as LoopbackTunnel from "./LoopbackTunnel.ts"; @@ -74,9 +77,10 @@ const unusedPort = Effect.promise( }), ); -/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ -const routeThroughTunnel = ( - tunnelUrl: string | null, +/** The tunnel service, with every access request answered with `tunnelUrl`. */ +const makeTunnel = ( + /** A function answers each access request with its current value. */ + tunnelUrl: string | null | (() => string | null), host?: Layer.Layer | Layer.Layer, ) => Effect.gen(function* () { @@ -96,6 +100,7 @@ const routeThroughTunnel = ( currentMainOrFirst: Effect.succeedSome(window as unknown as Electron.BrowserWindow), }), NodeFileSystem.layer, + SecureRandom.layerWebCrypto, host ?? Layer.empty, ), ), @@ -103,10 +108,25 @@ const routeThroughTunnel = ( ); const tunnel = Context.get(services, LoopbackTunnel.LoopbackTunnel); yield* Queue.take(accessRequests).pipe( - Effect.flatMap((requestId) => tunnel.resolveAccess({ requestId, url: tunnelUrl })), + Effect.flatMap((requestId) => + tunnel.resolveAccess({ + requestId, + url: typeof tunnelUrl === "function" ? tunnelUrl() : tunnelUrl, + }), + ), Effect.forever, Effect.forkScoped, ); + return tunnel; + }); + +/** Routes a stand-in session through the tunnel and returns its SOCKS listener port. */ +const routeThroughTunnel = ( + tunnelUrl: string | null, + host?: Layer.Layer | Layer.Layer, +) => + Effect.gen(function* () { + const tunnel = yield* makeTunnel(tunnelUrl, host); let proxyRules = ""; const session = { setProxy: async (config: Electron.ProxyConfig) => { @@ -284,3 +304,214 @@ it.effect("connects straight to the environment's own forwarded origin port", () expect(received).toEqual([7, 8]); }), ); + +/** Connects to a local port, sends `bytes`, and resolves with the first chunk back. */ +const exchange = (port: number, bytes: Uint8Array) => + Effect.promise( + () => + new Promise((resolve, reject) => { + const socket = NodeNet.connect(port, "127.0.0.1", () => socket.write(bytes)); + socket.once("data", (chunk) => { + resolve([...chunk]); + socket.destroy(); + }); + socket.on("error", reject); + }), + ); + +const refusesConnections = (port: number) => + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(port, "127.0.0.1", () => { + socket.destroy(); + resolve(false); + }); + socket.on("error", () => resolve(true)); + }), + ); + +it.effect("forwards a port over the tunnel on the same local port until stopped", () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel?wsTicket=t`, + ); + const announced: number[][] = []; + yield* tunnel.subscribeForwards((forwards) => + Effect.sync(() => announced.push(forwards.map((forward) => forward.localPort))), + ); + const environmentId = EnvironmentId.make("remote"); + const forward = yield* tunnel.forward({ environmentId, remotePort }); + expect(forward).toEqual({ environmentId, remotePort, localPort: remotePort }); + + expect(yield* exchange(remotePort, Uint8Array.of(4, 5))).toEqual([0xee, 4, 5]); + // The first request is the same-machine probe. + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?wsTicket=t&port=${remotePort}`); + + yield* tunnel.stopForward({ environmentId, remotePort }); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + expect(announced).toEqual([[remotePort], []]); + }), +); + +it.effect("moves a forward to a free port when its own is taken here", () => + Effect.gen(function* () { + const decoy = yield* listenDecoy; + const endpoint = yield* listenEndpoint; + const remotePort = addressPort(decoy.server); + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort, + }); + expect(forward.localPort).not.toBe(remotePort); + + expect(yield* exchange(forward.localPort, Uint8Array.of(6))).toEqual([0xee, 6]); + expect(endpoint.requests.at(-1)).toBe(`/api/preview/tunnel?port=${remotePort}`); + expect(decoy.connections()).toBe(0); + }), +); + +/** An environment on this machine: each tunnel connection dials the requested local port. */ +const listenSameMachineEndpoint = Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer( + { port: 0, host: "127.0.0.1" }, + () => resolve(server), + ); + server.on("connection", (socket: NodeWS.WebSocket, request: { url?: string }) => { + const port = Number(new URL(request.url ?? "", "ws://x").searchParams.get("port")); + const local = NodeNet.connect(port, "127.0.0.1"); + local.on("data", (chunk) => socket.send(chunk)); + local.on("error", () => socket.close()); + socket.on("message", (data: Buffer) => local.write(data)); + socket.on("close", () => local.destroy()); + }); + }), + ), + closeServer, +); + +it.effect("refuses to forward from an environment that shares this machine's loopback", () => + Effect.gen(function* () { + const endpoint = yield* listenSameMachineEndpoint; + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel(`ws://127.0.0.1:${addressPort(endpoint)}/api/preview/tunnel`); + const error = yield* tunnel + .forward({ environmentId: EnvironmentId.make("remote"), remotePort }) + .pipe(Effect.flip); + expect(error._tag).toBe("LoopbackTunnelSameMachineError"); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + }), +); + +it.effect( + "forwards nothing while the environment is out of reach, then forwards once it is back", + () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const remotePort = yield* unusedPort; + let access: string | null = null; + const tunnel = yield* makeTunnel(() => access); + const environmentId = EnvironmentId.make("remote"); + + const unavailable = yield* tunnel.forward({ environmentId, remotePort }).pipe(Effect.flip); + expect(unavailable._tag).toBe("LoopbackTunnelUnavailableError"); + expect(yield* refusesConnections(remotePort)).toBe(true); + expect(yield* tunnel.forwards).toEqual([]); + + access = `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`; + const forward = yield* tunnel.forward({ environmentId, remotePort }); + expect(yield* exchange(forward.localPort, Uint8Array.of(9))).toEqual([0xee, 9]); + }), +); + +/** The environment's tunnel route refusing every port with a 502, as for a port nothing listens on. */ +const listenRefusingEndpoint = (headers: Record) => + Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const server: NodeWS.WebSocketServer = new NodeWS.WebSocketServer( + { + port: 0, + host: "127.0.0.1", + verifyClient: (_info, done) => done(false, 502, "Bad Gateway", headers), + }, + () => resolve(server), + ); + }), + ), + closeServer, + ); + +it.effect.each([ + { case: "the environment reports nothing on the probe port", refused: true }, + { case: "the tunnel fails for another reason", refused: false }, +])("decides a forward's machine only on proof: $case", ({ refused }) => + Effect.gen(function* () { + const endpoint = yield* listenRefusingEndpoint( + refused ? { "x-t3-tunnel-port-refused": "1" } : {}, + ); + const remotePort = yield* unusedPort; + const tunnel = yield* makeTunnel(`ws://127.0.0.1:${addressPort(endpoint)}/api/preview/tunnel`); + const result = yield* tunnel + .forward({ environmentId: EnvironmentId.make("remote"), remotePort }) + .pipe(Effect.result); + if (refused) { + expect(Result.isSuccess(result)).toBe(true); + } else { + expect(Result.isFailure(result) && result.failure._tag).toBe( + "LoopbackTunnelUnavailableError", + ); + expect(yield* refusesConnections(remotePort)).toBe(true); + } + }), +); + +it.effect("closes connections beyond a forward's limit without tunnelling them", () => + Effect.gen(function* () { + const endpoint = yield* listenEndpoint; + const tunnel = yield* makeTunnel( + `ws://127.0.0.1:${addressPort(endpoint.server)}/api/preview/tunnel`, + ); + const forward = yield* tunnel.forward({ + environmentId: EnvironmentId.make("remote"), + remotePort: yield* unusedPort, + }); + const open = () => + Effect.acquireRelease( + Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(forward.localPort, "127.0.0.1", () => { + socket.once("data", () => resolve(socket)); + socket.write(Uint8Array.of(1)); + }); + }), + ), + (socket) => Effect.sync(() => socket.destroy()), + ); + yield* Effect.forEach(Array.from({ length: 64 }), open, { concurrency: "unbounded" }); + const tunnelled = endpoint.requests.length; + const closed = yield* Effect.promise( + () => + new Promise((resolve) => { + const socket = NodeNet.connect(forward.localPort, "127.0.0.1"); + socket.on("close", () => resolve(true)); + socket.on("data", () => resolve(false)); + socket.write(Uint8Array.of(2)); + }), + ); + expect(closed).toBe(true); + expect(endpoint.requests.length).toBe(tunnelled); + }), +); diff --git a/apps/desktop/src/preview/LoopbackTunnel.ts b/apps/desktop/src/preview/LoopbackTunnel.ts index 6eff2dd70b345..1e06993fa54f0 100644 --- a/apps/desktop/src/preview/LoopbackTunnel.ts +++ b/apps/desktop/src/preview/LoopbackTunnel.ts @@ -1,21 +1,28 @@ // Renders another environment's localhost pages in a local webview: the partition's loopback // traffic goes to a SOCKS5 listener here, and each connection rides one WebSocket to the -// environment's /api/preview/tunnel. The page keeps its localhost origin. +// environment's /api/preview/tunnel. The page keeps its localhost origin. Forwarded ports take +// the same route from a plain listener, for any client on this machine. import * as NodeSocket from "@effect/platform-node/NodeSocket"; import * as NodeSocketServer from "@effect/platform-node/NodeSocketServer"; import * as NodeWS from "@effect/platform-node/NodeWS"; -import type { DesktopPreviewTunnelAccessRequest } from "@t3tools/contracts"; +import type { + DesktopPortForward, + DesktopPreviewTunnelAccessRequest, + EnvironmentId, +} from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import type { NonEmptyReadonlyArray } from "effect/Array"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as NetAddress from "effect/net/NetAddress"; import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Socket from "effect/socket/Socket"; @@ -24,6 +31,8 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import { PREVIEW_TUNNEL_ACCESS_REQUEST_CHANNEL } from "../ipc/channels.ts"; const ACCESS_TIMEOUT = "15 seconds"; +const PROBE_TIMEOUT = "3 seconds"; +const MAX_FORWARD_CONNECTIONS = 64; const CONNECT_TIMEOUT = "10 seconds"; const REPLY_SUCCEEDED = 0; @@ -127,9 +136,13 @@ const isTunnelEndpoint = (tunnelUrl: string, port: number) => { }; /** Opens a connection to the destination; `ws` pauses its socket, so a slow page slows the tunnel. */ +/** Set by the environment's /api/preview/tunnel when it reached the port and nothing listens. */ +const PORT_REFUSED_HEADER = "x-t3-tunnel-port-refused"; + const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* ( tunnelUrl: string, port: number, + onPortRefused?: () => void, ) { if (isTunnelEndpoint(tunnelUrl, port)) { const endpoint = yield* NodeSocket.makeNet({ @@ -141,10 +154,18 @@ const dialDestination = Effect.fn("LoopbackTunnel.dialDestination")(function* ( const url = new URL(tunnelUrl); url.searchParams.set("port", String(port)); const tunnel = yield* Effect.acquireRelease( - Effect.sync(() => + Effect.sync(() => { // Closing before the handshake finishes emits an error after Socket's listeners are gone. - new NodeWS.WebSocket(url).on("error", () => undefined), - ), + const tunnel = new NodeWS.WebSocket(url).on("error", () => undefined); + if (onPortRefused) { + tunnel.on("unexpected-response", (_request, response) => { + if (response.headers[PORT_REFUSED_HEADER] !== undefined) onPortRefused(); + // Handled here, so `ws` leaves aborting the handshake to us. + tunnel.terminate(); + }); + } + return tunnel; + }), (tunnel) => Effect.sync(() => tunnel.close()), ); const socket = yield* Socket.fromWebSocket(Effect.succeed(tunnel), { @@ -224,6 +245,33 @@ export class LoopbackTunnelRouteError extends Schema.TaggedError()( + "LoopbackTunnelForwardError", + { environmentId: Schema.String, port: Schema.Number, cause: Schema.Defect() }, +) { + override get message(): string { + return `Failed to forward port ${this.port} of environment "${this.environmentId}".`; + } +} + +export class LoopbackTunnelUnavailableError extends Schema.TaggedError()( + "LoopbackTunnelUnavailableError", + { environmentId: Schema.String }, +) { + override get message(): string { + return `Environment "${this.environmentId}" can't be reached through the tunnel right now.`; + } +} + +export class LoopbackTunnelSameMachineError extends Schema.TaggedError()( + "LoopbackTunnelSameMachineError", + { environmentId: Schema.String, port: Schema.Number }, +) { + override get message(): string { + return `This environment runs on this computer, so localhost:${this.port} already reaches it.`; + } +} + export class LoopbackTunnel extends Context.Service< LoopbackTunnel, { @@ -237,6 +285,26 @@ export class LoopbackTunnel extends Context.Service< readonly requestId: string; readonly url: string | null; }) => Effect.Effect; + /** Listens on this machine's loopback, on the same port when it is free. */ + readonly forward: (input: { + readonly environmentId: EnvironmentId; + readonly remotePort: number; + }) => Effect.Effect< + DesktopPortForward, + LoopbackTunnelForwardError | LoopbackTunnelSameMachineError | LoopbackTunnelUnavailableError + >; + readonly stopForward: (input: { + readonly environmentId: EnvironmentId; + readonly remotePort: number; + }) => Effect.Effect; + readonly forwards: Effect.Effect>; + /** Whether the environment's loopback is this machine's, so forwarding would only loop. */ + readonly sharesLoopback: ( + environmentId: EnvironmentId, + ) => Effect.Effect; + readonly subscribeForwards: ( + listener: (forwards: ReadonlyArray) => Effect.Effect, + ) => Effect.Effect; } >()("@t3tools/desktop/preview/LoopbackTunnel") {} @@ -245,8 +313,17 @@ const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const platform = yield* HostProcess.Platform; const userId = yield* HostProcess.UserId; + const random = yield* SecureRandom.SecureRandom; const listenerScope = yield* Effect.scope; const routing = yield* Semaphore.make(1); + const forwarding = yield* Semaphore.make(1); + const forwarded = new Map< + string, + { readonly forward: DesktopPortForward; readonly scope: Scope.Closeable } + >(); + const forwardListeners = new Set< + (forwards: ReadonlyArray) => Effect.Effect + >(); const pending = new Map>(); const listenerPorts = new Map(); const routed = new WeakSet(); @@ -318,6 +395,163 @@ const make = Effect.gen(function* () { (effect) => Effect.ignoreCause(effect), ); + /** Serves one connection to a forwarded port; closes it when the environment is out of reach. */ + const serveForward = (environmentId: string, port: number) => { + let active = 0; + return Effect.fn("LoopbackTunnel.serveForward")( + function* (socket: Socket.Socket) { + // Acquiring the socket ties it to this scope, so returning early closes it. + const pull = yield* Socket.readerBytes(socket); + const writer = yield* socket.writer; + // Closed at once, so a page hammering the port can't queue tunnels and access requests. + if (active >= MAX_FORWARD_CONNECTIONS) return; + active++; + yield* Effect.addFinalizer(() => Effect.sync(() => active--)); + if (!(yield* isOwnConnection())) return; + const tunnelUrl = yield* requestAccess(environmentId); + if (tunnelUrl === null) return; + const destination = yield* dialDestination(tunnelUrl, port); + return yield* Effect.raceFirst( + pump(pull, destination.writer.writeAll), + pump(destination.pull, writer.writeAll), + ); + }, + Effect.scoped, + (effect) => Effect.ignoreCause(effect), + ); + }; + + /** + * Whether the environment's loopback is this machine's, by tunnelling a nonce to a local probe. + * A forward there would accept the environment's own dials and loop through the tunnel. + */ + const sharesLoopback = Effect.fn("LoopbackTunnel.sharesLoopback")(function* ( + environmentId: string, + ) { + const tunnelUrl = yield* requestAccess(environmentId); + // Without access the answer is unknown, not "another machine": a forward could loop later. + if (tunnelUrl === null) return yield* new LoopbackTunnelUnavailableError({ environmentId }); + return yield* probeLoopback(environmentId, tunnelUrl); + }); + + /** + * True only when the nonce reaches this machine's probe; false only on proof the environment + * was reached and nothing listens on the probe port there. Anything else is unknown. + */ + const probeLoopback = Effect.fn("LoopbackTunnel.probeLoopback")( + function* (environmentId: string, tunnelUrl: string) { + const unavailable = new LoopbackTunnelUnavailableError({ environmentId }); + const nonce = new TextEncoder().encode(yield* random.uuidV4()); + const arrived = yield* Deferred.make(); + const probe = yield* NodeSocketServer.make({ port: 0, host: "127.0.0.1" }); + yield* probe + .run( + Effect.fnUntraced( + function* (socket: Socket.Socket) { + const pull = yield* Socket.readerBytes(socket); + let received = Buffer.alloc(0); + while (received.length < nonce.length) { + received = Buffer.concat([received, ...(yield* pull)]); + } + if (received.subarray(0, nonce.length).equals(nonce)) { + yield* Deferred.succeed(arrived, undefined); + } + }, + Effect.scoped, + (effect) => Effect.ignoreCause(effect), + ), + ) + .pipe(Effect.forkScoped); + let portRefused = false; + const destination = yield* dialDestination( + tunnelUrl, + (probe.address as NetAddress.InetAddress).port, + () => { + portRefused = true; + }, + ).pipe(Effect.option); + if (Option.isNone(destination)) { + if (portRefused) return false; + return yield* unavailable; + } + yield* destination.value.writer.write(nonce); + // An answer or a close means a service on another machine took the connection. + const answer = yield* Effect.raceFirst( + Deferred.await(arrived).pipe(Effect.as(true)), + destination.value.pull.pipe(Effect.as(false)), + ).pipe(Effect.timeoutOption(PROBE_TIMEOUT)); + if (Option.isNone(answer)) return yield* unavailable; + return answer.value; + }, + Effect.scoped, + (effect, environmentId) => + effect.pipe( + Effect.mapError((error) => + error._tag === "LoopbackTunnelUnavailableError" + ? error + : new LoopbackTunnelUnavailableError({ environmentId }), + ), + ), + ); + + const forwardKey = (environmentId: string, port: number) => `${environmentId}:${port}`; + const currentForwards = () => [...forwarded.values()].map(({ forward }) => forward); + const announceForwards = Effect.suspend(() => { + const forwards = currentForwards(); + return Effect.forEach([...forwardListeners], (listener) => listener(forwards), { + discard: true, + }); + }); + + const forward: LoopbackTunnel["Service"]["forward"] = Effect.fn("LoopbackTunnel.forward")( + function* ({ environmentId, remotePort }) { + const existing = forwarded.get(forwardKey(environmentId, remotePort)); + if (existing) return existing.forward; + if (yield* sharesLoopback(environmentId)) { + 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 server = yield* bind(remotePort).pipe( + // Taken here, or privileged: any free port still reaches the environment's. + Effect.catch(() => bind(0)), + Effect.onError(() => Scope.close(scope, Exit.void)), + Effect.mapError( + (cause) => new LoopbackTunnelForwardError({ environmentId, port: remotePort, cause }), + ), + ); + yield* server.run(serveForward(environmentId, remotePort)).pipe(Effect.forkIn(scope)); + const forward = { + environmentId, + remotePort, + localPort: (server.address as NetAddress.InetAddress).port, + }; + forwarded.set(forwardKey(environmentId, remotePort), { forward, scope }); + yield* announceForwards; + return forward; + }, + forwarding.withPermits(1), + ); + + const stopForward: LoopbackTunnel["Service"]["stopForward"] = Effect.fn( + "LoopbackTunnel.stopForward", + )(function* ({ environmentId, remotePort }) { + const key = forwardKey(environmentId, remotePort); + const existing = forwarded.get(key); + if (!existing) return; + forwarded.delete(key); + // Closing the scope also ends the connections it carries. + yield* Scope.close(existing.scope, Exit.void); + yield* announceForwards; + }, forwarding.withPermits(1)); + + const subscribeForwards: LoopbackTunnel["Service"]["subscribeForwards"] = (listener) => + Effect.acquireRelease( + Effect.sync(() => forwardListeners.add(listener)), + () => Effect.sync(() => forwardListeners.delete(listener)), + ).pipe(Effect.asVoid); + const listen = Effect.fn("LoopbackTunnel.listen")(function* (environmentId: string) { const existing = listenerPorts.get(environmentId); if (existing !== undefined) return existing; @@ -375,7 +609,15 @@ const make = Effect.gen(function* () { return answer ? Deferred.succeed(answer, url).pipe(Effect.asVoid) : Effect.void; }; - return LoopbackTunnel.of({ route, resolveAccess }); + return LoopbackTunnel.of({ + route, + resolveAccess, + forward, + stopForward, + forwards: Effect.sync(currentForwards), + sharesLoopback, + subscribeForwards, + }); }); export const layer = Layer.effect(LoopbackTunnel, make); diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 2091ff3c7f8f2..2a01977302594 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -2415,10 +2415,18 @@ describe("PreviewManager", () => { Effect.gen(function* () { const host = yield* DesktopBrowserHost.DesktopBrowserHost; const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; + const windowThrottling = vi.fn<(enabled: boolean) => void>(); + const mainWebContents = Object.assign(makeTestHostWebContents(), { + setBackgroundThrottling: windowThrottling, + }); const contents = Object.assign( - makeTestPreviewWebContents(async () => { - throw new Error("unused"); - }, 42), + makeTestPreviewWebContents( + async () => { + throw new Error("unused"); + }, + 42, + mainWebContents, + ), { isDevToolsOpened: () => false, getUserAgent: () => "Electron", @@ -2431,6 +2439,11 @@ describe("PreviewManager", () => { ) as unknown as typeof contents.debugger.sendCommand; fromId.mockReturnValue(contents); const manager = yield* PreviewManager.PreviewManager; + yield* manager.setMainWindow({ + isDestroyed: () => false, + once: vi.fn(), + webContents: mainWebContents, + } as never); const capturing = yield* Queue.unbounded(); yield* manager.subscribeStateChanges((_tabId, state) => Queue.offer(capturing, state.capturing).pipe(Effect.asVoid), @@ -2463,9 +2476,14 @@ describe("PreviewManager", () => { }), ); expect(yield* Queue.take(capturing)).toBe(true); + // A locked or covered window paints a guest it had hidden only while unthrottled. + expect(windowThrottling.mock.calls).toEqual([[false]]); + expect(contents.setBackgroundThrottling.mock.calls).toEqual([[false]]); yield* manager.setCaptureDrawn("tab_1", true); screenshot.resolve({ data: "" }); expect(yield* Queue.take(capturing)).toBe(false); + expect(windowThrottling.mock.calls).toEqual([[false], [true]]); + expect(contents.setBackgroundThrottling.mock.calls).toEqual([[false], [true]]); }).pipe(Effect.provide(managerLayer())), ); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 1f28826bcc196..fbf70e12fd375 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -3623,6 +3623,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function { discard: true }, ); }); + // A hidden or locked window draws no frames, so a guest it hid stays unpainted until unthrottled. + const serverCaptureLeases = new Map(); const updateServerTabCapturing = Effect.fn("PreviewManager.updateServerTabCapturing")( function* (painting: { readonly key: { readonly threadId: string; readonly tabId: string }; @@ -3633,6 +3635,25 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function candidate.serverTab?.threadId === painting.key.threadId && candidate.serverTab.tabId === painting.key.tabId, ); + const key = `${painting.key.threadId}\u0000${painting.key.tabId}`; + const held = serverCaptureLeases.get(key); + if (!painting.active && held) { + serverCaptureLeases.delete(key); + yield* stopFrameCapture(held.tabId, held.lease); + } else if (painting.active && !held && tab) { + const lease = Symbol("server-capture"); + yield* startFrameCapture(tab.tabId, lease).pipe( + Effect.andThen( + Effect.sync(() => serverCaptureLeases.set(key, { tabId: tab.tabId, lease })), + ), + Effect.catch((error) => + Effect.logWarning("Failed to unthrottle a server tab for its capture.", { + tabId: tab.tabId, + error, + }), + ), + ); + } if (tab && tab.capturing !== painting.active) { yield* update(tab.tabId, { capturing: painting.active }); } diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 90c8740f83725..d66ca346aabb3 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -27,6 +27,7 @@ const clientSettings: ClientSettings = { browserDefaultAppearance: "dark", browserRecordingFrameRate: 60, browserLinkTarget: "app", + sideThreadOpenTarget: "main", browserAutoShowFloatingPreview: false, browserProfiles: [{ id: "work", name: "Work", kind: "persistent" }], browserDefaultProfileId: "work", diff --git a/apps/desktop/src/speech/AppleSpeech.test.ts b/apps/desktop/src/speech/AppleSpeech.test.ts new file mode 100644 index 0000000000000..0e831fab8d15b --- /dev/null +++ b/apps/desktop/src/speech/AppleSpeech.test.ts @@ -0,0 +1,176 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; +import * as AppleSpeech from "./AppleSpeech.ts"; + +const encoder = new TextEncoder(); +const text = (value: string) => (value ? Stream.make(encoder.encode(value)) : Stream.empty); + +type HelperOutput = { + stdout?: string; + stderr?: string; + exitCode: number; + exit?: Deferred.Deferred; +}; + +function makeProcess(result: HelperOutput) { + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: text(result.stdout ?? ""), + stderr: text(result.stderr ?? ""), + all: Stream.empty, + exitCode: (result.exit ? Deferred.await(result.exit) : Effect.void).pipe( + Effect.as(ChildProcessSpawner.ExitCode(result.exitCode)), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); +} + +function setup(result: HelperOutput, kernelRelease = "25.0.0") { + const commands: Array> = []; + const written: Uint8Array[] = []; + const layer = AppleSpeech.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(HostProcess.KernelRelease, kernelRelease), + Layer.succeed(DesktopEnvironment.DesktopEnvironment, { + platform: "darwin", + isPackaged: true, + resourcesPath: "/app/Resources", + path: { join: (...parts: string[]) => parts.join("/") }, + } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]), + FileSystem.layerNoop({ + exists: () => Effect.succeed(true), + makeTempFileScoped: () => Effect.succeed("/tmp/recording.wav"), + writeFile: (_path, data) => Effect.sync(() => void written.push(data)), + }), + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => { + const { command: executable, args } = command as unknown as { + command: string; + args: ReadonlyArray; + }; + commands.push([executable, ...args]); + return Effect.succeed(makeProcess(result)); + }), + ), + ), + ), + ); + return { commands, written, layer }; +} + +describe("AppleSpeech", () => { + it.effect.each([ + [ + { stdout: '{"value":"en-US"}', exitCode: 0 }, + { ok: true, value: "en-US" }, + ], + [ + { stderr: "Locale not supported: xx\n", exitCode: 2 }, + { ok: false, code: "unsupported-locale" }, + ], + [{ exitCode: 3 }, { ok: false, code: "unavailable" }], + [ + { stderr: "boom", exitCode: 1 }, + { ok: false, code: "failed" }, + ], + ] as const)("maps helper output %j to %j", ([output, expected]) => { + const { layer, commands } = setup(output); + return Effect.gen(function* () { + const speech = yield* AppleSpeech.AppleSpeech; + assert.deepEqual(yield* speech.prepare("en-US"), expected); + assert.deepEqual(commands, [ + ["/app/Resources/apple-speech/t3-apple-speech", "prepare", "en-US"], + ]); + }).pipe(Effect.provide(layer)); + }); + + it.effect("shares one helper between prepares that start while the first is running", () => + Effect.gen(function* () { + const exit = yield* Deferred.make(); + const { layer, commands } = setup({ stdout: '{"value":"en-US"}', exitCode: 0, exit }); + return yield* Effect.gen(function* () { + const speech = yield* AppleSpeech.AppleSpeech; + const first = yield* speech + .prepare("en-US") + .pipe(Effect.forkChild({ startImmediately: true })); + const second = yield* speech + .prepare("en-US") + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.succeed(exit, undefined); + assert.deepEqual(yield* Fiber.join(first), { ok: true, value: "en-US" }); + assert.deepEqual(yield* Fiber.join(second), { ok: true, value: "en-US" }); + assert.lengthOf(commands, 1); + }).pipe(Effect.provide(layer)); + }), + ); + + it.effect.each([ + ["25.0.0", 0, ["en-US", "fr-FR"], 1], + ["25.0.0", 3, [], 1], + ["25.0.0", 1, [], 2], + ["24.6.0", 0, [], 0], + ] as const)( + "on Darwin %s resolves locales on helper exit %i to %j with %i probe(s) across two calls", + ([release, exitCode, expected, probes]) => { + const { layer, commands } = setup({ stdout: '{"value":"en-US,fr-FR"}', exitCode }, release); + return Effect.gen(function* () { + const speech = yield* AppleSpeech.AppleSpeech; + assert.deepEqual(yield* speech.supportedLocales, expected); + assert.deepEqual(yield* speech.supportedLocales, expected); + assert.lengthOf(commands, probes); + }).pipe(Effect.provide(layer)); + }, + ); + + it.effect("transcribes Float32 PCM through a 16-bit WAV file", () => { + const { layer, commands, written } = setup({ stdout: '{"value":"hello"}', exitCode: 0 }); + // An unaligned Buffer view: Buffer.slice and subarray do not copy. + const pcm = new Uint8Array(17); + new DataView(pcm.buffer).setFloat32(1, 0, true); + new DataView(pcm.buffer).setFloat32(5, 1, true); + new DataView(pcm.buffer).setFloat32(9, -1, true); + new DataView(pcm.buffer).setFloat32(13, 2, true); + return Effect.gen(function* () { + const result = yield* (yield* AppleSpeech.AppleSpeech).transcribe( + "en-US", + Buffer.from(pcm.buffer).subarray(1), + ); + assert.deepEqual(result, { ok: true, value: "hello" }); + assert.deepEqual(commands, [ + [ + "/app/Resources/apple-speech/t3-apple-speech", + "transcribe", + "en-US", + "/tmp/recording.wav", + ], + ]); + const wav = new DataView(written[0]!.buffer); + assert.equal(new TextDecoder().decode(written[0]!.subarray(0, 4)), "RIFF"); + assert.equal(wav.getUint16(20, true), 1); + assert.equal(wav.getUint32(24, true), 16_000); + assert.equal(wav.getUint16(34, true), 16); + assert.equal(wav.getUint32(40, true), 8); + assert.deepEqual( + [0, 1, 2, 3].map((index) => wav.getInt16(44 + index * 2, true)), + [0, 32767, -32767, 32767], + ); + }).pipe(Effect.provide(layer)); + }); +}); diff --git a/apps/desktop/src/speech/AppleSpeech.ts b/apps/desktop/src/speech/AppleSpeech.ts new file mode 100644 index 0000000000000..a2f58d4f949a9 --- /dev/null +++ b/apps/desktop/src/speech/AppleSpeech.ts @@ -0,0 +1,191 @@ +import type { DesktopAppleSpeechResult } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Context from "effect/Context"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; + +import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; + +const SAMPLE_RATE = 16_000; +const MAX_PCM_BYTES = SAMPLE_RATE * Float32Array.BYTES_PER_ELEMENT * 5 * 60; +// Preparing a language for the first time downloads Apple's model. +const PREPARE_TIMEOUT = Duration.minutes(10); +const TRANSCRIBE_TIMEOUT = Duration.minutes(5); + +const decodeOutput = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ value: Schema.String })), +); + +/** 16 kHz mono Float32 PCM to a 16-bit WAV that AVAudioFile reads. */ +function encodeSpeechWav(pcmBytes: Uint8Array): Uint8Array { + // Float32Array needs a 4-byte-aligned offset; copy a view that is not (Buffer.slice is a view). + const aligned = + pcmBytes.byteOffset % Float32Array.BYTES_PER_ELEMENT === 0 + ? pcmBytes + : new Uint8Array(pcmBytes); + const samples = new Float32Array( + aligned.buffer, + aligned.byteOffset, + aligned.byteLength / Float32Array.BYTES_PER_ELEMENT, + ); + const wav = new Uint8Array(44 + samples.length * 2); + const view = new DataView(wav.buffer); + const ascii = (offset: number, text: string) => { + for (let index = 0; index < text.length; index++) + view.setUint8(offset + index, text.charCodeAt(index)); + }; + ascii(0, "RIFF"); + view.setUint32(4, 36 + samples.length * 2, true); + ascii(8, "WAVE"); + ascii(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, SAMPLE_RATE, true); + view.setUint32(28, SAMPLE_RATE * 2, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + ascii(36, "data"); + view.setUint32(40, samples.length * 2, true); + samples.forEach((sample, index) => { + const clamped = Number.isFinite(sample) ? Math.max(-1, Math.min(1, sample)) : 0; + view.setInt16(44 + index * 2, Math.round(clamped * 0x7fff), true); + }); + return wav; +} + +export class AppleSpeech extends Context.Service< + AppleSpeech, + { + readonly supportedLocales: Effect.Effect; + readonly prepare: (locale: string) => Effect.Effect; + readonly transcribe: ( + locale: string, + pcm: Uint8Array, + ) => Effect.Effect; + } +>()("@t3tools/desktop/speech/AppleSpeech") {} + +const unavailable: DesktopAppleSpeechResult = { ok: false, code: "unavailable" }; +const failed: DesktopAppleSpeechResult = { ok: false, code: "failed" }; + +export const layer = Layer.effect( + AppleSpeech, + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const hostEnvironment = yield* HostProcess.Environment; + const kernelRelease = yield* HostProcess.KernelRelease; + + let helper: string | undefined; + // macOS 26 is Darwin 25, the helper's minimum deployment target. + if (environment.platform === "darwin" && Number.parseInt(kernelRelease, 10) >= 25) { + const candidate = environment.isPackaged + ? environment.path.join(environment.resourcesPath, "apple-speech", "t3-apple-speech") + : environment.path.join( + environment.rootDir, + "native", + "apple-speech", + "build", + environment.processArch, + "t3-apple-speech", + ); + if (yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false))) + helper = candidate; + } + + const run = (args: readonly string[], timeout: Duration.Input) => + Effect.scoped( + Effect.gen(function* () { + if (helper === undefined) return unavailable; + const handle = yield* spawner.spawn( + ChildProcess.make(helper, args, { stdin: "ignore", env: hostEnvironment }), + ); + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + handle.stdout.pipe(Stream.decodeText(), Stream.mkString), + handle.stderr.pipe(Stream.decodeText(), Stream.mkString), + handle.exitCode, + ], + { concurrency: "unbounded" }, + ); + switch (Number(exitCode)) { + case 0: + return { ok: true, value: (yield* decodeOutput(stdout)).value } as const; + case 2: + return { ok: false, code: "unsupported-locale" } as const; + case 3: + return unavailable; + default: + yield* Effect.logWarning("Apple Speech helper failed", { exitCode, stderr }); + return failed; + } + }), + ).pipe( + // Leaving the scope kills a helper that outlives its timeout. + Effect.timeoutOrElse({ duration: timeout, orElse: () => Effect.succeed(failed) }), + Effect.catch((cause) => + Effect.logWarning("Apple Speech helper did not run", { cause }).pipe(Effect.as(failed)), + ), + ); + + // Only a definite answer is kept; a slow or failed probe is asked again next time. + let locales: readonly string[] | undefined; + const supportedLocales = Effect.suspend(() => + locales === undefined + ? run(["available"], Duration.seconds(10)).pipe( + Effect.map((result) => { + if (result.ok) locales = result.value.split(",").filter(Boolean); + else if (result.code === "unavailable") locales = []; + return locales ?? []; + }), + ) + : Effect.succeed(locales), + ); + + const pending = new Map>(); + const preparePermit = yield* Semaphore.make(1); + const getPendingPrepare = Effect.fn("AppleSpeech.getPendingPrepare")(function* ( + locale: string, + ) { + const existing = pending.get(locale); + if (existing) return existing; + const preparation = yield* Effect.cached( + run(["prepare", locale], PREPARE_TIMEOUT).pipe( + Effect.ensuring(Effect.sync(() => pending.delete(locale))), + ), + ); + pending.set(locale, preparation); + return preparation; + }, preparePermit.withPermits(1)); + + return AppleSpeech.of({ + supportedLocales, + prepare: Effect.fn("AppleSpeech.prepare")(function* (locale) { + return yield* yield* getPendingPrepare(locale); + }), + transcribe: Effect.fn("AppleSpeech.transcribe")(function* (locale, pcm) { + if ( + pcm.byteLength === 0 || + pcm.byteLength > MAX_PCM_BYTES || + pcm.byteLength % Float32Array.BYTES_PER_ELEMENT !== 0 + ) + return failed; + return yield* Effect.scoped( + Effect.gen(function* () { + const file = yield* fileSystem.makeTempFileScoped({ suffix: ".wav" }); + yield* fileSystem.writeFile(file, encodeSpeechWav(pcm)); + return yield* run(["transcribe", locale, file], TRANSCRIBE_TIMEOUT); + }), + ).pipe(Effect.orElseSucceed(() => failed)); + }), + }); + }), +); diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 33ed00a764738..535e1123d2911 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -79,6 +79,17 @@ const stableUpdateInfo = ( }; }; +// Subscribes before emitting, so the state the emit publishes is the one awaited, not a scheduler yield. +const nextPublishedState = (emit: () => void) => + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + const { changes } = yield* updates.subscribe; + const published = yield* Stream.runHead(changes).pipe(Effect.forkChild); + emit(); + yield* Fiber.join(published); + return yield* updates.getState; + }); + describe("DesktopUpdates", () => { it.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () => Effect.gen(function* () { @@ -1191,16 +1202,49 @@ describe("DesktopUpdates", () => { const updates = yield* DesktopUpdates.DesktopUpdates; yield* updates.configure; yield* updates.check("startup"); - harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" }); - yield* flushCallbacks; - - assert.equal((yield* updates.getState).channel, "nightly"); - assert.isNull((yield* updates.getState).availableVersion); + const state = yield* nextPublishedState(() => + harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" }), + ); + assert.equal(state.channel, "nightly"); + assert.isNull(state.availableVersion); + assert.equal(state.status, "error"); + assert.equal(state.errorContext, "check"); + assert.isTrue(state.canRetry); + assert.deepEqual(state.trackMismatch, { buildChannel: "latest" }); assert.deepEqual(harness.checkAllowedDowngrade, [false]); }), ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("reports a track mismatch when the feed offers no release at all", () => { + const harness = makeHarness({ savedChannel: "nightly" }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("startup"); + const state = yield* nextPublishedState(() => harness.emit("update-not-available")); + assert.equal(state.status, "error"); + assert.equal(state.errorContext, "check"); + assert.isTrue(state.canRetry); + assert.deepEqual(state.trackMismatch, { buildChannel: "latest" }); + + // A later failure has its own reason, so the mismatch must not stay attached to it. + const failed = yield* nextPublishedState(() => + harness.emit("error", new Error("background updater failure")), + ); + assert.isUndefined(failed.trackMismatch); + + const mismatched = yield* nextPublishedState(() => harness.emit("update-not-available")); + assert.isDefined(mismatched.trackMismatch); + yield* updates.check("menu"); + assert.equal((yield* updates.getState).status, "checking"); + assert.isUndefined((yield* updates.getState).trackMismatch); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("never offers an older Nightly to a Nightly build's own checks", () => { const harness = makeHarness({ appVersion: "1.2.4-nightly.20261027.1" }); @@ -1389,6 +1433,28 @@ describe("DesktopUpdates under a managed policy", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("does not name a blocked build track as the one to switch back to", () => { + const harness = makeHarness({ + appVersion: "1.2.4-nightly.20261027.1", + savedChannel: "latest", + policy: managed({ allowNightly: false, feedUrl: "https://updates.example.com/t3code" }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("startup"); + const state = yield* nextPublishedState(() => harness.emit("update-not-available")); + + assert.equal(state.channel, "latest"); + assert.equal(state.status, "error"); + assert.equal(state.errorContext, "check"); + assert.isUndefined(state.trackMismatch); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("does not report the channel as the only block when updates are off anyway", () => { const harness = makeHarness({ appVersion: "1.2.3-nightly.20261028.1", diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 775a9ff6b04ff..7976503d9e761 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -368,6 +368,13 @@ function getAutoUpdateDisabledReason(args: { return null; } +const trackLabel = (channel: DesktopUpdateChannel) => + channel === "nightly" ? "Nightly" : "Stable"; + +// Clients localize `trackMismatch`; this English text serves older renderers and remote reports. +const trackMismatchMessage = (build: DesktopUpdateChannel, saved: DesktopUpdateChannel) => + `This ${trackLabel(build)} build can't update from the ${trackLabel(saved)} track on its own. Switch the update track back to ${trackLabel(build)}, or use Review beside Update track to retry the switch to ${trackLabel(saved)}.`; + function isArm64HostRunningIntelBuild(runtimeInfo: DesktopRuntimeInfo): boolean { return runtimeInfo.hostArch === "arm64" && runtimeInfo.appArch === "x64"; } @@ -496,6 +503,26 @@ export const make = Effect.gen(function* () { ) : Option.none(); + // Without a release floor, a build on another track than its saved one never offers anything. + // A track the policy blocks is never named as the one to switch to. + const noOfferState = (state: DesktopUpdateState, checkedAt: string) => + Effect.map(Ref.get(releaseFloorRef), (floor) => { + const buildChannel = desktopUpdateChannelOf(environment.appVersion); + if (Option.isSome(floor) || buildChannel === state.channel) { + return reduceDesktopUpdateStateOnNoUpdate(state, checkedAt); + } + const blocked = channelBlockedReason(buildChannel); + if (Option.isSome(blocked)) { + return reduceDesktopUpdateStateOnCheckFailure(state, blocked.value, checkedAt); + } + return reduceDesktopUpdateStateOnCheckFailure( + state, + trackMismatchMessage(buildChannel, state.channel), + checkedAt, + { buildChannel }, + ); + }); + const resolveStateDisabledReason = (channel: DesktopUpdateChannel) => resolveDisabledReason.pipe(Effect.map(Option.orElse(() => channelBlockedReason(channel)))); @@ -1070,7 +1097,7 @@ export const make = Effect.gen(function* () { channel: state.channel, }); const checkedAt = yield* currentIsoTimestamp; - yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt)); + yield* setState(yield* noOfferState(state, checkedAt)); yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); return; } @@ -1117,7 +1144,7 @@ export const make = Effect.gen(function* () { const handleUpdateNotAvailable = Effect.gen(function* () { const checkedAt = yield* currentIsoTimestamp; const state = yield* Ref.get(updateStateRef); - yield* setState(reduceDesktopUpdateStateOnNoUpdate(state, checkedAt)); + yield* setState(yield* noOfferState(state, checkedAt)); yield* Ref.set(lastLoggedDownloadMilestoneRef, -1); yield* logUpdaterInfo("no updates available"); }).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable")); @@ -1145,7 +1172,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(activeAction)) { const checkedAt = yield* currentIsoTimestamp; - yield* updateState((current) => ({ + yield* updateState(({ trackMismatch: _trackMismatch, ...current }) => ({ ...current, status: "error", message: error.message, diff --git a/apps/desktop/src/updates/updateMachine.ts b/apps/desktop/src/updates/updateMachine.ts index 4d3852446b189..80751315657c0 100644 --- a/apps/desktop/src/updates/updateMachine.ts +++ b/apps/desktop/src/updates/updateMachine.ts @@ -11,6 +11,14 @@ function nextStatusAfterDownloadFailure( return currentState.availableVersion ? "available" : "error"; } +// A mismatch describes only the check that found it. +function withoutTrackMismatch({ + trackMismatch: _trackMismatch, + ...state +}: DesktopUpdateState): DesktopUpdateState { + return state; +} + function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean { return currentState.availableVersion !== null; } @@ -46,7 +54,7 @@ export function reduceDesktopUpdateStateOnCheckStart( ): DesktopUpdateState { const hasDownloadedUpdate = state.downloadedVersion !== null; return { - ...state, + ...withoutTrackMismatch(state), status: "checking", checkedAt, releaseNotes: hasDownloadedUpdate ? state.releaseNotes : [], @@ -62,10 +70,11 @@ export function reduceDesktopUpdateStateOnCheckFailure( state: DesktopUpdateState, message: string, checkedAt: string, + trackMismatch?: DesktopUpdateState["trackMismatch"], ): DesktopUpdateState { if (state.downloadedVersion !== null) { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", message: null, checkedAt, @@ -76,13 +85,14 @@ export function reduceDesktopUpdateStateOnCheckFailure( } return { - ...state, + ...withoutTrackMismatch(state), status: "error", message, checkedAt, downloadPercent: null, errorContext: "check", canRetry: true, + ...(trackMismatch === undefined ? {} : { trackMismatch }), }; } @@ -96,7 +106,7 @@ export function reduceDesktopUpdateStateOnUpdateAvailable( const isDownloadedVersion = state.downloadedVersion === version; const preserveReleaseNotes = isDownloadedVersion && releaseNotes.length === 0; return { - ...state, + ...withoutTrackMismatch(state), status: isDownloadedVersion ? "downloaded" : "available", availableVersion: version, downloadedVersion: isDownloadedVersion ? version : null, @@ -116,7 +126,7 @@ export function reduceDesktopUpdateStateOnNoUpdate( ): DesktopUpdateState { if (state.downloadedVersion !== null) { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", availableVersion: state.downloadedVersion, downloadPercent: 100, @@ -128,7 +138,7 @@ export function reduceDesktopUpdateStateOnNoUpdate( } return { - ...state, + ...withoutTrackMismatch(state), status: "up-to-date", availableVersion: null, downloadedVersion: null, @@ -146,7 +156,7 @@ export function reduceDesktopUpdateStateOnDownloadStart( state: DesktopUpdateState, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloading", downloadPercent: 0, message: null, @@ -160,7 +170,7 @@ export function reduceDesktopUpdateStateOnDownloadFailure( message: string, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: nextStatusAfterDownloadFailure(state), message, downloadPercent: null, @@ -174,7 +184,7 @@ export function reduceDesktopUpdateStateOnDownloadProgress( percent: number, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloading", downloadPercent: percent, message: null, @@ -188,7 +198,7 @@ export function reduceDesktopUpdateStateOnDownloadComplete( version: string, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", availableVersion: version, downloadedVersion: version, @@ -204,7 +214,7 @@ export function reduceDesktopUpdateStateOnInstallFailure( message: string, ): DesktopUpdateState { return { - ...state, + ...withoutTrackMismatch(state), status: "downloaded", message, errorContext: "install", diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 392208d5b54c9..543d8d245731b 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -4,6 +4,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; +import type { DesktopUpdateChannel } from "@t3tools/contracts"; import * as Electron from "electron"; import { msg } from "gt-i18n"; @@ -68,6 +69,11 @@ const runMainContentsCommand = Effect.fn("desktop.menu.runMainContentsCommand")( yield* desktopWindow.runMainContentsCommand(command); }); +const trackLabel = (channel: DesktopUpdateChannel) => + channel === "nightly" + ? m(msg("Nightly", { $context: "release track" })) + : m(msg("Stable", { $context: "release track" })); + const checkForUpdatesFromMenu = Effect.gen(function* () { const updates = yield* DesktopUpdates.DesktopUpdates; const electronDialog = yield* ElectronDialog.ElectronDialog; @@ -134,7 +140,18 @@ const checkForUpdatesFromMenu = Effect.gen(function* () { type: "warning", title: m(msg("Update check failed")), message: m(msg("Could not check for updates.")), - detail: updateState.message ?? m(msg("An unknown error occurred. Please try again later.")), + detail: + updateState.trackMismatch !== undefined + ? m( + msg( + "This {build} build can't update from the {saved} track on its own. Switch the update track back to {build}, or use Review beside Update track to retry the switch to {saved}.", + ), + { + build: trackLabel(updateState.trackMismatch.buildChannel), + saved: trackLabel(updateState.channel), + }, + ) + : (updateState.message ?? m(msg("An unknown error occurred. Please try again later."))), buttons: [m(msg("OK"))], }); } diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index 7f4a2507a736e..a563b6a4ee3a7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -22,10 +22,10 @@ import { layer as layerDesktopWslEnvironment, buildWslRuntimeInstallScript, makeIsAvailable, - buildWslRuntimeInvalidateScript, buildWslRuntimePruneScript, buildWslRuntimeProbeScript, parseResolvedPath, + parseT3Home, parseWslRuntimeRoot, windowsToWslPathImpl, } from "./DesktopWslEnvironment.ts"; @@ -96,10 +96,9 @@ describe("WSL runtime cache", () => { it.each([ [ "install", - (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64)), + (id: string) => buildWslRuntimeInstallScript("/runtime.tar.gz", id, "b".repeat(64), null), ], - ["prune", buildWslRuntimePruneScript], - ["invalidate", buildWslRuntimeInvalidateScript], + ["prune", (id: string) => buildWslRuntimePruneScript(id, null)], ] as const)("sanitizes cache ids in the %s script", (_, buildScript) => { const runtimeId = "1.2.3/x64; touch /tmp/nope"; const script = buildScript(runtimeId); @@ -139,11 +138,11 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed const archiveSha = readField(result.stdout, "archiveSha"); const runtimeId = `sha256-${archiveSha}`; // WSL does not inherit HOME; embed the fixture's override in the script. - const installScript = (archive = archivePath, sha = archiveSha) => + const installScript = (archive = archivePath, sha = archiveSha, t3Home: string | null = null) => [ `HOME=${sh(`${work}/home`)}`, "export HOME", - buildWslRuntimeInstallScript(archive, runtimeId, sha), + buildWslRuntimeInstallScript(archive, runtimeId, sha, t3Home), ].join("\n"); return { work, @@ -154,7 +153,8 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed runtimeRoot: `${work}/home/.t3/wsl-runtime/${runtimeId}`, serverEntry: `${work}/home/.t3/wsl-runtime/${runtimeId}/t3`, installScript, - install: (archive?: string, sha?: string) => runShell(installScript(archive, sha)), + install: (archive?: string, sha?: string, t3Home?: string | null) => + runShell(installScript(archive, sha, t3Home)), }; }; @@ -200,6 +200,24 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed expect(provider.stdout).toBe("linux-node-provider\n"); }); + it("stages the runtime under the login shell's T3CODE_HOME and reports it to the launcher", () => { + const fixture = createFixture(); + const t3Home = `${fixture.work}/home/.config/t3 home`; + const install = fixture.install(undefined, undefined, t3Home); + expect(install.status, install.stderr).toBe(0); + expect(parseWslRuntimeRoot(install.stdout)).toBe(`${t3Home}/wsl-runtime/${fixture.runtimeId}`); + expect(runShell(`test ! -e ${sh(`${fixture.work}/home/.t3`)}`).status).toBe(0); + + const probe = runShell( + [ + `bash() { ( export T3CODE_HOME=${sh(t3Home)}; eval "$2" ); }`, + buildWslRuntimeProbeScript(), + ].join("\n"), + ); + expect(probe.status, probe.stderr).toBe(0); + expect(parseT3Home(probe.stdout)).toBe(t3Home); + }); + it("keeps the inherited PATH when bash is unavailable", () => { const fixture = createFixture(); expect(fixture.install().status).toBe(0); @@ -382,7 +400,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed `sh ${sh(`${fixture.work}/select.sh`)}`, `HOME=${sh(`${fixture.work}/home`)}`, "export HOME", - buildWslRuntimePruneScript("sha256-current"), + buildWslRuntimePruneScript("sha256-current", null), `test -d ${sh(fixture.runtimeRoot)}`, ].join("\n"), ); @@ -463,11 +481,15 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed const translated = yield* wsl.windowsToWslPath("Ubuntu", fixture.archivePath); expect(translated._tag).toBe("None"); - const prepared = yield* wsl.prepareRuntime("Ubuntu", { - windowsPath: fixture.archivePath, - runtimeId: fixture.runtimeId, - sha256: fixture.archiveSha, - }); + const prepared = yield* wsl.prepareRuntime( + "Ubuntu", + { + windowsPath: fixture.archivePath, + runtimeId: fixture.runtimeId, + sha256: fixture.archiveSha, + }, + null, + ); expect(prepared).toEqual({ ok: true, linuxAppRoot: fixture.runtimeRoot }); const version = runShell(`${sh(fixture.serverEntry)} --version`); @@ -500,7 +522,7 @@ describe.skipIf(posixShellRunner === null)("WSL runtime install script (executed holdInstallLock('"$runtime_parent/.sha256-locked.install.lock"'), `HOME="$home"`, "export HOME", - buildWslRuntimePruneScript("sha256-current"), + buildWslRuntimePruneScript("sha256-current", null), 'test -d "$runtime_parent/sha256-current"', 'test -d "$runtime_parent/sha256-previous"', 'test -d "$runtime_parent/sha256-active"', diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index 5ba7d3794fad1..f1d2fccde537b 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -60,6 +60,7 @@ export type EnsureWslNodePtyResult = readonly ok: true; readonly nodePath: string; readonly resolvedPath: string; + readonly t3Home: string | null; } | { readonly ok: false; @@ -72,6 +73,7 @@ export type ProbeWslRuntimeResult = | { readonly ok: true; readonly resolvedPath: string; + readonly t3Home: string | null; } | { readonly ok: false; @@ -104,12 +106,17 @@ export class DesktopWslEnvironment extends Context.Service< readonly getUserHome: (distro: string | null) => Effect.Effect>; // Use the distro IP to avoid unreliable wslhost localhost forwarding. readonly getDistroIp: (distro: string | null) => Effect.Effect>; + // A null t3Home means the distro's login shell has no absolute T3CODE_HOME, so ~/.t3 applies. readonly prepareRuntime: ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, ) => Effect.Effect; - readonly pruneRuntimes: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly invalidateRuntime: (distro: string | null, runtimeId: string) => Effect.Effect; + readonly pruneRuntimes: ( + distro: string | null, + runtimeId: string, + t3Home: string | null, + ) => Effect.Effect; readonly probeRuntime: (distro: string | null) => Effect.Effect; readonly ensureNodePty: ( distro: string | null, @@ -264,16 +271,22 @@ const WSL_RUNTIME_SELECTION_GRACE_MINUTES = 5; const sanitizeWslRuntimeId = (value: string): string => value.replace(/[^A-Za-z0-9._-]/g, "_"); +const runtimeParentAssignment = (t3Home: string | null): string => + t3Home === null + ? 'runtime_parent="$HOME/.t3/wsl-runtime"' + : `runtime_parent=${shellQuote(`${t3Home}/wsl-runtime`)}`; + // A null archive path asks for a staging directory to copy the archive into, unless the cache is ready. export const buildWslRuntimeInstallScript = ( linuxArchivePath: string | null, runtimeId: string, archiveSha256: string, + t3Home: string | null, ): string => { const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); const readyCheck = [ "set -eu", - 'runtime_parent="$HOME/.t3/wsl-runtime"', + runtimeParentAssignment(t3Home), `runtime_root="$runtime_parent/${safeRuntimeId}"`, `ready_marker="$runtime_root/${WSL_RUNTIME_READY_MARKER}"`, "runtime_entry_runs() {", @@ -369,11 +382,11 @@ export const buildWslRuntimeInstallScript = ( // Two hours exceeds cold-install time while bounding orphan retention. const ORPHANED_RUNTIME_SCRATCH_MAX_AGE_MINUTES = 120; -export const buildWslRuntimePruneScript = (runtimeId: string): string => { +export const buildWslRuntimePruneScript = (runtimeId: string, t3Home: string | null): string => { const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); return [ "set -eu", - 'runtime_parent="$HOME/.t3/wsl-runtime"', + runtimeParentAssignment(t3Home), `current_runtime="$runtime_parent/${safeRuntimeId}"`, '[ -d "$runtime_parent" ] || exit 0', // Serialize pruning so backends cannot select and delete different previous caches. @@ -419,15 +432,6 @@ export const buildWslRuntimePruneScript = (runtimeId: string): string => { ].join("\n"); }; -// Invalidate trees that pass install checks but fail launch probes, or each launch reuses the broken cache. -export const buildWslRuntimeInvalidateScript = (runtimeId: string): string => { - const safeRuntimeId = sanitizeWslRuntimeId(runtimeId); - return [ - "set -eu", - `rm -f "$HOME/.t3/wsl-runtime/${safeRuntimeId}/${WSL_RUNTIME_READY_MARKER}"`, - ].join("\n"); -}; - const parseAbsolutePathField = (stdout: string, field: string): string | null => { const prefix = `${field}:`; const line = stdout.split("\n").find((candidate) => candidate.startsWith(prefix)); @@ -448,12 +452,15 @@ const formatNodePtyProbeFailureReason = (exitCode: number): string | null => // Capture login-shell PATH because the server launches provider CLIs by name. const RESOLVED_PATH_LINE = `printf 'resolvedPath:%s\\n' "$PATH"`; +// wsl.exe --exec skips the profile, so the server only sees a profile-exported T3CODE_HOME if passed on. +const T3_HOME_LINE = `printf 't3Home:%s\\n' "\${T3CODE_HOME:-}"`; const NODE_PTY_PROBE_SCRIPT = ( linuxServerDir: string, ) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)" printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)" ${RESOLVED_PATH_LINE} +${T3_HOME_LINE} cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1 // The WSL Node can't read inside app.asar, so confirm what the server needs is // unpacked on the real filesystem before reporting the backend healthy. Exit 3 @@ -482,7 +489,7 @@ NODE`; // Resolve version-managed Node for providers without making runtime readiness depend on it. // The install script already ran the staged t3, so running it again here only adds a second startup. export const buildWslRuntimeProbeScript = () => - `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`; + `bash -lc ${shellQuote(`${buildWslNodeEnvPreamble()}${RESOLVED_PATH_LINE}\n${T3_HOME_LINE}`)} 2>/dev/null || ${RESOLVED_PATH_LINE}`; const TOOLCHAIN_CHECK_SCRIPT = [ "for tool in node make g++ python3; do", @@ -553,6 +560,10 @@ export const parseResolvedPath = (stdout: string): string | null => { return resolvedPath.length > 0 ? resolvedPath : null; }; +// Relative values are ignored: the runtime scripts and the server would resolve them from different cwds. +export const parseT3Home = (stdout: string): string | null => + parseAbsolutePathField(stdout, "t3Home"); + const formatMissingToolsReason = ( report: ToolchainReport, requiredRange: string | null, @@ -614,7 +625,7 @@ const probeWslRuntimeImpl = Effect.fn("DesktopWslEnvironment.probeWslRuntimeImpl reason: "WSL login-shell PATH could not be resolved during backend preflight.", } as const; } - return { ok: true, resolvedPath } as const; + return { ok: true, resolvedPath, t3Home: parseT3Home(probe.stdout) } as const; }); const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(function* ( @@ -634,6 +645,7 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f ); const nodePath = parseNodePath(probe.stdout); const resolvedPath = parseResolvedPath(probe.stdout); + const t3Home = parseT3Home(probe.stdout); const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure); if (transportFailureReason !== null) { @@ -700,7 +712,7 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f fatal: true, } as const; } - return { ok: true, nodePath, resolvedPath } as const; + return { ok: true, nodePath, resolvedPath, t3Home } as const; } if (options.allowBuild !== true) { @@ -773,7 +785,7 @@ const ensureNodePtyImpl = Effect.fn("DesktopWslEnvironment.ensureNodePtyImpl")(f retryLimit: BUILD_TRANSPORT_RETRY_LIMIT, } as const; } - if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const; + if (build.exitCode === 0) return { ok: true, nodePath, resolvedPath, t3Home } as const; const trimmedTail = `${build.stdout}${build.stderr}`.trim().slice(-500); return { ok: false, @@ -789,11 +801,12 @@ type WslRuntimeInstallOutcome = const runWslRuntimeInstall = Effect.fn("desktop.wsl.runRuntimeInstall")(function* ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, linuxArchivePath: string | null, ): Effect.fn.Return { const install = yield* runWslShell( distro, - buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256), + buildWslRuntimeInstallScript(linuxArchivePath, archive.runtimeId, archive.sha256, t3Home), RUNTIME_INSTALL_TIMEOUT, { resolveNode: false }, ); @@ -832,9 +845,10 @@ const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromH function* ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, archiveBytes: Stream.Stream, ): Effect.fn.Return { - const staged = yield* runWslRuntimeInstall(distro, archive, null); + const staged = yield* runWslRuntimeInstall(distro, archive, t3Home, null); if (!staged.ok || parseWslRuntimeRoot(staged.stdout) !== null) { return toPrepareWslRuntimeResult(staged); } @@ -875,7 +889,7 @@ const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromH } as const; } return toPrepareWslRuntimeResult( - yield* runWslRuntimeInstall(distro, archive, linuxArchivePath), + yield* runWslRuntimeInstall(distro, archive, t3Home, linuxArchivePath), ); }); @@ -892,6 +906,7 @@ const installWslRuntimeFromHostCopy = Effect.fn("desktop.wsl.installRuntimeFromH const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(function* ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, windowsToWslPath: ( distro: string | null, windowsPath: string, @@ -907,21 +922,23 @@ const prepareWslRuntimeImpl = Effect.fn("desktop.wsl.prepareRuntimeImpl")(functi return yield* installWslRuntimeFromHostCopy( distro, archive, + t3Home, fileSystem.stream(archive.windowsPath), ); } return toPrepareWslRuntimeResult( - yield* runWslRuntimeInstall(distro, archive, linuxArchivePath.value), + yield* runWslRuntimeInstall(distro, archive, t3Home, linuxArchivePath.value), ); }); const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function* ( distro: string | null, runtimeId: string, + t3Home: string | null, ): Effect.fn.Return { const result = yield* runWslShell( distro, - buildWslRuntimePruneScript(runtimeId), + buildWslRuntimePruneScript(runtimeId, t3Home), RUNTIME_PRUNE_TIMEOUT, { resolveNode: false }, ); @@ -935,26 +952,6 @@ const pruneWslRuntimesImpl = Effect.fn("desktop.wsl.pruneRuntimesImpl")(function }); }); -const invalidateWslRuntimeImpl = Effect.fn("desktop.wsl.invalidateRuntimeImpl")(function* ( - distro: string | null, - runtimeId: string, -): Effect.fn.Return { - const result = yield* runWslShell( - distro, - buildWslRuntimeInvalidateScript(runtimeId), - RUNTIME_INVALIDATE_TIMEOUT, - { resolveNode: false }, - ); - if (result.transportFailure === null && result.exitCode === 0) return; - - const detail = `${result.stdout}${result.stderr}`.trim().slice(-500); - yield* Effect.logWarning("Could not invalidate the staged WSL runtime cache.", { - distro, - runtimeId, - detail: detail || `exit ${result.exitCode}`, - }); -}); - const probeWslDistros: Effect.Effect< readonly WslDistro[], DesktopWslDistroListError, @@ -1154,9 +1151,13 @@ export interface DesktopWslEnvironmentTestStub { readonly prepareRuntime?: ( distro: string | null, archive: WslRuntimeArchive, + t3Home: string | null, ) => PrepareWslRuntimeResult; - readonly pruneRuntimes?: (distro: string | null, runtimeId: string) => Effect.Effect; - readonly invalidateRuntime?: (distro: string | null, runtimeId: string) => Effect.Effect; + readonly pruneRuntimes?: ( + distro: string | null, + runtimeId: string, + t3Home: string | null, + ) => Effect.Effect; readonly probeRuntime?: (distro: string | null) => ProbeWslRuntimeResult; readonly ensureNodePty?: ( distro: string | null, @@ -1188,20 +1189,19 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => { getDistroIp: Effect.fn("DesktopWslEnvironment.getDistroIp")(function (distro) { return Effect.succeed(stub.getDistroIp?.(distro) ?? Option.none()); }), - prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")(function (distro, archive) { - return Effect.succeed( - stub.prepareRuntime?.(distro, archive) ?? { - ok: false, - reason: "prepareRuntime stub not configured", - }, - ); - }), - pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")(function (distro, runtimeId) { - return stub.pruneRuntimes?.(distro, runtimeId) ?? Effect.void; - }), - invalidateRuntime: Effect.fn("DesktopWslEnvironment.invalidateRuntime")( - function (distro, runtimeId) { - return stub.invalidateRuntime?.(distro, runtimeId) ?? Effect.void; + prepareRuntime: Effect.fn("DesktopWslEnvironment.prepareRuntime")( + function (distro, archive, t3Home) { + return Effect.succeed( + stub.prepareRuntime?.(distro, archive, t3Home) ?? { + ok: false, + reason: "prepareRuntime stub not configured", + }, + ); + }, + ), + pruneRuntimes: Effect.fn("DesktopWslEnvironment.pruneRuntimes")( + function (distro, runtimeId, t3Home) { + return stub.pruneRuntimes?.(distro, runtimeId, t3Home) ?? Effect.void; }, ), probeRuntime: Effect.fn("DesktopWslEnvironment.probeRuntime")(function (distro) { @@ -1209,6 +1209,7 @@ export const layerTest = (stub: DesktopWslEnvironmentTestStub = {}) => { stub.probeRuntime?.(distro) ?? { ok: true, resolvedPath: "/usr/bin:/bin", + t3Home: null, }, ); }), @@ -1288,18 +1289,15 @@ export const layer = Layer.effect( windowsToWslPath, getUserHome, getDistroIp, - prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive) { + prepareRuntime: Effect.fn("desktop.wsl.prepareRuntime")(function (distro, archive, t3Home) { return provideSpawner( - prepareWslRuntimeImpl(distro, archive, windowsToWslPath).pipe( + prepareWslRuntimeImpl(distro, archive, t3Home, windowsToWslPath).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), ), ); }), - pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId) { - return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId)); - }), - invalidateRuntime: Effect.fn("desktop.wsl.invalidateRuntime")(function (distro, runtimeId) { - return provideSpawner(invalidateWslRuntimeImpl(distro, runtimeId)); + pruneRuntimes: Effect.fn("desktop.wsl.pruneRuntimes")(function (distro, runtimeId, t3Home) { + return provideSpawner(pruneWslRuntimesImpl(distro, runtimeId, t3Home)); }), probeRuntime: Effect.fn("desktop.wsl.probeRuntime")(function (distro) { return provideSpawner(probeWslRuntimeImpl(distro)); diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index f4e04317e4924..6ded8e851ddbb 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -31,7 +31,7 @@ export default defineConfig({ tasks: { build: { command: - "node scripts/build-browser-secret.mjs && node scripts/build-preview-annotation-css.mjs && vp pack", + "node scripts/build-browser-secret.mjs && node scripts/build-apple-speech.mjs && node scripts/build-preview-annotation-css.mjs && vp pack", dependsOn: ["t3#build"], cache: false, }, @@ -43,13 +43,13 @@ export default defineConfig({ }, dev: { command: - "node scripts/build-browser-secret.mjs && node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch", + "node scripts/build-browser-secret.mjs && node scripts/build-apple-speech.mjs && node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch", dependsOn: ["t3#build"], cache: false, }, "dev:bundle": { command: - "node scripts/build-browser-secret.mjs && node scripts/build-preview-annotation-css.mjs && vp pack --watch", + "node scripts/build-browser-secret.mjs && node scripts/build-apple-speech.mjs && node scripts/build-preview-annotation-css.mjs && vp pack --watch", cache: false, }, "dev:electron": { diff --git a/apps/marketing/src/i18n/zh.ts b/apps/marketing/src/i18n/zh.ts index dd57a9414be7b..09abf6efd0a8e 100644 --- a/apps/marketing/src/i18n/zh.ts +++ b/apps/marketing/src/i18n/zh.ts @@ -11,7 +11,7 @@ export const zh: Messages = { starsLabel: "在 GitHub 上为 T3 Code 加星标,已有 {stars} 个星标", githubStars: "{stars} GitHub 星标", language: "语言", - mitLicensed: "MIT 许可", + mitLicensed: "MIT 许可证", iosApp: "iOS 应用", androidApp: "Android 应用", terms: "条款", @@ -29,7 +29,7 @@ export const zh: Messages = { downloadForLinux: "下载 Linux 版", downloadForIos: "下载 iOS 版", downloadForAndroid: "下载 Android 版", - sourceLink: "来偷我们的代码(合法的)", + sourceLink: "来偷我们的代码(合法地)", alsoOnPhone: "手机上也能用:", screenshotAlt: "T3 Code 在同一个线程中运行 Claude、Codex、Muse 和 Gemini 子智能体", endorsementsTitle: "超过 {users} 名开发者觉得还行", diff --git a/apps/mobile/fingerprint.config.js b/apps/mobile/fingerprint.config.js index 7e684229320a2..e62be49dd5a33 100644 --- a/apps/mobile/fingerprint.config.js +++ b/apps/mobile/fingerprint.config.js @@ -14,5 +14,13 @@ if (!majorVersion) { module.exports = { nativeModuleSourceType: "files", - extraSources: [{ type: "contents", id: "appMajorVersion", contents: majorVersion }], + extraSources: [ + { type: "contents", id: "appMajorVersion", contents: majorVersion }, + // Expo skips symlinks when hashing local modules. + { + type: "file", + filePath: "../../native/apple-speech/AppleSpeechEngine.swift", + reasons: ["appleSpeech"], + }, + ], }; diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3SecretInputModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3SecretInputModule.kt index 4ac5b47a42f32..b6c4cbad80d35 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3SecretInputModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3SecretInputModule.kt @@ -14,6 +14,7 @@ import android.view.KeyEvent import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputMethodManager import android.widget.EditText import expo.modules.kotlin.AppContext import expo.modules.kotlin.modules.Module @@ -44,7 +45,13 @@ class T3SecretInputModule : Module() { } Prop("editable") { view: T3SecretInputView, value: Boolean -> view.input.isEnabled = value } Prop("revealed") { view: T3SecretInputView, value: Boolean -> view.setRevealed(value) } + Prop("returnKey") { view: T3SecretInputView, value: String -> + view.input.imeOptions = + if (value == "next") EditorInfo.IME_ACTION_NEXT else EditorInfo.IME_ACTION_DONE + } Events("onChangeText", "onSubmit") + + AsyncFunction("focus") { view: T3SecretInputView -> view.focusInput() } } } } @@ -103,7 +110,12 @@ class T3SecretInputView(context: Context, appContext: AppContext) : ExpoView(con } ) input.setOnEditorActionListener { _, actionId, event -> - if (actionId == EditorInfo.IME_ACTION_DONE || event?.keyCode == KeyEvent.KEYCODE_ENTER) { + // Next is submitted too: JS moves focus to the following field. + if ( + actionId == EditorInfo.IME_ACTION_DONE || + actionId == EditorInfo.IME_ACTION_NEXT || + event?.keyCode == KeyEvent.KEYCODE_ENTER + ) { // Hardware Enter reports IME_NULL on Android 13 and earlier, and both key down and key up. if (event == null || event.action == KeyEvent.ACTION_DOWN) { onSubmit(mapOf("value" to input.text.toString())) @@ -147,6 +159,12 @@ class T3SecretInputView(context: Context, appContext: AppContext) : ExpoView(con applyingValue = false } + fun focusInput() { + input.requestFocus() + val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT) + } + fun setCursorColor(color: Int) { input.highlightColor = Color.argb(0x52, Color.red(color), Color.green(color), Color.blue(color)) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index 2f1e4d9fd4a43..d86861018c77d 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -221,6 +221,7 @@ internal class ReviewDiffCanvasDrawing(context: Context) { private var measuredContentWidth = 0 private var asciiCharacterWidth = 0f private var asciiFixedPitch = false + private var wordDiffLefts = FloatArray(0) fun tokensChangeWidth( previous: Map>, @@ -332,14 +333,58 @@ internal class ReviewDiffCanvasDrawing(context: Context) { configureMonospacePaint(theme.hunkText, style.hunkFontSizePx, style.hunkFontWeight) return textPaint.measureText(row.text.ifEmpty { row.content }) } - val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens - var width = 0f - // Match drawCode's run boundaries and fonts, including fallback glyphs and tabs. - for (run in runs) { - configureCodePaint(run.color ?: theme.text, run.fontStyle, style) - width += textPaint.measureText(run.content) + val lines = CodeWrapLayout.NONE.lines(row) + return forEachCodePiece(row, tokens, style, lines) { text, start, end, _, _, _, _ -> + textPaint.measureText(text, start, end) } - return width + } + + /** Row width, highlights and drawCode share these drawText pieces so their positions agree. */ + private inline fun forEachCodePiece( + row: DiffRow, + tokens: List?, + style: DiffStyle, + lines: CodeLines, + piece: ( + text: String, + start: Int, + end: Int, + tokenStart: Int, + x: Float, + line: Int, + note: Boolean + ) -> Float + ): Float { + val noteStart = row.noteStart ?: Int.MAX_VALUE + var line = 0 + var x = 0f + var tokenStart = 0 + val runCount = if (tokens.isNullOrEmpty()) 1 else tokens.size + for (index in 0 until runCount) { + val run = tokens?.getOrNull(index) + val text = run?.content ?: row.content + var start = 0 + while (start < text.length) { + while (line + 1 < lines.starts.size && lines.starts[line + 1] <= tokenStart + start) { + line += 1 + x = 0f + } + val note = tokenStart + start >= noteStart + var end = min(text.length, lines.end(line, Int.MAX_VALUE) - tokenStart) + if (!note) end = min(end, noteStart - tokenStart) + if (start == 0 || tokenStart + start == noteStart) { + configureCodePaint( + if (note) theme.warningText else run?.color ?: theme.text, + run?.fontStyle ?: 0, + style, + ) + } + x += piece(text, start, end, tokenStart, x, line, note) + start = end + } + tokenStart += text.length + } + return x } fun lineNumberColor(change: String): Int = when (change) { @@ -368,34 +413,55 @@ internal class ReviewDiffCanvasDrawing(context: Context) { fun drawWordDiffRanges( canvas: Canvas, row: DiffRow, + tokens: List?, codeX: Float, top: Int, bottom: Int, - lines: CodeLines + lines: CodeLines, + style: DiffStyle ) { - if (lines.nativeLayout != null) return - if (row.wordDiffRanges.isEmpty() || (row.change != "add" && row.change != "delete")) return + val changed = row.change == "add" || row.change == "delete" + if (lines.nativeLayout != null || row.wordDiffRanges.isEmpty() || !changed) return val color = if (row.change == "add") theme.addBar else theme.deleteBar backgroundPaint.color = withAlpha(color, 71) - val characterWidth = textPaint.measureText("M") + configureCodePaint(theme.text, 0, style) val fontHeight = textPaint.fontMetrics.run { descent - ascent } val highlightHeight = max(4f * density, min(bottom - top - 4f * density, fontHeight)) val highlightTop = (top + bottom - highlightHeight) / 2f - row.wordDiffRanges.forEach { range -> - lines.starts.forEachIndexed { line, lineStart -> - val start = max(range.start, lineStart) - val end = min(range.end, lines.end(line, Int.MAX_VALUE)) - if (end <= start) return@forEachIndexed - val left = codeX + (start - lineStart) * characterWidth - val right = max(left + 2f * density, left + (end - start) * characterWidth) - val lineTop = highlightTop + line * lines.height - canvas.drawRoundRect( - RectF(left, lineTop, right, lineTop + highlightHeight), - 3f * density, - 3f * density, - backgroundPaint, - ) + if (wordDiffLefts.size < row.wordDiffRanges.size) { + wordDiffLefts = FloatArray(row.wordDiffRanges.size) + } + val lefts = wordDiffLefts + val lastEnd = row.wordDiffRanges.maxOf { it.end } + forEachCodePiece(row, tokens, style, lines) { text, start, end, tokenStart, x, line, _ -> + val pieceX = codeX + x + val advance = textPaint.measureText(text, start, end) + + // Inside a piece an edge keeps its kerning and clusters, as drawText shapes the whole piece; + // the piece's end is where drawCode starts the next one. + fun edge(at: Int) = if (at == end) { + pieceX + advance + } else { + pieceX + textPaint.getRunAdvance(text, start, end, start, end, false, at) + } + row.wordDiffRanges.forEachIndexed { index, range -> + val left = max(range.start, lines.starts[line]) - tokenStart + val right = min(range.end, lines.end(line, Int.MAX_VALUE)) - tokenStart + if (right <= left) return@forEachIndexed + if (left in start until end) lefts[index] = edge(left) + if (right in start + 1..end) { + val lineTop = highlightTop + line * lines.height + val rightX = max(lefts[index] + 2f * density, edge(right)) + canvas.drawRoundRect( + RectF(lefts[index], lineTop, rightX, lineTop + highlightHeight), + 3f * density, + 3f * density, + backgroundPaint, + ) + } } + if (tokenStart + end >= lastEnd) return + advance } } @@ -417,35 +483,19 @@ internal class ReviewDiffCanvasDrawing(context: Context) { canvas.restore() return } - val runs = if (tokens.isNullOrEmpty()) listOf(DiffToken(row.content, null, 0)) else tokens - var line = 0 - var x = codeX - var column = 0 - splitAtNote(runs, row.noteStart).forEach { (run, note) -> - configureCodePaint( - if (note) theme.warningText else run.color ?: theme.text, - run.fontStyle, - style, - ) - var start = 0 - while (start < run.content.length) { - while (line + 1 < lines.starts.size && lines.starts[line + 1] <= column + start) { - line += 1 - x = codeX - } - val end = min(run.content.length, lines.end(line, Int.MAX_VALUE) - column) - val lineBaseline = baseline + line * lines.height - if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top && - lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom - ) { - val segmentWidth = textPaint.measureText(run.content, start, end) - fillNote(canvas, note, x, x + segmentWidth, lineBaseline) - canvas.drawText(run.content, start, end, x, lineBaseline, textPaint) - x += segmentWidth - } - start = end + forEachCodePiece(row, tokens, style, lines) { text, start, end, _, x, line, note -> + val lineBaseline = baseline + line * lines.height + if (lineBaseline + textPaint.fontMetrics.descent >= canvas.clipBounds.top && + lineBaseline + textPaint.fontMetrics.ascent <= canvas.clipBounds.bottom + ) { + val left = codeX + x + val segmentWidth = textPaint.measureText(text, start, end) + fillNote(canvas, note, left, left + segmentWidth, lineBaseline) + canvas.drawText(text, start, end, left, lineBaseline, textPaint) + segmentWidth + } else { + 0f } - column += run.content.length } } @@ -553,24 +603,3 @@ private object ReviewDiffTypefaces { else -> regular } } - -/** Splits color runs where a cut line's note starts; the flag marks the note's runs. */ -private fun splitAtNote(runs: List, noteStart: Int?): List> { - if (noteStart == null) return runs.map { it to false } - return buildList { - var offset = 0 - for (run in runs) { - val end = offset + run.content.length - when { - end <= noteStart -> add(run to false) - offset >= noteStart -> add(run to true) - else -> { - val cut = noteStart - offset - add(run.copy(content = run.content.substring(0, cut)) to false) - add(run.copy(content = run.content.substring(cut)) to true) - } - } - offset = end - } - } -} diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 91bb6719ed8fa..8b0a84a952caf 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -1329,9 +1329,10 @@ private class DiffCanvasView(context: Context) : View(context) { val firstLineBottom = top + lines.firstHeight(style.rowHeightPx.toInt()) drawScrollableCode(canvas, top, bottom) { codeX -> drawing.configureCodePaint(theme.text, 0, style) - drawing.drawWordDiffRanges(canvas, row, codeX, top, firstLineBottom, lines) val baseline = lines.baseline(top, firstLineBottom, textPaint) - drawing.drawCode(canvas, row, tokensByRowId[row.id], codeX, baseline, style, lines) + val tokens = tokensByRowId[row.id] + drawing.drawWordDiffRanges(canvas, row, tokens, codeX, top, firstLineBottom, lines, style) + drawing.drawCode(canvas, row, tokens, codeX, baseline, style, lines) } drawLineNumber(canvas, row, top, firstLineBottom) diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt index beac68f8e5357..f2992979bf522 100644 --- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt +++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt @@ -1,6 +1,12 @@ package expo.modules.t3reviewdiff +import android.graphics.Bitmap +import android.graphics.Canvas import android.graphics.Color +import android.graphics.Paint +import android.graphics.RectF +import android.text.StaticLayout +import android.text.TextPaint import android.view.View import kotlin.math.ceil import expo.modules.kotlin.AppContext @@ -177,6 +183,82 @@ class ReviewDiffGeometryTest { } } + @Test + fun unwrappedWordDiffHighlightsCoverTheTextDrawCodeDraws() { + val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) + val boxes = mutableListOf() + val texts = mutableMapOf() + val paints = mutableMapOf() + val bitmap = Bitmap.createBitmap(1000, 60, Bitmap.Config.ARGB_8888) + val canvas = object : Canvas(bitmap) { + override fun drawRoundRect(rect: RectF, rx: Float, ry: Float, paint: Paint) { + boxes += RectF(rect) + } + + override fun drawText( + text: String, + start: Int, + end: Int, + x: Float, + y: Float, + paint: Paint + ) { + texts[text.substring(start, end)] = x + paints[text.substring(start, end)] = TextPaint(paint) + } + } + + // The framework's caret position in the piece drawCode drew, kerning included. + fun caret(piece: String, offset: Int): Float { + val layout = StaticLayout.Builder.obtain(piece, 0, piece.length, paints.getValue(piece), 1000) + return texts.getValue(piece) + layout.build().getPrimaryHorizontal(offset) + } + val lines = CodeLines(intArrayOf(0), 0) + for (weight in listOf("medium", "regular")) { + val style = DiffStyle.defaults(1f).copy(codeFontWeight = weight, codeFontSizePx = 17f) + for (prefix in listOf("if ", "说明 ", "😀 ")) { + val tokens = listOf( + DiffToken(prefix, Color.RED, 2), + DiffToken("go ", Color.BLUE, 0), + DiffToken("1.27.3", Color.GREEN, 0), + DiffToken(";", Color.BLUE, 0), + DiffToken(" LTP.", Color.BLUE, 0), + DiffToken(" AV", Color.GREEN, 0), + DiffToken("LP.", Color.BLUE, 0), + ) + val content = tokens.joinToString("") { it.content } + val start = content.indexOf("1.27.3") + val kerned = content.indexOf("TP") + val crossing = content.indexOf("VLP") + val row = row("line", content).copy( + wordDiffRanges = listOf( + DiffWordDiffRange(start, start + "1.27.3".length), + DiffWordDiffRange(kerned, kerned + 2), + DiffWordDiffRange(crossing, crossing + 3), + ), + ) + boxes.clear() + texts.clear() + paints.clear() + drawing.configureCodePaint(Color.BLACK, 0, style) + drawing.drawWordDiffRanges(canvas, row, tokens, 10f, 0, 40, lines, style) + drawing.drawCode(canvas, row, tokens, 10f, 28f, style, lines) + assertEquals(3, boxes.size) + val (box, kernedBox, crossingBox) = boxes + val case = "weight=$weight prefix=$prefix" + assertEquals("$case left", requireNotNull(texts["1.27.3"]), box.left, 0.5f) + assertEquals("$case right", requireNotNull(texts[";"]), box.right, 0.5f) + val unkerned = texts.getValue(" LTP.") + paints.getValue(" LTP.").measureText(" L") + if (weight == "medium") assertTrue("$case L and T kern", caret(" LTP.", 2) < unkerned - 1f) + assertEquals("$case kerned left", caret(" LTP.", 2), kernedBox.left, 0.5f) + assertEquals("$case kerned right", caret(" LTP.", 4), kernedBox.right, 0.5f) + assertEquals("$case crossing left", caret(" AV", 2), crossingBox.left, 0.5f) + assertEquals("$case crossing right", caret("LP.", 2), crossingBox.right, 0.5f) + } + } + bitmap.recycle() + } + @Test fun lazyAsciiHeightAndLineStartsMatchTheExistingLayoutAtEveryBoundary() { val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) diff --git a/apps/mobile/modules/t3-voice-transcription/ios/AppleSpeechEngine.swift b/apps/mobile/modules/t3-voice-transcription/ios/AppleSpeechEngine.swift new file mode 120000 index 0000000000000..8c54186f2ac73 --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/ios/AppleSpeechEngine.swift @@ -0,0 +1 @@ +../../../../../native/apple-speech/AppleSpeechEngine.swift \ No newline at end of file diff --git a/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift b/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift index 8c02fbd84a9d5..f975854669dfc 100644 --- a/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift +++ b/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift @@ -6,6 +6,25 @@ public class T3VoiceTranscriptionModule: Module { public func definition() -> ModuleDefinition { Name("T3VoiceTranscription") + Function("isAppleSpeechAvailable") { + if #available(iOS 26, *) { return AppleSpeechEngine.isAvailable } + return false + } + + AsyncFunction("prepareAppleSpeech") { (locale: String) async throws -> String? in + guard #available(iOS 26, *) else { throw CocoaError(.featureUnsupported) } + do { + return try await AppleSpeechEngine.prepare(locale) + } catch AppleSpeechEngine.Failure.unsupportedLocale { + return nil + } + } + + AsyncFunction("transcribeWithAppleSpeech") { (uri: URL, locale: String) async throws -> String in + guard #available(iOS 26, *) else { throw CocoaError(.featureUnsupported) } + return try await AppleSpeechEngine.transcribe(locale, file: uri) + } + AsyncFunction("decodeRecording") { (uri: URL) throws -> Data in guard uri.isFileURL else { throw CocoaError(.fileReadUnsupportedScheme) } var opened: ExtAudioFileRef? diff --git a/apps/mobile/package.json b/apps/mobile/package.json index b6e3c57d83606..d86ac2320328b 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -68,7 +68,6 @@ "@material/material-color-utilities": "0.3.0", "@pierre/diffs": "catalog:", "@pierre/highlights": "catalog:", - "@react-native-ai/apple": "0.12.0", "@react-native-menu/menu": "^2.0.0", "@react-navigation/elements": "2.9.45", "@react-navigation/native": "7.5.1", diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 7a9a806f54f19..696b01ce29692 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -69,6 +69,7 @@ import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet"; import { GitOverviewSheet } from "./features/threads/git/GitOverviewSheet"; import { ThreadPullRequestsSheet } from "./features/threads/ThreadPullRequestsSheet"; import { ThreadAgentsSheet } from "./features/threads/ThreadAgentsSheet"; +import { LinkedThreadSheet } from "./features/threads/LinkedThreadSheet"; import { ThreadGuestShareSheet } from "./features/threads/ThreadGuestShareSheet"; import { ThreadBackgroundWorkSheet } from "./features/threads/ThreadBackgroundWorkSheet"; import { ThreadQueueSheet } from "./features/threads/ThreadQueueControl"; @@ -784,6 +785,15 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadAgentsSheet, options: sheetRoute({ detent: 0.5, androidMaxDetent: 0.9 }), }), + LinkedThread: createNativeStackScreen({ + screen: LinkedThreadSheet, + options: sheetRoute({ detent: 0.9, android: "fullScreen" }), + }), + // Maximized from the inspector, like ThreadInspectorFullscreen. + LinkedThreadFullscreen: createNativeStackScreen({ + screen: LinkedThreadSheet, + options: modalRoute({ header: "glass", itemStyle: "editor", duoMinimize: "onScrollUp" }), + }), ThreadGuestShare: createNativeStackScreen({ screen: ThreadGuestShareSheet, options: sheetRoute({ detent: 0.5 }), diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index 767a689568131..ba7d9790c4120 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -66,6 +66,13 @@ export function ComposerAttachmentThumbnail(props: ComposerAttachmentThumbnailPr return ( + {upload?.status === "failed" ? ( + + ) : null} {upload && upload.status !== "ready" ? ( ({ alert: vi.fn() })); vi.mock("./ui/AppText", () => ({ AppText: ({ children }: { children?: ReactNode }) => children })); vi.mock("./ComposerContextSheet", () => ({ ComposerContextSheet: () => null })); vi.mock("./AssistantCitationSheet", () => ({ AssistantCitationSheet: () => null })); -vi.mock("../features/threads/useOpenLinkedThread", () => ({ useOpenLinkedThread: () => vi.fn() })); +vi.mock("../features/threads/useOpenThreadLink", () => ({ useOpenThreadLink: () => vi.fn() })); vi.mock("../state/peerLinks", () => ({ useLinkedEnvironments: () => [] })); vi.mock("../state/model-mentions", () => ({ useModelMentions: () => [] })); vi.mock("../state/preferences", async () => { diff --git a/apps/mobile/src/components/ComposerEditor.tsx b/apps/mobile/src/components/ComposerEditor.tsx index 8d3805234696b..39e12816cdf61 100644 --- a/apps/mobile/src/components/ComposerEditor.tsx +++ b/apps/mobile/src/components/ComposerEditor.tsx @@ -37,7 +37,7 @@ import { appAtomRegistry } from "../state/atom-registry"; import { enrichedModelDetails, enrichedModelReference } from "../lib/enrichedLinkPresentation"; import { useModelMentions } from "../state/model-mentions"; import { mobilePreferencesAtom } from "../state/preferences"; -import { useOpenLinkedThread } from "../features/threads/useOpenLinkedThread"; +import { useOpenThreadLink } from "../features/threads/useOpenThreadLink"; import { useLinkedEnvironments } from "../state/peerLinks"; import { ComposerContextSheet } from "./ComposerContextSheet"; import { AppText as Text } from "./ui/AppText"; @@ -186,7 +186,7 @@ export function ComposerEditor({ }), }) : ""; - const openLinkedThread = useOpenLinkedThread(); + const openThreadLink = useOpenThreadLink(environmentId ?? null); const selectedReference = selected ? collectComposerContextReferences(selected.source)[0] : undefined; @@ -338,10 +338,7 @@ export function ComposerEditor({ : {})} onOpenThread={(thread) => { setSelected(null); - openLinkedThread({ - environmentId: String(thread.environmentId), - threadId: String(thread.threadId), - }); + openThreadLink(thread); }} environmentId={environmentId ?? draft.project?.environmentId} projectId={draft.project?.projectId} diff --git a/apps/mobile/src/components/ui/ListToggleRow.test.tsx b/apps/mobile/src/components/ui/ListToggleRow.test.tsx new file mode 100644 index 0000000000000..60476f9a7094f --- /dev/null +++ b/apps/mobile/src/components/ui/ListToggleRow.test.tsx @@ -0,0 +1,55 @@ +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +vi.mock("react-native", () => ({ + Pressable: (props: { + readonly children?: ReactNode; + readonly accessibilityLabel?: string; + readonly onPress: () => void; + }) => ( + + ), +})); +vi.mock("./AppText", () => ({ AppText: (props: { children?: ReactNode }) => props.children })); +vi.mock("./ListRowLayout", () => ({ + ListRowLayout: (props: { accessory?: ReactNode }) => props.accessory, +})); +vi.mock("./ThemedSwitch", () => ({ ThemedSwitch: () => null })); + +import { ListToggleRow } from "./ListToggleRow"; + +it("sets a mixed row on, then off when an older environment drops it", () => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const saves: boolean[] = []; + try { + // The older environment dropped the unknown key, so the row stays mixed after every save. + act(() => + root.render( + saves.push(value)} + />, + ), + ); + const button = () => container.querySelector("button")!; + + act(() => button().click()); + const offer = { text: button().textContent, label: button().getAttribute("aria-label") }; + act(() => button().click()); + + expect(saves).toEqual([true, false]); + expect(offer).toEqual({ + text: "Mixed · Set off", + label: "Set Clone into host folders off for selected environments", + }); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } +}); diff --git a/apps/mobile/src/components/ui/ListToggleRow.tsx b/apps/mobile/src/components/ui/ListToggleRow.tsx index 6a92b18069aae..ba5c8a65f9ae0 100644 --- a/apps/mobile/src/components/ui/ListToggleRow.tsx +++ b/apps/mobile/src/components/ui/ListToggleRow.tsx @@ -1,10 +1,15 @@ import { T, useGT } from "gt-react-native"; +import { useState } from "react"; import { Pressable } from "react-native"; import { AppText } from "./AppText"; import { ListRowLayout, type ListRowContentProps } from "./ListRowLayout"; import { ThemedSwitch } from "./ThemedSwitch"; +/** + * A mixed row flips the value last picked on it, so a pick that some environments dropped can be + * undone. Before any pick, it sets the value on everywhere. + */ export function ListToggleRow( props: Omit & { readonly value: boolean | null; @@ -12,6 +17,11 @@ export function ListToggleRow( }, ) { const gt = useGT(); + const [picked, setPicked] = useState(false); + const pick = (value: boolean) => { + setPicked(value); + props.onValueChange(value); + }; return ( props.onValueChange(true)} + onPress={() => pick(!picked)} > - Mixed · Set on + {picked ? Mixed · Set off : Mixed · Set on} ) : ( @@ -40,7 +52,7 @@ export function ListToggleRow( accessibilityLabel={props.label} accessibilityHint={props.description} disabled={props.disabled} - onValueChange={props.onValueChange} + onValueChange={pick} value={props.value} /> ) diff --git a/apps/mobile/src/components/ui/SecretTextInput.android.tsx b/apps/mobile/src/components/ui/SecretTextInput.android.tsx index 9a9f98bd55c14..3f6539e24c782 100644 --- a/apps/mobile/src/components/ui/SecretTextInput.android.tsx +++ b/apps/mobile/src/components/ui/SecretTextInput.android.tsx @@ -1,13 +1,19 @@ import { requireNativeView } from "expo"; -import { useState } from "react"; +import { useState, type Ref } from "react"; import { processColor, View, type NativeSyntheticEvent, type ViewProps } from "react-native"; +import { cn } from "../../lib/cn"; import { flattenThemeColor } from "../../lib/mobileTheme"; import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { SecretRevealButton } from "./SecretRevealButton"; import type { SecretTextInputProps } from "./SecretTextInput.types"; +interface NativeSecretInputRef { + focus: () => Promise; +} + interface NativeSecretInputProps extends ViewProps { + readonly ref?: Ref; readonly inputLabel: string; readonly value: string; readonly placeholder: string; @@ -17,6 +23,7 @@ interface NativeSecretInputProps extends ViewProps { readonly fontSize: number; readonly editable: boolean; readonly revealed: boolean; + readonly returnKey: "next" | "done"; readonly onChangeText: (event: NativeSyntheticEvent<{ readonly value: string }>) => void; readonly onSubmit: (event: NativeSyntheticEvent<{ readonly value: string }>) => void; } @@ -36,13 +43,28 @@ function nativeColor(value: string) { * offer logins above the keyboard. This field is a native EditText that reports no autofill type. * The frame matches AppTextInput's. */ -export function SecretTextInput(props: SecretTextInputProps) { +export function SecretTextInput({ onMount, secret = true, ...props }: SecretTextInputProps) { const theme = useUniwindTheme(); const surface = theme["--color-input"]; const [revealed, setRevealed] = useState(false); return ( - + + onMount( + native === null + ? null + : { focus: () => void native.focus().catch(() => undefined) }, + ) + } inputLabel={props.accessibilityLabel} value={props.value} placeholder={props.placeholder} @@ -51,12 +73,15 @@ export function SecretTextInput(props: SecretTextInputProps) { cursorColor={nativeColor(flattenThemeColor(theme["--color-focus"], surface))} fontSize={FONT_SIZE} editable={props.editable} - revealed={revealed} + revealed={!secret || revealed} + returnKey={props.returnKeyType ?? "done"} onChangeText={(event) => props.onChangeText(event.nativeEvent.value)} onSubmit={(event) => props.onSubmitEditing(event.nativeEvent.value)} style={{ flex: 1, height: LINE_HEIGHT }} /> - setRevealed(!revealed)} /> + {secret ? ( + setRevealed(!revealed)} /> + ) : null} ); } diff --git a/apps/mobile/src/components/ui/SecretTextInput.tsx b/apps/mobile/src/components/ui/SecretTextInput.tsx index 643fe5acbb63d..210f27aad5be3 100644 --- a/apps/mobile/src/components/ui/SecretTextInput.tsx +++ b/apps/mobile/src/components/ui/SecretTextInput.tsx @@ -6,30 +6,35 @@ import { SecretRevealButton } from "./SecretRevealButton"; import type { SecretTextInputProps } from "./SecretTextInput.types"; /** Masked field for a value that must stay out of password managers and suggestions. */ -export function SecretTextInput(props: SecretTextInputProps) { +export function SecretTextInput({ onMount, secret = true, ...props }: SecretTextInputProps) { const [revealed, setRevealed] = useState(false); + const returnKeyType = props.returnKeyType ?? "done"; return ( props.onSubmitEditing(event.nativeEvent.text)} /> - - setRevealed(!revealed)} /> - + {secret ? ( + + setRevealed(!revealed)} /> + + ) : null} ); } diff --git a/apps/mobile/src/components/ui/SecretTextInput.types.ts b/apps/mobile/src/components/ui/SecretTextInput.types.ts index 37db8e458d28d..4e839846ad679 100644 --- a/apps/mobile/src/components/ui/SecretTextInput.types.ts +++ b/apps/mobile/src/components/ui/SecretTextInput.types.ts @@ -1,3 +1,7 @@ +export interface SecretTextInputHandle { + readonly focus: () => void; +} + export interface SecretTextInputProps { readonly accessibilityLabel: string; readonly placeholder: string; @@ -6,4 +10,9 @@ export interface SecretTextInputProps { /** Receives the field's current text, so a submit never uses a stale render of it. */ readonly onSubmitEditing: (value: string) => void; readonly editable: boolean; + /** False shows the text with no eye toggle, for a value such as an email. Defaults to true. */ + readonly secret?: boolean; + /** "next" keeps the keyboard open for the following field. */ + readonly returnKeyType?: "next" | "done"; + readonly onMount?: (handle: SecretTextInputHandle | null) => void; } diff --git a/apps/mobile/src/connection/onboarding.ts b/apps/mobile/src/connection/onboarding.ts index 54963759ed189..bf10122432349 100644 --- a/apps/mobile/src/connection/onboarding.ts +++ b/apps/mobile/src/connection/onboarding.ts @@ -44,3 +44,11 @@ export const updateBearerConnection = createRuntimeCommand(connectionAtomRuntime Effect.flatMap((onboarding) => onboarding.updateBearer(input)), ), }); + +export const reachesEnvironment = createRuntimeCommand(connectionAtomRuntime, { + label: "mobile:connection:reaches-environment", + execute: (input: { readonly host: string; readonly environmentId: EnvironmentId }) => + ConnectionOnboarding.ConnectionOnboarding.pipe( + Effect.flatMap((onboarding) => onboarding.reaches(input)), + ), +}); diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts index 4ea1aea9989b3..2bf255d39e099 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts @@ -3,10 +3,16 @@ import { describe, expect, it } from "@effect/vitest"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; import type { EnvironmentId } from "@t3tools/contracts"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; import type { SavedRemoteConnection } from "../../lib/connection"; +import { + MobilePreferencesSaveError, + MobilePreferencesStore, +} from "../../persistence/mobile-preferences"; +import { MobileStorage } from "../../persistence/mobile-storage"; import { CloudEnvironmentLinkError } from "../cloud/linkEnvironment"; import { setLiveActivityUpdatesEnabled } from "./liveActivityPreferences"; import { updateAgentAwarenessRegistrationPreferences } from "./remoteRegistration"; @@ -48,6 +54,10 @@ const linkEnvironment = vi.fn< ) => Effect.Effect >(() => Effect.void); +const saveLocalPreference = vi.fn< + (enabled: boolean) => Effect.Effect +>(() => Effect.void); + const connection: SavedRemoteConnection = { environmentId: "env-1" as EnvironmentId, environmentLabel: "Desktop", @@ -58,7 +68,13 @@ const connection: SavedRemoteConnection = { bearerToken: "local-bearer", }; -const withRelayClient = Effect.provideService(ManagedRelay.ManagedRelayClient, null as never); +const withRelayClient = Effect.provide( + Layer.mergeAll( + Layer.succeed(ManagedRelay.ManagedRelayClient, null as never), + Layer.succeed(MobileStorage, null as never), + Layer.succeed(MobilePreferencesStore, null as never), + ), +); describe("liveActivityPreferences", () => { beforeEach(() => { @@ -76,6 +92,7 @@ describe("liveActivityPreferences", () => { setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -103,6 +120,33 @@ describe("liveActivityPreferences", () => { }).pipe(withRelayClient); }); + it.effect("restores the device preference when the device cannot save the setting", () => { + saveLocalPreference.mockImplementationOnce(() => + Effect.fail(new MobilePreferencesSaveError({ cause: new Error("storage full") })), + ); + + return Effect.gen(function* () { + const exit = yield* Effect.exit( + setLiveActivityUpdatesEnabled({ + updateEnvironment, + linkEnvironment, + saveLocalPreference, + enabled: true, + previousEnabled: false, + clerkToken: "clerk-token", + connections: [connection], + canConfigureEnvironment: () => false, + canUpdateEnvironment: () => true, + }), + ); + + expect(Exit.isFailure(exit)).toBe(true); + expect(updateAgentAwarenessRegistrationPreferences).toHaveBeenLastCalledWith({ + liveActivitiesEnabled: false, + }); + }).pipe(withRelayClient); + }); + it.effect("reports a relay preference committed before environment configuration fails", () => { const failure = new CloudEnvironmentLinkError({ message: "environment configuration failed", @@ -116,6 +160,7 @@ describe("liveActivityPreferences", () => { setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -156,6 +201,7 @@ describe("liveActivityPreferences", () => { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -185,6 +231,7 @@ describe("liveActivityPreferences", () => { const partial = yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -209,6 +256,7 @@ describe("liveActivityPreferences", () => { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts index 6ff47c294a4cb..a8cbe09ddfebd 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts @@ -15,92 +15,95 @@ export class LiveActivityEnvironmentUpdateError extends Schema.TaggedError; - readonly updateEnvironment: ( - environmentId: EnvironmentId, - enabled: boolean, - ) => Effect.Effect< - "updated" | "unlinked" | "unsupported" | "disconnected", - CloudEnvironmentLinkError - >; - readonly linkEnvironment: ( - environmentId: EnvironmentId, - input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, - ) => Effect.Effect; - readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean; - readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean; - }) { - const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* ( - connection: SavedRemoteConnection, - enabled: boolean, - clerkToken: string | null, - ) { - const result = input.canUpdateEnvironment(connection.environmentId) - ? yield* input.updateEnvironment(connection.environmentId, enabled) - : "unlinked"; - if (result === "updated" || result === "disconnected") return result; - if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) { - return result; - } +export const setLiveActivityUpdatesEnabled = Effect.fn("setLiveActivityUpdatesEnabled")(function* < + SaveError, +>(input: { + readonly enabled: boolean; + readonly previousEnabled: boolean; + readonly clerkToken: string | null; + readonly connections: ReadonlyArray; + readonly updateEnvironment: ( + environmentId: EnvironmentId, + enabled: boolean, + ) => Effect.Effect< + "updated" | "unlinked" | "unsupported" | "disconnected", + CloudEnvironmentLinkError + >; + readonly linkEnvironment: ( + environmentId: EnvironmentId, + input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }, + ) => Effect.Effect; + readonly canUpdateEnvironment: (environmentId: EnvironmentId) => boolean; + readonly canConfigureEnvironment: (environmentId: EnvironmentId) => boolean; + readonly saveLocalPreference: (enabled: boolean) => Effect.Effect; +}) { + const updateEnvironmentPreference = Effect.fn("updateEnvironmentPreference")(function* ( + connection: SavedRemoteConnection, + enabled: boolean, + clerkToken: string | null, + ) { + const result = input.canUpdateEnvironment(connection.environmentId) + ? yield* input.updateEnvironment(connection.environmentId, enabled) + : "unlinked"; + if (result === "updated" || result === "disconnected") return result; + if (!enabled || !clerkToken || !input.canConfigureEnvironment(connection.environmentId)) { + return result; + } - yield* input.linkEnvironment(connection.environmentId, { - clerkToken, - liveActivitiesEnabled: enabled, - }); - return "updated" as const; + yield* input.linkEnvironment(connection.environmentId, { + clerkToken, + liveActivitiesEnabled: enabled, }); + return "updated" as const; + }); - const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) { - yield* updateAgentAwarenessRegistrationPreferences({ - liveActivitiesEnabled: enabled, - }); + const updateRelayPreference = Effect.fn("updateRelayPreference")(function* (enabled: boolean) { + yield* updateAgentAwarenessRegistrationPreferences({ + liveActivitiesEnabled: enabled, + }); - const clerkToken = input.clerkToken; - if (!clerkToken) return false; + const clerkToken = input.clerkToken; + if (!clerkToken) return false; - const results = yield* Effect.forEach( - input.connections, - (connection) => - updateEnvironmentPreference(connection, enabled, clerkToken).pipe( - Effect.result, - Effect.map((result) => ({ connection, result })), - ), - { concurrency: "unbounded" }, - ); - const failure = results.find(({ result }) => Result.isFailure(result)); - if (failure && Result.isFailure(failure.result)) { - const updatedEnvironments = results.flatMap(({ connection, result }) => { - const changed = Result.isSuccess(result) - ? result.success === "updated" - : result.failure.relayLinkCommitted === true; - return changed ? [connection.environmentLabel] : []; - }); - if (updatedEnvironments.length === 0) return yield* failure.result.failure; - return yield* new LiveActivityEnvironmentUpdateError({ - updatedEnvironments, - cause: failure.result.failure, - }); - } - return results.some( - ({ result }) => Result.isSuccess(result) && result.success === "unsupported", - ); - }); + const results = yield* Effect.forEach( + input.connections, + (connection) => + updateEnvironmentPreference(connection, enabled, clerkToken).pipe( + Effect.result, + Effect.map((result) => ({ connection, result })), + ), + { concurrency: "unbounded" }, + ); + const failure = results.find(({ result }) => Result.isFailure(result)); + if (failure && Result.isFailure(failure.result)) { + const updatedEnvironments = results.flatMap(({ connection, result }) => { + const changed = Result.isSuccess(result) + ? result.success === "updated" + : result.failure.relayLinkCommitted === true; + return changed ? [connection.environmentLabel] : []; + }); + if (updatedEnvironments.length === 0) return yield* failure.result.failure; + return yield* new LiveActivityEnvironmentUpdateError({ + updatedEnvironments, + cause: failure.result.failure, + }); + } + return results.some( + ({ result }) => Result.isSuccess(result) && result.success === "unsupported", + ); + }); - return yield* updateRelayPreference(input.enabled).pipe( - Effect.onError(() => - updateAgentAwarenessRegistrationPreferences({ - liveActivitiesEnabled: input.previousEnabled, - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Could not restore Live Activity device preference.", cause), - ), + return yield* updateRelayPreference(input.enabled).pipe( + // Saved here so a device that cannot keep the setting restores its registration too. + Effect.tap(() => input.saveLocalPreference(input.enabled)), + Effect.onError(() => + updateAgentAwarenessRegistrationPreferences({ + liveActivitiesEnabled: input.previousEnabled, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not restore Live Activity device preference.", cause), ), ), - ); - }, -); + ), + ); +}); diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index d4438911eb7bf..5f5a46b653b1b 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -21,12 +21,19 @@ import * as Dpop from "../cloud/dpop"; import * as ManagedRelayLayer from "../cloud/managedRelayLayer"; import { clearAgentAwarenessRegistrationRecord, + loadAgentAwarenessDeviceId, loadAgentAwarenessRegistrationRecord, loadOrCreateAgentAwarenessDeviceId, loadPreferences, saveAgentAwarenessRegistrationRecord, } from "../../persistence/imperative"; -import type { Preferences } from "../../persistence/mobile-preferences"; +import { + MobilePreferencesLoadError, + MobilePreferencesStore, + type Preferences, +} from "../../persistence/mobile-preferences"; +import { MobileSecureStorageError } from "../../persistence/mobile-secure-storage"; +import * as MobileStorage from "../../persistence/mobile-storage"; import { makeRelayDeviceRegistrationRequest } from "./registrationPayload"; import { __resetAgentAwarenessRemoteRegistrationForTest, @@ -40,6 +47,7 @@ import { subscribeAgentAwarenessRegistrationStatus, updateAgentAwarenessRegistrationPreferences, type AgentAwarenessRegistrationError, + type AgentAwarenessRegistrationServices, } from "./remoteRegistration"; import * as Notifications from "expo-notifications"; import { Platform } from "react-native"; @@ -218,8 +226,53 @@ function proofIat(proof: string): number { return decoded.iat; } +const storageFailure = (cause: unknown) => + new MobileSecureStorageError({ operation: "read", key: "test", cause }); +const unexpectedStorage = () => Effect.die("Unexpected storage request"); + +// Delegates to the persistence/imperative mocks so each test steers both paths the same way. +const layerPersistenceTest = Layer.merge( + Layer.succeed( + MobileStorage.MobileStorage, + MobileStorage.MobileStorage.of({ + loadOrCreateAgentAwarenessDeviceId: Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: storageFailure, + }), + loadAgentAwarenessDeviceId: Effect.tryPromise({ + try: () => loadAgentAwarenessDeviceId(), + catch: storageFailure, + }), + loadAgentAwarenessRegistrationRecord: Effect.tryPromise({ + try: () => loadAgentAwarenessRegistrationRecord(), + catch: storageFailure, + }), + saveAgentAwarenessRegistrationRecord: (record) => + Effect.tryPromise({ + try: () => saveAgentAwarenessRegistrationRecord(record), + catch: storageFailure, + }), + clearAgentAwarenessRegistrationRecord: unexpectedStorage(), + loadRecentThreadShortcuts: unexpectedStorage(), + saveRecentThreadShortcuts: unexpectedStorage, + }), + ), + Layer.succeed( + MobilePreferencesStore, + MobilePreferencesStore.of({ + load: Effect.tryPromise({ + try: () => loadPreferences(), + catch: (cause) => new MobilePreferencesLoadError({ cause }), + }), + savePatch: unexpectedStorage, + update: unexpectedStorage, + }), + ), +); + const layerRelayTest = ManagedRelayLayer.layer("https://relay.example.test").pipe( Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)), + Layer.merge(layerPersistenceTest), ); const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundOperations")( @@ -241,7 +294,7 @@ const runBackgroundOperations = Effect.fn("TestRemoteRegistration.runBackgroundO pending.operation as Effect.Effect< unknown, AgentAwarenessRegistrationError, - ManagedRelay.ManagedRelayClient + AgentAwarenessRegistrationServices >, ); yield* Effect.sync(() => { @@ -599,6 +652,22 @@ describe("makeRelayDeviceRegistrationRequest", () => { }).pipe(Effect.provide(layerRelayTest)); }); + it.effect("leaves the signed-out status alone when an obsolete registration fails", () => { + Constants.expoConfig!.extra = { + relay: { + url: "https://relay.example.test/", + }, + }; + vi.mocked(loadOrCreateAgentAwarenessDeviceId).mockRejectedValue(new Error("storage failure")); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + setAgentAwarenessRelayTokenProvider(null); + + return Effect.gen(function* () { + yield* runBackgroundOperations(); + expect(getAgentAwarenessRegistrationStatus()).toBe("unknown"); + }).pipe(Effect.provide(layerRelayTest)); + }); + it.effect("does not re-register the same account when nothing has changed", () => { Constants.expoConfig!.extra = { relay: { @@ -706,6 +775,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { Effect.provide( ManagedRelayLayer.layer("https://permission-relay.example.test").pipe( Layer.provide(Layer.mergeAll(FetchHttpClient.layer, Dpop.layer)), + Layer.merge(layerPersistenceTest), ), ), ); @@ -1005,7 +1075,7 @@ describe("makeRelayDeviceRegistrationRequest", () => { getAgentActivitySnapshot, resetTokenCache: Effect.void, }), - ); + ).pipe(Layer.merge(layerPersistenceTest)); } it.effect("registers an existing Live Activity before waiting on the widget read", () => { diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index 2c995bd8eafa8..bea319f0877d3 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -29,14 +29,11 @@ import { m } from "../../i18n/messages"; import { runtime } from "../../lib/runtime"; import { appAtomRegistry } from "../../state/atom-registry"; import { environmentServerConfigsAtom } from "../../state/server"; -import type { Preferences } from "../../persistence/mobile-preferences"; +import { MobilePreferencesStore, type Preferences } from "../../persistence/mobile-preferences"; +import * as MobileStorage from "../../persistence/mobile-storage"; import { clearAgentAwarenessRegistrationRecord, - loadAgentAwarenessDeviceId, - loadAgentAwarenessRegistrationRecord, - loadOrCreateAgentAwarenessDeviceId, loadPreferences, - saveAgentAwarenessRegistrationRecord, } from "../../persistence/imperative"; import type { AgentActivityProps } from "../../widgets/AgentActivity"; import { @@ -88,6 +85,11 @@ export type AgentAwarenessRegistrationError = | AgentAwarenessOperationError | ManagedRelay.ManagedRelayClientError; +export type AgentAwarenessRegistrationServices = + | ManagedRelay.ManagedRelayClient + | MobileStorage.MobileStorage + | MobilePreferencesStore; + // ActivityKit returns new wrappers per id; serialize by id to prevent stale-token registration. const activityPushTokenLocks = new Map(); // Each accepted registration replays the relay aggregate, repairing drifted or orphaned activities. @@ -387,7 +389,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string { const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* ( body: RelayDeviceRegistrationRequest, expectedGeneration: number, -): Effect.fn.Return { +): Effect.fn.Return { if (expectedGeneration !== deviceRegistrationGeneration) { return; } @@ -406,11 +408,13 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith } const identity = relayTokenProviderIdentity ?? ""; - const persisted = yield* Effect.tryPromise({ - try: () => loadAgentAwarenessRegistrationRecord(), - catch: (cause) => - new AgentAwarenessOperationError({ operation: "load-registration-record", cause }), - }).pipe(Effect.orElseSucceed(() => null)); + const storage = yield* MobileStorage.MobileStorage; + const persisted = yield* storage.loadAgentAwarenessRegistrationRecord.pipe( + Effect.mapError( + (cause) => new AgentAwarenessOperationError({ operation: "load-registration-record", cause }), + ), + Effect.orElseSucceed(() => null), + ); if (expectedGeneration !== deviceRegistrationGeneration) { // Signed out while the record loaded — do not resurrect the cleared // record or report the previous account's registration as current. @@ -449,13 +453,12 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith } if (body.platform === "android") androidDeviceReplayedAt = yield* Clock.currentTimeMillis; setRegistrationStatus("registered", Boolean(payload.pushToken)); - yield* Effect.promise(() => - saveAgentAwarenessRegistrationRecord({ - identity, - signature, - }).catch((error: unknown) => { - logRegistrationError("persist registration record failed", error); - }), + yield* storage.saveAgentAwarenessRegistrationRecord({ identity, signature }).pipe( + Effect.catch((error) => + Effect.sync(() => { + logRegistrationError("persist registration record failed", error); + }), + ), ); }); @@ -610,7 +613,7 @@ function logRegistrationError(context: string, error: unknown): void { } function runRegistrationInBackground( - operation: Effect.Effect, + operation: Effect.Effect, context: string, ): void { void (async () => { @@ -660,7 +663,8 @@ function startPendingDeviceRegistration(): void { ); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { // Refresh failures leave the relay's accepted registration intact; preserve registered status. - if (registrationStatus !== "registered") { + // A sign-out or account switch meanwhile owns the status, so an obsolete run leaves it alone. + if (generation === deviceRegistrationGeneration && registrationStatus !== "registered") { setRegistrationStatus("failed"); } logRegistrationError(next.context, squashAtomCommandFailure(result)); @@ -692,28 +696,32 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* ( input: RegisterDeviceInput = {}, expectedGeneration = deviceRegistrationGeneration, -): Effect.fn.Return { +): Effect.fn.Return { if (!canRegisterPushNotifications()) { return; } + const storage = yield* MobileStorage.MobileStorage; + const preferencesStore = yield* MobilePreferencesStore; const [deviceId, storedPreferences] = yield* Effect.all([ - Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-device-registration-identifier", - cause, - }), - }), - Effect.tryPromise({ - try: () => loadPreferences(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-device-registration-preferences", - cause, - }), - }), + storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-registration-identifier", + cause, + }), + ), + ), + preferencesStore.load.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-registration-preferences", + cause, + }), + ), + ), ]); const preferences = mergeAgentAwarenessRegistrationPreferences( storedPreferences, @@ -759,14 +767,6 @@ const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* ); }); -function registerDeviceForCurrentUser(): Effect.Effect< - void, - AgentAwarenessRegistrationError, - ManagedRelay.ManagedRelayClient -> { - return registerDevice(undefined); -} - function ensurePushTokenListener(): void { if (pushTokenSubscription || !canRegisterPushNotifications()) { return; @@ -840,33 +840,39 @@ function endLocalLiveActivities(context: string): void { export function refreshAgentAwarenessRegistration(): Effect.Effect< void, never, - ManagedRelay.ManagedRelayClient + AgentAwarenessRegistrationServices > { - return registerDeviceForCurrentUser().pipe( - Effect.catch((error) => - Effect.sync(() => { - if (registrationStatus !== "registered") { - setRegistrationStatus("failed"); - } - logRegistrationError("device registration refresh failed", error); - }), - ), - ); + return Effect.suspend(() => { + const generation = deviceRegistrationGeneration; + return registerDevice(undefined, generation).pipe( + Effect.catch((error) => + Effect.sync(() => { + if (generation === deviceRegistrationGeneration && registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } + logRegistrationError("device registration refresh failed", error); + }), + ), + ); + }); } export function updateAgentAwarenessRegistrationPreferences( preferencesOverride: Partial, -): Effect.Effect { - return registerDevice({ preferencesOverride }).pipe( - Effect.tapError((error) => - Effect.sync(() => { - if (registrationStatus !== "registered") { - setRegistrationStatus("failed"); - } - logRegistrationError("device preference registration refresh failed", error); - }), - ), - ); +): Effect.Effect { + return Effect.suspend(() => { + const generation = deviceRegistrationGeneration; + return registerDevice({ preferencesOverride }, generation).pipe( + Effect.tapError((error) => + Effect.sync(() => { + if (generation === deviceRegistrationGeneration && registrationStatus !== "registered") { + setRegistrationStatus("failed"); + } + logRegistrationError("device preference registration refresh failed", error); + }), + ), + ); + }); } export function __resetAgentAwarenessRemoteRegistrationForTest(): void { @@ -896,18 +902,20 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void { export const unregisterAgentAwarenessDeviceForCurrentUser: ( tokenProvider: () => Promise, -) => Effect.Effect = Effect.fn( +) => Effect.Effect = Effect.fn( "remoteRegistration.unregisterAgentAwarenessDeviceForCurrentUser", )( function* (tokenProvider: () => Promise) { - const deviceId = yield* Effect.tryPromise({ - try: () => loadAgentAwarenessDeviceId(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-device-unregistration-identifier", - cause, - }), - }); + const storage = yield* MobileStorage.MobileStorage; + const deviceId = yield* storage.loadAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-unregistration-identifier", + cause, + }), + ), + ); if (!deviceId) { return; } @@ -924,7 +932,7 @@ export const registerLiveActivityPushToken = Effect.fn( "remoteRegistration.registerLiveActivityPushToken", )(function* (input: { readonly activity: LiveActivity; -}): Effect.fn.Return { +}): Effect.fn.Return { if (!canRegisterRemoteLiveActivities()) { return false; } @@ -972,7 +980,7 @@ const registerLiveActivityPushTokenValue = Effect.fn( "remoteRegistration.registerLiveActivityPushTokenValue", )(function* (input: { readonly activityPushToken: string; -}): Effect.fn.Return { +}): Effect.fn.Return { const acceptedAt = registeredActivityPushTokens.get(input.activityPushToken); if ( acceptedAt !== undefined && @@ -980,14 +988,16 @@ const registerLiveActivityPushTokenValue = Effect.fn( ) { return true; } - const deviceId = yield* Effect.tryPromise({ - try: () => loadOrCreateAgentAwarenessDeviceId(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-live-activity-registration-identifier", - cause, - }), - }); + const storage = yield* MobileStorage.MobileStorage; + const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-live-activity-registration-identifier", + cause, + }), + ), + ); const registered = yield* registerLiveActivityWithRelay({ deviceId, activityPushToken: input.activityPushToken, @@ -1014,7 +1024,7 @@ function scheduleActiveLiveActivityRegistrationRetry(): void { export const refreshActiveLiveActivityRemoteRegistration = Effect.fn( "remoteRegistration.refreshActiveLiveActivityRemoteRegistration", -)(function* (): Effect.fn.Return { +)(function* (): Effect.fn.Return { if (!canRegisterRemoteLiveActivities() || !relayTokenProvider) { return; } @@ -1085,14 +1095,17 @@ export const refreshActiveLiveActivityRemoteRegistration = Effect.fn( return; } const { snapshot } = widgetRead; - const preferences = yield* Effect.tryPromise({ - try: () => loadPreferences(), - catch: (cause) => - new AgentAwarenessOperationError({ - operation: "load-live-activity-prime-preferences", - cause, - }), - }).pipe(Effect.orElseSucceed(() => null)); + const preferencesStore = yield* MobilePreferencesStore; + const preferences = yield* preferencesStore.load.pipe( + Effect.mapError( + (cause) => + new AgentAwarenessOperationError({ + operation: "load-live-activity-prime-preferences", + cause, + }), + ), + Effect.orElseSucceed(() => null), + ); // A sign-out, account switch, or newer read during the preference read // makes this snapshot stale; priming now could bring old rows back. if (!isNewestRead()) { diff --git a/apps/mobile/src/features/browser/BrowserTabMenu.tsx b/apps/mobile/src/features/browser/BrowserTabMenu.tsx index c0df3fb971419..a98bded8b883e 100644 --- a/apps/mobile/src/features/browser/BrowserTabMenu.tsx +++ b/apps/mobile/src/features/browser/BrowserTabMenu.tsx @@ -16,6 +16,7 @@ import { msg, useGT, useMessages } from "gt-react-native"; import { ControlPill } from "../../components/ui/ControlPill"; import { Menu } from "../../components/ui/Menu"; import { m } from "../../i18n/messages"; +import { useEnvironmentPreviewTunnelOff } from "../../state/entities"; import { previewEnvironment } from "../../state/preview"; import { useAtomCommand } from "../../state/use-atom-command"; import { browserTabUrl, loopbackUrlForDevice } from "./browserTabs"; @@ -65,6 +66,7 @@ export function BrowserTabMenu({ readonly onReleaseControl?: () => void; }) { const openLocalPreview = useOpenLocalPreview(); + const tunnelOff = useEnvironmentPreviewTunnelOff(environmentId); const adjust = useAtomCommand(previewEnvironment.adjust, "browser tab change"); const resize = useAtomCommand(previewEnvironment.resize, "browser viewport change"); const close = useAtomCommand(previewEnvironment.close, "browser tab close"); @@ -92,7 +94,7 @@ export function BrowserTabMenu({ image: "xmark", attributes: { destructive: true, disabled: !canClose }, }; - const deviceUrl = loopbackUrlForDevice(browserTabUrl(tab)); + const deviceUrl = tunnelOff ? null : loopbackUrlForDevice(browserTabUrl(tab)); // The device preview has its own webview and tunnel, so it doesn't wait for the stream. const openOnDevice: MenuAction[] = deviceUrl ? [{ id: "open-on-device", title: gt("Open on this device"), image: "iphone" }] diff --git a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx index e8750bcf74349..8cfd22142698a 100644 --- a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx +++ b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx @@ -10,6 +10,7 @@ import { AppText } from "../../components/ui/AppText"; import * as Dialog from "../../components/ui/Dialog"; import { EmptyState } from "../../components/ui/EmptyState"; import { m } from "../../i18n/messages"; +import { useEnvironmentPreviewTunnelOff } from "../../state/entities"; import { useEnvironments } from "../../state/environments"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { BrowserChrome } from "./BrowserBar"; @@ -49,6 +50,7 @@ export function LocalPreviewScreen(props: { useEnvironments().presentationById.get(environmentId)?.entry.target.label ?? gt("the environment", { $context: "stands in for an environment name in a sentence" }); const { themeVariables } = useAppearancePreferences(); + const tunnelOff = useEnvironmentPreviewTunnelOff(environmentId); const webView = useRef(null); const [requested, setRequested] = useState(initialUrl); const [page, setPage] = useState(null); @@ -77,7 +79,7 @@ export function LocalPreviewScreen(props: { }; const back = () => void webView.current?.goBack(); const canGoBack = page?.canGoBack ?? false; - const pageColor = failed || unsupported !== null ? null : page?.pageColor || null; + const pageColor = failed || tunnelOff || unsupported !== null ? null : page?.pageColor || null; return ( // Full screen spans the Duo's rail, so it insets its own sides; the pane is inset already. @@ -127,7 +129,24 @@ export function LocalPreviewScreen(props: { setFailed(true); }} /> - {unsupported !== null ? ( + {tunnelOff ? ( + + + + + + ) : unsupported !== null ? ( ) : ( - - confirmDeregister(environment, () => void handleDeregister(environment)) - } - > - + + confirmDeregister(environment, () => void handleDeregister(environment)) + } > - - - - - + + + + + + + ) } /> diff --git a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx index 965b8bc1b5958..c32a7c5f5f098 100644 --- a/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx +++ b/apps/mobile/src/features/connection/ConnectionDiagnosisDetails.tsx @@ -12,7 +12,8 @@ import { import type { EnvironmentId } from "@t3tools/contracts"; import Constants from "expo-constants"; import { AsyncResult } from "effect/reactivity"; -import { Linking, View } from "react-native"; +import { View } from "react-native"; +import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { AppText as Text } from "../../components/ui/AppText"; import { Button } from "../../components/ui/Button"; @@ -103,7 +104,7 @@ export function ConnectionDiagnosisDetails(props: { label={gt("More info")} icon="safari" tone="secondary" - onPress={() => void Linking.openURL(moreInfoUrl).catch(() => undefined)} + onPress={() => void tryOpenExternalUrl(moreInfoUrl)} /> ) : null} diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx index 533c71b54ef35..73e035fe75ece 100644 --- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx @@ -30,6 +30,7 @@ import { SymbolView } from "../../components/ui/AppSymbol"; import { hasCloudPublicConfig } from "../cloud/publicConfig"; import { CloudEnvironmentRows } from "./CloudEnvironmentRows"; import { autoConnectReport, devAutoConnectAttemptAtom } from "./devAutoConnect"; +import { linkedEnvironmentPrefillAtom } from "./linkedEnvironmentPrefill"; import { splitEnvironmentSections } from "./environmentSections"; import { leaveSettingsPage } from "../settings/settings-navigation"; import { workspaceHasColumns } from "../layout/workspace/workspace-selection-store"; @@ -40,6 +41,8 @@ type ConnectionsNewRouteParams = { readonly pairingUrl?: string; readonly autoConnect?: string; readonly routeFor?: EnvironmentId; + /** A linked machine this app chose to pair with; its details come from app state, never the link. */ + readonly linked?: string; }; export function ConnectionsNewRouteScreen({ @@ -48,12 +51,15 @@ export function ConnectionsNewRouteScreen({ const params = route.params ?? {}; // Dev-only prefill prevents production links from supplying an attacker-chosen host and token. const routePairingUrl = __DEV__ ? (params.pairingUrl?.trim() ?? "") : ""; + const known = useAtomValue(linkedEnvironmentPrefillAtom); + const linked = known !== null && known.environmentId === params.linked ? known : null; // A new prefill link replaces whatever the form held. return ( ); } @@ -61,9 +67,11 @@ export function ConnectionsNewRouteScreen({ function PairingForm({ routePairingUrl, routeFor, + linked, }: { readonly routePairingUrl: string; readonly routeFor: EnvironmentId | undefined; + readonly linked: { readonly label: string; readonly host: string | null } | null; }) { const gt = useGT(); const { connectionPairingUrl, onChangeConnectionPairingUrl, onConnectPress } = @@ -71,7 +79,7 @@ function PairingForm({ const navigation = useNavigation(); const insets = useSafeAreaInsets(); const [initialPairing] = useState(() => parsePairingUrl(routePairingUrl || connectionPairingUrl)); - const [hostInput, setHostInput] = useState(initialPairing.host); + const [hostInput, setHostInput] = useState(linked?.host ?? initialPairing.host); const [codeInput, setCodeInput] = useState(initialPairing.code); const [isSubmitting, setIsSubmitting] = useState(false); const [submitError, setSubmitError] = useState(null); @@ -188,7 +196,11 @@ function PairingForm({ return ( {pairingConnectionError ?? - gt( - "For machines on your local network or tailnet. The machine keeps its own provider credentials.", - )} + (linked + ? gt( + "Create a pairing code on {environment}, in its Settings → Sharing & access or with `t3 auth pairing create`, and enter it here.", + { environment: linked.label }, + ) + : gt( + "For machines on your local network or tailnet. The machine keeps its own provider credentials.", + ))} diff --git a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx index 5e0e854dd8ec1..15dd76b7aac6b 100644 --- a/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx +++ b/apps/mobile/src/features/connection/ConnectionsRouteScreen.tsx @@ -3,7 +3,7 @@ import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScroll import { useNavigation } from "@react-navigation/native"; import type { EnvironmentId } from "@t3tools/contracts"; -import { useState } from "react"; +import { Fragment, useState } from "react"; import { View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -12,6 +12,7 @@ import { useRemoteConnections } from "../../state/use-remote-environment-registr import { LocalEnvironmentList } from "./LocalEnvironmentList"; import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings"; import { LinkedEnvironmentsSection } from "./LinkedEnvironmentsSection"; +import { LinkSeveralEnvironmentsAction } from "./LinkSeveralEnvironments"; export function ConnectionsRouteScreen() { const gt = useGT(); @@ -65,11 +66,16 @@ export function ConnectionsRouteScreen() { {connectedEnvironments .filter((environment) => environment.connectionState === "connected") .map((environment) => ( - + + + + ))} diff --git a/apps/mobile/src/features/connection/LinkSeveralEnvironments.tsx b/apps/mobile/src/features/connection/LinkSeveralEnvironments.tsx new file mode 100644 index 0000000000000..406904bb0c58e --- /dev/null +++ b/apps/mobile/src/features/connection/LinkSeveralEnvironments.tsx @@ -0,0 +1,344 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + linkBatchBlockLabel, + linkBatchCandidates, + linkBatchFailureLabel, + type LinkBatchOutcome, + linkBatchSummary, + linkListState, + runLinkBatch, +} from "@t3tools/client-runtime/link-batch"; +import { offersLinkedEnvironments } from "@t3tools/client-runtime/link-request"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { + AuthAccessWriteScope, + type AuthMcpClientAccess, + type EnvironmentId, +} from "@t3tools/contracts"; +import * as Result from "effect/Result"; +import { T, useGT, useMessages } from "gt-react-native"; +import { useMemo, useRef, useState } from "react"; +import { Pressable, ScrollView, View } from "react-native"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol"; +import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppText as Text } from "../../components/ui/AppText"; +import { Button } from "../../components/ui/Button"; +import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; +import { Sheet } from "../../components/ui/Sheet"; +import { useEnvironmentServerConfig } from "../../state/entities"; +import { useEnvironments } from "../../state/environments"; +import { peerLinkEnvironment, useLinkableMachines } from "../../state/peerLinks"; +import { mintPairingCodeOn } from "../../state/peerPairingCode"; +import { useEnvironmentQuery } from "../../state/query"; +import { useEnvironmentsWithScope } from "../../state/session"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { SettingsSection } from "../settings/components/SettingsSection"; +import { LINK_ACCESS_CHOICES } from "../threads/LinkRequestCard"; + +const NO_MACHINES: ReadonlySet = new Set(); +const NO_OUTCOMES: ReadonlyMap = new Map(); + +/** Offers a batch link from `environmentId` once this app has two other machines saved. */ +export function LinkSeveralEnvironmentsAction(props: { + readonly environmentId: EnvironmentId; + readonly environmentLabel: string; +}) { + const gt = useGT(); + const [open, setOpen] = useState(false); + const config = useEnvironmentServerConfig(props.environmentId); + const canLink = useAtomValue(peerLinkEnvironment.link.permissionAtom(props.environmentId)); + const otherMachines = useEnvironments().environments.length - 1; + if (!canLink || !offersLinkedEnvironments(config) || otherMachines < 2) return null; + return ( + +