diff --git a/.github/fork/upstream-tag b/.github/fork/upstream-tag index 6d46f655e4f42..8de4a8fa2abd7 100644 --- a/.github/fork/upstream-tag +++ b/.github/fork/upstream-tag @@ -1 +1 @@ -v0.1.11-nightly.20261119.4928 +v0.1.11-nightly.20261120.4979 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 feb902d4fff23..ccaaa123dad7b 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/src/electron/ElectronHttpExecutor.test.ts b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts index 0a37f621dd601..fb7e947019bb4 100644 --- a/apps/desktop/src/electron/ElectronHttpExecutor.test.ts +++ b/apps/desktop/src/electron/ElectronHttpExecutor.test.ts @@ -1,8 +1,33 @@ // @effect-diagnostics nodeBuiltinImport:off -- Fake Electron net request and response emitters. +import * as NodeCrypto from "node:crypto"; import * as NodeEvents from "node:events"; +import * as NodeFS from "node:fs"; +import * as NodeModule from "node:module"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import * as NodeStream from "node:stream"; import { ElectronHttpExecutor } from "electron-updater/out/electronHttpExecutor.js"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +type DownloadOptions = Parameters[2]; +type FakeRequest = NodeEvents.EventEmitter & { abort: () => void }; + +// electron-updater is CommonJS, so a spy goes on the module object its require() returns. +const fsModule = NodeModule.createRequire(import.meta.url)("node:fs") as typeof NodeFS; +const openForReading = fsModule.createReadStream; +// electron-updater's own dependency, which apps/desktop does not declare. +const { CancellationToken, CancellationError } = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("electron-updater"), +)("builder-util-runtime") as { + CancellationToken: new () => DownloadOptions["cancellationToken"]; + CancellationError: new () => Error; +}; +const RELEASE = "hello world"; +// Larger than a file stream's buffer, so its "drain" marks a write of it as committed to disk. +const PREFIX = "a".repeat(1 << 20); +const LARGE_RELEASE = `${PREFIX}world`; +const RESUMED_RANGE = `bytes ${PREFIX.length}-${LARGE_RELEASE.length - 1}/${LARGE_RELEASE.length}`; + function startRequest() { const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn() }); const response = new NodeEvents.EventEmitter(); @@ -14,6 +39,103 @@ function startRequest() { return { request, response, reject }; } +// The temp update file already holds `onDisk`, as the differential downloader's output can. +function startDownload(onDisk: string, release = RELEASE) { + const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "electron-http-executor-")); + const destination = NodePath.join(dir, "update.AppImage"); + NodeFS.writeFileSync(destination, onDisk); + const createWriteStream = vi.spyOn(fsModule, "createWriteStream"); + const createReadStream = vi.spyOn(fsModule, "createReadStream"); + const created = new NodeEvents.EventEmitter(); + let requestCount = 0; + const executor = new ElectronHttpExecutor(); + executor.createRequest = (options: { headers: Record }, callback) => { + const request = Object.assign(new NodeEvents.EventEmitter(), { abort: vi.fn(), end: vi.fn() }); + request.on("response", callback); + requestCount++; + created.emit("request", { request, headers: options.headers }); + return request as unknown as Electron.ClientRequest; + }; + const cancellationToken = new CancellationToken(); + const first = NodeEvents.EventEmitter.once(created, "request"); + const result = executor.download(new URL("https://example.com/update.AppImage"), destination, { + cancellationToken, + sha512: NodeCrypto.createHash("sha512").update(release).digest("base64"), + }); + // A download that settles instead of sending another request fails the wait with its error. + const settled = result.then(() => { + throw new Error("The download finished without another request"); + }); + settled.catch(() => {}); + const nextRequest = async () => { + const [request] = await Promise.race([ + NodeEvents.EventEmitter.once(created, "request"), + settled, + ]); + return request as { request: FakeRequest; headers: Record }; + }; + // The first request answers 200 and writes `body` to the file, then stalls before the end. + const stallAfterWriting = async (body: string) => { + const [{ request }] = await first; + const response = startResponse(request, 200, { "content-length": String(release.length) }); + const fileOut = createWriteStream.mock.results[0]!.value as NodeFS.WriteStream; + const committed = NodeEvents.EventEmitter.once(fileOut, "drain"); + response.write(body); + await committed; + const closed = NodeEvents.EventEmitter.once(fileOut, "close"); + const retry = nextRequest(); + await vi.advanceTimersByTimeAsync(60_000); + await closed; + await vi.advanceTimersByTimeAsync(2_000); + return retry; + }; + return { + destination, + first, + nextRequest, + stallAfterWriting, + result, + cancel: () => cancellationToken.cancel(), + // Resolves once the file is open for its digest check, before any of it is read. + readOpened: () => + new Promise((resolve) => { + createReadStream.mockImplementationOnce((...args) => { + const stream = openForReading(...args); + stream.once("open", () => resolve()); + return stream; + }); + }), + requestCount: () => requestCount, + read: () => NodeFS.readFileSync(destination, "utf8"), + [Symbol.dispose]: () => { + createWriteStream.mockRestore(); + createReadStream.mockRestore(); + NodeFS.rmSync(dir, { recursive: true, force: true }); + }, + }; +} + +function startResponse(request: FakeRequest, statusCode: number, headers: Record) { + const response = Object.assign(new NodeStream.PassThrough(), { + statusCode, + statusMessage: "", + headers, + }); + request.emit("response", response); + return response; +} + +function respond( + request: FakeRequest, + statusCode: number, + headers: Record, + body: string, +) { + startResponse(request, statusCode, { "content-length": String(body.length), ...headers }).end( + body, + ); +} + describe("ElectronHttpExecutor idle timeout", () => { beforeEach(() => { vi.useFakeTimers(); @@ -56,4 +178,96 @@ describe("ElectronHttpExecutor idle timeout", () => { expect(request.abort).not.toHaveBeenCalled(); expect(reject).not.toHaveBeenCalled(); }); + + it.each([ + { + name: "resumes a stalled download from the bytes already written", + written: PREFIX, + retry: { status: 206, headers: { "content-range": RESUMED_RANGE }, body: "world" }, + }, + { + name: "accepts a file that already holds every byte when the retry is past the end", + written: LARGE_RELEASE, + retry: { + status: 416, + headers: { "content-range": `bytes */${LARGE_RELEASE.length}` }, + body: "", + }, + }, + { + name: "starts over when the server ignores the range", + written: PREFIX, + retry: { status: 200, headers: {}, body: LARGE_RELEASE }, + }, + ])("$name", async ({ written, retry: { status, headers, body } }) => { + using download = startDownload("", LARGE_RELEASE); + + const { request: unanswered, headers: first } = await download.stallAfterWriting(written); + expect(first.Range).toBe(`bytes=${written.length}-`); + // A retry that fails before any response still resumes after the bytes the first one wrote. + const retry = download.nextRequest(); + unanswered.emit("error", new Error("net::ERR_TIMED_OUT")); + await vi.advanceTimersByTimeAsync(4_000); + const { request, headers: second } = await retry; + expect(second.Range).toBe(`bytes=${written.length}-`); + respond(request, status, headers, body); + + await expect(download.result).resolves.toBe(download.destination); + expect(download.read()).toBe(LARGE_RELEASE); + }); + + it("fails a file past the end of the release when the caller cancels its digest check", async () => { + using download = startDownload("", LARGE_RELEASE); + + const { request } = await download.stallAfterWriting(LARGE_RELEASE); + const opened = download.readOpened(); + respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, ""); + await opened; + download.cancel(); + + await expect(download.result).rejects.toBeInstanceOf(CancellationError); + }); + + it("fails a file past the end of the release whose bytes do not match it", async () => { + using download = startDownload("", LARGE_RELEASE); + + const { request } = await download.stallAfterWriting(`b${LARGE_RELEASE.slice(1)}`); + respond(request, 416, { "content-range": `bytes */${LARGE_RELEASE.length}` }, ""); + + await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" }); + expect(download.requestCount()).toBe(2); + }); + + it("fails a resumed download whose earlier bytes do not match the release", async () => { + using download = startDownload("", LARGE_RELEASE); + + const { request } = await download.stallAfterWriting(`b${PREFIX.slice(1)}`); + respond(request, 206, { "content-range": RESUMED_RANGE }, "world"); + + await expect(download.result).rejects.toMatchObject({ code: "ERR_CHECKSUM_MISMATCH" }); + }); + + it("gives up after three retries without resuming from a file it did not write", async () => { + using download = startDownload("differential output"); + for (const backoff of [2_000, 4_000, 8_000]) { + const retry = download.nextRequest(); + await vi.advanceTimersByTimeAsync(60_000 + backoff); + expect((await retry).headers.Range).toBeUndefined(); + } + const outcome = expect(download.result).rejects.toThrow("Request timed out"); + + await vi.advanceTimersByTimeAsync(60_000); + await outcome; + expect(download.requestCount()).toBe(4); + }); + + it("does not retry a request that fails for another reason", async () => { + using download = startDownload(""); + const [{ request }] = await download.first; + const outcome = expect(download.result).rejects.toThrow("net::ERR_CONNECTION_REFUSED"); + + request.emit("error", new Error("net::ERR_CONNECTION_REFUSED")); + await outcome; + expect(download.requestCount()).toBe(1); + }); }); 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 bb708a6ab7c88..4a99d52b0e79d 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 b413656a15241..280c5ad6c6716 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -449,6 +449,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/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-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/SocksListener.kt b/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/SocksListener.kt index 83264890e4ead..13d52e890b28c 100644 --- a/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/SocksListener.kt +++ b/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/SocksListener.kt @@ -23,6 +23,24 @@ private const val HANDSHAKE_TIMEOUT_MS = 10_000 private const val MAX_CONNECTIONS = 64 private const val MAX_SOCKS4_STRING = 255 +internal enum class TunnelFailure(val cause: String) { + ENVIRONMENT("environment"), + PORT("port"), + OUTDATED("outdated"); + + companion object { + /** + * The environment marks a dead or blocked port. A server from before the tunnel answers the + * route like any other page; anything else, such as a proxy's 502, means it is out of reach. + */ + fun classify(status: Int?, portRefused: Boolean): TunnelFailure = when { + portRefused -> PORT + status != null && (status in 200..299 || status == 404) -> OUTDATED + else -> ENVIRONMENT + } + } +} + private val client = OkHttpClient.Builder().readTimeout(0, TimeUnit.MILLISECONDS).build() // The webview names the host as typed, so IP literals can also arrive as domain names. @@ -48,6 +66,10 @@ internal class SocksListener(private val requestAccess: () -> String?) { ) val port: Int = server.localPort + /** Why the latest tunnel failed, or null once one opened. The page's error alone can't tell. */ + @Volatile var lastFailure: TunnelFailure? = null + private set + init { Thread({ while (!server.isClosed) { @@ -110,6 +132,7 @@ internal class SocksListener(private val requestAccess: () -> String?) { ) { val base = requestAccess() if (base == null) { + lastFailure = TunnelFailure.ENVIRONMENT output.write(handshake.reply(false)) } else { tunnel(socket, input, output, base, handshake) @@ -184,6 +207,7 @@ internal class SocksListener(private val requestAccess: () -> String?) { return } val opened = CompletableFuture() + var failure = TunnelFailure.ENVIRONMENT val replied = CompletableFuture() val closed = CompletableFuture() @@ -217,12 +241,19 @@ internal class SocksListener(private val requestAccess: () -> String?) { } override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + if (!opened.isDone) { + failure = TunnelFailure.classify( + response?.code, + response?.header("x-t3-tunnel-port-refused") != null + ) + } opened.complete(false) closed.complete(Unit) } } ) if (!runCatching { opened.get(15, TimeUnit.SECONDS) }.getOrDefault(false)) { + lastFailure = failure replied.completeExceptionally(java.io.IOException("tunnel did not open")) webSocket.cancel() output.write(handshake.reply(false)) @@ -235,6 +266,7 @@ internal class SocksListener(private val requestAccess: () -> String?) { webSocket.cancel() return } + lastFailure = null replied.complete(Unit) socket.soTimeout = 0 val reader = Thread({ sendPageBytes(input, webSocket, closed) }, "t3-preview-tunnel-up") diff --git a/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/T3TunnelWebView.kt b/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/T3TunnelWebView.kt index 09076542faea7..d581779dc7177 100644 --- a/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/T3TunnelWebView.kt +++ b/apps/mobile/modules/t3-preview-tunnel/android/src/main/java/expo/modules/t3previewtunnel/T3TunnelWebView.kt @@ -73,7 +73,9 @@ class T3TunnelWebView(context: Context, appContext: AppContext) : ExpoView(conte request: WebResourceRequest, error: WebResourceError ) { - if (request.isForMainFrame) fail(error.description.toString(), request.url.toString()) + if (request.isForMainFrame) { + fail(error.description.toString(), request.url.toString(), listener?.lastFailure) + } } } webView.webChromeClient = object : WebChromeClient() { @@ -85,8 +87,15 @@ class T3TunnelWebView(context: Context, appContext: AppContext) : ExpoView(conte pendingUrl?.let { loadUrl(it) } } - private fun fail(description: String, url: String = "") { - onLoadError(mapOf("code" to -1, "description" to description, "url" to url)) + private fun fail(description: String, url: String = "", failure: TunnelFailure? = null) { + onLoadError( + mapOf( + "code" to -1, + "description" to description, + "url" to url, + "cause" to (failure?.cause ?: "") + ) + ) } /** Reports the page's scroll position in steps, enough for the bar to follow its direction. */ diff --git a/apps/mobile/modules/t3-preview-tunnel/ios/T3SocksListener.swift b/apps/mobile/modules/t3-preview-tunnel/ios/T3SocksListener.swift index 78253ced9bf23..318fde127aace 100644 --- a/apps/mobile/modules/t3-preview-tunnel/ios/T3SocksListener.swift +++ b/apps/mobile/modules/t3-preview-tunnel/ios/T3SocksListener.swift @@ -73,6 +73,17 @@ final class T3SocksListener { enum T3TunnelFailure: String { case environment case port + case outdated +} + +extension T3TunnelFailure { + /// The environment marks a dead or blocked port. A server from before the tunnel answers the + /// route like any other page; anything else, such as a proxy's 502, means it is out of reach. + static func classify(status: Int?, portRefused: Bool) -> T3TunnelFailure { + if portRefused { return .port } + guard let status else { return .environment } + return (200..<300).contains(status) || status == 404 ? .outdated : .environment + } } private let replySucceeded: UInt8 = 0 @@ -231,11 +242,12 @@ private final class T3SocksConnection { self?.queue.async { guard let self, !self.closed else { return } if error != nil { - // The environment marks a dead or blocked port; any other failure, including a proxy's - // 502 while the environment is down, means the environment itself is out of reach. - let portRefused = (tunnel.response as? HTTPURLResponse)? - .value(forHTTPHeaderField: "x-t3-tunnel-port-refused") != nil - self.onOutcome(portRefused ? .port : .environment) + let response = tunnel.response as? HTTPURLResponse + self.onOutcome( + T3TunnelFailure.classify( + status: response?.statusCode, + portRefused: response?.value(forHTTPHeaderField: "x-t3-tunnel-port-refused") != nil + )) return self.finish(socksReply(replyFailure)) } self.onOutcome(nil) 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" ? ( { expect(current.container.textContent).toContain("Shared content imported"); }); -it("tells a replaced alert it was dismissed", () => { +it.each([ + { + kind: "alert", + present: (onClose: () => void) => + Dialog.alert("Older", undefined, [{ text: "OK" }], { onDismiss: onClose }), + }, + { + kind: "confirm", + present: (onClose: () => void) => + Dialog.confirm({ + title: "Remove project", + confirmText: "Remove", + onConfirm: () => {}, + onCancel: onClose, + }), + }, + { + kind: "text-input", + present: (onClose: () => void) => + Dialog.prompt({ + title: "Rename", + initialValue: "", + confirmText: "Save", + onConfirm: () => {}, + onCancel: onClose, + }), + }, +])("tells a replaced $kind it was closed without an answer", ({ present }) => { mountHost(); - const onDismiss = vi.fn(); - act(() => Dialog.alert("Older", undefined, [{ text: "OK" }], { onDismiss })); + const onClose = vi.fn(); + act(() => present(onClose)); act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }])); - expect(onDismiss).toHaveBeenCalledOnce(); + expect(onClose).toHaveBeenCalledOnce(); +}); + +it.each([ + { action: "confirm", clickIndex: -1 }, + { action: "cancel", clickIndex: -2 }, +])("ignores a late $action click from a replaced confirmation", ({ clickIndex }) => { + const { container } = mountHost(); + const onConfirm = vi.fn(); + const onCancel = vi.fn(); + act(() => + Dialog.confirm({ title: "Remove project", confirmText: "Remove", onConfirm, onCancel }), + ); + const lateClick = renderedClicks.at(clickIndex)!; + act(() => Dialog.alert("Newer", undefined, [{ text: "OK" }])); + + act(() => lateClick()); + + expect(onConfirm).not.toHaveBeenCalled(); + expect(onCancel).toHaveBeenCalledOnce(); + expect(container.textContent).toContain("Newer"); }); it("ignores a late action from a dialog that a newer one replaced", () => { diff --git a/apps/mobile/src/components/ui/Dialog.android.tsx b/apps/mobile/src/components/ui/Dialog.android.tsx index cf7fac4c77a86..c423ae2347e14 100644 --- a/apps/mobile/src/components/ui/Dialog.android.tsx +++ b/apps/mobile/src/components/ui/Dialog.android.tsx @@ -53,13 +53,20 @@ function setPresented(next: PresentedDialog | null) { function submitRequest(dialog: DialogRequest) { const replaced = presented; setPresented({ ...dialog, id: ++nextPresentationId }); - // A replaced alert closed without an answer, which its owner hears as a dismissal. - if (replaced?.kind === "alert") replaced.request.options?.onDismiss?.(); + // A replaced dialog closed without an answer, which its owner hears as a dismissal. + if (replaced) closeUnanswered(replaced); +} + +function closeUnanswered(dialog: DialogRequest) { + if (dialog.kind === "alert") dialog.request.options?.onDismiss?.(); + else dialog.request.onCancel?.(); } /** Closes the dialog only if it is still the one the action came from. */ function dismiss(id: number) { - if (presented?.id === id) setPresented(null); + if (presented?.id !== id) return false; + setPresented(null); + return true; } function subscribe(listener: () => void) { @@ -97,15 +104,12 @@ export function Host() { const presented = useSyncExternalStore(subscribe, getPresented, getPresented); const handleCancel = () => { - if (!presented) return; - dismiss(presented.id); - if (presented.kind === "alert") presented.request.options?.onDismiss?.(); - else presented.request.onCancel?.(); + if (!presented || !dismiss(presented.id)) return; + closeUnanswered(presented); }; const handleConfirm = (nativeInputValue?: string) => { - if (!presented) return; - dismiss(presented.id); + if (!presented || !dismiss(presented.id)) return; if (presented.kind === "confirm") { presented.request.onConfirm(); } else if (presented.kind === "text-input") { diff --git a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx index 3d1617266984c..017dbdb1456fb 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx @@ -183,11 +183,14 @@ function AndroidFilePreview(props: FilePreviewViewerProps) { const { source } = props; if (source.kind === "pdf") return ; if (source.kind !== "image") return ; - if (source.images[source.selectedIndex]?.actionsSource) - return ; + const selected = source.images[source.selectedIndex]!; + const images = source.images.filter((image) => !image.failed); + const gallery = { ...source, images, selectedIndex: images.indexOf(selected) }; + if (selected.actionsSource) + return ; return ( ({ })); vi.mock("../../lib/previewPresentation", () => ({ usePreviewPresentation: () => {} })); vi.mock("./Dialog", () => ({ alert: harness.alert })); +vi.mock("./Button", () => ({ Button: () => null })); +vi.mock("./SheetHeader", () => ({ SheetHeader: () => null })); +vi.mock("./AppText", () => ({ AppText: () => null })); +vi.mock("../PdfPreview", () => ({ PdfPreview: () => null })); +vi.mock("../MediaPreviewHeader", () => ({ MediaPreviewHeader: () => null })); +vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) })); +vi.mock("react-native", () => ({ Modal: () => null, View: () => null })); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); +vi.mock("react-native-image-viewing", () => ({ + default: function ImageViewing(props: { + images: readonly { uri?: string }[]; + imageIndex: number; + }) { + useState(() => harness.mounts++); + harness.previews.push({ + kind: "image", + images: props.images, + selectedIndex: props.imageIndex, + }); + return null; + }, +})); +import { FilePreviewModal as AndroidFilePreviewModal } from "./FilePreviewModal.android"; import type { FilePreviewItem, FilePreviewViewerProps } from "./FilePreviewModal.types"; import { FilePreviewSession } from "./FilePreviewSession"; @@ -57,14 +80,19 @@ async function openGallery( harness.alert.mockClear(); const root = createRoot(document.createElement("div")); const onRequestClose = vi.fn(); + const source = { ...selected, gallery }; await act(async () => root.render( - , + progressiveGallery ? ( + + ) : ( + + ), ), ); return { onRequestClose, [Symbol.asyncDispose]: () => act(async () => root.unmount()) }; @@ -105,9 +133,17 @@ it.each([true, false])( }, ); -it.each([true, false])( - "handles a failed sibling without leaving a pending page (progressive: %s)", - async (progressiveGallery) => { +it.each([ + // The progressive viewer already gave the missing image a page; a viewer that waits opens without it. + [ + true, + 1, + [{ failed: true }, { uri: "https://signed.test/a.png" }, { uri: "https://signed.test/c.png" }], + ], + [false, 0, [{ uri: "https://signed.test/a.png" }, { uri: "https://signed.test/c.png" }]], +])( + "opens the gallery when a sibling cannot be resolved (progressive: %s)", + async (progressiveGallery, selectedIndex, images) => { harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => { if (resource.url.endsWith("missing.png")) throw new Error("not found"); return `https://signed.test/${resource.url.split("/").pop()}`; @@ -115,26 +151,16 @@ it.each([true, false])( const selected = image("https://github.com/a.png"); await using preview = await openGallery( selected, - [selected, image("https://github.com/missing.png"), image("https://github.com/c.png")], + [image("https://github.com/missing.png"), selected, image("https://github.com/c.png")], progressiveGallery, ); - if (!progressiveGallery) { - expect(preview.onRequestClose).toHaveBeenCalledOnce(); - expect(harness.alert).toHaveBeenCalledOnce(); - expect(harness.previews).toEqual([]); - return; - } - expect(preview.onRequestClose).not.toHaveBeenCalled(); expect(harness.alert).not.toHaveBeenCalled(); - expect(harness.previews.at(-1)).toMatchObject({ - selectedIndex: 0, - images: [ - { uri: "https://signed.test/a.png" }, - { failed: true }, - { uri: "https://signed.test/c.png" }, - ], + expect(harness.previews.at(-1)).toEqual({ + kind: "image", + selectedIndex, + images: images.map((page) => expect.objectContaining(page)), }); }, ); diff --git a/apps/mobile/src/components/ui/FilePreviewSession.tsx b/apps/mobile/src/components/ui/FilePreviewSession.tsx index 491ec57472f43..92b6dd620ce95 100644 --- a/apps/mobile/src/components/ui/FilePreviewSession.tsx +++ b/apps/mobile/src/components/ui/FilePreviewSession.tsx @@ -141,7 +141,7 @@ function ResolvedFilePreview( }, (error: unknown) => { if (controller.signal.aborted) return; - if (progressiveGallery && index !== selectedIndex) return settle(index, null); + if (index !== selectedIndex) return settle(index, null); controller.abort(); onResolutionError( isPreviewResolutionError(error) @@ -155,7 +155,7 @@ function ResolvedFilePreview( controller.abort(); for (const dispose of leases) dispose(); }; - }, [items, selectedIndex, progressiveGallery]); + }, [items, selectedIndex]); const selected = { ...items[selectedIndex]!, name: filePreviewName(items[selectedIndex]!) }; if (selected.kind === "image") { // A viewer that resets image gestures when its sources change waits for every image. diff --git a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.test.ts index 61e7e491c3cf6..7b89a2c774c95 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", @@ -104,6 +121,34 @@ 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, + phoneServerEnvironmentId: null, + }), + ); + + 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", @@ -117,6 +162,7 @@ describe("liveActivityPreferences", () => { setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -175,6 +221,7 @@ describe("liveActivityPreferences", () => { yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: true, previousEnabled: false, clerkToken: "clerk-token", @@ -213,6 +260,7 @@ describe("liveActivityPreferences", () => { const partial = yield* setLiveActivityUpdatesEnabled({ updateEnvironment, linkEnvironment, + saveLocalPreference, enabled: false, previousEnabled: true, clerkToken: "clerk-token", @@ -238,6 +286,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 9096fe00e7bca..5a5c07b681b0d 100644 --- a/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts +++ b/apps/mobile/src/features/agent-awareness/liveActivityPreferences.ts @@ -16,102 +16,105 @@ 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; - readonly phoneServerEnvironmentId: EnvironmentId | null; - }) { - // Linking gives a server a tunnel, so the phone's own server is linked only by its share - // switch. displayUrl follows the preferred route, which may not be the loopback one. - const connections = input.connections.filter( - (connection) => - connection.environmentId !== input.phoneServerEnvironmentId && - phoneServerPort(connection.displayUrl) === null && - phoneServerPort(connection.httpBaseUrl) === null, - ); +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; + readonly phoneServerEnvironmentId: EnvironmentId | null; +}) { + // Linking gives a server a tunnel, so the phone's own server is linked only by its share + // switch. displayUrl follows the preferred route, which may not be the loopback one. + const connections = input.connections.filter( + (connection) => + connection.environmentId !== input.phoneServerEnvironmentId && + phoneServerPort(connection.displayUrl) === null && + phoneServerPort(connection.httpBaseUrl) === null, + ); - 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; - } + 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( - 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( + 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 781370919d8e3..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,11 +50,13 @@ 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); const [failed, setFailed] = useState(false); const [disconnected, setDisconnected] = useState(false); + const [outdated, setOutdated] = useState(false); const [debug, setDebug] = useState(undefined); const [unsupported, setUnsupported] = useState(null); // After a failed load the webview reports no URL, so the address stays on the one asked for. @@ -76,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. @@ -120,12 +123,30 @@ export function LocalPreviewScreen(props: { // A link to another port fails with that port's address, not the one typed earlier. if (failure.url) setRequested(failure.url); setDebug(failure.debug); - // Android reports no cause, so a refused tunnel request stands in for it there. + // Without a cause, a refused tunnel request reported through onAccess stands in. if (failure.cause) setDisconnected(failure.cause === "environment"); + setOutdated(failure.cause === "outdated"); setFailed(true); }} /> - {unsupported !== null ? ( + {tunnelOff ? ( + + + + + + ) : unsupported !== null ? ( Promise; readonly goBack: () => Promise; @@ -80,10 +83,10 @@ export function TunnelWebView({ /** What the native proxy saw, shown with the error so a report carries it. iOS only. */ readonly debug?: string; /** - * iOS only: whether the environment itself was out of reach (`environment`) or answered that - * nothing listens on the port (`port`). + * Whether the environment itself was out of reach (`environment`), answered that nothing + * listens on the port (`port`), or runs a T3 Code server without the tunnel (`outdated`). */ - readonly cause?: "environment" | "port"; + readonly cause?: TunnelFailureCause; }) => void; /** Whether the last connection could get into the environment's tunnel at all. */ readonly onAccess?: (available: boolean) => void; @@ -121,10 +124,7 @@ export function TunnelWebView({ unsupported: nativeEvent.code === -1 && nativeEvent.url === "", description: nativeEvent.description, debug: nativeEvent.debug, - cause: - nativeEvent.cause === "environment" || nativeEvent.cause === "port" - ? nativeEvent.cause - : undefined, + cause: TUNNEL_FAILURE_CAUSES.find((cause) => cause === nativeEvent.cause), }) } /> 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 ( + +