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/AGENTS.md b/AGENTS.md index 4926c356754ed..6edcdea33126a 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/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 9aa43109e5a63..ec808cf6a83b6 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -391,7 +391,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); @@ -422,10 +427,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( @@ -436,17 +443,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"); @@ -464,6 +472,7 @@ describe("DesktopBackendConfiguration", () => { windowsArchivePath: archivePath, runtimeId: `sha256-${archiveHash}`, sha256: archiveHash, + t3Home, }, ]); assert.equal(probeCount, 1); @@ -479,12 +488,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)); }), @@ -507,6 +518,7 @@ describe("DesktopBackendConfiguration", () => { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin", + t3Home: null, }), }), }, @@ -539,10 +551,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, + }; }, }), }, @@ -561,28 +577,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, + }; }, }), }, @@ -599,23 +617,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, @@ -633,7 +645,6 @@ describe("DesktopBackendConfiguration", () => { assert.isFalse(failure.fatal); assert.equal(failure.retryLimit, 12); assert.include(failure.reason, "timed out"); - assert.deepEqual(invalidatedRuntimeIds, []); }), ); }); @@ -670,7 +681,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 811b25e0ec35c..15a52e3d6f50e 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -312,6 +312,7 @@ interface WslPreflightSuccess { readonly windowsEntryPath: string; readonly runtime: WslPreflightRuntime; readonly resolvedPath: string; + readonly t3Home: string | null; readonly runtimeId?: string; } @@ -431,7 +432,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", @@ -440,11 +441,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", @@ -452,20 +458,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 }; } } @@ -488,10 +495,6 @@ const runWslPreflight = Effect.fn("desktop.backendConfiguration.wslPreflight")(f : failedNodePty(nodePtyResult); } - if (stagedFailure?.runtimeId) { - yield* wslEnv.invalidateRuntime(runningDistro, stagedFailure.runtimeId); - } - return { _tag: "Ready", runningDistro, @@ -502,6 +505,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; }); @@ -769,13 +773,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 253643f19b9b9..92f2ec88b3bdb 100644 --- a/apps/desktop/src/i18n/translations/de.json +++ b/apps/desktop/src/i18n/translations/de.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "Über {appName}", "959e09151d75e25b": "Nach Updates suchen...", "0c753e71e2dca0d0": "Einstellungen...", + "d510731926e3ceed": "Dienste", "a9fad846cd549d96": "{appName} ausblenden", + "4bd5ee69cf690b2d": "Andere ausblenden", + "9d2c1417fb5f62ec": "Alle einblenden", "4b375f39bfce229e": "{appName} beenden", "83506e64878b7b48": "Datei", "b1f24efbd4e80225": "Entwicklertools schließen", "2c85ee66be8b81b5": "Fenster schließen", + "a4bf583403a4125b": "Beenden", + "35b959237c8b221c": "Beenden", "31bfa0ca146dc77f": "Bearbeiten", + "8a6e013aa2aba5df": "Widerrufen", + "ccae47bbef819830": "Wiederholen", + "228c600d0e283938": "Ausschneiden", + "30b1b78cffc780c2": "Kopieren", + "7aced881395f74eb": "Einsetzen", "ebf150404ed417d5": "Als Text einfügen", + "983c993d804f0b29": "Löschen", + "efb0c6cb3adb0d8d": "Alles auswählen", "660715835d05ddca": "Sprachausgabe", + "f0995859f0a14a6b": "Sprachausgabe starten", + "660e62472f879a5f": "Sprachausgabe stoppen", "25994350fd047a38": "Ansicht", "573a9e6b17f4e9e3": "Neu laden", "826cb3059ebc7cc3": "Neu laden erzwingen", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Originalgröße", "a4ad1b27fdc9032d": "Vergrößern", "df6ed2014f1737a8": "Verkleinern", + "50fe114d093a5bc7": "Vollbildmodus ein/aus", + "d8c6d6d9845353da": "Fenster", + "f184aa190588625e": "Minimieren", + "c20a9deaed71bd1c": "Zoomen", + "d207ba3a23f94223": "Alle nach vorne bringen", + "7a72a6736dd09f82": "Hilfe", "953979a4737f48fa": "Keine Vorschläge", "202e13f15a3dcd30": "Link kopieren", "8af79268f2349f4c": "E-Mail-Adresse kopieren", diff --git a/apps/desktop/src/i18n/translations/en.json b/apps/desktop/src/i18n/translations/en.json index 833aea465a406..964d6a7ed12f7 100644 --- a/apps/desktop/src/i18n/translations/en.json +++ b/apps/desktop/src/i18n/translations/en.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "About {appName}", "959e09151d75e25b": "Check for Updates...", "0c753e71e2dca0d0": "Settings...", + "d510731926e3ceed": "Services", "a9fad846cd549d96": "Hide {appName}", + "4bd5ee69cf690b2d": "Hide Others", + "9d2c1417fb5f62ec": "Show All", "4b375f39bfce229e": "Quit {appName}", "83506e64878b7b48": "File", "b1f24efbd4e80225": "Close Developer Tools", "2c85ee66be8b81b5": "Close Window", + "a4bf583403a4125b": "Exit", + "35b959237c8b221c": "Quit", "31bfa0ca146dc77f": "Edit", + "8a6e013aa2aba5df": "Undo", + "ccae47bbef819830": "Redo", + "228c600d0e283938": "Cut", + "30b1b78cffc780c2": "Copy", + "7aced881395f74eb": "Paste", "ebf150404ed417d5": "Paste as Text", + "983c993d804f0b29": "Delete", + "efb0c6cb3adb0d8d": "Select All", "660715835d05ddca": "Speech", + "f0995859f0a14a6b": "Start Speaking", + "660e62472f879a5f": "Stop Speaking", "25994350fd047a38": "View", "573a9e6b17f4e9e3": "Reload", "826cb3059ebc7cc3": "Force Reload", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Actual Size", "a4ad1b27fdc9032d": "Zoom In", "df6ed2014f1737a8": "Zoom Out", + "50fe114d093a5bc7": "Toggle Full Screen", + "d8c6d6d9845353da": "Window", + "f184aa190588625e": "Minimize", + "c20a9deaed71bd1c": "Zoom", + "d207ba3a23f94223": "Bring All to Front", + "7a72a6736dd09f82": "Help", "953979a4737f48fa": "No suggestions", "202e13f15a3dcd30": "Copy Link", "8af79268f2349f4c": "Copy Email Address", diff --git a/apps/desktop/src/i18n/translations/es.json b/apps/desktop/src/i18n/translations/es.json index 4a45d87e968b5..c1a64c21e241d 100644 --- a/apps/desktop/src/i18n/translations/es.json +++ b/apps/desktop/src/i18n/translations/es.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "Acerca de {appName}", "959e09151d75e25b": "Buscar actualizaciones...", "0c753e71e2dca0d0": "Ajustes...", + "d510731926e3ceed": "Servicios", "a9fad846cd549d96": "Ocultar {appName}", + "4bd5ee69cf690b2d": "Ocultar otros", + "9d2c1417fb5f62ec": "Mostrar todo", "4b375f39bfce229e": "Salir de {appName}", "83506e64878b7b48": "Archivo", "b1f24efbd4e80225": "Cerrar las herramientas de desarrollo", "2c85ee66be8b81b5": "Cerrar ventana", + "a4bf583403a4125b": "Salir", + "35b959237c8b221c": "Salir", "31bfa0ca146dc77f": "Edición", + "8a6e013aa2aba5df": "Deshacer", + "ccae47bbef819830": "Rehacer", + "228c600d0e283938": "Cortar", + "30b1b78cffc780c2": "Copiar", + "7aced881395f74eb": "Pegar", "ebf150404ed417d5": "Pegar como texto", + "983c993d804f0b29": "Eliminar", + "efb0c6cb3adb0d8d": "Seleccionar todo", "660715835d05ddca": "Voz", + "f0995859f0a14a6b": "Iniciar lectura", + "660e62472f879a5f": "Detener lectura", "25994350fd047a38": "Ver", "573a9e6b17f4e9e3": "Recargar", "826cb3059ebc7cc3": "Forzar recarga", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Tamaño real", "a4ad1b27fdc9032d": "Acercar", "df6ed2014f1737a8": "Alejar", + "50fe114d093a5bc7": "Activar/desactivar pantalla completa", + "d8c6d6d9845353da": "Ventana", + "f184aa190588625e": "Minimizar", + "c20a9deaed71bd1c": "Zoom", + "d207ba3a23f94223": "Traer todo al frente", + "7a72a6736dd09f82": "Ayuda", "953979a4737f48fa": "Sin sugerencias", "202e13f15a3dcd30": "Copiar enlace", "8af79268f2349f4c": "Copiar dirección de correo", diff --git a/apps/desktop/src/i18n/translations/fr.json b/apps/desktop/src/i18n/translations/fr.json index 5c31d472f5d70..4a0376ba9c94a 100644 --- a/apps/desktop/src/i18n/translations/fr.json +++ b/apps/desktop/src/i18n/translations/fr.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "À propos de {appName}", "959e09151d75e25b": "Rechercher des mises à jour...", "0c753e71e2dca0d0": "Paramètres...", + "d510731926e3ceed": "Services", "a9fad846cd549d96": "Masquer {appName}", + "4bd5ee69cf690b2d": "Masquer les autres", + "9d2c1417fb5f62ec": "Tout afficher", "4b375f39bfce229e": "Quitter {appName}", "83506e64878b7b48": "Fichier", "b1f24efbd4e80225": "Fermer les outils de développement", "2c85ee66be8b81b5": "Fermer la fenêtre", + "a4bf583403a4125b": "Quitter", + "35b959237c8b221c": "Quitter", "31bfa0ca146dc77f": "Édition", + "8a6e013aa2aba5df": "Annuler", + "ccae47bbef819830": "Rétablir", + "228c600d0e283938": "Couper", + "30b1b78cffc780c2": "Copier", + "7aced881395f74eb": "Coller", "ebf150404ed417d5": "Coller en texte brut", + "983c993d804f0b29": "Supprimer", + "efb0c6cb3adb0d8d": "Tout sélectionner", "660715835d05ddca": "Parole", + "f0995859f0a14a6b": "Démarrer la lecture", + "660e62472f879a5f": "Arrêter la lecture", "25994350fd047a38": "Présentation", "573a9e6b17f4e9e3": "Recharger", "826cb3059ebc7cc3": "Forcer le rechargement", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Taille réelle", "a4ad1b27fdc9032d": "Zoom avant", "df6ed2014f1737a8": "Zoom arrière", + "50fe114d093a5bc7": "Activer/désactiver le plein écran", + "d8c6d6d9845353da": "Fenêtre", + "f184aa190588625e": "Réduire", + "c20a9deaed71bd1c": "Zoom", + "d207ba3a23f94223": "Tout ramener au premier plan", + "7a72a6736dd09f82": "Aide", "953979a4737f48fa": "Aucune suggestion", "202e13f15a3dcd30": "Copier le lien", "8af79268f2349f4c": "Copier l’adresse e-mail", diff --git a/apps/desktop/src/i18n/translations/ja.json b/apps/desktop/src/i18n/translations/ja.json index 867b271262724..4b5db0e253a42 100644 --- a/apps/desktop/src/i18n/translations/ja.json +++ b/apps/desktop/src/i18n/translations/ja.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "{appName} について", "959e09151d75e25b": "更新を確認...", "0c753e71e2dca0d0": "設定...", + "d510731926e3ceed": "サービス", "a9fad846cd549d96": "{appName} を隠す", + "4bd5ee69cf690b2d": "ほかを隠す", + "9d2c1417fb5f62ec": "すべてを表示", "4b375f39bfce229e": "{appName} を終了", "83506e64878b7b48": "ファイル", "b1f24efbd4e80225": "開発者ツールを閉じる", "2c85ee66be8b81b5": "ウィンドウを閉じる", + "a4bf583403a4125b": "終了", + "35b959237c8b221c": "終了", "31bfa0ca146dc77f": "編集", + "8a6e013aa2aba5df": "取り消す", + "ccae47bbef819830": "やり直す", + "228c600d0e283938": "カット", + "30b1b78cffc780c2": "コピー", + "7aced881395f74eb": "ペースト", "ebf150404ed417d5": "テキストとして貼り付け", + "983c993d804f0b29": "削除", + "efb0c6cb3adb0d8d": "すべてを選択", "660715835d05ddca": "スピーチ", + "f0995859f0a14a6b": "読み上げを開始", + "660e62472f879a5f": "読み上げを停止", "25994350fd047a38": "表示", "573a9e6b17f4e9e3": "再読み込み", "826cb3059ebc7cc3": "強制再読み込み", @@ -95,6 +109,12 @@ "a7ab66e786347118": "実際のサイズ", "a4ad1b27fdc9032d": "拡大", "df6ed2014f1737a8": "縮小", + "50fe114d093a5bc7": "フルスクリーンに切り替え", + "d8c6d6d9845353da": "ウインドウ", + "f184aa190588625e": "しまう", + "c20a9deaed71bd1c": "拡大/縮小", + "d207ba3a23f94223": "すべてを手前に移動", + "7a72a6736dd09f82": "ヘルプ", "953979a4737f48fa": "候補はありません", "202e13f15a3dcd30": "リンクをコピー", "8af79268f2349f4c": "メールアドレスをコピー", diff --git a/apps/desktop/src/i18n/translations/ko.json b/apps/desktop/src/i18n/translations/ko.json index 7c15523447278..ccebba3366e84 100644 --- a/apps/desktop/src/i18n/translations/ko.json +++ b/apps/desktop/src/i18n/translations/ko.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "{appName} 정보", "959e09151d75e25b": "업데이트 확인...", "0c753e71e2dca0d0": "설정...", + "d510731926e3ceed": "서비스", "a9fad846cd549d96": "{appName} 가리기", + "4bd5ee69cf690b2d": "기타 가리기", + "9d2c1417fb5f62ec": "모두 보기", "4b375f39bfce229e": "{appName} 종료", "83506e64878b7b48": "파일", "b1f24efbd4e80225": "개발자 도구 닫기", "2c85ee66be8b81b5": "창 닫기", + "a4bf583403a4125b": "종료", + "35b959237c8b221c": "종료", "31bfa0ca146dc77f": "편집", + "8a6e013aa2aba5df": "실행 취소", + "ccae47bbef819830": "실행 복귀", + "228c600d0e283938": "오려두기", + "30b1b78cffc780c2": "복사하기", + "7aced881395f74eb": "붙여넣기", "ebf150404ed417d5": "텍스트로 붙여넣기", + "983c993d804f0b29": "삭제", + "efb0c6cb3adb0d8d": "전체 선택", "660715835d05ddca": "말하기", + "f0995859f0a14a6b": "말하기 시작", + "660e62472f879a5f": "말하기 중지", "25994350fd047a38": "보기", "573a9e6b17f4e9e3": "새로 고침", "826cb3059ebc7cc3": "강제 새로 고침", @@ -95,6 +109,12 @@ "a7ab66e786347118": "실제 크기", "a4ad1b27fdc9032d": "확대", "df6ed2014f1737a8": "축소", + "50fe114d093a5bc7": "전체 화면 전환", + "d8c6d6d9845353da": "윈도우", + "f184aa190588625e": "최소화", + "c20a9deaed71bd1c": "확대/축소", + "d207ba3a23f94223": "모두 앞으로 가져오기", + "7a72a6736dd09f82": "도움말", "953979a4737f48fa": "제안 없음", "202e13f15a3dcd30": "링크 복사", "8af79268f2349f4c": "이메일 주소 복사", diff --git a/apps/desktop/src/i18n/translations/pt-BR.json b/apps/desktop/src/i18n/translations/pt-BR.json index 4f3460638c22a..11e80a2f667bb 100644 --- a/apps/desktop/src/i18n/translations/pt-BR.json +++ b/apps/desktop/src/i18n/translations/pt-BR.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "Sobre o {appName}", "959e09151d75e25b": "Verificar atualizações...", "0c753e71e2dca0d0": "Configurações...", + "d510731926e3ceed": "Serviços", "a9fad846cd549d96": "Ocultar {appName}", + "4bd5ee69cf690b2d": "Ocultar outros", + "9d2c1417fb5f62ec": "Mostrar tudo", "4b375f39bfce229e": "Sair do {appName}", "83506e64878b7b48": "Arquivo", "b1f24efbd4e80225": "Fechar ferramentas do desenvolvedor", "2c85ee66be8b81b5": "Fechar janela", + "a4bf583403a4125b": "Sair", + "35b959237c8b221c": "Encerrar", "31bfa0ca146dc77f": "Editar", + "8a6e013aa2aba5df": "Desfazer", + "ccae47bbef819830": "Refazer", + "228c600d0e283938": "Recortar", + "30b1b78cffc780c2": "Copiar", + "7aced881395f74eb": "Colar", "ebf150404ed417d5": "Colar como texto", + "983c993d804f0b29": "Apagar", + "efb0c6cb3adb0d8d": "Selecionar tudo", "660715835d05ddca": "Fala", + "f0995859f0a14a6b": "Iniciar fala", + "660e62472f879a5f": "Parar fala", "25994350fd047a38": "Exibir", "573a9e6b17f4e9e3": "Recarregar", "826cb3059ebc7cc3": "Forçar recarregamento", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Tamanho real", "a4ad1b27fdc9032d": "Aumentar zoom", "df6ed2014f1737a8": "Diminuir zoom", + "50fe114d093a5bc7": "Alternar tela cheia", + "d8c6d6d9845353da": "Janela", + "f184aa190588625e": "Minimizar", + "c20a9deaed71bd1c": "Zoom", + "d207ba3a23f94223": "Trazer tudo para a frente", + "7a72a6736dd09f82": "Ajuda", "953979a4737f48fa": "Nenhuma sugestão", "202e13f15a3dcd30": "Copiar link", "8af79268f2349f4c": "Copiar endereço de e-mail", diff --git a/apps/desktop/src/i18n/translations/ru.json b/apps/desktop/src/i18n/translations/ru.json index 3e8f2fa9fed06..cdcf02d0648dd 100644 --- a/apps/desktop/src/i18n/translations/ru.json +++ b/apps/desktop/src/i18n/translations/ru.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "О приложении {appName}", "959e09151d75e25b": "Проверить обновления...", "0c753e71e2dca0d0": "Настройки...", + "d510731926e3ceed": "Службы", "a9fad846cd549d96": "Скрыть {appName}", + "4bd5ee69cf690b2d": "Скрыть остальные", + "9d2c1417fb5f62ec": "Показать все", "4b375f39bfce229e": "Выйти из {appName}", "83506e64878b7b48": "Файл", "b1f24efbd4e80225": "Закрыть инструменты разработчика", "2c85ee66be8b81b5": "Закрыть окно", + "a4bf583403a4125b": "Выход", + "35b959237c8b221c": "Завершить", "31bfa0ca146dc77f": "Правка", + "8a6e013aa2aba5df": "Отменить", + "ccae47bbef819830": "Повторить", + "228c600d0e283938": "Вырезать", + "30b1b78cffc780c2": "Копировать", + "7aced881395f74eb": "Вставить", "ebf150404ed417d5": "Вставить как текст", + "983c993d804f0b29": "Удалить", + "efb0c6cb3adb0d8d": "Выбрать все", "660715835d05ddca": "Речь", + "f0995859f0a14a6b": "Начать чтение", + "660e62472f879a5f": "Остановить чтение", "25994350fd047a38": "Вид", "573a9e6b17f4e9e3": "Перезагрузить", "826cb3059ebc7cc3": "Принудительная перезагрузка", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Фактический размер", "a4ad1b27fdc9032d": "Увеличить", "df6ed2014f1737a8": "Уменьшить", + "50fe114d093a5bc7": "Полноэкранный режим", + "d8c6d6d9845353da": "Окно", + "f184aa190588625e": "Свернуть", + "c20a9deaed71bd1c": "Масштаб", + "d207ba3a23f94223": "Все окна на передний план", + "7a72a6736dd09f82": "Справка", "953979a4737f48fa": "Нет вариантов", "202e13f15a3dcd30": "Копировать ссылку", "8af79268f2349f4c": "Копировать адрес электронной почты", diff --git a/apps/desktop/src/i18n/translations/sv.json b/apps/desktop/src/i18n/translations/sv.json index e8ac486b64242..e2a204965fec2 100644 --- a/apps/desktop/src/i18n/translations/sv.json +++ b/apps/desktop/src/i18n/translations/sv.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "Om {appName}", "959e09151d75e25b": "Sök efter uppdateringar...", "0c753e71e2dca0d0": "Inställningar...", + "d510731926e3ceed": "Tjänster", "a9fad846cd549d96": "Dölj {appName}", + "4bd5ee69cf690b2d": "Göm andra", + "9d2c1417fb5f62ec": "Visa alla", "4b375f39bfce229e": "Avsluta {appName}", "83506e64878b7b48": "Arkiv", "b1f24efbd4e80225": "Stäng utvecklarverktyg", "2c85ee66be8b81b5": "Stäng fönster", + "a4bf583403a4125b": "Avsluta", + "35b959237c8b221c": "Avsluta", "31bfa0ca146dc77f": "Redigera", + "8a6e013aa2aba5df": "Ångra", + "ccae47bbef819830": "Gör om", + "228c600d0e283938": "Klipp ut", + "30b1b78cffc780c2": "Kopiera", + "7aced881395f74eb": "Klistra in", "ebf150404ed417d5": "Klistra in som text", + "983c993d804f0b29": "Radera", + "efb0c6cb3adb0d8d": "Markera allt", "660715835d05ddca": "Tal", + "f0995859f0a14a6b": "Börja tala", + "660e62472f879a5f": "Sluta tala", "25994350fd047a38": "Visa", "573a9e6b17f4e9e3": "Läs in igen", "826cb3059ebc7cc3": "Tvinga omladdning", @@ -95,6 +109,12 @@ "a7ab66e786347118": "Verklig storlek", "a4ad1b27fdc9032d": "Zooma in", "df6ed2014f1737a8": "Zooma ut", + "50fe114d093a5bc7": "Växla helskärm", + "d8c6d6d9845353da": "Fönster", + "f184aa190588625e": "Minimera", + "c20a9deaed71bd1c": "Zooma", + "d207ba3a23f94223": "Lägg alla överst", + "7a72a6736dd09f82": "Hjälp", "953979a4737f48fa": "Inga förslag", "202e13f15a3dcd30": "Kopiera länk", "8af79268f2349f4c": "Kopiera e-postadress", diff --git a/apps/desktop/src/i18n/translations/zh.json b/apps/desktop/src/i18n/translations/zh.json index ecee6a4ab13ae..6a89cd600c37a 100644 --- a/apps/desktop/src/i18n/translations/zh.json +++ b/apps/desktop/src/i18n/translations/zh.json @@ -80,14 +80,28 @@ "835247f842c92bc9": "关于 {appName}", "959e09151d75e25b": "检查更新…", "0c753e71e2dca0d0": "设置…", + "d510731926e3ceed": "服务", "a9fad846cd549d96": "隐藏 {appName}", + "4bd5ee69cf690b2d": "隐藏其他", + "9d2c1417fb5f62ec": "全部显示", "4b375f39bfce229e": "退出 {appName}", "83506e64878b7b48": "文件", "b1f24efbd4e80225": "关闭开发者工具", "2c85ee66be8b81b5": "关闭窗口", + "a4bf583403a4125b": "退出", + "35b959237c8b221c": "退出", "31bfa0ca146dc77f": "编辑", + "8a6e013aa2aba5df": "撤销", + "ccae47bbef819830": "重做", + "228c600d0e283938": "剪切", + "30b1b78cffc780c2": "复制", + "7aced881395f74eb": "粘贴", "ebf150404ed417d5": "粘贴为纯文本", + "983c993d804f0b29": "删除", + "efb0c6cb3adb0d8d": "全选", "660715835d05ddca": "语音", + "f0995859f0a14a6b": "开始朗读", + "660e62472f879a5f": "停止朗读", "25994350fd047a38": "查看", "573a9e6b17f4e9e3": "重新加载", "826cb3059ebc7cc3": "强制重新加载", @@ -95,6 +109,12 @@ "a7ab66e786347118": "实际大小", "a4ad1b27fdc9032d": "放大", "df6ed2014f1737a8": "缩小", + "50fe114d093a5bc7": "切换全屏", + "d8c6d6d9845353da": "窗口", + "f184aa190588625e": "最小化", + "c20a9deaed71bd1c": "缩放", + "d207ba3a23f94223": "前置全部窗口", + "7a72a6736dd09f82": "帮助", "953979a4737f48fa": "无建议", "202e13f15a3dcd30": "复制链接", "8af79268f2349f4c": "复制邮箱地址", diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index f8be524ad188f..878d71dcfe88c 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -128,6 +128,11 @@ 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"; 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/preload.ts b/apps/desktop/src/preload.ts index 82e3903a6ff8d..7bbff96be61fc 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -466,6 +466,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/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 46004ca302295..8b2c4317bd20f 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -368,4 +368,29 @@ describe("DesktopApplicationMenu", () => { assert.include(`${dialog.title ?? ""} ${dialog.message} ${dialog.detail ?? ""}`, "0.1.7"); }), ); + + it.effect("labels every role item so the menu follows the UI language", () => + Effect.gen(function* () { + // Electron's role defaults are English on every platform, so each role item needs a label. + for (const platform of ["darwin", "linux", "win32"] as const) { + const applicationMenuTemplate = + yield* Deferred.make(); + yield* configureMenu(yield* Deferred.make(), applicationMenuTemplate, { + platform, + }); + + const unlabeled: string[] = []; + const collect = (template: readonly Electron.MenuItemConstructorOptions[]) => { + for (const item of template) { + if (item.role !== undefined && typeof item.label !== "string") { + unlabeled.push(item.role); + } + if (Array.isArray(item.submenu)) collect(item.submenu); + } + }; + collect(yield* Deferred.await(applicationMenuTemplate)); + assert.deepStrictEqual(unlabeled, [], platform); + } + }), + ); }); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 4c5475f8a6023..392208d5b54c9 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -230,11 +230,14 @@ export const make = Effect.gen(function* () { click: settingsClick, }, { type: "separator" }, - { role: "services" }, + { role: "services", label: m(msg("Services", { $context: "macOS app menu item" })) }, { type: "separator" }, { role: "hide", label: m(msg("Hide {appName}"), { appName: environment.displayName }) }, - { role: "hideOthers" }, - { role: "unhide" }, + { role: "hideOthers", label: m(msg("Hide Others")) }, + { + role: "unhide", + label: m(msg("Show All", { $context: "macOS app menu item, shows hidden apps" })), + }, { type: "separator" }, { role: "quit", label: m(msg("Quit {appName}"), { appName: environment.displayName }) }, ], @@ -269,32 +272,41 @@ export const make = Effect.gen(function* () { // Cmd/Ctrl+W belongs to the renderer's tab close; it must never close the window. environment.platform === "darwin" ? { label: m(msg("Close Window")), click: (_item, window) => window?.close() } - : { role: "quit" }, + : { + role: "quit", + label: + environment.platform === "win32" + ? m(msg("Exit", { $context: "File menu item, quits the app" })) + : m(msg("Quit")), + }, ], }, { label: m(msg("Edit", { $context: "menu bar title" })), submenu: [ - { role: "undo" }, - { role: "redo" }, + { role: "undo", label: m(msg("Undo", { $context: "Edit menu item" })) }, + { role: "redo", label: m(msg("Redo", { $context: "Edit menu item" })) }, { type: "separator" }, - { role: "cut" }, - { role: "copy" }, - { role: "paste" }, + { role: "cut", label: m(msg("Cut", { $context: "Edit menu item" })) }, + { role: "copy", label: m(msg("Copy", { $context: "Edit menu item" })) }, + { role: "paste", label: m(msg("Paste", { $context: "Edit menu item" })) }, { label: m(msg("Paste as Text")), accelerator: "CmdOrCtrl+Shift+V", click: pasteAsTextClick, }, - { role: "delete" }, + { role: "delete", label: m(msg("Delete", { $context: "Edit menu item" })) }, { type: "separator" }, - { role: "selectAll" }, + { role: "selectAll", label: m(msg("Select All", { $context: "Edit menu item" })) }, ...(environment.platform === "darwin" ? [ { type: "separator" as const }, { label: m(msg("Speech", { $context: "menu, text-to-speech" })), - submenu: [{ role: "startSpeaking" as const }, { role: "stopSpeaking" as const }], + submenu: [ + { role: "startSpeaking" as const, label: m(msg("Start Speaking")) }, + { role: "stopSpeaking" as const, label: m(msg("Stop Speaking")) }, + ], }, ] : []), @@ -359,22 +371,30 @@ export const make = Effect.gen(function* () { click: zoomClick("out"), }, { type: "separator" }, - { role: "togglefullscreen" }, + { role: "togglefullscreen", label: m(msg("Toggle Full Screen")) }, ], }, { // Electron's default Window submenu adds a Ctrl+W close role off macOS. role: "windowMenu", + label: m(msg("Window", { $context: "menu bar title" })), submenu: [ - { role: "minimize" }, - { role: "zoom" }, + { role: "minimize", label: m(msg("Minimize", { $context: "Window menu item" })) }, + { + role: "zoom", + label: m(msg("Zoom", { $context: "Window menu item, resizes the window" })), + }, ...(environment.platform === "darwin" - ? [{ type: "separator" as const }, { role: "front" as const }] + ? [ + { type: "separator" as const }, + { role: "front" as const, label: m(msg("Bring All to Front")) }, + ] : []), ], }, { role: "help", + label: m(msg("Help", { $context: "menu bar title" })), submenu: [ { label: m(msg("Check for Updates...")), diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 556853a6cc5f8..741e03b79b3c2 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -717,10 +717,26 @@ export const make = Effect.gen(function* () { } menuTemplate.push( - { role: "cut", enabled: params.editFlags.canCut }, - { role: "copy", enabled: params.editFlags.canCopy }, - { role: "paste", enabled: params.editFlags.canPaste }, - { role: "selectAll", enabled: params.editFlags.canSelectAll }, + { + role: "cut", + label: m(msg("Cut", { $context: "Edit menu item" })), + enabled: params.editFlags.canCut, + }, + { + role: "copy", + label: m(msg("Copy", { $context: "Edit menu item" })), + enabled: params.editFlags.canCopy, + }, + { + role: "paste", + label: m(msg("Paste", { $context: "Edit menu item" })), + enabled: params.editFlags.canPaste, + }, + { + role: "selectAll", + label: m(msg("Select All", { $context: "Edit menu item" })), + enabled: params.editFlags.canSelectAll, + }, ); void runPromise( 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/marketing/src/i18n/de.ts b/apps/marketing/src/i18n/de.ts index 4bed319eb437f..c90b93c467e84 100644 --- a/apps/marketing/src/i18n/de.ts +++ b/apps/marketing/src/i18n/de.ts @@ -34,7 +34,7 @@ export const de: Messages = { screenshotAlt: "T3 Code führt Subagenten von Claude, Codex, Muse und Gemini in einem Thread aus", endorsementsTitle: "Toleriert von über {users} Devs", - endorsementsSub: "Manche haben sogar darüber getwittert.", + endorsementsSub: "Ein paar haben sogar Nettes getwittert.", endorsementsLabel: "Stimmen von Entwicklern", readPost: "Beitrag von {handle} auf X lesen", harnessTitle: "Bring dein eigenes Abo mit", @@ -76,7 +76,7 @@ export const de: Messages = { browseSource: "Quellcode ansehen", ctaTitle: "Deine Agenten verdienen Besseres als ein Terminal.", ctaSub: - "T3 Code ist kostenlos, Open Source und schnell. Installier es, binde das Tool ein, für das du schon zahlst, und lass deine Agenten loslegen.", + "T3 Code ist kostenlos, Open Source und schnell. Installier es, verbinde die Agenten, für die du schon zahlst, und lass sie direkt loslegen.", otherPlatforms: "Andere Plattformen", }, download: { diff --git a/apps/marketing/src/i18n/es.ts b/apps/marketing/src/i18n/es.ts index 90fcf79bd9429..2c7e64cfaee06 100644 --- a/apps/marketing/src/i18n/es.ts +++ b/apps/marketing/src/i18n/es.ts @@ -34,7 +34,7 @@ export const es: Messages = { alsoOnPhone: "También en tu teléfono:", screenshotAlt: "T3 Code ejecutando subagentes de Claude, Codex, Muse y Gemini en un mismo hilo", endorsementsTitle: "Tolerado por más de {users} desarrolladores", - endorsementsSub: "Algunos hasta tuitearon al respecto.", + endorsementsSub: "Algunos hasta tuitearon cosas buenas.", endorsementsLabel: "Opiniones de desarrolladores", readPost: "Leer la publicación de {handle} en X", harnessTitle: "Trae tu propia suscripción", @@ -42,7 +42,7 @@ export const es: Messages = { "T3 Code no revende tokens. Conecta Claude Code, Codex, Antigravity, OpenCode, Cursor o Grok con las credenciales que ya tienes. Nosotros los orquestamos, tú conservas tu plan.", googleSignIn: "Inicio de sesión con Google", harnessPoints: [ - "Sin reventa de claves. Sin límites de cuota.", + "Sin venta de claves. Sin límites de cuota.", "Cambia de modelo a mitad del hilo.", "Nuevas integraciones cada semana.", ], diff --git a/apps/marketing/src/i18n/fr.ts b/apps/marketing/src/i18n/fr.ts index dd5885372efaf..b692ee6759564 100644 --- a/apps/marketing/src/i18n/fr.ts +++ b/apps/marketing/src/i18n/fr.ts @@ -34,7 +34,7 @@ export const fr: Messages = { screenshotAlt: "T3 Code exécutant des sous-agents Claude, Codex, Muse et Gemini dans un même fil", endorsementsTitle: "Toléré par plus de {users} devs", - endorsementsSub: "Certains en ont même parlé sur X.", + endorsementsSub: "Certains en ont même dit du bien sur X.", endorsementsLabel: "Avis de développeurs", readPost: "Lire le post de {handle} sur X", harnessTitle: "Apportez votre abonnement", diff --git a/apps/marketing/src/i18n/ja.ts b/apps/marketing/src/i18n/ja.ts index 839ff92e051b4..f1136d97c8195 100644 --- a/apps/marketing/src/i18n/ja.ts +++ b/apps/marketing/src/i18n/ja.ts @@ -3,10 +3,9 @@ import type { Messages } from "./en"; export const ja: Messages = { layout: { defaultTitle: "T3 Code", - defaultDescription: - "T3 Code。コーディングエージェントのためのオープンソースのコントロールプレーン。", + defaultDescription: "T3 Code。オープンソースのコーディングエージェント制御プレーン。", socialImageAlt: - "T3 Code:コーディングエージェントのためのオープンソースのコントロールプレーン。Claude Code、Codex、Cursor、OpenCode、Grok、Antigravity に対応。", + "T3 Code:オープンソースのコーディングエージェント制御プレーン。Claude Code、Codex、Cursor、OpenCode、Grok、Antigravity に対応。", homeLabel: "T3 Code ホーム", download: "ダウンロード", starsLabel: "GitHub で T3 Code にスターを付ける({stars} スター)", @@ -20,9 +19,9 @@ export const ja: Messages = { security: "セキュリティ", }, home: { - title: "T3 Code | コーディングエージェントのためのオープンソースのコントロールプレーン", - description: "T3 Code。コーディングエージェントのためのオープンソースのコントロールプレーン。", - heroTitle: ["コーディングエージェントの", "オープンソース", "コントロールプレーン。"], + title: "T3 Code | オープンソースのコーディングエージェント制御プレーン", + description: "T3 Code。オープンソースのコーディングエージェント制御プレーン。", + heroTitle: ["オープンソースの", "コーディングエージェント", "制御プレーン。"], heroSub: "Claude Code、Codex、Antigravity、OpenCode、Cursor、Grok をひとつの画面からオーケストレーション。サブスクリプションは手持ちのものをそのまま。まるごとフォークも自由です。", downloadForMac: "macOS 版をダウンロード", @@ -35,15 +34,15 @@ export const ja: Messages = { screenshotAlt: "ひとつのスレッドで Claude、Codex、Muse、Gemini のサブエージェントを動かす T3 Code", endorsementsTitle: "{users}人以上の開発者たちが「悪くない」と言っています", - endorsementsSub: "ツイートまでしてくれた人もいます。", + endorsementsSub: "温かいツイートまでいただいています。", endorsementsLabel: "開発者の声", readPost: "X で {handle} の投稿を読む", harnessTitle: "サブスクは持ち込みで", harnessBody: - "T3 Code はトークンを転売しません。Claude Code、Codex、Antigravity、OpenCode、Cursor、Grok を、すでに持っている認証情報でつなぐだけ。オーケストレーションは私たちに任せて、プランは今のままで。", + "T3 Code はトークンの上乗せ販売を行いません。すでにお持ちの認証情報で、Claude Code、Codex、Antigravity、OpenCode、Cursor、Grok をつなぐだけ。T3 Code は制御プレーンのみを提供。プランは今のままで。", googleSignIn: "Google でサインイン", harnessPoints: [ - "キーの転売なし。使用量の上限なし。", + "キーの再販なし。使用量の上限なし。", "スレッドの途中でモデルを切り替え。", "対応エージェントは毎週追加。", ], @@ -75,9 +74,9 @@ export const ja: Messages = { stars: "{stars} スター", forkOnGithub: "GitHub でフォーク", browseSource: "ソースを見る", - ctaTitle: "あなたのエージェントに、ターミナルだけではもったいない。", + ctaTitle: "あなたのエージェントに、ターミナルよりふさわしい場所を。", ctaSub: - "T3 Code は無料、オープンソース、そして高速。インストールして、契約中のツールをつなぐだけ。あとはエージェントにおまかせ。", + "T3 Code は無料、オープンソースで、高速です。インストールしたら、お使いのハーネスをつなぐだけ。すぐに仕事に取り掛かれます。", otherPlatforms: "ほかのプラットフォーム", }, download: { diff --git a/apps/marketing/src/i18n/ko.ts b/apps/marketing/src/i18n/ko.ts index a9cbb1c8e81f3..6b5faee5ab299 100644 --- a/apps/marketing/src/i18n/ko.ts +++ b/apps/marketing/src/i18n/ko.ts @@ -21,7 +21,7 @@ export const ko: Messages = { home: { title: "T3 Code | 코딩 에이전트를 위한 오픈 소스 컨트롤 플레인", description: "T3 Code. 코딩 에이전트를 위한 오픈 소스 컨트롤 플레인.", - heroTitle: ["코딩 에이전트용", "오픈 소스", "컨트롤 플레인."], + heroTitle: ["코딩 에이전트를 위한", "오픈 소스", "컨트롤 플레인."], heroSub: "Claude Code, Codex, Antigravity, OpenCode, Cursor, Grok을 한 화면에서 오케스트레이션하세요. 구독은 쓰던 그대로. 통째로 포크하세요.", downloadForMac: "macOS용 다운로드", @@ -38,7 +38,7 @@ export const ko: Messages = { readPost: "X에서 {handle}님의 게시물 읽기", harnessTitle: "쓰던 구독 그대로", harnessBody: - "T3 Code는 토큰을 되팔지 않습니다. 이미 쓰고 있는 계정으로 Claude Code, Codex, Antigravity, OpenCode, Cursor, Grok을 연결하세요. 오케스트레이션은 저희가, 요금제는 그대로.", + "T3 Code는 토큰을 재판매하지 않습니다. 이미 쓰고 있는 계정으로 Claude Code, Codex, Antigravity, OpenCode, Cursor, Grok을 연결하세요. 오케스트레이션은 저희가, 요금제는 그대로.", googleSignIn: "Google 로그인", harnessPoints: [ "키 재판매 없음. 사용량 한도 없음.", @@ -70,9 +70,9 @@ export const ko: Messages = { stars: "스타 {stars}", forkOnGithub: "GitHub에서 포크", browseSource: "소스 보기", - ctaTitle: "에이전트를 터미널에만 두기엔 아깝습니다.", + ctaTitle: "에이전트에게 터미널보다 나은 작업 공간을.", ctaSub: - "T3 Code는 무료이고, 오픈 소스이며, 빠릅니다. 설치하고, 이미 구독 중인 서비스를 연결한 뒤, 에이전트에게 일을 맡기세요.", + "T3 Code는 무료이고, 오픈 소스이며, 빠릅니다. 설치하고 이미 쓰고 있는 에이전트를 연결하면 바로 일을 시작합니다.", otherPlatforms: "다른 플랫폼", }, download: { diff --git a/apps/marketing/src/i18n/pt-BR.ts b/apps/marketing/src/i18n/pt-BR.ts index 302bf1651c769..7212f13c6732a 100644 --- a/apps/marketing/src/i18n/pt-BR.ts +++ b/apps/marketing/src/i18n/pt-BR.ts @@ -76,7 +76,7 @@ export const ptBR: Messages = { browseSource: "Ver o código", ctaTitle: "Seus agentes merecem mais do que um terminal.", ctaSub: - "O T3 Code é gratuito, open source e rápido. Instale, conecte o provedor que você já paga para usar e deixe seus agentes trabalharem.", + "O T3 Code é gratuito, open source e rápido. Instale, conecte o provedor que você já paga para usar e coloque seus agentes para trabalhar.", otherPlatforms: "Outras plataformas", }, download: { diff --git a/apps/marketing/src/i18n/ru.ts b/apps/marketing/src/i18n/ru.ts index ef5757ee1a6ab..39e564abfdec0 100644 --- a/apps/marketing/src/i18n/ru.ts +++ b/apps/marketing/src/i18n/ru.ts @@ -72,7 +72,7 @@ export const ru: Messages = { browseSource: "Исходный код", ctaTitle: "Ваши агенты заслуживают лучшего, чем терминал.", ctaSub: - "T3 Code бесплатный, открытый и быстрый. Установите его, подключите провайдера, которому уже платите, и дайте агентам поработать.", + "T3 Code бесплатный, открытый и быстрый. Установите его, подключите провайдера, которому уже платите, и агенты сразу возьмутся за дело.", otherPlatforms: "Другие платформы", }, download: { 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/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/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" ? ( ({ + 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/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 ? ( void Linking.openURL(moreInfoUrl).catch(() => undefined)} + onPress={() => void tryOpenExternalUrl(moreInfoUrl)} /> ) : null} 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 ( + +