diff --git a/.agents/skills/lazurio-upstream-rebuild/SKILL.md b/.agents/skills/lazurio-upstream-rebuild/SKILL.md new file mode 100644 index 0000000000000..3a68e453b3c70 --- /dev/null +++ b/.agents/skills/lazurio-upstream-rebuild/SKILL.md @@ -0,0 +1,94 @@ +--- +name: lazurio-upstream-rebuild +description: Přestaví Lazurio T3 Code na nové stabilní vydání upstream T3 Code end to end podle runbooku forku (inventura, rozhodnutí, candidate, CI, review, zachycení starého main, výměna main, preview, Ring 0 s ověřením v prohlížeči, stable a plán dalších vln). Použij, když upstream vydá stable vX.Y.Z, když se otevře issue „Přestavba na upstream T3 Code“ nebo když Operátor řekne „použij skill“ k nové verzi. Nepoužívej na běžnou opravu overlaye na stejné bázi. +--- + +# Přestavba Lazurio T3 Code na nový upstream + +Tento skill vede práci. **Kroky, příkazy a overlay drží jen runbook** +[`docs/operations/lazurio-fork-release.md`](../../../docs/operations/lazurio-fork-release.md) +(sekce „Nové stabilní vydání upstreamu“, etapy 1–9) a +[`docs/operations/lazurio-overlay.md`](../../../docs/operations/lazurio-overlay.md). Než začneš, +přečti obě celé na aktuálním `main` (ne ze starého checkoutu). Když runbook při práci nesedí, +oprav runbook ve stejné přestavbě (řádek 5); tenhle skill nerozšiřuj o kroky. + +## Mandát + +Na začátku si od Operátora ujasni rozsah (bez něj platí jen etapy 2–5, viz runbook +„Zadání pro Task Agenta“): + +- etapy, které smíš udělat sám (typicky 2–9 bez vln mimo Ring 0); +- že vydání spouštíš jeho účtem podle runbooku (oddíl Schválení), vždy jen na přesném SHA + a verzi, které jsi sám ověřil, a schvaluje ho persona; jeho účtem schvaluješ jen při + přechodu, a jen běh, který spustil jiný účet; +- co chce u řádků overlaye určitě zachovat a co posoudíš sám; +- komu patří Ring 0 a kdo tam ještě pracuje (domluv se s těmi vlákny dřív, než něco nasadíš). + +Rozhodnutí, která by schvaloval Admin, smíš brát jako schválená jen tehdy, když to zadání výslovně +říká; i pak je zapiš do issue přestavby s citací a zdrojem. + +## Průběh + +1. **Orientace.** Root `AGENTS.md`, worktree disciplína (primární checkout nech na `main`), + volné místo na disku (počítej asi 1 GB na worktree s `node_modules`), toolchain + (pnpm a vite-plus přes `npx --yes pnpm@`), aktivní tailnet a vlákna, + která pracují na Ring 0. Ověř přesný tag proti `pingdotgg/t3code` (etapa 2). +2. **Issue přestavby** podle šablony z runbooku: přejmenuj otevřené issue na novou verzi, nebo + založ nové. Vstupy vyplň hned. +3. **Inventura paralelně, jen čtení** (etapa 2 a brány z etapy 5). Rozděl řádky do skupin, + které spolu sdílejí soubory (osvědčilo se: hosted a vydávání 1–5 s branami; server prohlížeče + Environmentu 8, 10–12; web 6, 7, 9, 13, 16, 17; spravovaná složka, přihlášení a párování 15, 18, + 19; agenti a otázky 20–22; Buddy 23–28; usměrnění a fronta 30–33). Dodatek, který na `main` + nese pozdější commit, vrať do jeho řádku. Každé skupině dej společné zadání (cesty, SHA, závazná přání + Operátora, formát zprávy po řádcích) a ať píše zprávu do souboru. Zprávy čti sám a tvrzení, na kterých stojí rozhodnutí, ověř v kódu. +4. **Rozhodnutí do issue dřív, než se změní kód.** Tabulka po řádcích (ponechat, přestavět, + zmenšit, odebrat, nabídnout upstreamu) a brány. Kde upstream umí totéž stejně dobře, řádek odeber. +5. **Zachycení starého `main`.** Když se `main` od posledního stable liší mimo `docs/`, vydej + nejdřív stable na staré bázi: preview na Ring 0 (záloha databáze, `t3 update` s potvrzením), + kontrola v prohlížeči, pak stable ze špičky `main`. Vydání spustíš podle runbooku (oddíl + Schválení: komentář `Release dispatch request:`, pak dispatch účtem Organization Admina) + a schválí ho persona (environment má `prevent_self_review`); ověř publikované vydání podle + runbooku. +6. **Candidate** (etapa 3). Řádky, které jdou přenést s malou úpravou, přehraj sám rovnou do větve + `lazurio/rebuild-vX.Y.Z` po souborech (runbook, etapa 3). Těžké řádky dej implementačním + skupinám ve vlastních worktree z přesného tagu, každá commit na řádek; společné zadání jako + u inventury, k tomu „nikdy nepushuj, nesahej na `main`“. Závislosti mezi skupinami řeš dočasným + lešením, které při integraci zahodíš. Commity skupin přenes do větve cherry-pickem v pořadí + Cílového stacku, řádek 5 poslední. Commity řádků ber z `git log --reverse ..origin/main` + podle předmětu, ne z hashů v Cílovém stacku (runbook, etapa 3). Pre-commit hook od v0.1.5 spouští `knip:check` nad celým + repozitářem: přehrávej s `--no-verify` a knip pusť nad hotovým stackem (runbook, etapa 3). + Opravu nad hotovým stackem adresuj řádku, který dotčené místo přidal (`git log -S`, runbook, + etapa 3); fixup mířený na dřívější řádek autosquash nepřehraje. +7. **Kontrola integrace.** Diff každého řádku přečti sám, typecheck, lint a testy spusť sám (ne jen + převezmi hlášení skupin; k nim `vp run knip:check`; ve worktree vnořeném v jiném repozitáři ověř formát a lint podle + runbooku, etapa 3), a teprve pak push a draft PR (etapa 4). Když `pull_request` CI na + draft PR neběží, spusť `Lazurio Fork CI` ručně na větvi. +8. **Review** od Stewarda (nebo review agenta jeho Organizace) na přesném headu, v rozsahu overlaye + (runbook, etapa 4); žádost o review ten rozsah uvádí. Skutečné vady oprav hned; + drobnosti a rozšiřování scope odmítni věcnou námitkou v PR (root `AGENTS.md`, rozhodnutí 0163). +9. **Brány kompatibility** (etapa 5): každou zapiš do issue i s tím, jak je ověřená. +10. **Výměna `main`** (etapa 6) přesně podle runbooku: přesné SHA, `--force-with-lease`, nikdy + automatický retry; po výměně vypni nové upstream workflow. +11. **Preview a Ring 0** (etapa 7): kontroly z runbooku a kontrola v prohlížeči. Ta potřebuje + přihlášení člověka nebo testovací účet z lokální custody Ring 0; použij vlastní profil + prohlížeče, ať tě neodhlásí test jiného vlákna. Agentní turn s Codexem i Claude jen tam, kde je + AI. +12. **Stable** (etapa 8) ze stejného commitu po souhlasu Admina (nebo podle mandátu), Ring 0 zpět + na stable a test tlačítka Update z předchozího stable. +13. **Další vlny** nenasazuj sám, pokud to mandát neříká: předlož Operátorovi plán (Environmenty, + pořadí, okna, přepnutí tailnetu, změny Machines a Platformy, oznámení lidem). +14. **Po vydání** (etapa 9): návrhy upstreamu, runbook (Cílový stack, „Upstream a přestavba“, vše, + co při přestavbě nesedělo), zavření issue. + +## Kdy se zeptat Operátora + +Jen když odpověď nenajdeš v runbooku, rozhodovacím registru, issue ani kódu, nebo když bez něj +nejde pokračovat bezpečně: přihlášení člověka, rozhodnutí mimo mandát (nové chování, které zadání +nepokrývá), nasazení mimo Ring 0, a selhání, které vyžaduje volbu mezi dvěma mechanismy. Ptej se +jednou a sdruženě. + +## Handoff + +Pro Operátora česky a lidsky: co se změnilo pro lidi na Environmentech, které funkce overlaye +zůstaly, které nahradil upstream a proč, co je ověřené v prohlížeči. Odkazy na PR, vydání a issue, +přesné SHA a verze, plán dalších vln a co zůstává otevřené. diff --git a/.agents/skills/lazurio-upstream-rebuild/agents/openai.yaml b/.agents/skills/lazurio-upstream-rebuild/agents/openai.yaml new file mode 100644 index 0000000000000..5425705276256 --- /dev/null +++ b/.agents/skills/lazurio-upstream-rebuild/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Lazurio Upstream Rebuild" + short_description: "Rebuild Lazurio T3 Code on a new upstream stable, end to end" + default_prompt: "Use $lazurio-upstream-rebuild to rebuild Lazurio T3 Code on the new upstream stable release." diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000..477378e8cbdf6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,76 @@ +.git +.github +.repos +.vite-plus +.vite-hooks +.vite-hooks/ +.worktrees +.bun +.bun/ +.turbo +.turbo/ +.astro +.astro/ +.tanstack +.tanstack/ +.vitest-* +.cache +.cache/ +.pnpm-store +.pnpm-store/ +.idea +.idea/ +.DS_Store +.t3 +.t3/ +**/.t3 +**/.t3/ +.alchemy +.alchemy/ +**/.alchemy +**/.alchemy/ +.vercel +.vercel/ +**/.vercel +**/.vercel/ +.gstack +.gstack/ +.plans +.plans/ +.logs +.logs/ +.env* +**/.env* +.npmrc +**/.npmrc +.netrc +**/.netrc +*.log +release +release/ +release-mock +release-mock/ +artifacts +artifacts/ +build +build/ +coverage +coverage/ +squashfs-root +squashfs-root/ +.electron-runtime +.electron-runtime/ +.showcase +.showcase/ +__screenshots__ +__screenshots__/ +**/__screenshots__ +**/__screenshots__/ +apps/web/.playwright +apps/web/.playwright/ +apps/web/playwright-report +apps/web/playwright-report/ +**/node_modules +**/dist +**/dist-electron +*.tsbuildinfo diff --git a/.github/ISSUE_TEMPLATE/1-lazurio-t3-code.yml b/.github/ISSUE_TEMPLATE/1-lazurio-t3-code.yml new file mode 100644 index 0000000000000..4141dabdcac61 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1-lazurio-t3-code.yml @@ -0,0 +1,81 @@ +name: Lazurio T3 Code problem +description: Report a problem with Lazurio T3 Code, the modified distribution of T3 Code in this repository. +labels: + - bug +body: + - type: markdown + attributes: + value: | + This repository is Lazurio T3 Code, a modified distribution of T3 Code for Lazurio + Environments. Report problems with it here, not to the T3 Code team. If the problem also + happens in upstream T3 Code, report it upstream too. + + Do not report a security problem in a public issue. Report it privately: on this + repository's **Security** tab, choose **Report a vulnerability**. + + - type: dropdown + id: area + attributes: + label: Area + description: Which part of Lazurio T3 Code is affected? + options: + - Environment browser (right panel, New tab, browser tools) + - Lazurio Folder project + - Lazurio shell (rail, app switcher) + - Name or look on a Lazurio Environment + - Prepared prompt from Lazurio + - Updates and releases + - Hosting (sign-in, pairing, session) + - Something else, or not sure + validations: + required: true + + - type: textarea + id: what-happened + attributes: + label: What happened + description: What you did, what you expected, and what happened instead. + validations: + required: true + + - type: textarea + id: steps + attributes: + label: Steps to reproduce + placeholder: | + 1. Open Chat on the Environment + 2. ... + validations: + required: true + + - type: input + id: version + attributes: + label: Version + description: Settings → General shows it, and so does `t3 --version` on the Environment. + placeholder: 0.1.8-lazurio.1 + validations: + required: true + + - type: input + id: browser + attributes: + label: Browser and device + placeholder: Chrome on macOS + + - type: dropdown + id: upstream + attributes: + label: Does it also happen in upstream T3 Code? + options: + - "No" + - "Yes" + - Not checked + validations: + required: true + + - type: textarea + id: details + attributes: + label: Logs or screenshots + description: The most relevant part only. Remove secrets, tokens and private names first. diff --git a/.github/README.md b/.github/README.md new file mode 100644 index 0000000000000..20a964801cc09 --- /dev/null +++ b/.github/README.md @@ -0,0 +1,126 @@ +# Lazurio T3 Code + +Lazurio T3 Code is a modified distribution of [T3 Code](https://github.com/pingdotgg/t3code) and +the Chat app of [Lazurio](https://github.com/Lazurio). It is T3 Code's server and web client, built +from upstream's stable releases with a Lazurio overlay on top, for Lazurio Environments. + +It is not an official T3 Code release, and the T3 Code team does not support it. Report problems +with it here, not upstream (see [Reporting issues](#reporting-issues)). + +## How it differs from T3 Code + +### The browser works differently + +This is the biggest difference. + +In upstream T3 Code, the desktop app has its own preview browser, and the T3 Code server runs a +headless browser of its own for the web and mobile apps, in fresh contexts without your sign-ins. + +In Lazurio T3 Code's web client, the browser is the **Environment browser**: one Chromium with one +persistent profile that runs on the Lazurio Environment itself. Every app, chat and agent of the +Environment shares it, and its sign-ins with it. On a Lazurio Environment the server's own browser +never starts, so the Environment browser is the web client's only browser. + +- The right panel shows a thread's tabs in that browser. Each one is a live view of a remote tab, + which keeps running when you close the page. Every device shows the same tabs of a thread. +- A thread's agents work in their own window of that browser, through the `agent-browser` CLI or + T3 Code's own browser tools (`preview_open`, `preview_snapshot`, `preview_click` and the rest). + You can watch them and work in the same tab at the same time, for example to sign in or to + solve a CAPTCHA. Nothing is handed over. +- "+" opens a New tab page with an address bar, T3 Code's tools and an overview of the + Environment's open tabs. +- Closing a tab lets go of it for this thread, with an undo. The remote tab stays open while an + agent works in it or another place holds it. Archiving or deleting a thread lets go of its tabs. +- A link to a tab of another Lazurio Environment opens as a marked tab of that Environment. + +The official desktop and mobile apps are upstream's and unmodified. Connected to a Lazurio +Environment, the desktop app keeps its own browser and the mobile app shows no browser. + +### The Lazurio Folder project + +On a Lazurio Environment, Chat starts in the Environment's Lazurio Folder. The server creates or +adopts the Folder as a project when it starts, new chats start in it, and a short welcome explains +it. Earlier conversations stay as history. The model the Environment recommends is the Lazurio +project's default model (Settings → General, with the Lazurio project selected); a model you choose +there stays yours. + +### Other changes + +- **The name and the look.** The app calls itself "T3 Code (Lazurio)", and its wordmark and icons + stay T3 Code's. On a Lazurio Environment, T3 Code's standard light theme takes the Lazurio + design system's colours, font and radii from tokens the Environment's shell declares. A theme + you pick and the dark theme stay T3 Code's own. +- **Lazurio shell.** The Environment rail, the app switcher at the top of the sidebar and Buddy + load at runtime from the Environment. Outside Lazurio, nothing extra renders. +- **Prepared prompts.** Lazurio can open Chat with a prepared prompt in a new thread's message + box. It is never sent on its own. +- **Signing in to Codex and Claude.** On a Lazurio Environment they sign in with their own CLIs from + the Environment's Getting started page, so the sign-in works for T3 Code, the terminal and every + agent alike. T3 Code's own ChatGPT sign-in is not offered there. +- **Pairing.** A Lazurio Environment pairs your browser itself: however you open Chat, a browser + without a session signs in without a pairing token and stays on the page you opened, and a + browser paired with an older release pairs again. **Settings → Connections** shows your + authorized clients; on an Environment in your tailnet you create pairing links there for the + desktop and mobile apps. The Environment's pairing never lets a browser manage T3 Connect. +- **Hosting behind a reverse proxy.** `T3CODE_EXTERNAL_ORIGIN` serves T3 Code at the root of its + own HTTPS hostname with a Secure session cookie, `T3CODE_CLIENT_SESSION_TTL` sets how long a + paired browser stays signed in, and `T3CODE_ENVIRONMENT_LABEL` names the Environment. +- **Buddy's chat.** With `T3CODE_LAZURIO_BUDDY=1`, a T3 Code server is Buddy's chat on a person's + Osobní Prostředí. Its provider instance `buddy` runs Buddy's Hermes Agent over ACP and gets only + what the person sends: their words, their attachments and the page they ask from, never T3 + Code's own instructions. The web client is Buddy's one conversation: one thread with its days + beside it, no thread list, forks or rollbacks, and a message sent during a turn steers it. It + reads like a chat with a friend: what Buddy writes, and one quiet line while he works, never his + tool calls or reasoning, and a message box without access or mode controls. In Buddy's bubble it + talks to the page around it through the bubble's `lazurio.buddy.*` messages, and that page + travels with the person's message as a chip they can remove. +- **Updates from this repository.** The server offers the newest release of this repository and + installs it with the Update button, and `t3 update` and the install scripts take it from here + too. `T3CODE_RELEASE_REPOSITORY=owner/name` picks another repository's releases. After the + update, the `t3` command follows the version the server runs. + +Apart from the name and the release repository, each change stays off until its setting is +present or the page runs on a Lazurio Environment. Without them, the server and the web client +behave like upstream T3 Code; agent processes and thread terminals still get an +`AGENT_BROWSER_SESSION` variable, which does nothing on its own, and a page served over HTTPS +without a session first asks its own origin whether Lazurio pairs it. + +## Tracking upstream + +`main` is an exact upstream stable release tag with the Lazurio overlay commits on top, and nothing +else. When upstream publishes a new stable release, a daily check opens an issue in this repository +that tracks the move: the overlay is rebuilt on the new release, one commit per change, and every +change upstream now covers is dropped. Changes that would help everyone are offered upstream. + +## Releases + +Releases are on this repository's [Releases](https://github.com/Lazurio/t3code/releases) page, and +Lazurio Environments install and update from there. + +- **Stable:** `X.Y.Z-lazurio.N`, tagged `vX.Y.Z-lazurio.N`. `X.Y.Z` is the upstream release it is + built on, and `N` counts the releases on that base. +- **Preview:** `X.Y.Z-preview.YYYYMMDD.N`. A preview is a canary: it is never offered as an + update, and you install one on purpose with `t3 update `. + +Each release has CLI archives for `linux-x64` and `darwin-arm64`, a `SHA256SUMS` file, build +provenance attestations and the OCI image `ghcr.io/lazurio/t3code:`. + +## Reporting issues + +Report problems with Lazurio T3 Code in this repository's +[issues](https://github.com/Lazurio/t3code/issues), especially anything about the Environment +browser, the Lazurio Folder or the other changes above. Please don't report them to the T3 Code +team. If a problem also happens in upstream T3 Code, report it upstream too. + +Report security problems privately: on this repository's **Security** tab, choose +**Report a vulnerability**. + +## Credit and license + +Lazurio T3 Code is built on [T3 Code](https://github.com/pingdotgg/t3code) by T3 Tools Inc. and its +contributors. T3 Code is licensed under the MIT License, and so are the Lazurio changes: see +[LICENSE](../LICENSE), which keeps upstream's copyright notice. Every image and CLI archive ships +that licence. Upstream's own README is [README.md](../README.md). + +Lazurio's brand assets are the exception: the MIT License does not cover the Lazurio symbol or +Buddy's character Mattyčus (see [their terms](../apps/web/src/lazurio/brand/README.md)). diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 69dc53dc4393f..26d2449559f57 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,7 +1,17 @@ # Security policy +This repository is Lazurio T3 Code, a modified distribution of T3 Code for Lazurio Environments +(see the [README](README.md)). Report security problems with it privately, here: on this +repository's **Security** tab, choose **Report a vulnerability**. Please do not disclose them +publicly until we have had a reasonable opportunity to investigate and fix them. + +A problem in the Lazurio changes is ours to fix, so please don't send it to the T3 Code team. If +it also affects upstream T3 Code, report it to them too, under their policy below. + +## Upstream T3 Code + Report security vulnerabilities affecting T3 Code or T3 Tools-operated infrastructure to -[security@ping.gg](mailto:security@ping.gg). Please do not disclose them publicly until we have had +[security@t3.codes](mailto:security@t3.codes). Please do not disclose them publicly until we have had a reasonable opportunity to investigate and remediate them. See the [full security policy](https://t3.codes/security-policy) for reporting details, scope, diff --git a/.github/actions/ci-changes/action.yml b/.github/actions/ci-changes/action.yml index ecf787404657a..7d2adc0c9e035 100644 --- a/.github/actions/ci-changes/action.yml +++ b/.github/actions/ci-changes/action.yml @@ -5,6 +5,8 @@ outputs: value: ${{ steps.detect.outputs.typecheck }} build: value: ${{ steps.detect.outputs.build }} + desktop_launch: + value: ${{ steps.detect.outputs.desktop_launch }} test: value: ${{ steps.detect.outputs.test }} test_packages: diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index e9b7ae70a36ad..e27a8c90fdff8 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -13,6 +13,10 @@ inputs: description: Arguments for `vp install`, such as filters. Empty installs the whole workspace. required: false default: "" + save-pnpm-store: + description: Set to "false" when a concurrent job with the same install args saves the pnpm store + required: false + default: "true" runs: using: composite steps: @@ -123,10 +127,14 @@ runs: key: ${{ steps.pnpm_verified.outputs.cache-primary-key }} # A filtered install that started from the current full store adds nothing - # worth a second copy of it. + # worth a second copy of it. A stacked PR, based on a branch other than the + # default, saves a ~1 GB store only its own reruns can read, so it only restores. + # Concurrent jobs with the same install args reserve one key, so the losers + # compress the store for nothing; all but one pass save-pnpm-store: false. - name: Save pnpm store if: >- - inputs.install == 'true' && + inputs.install == 'true' && inputs.save-pnpm-store == 'true' && + (github.event_name != 'pull_request' || github.base_ref == github.event.repository.default_branch) && steps.pnpm_cache.outputs.cache-hit != 'true' && (steps.pnpm_store.outputs.namespace == 'full' || steps.pnpm_cache.outputs.cache-matched-key != format('pnpm-full-v1-{0}-{1}-{2}', runner.os, runner.arch, hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json'))) diff --git a/.github/scripts/check-nightly-release.cjs b/.github/scripts/check-nightly-release.cjs index 943bf116909d2..95581e2b22781 100644 --- a/.github/scripts/check-nightly-release.cjs +++ b/.github/scripts/check-nightly-release.cjs @@ -40,42 +40,67 @@ async function assertReleaseSource({ github, context, releaseChannel }) { const isNightlyTag = (tag) => /^v.*-nightly\./.test(tag) || tag.startsWith("nightly-v"); -async function findLatestNightly({ github, context }) { - const releases = await github.paginate(github.rest.repos.listReleases, { - ...context.repo, - per_page: 100, - }); - return releases - .filter((release) => !release.draft && release.published_at && isNightlyTag(release.tag_name)) - .sort((a, b) => Date.parse(b.published_at) - Date.parse(a.published_at))[0]; +// Only the three fields the gate reads. The REST list also returns every asset, +// which made a full scan tens of megabytes. +const RELEASES_QUERY = ` + query ($owner: String!, $repo: String!, $cursor: String) { + repository(owner: $owner, name: $repo) { + releases(first: 100, after: $cursor, orderBy: { field: CREATED_AT, direction: DESC }) { + pageInfo { hasNextPage endCursor } + nodes { tagName isDraft publishedAt } + } + } + } +`; + +// Returns the nightly with the newest publishedAt. Release order follows the +// tagged commit date, not publication, so every page is read unless `isSettled` +// says the newest nightly seen so far already decides the caller's answer. +async function findLatestNightly({ github, context, isSettled = () => false }) { + let latest; + let cursor = null; + do { + const { repository } = await github.graphql(RELEASES_QUERY, { ...context.repo, cursor }); + const { nodes, pageInfo } = repository.releases; + for (const release of nodes) { + if (release.isDraft || !release.publishedAt || !isNightlyTag(release.tagName)) continue; + if (!latest || Date.parse(release.publishedAt) > Date.parse(latest.publishedAt)) { + latest = release; + } + } + if (latest && isSettled(latest)) return latest; + cursor = pageInfo.hasNextPage ? pageInfo.endCursor : null; + } while (cursor); + return latest; } async function shouldReleaseNightly({ github, context, core, now = Date.now() }) { - const lastNightly = await findLatestNightly({ github, context }); + const isInGap = (release) => now - Date.parse(release.publishedAt) < MINIMUM_RELEASE_GAP_MS; + // Any nightly inside the gap means the newest one is too, so stop reading. + const lastNightly = await findLatestNightly({ github, context, isSettled: isInGap }); if (!lastNightly) { core.info("No published nightly found. Proceeding with release."); return true; } - if (now - Date.parse(lastNightly.published_at) < MINIMUM_RELEASE_GAP_MS) { - core.info(`Nightly ${lastNightly.tag_name} was published less than six hours ago. Skipping.`); + const tag = lastNightly.tagName; + if (isInGap(lastNightly)) { + core.info(`Nightly ${tag} was published less than six hours ago. Skipping.`); return false; } const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({ ...context.repo, - basehead: `${lastNightly.tag_name}...${context.sha}`, + basehead: `${tag}...${context.sha}`, per_page: 1, }); if (comparison.status !== "ahead") { - core.info( - `Candidate commit is ${comparison.status} relative to ${lastNightly.tag_name}. Skipping.`, - ); + core.info(`Candidate commit is ${comparison.status} relative to ${tag}. Skipping.`); return false; } - core.info(`New commits since ${lastNightly.tag_name}, and the six-hour gap has passed.`); + core.info(`New commits since ${tag}, and the six-hour gap has passed.`); return true; } @@ -85,7 +110,7 @@ async function resolveLatestNightlyCommit({ github, context, core }) { throw new Error("No published nightly found. Stable releases build the latest nightly commit."); } - const tag = lastNightly.tag_name; + const tag = lastNightly.tagName; const { data: commit } = await github.rest.repos.getCommit({ ...context.repo, ref: tag }); const version = /^(?:nightly-)?v(\d+\.\d+\.\d+)-nightly\./.exec(tag)?.[1]; if (!version) { diff --git a/.github/scripts/check-nightly-release.test.cjs b/.github/scripts/check-nightly-release.test.cjs index f55d29c10dc6a..3030080d946ce 100644 --- a/.github/scripts/check-nightly-release.test.cjs +++ b/.github/scripts/check-nightly-release.test.cjs @@ -9,9 +9,9 @@ const { const now = Date.parse("2026-09-05T12:00:00Z"); const hour = 60 * 60 * 1000; const nightly = (hoursAgo, overrides = {}) => ({ - tag_name: "v1.0.1-nightly.20260905.123", - draft: false, - published_at: new Date(now - hoursAgo * hour).toISOString(), + tagName: "v1.0.1-nightly.20260905.123", + isDraft: false, + publishedAt: new Date(now - hoursAgo * hour).toISOString(), ...overrides, }); @@ -73,10 +73,13 @@ for (const comparisonStatus of ["behind", "diverged"]) { }); } -function fixture({ releases = [nightly(7)], comparisonStatus = "ahead" } = {}) { +// `pages` holds the GraphQL release pages; `releases` is shorthand for one page. +function fixture({ releases = [nightly(7)], pages = [releases], comparisonStatus = "ahead" } = {}) { const calls = []; + const cursors = []; return { calls, + cursors, options: { now, context: { repo: { owner: "example", repo: "app" }, sha: "new" }, @@ -84,15 +87,25 @@ function fixture({ releases = [nightly(7)], comparisonStatus = "ahead" } = {}) { github: { rest: { repos: { - listReleases() {}, async compareCommitsWithBasehead(params) { calls.push(params); return { data: { status: comparisonStatus } }; }, }, }, - async paginate() { - return releases; + async graphql(_query, { owner, repo, cursor }) { + assert.deepEqual({ owner, repo }, { owner: "example", repo: "app" }); + cursors.push(cursor); + const index = cursor === null ? 0 : Number(cursor); + const hasNextPage = index + 1 < pages.length; + return { + repository: { + releases: { + nodes: pages[index], + pageInfo: { hasNextPage, endCursor: hasNextPage ? String(index + 1) : null }, + }, + }, + }; }, }, }, @@ -101,28 +114,65 @@ function fixture({ releases = [nightly(7)], comparisonStatus = "ahead" } = {}) { test("releases the first nightly when no nightly is published", async () => { const { options } = fixture({ - releases: [nightly(0, { tag_name: "v1.0.0" }), nightly(0, { draft: true })], + releases: [nightly(0, { tagName: "v1.0.0" }), nightly(0, { isDraft: true })], }); assert.equal(await shouldReleaseNightly(options), true); }); test("uses publication time, not release order or the tagged commit date", async () => { const { options } = fixture({ - releases: [nightly(10), nightly(1), nightly(20, { tag_name: "nightly-v0.9.0" })], + releases: [nightly(10), nightly(1), nightly(20, { tagName: "nightly-v0.9.0" })], + }); + assert.equal(await shouldReleaseNightly(options), false); +}); + +test("the six-hour gap ends exactly six hours after publication", async () => { + const atBoundary = fixture({ releases: [nightly(6)] }); + assert.equal(await shouldReleaseNightly(atBoundary.options), true); + const justInside = fixture({ releases: [nightly(6 - 1 / 3_600_000)] }); + assert.equal(await shouldReleaseNightly(justInside.options), false); + assert.equal(justInside.calls.length, 0); +}); + +test("stops reading releases once a nightly inside the gap is seen", async () => { + const { options, cursors } = fixture({ pages: [[nightly(10), nightly(2)], [nightly(30)]] }); + assert.equal(await shouldReleaseNightly(options), false); + assert.deepEqual(cursors, [null]); +}); + +test("reads every page when no nightly seen so far settles the gap", async () => { + const { options, cursors, calls } = fixture({ + pages: [ + [nightly(10), nightly(0, { tagName: "v1.0.0" })], + [nightly(1, { tagName: "nightly-v0.9.0" })], + ], }); assert.equal(await shouldReleaseNightly(options), false); + assert.deepEqual(cursors, [null, "1"]); + assert.equal(calls.length, 0); +}); + +test("compares against the newest nightly across pages once the gap has passed", async () => { + const { options, calls } = fixture({ + pages: [[nightly(10, { tagName: "v1.0.1-nightly.20260905.100" })], [nightly(8)]], + }); + assert.equal(await shouldReleaseNightly(options), true); + assert.deepEqual( + calls.map((call) => call.basehead), + ["v1.0.1-nightly.20260905.123...new"], + ); }); test("ignores stable releases and drafts when checking the gap", async () => { const { options } = fixture({ - releases: [nightly(0, { tag_name: "v1.0.0" }), nightly(0, { draft: true }), nightly(7)], + releases: [nightly(0, { tagName: "v1.0.0" }), nightly(0, { isDraft: true }), nightly(7)], }); assert.equal(await shouldReleaseNightly(options), true); }); test("fails instead of releasing when GitHub cannot supply release state", async () => { const { options } = fixture(); - options.github.paginate = async () => { + options.github.graphql = async () => { throw new Error("GitHub unavailable"); }; await assert.rejects(shouldReleaseNightly(options), /GitHub unavailable/); @@ -137,9 +187,9 @@ for (const status of ["behind", "diverged"]) { const { resolveLatestNightlyCommit } = require("./check-nightly-release.cjs"); -function nightlyCommitFixture({ releases, commitSha = "abc123" }) { +function nightlyCommitFixture({ releases, pages, commitSha = "abc123" }) { const refs = []; - const { options } = fixture({ releases }); + const { options } = fixture({ releases, pages }); options.github.rest.repos.getCommit = async ({ ref }) => { refs.push(ref); return { data: { sha: commitSha } }; @@ -150,10 +200,10 @@ function nightlyCommitFixture({ releases, commitSha = "abc123" }) { test("stable releases resolve the commit of the newest published nightly", async () => { const { options, refs } = nightlyCommitFixture({ releases: [ - nightly(10, { tag_name: "v1.0.1-nightly.20260905.100" }), - nightly(1, { tag_name: "v1.0.1-nightly.20260905.123" }), - nightly(0, { tag_name: "v1.0.0" }), - nightly(0, { draft: true, tag_name: "v1.0.1-nightly.20260905.999" }), + nightly(10, { tagName: "v1.0.1-nightly.20260905.100" }), + nightly(1, { tagName: "v1.0.1-nightly.20260905.123" }), + nightly(0, { tagName: "v1.0.0" }), + nightly(0, { isDraft: true, tagName: "v1.0.1-nightly.20260905.999" }), ], commitSha: "deadbeef", }); @@ -167,7 +217,23 @@ test("stable releases resolve the commit of the newest published nightly", async test("stable releases derive the version from legacy nightly tags", async () => { const { options } = nightlyCommitFixture({ - releases: [nightly(1, { tag_name: "nightly-v0.9.0-nightly.20260905.5" })], + releases: [nightly(1, { tagName: "nightly-v0.9.0-nightly.20260905.5" })], }); assert.equal((await resolveLatestNightlyCommit(options)).version, "0.9.0"); }); + +test("stable releases read every page, even after a recent nightly", async () => { + const { options, refs } = nightlyCommitFixture({ + pages: [ + [nightly(2, { tagName: "v1.0.1-nightly.20260905.100" })], + [nightly(1, { tagName: "v1.0.1-nightly.20260905.123" })], + ], + }); + assert.equal((await resolveLatestNightlyCommit(options)).tag, "v1.0.1-nightly.20260905.123"); + assert.deepEqual(refs, ["v1.0.1-nightly.20260905.123"]); +}); + +test("stable releases fail when no nightly is published", async () => { + const { options } = nightlyCommitFixture({ releases: [nightly(1, { tagName: "v1.0.0" })] }); + await assert.rejects(resolveLatestNightlyCommit(options), /No published nightly found/); +}); diff --git a/.github/scripts/ci-changes.cjs b/.github/scripts/ci-changes.cjs index ed32670755ff6..7b7332903ed9f 100644 --- a/.github/scripts/ci-changes.cjs +++ b/.github/scripts/ci-changes.cjs @@ -51,6 +51,21 @@ const BUILD_ONLY_DEPS = { t3: ["@t3tools/web"] }; const MOBILE_NATIVE = /^apps\/mobile\/.*\.(swift|kt|kts)$|^apps\/mobile\/(\.swiftlint\.yml|detekt\.yml|\.editorconfig|Brewfile)$|^scripts\/mobile-native-static-check\.ts$|^package\.json$|^\.github\/workflows\/ci\.yml$|^\.github\/scripts\/ci-changes\.cjs$|^\.github\/actions\/ci-changes\//; +// Startup, migration, settlement, and sidebar paths that decide whether an upgraded user's +// threads show after launch. Build runs scripts/smoke-desktop-app.ts for them, so they do not +// first fail in the release launch check. +const DESKTOP_LAUNCH = [ + /^apps\/desktop\/src\/((main|boot|compileCache|serverCompileCache)\.ts$|(app|backend|window)\/)/, + /^apps\/desktop\/src\/electron\/(ElectronApp|ElectronProtocol|ElectronWindow)\.ts$/, + /^apps\/web\/src\/((main|AppRoot|appInit)\.tsx|(bootstrap|router)\.ts)$/, + /^apps\/web\/src\/.*sidebar/i, + /^apps\/server\/src\/(bin|binMain|server|serverRuntimeStartup)\.ts$/, + /^apps\/server\/src\/persistence\/Migrations/, + /^apps\/server\/src\/orchestration-v2\/((ThreadSettlementService|ProjectionStore)\.ts$|legacy\/)/, + /^packages\/contracts\/src\/settings\.ts$/, + /^scripts\/(smoke-desktop-app\.ts|fixtures\/desktop-launch\/)/, +]; + const OWN_TEST_JOB = new Set(["t3", "@t3tools/web", "@t3tools/monorepo"]); function readWorkspace() { @@ -151,12 +166,18 @@ function decide(files, packages, full) { (pkg) => pkg.hasTest && !OWN_TEST_JOB.has(pkg.name) && affected.has(pkg.name), ); const has = (name) => affected.has(name); + const desktopLaunch = + everything || + files.some( + (file) => !/\.test\.tsx?$/.test(file) && DESKTOP_LAUNCH.some((pattern) => pattern.test(file)), + ); return { affected: [...affected].sort(), outputs: { typecheck: affected.size > 0, - build: has("@t3tools/desktop") || has("t3") || has("@t3tools/web"), + build: has("@t3tools/desktop") || has("t3") || has("@t3tools/web") || desktopLaunch, + desktop_launch: desktopLaunch, test: tested.length > 0, // Empty means every package the Test job covers. test_packages: everything ? "" : tested.map((pkg) => pkg.name).join(" "), diff --git a/.github/scripts/ci-changes.d.cts b/.github/scripts/ci-changes.d.cts index afe6f61339362..4640e89776b0d 100644 --- a/.github/scripts/ci-changes.d.cts +++ b/.github/scripts/ci-changes.d.cts @@ -16,6 +16,7 @@ export function decide( outputs: { typecheck: boolean; build: boolean; + desktop_launch: boolean; test: boolean; test_packages: string; test_web: boolean; diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4c45728c2342..1ccf0d626e725 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,6 +27,7 @@ jobs: outputs: typecheck: ${{ steps.detect.outputs.typecheck }} build: ${{ steps.detect.outputs.build }} + desktop_launch: ${{ steps.detect.outputs.desktop_launch }} test: ${{ steps.detect.outputs.test }} test_packages: ${{ steps.detect.outputs.test_packages }} test_web: ${{ steps.detect.outputs.test_web }} @@ -135,13 +136,14 @@ jobs: if: needs.changes.outputs.build != 'false' # Runs in the background while Vite+ installs; the step before the build waits for it. + # Xvfb is for the desktop launch check below. - name: Start installing browser secret helper build libraries if: needs.changes.outputs.build != 'false' run: | sudo sed -i 's|http://|https://|g' /etc/apt/blacksmith-ubuntu-mirrors.txt /etc/apt/sources.list.d/ubuntu.sources ( set +e - sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config + sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config xvfb echo "$?" > "$RUNNER_TEMP/apt-status" ) > "$RUNNER_TEMP/apt.log" 2>&1 < /dev/null & @@ -192,6 +194,60 @@ jobs: if: ${{ !cancelled() && steps.build.outcome == 'success' }} run: node apps/desktop/scripts/verify-preload-bundle.mjs + # The release launch check, run unpackaged against the same old-state fixture, for + # startup and sidebar changes. Packaging and signing stay release-only. + - name: Open the seeded thread in the built desktop app + id: desktop_launch + if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.desktop_launch != 'false' }} + timeout-minutes: 4 + run: | + electron=$(node -p "require('./apps/desktop/node_modules/electron')") + xvfb-run -a node scripts/smoke-desktop-app.ts --executable "$electron" --app apps/desktop \ + --artifacts-dir "$RUNNER_TEMP/desktop-launch-check" + + - name: Upload desktop launch check + if: ${{ failure() && steps.desktop_launch.outcome == 'failure' }} + uses: actions/upload-artifact@v7 + with: + name: desktop-launch-check + path: ${{ runner.temp }}/desktop-launch-check + if-no-files-found: ignore + + # Browser tests run source modules; this boots the production chunk graph. The + # desktop build above already produced apps/web/dist, and the client waits about + # 15s for a session that never comes, so this runs here instead of in Test Web, + # which gates the whole run. Chromium comes from the cache Test Web shares. + - name: Resolve Playwright version + id: playwright_version + if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' }} + run: echo "version=$(node -p "require('./apps/web/node_modules/playwright/package.json').version")" >> "$GITHUB_OUTPUT" + + - name: Cache Chromium + id: chromium_cache + if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' }} + uses: actions/cache@v6 + with: + path: ~/.cache/ms-playwright + key: playwright-chromium-shell-${{ runner.os }}-${{ runner.arch }}-${{ steps.playwright_version.outputs.version }} + + - name: Install Chromium for the built web client boot check + if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' && steps.chromium_cache.outputs.cache-hit != 'true' }} + run: node apps/web/node_modules/playwright/cli.js install --only-shell chromium + + - name: Install missing Chromium system dependencies + if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' }} + run: | + browser=$(find "$HOME/.cache/ms-playwright" -name chrome-headless-shell -type f -print -quit) + test -n "$browser" + if ldd "$browser" | grep '=> not found'; then + node apps/web/node_modules/playwright/cli.js install-deps chromium + fi + + - name: Boot the built web client + if: ${{ !cancelled() && steps.build.outcome == 'success' && needs.changes.outputs.test_web != 'false' }} + timeout-minutes: 3 + run: node apps/web/scripts/verify-built-boot.ts + - name: Typecheck if: ${{ !cancelled() && steps.typecheck.outcome == 'success' }} timeout-minutes: 5 @@ -272,12 +328,18 @@ jobs: env: TEST_PACKAGES: ${{ needs.changes.outputs.test_packages }} run: | + set -o pipefail filters=(--filter '!t3' --filter '!@t3tools/monorepo' --filter '!@t3tools/web') if [[ -n "$TEST_PACKAGES" ]]; then filters=() for package in $TEST_PACKAGES; do filters+=(--filter "$package"); done fi - vp run --parallel --concurrency-limit 4 "${filters[@]}" test + # The runner's trace writer can crash on surrogate pairs in test output. + vp run --parallel --concurrency-limit 4 "${filters[@]}" test 2>&1 | python3 -u -c ' + import sys + for line in sys.stdin: + sys.stdout.write(line.encode("ascii", "backslashreplace").decode("ascii")) + ' # The web suite is the largest outside the server. In the shared Test job it # started last and ran alone for about 40s after everything else finished. @@ -334,12 +396,6 @@ jobs: - name: Test run: vp run --filter @t3tools/web test - # Browser tests run source modules; this boots the production chunk graph. - - name: Boot the built web client - run: | - vp run --filter @t3tools/web build - node apps/web/scripts/verify-built-boot.ts - # apps/server sets `fileParallelism: false`, so its test files run strictly # one at a time. Sharding spreads them over separate runners instead of # separate workers, so no two server test files ever share a machine and the @@ -536,7 +592,7 @@ jobs: needs: changes if: ${{ !cancelled() && needs.changes.outputs.release_smoke != 'false' }} runs-on: blacksmith-8vcpu-ubuntu-2404 - timeout-minutes: 10 + timeout-minutes: 15 steps: - name: Checkout uses: actions/checkout@v6 @@ -587,7 +643,7 @@ jobs: # not needed. Gates are keyed by job name, except merged Build and the # macOS lint. echo "$RESULTS" | jq -e '.changes.outputs as $gates - | {build: ["build", "typecheck"], mobile_native_static_analysis: ["mobile_native"]} as $renamed + | {build: ["build", "typecheck", "desktop_launch"], mobile_native_static_analysis: ["mobile_native"]} as $renamed | all(to_entries[]; .value.result == "success" or (.value.result == "skipped" diff --git a/.github/workflows/desktop-macos-preview.yml b/.github/workflows/desktop-macos-preview.yml index 6dcdd702c2da1..0213f3fce6a99 100644 --- a/.github/workflows/desktop-macos-preview.yml +++ b/.github/workflows/desktop-macos-preview.yml @@ -73,16 +73,27 @@ jobs: # Public T3 Connect identifiers (Clerk publishable key, relay URL). cp .env.example .env - - uses: ./.github/actions/setup-apt-mirrors + # PR heads from before build:desktop:bundle use the full build, which + # compiles the Linux browser secret helper and needs libsecret. + - name: Check bundle-only build support + id: bundle_build + run: | + script="$(node -p "require('./package.json').scripts['build:desktop:bundle'] ? 'build:desktop:bundle' : 'build:desktop'")" + echo "script=$script" >> "$GITHUB_OUTPUT" + + - if: steps.bundle_build.outputs.script == 'build:desktop' + uses: ./.github/actions/setup-apt-mirrors - name: Install browser secret helper build libraries + if: steps.bundle_build.outputs.script == 'build:desktop' run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config - # desktop-macos-preview-publish.yml packages this bundle as the preview channel. + # desktop-macos-preview-publish.yml packages this bundle as the preview + # channel. The Linux browser secret helper is not part of a macOS app. - name: Build JS bundle env: T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && 'preview' || 'dev' }} - run: vp run build:desktop + run: vp run ${{ steps.bundle_build.outputs.script }} # Same layout as release.yml's js-bundle so release-desktop.yml can # package it unchanged. diff --git a/.github/workflows/lazurio-cli-archives.yml b/.github/workflows/lazurio-cli-archives.yml new file mode 100644 index 0000000000000..392128715c8c1 --- /dev/null +++ b/.github/workflows/lazurio-cli-archives.yml @@ -0,0 +1,275 @@ +name: Lazurio CLI archives + +# Builds and tests the per-platform CLI archives that Lazurio Machines install +# and self-update from. Called by lazurio-release.yml before publishing and by +# lazurio-fork-ci.yml on every pull request. Each step reuses upstream's own +# scripts exactly as .github/workflows/release-desktop.yml runs them; see +# docs/operations/lazurio-fork-release.md. + +on: + workflow_call: + inputs: + version: + description: Exact release version (X.Y.Z-lazurio.N) + required: true + type: string + source_sha: + description: Exact 40-character source commit + required: true + type: string + source_repository: + description: Repository that holds the source commit + required: false + default: ${{ github.repository }} + type: string + +permissions: + contents: read + id-token: none + +jobs: + build: + name: Build ${{ matrix.key }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - key: linux-x64 + runner: ubuntu-24.04 + platform: linux + arch: x64 + rust_target: x86_64-unknown-linux-gnu + - key: darwin-arm64 + runner: macos-15 + platform: mac + arch: arm64 + rust_target: aarch64-apple-darwin + env: + VERSION: ${{ inputs.version }} + steps: + - name: Fetch exact source without credentials + shell: bash + env: + SOURCE_SHA: ${{ inputs.source_sha }} + SOURCE_REPOSITORY: ${{ inputs.source_repository }} + GIT_TERMINAL_PROMPT: "0" + run: | + set -euo pipefail + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+-(lazurio\.[0-9]+|preview\.[0-9]{8}\.[0-9]+)$ ]] + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + git init . + git remote add origin "${GITHUB_SERVER_URL}/${SOURCE_REPOSITORY}.git" + git fetch --no-tags --depth=1 origin "$SOURCE_SHA" + git sparse-checkout set --no-cone '/*' '!/.repos/' + git checkout --detach FETCH_HEAD + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 + with: + node-version-file: package.json + cache: true + run-install: false + + - name: Install server and web dependencies + run: vp install --filter=t3... --filter=@t3tools/web... --filter=@t3tools/scripts... + + - name: Setup Rust + uses: dtolnay/rust-toolchain@6bed0761d98439e5a578e2877258200ad565ba87 # stable + with: + toolchain: stable + targets: ${{ matrix.rust_target }} + + # The binary reports apps/server/package.json and the launcher checks it + # for exact equality, so versions are stamped before anything is built. + - name: Align package versions to release version + run: node scripts/update-release-package-versions.ts "$VERSION" + + - name: Build server and web client + run: vp run --filter t3 build + + # The server build bundles the web client with upstream's development + # icons; a release carries upstream's production ones, as upstream's own + # release build does. + - name: Apply upstream's production web icons + run: node scripts/apply-web-brand-assets.ts production apps/server/dist/client + + - name: Build resource monitor + run: cargo build --locked --release --manifest-path native/resource-monitor/Cargo.toml --target "${{ matrix.rust_target }}" + + # The single executable embeds the Node setup-vp installed from package.json's exact + # engines.node; apps/server/vite.config.ts refuses any other. + - name: Build CLI single-executable + run: node apps/server/scripts/cli.ts build-exe --verbose + + - name: Stage resource monitor for the CLI archive + shell: bash + run: | + set -euo pipefail + target_dir="$RUNNER_TEMP/cli-resource-monitor/${{ matrix.key }}" + mkdir -p "$target_dir" + cp "native/resource-monitor/target/${{ matrix.rust_target }}/release/t3-resource-monitor" "$target_dir/t3-resource-monitor" + + # The Linux archive ships libatomic.so.1 and points t3's RUNPATH at it (upstream's + # release-desktop.yml installs patchelf the same way, pingdotgg/t3code#26912). + - name: Install patchelf + if: matrix.platform == 'linux' + shell: bash + run: command -v patchelf || { sudo apt-get update && sudo apt-get install -y patchelf; } + + # No signing identity is configured, so macOS binaries are signed ad hoc, + # as upstream does without CSC_LINK. + - name: Build CLI archive + run: | + node scripts/build-cli-archive.ts \ + --platform "${{ matrix.platform }}" \ + --arch "${{ matrix.arch }}" \ + --version "$VERSION" \ + --resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \ + --output-dir release-cli + + # T3 Code's MIT licence travels with every copy of it. Upstream's archive + # has no place for it, so it is added beside the executable; the launcher + # and the install scripts unpack the archive whole. + - name: Add T3 Code's licence to the CLI archive + shell: bash + run: | + set -euo pipefail + stem="t3-$VERSION-${{ matrix.key }}" + mkdir -p "$RUNNER_TEMP/cli-licence/$stem" + cp LICENSE "$RUNNER_TEMP/cli-licence/$stem/LICENSE" + gzip -d "release-cli/$stem.tar.gz" + tar -rf "release-cli/$stem.tar" -C "$RUNNER_TEMP/cli-licence" "$stem/LICENSE" + gzip -n "release-cli/$stem.tar" + + - name: Check the archive's licence and web icons + shell: bash + run: | + set -euo pipefail + stem="t3-$VERSION-${{ matrix.key }}" + tar -xzOf "release-cli/$stem.tar.gz" "$stem/LICENSE" | cmp - LICENSE + tar -xzOf "release-cli/$stem.tar.gz" "$stem/client/favicon.ico" | cmp - assets/prod/t3-black-web-favicon.ico + + - name: Smoke-test CLI archive + run: node scripts/smoke-cli-archive.ts --archive "release-cli/t3-$VERSION-${{ matrix.key }}.tar.gz" --expect-version "$VERSION" + + - name: Upload CLI archive + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: cli-${{ matrix.key }} + path: release-cli/t3-${{ inputs.version }}-${{ matrix.key }}.tar.gz + if-no-files-found: error + + # Installs the linux-x64 archive the way a Machine's Update does: the release + # directory is served over HTTP in upstream's layout, `t3 update` downloads + # SHA256SUMS and the archive through T3CODE_RELEASE_BASE_URL, verifies the + # checksum, unpacks the runtime and checks its exact version, and the staged + # runtime then answers the launcher's service preflight. Only the service + # restart itself is not exercised; runners have no user service manager. + launcher: + name: Launcher install linux-x64 + needs: build + runs-on: ubuntu-24.04 + timeout-minutes: 20 + env: + VERSION: ${{ inputs.version }} + steps: + - name: Fetch exact source without credentials + shell: bash + env: + SOURCE_SHA: ${{ inputs.source_sha }} + SOURCE_REPOSITORY: ${{ inputs.source_repository }} + GIT_TERMINAL_PROMPT: "0" + run: | + set -euo pipefail + git init . + git remote add origin "${GITHUB_SERVER_URL}/${SOURCE_REPOSITORY}.git" + git fetch --no-tags --depth=1 origin "$SOURCE_SHA" + git sparse-checkout set --no-cone '/*' '!/.repos/' + git checkout --detach FETCH_HEAD + test "$(git rev-parse HEAD)" = "$SOURCE_SHA" + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@250f29ce396baf5e8f24498e17c0dfdebabc26eb # v1 + with: + node-version-file: package.json + cache: true + run-install: false + + - name: Install server dependencies + run: vp install --filter=t3... + + - name: Download linux-x64 archive + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: cli-linux-x64 + path: ${{ runner.temp }}/channel/v${{ inputs.version }} + + # The updating CLI runs from the unstamped source, so it is a different + # version than the target, just like a Machine on the previous release. + # It runs in a pseudo-terminal: a preview target must pass the real + # consent prompt, which refuses without a TTY. The prompt is answered + # only for a preview and must not appear for a stable target. + - name: Install the archive through the release channel + shell: bash + run: | + set -euo pipefail + release_dir="$RUNNER_TEMP/channel/v$VERSION" + (cd "$release_dir" && sha256sum t3-*.tar.gz > SHA256SUMS && cat SHA256SUMS) + + python3 -m http.server 8765 --bind 127.0.0.1 --directory "$RUNNER_TEMP/channel" \ + > "$RUNNER_TEMP/http.log" 2>&1 & + server_pid=$! + trap 'kill "$server_pid"' EXIT + for _ in $(seq 1 50); do + curl --silent --fail --output /dev/null "http://127.0.0.1:8765/v$VERSION/SHA256SUMS" && break + sleep 0.2 + done + + home="$RUNNER_TEMP/t3-home" + expect_prompt=0 + [[ "$VERSION" == *-preview.* ]] && expect_prompt=1 + T3CODE_RELEASE_BASE_URL=http://127.0.0.1:8765 EXPECT_PREVIEW_PROMPT="$expect_prompt" \ + python3 - node apps/server/src/bin.ts update "$VERSION" --base-dir "$home" --allow-downgrade --yes <<'PY' + import os, pty, select, sys + + prompt = b"Install the preview build anyway?" + pid, fd = pty.fork() + if pid == 0: + os.execvp(sys.argv[1], sys.argv[1:]) + seen = b"" + answered = False + while True: + ready, _, _ = select.select([fd], [], [], 900) + if not ready: + sys.exit("t3 update produced no output for 15 minutes") + try: + chunk = os.read(fd, 4096) + except OSError: + break + if not chunk: + break + sys.stdout.buffer.write(chunk) + sys.stdout.flush() + seen = (seen + chunk)[-4096:] + if not answered and prompt in seen: + if os.environ["EXPECT_PREVIEW_PROMPT"] != "1": + sys.exit("a stable target must not ask for preview consent") + os.write(fd, b"y") + answered = True + code = os.waitstatus_to_exitcode(os.waitpid(pid, 0)[1]) + if os.environ["EXPECT_PREVIEW_PROMPT"] == "1" and not answered: + sys.exit("a preview target must ask for consent before installing") + sys.exit(code) + PY + + runtime="$home/runtime/versions/$VERSION/t3" + test "$(cat "$home/runtime/versions/$VERSION/.install-complete")" = "$VERSION" + test "$("$runtime" --version)" = "t3 v$VERSION" + protocol="$(sed -n 's/^export const SERVICE_LAUNCHER_PROTOCOL = \([0-9][0-9]*\) as const;$/\1/p' apps/server/src/cloud/serviceProtocol.ts)" + [[ "$protocol" =~ ^[0-9]+$ ]] + preflight="$("$runtime" __service-preflight --database-path "$home/userdata/state.sqlite" --launcher-protocol "$protocol")" + echo "$preflight" + jq -e --arg version "$VERSION" '.status == "ready" and .version == $version' <<< "$preflight" diff --git a/.github/workflows/lazurio-fork-ci.yml b/.github/workflows/lazurio-fork-ci.yml new file mode 100644 index 0000000000000..19c9abed5e41d --- /dev/null +++ b/.github/workflows/lazurio-fork-ci.yml @@ -0,0 +1,570 @@ +name: Lazurio Fork CI + +# Read-only CI for the Lazurio overlay on upstream T3 Code. Upstream workflows +# need Blacksmith runners and upstream secrets and are disabled in this +# repository's Actions settings; see docs/operations/lazurio-fork-release.md. + +on: + workflow_dispatch: + pull_request: + push: + branches: + - main + +permissions: + contents: read + id-token: none + +concurrency: + group: lazurio-fork-ci-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + UPSTREAM_TAG: v0.1.8 + UPSTREAM_SHA: bf469bb19669671d0df2efda74ed73867a7137c0 + +jobs: + server-and-web: + name: Server and web compatibility + runs-on: ubuntu-24.04 + timeout-minutes: 40 + steps: + - name: Fetch exact source and upstream base without credentials + env: + SOURCE_REF: ${{ github.event.pull_request.head.sha || github.sha }} + SOURCE_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name || github.repository }} + run: | + set -euo pipefail + git init . + git remote add source "https://github.com/${SOURCE_REPOSITORY}.git" + git fetch --filter=blob:none source "$SOURCE_REF" + git checkout --detach FETCH_HEAD + test "$(git rev-parse HEAD)" = "$SOURCE_REF" + + git remote add upstream https://github.com/pingdotgg/t3code.git + git fetch --filter=blob:none upstream \ + "refs/tags/$UPSTREAM_TAG:refs/tags/upstream-$UPSTREAM_TAG" + test "$(git rev-parse "refs/tags/upstream-$UPSTREAM_TAG^{commit}")" = "$UPSTREAM_SHA" + git merge-base --is-ancestor "$UPSTREAM_SHA" HEAD + test "$(git rev-list --merges "$UPSTREAM_SHA..HEAD" --count)" = 0 + + # The overlay is the Lazurio release files plus seams in upstream T3 Code. + # Under apps/, packages/ and scripts/ it changes only the files below, each + # a reviewed decision, grouped by the feature that owns it; its own folders, + # apps/*/src/lazurio/, which upstream does not have, pass whole. Any other + # change there fails. + allowed_upstream_changes=( + # Shared seams, each with the hooks of several features below: the server's + # CLI and runtime config (hosted settings, the managed Folder), SessionStore.ts (the + # hosted session's TTL and cookie, and who a session acts as, signed into its token), + # EnvironmentAuth.ts (a headless MCP client's runtime-mode ceiling, and who a session + # is issued and authenticated as acting for), ServerEnvironment.ts + # (the update notice's descriptor field, and no serverBrowser or triage capability on + # a Lazurio Environment), CodexAdapterV2.ts and its test (a Codex thread's agent-browser + # session in its config, and the question tool's feature on the app-server T3 starts), + # orchestration-v2/runtimeLayer.ts (the managed Folder's guards, the sign-in guard, + # Buddy's one conversation and the record of who acted, as decorators where it builds + # upstream's services), server.ts (the overlay's one route layer, the gate over + # upstream's server browser, no triage on a managed Environment, the agent scope that + # gives a thread's agents its agent-browser session, the `t3` command following the + # version the launcher activated, Buddy's instance without T3's instructions, model or + # effort where it builds its provider instances, one request namespace for the agent + # commands' MCP sessions, and no checkpoints in Buddy's project), ws.ts (the managed + # Folder's config and Buddy's surface for clients, a dispatch run as the session that + # sent it, and no ChatGPT handoff on a Lazurio Environment), index.html + # (the shell slot, the name in the app, and the composer's room for Buddy's launcher), + # main.tsx (the prepared prompt, and the import + # of the design system's light look, root decision 0200, whose one stylesheet is + # apps/web/src/lazurio/theme.css), ChatView.tsx (Environment browser, Buddy's surface + # and its page chip), RightPanelTabs.tsx and rightPanelStore.ts (Environment browser, + # Nová karta), chat/MessagesTimeline.tsx (Buddy's surface with a line above each day, + # and the rows that who acted and Buddy's chat leave), chat/TimelineUserMessageRow.tsx + # (no "Copy prompt link" on a managed Environment, and who sent an agent's folded + # message), sidebar/SidebarChrome.tsx (the shell's column head under every sidebar's + # top row, and the name in the app). + apps/server/src/auth/EnvironmentAuth.ts + apps/server/src/auth/SessionStore.ts + apps/server/src/cli/config.ts + apps/server/src/config.ts + apps/server/src/environment/ServerEnvironment.ts + apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts + apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts + apps/server/src/orchestration-v2/runtimeLayer.ts + apps/server/src/server.ts + apps/server/src/ws.ts + apps/web/index.html + apps/web/src/components/ChatView.tsx + apps/web/src/components/RightPanelTabs.tsx + apps/web/src/components/chat/MessagesTimeline.tsx + apps/web/src/components/chat/TimelineUserMessageRow.tsx + apps/web/src/components/sidebar/SidebarChrome.tsx + apps/web/src/main.tsx + apps/web/src/rightPanelStore.ts + # Hosted configuration: T3CODE_CLIENT_SESSION_TTL, T3CODE_EXTERNAL_ORIGIN (a + # Secure __Host- cookie, and a loopback bind behind that origin counts as reached + # remotely; upstream itself accepts cookie-authenticated requests only from allowed + # origins) and T3CODE_ENVIRONMENT_LABEL. Unset, the server behaves as upstream. + apps/server/src/auth/EnvironmentAuthPolicy.test.ts + apps/server/src/auth/EnvironmentAuthPolicy.ts + apps/server/src/auth/SessionStore.test.ts + apps/server/src/auth/http.ts + apps/server/src/auth/utils.ts + apps/server/src/cli/config.test.ts + apps/server/src/environment/ServerEnvironmentLabel.ts + # In-app update from the configured release channel; proposed upstream. + # T3CODE_RELEASE_REPOSITORY in the server, the launcher and the install scripts, a + # semver release index, and the optional availableServerUpdate descriptor field behind + # the web client's update notice. Once the launcher activates the new version, the + # user's `t3` follows it (Lazurio/t3code#30, server.ts above). Without the variable, the + # distribution's own releases (Lazurio/t3code) are the default (Lazurio/t3code#22); the + # desktop app's SSH runner shares it through cliReleaseDownloadBaseUrl. Upstream's test + # of `t3 update`'s release lookup expects that repository and the index's own paging + # (Lazurio/t3code#97), and upstream's installer test (install.test.ts) names upstream's + # repository, which its fixture serves. The composer's Retry and a saved Environment's + # row offer the advertised target (useSystemComposerBanners.tsx and + # SavedEnvironmentRows.tsx, which v0.1.2 split out of ChatView.tsx and + # ConnectionsSettings.tsx). Since v0.1.3 removed the composer's "update available" + # notice (#25401), the sidebar's update button offers an advertised release: + # updateEverything.logic.ts makes it that server's target, and since v0.1.6 no update + # waits on npm (#27847). Since v0.1.4's one row per machine (#26210), a server whose + # target is not the header's shows its own in UpdateEverythingDialog.tsx, and only a + # server with threadRestartContinuation is promised that its threads resume + # (updateEverything.logic.test.ts covers both). + # ServerEnvironment.test.ts proves that a server the boot service does not manage never + # asks for a release. + apps/server/src/cli/update.test.ts + apps/server/src/cli/update.ts + apps/server/src/cloud/bootService.ts + apps/server/src/cloud/pinnedRuntime.test.ts + apps/server/src/cloud/pinnedRuntime.ts + apps/server/src/cloud/releaseIndex.test.ts + apps/server/src/cloud/releaseIndex.ts + apps/server/src/cloud/selfUpdate.test.ts + apps/server/src/cloud/selfUpdate.ts + apps/server/src/environment/ServerEnvironment.test.ts + apps/web/src/components/chat/useAutoBalanceUpdateBanner.tsx + apps/web/src/components/chat/useSystemComposerBanners.tsx + apps/web/src/components/settings/ConnectionsSettings.tsx + apps/web/src/components/settings/SavedEnvironmentRows.tsx + apps/web/src/components/sidebar/UpdateEverythingDialog.tsx + apps/web/src/components/sidebar/updateEverything.logic.test.ts + apps/web/src/components/sidebar/updateEverything.logic.ts + apps/web/src/versionSkew.test.ts + apps/web/src/versionSkew.ts + packages/contracts/src/environment.ts + packages/shared/src/cliRelease.test.ts + packages/shared/src/cliRelease.ts + scripts/install-scripts.test.ts + scripts/install.ps1 + scripts/install.sh + scripts/install.test.ts + # The Lazurio distribution: its contract test and the release's version check + # with its test. Its other files sit outside + # these folders (Dockerfile.lazurio, the lazurio-* workflows, the runbook and + # the rebuild's skill). + scripts/lazurio-release-contract.test.mjs + scripts/lazurio-release-version.mjs + scripts/lazurio-release-version.test.mjs + # Prepared prompt from the Lazurio shell by link (Lazurio/t3code#35): the link is + # taken off the address at boot (main.tsx, above), kept for the tab without the + # text across upstream's reload after pairing, and the chat layout opens it as an + # unsent draft. + apps/web/src/routes/_chat.tsx + # The name in the app (root decision 0200): T3 Code (Lazurio), from the stage + # label of the distribution's builds (Lazurio where upstream says Beta), with the + # label beside the wordmark in the sidebar, the page title in index.html and the + # web manifest; a preview is a canary, not a nightly. The wordmark and the icons + # stay upstream's. v0.1.3's "failed to start" screen (lib/bootError.ts) takes the + # name from branding.ts too, so upstream's bundled-dev test (bundledDev.test.ts) + # copies the branding files into its temporary Vite root with bootError.ts. + apps/web/public/manifest.webmanifest + apps/web/src/branding.logic.ts + apps/web/src/branding.ts + apps/web/src/bundledDev.test.ts + apps/web/src/lib/bootError.ts + # The Environment browser (root decision 0191, plan DEV-6646, LazurioPlatform F47): + # a thread's agents get its agent-browser session, Codex's through the thread's + # config (CodexAdapterV2.ts, above, whose test expects it) and the others' through the + # agent scope (server.ts, above), and so do a thread's terminals, through the + # environment the terminal manager starts their shells with (terminal/Manager.ts, + # Lazurio/t3code#73). On a Lazurio Environment upstream's server browser + # is neither built nor advertised (server.ts and ServerEnvironment.ts, above), and + # T3's browser tools drive the Environment browser as upstream's preferred preview + # host with upstream's page engine, unchanged, which measures a window Playwright + # does not emulate when asked for renderScale "display" (#19913); + # preview_open's result carries a view and a message, and its description says that a + # person without the inline preview opens the view (Lazurio/t3code#88). One overlay + # layer (server.ts, above) keeps a thread's tabs in its holder file and streams them + # to the web, whose right panel shows them. The web's seams are the shared files above, + # and chat/ThreadServersPanel.tsx, where a plain click on a thread's server opens it in + # a new tab of the Environment browser instead of upstream's preview (#22542). + apps/server/src/mcp/toolkits/preview/tools.ts + # Since v0.1.7 preview_open takes a dev-server target (#28027) and its handler answered + # an open with a target with the navigate result alone; the overlay keeps the open's + # view underneath, and the handler test fails without it. + apps/server/src/mcp/toolkits/preview/handlers.ts + apps/server/src/mcp/toolkits/preview/handlers.test.ts + apps/server/src/terminal/Manager.ts + apps/web/src/components/chat/ThreadServersPanel.tsx + # The managed Lazurio Folder (LazurioPlatform F51): with T3CODE_LAZURIO_FOLDER, Chat + # starts in the Environment's Folder. Its code lives in apps/*/src/lazurio/; these are + # the hooks. The server adopts or creates the Folder's project at startup; decorators + # where runtimeLayer.ts (above) builds the project service, the orchestrator, the + # session manager and the Scratch folders keep projects, commands and agent turns + # there; the VCS service keeps repositories out of the Folder; the settings writer + # applies the Platform's recommended model as the Lazurio project's own model where + # the person chose none for that project; `t3 lazurio` (binCli.ts) reports both, and + # clients learn the Folder (ws.ts, above). The web starts new threads there, leaves out + # what leads elsewhere, including T3's "Copy prompt link" on sent and automation + # messages (TimelineUserMessageRow.tsx, above) and in the palette, whose links open no + # thread there (Lazurio/t3code#77), and shows the managed welcome. Upstream's project + # service tests run through the decorated layer; lazurio/managedFolderVcs.test.ts + # covers the VCS service's hook. + apps/server/src/binCli.ts + apps/server/src/serverRuntimeStartup.ts + apps/server/src/serverSettings.ts + apps/server/src/vcs/VcsProvisioningService.ts + apps/web/src/components/CommandPalette.tsx + apps/web/src/components/GitActionsControl.tsx + apps/web/src/components/Sidebar.tsx + apps/web/src/components/chat/DraftHeroHeadline.tsx + apps/web/src/components/onboarding/FirstRunGate.tsx + apps/web/src/components/sidebar/SidebarThreadHeader.tsx + apps/web/src/hooks/useHandleNewThread.test.ts + apps/web/src/hooks/useHandleNewThread.ts + apps/web/src/routes/welcome.tsx + packages/contracts/src/server.ts + # Sign-in through Lazurio (root decision 0201, Lazurio/t3code#46): on a Lazurio + # Environment Codex and Claude sign in through their CLIs from the Launchpad's + # Getting started page. The web offers that page where it offered T3's own + # "Continue with ChatGPT"; the server refuses T3's own Codex sign-in (runtimeLayer.ts, + # above) and upstream's ChatGPT handoff (ws.ts, above; Lazurio/t3code#145), which the + # web no longer starts through a Lazurio primary, and `t3 lazurio providers` turns + # providers on and reads them again. Its code lives in apps/*/src/lazurio/; these are + # the web's hooks. + apps/web/src/components/settings/AddProviderInstanceDialog.tsx + apps/web/src/components/settings/CodexSetupSection.tsx + # The Environment pairs its own browser (the Admin's decision of 2026-10-17, which + # replaces the rule of 2026-09-21 that a direct visit shows T3's pairing page): without + # a link's or the desktop app's credential the web's auth gate asks its own origin for + # one, which the Launchpad mints with `t3 lazurio pairing` behind the gateway, and a + # session paired on 0.0.45 pairs again. Its code lives in apps/web/src/lazurio/; the + # gate holds two calls. + apps/web/src/environments/primary/auth.ts + # A headless MCP client's runtime-mode ceiling (root decision 0210, addendum 3; proposed + # upstream): `t3 auth session issue --subject mcp-client --runtime-mode-ceiling ` + # issues the ceiling the MCP sign-in's approval grants, so an agent without a browser + # can change threads that run above Supervised (EnvironmentAuth.ts, above). Without the + # flag nothing changes. + apps/server/src/cli/auth.test.ts + apps/server/src/cli/auth.ts + apps/server/src/cliAuthFormat.ts + # Agents work with threads as the Environment's owner (root decision 0210, addendum 3; + # plan DEV-6676): `t3 thread`, `t3 request`, `t3 queue` and `t3 events`. Their code lives + # in apps/server/src/lazurio/ and binCli.ts (above) adds the commands, with upstream's + # own `t3 thread` (#22732) merged into one group; `send --wait` prints the reply + # through upstream's runResultText, which cli/thread.ts exports for it. A thread in + # `t3 events` is the item `t3_thread_list` returns, which OrchestratorMcpService.ts + # exports for it. + apps/server/src/cli/thread.ts + apps/server/src/mcp/OrchestratorMcpService.ts + # Agents ask people through the question tool (root decision 0211, plan DEV-6676): the + # app-server T3 starts gets Codex's feature for request_user_input in Default mode on its + # command line (CodexAdapterV2.ts, above), and every turn's context tells the agent to ask + # with it; the Default mode's text no longer asks for a plain-text question. Its code + # and its tests live in apps/server/src/lazurio/questionTool*.ts. + apps/server/src/provider/CodexDeveloperInstructions.ts + # Buddy's Hermes gets only the person's words (root decision 0210, plan DEV-6676): in + # Buddy's own T3 Code (T3CODE_LAZURIO_BUDDY=1) the ACP instance `buddy` runs Hermes, + # which keeps every prompt in Buddy's memory. The ACP adapter leaves T3's instructions + # out of an instance's prompts where its host says so (AcpT3Instructions; server.ts, + # above, says so for Buddy's instance), and the turn start projects a page context as a + # labelled Czech block for that instance. Since 0210's addendum of HumanAndMachines/Lazurio#648 the Platform + # sets Buddy's model and effort in Hermes's own config: the adapter applies no model + # and only the options a host names where it says so (AcpT3Selection, Hermes's speed + # for Buddy's instance), and the adapter's test checks that on the mock agent + # (AcpAdapterV2.test.ts). Its code lives in apps/server/src/lazurio/buddyPrompt.ts. + apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts + apps/server/src/orchestration-v2/ProviderTurnStartService.ts + packages/provider-acp/src/server/adapter.ts + # Buddy's one conversation (root decision 0210, plan DEV-6676): Buddy's T3 Code is one + # thread in Buddy's layer of the Lazurio Folder, its managed Folder. The server refuses + # forks, rollbacks and any other thread (runtimeLayer.ts, above), takes no checkpoints + # in Buddy's project and keeps linked Environments off (server.ts, above, and the + # settings `t3 environment` builds for itself, cli/environment.ts), applies Buddy's + # defaults once at startup (serverRuntimeStartup.ts, above) and tells clients (ws.ts and + # the contracts' server.ts, above). The web shows Buddy's surface in place of T3's + # sidebar and command palette (__root.tsx) and opens Buddy's thread at `/` + # (_chat.index.tsx); the chat route's shortcuts, which v0.1.3 installs at app start + # (#25366), are off there (shortcuts/chatRouteCommands.ts), and so is upstream's guest + # sharing of a thread (#24104, __root.tsx and runtimeLayer.ts, above), since a + # Personalspace is never shared (root decision 0091); the chat layout leaves out the + # prepared prompt (_chat.tsx, above), the chat its header, thread details and rollbacks + # (ChatView.tsx, above), and the timeline draws a line above each day + # (MessagesTimeline.tsx, above) and no fork button: the row state knows Buddy's surface + # (timelineRowContext.ts) and the assistant row's meta leaves the fork out + # (TimelineAssistantRows.tsx). avatar.webp is Buddy's character from the design system. + # Its code lives in apps/*/src/lazurio/ (buddySurface* and BuddySurface.tsx). + apps/server/src/cli/environment.ts + apps/web/public/assets/avatar.webp + apps/web/src/components/chat/TimelineAssistantRows.tsx + apps/web/src/components/chat/timelineRowContext.ts + apps/web/src/routes/__root.tsx + apps/web/src/routes/_chat.index.tsx + apps/web/src/shortcuts/chatRouteCommands.ts + # The page Buddy is asked from (root decision 0210, plan DEV-6676): in Buddy's surface + # the host page's last valid context is a chip above the composer, which the person can + # remove. While it is there, a message carries the page as a `lazurio-page` record + # with a reference in its text (useComposerSend.ts, from the record ChatView.tsx, above, + # passes it), which Buddy's T3 Code projects as the Czech block (row 23). Composer and + # sent messages show the reference as a page chip where T3 would call an unknown context + # unavailable (composerContextPresentation.tsx and UserMessageContextChips.tsx). Its + # code lives in apps/web/src/lazurio/ (buddySurfacePage.ts, BuddySurfacePageChip.tsx). + # useComposerSend.ts also counts a sent prompt toward upstream's request for a star on + # its repository (#27832) only outside a Lazurio Environment (lazurio/starPrompt.ts). + apps/web/src/components/chat/UserMessageContextChips.tsx + apps/web/src/components/chat/useComposerSend.ts + apps/web/src/components/composerContextPresentation.tsx + # Who acted: Buddy and Delegace (root decision 0210, evening addendum, point 5; plan + # DEV-6676). An agent command whose environment names who it acts as + # (T3CODE_ACTING_SENDER) issues its sessions with that claim signed in (SessionStore.ts + # and EnvironmentAuth.ts, above). An MCP client's invocation carries it to the tools, + # the client surface runs a dispatch as its session (ws.ts, above), the orchestrator's + # decorator records the messages and decisions it sent (runtimeLayer.ts, above), and the + # web marks them: the timeline's rows leave out Delegace's wake (MessagesTimeline.tsx, + # above), an agent's folded message names Buddy (TimelineUserMessageRow.tsx, above) and + # a request Buddy decided carries the mark (TimelineWorkEntryRow.tsx). Its code lives in + # apps/*/src/lazurio/. McpOAuth.ts also gives outside MCP clients thread links on + # T3CODE_EXTERNAL_ORIGIN when it is set, as people open threads there (row 2). + apps/server/src/auth/McpOAuth.ts + apps/server/src/mcp/McpInvocationContext.ts + apps/web/src/components/chat/TimelineWorkEntryRow.tsx + # Buddy's chat reads like a chat with a friend (root decision 0210, addendum of + # 2026-10-22, point 1; plan DEV-6676; row 28): Buddy's surface shows what Buddy writes + # and one quiet line while he works, also on work that still runs after his turn, + # never T3's work rows, and a failed turn as one line in human words + # (MessagesTimeline.tsx, above). The thread's error banner speaks in human words too + # (ChatBannerLane.tsx), and the end of the timeline shows none of the turn's work: no + # background work, goal or child thread's question, and the queue there counts only the + # person's messages (ChatView.tsx, above; v0.1.3 moved them there, #25401). The + # composer asks for a message to Buddy (ChatComposer.tsx). Since 0210's addendum of + # HumanAndMachines/Lazurio#648 its only control is Hermes's Normal / Fast switch, in place of T3's model, + # options, access and mode (ComposerControlsBar.tsx), and the runtime mode it asks for + # is always full access (ChatView.tsx, above). Its queue holds only the person's own + # messages (QueuedRunsControl.tsx). The keys of the terminal, the right panel and the + # choices it does not offer stay the browser's (ChatView.tsx and __root.tsx, above; + # Lazurio/t3code#109). It shows neither T3's terminal nor its right panel, whatever the + # thread holds, and follows no Environment browser tabs (ChatView.tsx, above); a code + # block offers no Run in terminal (MessagesTimeline.tsx, above), and a link in the + # conversation opens in a new tab. Its code lives in apps/web/src/lazurio/ + # (buddySurfaceTimeline.ts, buddySurfaceControls.ts, BuddySurface.tsx). + apps/web/src/components/chat/ChatBannerLane.tsx + apps/web/src/components/chat/ChatComposer.tsx + apps/web/src/components/chat/ComposerControlsBar.tsx + apps/web/src/components/chat/QueuedRunsControl.tsx + # Any steer queues while the running turn waits on the person's answer to a question or + # an approval, instead of aborting the provider's pending callback (row 30, + # Lazurio/t3code#119, Lazurio/t3code#139): the guard in CommandPolicy.ts, a promoted + # message first in the queue (Orchestrator.ts), and their tests. A follow-up sent + # before the provider turn started notes that run (steersRunId in orchestrationV2.ts) + # and steers in once the turn runs (Lazurio/t3code#170): the web composer keeps such a + # message auto while the run is set up (ChatView.logic.ts), and one sent as Queue stays + # queued (composerDispatch.ts, composerCommandKey.ts and ChatComposer.tsx, above). + apps/server/src/orchestration-v2/CommandPolicy.test.ts + apps/server/src/orchestration-v2/CommandPolicy.ts + apps/server/src/orchestration-v2/Orchestrator.ts + apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts + apps/server/src/orchestration-v2/ThreadManagementService.test.ts + apps/web/src/components/ChatView.logic.test.ts + apps/web/src/components/ChatView.logic.ts + apps/web/src/components/chat/composerCommandKey.ts + packages/client-runtime/src/state/composerDispatch.ts + packages/client-runtime/src/state/composerDispatch.test.ts + packages/contracts/src/orchestrationV2.ts + # A follow-up `queue` saved before the v0.1.3 line becomes `steer` once, and the marker + # the web client's settings store next to them keeps a later `queue` (Lazurio/t3code#140; + # the migration is apps/web/src/lazurio/followUpSteerMigration.ts). + apps/web/src/clientPersistenceStorage.ts + apps/web/src/clientPersistenceStorage.test.ts + # A commit, push or pull request runs detached from the socket that started it and + # finishes when that socket closes; the client reports a dropped connection as lost, + # not as a failed action (row 31, Lazurio/t3code#125). ws.ts is listed above. + apps/server/src/git/detachedProgressStream.ts + apps/server/src/git/detachedProgressStream.test.ts + packages/client-runtime/src/state/vcsAction.ts + packages/client-runtime/src/state/vcsAction.test.ts + # A message sent while an ACP agent works steers its running turn through the extension + # request _lazurio/steer instead of cancelling it, where the agent lists + # lazurio.activeSteer in initialize's _meta (row 33, Lazurio/t3code#138): the adapter and + # its test are listed above, effect-acp keeps capabilities._meta, and the mock agent + # answers the request. Such an agent confirms steers (ProviderAdapter.ts): the turn + # control service asks it about a turn that completed while the steer was on its way, + # and only its refusal sends the message as the next turn (Lazurio/t3code#141). + apps/server/scripts/acp-mock-agent.ts + packages/effect-acp/src/client.ts + packages/provider-core/src/server/ProviderAdapter.ts + apps/server/src/orchestration-v2/ProviderTurnControlService.ts + # Native pairing reaches the socket with only requests a Lazurio workspace gateway + # admits, a copy of APPLICATION_PUBLIC_PATHS in HumanAndMachine-ai/Machines (row 34, + # root decision 0157). + packages/client-runtime/src/lazurio/workspaceGateway.test.ts + ) + unexpected="$(git diff --name-only "$UPSTREAM_SHA..HEAD" | + grep -E '^(apps|packages|scripts)/' | + grep -vE '^apps/[^/]+/src/lazurio/' | + grep -vxF -f <(printf '%s\n' "${allowed_upstream_changes[@]}") || true)" + if [ -n "$unexpected" ]; then + echo "Fork overlay changed an upstream file that is not on its allowlist:" >&2 + echo "$unexpected" >&2 + exit 1 + fi + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 + with: + version: 12.14.0 + run_install: false + + - name: Install Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: 26.12.1 + cache: pnpm + + # lazurio-release.yml's version check, run as its verify job runs it: after only the + # same filtered install, before this job's full install. An import that install does + # not cover fails here instead of in a dispatched release. + - name: Install the version check's locked dependencies + run: pnpm install --frozen-lockfile --ignore-scripts --filter @t3tools/shared + + - name: Run the release version check as the release runs it + run: node --test scripts/lazurio-release-version.test.mjs + + - name: Install locked dependencies + run: pnpm install --frozen-lockfile + + - name: Check formatting + run: pnpm exec vp fmt --check + + # Upstream's lint script with upstream's rules (the same rules its own `vp check` + # holds). + - name: Lint + run: pnpm run lint + + - name: Typecheck server and web + run: | + pnpm exec vp run --filter t3 typecheck + pnpm exec vp run --filter @t3tools/web typecheck + + # Upstream's web tests that render React run in headless Chromium (#20797), and so + # does the engine test of upstream's server browser in the gate below. Upstream's + # own test jobs install the same shell this way; web and server pin the same + # Playwright, so one install serves both. + - name: Install Chromium for the browser tests + run: node apps/server/node_modules/playwright-core/cli.js install --with-deps --only-shell chromium + + # The tests come from the diff against the exact upstream base, so a new + # seam is tested without editing this step: every test file the overlay + # adds or changes, and upstream's own tests beside every file it changes + # (X.ts → X.test.ts, X.browser.test.ts and any other X..test.ts). Plus + # the fixed gate below, whatever the diff says. Each package runs its files + # with its own test script. + - name: Test what the overlay changes + run: | + set -euo pipefail + # The fixed gate: every test under these paths runs. It keeps what fork CI + # always ran: the directories whose tests import overlay seams without + # being changed (src/auth: the external origin, the session TTL and the + # server config), both overlay folders (which also hold the tests of the + # environment label, the managed Folder's VCS hook and the right panel's + # "+" and Mod+T, whose upstream test files v0.1.2 deleted), the tests of + # the hosted configuration and the managed Folder (ProjectService.test.ts + # runs upstream's project tests through the decorated project service), the + # engine test of upstream's server browser, which the Environment browser's + # host drives, and the check that the React Compiler compiles every web + # file, the overlay's included. A path that is gone or holds no tests fails + # the step, so a rebuild reviews the gate. + gate=( + apps/server/src/auth + apps/server/src/cli/config.test.ts + apps/server/src/lazurio + apps/server/src/preview/ServerBrowserPage.test.ts + apps/server/src/project/ProjectService.test.ts + apps/server/src/serverSettings.test.ts + apps/web/src/lazurio + apps/web/src/reactCompilerCoverage.test.ts + ) + tests="$RUNNER_TEMP/overlay-tests.tsv" + { + git diff --name-only --diff-filter=d "$UPSTREAM_SHA..HEAD" -- '*.ts' '*.tsx' | + while IFS= read -r file; do + case "$file" in + *.test.ts | *.test.tsx) echo "$file" ;; + *) + for test in "${file%.*}".test.ts "${file%.*}".test.tsx "${file%.*}".*.test.ts "${file%.*}".*.test.tsx; do + if [ -f "$test" ]; then echo "$test"; fi + done + ;; + esac + done + for path in "${gate[@]}"; do + gated="$(git ls-files -- "$path" | grep -E '\.test\.tsx?$' || true)" + if [ -z "$gated" ]; then + echo "The test gate's $path is gone or holds no tests." >&2 + exit 1 + fi + echo "$gated" + done + } | sort -u | + while IFS= read -r test; do + package="$(dirname "$test")" + until [ -f "$package/package.json" ]; do package="$(dirname "$package")"; done + printf '%s\t%s\n' "$package" "${test#"$package"/}" + done > "$tests" + status=0 + for package in $(cut -f1 "$tests" | sort -u); do + files=() + while IFS=$'\t' read -r owner test; do + if [ "$owner" = "$package" ]; then files+=("$test"); fi + done < "$tests" + echo "::group::$package: ${#files[@]} test files" + (cd "$package" && pnpm run test "${files[@]}") || status=1 + echo "::endgroup::" + done + exit "$status" + + - name: Validate Lazurio release contract + run: node --test scripts/lazurio-release-contract.test.mjs + + - name: Build the release image without publishing + run: | + set -euo pipefail + docker build \ + --file Dockerfile.lazurio \ + --build-arg NODE_BASE_IMAGE=node:26.12.1-bookworm@sha256:5c4012d11d9857c42713ba511fbc19645cac1706bb710d51d42b0d301dff7f88 \ + --build-arg PACKAGE_VERSION="${UPSTREAM_TAG#v}-lazurio.0" \ + --build-arg PNPM_VERSION=12.14.0 \ + --build-arg RELEASE_TAG=ci \ + --build-arg SOURCE_DATE_EPOCH="$(git show -s --format=%ct HEAD)" \ + --build-arg SOURCE_REVISION="$(git rev-parse HEAD)" \ + --build-arg UPSTREAM_BASE="$UPSTREAM_SHA" \ + --tag lazurio/t3code:ci \ + . + docker run --rm --network none lazurio/t3code:ci --version | grep -Fx "t3 ${UPSTREAM_TAG}-lazurio.0" + docker image inspect lazurio/t3code:ci \ + --format '{{range .Config.Env}}{{println .}}{{end}}' | \ + grep -Fx 'T3CODE_CLIENT_SESSION_TTL=365d' + docker run --rm --network none --entrypoint cat lazurio/t3code:ci \ + /opt/lazurio-t3/LICENSE | cmp - LICENSE + docker run --rm --network none --entrypoint cat lazurio/t3code:ci \ + /opt/lazurio-t3/dist/client/favicon.ico | cmp - assets/prod/t3-black-web-favicon.ico + + # The same archive build and launcher install the release runs, under the + # never-released version -lazurio.0. Keep it in step with UPSTREAM_TAG. + cli-archives: + name: CLI archives + uses: ./.github/workflows/lazurio-cli-archives.yml + with: + version: 0.1.8-lazurio.0 + source_sha: ${{ github.event.pull_request.head.sha || github.sha }} + source_repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }} diff --git a/.github/workflows/lazurio-release.yml b/.github/workflows/lazurio-release.yml new file mode 100644 index 0000000000000..7d1d713e88de6 --- /dev/null +++ b/.github/workflows/lazurio-release.yml @@ -0,0 +1,445 @@ +name: Lazurio T3 Code Release + +# Manually dispatched from main by the release owner. Builds and tests the CLI +# archives, then waits for approval in the lazurio-t3code-release environment +# before it tags the source, publishes the GitHub Release that Lazurio Machines +# update from, and pushes the matching OCI image. Nothing is ever overwritten. +# The channel follows upstream: X.Y.Z-lazurio.N is stable, X.Y.Z-preview.YYYYMMDD.N +# is preview, published as a GitHub pre-release and never as latest. +# Runbook: docs/operations/lazurio-fork-release.md. + +on: + workflow_dispatch: + inputs: + version: + description: Stable X.Y.Z-lazurio.N or preview X.Y.Z-preview.YYYYMMDD.N (tag v) + required: true + type: string + source_sha: + description: Exact 40-character commit at the tip of main + required: true + type: string + upstream_tag: + description: Exact upstream stable tag the source is based on (vX.Y.Z) + required: true + type: string + upstream_sha: + description: Exact 40-character upstream tag commit + required: true + type: string + +permissions: + contents: read + id-token: none + +concurrency: + group: lazurio-t3code-release + cancel-in-progress: false + +env: + IMAGE: ghcr.io/lazurio/t3code + VERSION: ${{ inputs.version }} + # The verify job accepts only these two shapes, as upstream's cliReleaseChannelOf reads them. + CHANNEL: ${{ contains(inputs.version, '-preview.') && 'preview' || 'stable' }} + RELEASE_TAG: v${{ inputs.version }} + SOURCE_SHA: ${{ inputs.source_sha }} + UPSTREAM_TAG: ${{ inputs.upstream_tag }} + UPSTREAM_SHA: ${{ inputs.upstream_sha }} + +jobs: + verify: + name: Verify source and version + if: github.repository == 'Lazurio/t3code' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - name: Fetch and verify the exact release source + shell: bash + run: | + set -euo pipefail + + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+-(lazurio\.[1-9][0-9]*|preview\.[0-9]{8}\.[1-9][0-9]*)$ ]] + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$UPSTREAM_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$UPSTREAM_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + [[ "$VERSION" == "${UPSTREAM_TAG#v}-"* ]] + test "$GITHUB_REF" = "refs/heads/main" + + git init . + git remote add origin "https://github.com/$GITHUB_REPOSITORY.git" + git fetch --filter=blob:none --no-tags origin \ + "refs/heads/main:refs/remotes/origin/main" + test "$(git rev-parse refs/remotes/origin/main)" = "$SOURCE_SHA" + git checkout --detach "$SOURCE_SHA" + + git remote add upstream https://github.com/pingdotgg/t3code.git + git fetch --filter=blob:none upstream \ + "refs/tags/$UPSTREAM_TAG:refs/tags/upstream-$UPSTREAM_TAG" + test "$(git rev-parse "refs/tags/upstream-$UPSTREAM_TAG^{commit}")" = "$UPSTREAM_SHA" + test "$(git merge-base "$UPSTREAM_SHA" "$SOURCE_SHA")" = "$UPSTREAM_SHA" + test "$(git rev-list --merges "$UPSTREAM_SHA..$SOURCE_SHA" --count)" = 0 + # The base must be the one the source is built on, as its CI pins it. Upstream's + # history is linear, so every older stable tag is an ancestor too, and a release + # named after it would carry newer code under an older version (#69). + test "$(sed -n 's/^ UPSTREAM_TAG: //p' .github/workflows/lazurio-fork-ci.yml)" = "$UPSTREAM_TAG" + test "$(sed -n 's/^ UPSTREAM_SHA: //p' .github/workflows/lazurio-fork-ci.yml)" = "$UPSTREAM_SHA" + + # The same pnpm and Node as lazurio-fork-ci.yml, without its dependency cache, so a release + # never restores state another run wrote. + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10 + with: + version: 12.14.0 + run_install: false + + - name: Install Node.js + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: 26.12.1 + + # The version check imports upstream's cliRelease.ts, which needs effect since + # v0.1.6. Only that package's locked dependencies, without install scripts. + # lazurio-fork-ci.yml runs this install and the check the same way on every PR. + - name: Install the version check's locked dependencies + run: pnpm install --frozen-lockfile --ignore-scripts --filter @t3tools/shared + + # Servers take the newest non-draft release on their own channel as the + # one to update to, so a release must be the highest version on its + # channel. Channels are derived from the version exactly as upstream's + # cliReleaseChannelOf does; a preview never competes with stable. + - name: Refuse an existing or non-increasing version + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: bash + run: | + set -euo pipefail + + if [[ -n "$(git ls-remote origin "refs/tags/$RELEASE_TAG")" ]]; then + echo "Tag $RELEASE_TAG already exists." >&2 + exit 1 + fi + gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/releases?per_page=100" > "$RUNNER_TEMP/releases.json" + node scripts/lazurio-release-version.mjs "$RUNNER_TEMP/releases.json" + + archives: + name: CLI archives + needs: verify + uses: ./.github/workflows/lazurio-cli-archives.yml + with: + version: ${{ inputs.version }} + source_sha: ${{ inputs.source_sha }} + + publish: + name: Publish release and image + needs: [verify, archives] + runs-on: ubuntu-24.04 + timeout-minutes: 45 + environment: lazurio-t3code-release + permissions: + attestations: write + contents: write + id-token: write + packages: write + env: + RELEASE_CONTROL: ${{ vars.LAZURIO_T3CODE_RELEASE_CONTROL }} + steps: + # Runs after approval and before any side effect. main may have moved + # while the run waited; then this release is stale and stops here. + - id: source + name: Recheck the release source after approval + shell: bash + env: + APP_ID_PRESENT: ${{ vars.LAZURIO_RELEASE_APP_ID != '' }} + APP_KEY_PRESENT: ${{ secrets.LAZURIO_RELEASE_APP_PRIVATE_KEY != '' }} + run: | + set -euo pipefail + test "$RELEASE_CONTROL" = "reviewed-v1" + if [[ "$APP_ID_PRESENT" != "true" || "$APP_KEY_PRESENT" != "true" ]]; then + echo "Release App variable LAZURIO_RELEASE_APP_ID or secret LAZURIO_RELEASE_APP_PRIVATE_KEY is missing; nothing was published." >&2 + exit 1 + fi + + git init . + git remote add origin "https://github.com/$GITHUB_REPOSITORY.git" + git fetch --filter=blob:none --no-tags origin \ + "refs/heads/main:refs/remotes/origin/main" + if [[ "$(git rev-parse refs/remotes/origin/main)" != "$SOURCE_SHA" ]]; then + echo "main moved away from $SOURCE_SHA since dispatch; nothing was published." >&2 + exit 1 + fi + git checkout --detach "$SOURCE_SHA" + git remote add upstream https://github.com/pingdotgg/t3code.git + git fetch --filter=blob:none upstream \ + "refs/tags/$UPSTREAM_TAG:refs/tags/upstream-$UPSTREAM_TAG" + test "$(git rev-parse "refs/tags/upstream-$UPSTREAM_TAG^{commit}")" = "$UPSTREAM_SHA" + + source_date_epoch="$(git show -s --format=%ct HEAD)" + echo "source_date_epoch=$source_date_epoch" >> "$GITHUB_OUTPUT" + echo "source_date_iso=$(date -u -d "@$source_date_epoch" +'%Y-%m-%dT%H:%M:%SZ')" >> "$GITHUB_OUTPUT" + + - name: Download CLI archives + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + pattern: cli-* + merge-multiple: true + path: release-assets + + # Installers verify archives against this file, so it is written from the + # exact bytes that get uploaded, in upstream's sha256sum format. + - name: Write CLI archive checksums + shell: bash + run: | + set -euo pipefail + cd release-assets + test "$(ls)" = "$(printf '%s\n' "t3-$VERSION-darwin-arm64.tar.gz" "t3-$VERSION-linux-x64.tar.gz")" + sha256sum t3-*.tar.gz > SHA256SUMS + cat SHA256SUMS + + # One attestation per archive: attestation-url is only set for a + # single subject, and each archive gets its own link in the evidence. + - id: attest_linux + name: Attest the linux-x64 archive + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 + with: + subject-path: release-assets/t3-${{ inputs.version }}-linux-x64.tar.gz + + - id: attest_darwin + name: Attest the darwin-arm64 archive + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 + with: + subject-path: release-assets/t3-${{ inputs.version }}-darwin-arm64.tar.gz + + - name: Log in to GitHub Container Registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Refuse an existing image tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: bash + run: | + set -euo pipefail + package_versions="$(mktemp)" + if ! gh api --paginate --slurp \ + "orgs/Lazurio/packages/container/t3code/versions?per_page=100" > "$package_versions" + then + echo "Unable to enumerate GHCR package versions." >&2 + exit 1 + fi + tag_query_status=0 + jq -e --arg tag "$VERSION" \ + '[.[][] | .metadata.container.tags[]?] | index($tag) != null' \ + "$package_versions" >/dev/null || tag_query_status=$? + if (( tag_query_status == 0 )); then + echo "OCI tag $IMAGE:$VERSION already exists and will not be overwritten." >&2 + exit 1 + fi + if (( tag_query_status != 1 )); then + echo "Unable to evaluate GHCR package version metadata." >&2 + exit 1 + fi + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - id: build + name: Build and publish the immutable image + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: . + file: Dockerfile.lazurio + platforms: linux/amd64 + push: true + pull: true + tags: ${{ env.IMAGE }}:${{ env.VERSION }} + provenance: mode=max + sbom: true + build-args: | + NODE_BASE_IMAGE=node:26.12.1-bookworm@sha256:5c4012d11d9857c42713ba511fbc19645cac1706bb710d51d42b0d301dff7f88 + PACKAGE_VERSION=${{ env.VERSION }} + PNPM_VERSION=12.14.0 + RELEASE_TAG=${{ env.RELEASE_TAG }} + SOURCE_DATE_EPOCH=${{ steps.source.outputs.source_date_epoch }} + SOURCE_REVISION=${{ env.SOURCE_SHA }} + UPSTREAM_BASE=${{ env.UPSTREAM_SHA }} + labels: | + org.opencontainers.image.created=${{ steps.source.outputs.source_date_iso }} + org.opencontainers.image.description=Lazurio T3 Code: a modified distribution of T3 Code for Lazurio Environments + org.opencontainers.image.licenses=MIT + org.opencontainers.image.revision=${{ env.SOURCE_SHA }} + org.opencontainers.image.source=https://github.com/Lazurio/t3code + org.opencontainers.image.title=Lazurio T3 Code + org.opencontainers.image.url=https://github.com/Lazurio/t3code + org.opencontainers.image.vendor=Lazurio + org.opencontainers.image.version=${{ env.VERSION }} + + - name: Verify the published image + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + shell: bash + run: | + set -euo pipefail + docker pull "$IMAGE@$IMAGE_DIGEST" + docker image inspect "$IMAGE@$IMAGE_DIGEST" \ + --format '{{range .Config.Env}}{{println .}}{{end}}' | \ + grep -Fx 'T3CODE_CLIENT_SESSION_TTL=365d' + docker run --rm --network none "$IMAGE@$IMAGE_DIGEST" --version | \ + grep -Fx "t3 v$VERSION" + docker run --rm --network none --entrypoint cat "$IMAGE@$IMAGE_DIGEST" \ + /opt/lazurio-t3/LICENSE | cmp - LICENSE + docker run --rm --network none --entrypoint cat "$IMAGE@$IMAGE_DIGEST" \ + /opt/lazurio-t3/dist/client/favicon.ico | cmp - assets/prod/t3-black-web-favicon.ico + + - id: attest_image + name: Attest the published OCI digest + uses: actions/attest-build-provenance@977bb373ede98d70efdf65b84cb5f73e068dcc2a # v3 + with: + subject-name: ${{ env.IMAGE }} + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + + - name: Assemble release notes and evidence + env: + LINUX_ATTESTATION: ${{ steps.attest_linux.outputs.attestation-url }} + DARWIN_ATTESTATION: ${{ steps.attest_darwin.outputs.attestation-url }} + IMAGE_ATTESTATION: ${{ steps.attest_image.outputs.attestation-url }} + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} + shell: bash + run: | + set -euo pipefail + jq -n --sort-keys \ + --arg repository "https://github.com/$GITHUB_REPOSITORY" \ + --arg source "$SOURCE_SHA" \ + --arg tag "$RELEASE_TAG" \ + --arg version "$VERSION" \ + --arg channel "$CHANNEL" \ + --arg upstream_tag "$UPSTREAM_TAG" \ + --arg upstream_sha "$UPSTREAM_SHA" \ + --arg image "$IMAGE" \ + --arg digest "$IMAGE_DIGEST" \ + --arg linux_attestation "$LINUX_ATTESTATION" \ + --arg darwin_attestation "$DARWIN_ATTESTATION" \ + --arg image_attestation "$IMAGE_ATTESTATION" \ + --arg run "$RUN_URL" \ + --rawfile checksums release-assets/SHA256SUMS \ + '{ + schema_version: "t3code.fork-release.v3", + source: { + repository: $repository, + commit: $source, + tag: $tag, + version: $version, + channel: $channel, + upstream_repository: "https://github.com/pingdotgg/t3code", + upstream_release: $upstream_tag, + upstream_base: $upstream_sha + }, + artifact: { + archives: ($checksums | split("\n") | map(select(length > 0) | split(" ") | {name: .[1], sha256: .[0]})), + checksums: "SHA256SUMS", + image: $image, + digest: $digest + }, + configuration: { + base_path: "/", + client_session_ttl: "365d", + external_origin: "runtime T3CODE_EXTERNAL_ORIGIN", + environment_label: "runtime T3CODE_ENVIRONMENT_LABEL" + }, + validation: { + workflow_run: $run, + archive_attestations: { + "linux-x64": $linux_attestation, + "darwin-arm64": $darwin_attestation + }, + image_attestation: $image_attestation + } + }' > release-assets/release-evidence.json + + { + echo "Lazurio T3 Code, a modified distribution of T3 Code $UPSTREAM_TAG for Lazurio" + echo "Environments: T3 Code's server and web client with the Lazurio overlay, served at the" + echo "root of its own hostname. Lazurio Environments update to it from this release." + echo + if [[ "$CHANNEL" == preview ]]; then + echo "Preview: never offered as an update. Install it on a chosen Environment with" + echo "\`t3 update $VERSION\`; return with \`t3 update --channel stable --allow-downgrade\`." + echo + fi + echo "- Source: \`$SOURCE_SHA\`" + echo "- Upstream base: \`$UPSTREAM_TAG\` at \`$UPSTREAM_SHA\`" + echo "- OCI image: \`$IMAGE:$VERSION\` = \`$IMAGE@$IMAGE_DIGEST\`" + echo "- linux-x64 archive attestation: $LINUX_ATTESTATION" + echo "- darwin-arm64 archive attestation: $DARWIN_ATTESTATION" + echo "- Image attestation: $IMAGE_ATTESTATION" + echo + echo "## Lazurio overlay" + echo + git log --no-merges --pretty='format:- %s (%h)' "$UPSTREAM_SHA..$SOURCE_SHA" + echo + echo + echo "Source code: https://github.com/$GITHUB_REPOSITORY/tree/$SOURCE_SHA. Licensed under the" + echo "MIT License, like T3 Code, except the Lazurio brand assets (the Lazurio symbol and Buddy's" + echo "character), which are not under it:" + echo "https://github.com/$GITHUB_REPOSITORY/blob/$SOURCE_SHA/apps/web/src/lazurio/brand/README.md." + echo "Each archive and the image include T3 Code's LICENSE." + } > "$RUNNER_TEMP/RELEASE_NOTES.md" + + # Release tags can only be created by the Lazurio T3 Code Release App, + # whose private key is a secret of this environment, so only an + # approved run can tag. The token is scoped to this repository. + - id: release_app + name: Mint the release App token + uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2 + with: + app-id: ${{ vars.LAZURIO_RELEASE_APP_ID }} + private-key: ${{ secrets.LAZURIO_RELEASE_APP_PRIVATE_KEY }} + owner: Lazurio + repositories: t3code + permission-contents: write + + # The API refuses an existing ref, so a tag that appeared since + # verification stops the release here. + - name: Tag the exact source with the release App + env: + GH_TOKEN: ${{ steps.release_app.outputs.token }} + shell: bash + run: | + set -euo pipefail + if [[ "$(git ls-remote origin refs/heads/main | cut -f1)" != "$SOURCE_SHA" ]]; then + echo "main moved away from $SOURCE_SHA; the release is not tagged." >&2 + exit 1 + fi + gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \ + -f ref="refs/tags/$RELEASE_TAG" -f sha="$SOURCE_SHA" > /dev/null + test "$(gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$RELEASE_TAG" --jq .object.sha)" = "$SOURCE_SHA" + + - name: Publish the GitHub Release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + shell: bash + run: | + set -euo pipefail + if [[ "$CHANNEL" == preview ]]; then + channel_flags=(--prerelease --latest=false) + else + channel_flags=(--latest) + fi + gh release create "$RELEASE_TAG" \ + --repo "$GITHUB_REPOSITORY" \ + --verify-tag \ + --title "Lazurio T3 Code $RELEASE_TAG" \ + --notes-file "$RUNNER_TEMP/RELEASE_NOTES.md" \ + "${channel_flags[@]}" \ + "release-assets/t3-$VERSION-darwin-arm64.tar.gz" \ + "release-assets/t3-$VERSION-linux-x64.tar.gz" \ + release-assets/SHA256SUMS \ + release-assets/release-evidence.json + test "$(gh release view "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --json isPrerelease --jq .isPrerelease)" = "$([[ "$CHANNEL" == preview ]] && echo true || echo false)" + if [[ "$CHANNEL" == preview ]]; then + test "$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)" != "$RELEASE_TAG" + fi diff --git a/.github/workflows/lazurio-upstream-watch.yml b/.github/workflows/lazurio-upstream-watch.yml new file mode 100644 index 0000000000000..52579c4b850d0 --- /dev/null +++ b/.github/workflows/lazurio-upstream-watch.yml @@ -0,0 +1,77 @@ +name: Lazurio upstream watch + +# Once a day: when upstream T3 Code has a stable release newer than the base of main +# (UPSTREAM_TAG in lazurio-fork-ci.yml), opens the rebuild's tracking issue from the runbook's +# template, or comments once on the open one. It reads upstream's public releases and this +# repository's files and writes only issues here, with this repository's token. The rebuild, +# the swap of main and the releases stay with people. +# Runbook: docs/operations/lazurio-fork-release.md, "Nové stabilní vydání upstreamu". + +on: + schedule: + - cron: "41 5 * * *" + workflow_dispatch: + +permissions: + contents: read + issues: write + +jobs: + watch: + name: Upstream stable release + if: github.repository == 'Lazurio/t3code' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Open or update the rebuild's tracking issue + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + shell: bash + run: | + set -euo pipefail + raw() { gh api "repos/$REPO/contents/$1?ref=main" -H "Accept: application/vnd.github.raw"; } + + base="$(raw .github/workflows/lazurio-fork-ci.yml | sed -n 's/^ UPSTREAM_TAG: //p')" + latest="$(gh release list --repo pingdotgg/t3code --exclude-drafts --exclude-pre-releases \ + --limit 20 --json tagName \ + --jq 'map(.tagName | select(test("^v[0-9]+\\.[0-9]+\\.[0-9]+$")))[0] // ""')" + if [[ ! "$base" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ || ! "$latest" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "Unexpected tags: main's UPSTREAM_TAG '$base', upstream's newest stable '$latest'." >&2 + exit 1 + fi + if [[ "$(printf '%s\n' "$base" "$latest" | sort -V | tail -n 1)" == "$base" ]]; then + echo "main is built on $base; upstream's newest stable release is $latest." + exit 0 + fi + + # The tag's commit: an annotated tag advertises it as ^{} beside the tag object; a + # lightweight tag is the commit itself. + refs="$(git ls-remote https://github.com/pingdotgg/t3code.git "refs/tags/$latest" "refs/tags/$latest^{}")" + sha="$(awk -v ref="refs/tags/$latest^{}" '$2 == ref { print $1 }' <<<"$refs")" + if [[ -z "$sha" ]]; then + sha="$(awk -v ref="refs/tags/$latest" '$2 == ref { print $1 }' <<<"$refs")" + fi + if [[ ! "$sha" =~ ^[0-9a-f]{40}$ ]]; then + echo "Upstream's tag $latest does not resolve to exactly one commit ('$sha')." >&2 + exit 1 + fi + marker="" + note="$marker + Upstream T3 Code vydal stabilní vydání [$latest](https://github.com/pingdotgg/t3code/releases/tag/$latest) (commit \`$sha\`). \`main\` stojí na $base. Postup: [Nové stabilní vydání upstreamu](https://github.com/$REPO/blob/main/docs/operations/lazurio-fork-release.md#nové-stabilní-vydání-upstreamu)." + + # One tracking issue at a time: a newer stable during a rebuild is noted in the open one. + issue="$(gh issue list --repo "$REPO" --state open --limit 500 --json number,title \ + --jq 'map(select(.title | startswith("Přestavba na upstream T3 Code ")))[0].number // ""')" + if [[ -z "$issue" ]]; then + template="$(raw docs/operations/lazurio-fork-release.md | + sed -n '/^$/,/^$/p')" + test -n "$template" + gh issue create --repo "$REPO" --title "Přestavba na upstream T3 Code $latest" \ + --body "$note"$'\n\n'"$template" + elif [[ "$(gh issue view "$issue" --repo "$REPO" --json body,comments \ + --jq '[.body, .comments[].body] | join("\n")')" != *"$marker"* ]]; then + gh issue comment "$issue" --repo "$REPO" --body "$note" + else + echo "Issue #$issue already notes $latest." + fi diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 3af4e6abeafe9..b227a2b8b12fe 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -77,6 +77,12 @@ on: required: false default: "" type: string + # Whether this job saves the workspace pnpm store. Release's two Macs + # install the same store on the same runner type, so only one saves it. + save_pnpm_store: + required: false + default: true + type: boolean version: required: true type: string @@ -160,6 +166,7 @@ jobs: uses: ./.github/actions/setup-ci-deps with: install-args: --filter=@t3tools/desktop... --filter=t3... --filter=@t3tools/scripts... + save-pnpm-store: ${{ inputs.save_pnpm_store }} env: pnpm_config_cache_dir: ${{ runner.temp }}/pnpm-metadata @@ -203,6 +210,20 @@ jobs: native/hyprland-snap-shot/target/${{ inputs.rust_target }}/release/t3-hyprland-snap-shot key: linux-capture-helpers-${{ inputs.rust_target }}-${{ hashFiles('native/kde-snap-shot/Cargo.lock', 'native/kde-snap-shot/Cargo.toml', 'native/kde-snap-shot/src/**', 'native/hyprland-snap-shot/Cargo.lock', 'native/hyprland-snap-shot/Cargo.toml', 'native/hyprland-snap-shot/src/**', 'native/hyprland-snap-shot/protocols/**') }} + # Every Linux build makes electron-builder fetch the AppImage runtime, FPM + # for the deb, and the 7-Zip that unpacks FPM from GitHub releases. It + # checks an archive found here against the SHA-256 pinned in those toolset + # files and downloads again on a mismatch, so only raw archives are cached. + - name: Cache Linux packaging tool archives + if: inputs.platform == 'linux' + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: | + ~/.cache/electron-builder/appimage@*/appimage-tools-runtime-*.tar.gz + ~/.cache/electron-builder/fpm@*/fpm-*.7z + ~/.cache/electron-builder/7zip@*/7zip-linux-*.tar.gz + key: electron-builder-linux-tools-${{ inputs.arch }}-${{ hashFiles('node_modules/.pnpm/app-builder-lib@*/node_modules/app-builder-lib/out/toolsets/linux.js', 'node_modules/.pnpm/app-builder-lib@*/node_modules/app-builder-lib/out/toolsets/7zip.js') }} + - name: Ensure Rosetta for macOS x64 bytecode generation if: inputs.platform == 'mac' && inputs.arch == 'x64' shell: bash @@ -408,6 +429,7 @@ jobs: run: command -v patchelf || { sudo apt-get update && sudo apt-get install -y patchelf; } - name: Build CLI archive + id: build_cli if: inputs.cli_archive shell: bash env: @@ -425,37 +447,52 @@ jobs: AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }} run: | set -euo pipefail - if [[ "${{ inputs.platform }}" == "mac" && -n "${APPLE_API_KEY:-}" ]]; then - key_path="$RUNNER_TEMP/AuthKey_cli_${APPLE_API_KEY_ID}.p8" - printf '%s' "$APPLE_API_KEY" > "$key_path" - export APPLE_API_KEY="$key_path" + extra_args=() + if [[ "${{ inputs.platform }}" == "mac" ]]; then + if [[ -n "${APPLE_API_KEY:-}" ]]; then + key_dir="$(mktemp -d "$RUNNER_TEMP/t3-cli-notary.XXXXXXXX")" + trap 'rm -rf "$key_dir"' EXIT + key_path="$key_dir/AuthKey.p8" + (umask 077 && printf '%s' "$APPLE_API_KEY" > "$key_path") + export APPLE_API_KEY="$key_path" + fi + # Older release refs lack deferred notarization and still wait here. + cli_help="$(node scripts/build-cli-archive.ts --help)" + if [[ "$cli_help" == *--notary-submission-file* ]]; then + extra_args=(--notary-submission-file "$RUNNER_TEMP/t3-cli-notary-submission") + echo "deferred_notarization=true" >> "$GITHUB_OUTPUT" + fi fi node scripts/build-cli-archive.ts \ --platform "${{ inputs.platform }}" \ --arch "${{ inputs.arch }}" \ --version "${{ inputs.version }}" \ --resource-monitor-dir "$RUNNER_TEMP/cli-resource-monitor" \ - --output-dir release-cli + --output-dir release-cli \ + ${extra_args[@]+"${extra_args[@]}"} - name: Smoke-test CLI archive if: inputs.cli_archive && inputs.verify_runner == '' shell: bash run: node scripts/smoke-cli-archive.ts --archive release-cli/* --expect-version "${{ inputs.version }}" + # macOS uploads its archive after "Await CLI notarization" instead. - name: Upload CLI archive - if: inputs.cli_archive + if: inputs.cli_archive && inputs.platform != 'mac' uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 with: name: cli-${{ inputs.platform }}-${{ inputs.arch }} path: release-cli/* if-no-files-found: error + # The archive is already gzip or zip; deflating it again saves under 2%. + compression-level: 0 - name: Install Linux desktop build libraries if: inputs.platform == 'linux' shell: bash run: | sudo apt-get update - sudo apt-get install -y libsecret-1-dev pkg-config + sudo apt-get install -y libsecret-1-dev pkg-config libgtk-3-0t64 libnss3 libasound2t64 libgbm1 if ! command -v magick >/dev/null 2>&1 && ! command -v convert >/dev/null 2>&1; then sudo apt-get install -y imagemagick fi @@ -618,6 +655,39 @@ jobs: vp run dist:desktop:artifact "${args[@]}" + # The CLI was submitted without waiting so Apple reviews it while the + # desktop builds. Notarization does not change the archive bytes, but + # nothing uploads them, so nothing publishes them, until Apple accepts. + # With signing configured, a missing submission id fails this step. + - name: Await CLI notarization + if: inputs.cli_archive && inputs.platform == 'mac' && steps.build_cli.outputs.deferred_notarization == 'true' + shell: bash + env: + APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} + APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} + APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} + run: | + set -euo pipefail + if [[ -n "${APPLE_API_KEY:-}" ]]; then + key_dir="$(mktemp -d "$RUNNER_TEMP/t3-cli-notary.XXXXXXXX")" + trap 'rm -rf "$key_dir"' EXIT + key_path="$key_dir/AuthKey.p8" + (umask 077 && printf '%s' "$APPLE_API_KEY" > "$key_path") + export APPLE_API_KEY="$key_path" + fi + node scripts/build-cli-archive.ts await-notarization \ + --submission-file "$RUNNER_TEMP/t3-cli-notary-submission" + + - name: Upload notarized CLI archive + if: inputs.cli_archive && inputs.platform == 'mac' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: cli-${{ inputs.platform }}-${{ inputs.arch }} + path: release-cli/* + if-no-files-found: error + # The archive is already gzip or zip; deflating it again saves under 2%. + compression-level: 0 + # Warm installs only touch the store index, so new content means a fetch. - name: Check staged install cache for new content id: stage_pnpm_changed @@ -761,6 +831,8 @@ jobs: name: desktop-${{ inputs.platform }}-${{ inputs.arch }} path: release-publish/* if-no-files-found: error + # Installers, zips and blockmaps are already compressed; deflating them again saves under 0.3%. + compression-level: 0 - name: Upload resource monitor uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 82f39f8034cc4..c56c76be7e0e7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -69,6 +69,8 @@ jobs: env: DISPATCH_CHANNEL: ${{ inputs.channel }} with: + # Every call here is a read; retry GitHub's transient 5xx and dropped connections. + retries: 3 script: | const { assertCommitOnDefaultBranch, @@ -517,6 +519,8 @@ jobs: if: ${{ !cancelled() && needs.preflight.result == 'success' && needs.relay_public_config.result == 'success' }} runs-on: blacksmith-32vcpu-ubuntu-2404 timeout-minutes: 30 + outputs: + npm_launcher_artifact_id: ${{ steps.npm_launcher.outputs.artifact-id }} env: T3CODE_CLERK_PUBLISHABLE_KEY: ${{ needs.relay_public_config.outputs.clerk_publishable_key }} T3CODE_CLERK_JWT_TEMPLATE: ${{ needs.relay_public_config.outputs.clerk_jwt_template }} @@ -565,22 +569,32 @@ jobs: - name: Align package versions to release version run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}" - - uses: ./.github/actions/setup-apt-mirrors + # Older release refs lack build:desktop:bundle and use the full build, + # which compiles the Linux browser secret helper and needs libsecret. + - name: Check bundle-only build support + id: bundle_build + run: | + script="$(node -p "require('./package.json').scripts['build:desktop:bundle'] ? 'build:desktop:bundle' : 'build:desktop'")" + echo "script=$script" >> "$GITHUB_OUTPUT" + + - if: steps.bundle_build.outputs.script == 'build:desktop' + uses: ./.github/actions/setup-apt-mirrors - # @t3tools/desktop#build compiles the Linux browser secret helper on a - # Linux host before packing, and that needs libsecret headers. - name: Install browser secret helper build libraries + if: steps.bundle_build.outputs.script == 'build:desktop' run: sudo apt-get update && sudo apt-get install -y libsecret-1-dev pkg-config - # Runs t3#build (which depends on @t3tools/web#build) and - # @t3tools/desktop#build, so apps/server/dist holds the server bundle - # plus the web client and apps/desktop/dist-electron the Electron main. + # Runs t3#build (which depends on @t3tools/web#build) and the desktop + # bundle, so apps/server/dist holds the server bundle plus the web client + # and apps/desktop/dist-electron the Electron main. build:desktop:bundle + # skips the Linux browser secret helper, which this artifact does not + # carry; each Linux package job compiles its own per arch. # The release channel is already stable, nightly, or preview. Builds in # other repositories report "dev" telemetry. - name: Build JS bundle env: T3CODE_TELEMETRY_CHANNEL: ${{ github.repository == 'pingdotgg/t3code' && needs.preflight.outputs.release_channel || 'dev' }} - run: vp run build:desktop + run: vp run ${{ steps.bundle_build.outputs.script }} # Two paths under apps/ so the artifact root is apps/; consumers download # into `apps` to restore both at their original locations. @@ -594,6 +608,22 @@ jobs: if-no-files-found: error retention-days: 1 + # publish_cli publishes this exact tarball, so the trusted publisher + # needs no workspace checkout or install. It is version-matched here. + - name: Build the npm launcher + run: node scripts/build-npm-launcher.ts --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages + + # GitHub allows a failed-jobs rerun for 30 days. publish_cli downloads + # this upload by its ID, which a publish_cli-only rerun keeps. + - name: Upload the npm launcher + id: npm_launcher + uses: actions/upload-artifact@v7 + with: + name: npm-launcher + path: npm-packages/t3.tgz + if-no-files-found: error + retention-days: 30 + # One job per platform and architecture (see release-desktop.yml), each # gated only on the JS bundle. Windows targets build on Linux and run their # native checks on a Windows runner of their own architecture. @@ -625,6 +655,8 @@ jobs: resource_key: darwin-arm64 cli_archive: true launch_check: true + # desktop_mac_x64 saves the shared pnpm store; this job finishes last. + save_pnpm_store: false desktop_mac_x64: name: Desktop macOS x64 @@ -796,6 +828,24 @@ jobs: with: install-args: --filter=@t3tools/scripts... + # Overlaps the artifact downloads. The wait below ends it before any + # workspace script runs, so the Play key lives only in this process. + # `exec` lets the runner's stop signals reach node directly. + - id: android_apk + name: Download nightly Android APK + if: needs.preflight.outputs.release_channel == 'nightly' + background: true + continue-on-error: true + timeout-minutes: 5 + env: + GOOGLE_PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT_JSON }} + PACKAGE_NAME: com.t3tools.t3code + APK_OUTPUT_DIR: ${{ runner.temp }}/android-apk + run: | + if [ -n "$GOOGLE_PLAY_SERVICE_ACCOUNT_JSON" ]; then + exec node .github/scripts/mirror-play-apk.cjs + fi + - name: Download all desktop artifacts uses: actions/download-artifact@v8 with: @@ -810,18 +860,6 @@ jobs: merge-multiple: true path: release-assets - - name: Download internal Android APK for Nightly - if: needs.preflight.outputs.release_channel == 'nightly' - continue-on-error: true - env: - GOOGLE_PLAY_SERVICE_ACCOUNT_JSON: ${{ secrets.GOOGLE_PLAY_SERVICE_ACCOUNT_JSON }} - PACKAGE_NAME: com.t3tools.t3code - APK_OUTPUT_DIR: release-assets - run: | - if [ -n "$GOOGLE_PLAY_SERVICE_ACCOUNT_JSON" ]; then - node .github/scripts/mirror-play-apk.cjs - fi - # Installers verify archives against this file, so it is written from the # signed bytes that get uploaded, never from an earlier stage. - name: Write CLI archive checksums @@ -838,6 +876,10 @@ jobs: sha256sum "${archives[@]}" > SHA256SUMS cat SHA256SUMS + # Always runs, even after a failed step, and keeps that failure. + - name: Wait for nightly Android APK + wait: android_apk + # The desktop build omits the publish config for preview versions, so # electron-builder emits no updater manifests for them. Refuse to publish # if one shows up anyway: a `latest*.yml` or `nightly*.yml` on a preview @@ -903,10 +945,13 @@ jobs: echo 'release-assets/*.yml' fi echo 'release-assets/*.tar.gz' - # Only list APKs when Play has a processed internal build available. - for apk in release-assets/*.apk; do - [[ -f "$apk" ]] && echo "$apk" - done + # A failed or timed-out fetch can leave partial bytes, so list the APK + # only when this attempt's fetch succeeded and Play had one ready. + if [[ "${{ steps.android_apk.outcome }}" == "success" ]]; then + for apk in "$RUNNER_TEMP"/android-apk/*.apk; do + [[ -f "$apk" ]] && echo "$apk" + done + fi echo 'release-assets/SHA256SUMS' echo 'EOF' } >> "$GITHUB_OUTPUT" @@ -1000,7 +1045,7 @@ jobs: # nothing resolves unless asked for by name. publish_cli: name: Publish CLI to npm - needs: [preflight, release] + needs: [preflight, build_bundle, release] if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }} runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 15 @@ -1008,26 +1053,57 @@ jobs: contents: read id-token: write steps: + # Only what setup-ci-deps reads to install the project's Node and npm. - name: Checkout uses: actions/checkout@v6 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | - /* - !/.repos/ + /.github/actions/setup-ci-deps/ + /package.json + /pnpm-workspace.yaml sparse-checkout-cone-mode: false - - name: Setup dependencies + - name: Setup Node.js uses: ./.github/actions/setup-ci-deps with: - install-args: --filter=t3... --filter=@t3tools/scripts... + install: "false" - - name: Build the npm launcher - run: node scripts/build-npm-launcher.ts --version "${{ needs.preflight.outputs.version }}" --output-dir npm-packages + # Bind to build_bundle's exact upload: a name lookup takes the newest + # same-name artifact, and an empty ID downloads every artifact in the + # run. A later same-name upload hides this ID, so the download fails. + - name: Check the npm launcher artifact ID + env: + ARTIFACT_ID: ${{ needs.build_bundle.outputs.npm_launcher_artifact_id }} + run: | + if [[ ! "$ARTIFACT_ID" =~ ^[1-9][0-9]*$ ]]; then + echo "::error::build_bundle gave no valid npm-launcher artifact ID: '$ARTIFACT_ID'." >&2 + exit 1 + fi + + - name: Download the npm launcher + uses: actions/download-artifact@v8 + with: + artifact-ids: ${{ needs.build_bundle.outputs.npm_launcher_artifact_id }} + path: npm-packages + digest-mismatch: error + + - name: Check the npm launcher version + env: + RELEASE_VERSION: ${{ needs.preflight.outputs.version }} + run: | + built="$(tar -xzOf npm-packages/t3.tgz package/package.json | jq -r .version)" + if [[ "$built" != "$RELEASE_VERSION" ]]; then + echo "::error::npm-launcher holds t3@$built, expected t3@$RELEASE_VERSION." >&2 + exit 1 + fi - name: Publish the npm launcher + env: + DIST_TAG: ${{ needs.preflight.outputs.cli_dist_tag }} run: | - if ! node apps/server/scripts/cli.ts publish --packages-dir npm-packages --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --provenance --verbose; then + # The ./ keeps npm from reading the path as a GitHub owner/repo spec. + if ! npm publish --access public --tag "$DIST_TAG" --provenance ./npm-packages/t3.tgz; then echo "::error::npm publish failed. Make sure package t3 has a trusted publisher registered for .github/workflows/release.yml (see docs/operations/release.md)." >&2 exit 1 fi @@ -1165,13 +1241,16 @@ jobs: T3CODE_WEB_NIGHTLY_DOMAIN: ${{ vars.T3CODE_WEB_NIGHTLY_DOMAIN }} VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }} steps: + # Only what setup-ci-deps reads to install vp and Node. The alias call + # names its deployment and scope, so it reads nothing else from the repo. - name: Checkout uses: actions/checkout@v6 with: ref: ${{ needs.preflight.outputs.ref }} sparse-checkout: | - /* - !/.repos/ + /.github/actions/setup-ci-deps/ + /package.json + /pnpm-workspace.yaml sparse-checkout-cone-mode: false - name: Setup Vite+ diff --git a/.macroscope/ignore.md b/.macroscope/ignore.md index 66e5434c5ed13..7e67d1d059427 100644 --- a/.macroscope/ignore.md +++ b/.macroscope/ignore.md @@ -279,3 +279,7 @@ native/libghostty-vt/include/** # it needs. Regenerated by apps/mobile/scripts/generate-highlights.mts; review # that script and cpp/t3_highlights.c instead. apps/mobile/modules/t3-highlights/Vendor/** + +# Nitro bindings for T3Highlights. Regenerated by `vp run generate:nitro` in +# apps/mobile from modules/t3-highlights/src/T3Highlights.nitro.ts. +apps/mobile/modules/t3-highlights/nitrogen/generated/** diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index a7b10f64404a6..87a153f7b030d 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,17 +1,33 @@ -// Windows installs need Linux x64 glibc binaries because WSL shares node_modules. -// Keep other platforms native; release scripts set their own architectures. +const fs = require("node:fs"); +const path = require("node:path"); + +// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of +// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +function forkTarballPatches(patchedDependencies) { + const manifestPath = path.join(__dirname, "apps/mobile/package.json"); + // Release staging installs a partial workspace without the mobile app. + if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + const forks = Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + return Object.keys(patchedDependencies).filter((key) => + forks.some((name) => key === name || key.startsWith(`${name}@`)), + ); +} + module.exports = { hooks: { - // `typescript` is @tsc-rs/typescript (the catalog entry). Its npm version (0.8.x) is outside - // vite-plus-core's typescript peer range, so pnpm gave the vite-plus that @effect/vitest - // imports apps/marketing's typescript@6.0.3 instead, and tests loaded a second vitest. - readPackage(pkg) { - if (pkg.name === "@voidzero-dev/vite-plus-core" && pkg.peerDependencies?.typescript) { - pkg.peerDependencies.typescript = "*"; - } - return pkg; - }, updateConfig(config) { + const forkPatches = forkTarballPatches(config.patchedDependencies); + if (forkPatches.length > 0) { + throw new Error( + `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + + "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + ); + } + // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. + // Keep other platforms native; release scripts set their own architectures. // oxlint-disable-next-line t3code/no-global-process-runtime -- pnpm loads this file before any Effect runtime exists. if (process.platform !== "win32") return config; return { diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 99e2f7ddf76db..b7b4c7aec81f3 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,3 +1,3 @@ { - "recommendations": ["oxc.oxc-vscode"] + "recommendations": ["oxc.oxc-vscode", "TypeScriptTeam.native-preview"] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 564120b4aaff3..2dba907475af6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,7 +5,8 @@ "source.fixAll.oxc": "always" }, "oxc.unusedDisableDirectives": "warn", - "js/ts.tsdk.path": "node_modules/typescript/lib", + "js/ts.experimental.useTsgo": true, + "js/ts.tsdk.path": ".vscode/tsdk", "typescript.preferences.autoImportFileExcludePatterns": [".repos/**"], "javascript.preferences.autoImportFileExcludePatterns": [".repos/**"], "files.watcherExclude": { diff --git a/.vscode/tsdk/tsgo b/.vscode/tsdk/tsgo new file mode 100755 index 0000000000000..aed04f69fd431 --- /dev/null +++ b/.vscode/tsdk/tsgo @@ -0,0 +1,11 @@ +#!/bin/sh +# VS Code's TypeScript 7 extension starts `/tsgo --lsp --stdio`. Exec Effect's patched tsrs +# directly: through the effect-tsgo Node launcher, the LSP's stdin read intermittently fails (EAGAIN). +exec "$(cd "$(dirname "$0")/../.." && node -e ' +const { createRequire } = require("node:module"); +const fs = require("node:fs"); +const path = require("node:path"); +const platform = `@effect/tsgo-${process.platform}-${process.arch}/package.json`; +const dir = path.join(path.dirname(createRequire(require.resolve("@effect/tsgo/package.json")).resolve(platform)), "artifacts/tsrs"); +process.stdout.write(path.join(dir, fs.readdirSync(dir).sort().at(-1), "tsrs")); +')" "$@" diff --git a/AGENTS.md b/AGENTS.md index 9f6f32d33b9f8..2effa629d25e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,13 +18,13 @@ Lots of apps have gotten bogged down with bad tech decisions and "slop". We have ### 3. Remote ready -The architecture of T3 Code's websocket layer (npx t3) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported. +The architecture of T3 Code's websocket layer (`t3`) enables a lot of awesome remote features. These have become core to the product. Whether users are connecting directly over their local network, using Tailscale, or leaning in fully with T3 Connect (our tunnel solution, also in this repo), we need to make sure new features are properly supported. ### 4. Multi-surface T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**. -**Web** is kind of two surfaces, as we have the public facing "app.t3.codes" as well as locally hosting the web app through the `npx t3` command. Both need to be supported by all new features where reasonable. +**Web** is kind of two surfaces, as we have the public facing "app.t3.codes" as well as locally hosting the web app through the `t3` command. Both need to be supported by all new features where reasonable. **Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app. @@ -100,7 +100,7 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real - Before you push, run `vp run check:changed`. It runs CI's fast checks for changed files: format, lint, knip, typecheck of affected packages and dependents, tests beside changes, and the cross-file checks those miss. CI still runs the full test suites. - While you iterate, run `vp test run `. For big files, add `-t ""`. -- Use `vp run typecheck`, not `npx tsc`; it caches per package. Both run tsc-rs (`typescript` is the `@tsc-rs/typescript` drop-in). +- Use `vp run typecheck`; it caches per package. Each package runs `effect-tsgo tsrs --noEmit`, the Rust TypeScript 7 checker with Effect's diagnostics built in. There is no `typescript` package to run. - Run `node -e` snippets from `apps/server` or the owning package. `effect` does not resolve from the repo root. - Test behavior that can break, such as orchestration and event-sourcing, provider protocol translation, auth and permission guards, persistence and migrations, external-format parsing, race fixes, and the logic a bug fix changed. Leave out tests for what types already guarantee, trivial logic, copy text, smoke runs, mock-call mirrors, callback wiring, and props rendered to static markup. - Extend before you add. When an existing test or table covers the behavior, add a row or an assertion there. Write a new `it` only when no case fits. diff --git a/Dockerfile.lazurio b/Dockerfile.lazurio new file mode 100644 index 0000000000000..2e2bc9392dbe2 --- /dev/null +++ b/Dockerfile.lazurio @@ -0,0 +1,68 @@ +# Lazurio T3 Code image: a modified distribution of T3 Code, its server and web +# client with the Lazurio overlay, served at the root of its own hostname behind +# a TLS reverse proxy. See docs/operations/lazurio-fork-release.md. +ARG NODE_BASE_IMAGE + +FROM $NODE_BASE_IMAGE AS build + +ARG PACKAGE_VERSION +ARG PNPM_VERSION +ARG SOURCE_DATE_EPOCH + +ENV SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH + +WORKDIR /source +COPY . . +RUN npm install --global "pnpm@$PNPM_VERSION" --no-audit --no-fund \ + && pnpm config set allowUnusedPatches true --location=project \ + && pnpm install --frozen-lockfile \ + && node scripts/update-release-package-versions.ts "$PACKAGE_VERSION" \ + && pnpm exec vp run --filter @t3tools/web build \ + && pnpm exec vp run --filter t3 build \ + && node scripts/apply-web-brand-assets.ts production apps/server/dist/client \ + && test -s /source/apps/server/dist/client/index.html \ + && pnpm --filter t3 deploy --prod --legacy --ignore-scripts /opt/lazurio-t3 \ + && node_pty_source="$(node -p "require.resolve('node-pty/package.json', { paths: ['/source/apps/server'] })")" \ + && node_pty_source="${node_pty_source%/package.json}" \ + && if [ -d "$node_pty_source/build" ]; then cp -a "$node_pty_source/build" /opt/lazurio-t3/node_modules/node-pty/; fi \ + && node -e ' \ + const pty = require("/opt/lazurio-t3/node_modules/node-pty"); \ + const child = pty.spawn("/bin/sh", ["-c", "printf lazurio-pty-ok"], { cwd: "/tmp" }); \ + let output = ""; \ + child.onData((data) => { output += data; }); \ + child.onExit(({ exitCode }) => { \ + if (exitCode !== 0 || !output.includes("lazurio-pty-ok")) process.exit(1); \ + });' + +FROM $NODE_BASE_IMAGE + +ARG RELEASE_TAG +ARG SOURCE_REVISION +ARG UPSTREAM_BASE + +# Hosted browsers stay paired for a year; the rest is configured per Workspace +# at runtime (T3CODE_EXTERNAL_ORIGIN, T3CODE_ENVIRONMENT_LABEL). +ENV NODE_ENV=production \ + T3CODE_CLIENT_SESSION_TTL=365d \ + PATH=/opt/lazurio-t3/dist:$PATH + +LABEL org.opencontainers.image.title="Lazurio T3 Code" \ + org.opencontainers.image.description="Lazurio T3 Code: a modified distribution of T3 Code for Lazurio Environments" \ + org.opencontainers.image.licenses="MIT" \ + org.opencontainers.image.url="https://github.com/Lazurio/t3code" \ + org.opencontainers.image.vendor="Lazurio" \ + org.opencontainers.image.source="https://github.com/Lazurio/t3code" \ + org.opencontainers.image.revision="$SOURCE_REVISION" \ + org.opencontainers.image.version="$RELEASE_TAG" \ + io.lazurio.t3code.upstream-base="$UPSTREAM_BASE" + +COPY --from=build /opt/lazurio-t3 /opt/lazurio-t3 +# T3 Code's MIT licence travels with every copy of it. +COPY LICENSE /opt/lazurio-t3/LICENSE + +RUN useradd --uid 10001 --create-home --shell /usr/sbin/nologin t3code + +USER 10001:10001 +WORKDIR /home/t3code +ENTRYPOINT ["node", "/opt/lazurio-t3/dist/bin.mjs"] +CMD ["serve", "--host", "127.0.0.1"] diff --git a/README.md b/README.md index 1f63f3609ae0d..de6978f57a74d 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ irm https://t3.codes/install.ps1 | iex Then run `t3` to start the server and open the local web app. `t3 service install` keeps it running in the background, `t3 update` moves to a newer release, and `t3 --help` has the full reference. -To try it once without installing, run `npx t3@latest` instead. +To try it once without installing, run `npx t3@latest`. It offers to install the `t3` command for you. ### Desktop app @@ -113,6 +113,7 @@ Full docs live in [docs/](./docs). There's no docs site yet. - [Appearance preferences](./docs/user/appearance.md) - [Remote access from a phone or another machine](./docs/user/remote-access.md) - [Connect Claude Code, Codex, ChatGPT and other agents over MCP](./docs/user/outside-agents.md) +- [Let an agent on the host work with your threads through the `t3` command](./docs/user/agent-cli.md) - [Keeping app and server in sync](./docs/user/updating.md) - [Source control integrations](./docs/user/source-control.md) - Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 729690b88c989..87a1eb2a8deda 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.1.6", + "version": "0.1.7", "private": true, "type": "module", "main": "dist-electron/boot.cjs", @@ -12,7 +12,7 @@ "dependencies": { "@clerk/electron": "catalog:", "@clerk/electron-passkeys": "catalog:", - "@crowecawcaw/xa11y": "0.13.0", + "@crowecawcaw/xa11y": "0.15.4", "@effect/platform-node": "catalog:", "@napi-rs/keyring": "^1.3.0", "@t3tools/client-runtime": "workspace:*", diff --git a/apps/desktop/scripts/verify-preload-bundle.mjs b/apps/desktop/scripts/verify-preload-bundle.mjs index f6976220d07fe..cd45e5f1360f6 100644 --- a/apps/desktop/scripts/verify-preload-bundle.mjs +++ b/apps/desktop/scripts/verify-preload-bundle.mjs @@ -103,11 +103,17 @@ const executeBundle = (source, sandboxModules) => { return sandboxModules.get(moduleName); }; + // A real preload loads with the page's DOM; no page events fire while the bundle runs here. + const document = Object.assign(new EventTarget(), { fullscreenElement: null }); + const window = Object.assign(new EventTarget(), { document }); + NodeVM.runInNewContext( source, { + document, process: sandboxProcess, require: requireSandboxModule, + window, }, { filename: "desktop-preload.cjs", diff --git a/apps/desktop/scripts/verify-preload-bundle.test.mjs b/apps/desktop/scripts/verify-preload-bundle.test.mjs index 8af6ae00c3f92..b80fe934f5d4d 100644 --- a/apps/desktop/scripts/verify-preload-bundle.test.mjs +++ b/apps/desktop/scripts/verify-preload-bundle.test.mjs @@ -80,6 +80,18 @@ describe("desktop preload bundle verifier", () => { ); }); + it("runs a preload that reads the page's DOM while loading", () => { + assert.doesNotThrow(() => + verifyPreloadBundle(` + ${validPreload} + const report = () => document.fullscreenElement; + report(); + document.addEventListener("fullscreenchange", report); + window.addEventListener("resize", report); + `), + ); + }); + it("ignores require-like text in strings and comments", () => { assert.doesNotThrow(() => verifyPreloadBundle(` diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 66fc83adae194..6cb00baf897d1 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -69,14 +70,19 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as MacPermissions from "../permissions/MacPermissions.ts"; import * as PreviewManager from "../preview/Manager.ts"; -it.effect( - "starts the backend and window while Linux registration is stalled and cancels it on shutdown", - () => +it.effect.each([false, true])( + "stops backends together before flushing history and cancels Linux registration, stop defect=%s", + (stopDefect) => Effect.gen(function* () { const registrationStarted = yield* Deferred.make(); const releaseRegistration = yield* Deferred.make(); const registrationStopped = yield* Deferred.make(); const windowStarted = yield* Deferred.make(); + const firstStopStarted = yield* Deferred.make(); + const secondStopStarted = yield* Deferred.make(); + const releaseStops = yield* Deferred.make(); + const historyStarted = yield* Deferred.make(); + const releaseHistory = yield* Deferred.make(); const quitting = yield* Ref.make(false); const events: string[] = []; const record = (event: string) => @@ -111,6 +117,7 @@ it.effect( Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, { installIntoProcess: Effect.succeed(true), awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), updates: Stream.empty, }), Effect.provideService(DesktopAppSettings.DesktopAppSettings, { @@ -169,7 +176,21 @@ it.effect( start: record("backend"), currentConfig: Effect.succeedSome({ preflightFailure: Option.none() }), }), - list: Effect.succeed([]), + list: Effect.succeed([ + { + stop: () => + Deferred.succeed(firstStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + Effect.andThen(stopDefect ? Effect.die("stop defect") : Effect.void), + ), + }, + { + stop: () => + Deferred.succeed(secondStopStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseStops)), + ), + }, + ]), } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]), Effect.provideService(DesktopServerExposure.DesktopServerExposure, { configureFromSettings: () => Effect.succeed({ mode: "local-only" }), @@ -182,7 +203,10 @@ it.effect( start: Effect.void, } as unknown as DesktopAppActivation.DesktopAppActivation["Service"]), Effect.provideService(DesktopRendererHistory.DesktopRendererHistory, { - shutdown: Effect.void, + shutdown: Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(releaseHistory)), + Effect.asVoid, + ), } as DesktopRendererHistory.DesktopRendererHistory["Service"]), ); const app = yield* runApp.pipe( @@ -226,8 +250,19 @@ it.effect( yield* Deferred.await(windowStarted); assert.deepEqual(events, ["identity", "ready", "identity", "backend", "window"]); assert.isFalse(yield* Deferred.isDone(registrationStopped)); - yield* (yield* DesktopShutdown.DesktopShutdown).request; - yield* Fiber.join(app); + const shutdown = yield* DesktopShutdown.DesktopShutdown; + yield* shutdown.request; + yield* Deferred.await(firstStopStarted); + yield* Deferred.await(secondStopStarted); + assert.isFalse(yield* Deferred.isDone(historyStarted)); + assert.isFalse(yield* shutdown.isComplete); + yield* Deferred.succeed(releaseStops, undefined); + yield* Deferred.await(historyStarted); + assert.isFalse(yield* shutdown.isComplete); + yield* Deferred.succeed(releaseHistory, undefined); + const result = yield* Fiber.await(app); + assert.equal(Exit.isFailure(result), stopDefect); + assert.isTrue(yield* shutdown.isComplete); assert.isTrue(yield* Deferred.isDone(registrationStopped)); }).pipe(Effect.provide(DesktopShutdown.layer)), ); diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 8bdd1957cbfb7..e3b6c49e3ab8d 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -1,5 +1,5 @@ import * as Cause from "effect/Cause"; -import * as Duration from "effect/Duration"; +import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -15,9 +15,11 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts"; import * as DesktopAppActivation from "./DesktopAppActivation.ts"; import * as DesktopAppIdentity from "./DesktopAppIdentity.ts"; import * as DesktopClerk from "./DesktopClerk.ts"; +import * as DesktopCliCommand from "./DesktopCliCommand.ts"; import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts"; import * as DesktopWindow from "../window/DesktopWindow.ts"; import * as PreviewPasskeys from "../preview/Passkeys.ts"; +import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import * as DesktopLegacyLocalStorage from "./DesktopLegacyLocalStorage.ts"; @@ -42,6 +44,11 @@ const DEFAULT_DESKTOP_BACKEND_PORT = 3773; const MAX_TCP_PORT = 65_535; const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const; +const LinuxDesktopSessionConfig = Config.all({ + current: Config.String("XDG_CURRENT_DESKTOP").pipe(Config.option), + session: Config.String("XDG_SESSION_DESKTOP").pipe(Config.option), +}); + const makeDesktopRunId = SecureRandom.SecureRandom.pipe( Effect.flatMap((random) => random.uuidV4()), Effect.map((value) => value.replaceAll("-", "").slice(0, 12)), @@ -154,7 +161,7 @@ const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")( const instances = yield* pool.list; yield* Effect.forEach( instances, - (instance) => instance.stop({ timeout: Duration.seconds(5) }), + (instance) => instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }), { concurrency: "unbounded" }, ); }, @@ -186,6 +193,18 @@ const bootstrap = Effect.gen(function* () { ); yield* snapShot.initialize; + // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has + // no cached one. Without it, the command is left to Settings. + const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch; + yield* Effect.forkScoped( + (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe( + Effect.flatMap((found) => + found || environment.platform === "win32" + ? installCli + : logBootstrapInfo("skipped installing the t3 command without the shell PATH"), + ), + ), + ); if (!settings.localEnvironmentEnabled) { yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)"); @@ -307,12 +326,13 @@ const startup = Effect.gen(function* () { yield* desktopSettings.load; if (linuxElectronOptions !== null) { + const xdgDesktop = yield* LinuxDesktopSessionConfig; yield* logStartupInfo("linux password store configured", { passwordStore: hasCommandLinePasswordStore ? "command-line" : (linuxElectronOptions.passwordStore ?? "electron-default"), - xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null, - xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null, + xdgCurrentDesktop: Option.getOrNull(xdgDesktop.current), + xdgSessionDesktop: Option.getOrNull(xdgDesktop.session), }); } @@ -356,6 +376,7 @@ const scopedProgram = Effect.scoped( stopAllPoolInstances().pipe( Effect.ensuring(rendererHistory.shutdown), Effect.ensuring(shutdown.markComplete), + Effect.withSpan("desktop.app.shutdown"), ), ); diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.ts index 32e7b3b3118d9..74d134c0b1001 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.test.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts @@ -42,6 +42,7 @@ const layerElectronApp = (calls: ElectronAppCalls) => metadata: Effect.die("unexpected metadata read"), name: Effect.succeed("T3 Code"), systemLocale: Effect.succeed("en-US"), + preferredSystemLanguages: Effect.succeed(["en-US"]), whenReady: Effect.void, requestSingleInstanceLock: Effect.succeed(true), quit: Effect.void, diff --git a/apps/desktop/src/app/DesktopCliCommand.test.ts b/apps/desktop/src/app/DesktopCliCommand.test.ts index 8566613dd6069..2dc59c58899ee 100644 --- a/apps/desktop/src/app/DesktopCliCommand.test.ts +++ b/apps/desktop/src/app/DesktopCliCommand.test.ts @@ -1,5 +1,5 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; -import { afterEach, beforeEach, expect, it } from "@effect/vitest"; +import { expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -24,12 +24,19 @@ const environmentFor = ( homeDirectory: input.home, baseDir: input.baseDir, stateDir: path.join(input.baseDir, "userdata"), + desktopSettingsPath: path.join(input.baseDir, "userdata", "desktop-settings.json"), serverRoot: "/opt/T3 Code/resources/app.asar", appImagePath: Option.none(), } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]); const commandIn = ( - input: { home: string; baseDir?: string; platform?: NodeJS.Platform; isPackaged?: boolean }, + input: { + home: string; + baseDir?: string; + platform?: NodeJS.Platform; + isPackaged?: boolean; + env?: NodeJS.ProcessEnv; + }, spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"], ) => Effect.gen(function* () { @@ -42,20 +49,22 @@ const commandIn = ( DesktopEnvironment.DesktopEnvironment, environmentFor(path, { ...input, baseDir }), ), + Effect.provideService(HostProcess.Environment, input.env ?? { PATH: "", SHELL: "/bin/zsh" }), ); return yield* spawner ? make.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)) : make; }); -const fakePowerShell = (initial: string) => { +/** `inherited` stands in for the app's own environment, which `extendEnv` passes on. */ +const fakePowerShell = (initial: string, inherited: Record = {}) => { const registry = { path: initial, failReads: false, writes: 0 }; const spawner = ChildProcessSpawner.make((command) => Effect.sync(() => { const { options } = command as unknown as { - readonly options: { readonly env?: Record }; + readonly options: { readonly env?: Record; readonly extendEnv?: boolean }; }; - const env = options.env ?? {}; + const env = { ...(options.extendEnv ? inherited : {}), ...options.env }; let exitCode = 0; let stdout = ""; if (env.T3_SET === "1") { @@ -84,21 +93,14 @@ const fakePowerShell = (initial: string) => { return { registry, spawner }; }; -const machinePath = process.env.PATH; -beforeEach(() => { - process.env.PATH = ""; -}); -afterEach(() => { - process.env.PATH = machinePath; -}); - it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { it.effect("links the launcher onto PATH and removes only that link", () => Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" }; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); const link = path.join(home, ".local", "bin", "t3"); expect(yield* command.state).toEqual({ @@ -107,24 +109,67 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { onPath: false, launcherPath: null, }); + yield* command.installOnFirstLaunch; + expect((yield* command.state).installedPath).toBe(link); const installed = yield* command.install; expect(installed.installedPath).toBe(link); expect(installed.launcherPath).toBe(path.join(home, ".t3", "bin", "t3")); + expect(installed.pathSetup).toEqual({ file: "~/.zshrc", added: false }); expect(yield* fs.readLink(link)).toBe(path.join(home, ".t3", "bin", "t3")); expect((yield* command.install).installedPath).toBe(link); + // Add to PATH appends one line, once, and keeps a final line with no newline intact. + const zshrc = path.join(home, ".zshrc"); + yield* fs.writeFileString(zshrc, "# mine"); + // A folder already on PATH needs nothing. + env.PATH = path.join(home, ".local", "bin"); + yield* command.addToPath; + expect(yield* fs.readFileString(zshrc)).toBe("# mine"); + env.PATH = ""; + yield* Effect.all([command.addToPath, command.addToPath], { concurrency: "unbounded" }); + expect((yield* command.addToPath).pathSetup).toEqual({ file: "~/.zshrc", added: true }); + expect(yield* fs.readFileString(zshrc)).toBe( + '# mine\n# Added by T3 Code\nexport PATH="$PATH:$HOME/.local/bin"\n', + ); + expect((yield* command.uninstall).installedPath).toBeNull(); expect(yield* fs.exists(link)).toBe(false); expect(yield* fs.exists(path.join(home, ".t3", "bin", "t3"))).toBe(true); + // Removed stays removed: first launch never installs again. + yield* command.installOnFirstLaunch; + expect(yield* fs.exists(link)).toBe(false); + + // Also when first launch was put off (no shell PATH yet) and the user removed it meanwhile. + const laterHome = yield* fs.makeTempDirectoryScoped(); + const later = yield* commandIn({ home: laterHome, env }); + yield* later.install; + yield* later.uninstall; + yield* later.installOnFirstLaunch; + expect(yield* fs.exists(path.join(laterHome, ".local", "bin", "t3"))).toBe(false); + + // An app that ran before left its settings or launcher. Its user may have removed t3 or + // chosen another, so first launch leaves it to Settings, where Install still works. + for (const left of ["userdata/desktop-settings.json", "bin/t3"]) { + const upgradedHome = yield* fs.makeTempDirectoryScoped(); + const leftFile = path.join(upgradedHome, ".t3", left); + yield* fs.makeDirectory(path.dirname(leftFile), { recursive: true }); + yield* fs.writeFileString(leftFile, `#!/bin/sh\n# ${DesktopCliShim.MARKER}\n`); + const upgraded = yield* commandIn({ home: upgradedHome, env }); + yield* upgraded.installOnFirstLaunch; + const upgradedLink = path.join(upgradedHome, ".local", "bin", "t3"); + expect(yield* fs.exists(upgradedLink)).toBe(false); + expect((yield* upgraded.install).installedPath).toBe(upgradedLink); + } }).pipe(Effect.scoped), ); it.effect("never replaces or removes a t3 it did not create", () => Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" }; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); const theirs = path.join(home, ".local", "bin", "t3"); yield* fs.makeDirectory(path.dirname(theirs), { recursive: true }); yield* fs.writeFileString(theirs, "npm's t3\n"); @@ -132,14 +177,27 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { yield* fs.symlink(path.join(home, "gone"), path.join(home, "bin", "t3")); const error = yield* Effect.flip(command.install); - expect(error.message).toContain("Another t3 command is already installed"); + expect(error.message).toContain("Another t3 command is already in"); yield* command.uninstall; expect(yield* fs.readFileString(theirs)).toBe("npm's t3\n"); expect(yield* fs.readLink(path.join(home, "bin", "t3"))).toBe(path.join(home, "gone")); + // A fresh install beside someone else's t3 (even off PATH or a dangling link) adds no second + // t3 in ~/bin. + for (const dangling of [false, true]) { + const besideHome = yield* fs.makeTempDirectoryScoped(); + const other = path.join(besideHome, ".local", "bin", "t3"); + yield* fs.makeDirectory(path.dirname(other), { recursive: true }); + yield* dangling + ? fs.symlink(path.join(besideHome, "gone"), other) + : fs.writeFileString(other, "npm's t3\n"); + yield* (yield* commandIn({ home: besideHome })).installOnFirstLaunch; + expect(yield* fs.exists(path.join(besideHome, "bin", "t3"))).toBe(false); + } + const launcher = path.join(home, ".t3", "bin", "t3"); yield* fs.writeFileString(launcher, "npm's t3\n"); - process.env.PATH = path.dirname(launcher); + env.PATH = path.dirname(launcher); expect(yield* command.state).toMatchObject({ onPath: false, shadowedBy: launcher }); expect((yield* Effect.flip(command.install)).message).toContain("Could not set up"); yield* command.uninstall; @@ -149,40 +207,102 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { it.effect("finds and removes a link left by a previous T3 home", () => Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" }; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); - const before = yield* commandIn({ home, baseDir: path.join(home, "old-t3") }); + const before = yield* commandIn({ home, baseDir: path.join(home, "old-t3"), env }); const link = (yield* before.install).installedPath; - const after = yield* commandIn({ home, baseDir: path.join(home, "new-t3") }); - expect((yield* after.state).installedPath).toBe(link); + const after = yield* commandIn({ home, baseDir: path.join(home, "new-t3"), env }); + // A first launch leaves another home's command alone; only Install takes it over. + yield* after.installOnFirstLaunch; + expect(yield* fs.readLink(link!)).toBe(path.join(home, "old-t3", "bin", "t3")); + // On PATH, it runs the other home's launcher. Settings offers Install (not Remove, and not + // "another t3 runs first"), which updates that link in place. + env.PATH = path.dirname(link!); + expect(yield* after.state).toMatchObject({ installedPath: null, onPath: false }); + expect((yield* after.state).shadowedBy).toBeUndefined(); + env.PATH = ""; + // Off PATH, Add to PATH would expose the other home's command, not this one. + expect((yield* after.state).pathSetup).toBeUndefined(); + yield* Effect.flip(after.addToPath); + expect(yield* fs.exists(path.join(home, ".zshrc"))).toBe(false); + // Behind another t3 the install fails, and the old link still works. + const shadow = path.join(home, "shadow"); + yield* fs.makeDirectory(shadow); + yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 }); + env.PATH = shadow; + yield* Effect.flip(after.install); + expect(yield* fs.readLink(link!)).toBe(path.join(home, "old-t3", "bin", "t3")); + // Install takes it over, also with its folder first on PATH. + env.PATH = path.dirname(link!); expect((yield* after.install).installedPath).toBe(link); expect(yield* fs.readLink(link!)).toBe(path.join(home, "new-t3", "bin", "t3")); + env.PATH = ""; yield* after.uninstall; expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false); expect(yield* fs.exists(path.join(home, "bin", "t3"))).toBe(false); + + // A folder already on PATH wins, even written with a trailing slash. + env.PATH = `${path.join(home, "bin")}/`; + expect((yield* after.install).installedPath).toBe(path.join(home, "bin", "t3")); + + // An old link of ours is updated where it is, not moved to a folder that may be off PATH. + yield* fs.writeFileString(path.join(home, "bin", "t3.staging"), "mine"); + yield* fs.remove(path.join(home, "bin", "t3")); + yield* fs.symlink(path.join(home, "old-t3", "bin", "t3"), path.join(home, "bin", "t3")); + env.PATH = ""; + expect((yield* after.install).installedPath).toBe(path.join(home, "bin", "t3")); + expect(yield* fs.readLink(path.join(home, "bin", "t3"))).toBe( + path.join(home, "new-t3", "bin", "t3"), + ); + expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false); + expect(yield* fs.readFileString(path.join(home, "bin", "t3.staging"))).toBe("mine"); }).pipe(Effect.scoped), ); it.effect("refuses to install behind another t3 that runs first", () => Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" }; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); const shadow = path.join(home, "shadow"); yield* fs.makeDirectory(shadow); yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 }); - process.env.PATH = [shadow, path.join(home, ".local", "bin")].join(":"); + env.PATH = [shadow, `${path.join(home, ".local", "bin")}/`].join(":"); - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); const theirs = path.join(shadow, "t3"); expect((yield* command.state).shadowedBy).toBe(theirs); const error = yield* Effect.flip(command.install); expect(error.message).toContain(theirs); + yield* command.installOnFirstLaunch; expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false); + expect(yield* fs.readFileString(theirs)).toBe("#!/bin/sh\n"); + + // Its folder is already on PATH behind theirs; adding it again would change which t3 runs. + yield* fs.makeDirectory(path.join(home, ".local", "bin"), { recursive: true }); + yield* fs.symlink( + path.join(home, ".t3", "bin", "t3"), + path.join(home, ".local", "bin", "t3"), + ); + const behind = yield* command.state; + expect(behind.installedPath).toBe(path.join(home, ".local", "bin", "t3")); + expect(behind.pathSetup).toBeUndefined(); + // Off PATH behind theirs, adding the folder would still put ours first. + env.PATH = shadow; + expect((yield* command.state).pathSetup).toBeUndefined(); + yield* Effect.flip(command.addToPath); + expect(yield* fs.exists(path.join(home, ".zshrc"))).toBe(false); + env.PATH = [shadow, `${path.join(home, ".local", "bin")}/`].join(":"); + yield* fs.remove(path.join(home, ".local", "bin", "t3")); + // A first-launch install that failed is not retried behind the user's back. yield* fs.remove(theirs); + yield* command.installOnFirstLaunch; + expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false); const installed = yield* command.install; expect(installed).toMatchObject({ onPath: true, @@ -196,6 +316,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { "skips a t3 directory or a file this user cannot execute", () => Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" }; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); @@ -209,9 +330,9 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { yield* fs.chmod(path.join(plain, "t3"), process.getuid?.() === 0 ? 0o600 : 0o601); yield* fs.makeDirectory(shadow); yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 }); - process.env.PATH = [folder, plain, shadow, path.join(home, ".local", "bin")].join(":"); + env.PATH = [folder, plain, shadow, path.join(home, ".local", "bin")].join(":"); - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); expect((yield* command.state).shadowedBy).toBe(path.join(shadow, "t3")); const error = yield* Effect.flip(command.install); @@ -227,13 +348,14 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { it.effect("does not treat its own launcher as another t3 when its folder is first on PATH", () => Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" }; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const home = yield* fs.makeTempDirectoryScoped(); const launcher = path.join(home, ".t3", "bin", "t3"); - process.env.PATH = [path.dirname(launcher), path.join(home, ".local", "bin")].join(":"); + env.PATH = [path.dirname(launcher), path.join(home, ".local", "bin")].join(":"); - const command = yield* commandIn({ home }); + const command = yield* commandIn({ home, env }); const installed = yield* command.install; expect(yield* fs.exists(launcher)).toBe(true); @@ -274,6 +396,21 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect(registry.path).toBe(`${userPath};${launcherDir}`); yield* command.uninstall; expect(registry.path).toBe(userPath); + + // A `;` in the folder would split it into two PATH entries, so nothing is written. + const split = fakePowerShell(userPath); + const semicolon = yield* commandIn( + { home, baseDir: `${home}\\T3;Home`, platform: "win32" }, + split.spawner, + ); + expect((yield* Effect.flip(semicolon.install)).message).toContain('has a ";"'); + expect(split.registry).toMatchObject({ path: userPath, writes: 0 }); + + // An inherited T3_SET=1 never turns a read into a write of the whole PATH. + const inherited = fakePowerShell(userPath, { T3_SET: "1", T3_PATH: "C:\\other" }); + const reader = yield* commandIn({ home, platform: "win32" }, inherited.spawner); + yield* reader.install; + expect(inherited.registry).toMatchObject({ path: `${userPath};${launcherDir}`, writes: 1 }); }).pipe(Effect.scoped), ); @@ -294,6 +431,16 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => { expect((yield* command.state).installedPath).toBeNull(); yield* command.uninstall; expect(registry.path).toBe(userPath); + + // A fresh install beside a standalone t3.cmd (from `t3 install`), even off PATH, leaves + // PATH alone. + const besideHome = yield* fs.makeTempDirectoryScoped(); + yield* fs.makeDirectory(path.join(besideHome, ".local", "bin"), { recursive: true }); + yield* fs.writeFileString(path.join(besideHome, ".local", "bin", "t3.cmd"), "@echo off\r\n"); + const beside = fakePowerShell("C:\\Tools"); + yield* (yield* commandIn({ home: besideHome, platform: "win32" }, beside.spawner)) + .installOnFirstLaunch; + expect(beside.registry).toMatchObject({ path: "C:\\Tools", writes: 0 }); }).pipe(Effect.scoped), ); }); diff --git a/apps/desktop/src/app/DesktopCliCommand.ts b/apps/desktop/src/app/DesktopCliCommand.ts index f53895a60a570..b5306a6bb5a82 100644 --- a/apps/desktop/src/app/DesktopCliCommand.ts +++ b/apps/desktop/src/app/DesktopCliCommand.ts @@ -2,28 +2,40 @@ import * as NodeFSP from "node:fs/promises"; import type { DesktopCliCommandState } from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Random from "effect/Random"; import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { pathSetup, readUserLoginShell } from "@t3tools/shared/shell"; + import * as DesktopCliShim from "./DesktopCliShim.ts"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; +import { makeComponentLogger } from "./DesktopObservability.ts"; + +const { logInfo, logWarning } = makeComponentLogger("desktop-cli-command"); export class DesktopCliCommandError extends Schema.TaggedError()( "DesktopCliCommandError", { message: Schema.String }, ) {} -const unixCandidates = (home: string, platform: NodeJS.Platform) => +const userCandidates = (home: string) => [`${home}/.local/bin`, `${home}/bin`]; + +// Older builds also linked into these macOS folders. Such a link is found, updated in place, and +// removed, but no new link goes there. +const knownLocations = (home: string, platform: NodeJS.Platform) => platform === "darwin" - ? ["/opt/homebrew/bin", "/usr/local/bin", `${home}/.local/bin`, `${home}/bin`] - : [`${home}/.local/bin`, `${home}/bin`]; + ? [...userCandidates(home), "/opt/homebrew/bin", "/usr/local/bin"] + : userCandidates(home); const pathEntries = (value: string | undefined, separator: string) => (value ?? "").split(separator).filter((entry) => entry.length > 0); @@ -58,22 +70,33 @@ export class DesktopCliCommand extends Context.Service< readonly state: Effect.Effect; readonly install: Effect.Effect; readonly uninstall: Effect.Effect; + /** Adds the installed command's folder to PATH in the user's shell startup file. */ + readonly addToPath: Effect.Effect; + /** Installs the command on a fresh install's first launch; removing it in Settings sticks. */ + readonly installOnFirstLaunch: Effect.Effect; } >()("@t3tools/desktop/app/DesktopCliCommand") {} -/** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fs = yield* FileSystem.FileSystem; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + // Read the live env: shell discovery patches PATH after startup, and Windows variable + // names are case-insensitive only on process.env, not on Config's copy of it. + const env = yield* HostProcess.Environment; const path = environment.path; const windows = environment.platform === "win32"; const launcher = DesktopCliShim.launcherPath(environment); const binDirectory = path.dirname(launcher); const ownedPathMarker = path.join(environment.stateDir, "cli-command-path-entry"); + const firstLaunchMarker = path.join(environment.stateDir, "cli-command-first-launch"); const fail = (message: string) => new DesktopCliCommandError({ message }); const exists = (target: string) => fs.exists(target).pipe(Effect.orElseSucceed(() => false)); + // Read before this launch writes either one: an app that ran before left its launcher or + // settings. Its user may have removed t3 or chosen another, so only Settings installs there. + const freshInstall = + !(yield* exists(launcher)) && !(yield* exists(environment.desktopSettingsPath)); const writableDirectory = (directory: string) => fs.access(directory, { writable: true }).pipe( Effect.as(true), @@ -94,8 +117,8 @@ export const make = Effect.gen(function* () { // PATH can reach the regular launcher directly; removal still requires isOurLink. const runsOurLauncher = Effect.fn("DesktopCliCommand.runsOurLauncher")( + // Another T3 home's link is marked too, so compare where it leads, not the marker alone. function* (candidate: string) { - if (yield* isOurLink(candidate)) return true; const [resolved, ours] = yield* Effect.all([fs.realPath(candidate), fs.realPath(launcher)]); if (resolved !== ours) return false; const info = yield* fs.stat(candidate); @@ -105,15 +128,15 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); - const powershell = (env: Record) => + const powershell = (overrides: Record) => Effect.scoped( Effect.gen(function* () { - const root = process.env.SystemRoot ?? process.env.WINDIR; + const root = env.SystemRoot ?? env.WINDIR; const handle = yield* spawner.spawn( ChildProcess.make( root ? `${root}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe` : "powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", WINDOWS_USER_PATH_SCRIPT], - { stdin: "ignore", stderr: "ignore", env, extendEnv: true }, + { stdin: "ignore", stderr: "ignore", env: overrides, extendEnv: true }, ), ); const [stdout, exitCode] = yield* Effect.all( @@ -124,7 +147,8 @@ export const make = Effect.gen(function* () { return stdout; }), ); - const readUserPath = powershell({}).pipe( + // Explicit, so an inherited T3_SET=1 can never turn a read into a PATH write. + const readUserPath = powershell({ T3_SET: "0" }).pipe( Effect.map((encoded) => Buffer.from(encoded.trim(), "base64").toString("utf8")), Effect.mapError(() => fail("Could not read your PATH, so it was left unchanged.")), ); @@ -137,14 +161,17 @@ export const make = Effect.gen(function* () { const isExecutableFile = Effect.fn("DesktopCliCommand.isExecutableFile")( function* (target: string) { if ((yield* fs.stat(target)).type !== "File") return false; - yield* Effect.tryPromise(() => NodeFSP.access(target, NodeFSP.constants.X_OK)); + yield* Effect.tryPromise({ + try: () => NodeFSP.access(target, NodeFSP.constants.X_OK), + catch: () => fail(`${target} is not executable.`), + }); return true; }, Effect.orElseSucceed(() => false), ); const firstOnPath = Effect.gen(function* () { - for (const directory of pathEntries(process.env.PATH, ":")) { + for (const directory of pathEntries(env.PATH, ":")) { const candidate = path.join(directory, "t3"); if (yield* isExecutableFile(candidate)) return Option.some(candidate); } @@ -158,6 +185,13 @@ export const make = Effect.gen(function* () { return first; }); + /** A link to this home's launcher; another home's link is marked too. */ + const leadsHere = (link: string) => + fs.readLink(link).pipe( + Effect.map((target) => target === launcher), + Effect.orElseSucceed(() => false), + ); + const installedAt = Effect.gen(function* () { if (windows) { if (!(yield* exists(ownedPathMarker))) return Option.none(); @@ -166,31 +200,77 @@ export const make = Effect.gen(function* () { ? Option.some(launcher) : Option.none(); } - for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) { + for (const directory of knownLocations(environment.homeDirectory, environment.platform)) { const link = path.join(directory, "t3"); if (yield* isOurLink(link)) return Option.some(link); } return Option.none(); }); + const startupLine = (installedPath: string) => { + const setup = pathSetup({ + directory: path.dirname(installedPath), + home: environment.homeDirectory, + // A Finder or desktop launch may not set SHELL. + shell: env.SHELL || readUserLoginShell(), + platform: environment.platform, + configHome: env.XDG_CONFIG_HOME, + zdotdir: env.ZDOTDIR, + }); + if (setup === undefined) return undefined; + const file = setup.file.startsWith("~/") + ? path.join(environment.homeDirectory, setup.file.slice(2)) + : setup.file; + return { ...setup, path: file }; + }; + const hasLine = (setup: { readonly path: string; readonly line: string }) => + fs.readFileString(setup.path).pipe( + Effect.map((content) => content.split("\n").some((line) => line.trim() === setup.line)), + Effect.orElseSucceed(() => false), + ); + + const folderOnPath = (link: string) => + Effect.sync(() => + pathEntries(env.PATH, ":").some((entry) => entry.replace(/\/+$/, "") === path.dirname(link)), + ); + const state: DesktopCliCommand["Service"]["state"] = Effect.gen(function* () { if (!environment.isPackaged) { return { supported: false, installedPath: null, onPath: false, launcherPath: null } as const; } const launcherPath = (yield* exists(launcher)) ? launcher : null; - const installed = yield* installedAt; - const shadowedBy = yield* foreignFirstOnPath; + const found = yield* installedAt; + // Our link into another T3 home is not this app's command; Install updates it in place. + const installed = + windows || (Option.isSome(found) && (yield* leadsHere(found.value))) + ? found + : Option.none(); + const shadowedBy = (yield* foreignFirstOnPath).pipe( + Option.filter((first) => first !== Option.getOrUndefined(found)), + ); const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {}; const first = yield* firstOnPath; const onPath = windows ? Option.isSome(installed) : Option.isSome(first) && (yield* runsOurLauncher(first.value)); + // Only a folder missing from PATH, with no other t3 first: with one, the added folder (last + // on PATH) would still not run this t3. + const setup = + onPath || + Option.isSome(shadowedBy) || + Option.isNone(installed) || + (yield* folderOnPath(installed.value)) + ? undefined + : startupLine(installed.value); return { supported: true, installedPath: Option.getOrNull(installed), onPath, launcherPath, ...shadow, + ...(setup === undefined + ? {} + : { pathSetup: { file: setup.file, added: yield* hasLine(setup) } }), }; }).pipe( Effect.orElseSucceed(() => ({ @@ -216,6 +296,12 @@ export const make = Effect.gen(function* () { if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app."); yield* ensureLauncher; if (windows) { + // PATH would split the folder at the `;`, leaving two wrong entries behind. + if (binDirectory.includes(";")) { + return yield* fail( + `T3 Code cannot put ${binDirectory} on PATH because it has a ";". Run ${launcher} directly.`, + ); + } const entries = pathEntries(yield* readUserPath, ";"); if (!entries.some((entry) => sameWindowsPath(entry, binDirectory))) { yield* writeUserPath([...entries, binDirectory].join(";")); @@ -225,26 +311,27 @@ export const make = Effect.gen(function* () { } return yield* state; } - const existing = yield* installedAt; - if (Option.isSome(existing)) { - const target = yield* fs.readLink(existing.value).pipe(Effect.option); + const candidates = userCandidates(environment.homeDirectory); + const replaced = Option.getOrUndefined(yield* installedAt); + if (replaced !== undefined) { + const target = yield* fs.readLink(replaced).pipe(Effect.option); if (Option.getOrUndefined(target) === launcher) return yield* state; - yield* fs - .remove(existing.value) - .pipe(Effect.mapError(() => fail(`Could not replace ${existing.value}.`))); } const shadowedBy = yield* foreignFirstOnPath; - if (Option.isSome(shadowedBy)) { + // Our own link into another T3 home runs first too; it is the one this install updates. + if (Option.isSome(shadowedBy) && shadowedBy.value !== replaced) { return yield* fail( `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`, ); } - const onPath = pathEntries(process.env.PATH, ":"); - const candidates = unixCandidates(environment.homeDirectory, environment.platform); - for (const directory of [ + // An old link of ours is updated where it is, so a t3 that works now keeps working. It is + // removed only once a new link exists elsewhere. + const onPath = pathEntries(env.PATH, ":").map((entry) => entry.replace(/\/+$/, "")); + for (const directory of new Set([ + ...(replaced === undefined ? [] : [path.dirname(replaced)]), ...candidates.filter((candidate) => onPath.includes(candidate)), ...candidates.filter((candidate) => !onPath.includes(candidate)), - ]) { + ])) { const link = path.join(directory, "t3"); const created = (yield* exists(directory)) ? yield* writableDirectory(directory) @@ -253,18 +340,38 @@ export const make = Effect.gen(function* () { Effect.orElseSucceed(() => false), ); if (!created) continue; - const linked = yield* fs.symlink(launcher, link).pipe( + // Our own link is swapped in place; anything else there makes symlink fail and stays. + const staging = `${link}.${yield* Random.nextIntBetween(0, 0xffffff)}.tmp`; + const linked = yield* ( + link === replaced + ? fs + .symlink(launcher, staging) + .pipe( + Effect.andThen( + fs + .rename(staging, link) + .pipe(Effect.tapError(() => fs.remove(staging).pipe(Effect.ignore))), + ), + ) + : fs.symlink(launcher, link) + ).pipe( Effect.as(true), Effect.orElseSucceed(() => false), ); - if (linked) return yield* state; + if (!linked) continue; + if (replaced !== undefined && replaced !== link) { + yield* fs.remove(replaced).pipe(Effect.ignore); + } + return yield* state; } return yield* fail( - `Another t3 command is already installed, or no folder on your PATH is writable. Run the launcher directly at ${launcher}.`, + `Another t3 command is already in ~/.local/bin and ~/bin, or neither is writable. Run the launcher directly at ${launcher}.`, ); }).pipe(Effect.withSpan("desktop.cliCommand.install")); const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () { + // A first launch put off for the shell PATH must not bring back what the user removed. + yield* fs.writeFileString(firstLaunchMarker, "").pipe(Effect.ignore); if (windows) { if (yield* exists(ownedPathMarker)) { const entries = pathEntries(yield* readUserPath, ";"); @@ -274,7 +381,7 @@ export const make = Effect.gen(function* () { } return yield* state; } - for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) { + for (const directory of knownLocations(environment.homeDirectory, environment.platform)) { const link = path.join(directory, "t3"); if (yield* isOurLink(link)) { yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`))); @@ -283,7 +390,79 @@ export const make = Effect.gen(function* () { return yield* state; }).pipe(Effect.withSpan("desktop.cliCommand.uninstall")); - return DesktopCliCommand.of({ state, install, uninstall }); + // One at a time, so Settings and onboarding cannot both append the line. + const addToPathPermit = yield* Semaphore.make(1); + const addToPath: DesktopCliCommand["Service"]["addToPath"] = Effect.gen(function* () { + const installed = yield* installedAt; + if (Option.isNone(installed) || !(yield* leadsHere(installed.value))) { + return yield* fail("Install the t3 command first."); + } + const setup = startupLine(installed.value); + if (setup === undefined) return yield* fail("T3 Code cannot add t3 to this shell's PATH."); + const shadowedBy = yield* foreignFirstOnPath; + if (Option.isSome(shadowedBy)) { + return yield* fail( + `Another t3 at ${shadowedBy.value} runs first; T3 Code leaves it in place.`, + ); + } + if (!(yield* folderOnPath(installed.value)) && !(yield* hasLine(setup))) { + yield* fs.makeDirectory(path.dirname(setup.path), { recursive: true }).pipe( + Effect.andThen( + fs.writeFileString(setup.path, `\n# Added by T3 Code\n${setup.line}\n`, { flag: "a" }), + ), + Effect.mapError(() => fail(`Could not add t3 to ${setup.file}.`)), + ); + } + return yield* state; + }).pipe(addToPathPermit.withPermits(1), Effect.withSpan("desktop.cliCommand.addToPath")); + + const installOnFirstLaunch: DesktopCliCommand["Service"]["installOnFirstLaunch"] = Effect.gen( + function* () { + if (!environment.isPackaged || (yield* exists(firstLaunchMarker))) return; + // Mark first so a failed or removed install is never retried behind the user's back. + yield* fs.writeFileString(firstLaunchMarker, ""); + if (!freshInstall) { + return yield* logInfo("left the t3 command to Settings on an existing install"); + } + // Another T3 home's app owns the existing link; only Install in Settings may take it over. + const existing = Option.getOrUndefined(yield* installedAt); + if (existing !== undefined) { + const target = yield* fs.readLink(existing).pipe(Effect.option); + if (Option.getOrUndefined(target) !== launcher) { + return yield* logInfo("left another T3 Code app's t3 command in place", { + existing, + }); + } + } + // A t3 that is not ours in these folders, even off PATH, means the user has one already. On + // Windows the app never writes there, so any t3 there is someone else's. + for (const directory of userCandidates(environment.homeDirectory)) { + for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) { + const other = path.join(directory, name); + const present = + (yield* exists(other)) || Option.isSome(yield* fs.readLink(other).pipe(Effect.option)); + if (present && (windows || !(yield* isOurLink(other)))) { + return yield* logInfo("left the t3 command to Settings beside another t3", { other }); + } + } + } + const installed = yield* install; + yield* logInfo("installed the t3 command on first launch", { + installedPath: installed.installedPath, + onPath: installed.onPath, + }); + }, + ).pipe( + // Our own messages are short and name only paths; anything else is logged as a category. + Effect.catch((error) => + logWarning("did not install the t3 command on first launch", { + reason: error._tag === "DesktopCliCommandError" ? error.message : "state-write-failed", + }), + ), + Effect.withSpan("desktop.cliCommand.installOnFirstLaunch"), + ); + + return DesktopCliCommand.of({ state, install, uninstall, addToPath, installOnFirstLaunch }); }); export const layer = Layer.effect(DesktopCliCommand, make); diff --git a/apps/desktop/src/app/DesktopCliShim.ts b/apps/desktop/src/app/DesktopCliShim.ts index 3d4b94abff462..f8bd8b5f91deb 100644 --- a/apps/desktop/src/app/DesktopCliShim.ts +++ b/apps/desktop/src/app/DesktopCliShim.ts @@ -2,6 +2,7 @@ import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; +import * as Random from "effect/Random"; import * as DesktopEnvironment from "./DesktopEnvironment.ts"; import { makeComponentLogger } from "./DesktopObservability.ts"; @@ -147,7 +148,8 @@ export const install = Effect.gen(function* () { } if (Option.getOrUndefined(existing) !== content) { yield* fs.makeDirectory(path.dirname(shimPath), { recursive: true }); - const staging = `${shimPath}.${process.pid}.tmp`; + // Unique per call: backend startup and the first-launch command install can race here. + const staging = `${shimPath}.${process.pid}.${yield* Random.nextIntBetween(0, 0xffffff)}.tmp`; yield* fs.writeFileString(staging, content, { mode: 0o755 }); yield* fs.rename(staging, shimPath); yield* logInfo("installed t3 launcher", { shimPath }); diff --git a/apps/desktop/src/app/DesktopConfig.ts b/apps/desktop/src/app/DesktopConfig.ts index 11f975a6b86af..ef2909045bb4f 100644 --- a/apps/desktop/src/app/DesktopConfig.ts +++ b/apps/desktop/src/app/DesktopConfig.ts @@ -8,7 +8,7 @@ const trimNonEmptyOption = (value: string): Option.Option => { return trimmed.length > 0 ? Option.some(trimmed) : Option.none(); }; -const trimmedString = (name: string) => +export const trimmedString = (name: string) => Config.String(name).pipe(Config.option, Config.map(Option.flatMap(trimNonEmptyOption))); const optionalBoolean = (name: string) => diff --git a/apps/desktop/src/app/DesktopLifecycle.test.ts b/apps/desktop/src/app/DesktopLifecycle.test.ts index fa1bcd8bbf05a..30df96c58ad79 100644 --- a/apps/desktop/src/app/DesktopLifecycle.test.ts +++ b/apps/desktop/src/app/DesktopLifecycle.test.ts @@ -39,6 +39,7 @@ function layerElectronApp( metadata: Effect.die("unexpected metadata read"), name: Effect.succeed("T3 Code"), systemLocale: Effect.succeed("en-US"), + preferredSystemLanguages: Effect.succeed(["en-US"]), whenReady: Effect.void, requestSingleInstanceLock: Effect.succeed(true), quit, diff --git a/apps/desktop/src/app/DesktopManagedPolicy.ts b/apps/desktop/src/app/DesktopManagedPolicy.ts index 6dc9e8c21b2ae..38d39a75424ff 100644 --- a/apps/desktop/src/app/DesktopManagedPolicy.ts +++ b/apps/desktop/src/app/DesktopManagedPolicy.ts @@ -56,8 +56,7 @@ export const layerTest = (policy?: ManagedPolicyDocument | ManagedPolicyFileErro DesktopManagedPolicy.of({ read: policy === undefined - ? // @effect-diagnostics-next-line effectSucceedWithVoid:off - No policy is undefined, not void. - Effect.succeed(undefined) + ? Effect.undefined : isManagedPolicyFileError(policy) ? Effect.fail(policy) : Effect.succeed({ source: "/test/policy.json", document: policy }), diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index f2b176ee3761f..22bfc969c4088 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -57,6 +57,7 @@ vi.mock("node:child_process", () => ({ execFileSync: execFileSyncMock, })); +import * as DesktopConfig from "./DesktopConfig.ts"; import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts"; describe("DesktopPreReadyPlatform", () => { @@ -124,8 +125,6 @@ describe("DesktopPreReadyPlatform", () => { { previousEntry: 'Exec="/Applications/deleted-previous.AppImage" %U', label: "stale" }, ])("prepares a $label Linux desktop entry before startup yields", ({ previousEntry }) => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); - vi.stubEnv("XDG_DATA_HOME", "/xdg"); - vi.stubEnv("APPIMAGE", "/Applications/current.AppImage"); getSwitchValueMock.mockReturnValue(""); let desktopName = "t3code.desktop"; let desktopEntry = previousEntry; @@ -150,6 +149,12 @@ describe("DesktopPreReadyPlatform", () => { yield* Layer.build( DesktopPreReadyPlatform.layer.pipe( Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + Layer.provide( + DesktopConfig.layerTest({ + XDG_DATA_HOME: "/xdg", + APPIMAGE: "/Applications/current.AppImage", + }), + ), ), ); const identity = yield* Effect.promise(() => portalIdentity); @@ -168,9 +173,6 @@ describe("DesktopPreReadyPlatform", () => { it.effect("points the early portal entry at a configured distribution launcher", () => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); - vi.stubEnv("XDG_DATA_HOME", "/xdg"); - vi.stubEnv("APPIMAGE", "/Applications/current.AppImage"); - vi.stubEnv("T3CODE_DESKTOP_LAUNCHER_PATH", " /opt/T3 Code/t3code "); getSwitchValueMock.mockReturnValue(""); return Effect.scoped( @@ -178,6 +180,13 @@ describe("DesktopPreReadyPlatform", () => { yield* Layer.build( DesktopPreReadyPlatform.layer.pipe( Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + Layer.provide( + DesktopConfig.layerTest({ + XDG_DATA_HOME: "/xdg", + APPIMAGE: "/Applications/current.AppImage", + T3CODE_DESKTOP_LAUNCHER_PATH: " /opt/T3 Code/t3code ", + }), + ), ), ); const entry = writeFileSyncMock.mock.calls.find( diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index d77544f54b69a..ff8c97b8f8260 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -2,14 +2,17 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; +import * as Config from "effect/Config"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Electron from "electron"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts"; +import { trimmedString } from "./DesktopConfig.ts"; import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts"; import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; @@ -49,10 +52,17 @@ export class DesktopPreReadyElectronOptions extends Context.Service< } >()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {} +const LinuxDesktopEntryConfig = Config.all({ + xdgDataHome: trimmedString("XDG_DATA_HOME"), + launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), + appImagePath: trimmedString("APPIMAGE"), +}); + /** @public */ export const make = Effect.gen(function* () { const platform = yield* HostProcess.Platform; const homeDirectory = yield* HostProcess.HomeDirectory; + const linuxDesktopEntryConfig = yield* LinuxDesktopEntryConfig; return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => { const linuxPasswordStoreCommandLine = platform === "linux" @@ -77,8 +87,9 @@ export const make = Effect.gen(function* () { // have removed the executable referenced by the previous launch's entry. try { const applicationsDir = NodePath.posix.join( - process.env.XDG_DATA_HOME?.trim() || + Option.getOrElse(linuxDesktopEntryConfig.xdgDataHome, () => NodePath.posix.join(homeDirectory, ".local", "share"), + ), "applications", ); NodeFS.mkdirSync(applicationsDir, { recursive: true }); @@ -110,9 +121,12 @@ export const make = Effect.gen(function* () { appVersion: Electron.app.getVersion(), }).displayName, execTarget: - process.env.T3CODE_DESKTOP_LAUNCHER_PATH?.trim() || - process.env.APPIMAGE?.trim() || - process.execPath, + Option.getOrUndefined( + Option.orElse( + linuxDesktopEntryConfig.launcherPath, + () => linuxDesktopEntryConfig.appImagePath, + ), + ) ?? process.execPath, scheme: ElectronProtocol.getDesktopScheme(linux.isDevelopment), ...(iconPath === undefined ? {} : { iconPath }), }), diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index aabc374798f24..c1b9c060d547e 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -2,6 +2,7 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -26,6 +27,7 @@ const layerShellEnvironment = (prepared = true) => Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, { installIntoProcess: Effect.succeed(prepared), awaitDiscovery: Effect.succeed(prepared), + awaitUserShellDiscovery: Effect.succeed(prepared), updates: Stream.empty, }); @@ -93,14 +95,6 @@ function layerEnvironment( ); } -const restoreEnv = (name: string, value: string | undefined) => { - if (value === undefined) { - delete process.env[name]; - } else { - process.env[name] = value; - } -}; - const withHarness = ( effect: Effect.Effect< A, @@ -262,10 +256,10 @@ describe("DesktopBackendConfiguration", () => { ); assert.equal( first.bootstrap.desktopBootstrapToken, - currentDesktopBootstrapToken( + yield* currentDesktopBootstrapToken( first.bootstrap.desktopBootstrapSecret ?? "", yield* Clock.currentTimeMillis, - ), + ).pipe(Effect.provide(NodeCrypto.layerMac)), ); assert.equal( yield* configuration.currentBootstrapToken, @@ -692,49 +686,38 @@ describe("DesktopBackendConfiguration", () => { prefix: "t3-desktop-backend-config-test-", }); - const previousWslEnv = process.env.WSLENV; - const previousDisabled = process.env.OTEL_SDK_DISABLED; - const previousTelemetry = process.env.T3CODE_TELEMETRY_ENABLED; - const previousResourceAttributes = process.env.OTEL_RESOURCE_ATTRIBUTES; - try { - delete process.env.WSLENV; - process.env.OTEL_SDK_DISABLED = "true"; - process.env.T3CODE_TELEMETRY_ENABLED = "false"; - process.env.OTEL_RESOURCE_ATTRIBUTES = "deployment.environment.name=staging"; - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); - - assert.equal(config.env.OTEL_SDK_DISABLED, "true"); - assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED"); - assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false"); - assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED"); - assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging"); - assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES"); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), - getDistroIp: () => Option.some("172.27.0.99"), - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), + yield* Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); + + assert.equal(config.env.OTEL_SDK_DISABLED, "true"); + assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED"); + assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false"); + assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED"); + assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging"); + assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES"); + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge( + DesktopWslEnvironment.layerTest({ + isAvailable: true, + windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), + getDistroIp: () => Option.some("172.27.0.99"), + }), ), + Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), ), - ); - } finally { - restoreEnv("WSLENV", previousWslEnv); - restoreEnv("OTEL_SDK_DISABLED", previousDisabled); - restoreEnv("T3CODE_TELEMETRY_ENABLED", previousTelemetry); - restoreEnv("OTEL_RESOURCE_ATTRIBUTES", previousResourceAttributes); - } + ), + Effect.provideService(HostProcess.Environment, { + OTEL_SDK_DISABLED: "true", + T3CODE_TELEMETRY_ENABLED: "false", + OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=staging", + }), + ); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); @@ -745,63 +728,48 @@ describe("DesktopBackendConfiguration", () => { prefix: "t3-desktop-backend-config-test-", }); - const previousWslEnv = process.env.WSLENV; - const previousOpenAiKey = process.env.OPENAI_API_KEY; - const previousAnthropicKey = process.env.ANTHROPIC_API_KEY; - const previousOtlpHeaders = process.env.T3CODE_OTLP_HEADERS; - const previousOtlpProtocol = process.env.T3CODE_OTLP_PROTOCOL; - const ambientOtel = Object.entries(process.env).filter(([name]) => name.startsWith("OTEL_")); - try { - for (const [name] of ambientOtel) delete process.env[name]; - process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u"; - process.env.OPENAI_API_KEY = "openai-key"; - process.env.ANTHROPIC_API_KEY = "anthropic-key"; - process.env.T3CODE_OTLP_HEADERS = 'authorization="Bearer%20my-token"'; - process.env.T3CODE_OTLP_PROTOCOL = "http/protobuf"; - - yield* Effect.gen(function* () { - const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); - - assert.equal(config.executablePath, "wsl.exe"); - assert.equal(config.bootstrap.port, 5050); - assert.equal(config.bootstrap.host, "0.0.0.0"); - assert.equal(config.bootstrap.tailscaleServeEnabled, false); - assert.notProperty(config.bootstrap, "desktopTelemetryFd"); - assert.notProperty(config.bootstrap, "resourceMonitorPath"); - assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/"); - assert.equal(config.env.OPENAI_API_KEY, "openai-key"); - assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key"); - assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf"); - assert.equal( - config.env.WSLENV, - "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", - ); - }).pipe( - Effect.provide( - layerBackendConfiguration().pipe( - Layer.provideMerge(layerServerExposure), - Layer.provideMerge(DesktopAppSettings.layerTest()), - Layer.provideMerge(DesktopWslServerTree.layerTest()), - Layer.provideMerge( - DesktopWslEnvironment.layerTest({ - isAvailable: true, - windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), - getDistroIp: () => Option.some("172.27.0.99"), - }), - ), - Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), + yield* Effect.gen(function* () { + const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; + const config = yield* configuration.resolveWsl({ port: 5050, distro: null }); + + assert.equal(config.executablePath, "wsl.exe"); + assert.equal(config.bootstrap.port, 5050); + assert.equal(config.bootstrap.host, "0.0.0.0"); + assert.equal(config.bootstrap.tailscaleServeEnabled, false); + assert.notProperty(config.bootstrap, "desktopTelemetryFd"); + assert.notProperty(config.bootstrap, "resourceMonitorPath"); + assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/"); + assert.equal(config.env.OPENAI_API_KEY, "openai-key"); + assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key"); + assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf"); + assert.equal( + config.env.WSLENV, + "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL", + ); + }).pipe( + Effect.provide( + layerBackendConfiguration().pipe( + Layer.provideMerge(layerServerExposure), + Layer.provideMerge(DesktopAppSettings.layerTest()), + Layer.provideMerge(DesktopWslServerTree.layerTest()), + Layer.provideMerge( + DesktopWslEnvironment.layerTest({ + isAvailable: true, + windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"), + getDistroIp: () => Option.some("172.27.0.99"), + }), ), + Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })), ), - ); - } finally { - restoreEnv("WSLENV", previousWslEnv); - restoreEnv("OPENAI_API_KEY", previousOpenAiKey); - restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey); - restoreEnv("T3CODE_OTLP_HEADERS", previousOtlpHeaders); - restoreEnv("T3CODE_OTLP_PROTOCOL", previousOtlpProtocol); - for (const [name, value] of ambientOtel) restoreEnv(name, value); - } + ), + Effect.provideService(HostProcess.Environment, { + WSLENV: "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u", + OPENAI_API_KEY: "openai-key", + ANTHROPIC_API_KEY: "anthropic-key", + T3CODE_OTLP_HEADERS: 'authorization="Bearer%20my-token"', + T3CODE_OTLP_PROTOCOL: "http/protobuf", + }), + ); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 69a70b68a4b3d..abadf58f3f02f 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -2,9 +2,11 @@ import * as NodeOS from "node:os"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Mac from "effect/crypto/Mac"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; @@ -561,6 +563,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const environment = yield* DesktopEnvironment.DesktopEnvironment; const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const fileSystem = yield* FileSystem.FileSystem; + const env = yield* HostProcess.Environment; // wslhost loopback forwarding is unreliable on some Windows hosts; advertise the WSL IP instead. const wslBindHost = "0.0.0.0"; @@ -632,7 +635,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl const forwardedEnv: Record = {}; const forwardedEnvNames: string[] = []; for (const name of WSL_FORWARDED_ENV_NAMES) { - const value = process.env[name]; + const value = env[name]; if (value !== undefined && value.length > 0) { forwardedEnv[name] = value; forwardedEnvNames.push(name); @@ -640,7 +643,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl } const parentEnvWithoutT3Home: Record = {}; - for (const [key, value] of Object.entries(process.env)) { + for (const [key, value] of Object.entries(env)) { if (key === "T3CODE_HOME") continue; parentEnvWithoutT3Home[key] = value; } @@ -657,7 +660,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl ...forwardedEnv, ...(wslEnv !== undefined ? { WSLENV: wslEnv } : {}), }, - // env already excludes T3CODE_HOME; merging process.env would restore it. + // env already excludes T3CODE_HOME; merging the host env would restore it. extendEnv: false, bootstrap, bootstrapDelivery: "stdin" as const, @@ -723,6 +726,7 @@ export const make = Effect.gen(function* () { const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment; const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree; const settings = yield* DesktopAppSettings.DesktopAppSettings; + const mac = yield* Mac.Mac; const random = yield* SecureRandom.SecureRandom; // Random generation yields; serialize it so concurrent backends cannot capture distinct bootstrap secrets. const secretRef = yield* SynchronizedRef.make(Option.none()); @@ -741,10 +745,10 @@ export const make = Effect.gen(function* () { const sharedInputs = Effect.gen(function* () { const bootstrapSecret = yield* getOrCreateBootstrapSecret; - const bootstrapToken = currentDesktopBootstrapToken( + const bootstrapToken = yield* currentDesktopBootstrapToken( bootstrapSecret, yield* Clock.currentTimeMillis, - ); + ).pipe(Effect.provideService(Mac.Mac, mac)); const observabilitySettings = yield* readBackendObservabilitySettings.pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment), @@ -806,7 +810,9 @@ export const make = Effect.gen(function* () { const currentBootstrapToken = Effect.gen(function* () { const secret = yield* getOrCreateBootstrapSecret; - return currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis); + return yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe( + Effect.provideService(Mac.Mac, mac), + ); }); return DesktopBackendConfiguration.of({ diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index e4714673777d9..2741daa1ddd07 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -720,4 +720,58 @@ describe("DesktopBackendManager", () => { }).pipe(Effect.provide(TestClock.layer())), ), ); + + it.effect("the quit stop deadline waits for a backend that only exits at the force kill", () => + Effect.scoped( + Effect.gen(function* () { + const spawned = yield* Deferred.make(); + const teardownStarted = yield* Deferred.make(); + const teardownFinished = yield* Deferred.make(); + // The real spawner sends SIGTERM, waits the grace, then SIGKILLs. A backend that + // ignores SIGTERM therefore finishes tearing down just after the grace. + const instance = yield* makeTestInstance({ + spawnerLayer: Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Scope.Scope; + yield* Deferred.succeed(spawned, undefined); + yield* Scope.addFinalizer( + scope, + Deferred.succeed(teardownStarted, undefined).pipe( + Effect.andThen(Effect.sleep(Duration.seconds(6))), + Effect.andThen(Deferred.succeed(teardownFinished, undefined)), + Effect.asVoid, + ), + ); + return makeProcess({ + exitCode: Deferred.await(teardownFinished).pipe( + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + }); + }), + ), + ), + httpClientLayer: layerHttpClient(() => Effect.never), + }); + yield* instance.start; + yield* Deferred.await(spawned); + + // App quit and the updater stop every backend with this deadline. + const quitDone = yield* Deferred.make(); + const quitFiber = yield* instance + .stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }) + .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); + + yield* Deferred.await(teardownStarted); + // Past the SIGTERM grace but before the force kill lands: quit must still be waiting. + yield* TestClock.adjust(Duration.millis(5_500)); + assert.isFalse(yield* Deferred.isDone(quitDone)); + + yield* TestClock.adjust(Duration.millis(500)); + yield* Fiber.join(quitFiber); + assert.isTrue(yield* Deferred.isDone(teardownFinished)); + }).pipe(Effect.provide(TestClock.layer())), + ), + ); }); diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 2f5b57c4e3c95..98de41e247155 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -41,6 +41,12 @@ const DEFAULT_BACKEND_READINESS_INTERVAL = Duration.millis(100); const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1); // Match the service launcher's grace period so backends can stop provider sessions. const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5); +// Allow SIGKILL and the spawner exit wait after the SIGTERM grace so quit cannot +// orphan a backend whose shutdown hangs. +export const BACKEND_QUIT_STOP_TIMEOUT = Duration.sum( + DEFAULT_BACKEND_TERMINATE_GRACE, + Duration.seconds(2), +); const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5); const BACKEND_READINESS_PATH = "/.well-known/t3/environment"; // Three restarts without readiness is about 2 s of backoff: past a blip, early enough to help. @@ -306,7 +312,10 @@ const closeRun = ( onNone: () => Effect.void, onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid), }); - const close = Scope.close(run.scope, Exit.void).pipe(Effect.andThen(waitForFiber)); + const close = Scope.close(run.scope, Exit.void).pipe( + Effect.withSpan("desktop.backendInstance.closeScope"), + Effect.andThen(waitForFiber.pipe(Effect.withSpan("desktop.backendInstance.awaitRun"))), + ); const timeout = options?.timeout; if (!timeout) { @@ -567,6 +576,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped); const exit = yield* handle.exitCode.pipe( + Effect.withSpan("desktop.backendProcess.awaitExit"), Effect.map((exitCode) => ({ code: Option.some(exitCode), reason: `code=${exitCode}`, @@ -602,6 +612,7 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* ( }).pipe( Effect.timeout(options.outputDrainTimeout ?? DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT), Effect.ignore, + Effect.withSpan("desktop.backendProcess.drainOutput"), ); if (Exit.isFailure(exit)) { return yield* Effect.failCause(exit.cause); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts index be16c4ecc43ee..e82e3afea7303 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts @@ -1,3 +1,4 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -80,7 +81,7 @@ describe("DesktopLocalEnvironmentAuth", () => { ]), } as unknown as DesktopBackendPool.DesktopBackendPool["Service"]); const layerTest = DesktopLocalEnvironmentAuth.layer.pipe( - Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)), + Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)), ); const [first, second] = yield* Effect.gen(function* () { @@ -151,14 +152,17 @@ describe("DesktopLocalEnvironmentAuth", () => { }).pipe( Effect.provide( DesktopLocalEnvironmentAuth.layer.pipe( - Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer)), + Layer.provide(Layer.mergeAll(poolLayer, httpClientLayer, NodeCrypto.layerMac)), ), ), ); assert.strictEqual( yield* Ref.get(presented), - currentDesktopBootstrapToken("desktop-secret", DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS * 2 + 1), + yield* currentDesktopBootstrapToken( + "desktop-secret", + DESKTOP_BOOTSTRAP_TOKEN_WINDOW_MS * 2 + 1, + ).pipe(Effect.provide(NodeCrypto.layerMac)), ); }).pipe(Effect.provide(TestClock.layer())), ); @@ -205,7 +209,7 @@ describe("DesktopLocalEnvironmentAuth", () => { const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth.pipe( Effect.provide( DesktopLocalEnvironmentAuth.layer.pipe( - Layer.provide(Layer.mergeAll(layerPool, layerHttpClient)), + Layer.provide(Layer.mergeAll(layerPool, layerHttpClient, NodeCrypto.layerMac)), ), ), ); diff --git a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts index e916b35053e8f..6c7d24623d40f 100644 --- a/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts +++ b/apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts @@ -5,6 +5,7 @@ import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapTo import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; +import * as Mac from "effect/crypto/Mac"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -67,6 +68,7 @@ export class DesktopLocalEnvironmentAuth extends Context.Service< export const make = Effect.gen(function* () { const pool = yield* DesktopBackendPool.DesktopBackendPool; const httpClient = yield* HttpClient.HttpClient; + const mac = yield* Mac.Mac; const tokenRef = yield* Ref.make(Option.none()); const mutex = yield* Semaphore.make(1); @@ -93,7 +95,9 @@ export const make = Effect.gen(function* () { const credential = secret === undefined ? config.bootstrap.desktopBootstrapToken - : currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis); + : yield* currentDesktopBootstrapToken(secret, yield* Clock.currentTimeMillis).pipe( + Effect.provideService(Mac.Mac, mac), + ); if (!credential) { return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError(); } diff --git a/apps/desktop/src/electron/ElectronApp.ts b/apps/desktop/src/electron/ElectronApp.ts index d677baa56dce3..188f53c4be8d7 100644 --- a/apps/desktop/src/electron/ElectronApp.ts +++ b/apps/desktop/src/electron/ElectronApp.ts @@ -46,6 +46,7 @@ export class ElectronApp extends Context.Service< readonly name: Effect.Effect; /** Packaged builds ship only en-US; app.getLocale() and Intl defaults do not reflect the OS locale. */ readonly systemLocale: Effect.Effect; + readonly preferredSystemLanguages: Effect.Effect>; readonly whenReady: Effect.Effect; readonly requestSingleInstanceLock: Effect.Effect; readonly quit: Effect.Effect; @@ -155,6 +156,7 @@ export const make = ElectronApp.of({ } return toSystemLocaleTag(identifier, hourCycle); }), + preferredSystemLanguages: Effect.sync(() => Electron.app.getPreferredSystemLanguages()), whenReady: Effect.gen(function* () { const isPackaged = Electron.app.isPackaged; yield* Effect.tryPromise({ diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 27af3f2cfd8ae..7563898f43efc 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -216,9 +216,7 @@ const serveDesktopAsset = Effect.fn("desktop.protocol.serveAsset")(function* ( if (request.method !== "GET" && request.method !== "HEAD") { return new Response(null, { status: 405 }); } - const pathname = yield* Effect.try(() => decodeURIComponent(url.pathname)).pipe( - Effect.orElseSucceed(() => null), - ); + const pathname = Option.getOrNull(Option.liftThrowable(decodeURIComponent)(url.pathname)); if (pathname === null || pathname.includes("\0")) return new Response(null, { status: 400 }); const root = path.resolve(assetDirectory); const assetPath = path.resolve(root, `.${pathname}`); diff --git a/apps/desktop/src/electron/ElectronShell.test.ts b/apps/desktop/src/electron/ElectronShell.test.ts index 0e72a46146e0a..9f8286a47ff98 100644 --- a/apps/desktop/src/electron/ElectronShell.test.ts +++ b/apps/desktop/src/electron/ElectronShell.test.ts @@ -54,6 +54,67 @@ describe("ElectronShell", () => { }).pipe(Effect.provide(ElectronShell.layer)), ); + it.effect("opens local editor file deep links", () => + Effect.gen(function* () { + openExternalMock.mockResolvedValue(undefined); + + const urls = [ + "cursor://file/Users/me/repo/file.md:186", + "vscode://file/Users/me/repo/file.md:3:7", + "vscode-insiders://file/Users/me/repo/file.md", + "vscodium://file/C:/Users/me/repo/file.md:3", + ]; + const electronShell = yield* ElectronShell.ElectronShell; + const results = yield* Effect.forEach(urls, (url) => electronShell.openExternal(url)); + + assert.deepEqual(results, [true, true, true, true]); + assert.deepEqual( + openExternalMock.mock.calls, + urls.map((url) => [url]), + ); + }).pipe(Effect.provide(ElectronShell.layer)), + ); + + it.effect("normalizes the scheme case of local editor file deep links", () => + Effect.gen(function* () { + openExternalMock.mockResolvedValue(undefined); + + const electronShell = yield* ElectronShell.ElectronShell; + const result = yield* electronShell.openExternal("VSCode://file/Users/me/repo/file.md:3"); + + assert.equal(result, true); + assert.deepEqual(openExternalMock.mock.calls, [["vscode://file/Users/me/repo/file.md:3"]]); + }).pipe(Effect.provide(ElectronShell.layer)), + ); + + it.effect("does not open editor URLs that are not absolute local file links", () => + Effect.gen(function* () { + openExternalMock.mockResolvedValue(undefined); + + const electronShell = yield* ElectronShell.ElectronShell; + const results = yield* Effect.forEach( + [ + "cursor://user@file/Users/me/repo/file.md", + "cursor://:secret@file/Users/me/repo/file.md", + "cursor://file:8080/Users/me/repo/file.md", + "cursor://anysphere.cursor-deeplink/prompt?text=hi", + "vscode://vscode.git/clone?url=https%3A%2F%2Fexample.com%2Frepo.git", + "cursor://file", + "cursor://file/", + "cursor:file/Users/me/repo/file.md", + "foo://file/Users/me/repo/file.md", + "zed://file/Users/me/repo/file.md", + "jetbrains://file/Users/me/repo/file.md", + "javascript:alert(1)", + ], + (url) => electronShell.openExternal(url), + ); + + assert.deepEqual(results, Array(12).fill(false)); + assert.equal(openExternalMock.mock.calls.length, 0); + }).pipe(Effect.provide(ElectronShell.layer)), + ); + it.effect("does not open editor URLs that mix up link shapes", () => Effect.gen(function* () { openExternalMock.mockResolvedValue(undefined); diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts index e32dba36a6dfa..308f60b10c2cb 100644 --- a/apps/desktop/src/electron/ElectronShell.ts +++ b/apps/desktop/src/electron/ElectronShell.ts @@ -1,5 +1,6 @@ import { MAC_PERMISSION_SETTINGS_URLS } from "../permissions/MacPermission.ts"; import { + isLocalEditorFileUrl, REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor, type SystemSettingsPane, @@ -11,7 +12,7 @@ import * as Option from "effect/Option"; import * as Electron from "electron"; -// Remote editor deep links must reach the OS handler. +// Remote editor deep links and local editor file links must reach the OS handler. const SAFE_WEB_PROTOCOLS = new Set(["http:", "https:"]); const REMOTE_EDITOR_PROTOCOLS = new Set( REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => { @@ -44,7 +45,9 @@ export function parseSafeExternalUrl(rawUrl: unknown): Option.Option { try { const url = new URL(rawUrl); - return SAFE_WEB_PROTOCOLS.has(url.protocol) || isRemoteEditorUrl(url) + return SAFE_WEB_PROTOCOLS.has(url.protocol) || + isRemoteEditorUrl(url) || + isLocalEditorFileUrl(url) ? Option.some(url.href) : Option.none(); } catch { diff --git a/apps/desktop/src/electron/ElectronWindow.test.ts b/apps/desktop/src/electron/ElectronWindow.test.ts index 478d490129014..9eb41ed4e2402 100644 --- a/apps/desktop/src/electron/ElectronWindow.test.ts +++ b/apps/desktop/src/electron/ElectronWindow.test.ts @@ -53,6 +53,15 @@ vi.mock("electron", () => ({ getAllWindows: getAllWindowsMock, getFocusedWindow: getFocusedWindowMock, }), + screen: { + // A 200% display, so the focus target must carry converted bounds. + dipToScreenRect: (_window: unknown, rect: Electron.Rectangle) => ({ + x: rect.x * 2, + y: rect.y * 2, + width: rect.width * 2, + height: rect.height * 2, + }), + }, })); import * as ElectronWindow from "./ElectronWindow.ts"; @@ -116,6 +125,13 @@ describe("ElectronWindow", () => { }); const electronWindow = yield* ElectronWindow.ElectronWindow; yield* electronWindow.prepareReveal(window as unknown as Electron.BrowserWindow); + assert.deepEqual(windowsForegroundPrepareMock.mock.calls[0]?.[0], { + windowId: 41, + processId: process.pid, + title: "T3 Code (Dev)", + bounds: { x: 200, y: 100, width: 2_400, height: 1_600 }, + contentBounds: { x: 216, y: 100, width: 2_368, height: 1_584 }, + }); window.getTitle.mockClear(); const revealFiber = yield* electronWindow diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.ts index 985f9c00775a0..15a117a52b050 100644 --- a/apps/desktop/src/electron/ElectronWindow.ts +++ b/apps/desktop/src/electron/ElectronWindow.ts @@ -26,8 +26,9 @@ function windowsForegroundFocusTarget(window: Electron.BrowserWindow) { windowId: window.id, processId: process.pid, title: window.getTitle(), - bounds: window.getBounds(), - contentBounds: window.getContentBounds(), + // xa11y reports physical desktop pixels on Windows; Electron bounds are DIPs. + bounds: Electron.screen.dipToScreenRect(window, window.getBounds()), + contentBounds: Electron.screen.dipToScreenRect(window, window.getContentBounds()), }; } diff --git a/apps/desktop/src/electron/WindowsForegroundFocusWorker.ts b/apps/desktop/src/electron/WindowsForegroundFocusWorker.ts index a2d892a1c338a..3bdd5d63eefc5 100644 --- a/apps/desktop/src/electron/WindowsForegroundFocusWorker.ts +++ b/apps/desktop/src/electron/WindowsForegroundFocusWorker.ts @@ -32,13 +32,7 @@ async function findTarget( const children = await App.byPid(target.processId, { timeout: 0 }) .then((app) => app.children()) .catch(() => []); - return ( - children.find((candidate) => matchesTarget(candidate, target)) ?? - (await App.list()) - .filter((candidate) => candidate.pid === target.processId) - .map((candidate) => candidate.asElement()) - .find((candidate) => matchesTarget(candidate, target)) - ); + return children.find((candidate) => matchesTarget(candidate, target)); } const cachedElements = new Map(); diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index a46dbafab0f41..6a1b1c62e7471 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -6,6 +6,7 @@ import { installNotificationBadge } from "./methods/notificationBadge.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; import { getConnectionCatalog, setConnectionCatalog } from "./methods/connectionCatalog.ts"; import { + getHostEnvironmentId, getLocalEnvironmentEnabled, setLocalEnvironmentEnabled, } from "./methods/localEnvironment.ts"; @@ -38,6 +39,7 @@ import { getLocalEnvironmentBearerToken, installRelayTelemetryEnabled, getSystemLocale, + getPreferredSystemLanguages, getWindowFullscreenState, openExternal, readMedia, @@ -50,6 +52,7 @@ import { pickProjectFavicon, pickThemeFiles, setTheme, + syncHtmlFullscreen, showContextMenu, } from "./methods/window.ts"; import { @@ -78,6 +81,7 @@ import { getCliCommandState, installCliCommand, uninstallCliCommand, + addCliCommandToPath, } from "./methods/cliCommand.ts"; export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () { @@ -94,10 +98,12 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handleSync(getAppBranding); yield* installRelayTelemetryEnabled(); yield* ipc.handleSync(getSystemLocale); + yield* ipc.handleSync(getPreferredSystemLanguages); yield* ipc.handleSync(getWindowFullscreenState); yield* ipc.handleSync(getLocalEnvironmentBootstraps); yield* ipc.handleSync(getLocalEnvironmentEnabled); yield* ipc.handle(setLocalEnvironmentEnabled); + yield* ipc.handle(getHostEnvironmentId); yield* ipc.handle(getLocalEnvironmentBearerToken); yield* ipc.handle(getClientSettings); @@ -149,6 +155,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(checkSystemPermission); yield* ipc.handle(pasteAsText); yield* ipc.handle(revealWindow); + yield* ipc.handle(syncHtmlFullscreen); yield* ipc.handle(probeRemoteEditors); yield* ipc.handle(getUpdateState); yield* ipc.handle(setUpdateChannel); @@ -158,6 +165,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(getCliCommandState); yield* ipc.handle(installCliCommand); yield* ipc.handle(uninstallCliCommand); + yield* ipc.handle(addCliCommandToPath); for (const previewMethod of PreviewIpc.methods) { // Explicit types preserve the error/service union of these heterogeneous preview methods. yield* ipc.handle< diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 0f125c05de307..aebbc1c24f8c2 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -19,6 +19,7 @@ export const TRACKPAD_SCROLL_BEGIN_CHANNEL = "desktop:trackpad-scroll-begin"; export const TRACKPAD_SCROLL_END_CHANNEL = "desktop:trackpad-scroll-end"; export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state"; export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state"; +export const SYNC_HTML_FULLSCREEN_CHANNEL = "desktop:sync-html-fullscreen"; export const DESKTOP_APP_ACTIVATION_READY_CHANNEL = "desktop:app-activation-ready"; export const DESKTOP_APP_ACTIVATION_COMPLETE_CHANNEL = "desktop:app-activation-complete"; export const DESKTOP_APP_ACTIVATION_REQUEST_CHANNEL = "desktop:app-activation-request"; @@ -31,12 +32,15 @@ export const UPDATE_CHECK_CHANNEL = "desktop:update-check"; export const CLI_COMMAND_GET_STATE_CHANNEL = "desktop:cli-command-get-state"; export const CLI_COMMAND_INSTALL_CHANNEL = "desktop:cli-command-install"; export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall"; +export const CLI_COMMAND_ADD_TO_PATH_CHANNEL = "desktop:cli-command-add-to-path"; export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled"; export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale"; +export const GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL = "desktop:get-preferred-system-languages"; export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps"; export const GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:get-local-environment-enabled"; export const SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL = "desktop:set-local-environment-enabled"; +export const GET_HOST_ENVIRONMENT_ID_CHANNEL = "desktop:get-host-environment-id"; export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL = "desktop:get-local-environment-bearer-token"; export const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings"; @@ -90,6 +94,7 @@ export const PREVIEW_SET_ZOOM_FACTOR_CHANNEL = "desktop:preview-set-zoom-factor" export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload"; export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme"; export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted"; +export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown"; export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools"; export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies"; export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache"; @@ -120,6 +125,9 @@ export const CHECK_SYSTEM_PERMISSION_CHANNEL = "desktop:check-system-permission" export const PREVIEW_RECORDING_INPUT_CHANNEL = "desktop:preview-recording-input"; +export const PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL = "desktop:preview-annotation-voice-event"; +export const PREVIEW_ANNOTATION_VOICE_STATE_CHANNEL = "desktop:preview-annotation-voice-state"; + export const RECEIVE_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:receive-provider-auth-callback"; export const CANCEL_PROVIDER_AUTH_CALLBACK_CHANNEL = "desktop:cancel-provider-auth-callback"; export const TAKE_LEGACY_LOCAL_STORAGE_CHANNEL = "desktop:take-legacy-local-storage"; diff --git a/apps/desktop/src/ipc/methods/cliCommand.ts b/apps/desktop/src/ipc/methods/cliCommand.ts index be9672c682517..b3731b8b6f9cb 100644 --- a/apps/desktop/src/ipc/methods/cliCommand.ts +++ b/apps/desktop/src/ipc/methods/cliCommand.ts @@ -32,3 +32,12 @@ export const uninstallCliCommand = makeIpcMethod({ return yield* (yield* DesktopCliCommand.DesktopCliCommand).uninstall; }), }); + +export const addCliCommandToPath = makeIpcMethod({ + channel: IpcChannels.CLI_COMMAND_ADD_TO_PATH_CHANNEL, + payload: Schema.Void, + result: DesktopCliCommandStateSchema, + handler: Effect.fn("desktop.ipc.cliCommand.addToPath")(function* () { + return yield* (yield* DesktopCliCommand.DesktopCliCommand).addToPath; + }), +}); diff --git a/apps/desktop/src/ipc/methods/localEnvironment.test.ts b/apps/desktop/src/ipc/methods/localEnvironment.test.ts index 94bbf085a9921..36e89eb880c15 100644 --- a/apps/desktop/src/ipc/methods/localEnvironment.test.ts +++ b/apps/desktop/src/ipc/methods/localEnvironment.test.ts @@ -1,4 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -10,7 +13,11 @@ import * as ElectronApp from "../../electron/ElectronApp.ts"; import * as ElectronTheme from "../../electron/ElectronTheme.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as DesktopWindow from "../../window/DesktopWindow.ts"; -import { getLocalEnvironmentEnabled, setLocalEnvironmentEnabled } from "./localEnvironment.ts"; +import { + getHostEnvironmentId, + getLocalEnvironmentEnabled, + setLocalEnvironmentEnabled, +} from "./localEnvironment.ts"; const layerUnusedLifecycleRuntime = Layer.mergeAll( DesktopShutdown.layer, @@ -27,6 +34,26 @@ const layerUnusedLifecycleRuntime = Layer.mergeAll( ); describe("local environment IPC", () => { + it.effect("reads the shared home identity without creating one", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const environment = DesktopEnvironment.DesktopEnvironment.of({ + path, + stateDir, + } as DesktopEnvironment.DesktopEnvironment["Service"]); + const read = getHostEnvironmentId + .handler(undefined) + .pipe(Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment)); + assert.strictEqual(yield* read, null); + assert.isFalse(yield* fs.exists(path.join(stateDir, "environment-id"))); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), " service-id\n"); + assert.strictEqual(yield* read, "service-id"); + yield* fs.writeFileString(path.join(stateDir, "environment-id"), "\n"); + assert.strictEqual(yield* read, null); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); it.effect("relaunches only when the setting changes and keeps other settings", () => { const relaunchReasons: Array = []; const layer = Layer.mergeAll( diff --git a/apps/desktop/src/ipc/methods/localEnvironment.ts b/apps/desktop/src/ipc/methods/localEnvironment.ts index 74cccd04a0c58..3c5c2c63d77da 100644 --- a/apps/desktop/src/ipc/methods/localEnvironment.ts +++ b/apps/desktop/src/ipc/methods/localEnvironment.ts @@ -1,6 +1,8 @@ import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Schema from "effect/Schema"; +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts"; import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts"; import * as IpcChannels from "../channels.ts"; @@ -28,3 +30,18 @@ export const setLocalEnvironmentEnabled = makeIpcMethod({ } }), }); + +// A background service sharing this app's T3 home records its environment ID in the same state dir. +export const getHostEnvironmentId = makeIpcMethod({ + channel: IpcChannels.GET_HOST_ENVIRONMENT_ID_CHANNEL, + payload: Schema.Void, + result: Schema.NullOr(Schema.String), + handler: Effect.fn("desktop.ipc.localEnvironment.getHostEnvironmentId")(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const contents = yield* fileSystem + .readFileString(environment.path.join(environment.stateDir, "environment-id")) + .pipe(Effect.orElseSucceed(() => "")); + return contents.trim() || null; + }), +}); diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index 20b7bb4877d59..98a0aab831645 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -1,6 +1,8 @@ import { DesktopPreviewAnnotationSendEnabledInputSchema, DesktopPreviewAnnotationThemeInputSchema, + DesktopPreviewAnnotationVoiceStateSchema, + DesktopPreviewPickElementInputSchema, DesktopPreviewArtifactInputSchema, DesktopPreviewConfigInputSchema, DesktopPreviewNavigateInputSchema, @@ -9,6 +11,7 @@ import { DesktopPreviewRegisterWebviewInputSchema, DesktopPreviewScreenshotArtifactSchema, DesktopPreviewSetAudioMutedInputSchema, + DesktopPreviewSetShownInputSchema, DesktopPreviewSetColorSchemeInputSchema, DesktopPreviewSetZoomFactorInputSchema, BrowserImportResult, @@ -193,6 +196,15 @@ const setAudioMuted = DesktopIpc.makeIpcMethod({ yield* manager.setAudioMuted(tabId, audioMuted); }), }); +const setShown = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, + payload: DesktopPreviewSetShownInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.setShown")(function* ({ tabId, shown }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.setShown(tabId, shown); + }), +}); const openDevTools = tabMethod( IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, "desktop.ipc.preview.openDevTools", @@ -353,11 +365,21 @@ const setAnnotationTheme = DesktopIpc.makeIpcMethod({ const pickElement = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, - payload: DesktopPreviewTabInputSchema, + payload: DesktopPreviewPickElementInputSchema, result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema), - handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) { + handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId, voice }) { + const manager = yield* PreviewManager.PreviewManager; + return yield* manager.pickElement(tabId, voice); + }), +}); + +const updateAnnotationVoice = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_ANNOTATION_VOICE_STATE_CHANNEL, + payload: DesktopPreviewAnnotationVoiceStateSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.updateAnnotationVoice")(function* (state) { const manager = yield* PreviewManager.PreviewManager; - return yield* manager.pickElement(tabId); + yield* manager.updateAnnotationVoice(state); }), }); @@ -418,6 +440,7 @@ const saveRecording = DesktopIpc.makeIpcMethod({ export const methods = [ setForwardedShortcuts, + updateAnnotationVoice, createTab, closeTab, registerWebview, @@ -432,6 +455,7 @@ export const methods = [ setColorScheme, setZoomFactor, setAudioMuted, + setShown, openDevTools, clearCookies, clearCache, diff --git a/apps/desktop/src/ipc/methods/sshEnvironment.ts b/apps/desktop/src/ipc/methods/sshEnvironment.ts index 15e04f71282b1..b368b5581d06d 100644 --- a/apps/desktop/src/ipc/methods/sshEnvironment.ts +++ b/apps/desktop/src/ipc/methods/sshEnvironment.ts @@ -26,7 +26,6 @@ import { } from "@t3tools/contracts"; import { SshHttpBridgeError } from "@t3tools/ssh/errors"; import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -35,10 +34,12 @@ import * as DesktopIpc from "../DesktopIpc.ts"; import * as DesktopSshEnvironment from "../../ssh/DesktopSshEnvironment.ts"; import * as DesktopSshPasswordPrompts from "../../ssh/DesktopSshPasswordPrompts.ts"; -type DesktopSshEnvironmentRequestOperation = - | "fetch-environment-descriptor" - | "bootstrap-bearer-session" - | "fetch-session-state"; +const DesktopSshEnvironmentRequestOperation = Schema.Literals([ + "fetch-environment-descriptor", + "bootstrap-bearer-session", + "fetch-session-state", +]); +type DesktopSshEnvironmentRequestOperation = typeof DesktopSshEnvironmentRequestOperation.Type; type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError; @@ -47,12 +48,13 @@ const isEnvironmentInternalError = Schema.is(EnvironmentInternalError); const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError); const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError); +const isRemoteEnvironmentAuthUndeclaredStatusError = Schema.is( + RemoteEnvironmentAuthUndeclaredStatusError, +); +const isSshHttpBridgeError = Schema.is(SshHttpBridgeError); function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null { - if ( - cause instanceof RemoteEnvironmentAuthUndeclaredStatusError || - cause instanceof SshHttpBridgeError - ) { + if (isRemoteEnvironmentAuthUndeclaredStatusError(cause) || isSshHttpBridgeError(cause)) { return cause.status ?? null; } if (isEnvironmentRequestInvalidError(cause)) { @@ -73,13 +75,14 @@ function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | n return null; } -export class DesktopSshEnvironmentRequestError extends Data.TaggedError( +export class DesktopSshEnvironmentRequestError extends Schema.TaggedError()( "DesktopSshEnvironmentRequestError", -)<{ - readonly operation: DesktopSshEnvironmentRequestOperation; - readonly cause: DesktopSshEnvironmentRequestCause; - readonly sshHttpStatus: number | null; -}> { + { + operation: DesktopSshEnvironmentRequestOperation, + cause: Schema.Defect(), + sshHttpStatus: Schema.NullOr(Schema.Number), + }, +) { // The web client matches "[ssh_http:500]" to explain version-skewed SSH pairing. override get message() { const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `; diff --git a/apps/desktop/src/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index 2ddc672891755..eebabd429025d 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -35,6 +35,7 @@ import { pickProjectFavicon, probeRemoteEditors, readMedia, + syncHtmlFullscreen, } from "./window.ts"; const readyWslConfig: DesktopBackendManager.DesktopBackendStartConfig = { @@ -356,6 +357,93 @@ describe("pickProjectFavicon", () => { ); }); +describe("syncHtmlFullscreen", () => { + const fullscreenWindow = (fullscreen: boolean, { animatedExit = false } = {}) => { + let current = fullscreen; + let exiting = false; + const queued: boolean[] = []; + const leaveListeners: Array<() => void> = []; + const leave = () => { + current = false; + for (const listener of leaveListeners) listener(); + }; + // Like macOS, an animated exit keeps reporting fullscreen and queues requests until it ends. + const setFullScreen = vi.fn((next: boolean) => { + if (exiting) queued.push(next); + else if (next) current = true; + else if (!current) return; + else if (animatedExit) exiting = true; + else leave(); + }); + const finishExit = () => { + exiting = false; + leave(); + for (const next of queued.splice(0)) setFullScreen(next); + }; + const window = { + webContents: { id: 1 }, + isDestroyed: () => false, + isFullScreen: () => current, + setFullScreen, + on: (event: string, listener: () => void) => { + if (event === "leave-full-screen") leaveListeners.push(listener); + }, + } as unknown as Electron.BrowserWindow; + const layer = Layer.mock(ElectronWindow.ElectronWindow)({ main: Effect.succeedSome(window) }); + return { window, setFullScreen, finishExit, layer }; + }; + const fromMainRenderer = { sender: { id: 1 } }; + + it.effect("takes the screen for the app's own fullscreen element and gives it back", () => { + const { window, layer } = fullscreenWindow(false); + return Effect.gen(function* () { + yield* syncHtmlFullscreen.handler(true, fromMainRenderer); + assert.isTrue(window.isFullScreen()); + + yield* syncHtmlFullscreen.handler(false, fromMainRenderer); + assert.isFalse(window.isFullScreen()); + }).pipe(Effect.provide(layer)); + }); + + it.effect("keeps a window the user had already made fullscreen", () => { + const { window, setFullScreen, layer } = fullscreenWindow(true); + return Effect.gen(function* () { + yield* syncHtmlFullscreen.handler(true, fromMainRenderer); + yield* syncHtmlFullscreen.handler(false, fromMainRenderer); + + assert.isTrue(window.isFullScreen()); + assert.strictEqual(setFullScreen.mock.calls.length, 0); + }).pipe(Effect.provide(layer)); + }); + + it.effect("hands the window back once the user leaves OS fullscreen during playback", () => { + const { window, layer } = fullscreenWindow(false); + return Effect.gen(function* () { + yield* syncHtmlFullscreen.handler(true, fromMainRenderer); + window.setFullScreen(false); + window.setFullScreen(true); + yield* syncHtmlFullscreen.handler(false, fromMainRenderer); + + assert.isTrue(window.isFullScreen()); + }).pipe(Effect.provide(layer)); + }); + + it.effect("takes the screen again when the video returns during an animated exit", () => { + const { window, finishExit, layer } = fullscreenWindow(false, { animatedExit: true }); + return Effect.gen(function* () { + yield* syncHtmlFullscreen.handler(true, fromMainRenderer); + yield* syncHtmlFullscreen.handler(false, fromMainRenderer); + yield* syncHtmlFullscreen.handler(true, fromMainRenderer); + finishExit(); + assert.isTrue(window.isFullScreen()); + + yield* syncHtmlFullscreen.handler(false, fromMainRenderer); + finishExit(); + assert.isFalse(window.isFullScreen()); + }).pipe(Effect.provide(layer)); + }); +}); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "finds remote editors installed without PATH launchers", () => diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index 63b8db03dad03..e0eea5c74c9ed 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -106,6 +106,15 @@ export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({ }), }); +export const getPreferredSystemLanguages = DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL, + result: Schema.Array(Schema.String), + handler: Effect.fn("desktop.ipc.window.getPreferredSystemLanguages")(function* () { + const electronApp = yield* ElectronApp.ElectronApp; + return yield* electronApp.preferredSystemLanguages; + }), +}); + export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({ channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL, result: Schema.Boolean, @@ -314,6 +323,12 @@ export const openExternal = DesktopIpc.makeIpcMethod({ const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024; +// No URL field: media URLs can carry signed query tokens. +class MediaReadError extends Schema.TaggedError()("MediaReadError", { + message: Schema.String, + cause: Schema.Defect(), +}) {} + // The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it. export const readMedia = DesktopIpc.makeIpcMethod({ channel: IpcChannels.READ_MEDIA_CHANNEL, @@ -330,25 +345,28 @@ export const readMedia = DesktopIpc.makeIpcMethod({ return null; } const session = window.value.webContents.session; - return yield* Effect.tryPromise(async () => { - // Like an , send the session's cookies. - const response = await session.fetch(url, { credentials: "include" }); - const mimeType = response.headers.get("content-type") ?? ""; - if (!response.ok || !response.body) { - await response.body?.cancel(); - return { status: response.status, mimeType, data: new Uint8Array() }; - } - // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory. - const chunks: Uint8Array[] = []; - let size = 0; - for await (const chunk of response.body) { - size += chunk.byteLength; - if (size > READ_MEDIA_MAX_BYTES) { - return { status: 413, mimeType, data: new Uint8Array() }; + return yield* Effect.tryPromise({ + try: async () => { + // Like an , send the session's cookies. + const response = await session.fetch(url, { credentials: "include" }); + const mimeType = response.headers.get("content-type") ?? ""; + if (!response.ok || !response.body) { + await response.body?.cancel(); + return { status: response.status, mimeType, data: new Uint8Array() }; } - chunks.push(chunk); - } - return { status: response.status, mimeType, data: Buffer.concat(chunks) }; + // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory. + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of response.body) { + size += chunk.byteLength; + if (size > READ_MEDIA_MAX_BYTES) { + return { status: 413, mimeType, data: new Uint8Array() }; + } + chunks.push(chunk); + } + return { status: response.status, mimeType, data: Buffer.concat(chunks) }; + }, + catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }), }).pipe(Effect.orElseSucceed(() => null)); }), }); @@ -433,6 +451,56 @@ export const revealWindow = DesktopIpc.makeIpcMethod({ }), }); +const htmlFullscreenStates = new WeakMap< + Electron.BrowserWindow, + { owned: boolean; leaving: boolean } +>(); + +const htmlFullscreenState = (window: Electron.BrowserWindow) => { + const existing = htmlFullscreenStates.get(window); + if (existing !== undefined) return existing; + const state = { owned: false, leaving: false }; + window.on("leave-full-screen", () => { + // Leaving OS fullscreen any other way, such as F11, hands the window back to the user. + if (!state.leaving) state.owned = false; + state.leaving = false; + }); + htmlFullscreenStates.set(window, state); + return state; +}; + +// The main window keeps HTML fullscreen inside itself so preview guests stay in their webview, +// so the app's own fullscreen elements, such as chat videos, take the screen here. +export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL, + payload: Schema.Boolean, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) { + const electronWindow = yield* ElectronWindow.ElectronWindow; + const main = yield* electronWindow.main; + if ( + event === undefined || + Option.isNone(main) || + main.value.isDestroyed() || + main.value.webContents.id !== event.sender.id + ) { + return; + } + const window = main.value; + const state = htmlFullscreenState(window); + if (fullscreen) { + // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry. + if (state.owned || (window.isFullScreen() && !state.leaving)) return; + state.owned = true; + window.setFullScreen(true); + } else if (state.owned) { + state.owned = false; + state.leaving = window.isFullScreen(); + window.setFullScreen(false); + } + }), +}); + const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024; export const pickThemeFiles = DesktopIpc.makeIpcMethod({ diff --git a/apps/desktop/src/permissions/MacPermissions.ts b/apps/desktop/src/permissions/MacPermissions.ts index 0a7bb3a2c4475..2052f378743c6 100644 --- a/apps/desktop/src/permissions/MacPermissions.ts +++ b/apps/desktop/src/permissions/MacPermissions.ts @@ -2,6 +2,7 @@ import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import * as Electron from "electron"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import { MacPermissionHelper } from "./MacPermissionHelper.ts"; @@ -18,6 +19,15 @@ export class MacPermissions extends Context.Service< } >()("@t3tools/desktop/permissions/MacPermissions") {} +class MacPermissionHelperError extends Schema.TaggedError()( + "MacPermissionHelperError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not show the permission helper."; + } +} + export const layer = Layer.effect( MacPermissions, Effect.gen(function* () { @@ -28,15 +38,17 @@ export const layer = Layer.effect( return MacPermissions.of({ showHelper: Effect.fn("MacPermissions.showHelper")(function* (permission, owner, isGranted) { if (environment.platform !== "darwin" || !environment.isPackaged) return; - yield* Effect.tryPromise(() => - helper.show( - permission, - path.join(environment.dirname, "mac-permission-preload.cjs"), - owner, - environment.resolveResourcePathCandidates("icon.png"), - isGranted, - ), - ).pipe( + yield* Effect.tryPromise({ + try: () => + helper.show( + permission, + path.join(environment.dirname, "mac-permission-preload.cjs"), + owner, + environment.resolveResourcePathCandidates("icon.png"), + isGranted, + ), + catch: (cause) => new MacPermissionHelperError({ cause }), + }).pipe( Effect.catch((cause) => Effect.logWarning("Could not show permission helper", cause)), ); }), diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index da56807186ac5..2dbc4eeda3ae5 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -1,5 +1,6 @@ import type { DesktopBridge, + DesktopPreviewAnnotationVoiceEvent, DesktopPreviewOpenLinkEvent, DesktopPreviewPointerEvent, DesktopPreviewRecordingInputEvent, @@ -56,6 +57,18 @@ if (clientPlatform === "darwin") { window.addEventListener("resize", syncWindowControlInset); } +const syncHtmlFullscreen = () => { + const element = document.fullscreenElement; + // A preview guest's fullscreen surfaces here as its , which stays inside the window. + void ipcRenderer.invoke( + IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL, + element !== null && element.tagName !== "WEBVIEW", + ); +}; +// A reload or renderer crash never reports the old document's exit, so each document reports its start. +syncHtmlFullscreen(); +document.addEventListener("fullscreenchange", syncHtmlFullscreen); + function unwrapEnsureSshEnvironmentResult(result: unknown) { if ( typeof result === "object" && @@ -106,6 +119,12 @@ contextBridge.exposeInMainWorld("desktopBridge", { const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL); return typeof result === "string" ? result : null; }, + getPreferredSystemLanguages: () => { + const result: unknown = ipcRenderer.sendSync( + IpcChannels.GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL, + ); + return Array.isArray(result) ? result.filter((tag) => typeof tag === "string") : []; + }, getLocalEnvironmentBootstraps: () => { const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL); if (!Array.isArray(result)) { @@ -119,6 +138,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL) !== false, setLocalEnvironmentEnabled: (enabled) => ipcRenderer.invoke(IpcChannels.SET_LOCAL_ENVIRONMENT_ENABLED_CHANNEL, enabled), + getHostEnvironmentId: () => ipcRenderer.invoke(IpcChannels.GET_HOST_ENVIRONMENT_ID_CHANNEL), getClientSettings: () => ipcRenderer.invoke(IpcChannels.GET_CLIENT_SETTINGS_CHANNEL), setClientSettings: (settings) => ipcRenderer.invoke(IpcChannels.SET_CLIENT_SETTINGS_CHANNEL, settings), @@ -277,6 +297,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { getState: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_GET_STATE_CHANNEL), install: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_INSTALL_CHANNEL), uninstall: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_UNINSTALL_CHANNEL), + addToPath: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_ADD_TO_PATH_CHANNEL), }, onUpdateState: (listener) => { const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => { @@ -348,6 +369,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }), setAudioMuted: (tabId, audioMuted) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }), + setShown: (tabId, shown) => + ipcRenderer.invoke(IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, { tabId, shown }), openDevTools: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }), listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL), @@ -366,7 +389,20 @@ contextBridge.exposeInMainWorld("desktopBridge", { tabId, enabled, }), - pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }), + annotationVoice: { + onEvent: (listener) => { + const onEvent = (_event: Electron.IpcRendererEvent, tabId: string, value: unknown) => { + if (typeof tabId !== "string" || typeof value !== "object" || value === null) return; + listener(tabId, value as DesktopPreviewAnnotationVoiceEvent); + }; + ipcRenderer.on(IpcChannels.PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL, onEvent); + return () => ipcRenderer.off(IpcChannels.PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL, onEvent); + }, + update: (state) => + ipcRenderer.invoke(IpcChannels.PREVIEW_ANNOTATION_VOICE_STATE_CHANNEL, state), + }, + pickElement: (tabId, voice) => + ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId, voice }), cancelPickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }), captureScreenshot: (tabId) => diff --git a/apps/desktop/src/preview/Annotation.css b/apps/desktop/src/preview/Annotation.css index 0897aad4f86d5..3c5604e1b8cf3 100644 --- a/apps/desktop/src/preview/Annotation.css +++ b/apps/desktop/src/preview/Annotation.css @@ -36,6 +36,7 @@ --t3-popover-foreground: oklch(0.269 0 0); --t3-primary: oklch(0.488 0.217 264); --t3-primary-foreground: white; + --t3-destructive: oklch(0.577 0.245 27.325); --t3-muted: rgb(0 0 0 / 4%); --t3-muted-foreground: oklch(0.556 0 0); --t3-accent: rgb(0 0 0 / 4%); @@ -66,3 +67,8 @@ textarea:focus-visible { outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent); outline-offset: -2px; } + +/* Utility display classes must not override the native hidden state. */ +[hidden] { + display: none !important; +} diff --git a/apps/desktop/src/preview/AnnotationStyles.generated.ts b/apps/desktop/src/preview/AnnotationStyles.generated.ts index d02abc8ac6123..3b8e2b7000896 100644 --- a/apps/desktop/src/preview/AnnotationStyles.generated.ts +++ b/apps/desktop/src/preview/AnnotationStyles.generated.ts @@ -1,3 +1,3 @@ // Generated by scripts/build-preview-annotation-css.mjs. Do not edit. export const previewAnnotationStyles = - '/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', \'Noto Sans\', Arial, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring:where(:not(iframe)) {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.visible {\n visibility: visible;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: 0px;\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);\n}\n.h-8 {\n height: calc(var(--spacing) * 8);\n}\n.max-h-24 {\n max-height: calc(var(--spacing) * 24);\n}\n.max-h-\\[calc\\(100vh-16px\\)\\] {\n max-height: calc(100vh - 16px);\n}\n.max-h-\\[min\\(176px\\,calc\\(100vh-180px\\)\\)\\] {\n max-height: min(176px, calc(100vh - 180px));\n}\n.min-h-7 {\n min-height: calc(var(--spacing) * 7);\n}\n.min-h-8 {\n min-height: calc(var(--spacing) * 8);\n}\n.w-6 {\n width: calc(var(--spacing) * 6);\n}\n.w-8 {\n width: calc(var(--spacing) * 8);\n}\n.w-\\[min\\(360px\\,calc\\(100vw-16px\\)\\)\\] {\n width: min(360px, calc(100vw - 16px));\n}\n.w-full {\n width: 100%;\n}\n.max-w-70 {\n max-width: calc(var(--spacing) * 70);\n}\n.min-w-0 {\n min-width: 0px;\n}\n.flex-1 {\n flex: 1;\n}\n.shrink-0 {\n flex-shrink: 0;\n}\n.-translate-x-1\\/2 {\n --tw-translate-x: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.-translate-y-1\\/2 {\n --tw-translate-y: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.cursor-grab {\n cursor: grab;\n}\n.cursor-pointer {\n cursor: pointer;\n}\n.resize {\n resize: both;\n}\n.resize-none {\n resize: none;\n}\n.appearance-none {\n appearance: none;\n}\n.grid-cols-\\[22px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 22px minmax(0,1fr);\n}\n.grid-cols-\\[82px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 82px minmax(0,1fr);\n}\n.flex-col {\n flex-direction: column;\n}\n.items-center {\n align-items: center;\n}\n.items-start {\n align-items: flex-start;\n}\n.justify-center {\n justify-content: center;\n}\n.gap-0\\.5 {\n gap: calc(var(--spacing) * 0.5);\n}\n.gap-1 {\n gap: var(--spacing);\n}\n.gap-2 {\n gap: calc(var(--spacing) * 2);\n}\n.overflow-auto {\n overflow: auto;\n}\n.overflow-hidden {\n overflow: hidden;\n}\n.overflow-y-hidden {\n overflow-y: hidden;\n}\n.rounded-lg {\n border-radius: var(--t3-radius);\n}\n.rounded-md {\n border-radius: calc(var(--t3-radius) - 2px);\n}\n.rounded-xl {\n border-radius: calc(var(--t3-radius) + 4px);\n}\n.border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n}\n.border-0 {\n border-style: var(--tw-border-style);\n border-width: 0px;\n}\n.border-t {\n border-top-style: var(--tw-border-style);\n border-top-width: 1px;\n}\n.border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n}\n.border-border {\n border-color: var(--t3-border);\n}\n.border-input {\n border-color: var(--t3-input);\n}\n.border-primary {\n border-color: var(--t3-primary);\n}\n.border-transparent {\n border-color: transparent;\n}\n.border-b-transparent {\n border-bottom-color: transparent;\n}\n.bg-background {\n background-color: var(--t3-background);\n}\n.bg-muted {\n background-color: var(--t3-muted);\n}\n.bg-muted\\/40 {\n background-color: var(--t3-muted);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-muted) 40%, transparent);\n }\n}\n.bg-popover\\/95 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 95%, transparent);\n }\n}\n.bg-popover\\/96 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 96%, transparent);\n }\n}\n.bg-primary {\n background-color: var(--t3-primary);\n}\n.bg-primary\\/10 {\n background-color: var(--t3-primary);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-primary) 10%, transparent);\n }\n}\n.bg-transparent {\n background-color: transparent;\n}\n.p-0 {\n padding: 0px;\n}\n.p-1 {\n padding: var(--spacing);\n}\n.p-2 {\n padding: calc(var(--spacing) * 2);\n}\n.px-0 {\n padding-inline: 0px;\n}\n.px-1 {\n padding-inline: var(--spacing);\n}\n.px-2 {\n padding-inline: calc(var(--spacing) * 2);\n}\n.px-2\\.5 {\n padding-inline: calc(var(--spacing) * 2.5);\n}\n.px-3 {\n padding-inline: calc(var(--spacing) * 3);\n}\n.py-1 {\n padding-block: var(--spacing);\n}\n.py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n}\n.py-2 {\n padding-block: calc(var(--spacing) * 2);\n}\n.font-mono {\n font-family: var(--t3-font-mono);\n}\n.font-sans {\n font-family: var(--t3-font-sans);\n}\n.text-lg {\n font-size: var(--text-lg);\n line-height: var(--tw-leading, var(--text-lg--line-height));\n}\n.text-sm {\n font-size: var(--text-sm);\n line-height: var(--tw-leading, var(--text-sm--line-height));\n}\n.text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n}\n.leading-5 {\n --tw-leading: calc(var(--spacing) * 5);\n line-height: calc(var(--spacing) * 5);\n}\n.font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n}\n.font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n}\n.font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n}\n.text-foreground {\n color: var(--t3-foreground);\n}\n.text-muted-foreground {\n color: var(--t3-muted-foreground);\n}\n.text-popover-foreground {\n color: var(--t3-popover-foreground);\n}\n.text-primary {\n color: var(--t3-primary);\n}\n.text-primary-foreground {\n color: var(--t3-primary-foreground);\n}\n.shadow-2xl {\n --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-md {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-xs {\n --tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.05));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.ring-0 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.blur {\n --tw-blur: blur(8px);\n filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);\n}\n.backdrop-blur-xl {\n --tw-backdrop-blur: blur(var(--blur-xl));\n -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n}\n.outline-none {\n --tw-outline-style: none;\n outline-style: none;\n}\n.select-none {\n -webkit-user-select: none;\n user-select: none;\n}\n.placeholder\\:text-muted-foreground::placeholder {\n color: var(--t3-muted-foreground);\n}\n@media (hover: hover) {\n .hover\\:bg-accent:hover {\n background-color: var(--t3-accent);\n }\n .hover\\:bg-primary\\/90:hover {\n background-color: var(--t3-primary);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .hover\\:bg-primary\\/90:hover {\n background-color: color-mix(in oklab, var(--t3-primary) 90%, transparent);\n }\n }\n .hover\\:text-accent-foreground:hover {\n color: var(--t3-accent-foreground);\n }\n}\n.focus\\:border-b-primary:focus {\n border-bottom-color: var(--t3-primary);\n}\n.focus\\:ring-0:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.focus\\:outline-none:focus {\n --tw-outline-style: none;\n outline-style: none;\n}\n.disabled\\:pointer-events-none:disabled {\n pointer-events: none;\n}\n.disabled\\:opacity-60:disabled {\n opacity: 60%;\n}\n:host {\n --t3-font-sans: "DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,\n sans-serif;\n --t3-font-mono: "SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;\n --t3-radius: 0.625rem;\n --t3-background: white;\n --t3-foreground: oklch(0.269 0 0);\n --t3-popover: white;\n --t3-popover-foreground: oklch(0.269 0 0);\n --t3-primary: oklch(0.488 0.217 264);\n --t3-primary-foreground: white;\n --t3-muted: rgb(0 0 0 / 4%);\n --t3-muted-foreground: oklch(0.556 0 0);\n --t3-accent: rgb(0 0 0 / 4%);\n --t3-accent-foreground: oklch(0.269 0 0);\n --t3-border: rgb(0 0 0 / 8%);\n --t3-input: rgb(0 0 0 / 10%);\n --t3-ring: oklch(0.488 0.217 264);\n color: var(--t3-foreground);\n font-family: var(--t3-font-sans);\n}\n* {\n box-sizing: border-box;\n border-color: var(--t3-border);\n}\nbutton, input, select, textarea {\n font: inherit;\n}\nbutton:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {\n outline: 2px solid var(--t3-ring);\n @supports (color: color-mix(in lab, red, red)) {\n outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);\n }\n outline-offset: -2px;\n}\n@property --tw-translate-x {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-y {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-z {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-leading {\n syntax: "*";\n inherits: false;\n}\n@property --tw-font-weight {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-inset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-ring-inset {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-offset-width {\n syntax: "";\n inherits: false;\n initial-value: 0px;\n}\n@property --tw-ring-offset-color {\n syntax: "*";\n inherits: false;\n initial-value: #fff;\n}\n@property --tw-ring-offset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-sepia {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-drop-shadow-size {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-sepia {\n syntax: "*";\n inherits: false;\n}\n@layer properties {\n *, ::before, ::after, ::backdrop {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-blur: initial;\n --tw-brightness: initial;\n --tw-contrast: initial;\n --tw-grayscale: initial;\n --tw-hue-rotate: initial;\n --tw-invert: initial;\n --tw-opacity: initial;\n --tw-saturate: initial;\n --tw-sepia: initial;\n --tw-drop-shadow: initial;\n --tw-drop-shadow-color: initial;\n --tw-drop-shadow-alpha: 100%;\n --tw-drop-shadow-size: initial;\n --tw-backdrop-blur: initial;\n --tw-backdrop-brightness: initial;\n --tw-backdrop-contrast: initial;\n --tw-backdrop-grayscale: initial;\n --tw-backdrop-hue-rotate: initial;\n --tw-backdrop-invert: initial;\n --tw-backdrop-opacity: initial;\n --tw-backdrop-saturate: initial;\n --tw-backdrop-sepia: initial;\n }\n}\n'; + '/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, \'Helvetica Neue\', \'Noto Sans\', Arial, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring:where(:not(iframe)) {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.visible {\n visibility: visible;\n}\n.sr-only {\n position: absolute;\n width: 1px;\n height: 1px;\n padding: 0;\n margin: -1px;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n border-width: 0;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: 0px;\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-5 {\n height: calc(var(--spacing) * 5);\n}\n.h-7 {\n height: calc(var(--spacing) * 7);\n}\n.h-8 {\n height: calc(var(--spacing) * 8);\n}\n.h-full {\n height: 100%;\n}\n.max-h-24 {\n max-height: calc(var(--spacing) * 24);\n}\n.max-h-\\[calc\\(100vh-16px\\)\\] {\n max-height: calc(100vh - 16px);\n}\n.max-h-\\[min\\(176px\\,calc\\(100vh-180px\\)\\)\\] {\n max-height: min(176px, calc(100vh - 180px));\n}\n.min-h-7 {\n min-height: calc(var(--spacing) * 7);\n}\n.min-h-8 {\n min-height: calc(var(--spacing) * 8);\n}\n.w-0\\.5 {\n width: calc(var(--spacing) * 0.5);\n}\n.w-6 {\n width: calc(var(--spacing) * 6);\n}\n.w-7 {\n width: calc(var(--spacing) * 7);\n}\n.w-8 {\n width: calc(var(--spacing) * 8);\n}\n.w-\\[min\\(360px\\,calc\\(100vw-16px\\)\\)\\] {\n width: min(360px, calc(100vw - 16px));\n}\n.w-full {\n width: 100%;\n}\n.max-w-70 {\n max-width: calc(var(--spacing) * 70);\n}\n.min-w-0 {\n min-width: 0px;\n}\n.flex-1 {\n flex: 1;\n}\n.shrink-0 {\n flex-shrink: 0;\n}\n.origin-center {\n transform-origin: center;\n}\n.-translate-x-1\\/2 {\n --tw-translate-x: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.-translate-y-1\\/2 {\n --tw-translate-y: calc(calc(1 / 2 * 100%) * -1);\n translate: var(--tw-translate-x) var(--tw-translate-y);\n}\n.cursor-grab {\n cursor: grab;\n}\n.cursor-pointer {\n cursor: pointer;\n}\n.resize {\n resize: both;\n}\n.resize-none {\n resize: none;\n}\n.appearance-none {\n appearance: none;\n}\n.grid-cols-\\[22px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 22px minmax(0,1fr);\n}\n.grid-cols-\\[82px_minmax\\(0\\,1fr\\)\\] {\n grid-template-columns: 82px minmax(0,1fr);\n}\n.flex-col {\n flex-direction: column;\n}\n.items-center {\n align-items: center;\n}\n.items-start {\n align-items: flex-start;\n}\n.justify-between {\n justify-content: space-between;\n}\n.justify-center {\n justify-content: center;\n}\n.justify-end {\n justify-content: flex-end;\n}\n.gap-0\\.5 {\n gap: calc(var(--spacing) * 0.5);\n}\n.gap-1 {\n gap: var(--spacing);\n}\n.gap-2 {\n gap: calc(var(--spacing) * 2);\n}\n.gap-px {\n gap: 1px;\n}\n.truncate {\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.overflow-auto {\n overflow: auto;\n}\n.overflow-hidden {\n overflow: hidden;\n}\n.overflow-y-hidden {\n overflow-y: hidden;\n}\n.rounded-full {\n border-radius: calc(infinity * 1px);\n}\n.rounded-lg {\n border-radius: var(--t3-radius);\n}\n.rounded-md {\n border-radius: calc(var(--t3-radius) - 2px);\n}\n.rounded-xl {\n border-radius: calc(var(--t3-radius) + 4px);\n}\n.border {\n border-style: var(--tw-border-style);\n border-width: 1px;\n}\n.border-0 {\n border-style: var(--tw-border-style);\n border-width: 0px;\n}\n.border-t {\n border-top-style: var(--tw-border-style);\n border-top-width: 1px;\n}\n.border-b {\n border-bottom-style: var(--tw-border-style);\n border-bottom-width: 1px;\n}\n.border-border {\n border-color: var(--t3-border);\n}\n.border-input {\n border-color: var(--t3-input);\n}\n.border-primary {\n border-color: var(--t3-primary);\n}\n.border-transparent {\n border-color: transparent;\n}\n.border-b-transparent {\n border-bottom-color: transparent;\n}\n.bg-background {\n background-color: var(--t3-background);\n}\n.bg-muted {\n background-color: var(--t3-muted);\n}\n.bg-muted\\/40 {\n background-color: var(--t3-muted);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-muted) 40%, transparent);\n }\n}\n.bg-popover\\/95 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 95%, transparent);\n }\n}\n.bg-popover\\/96 {\n background-color: var(--t3-popover);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-popover) 96%, transparent);\n }\n}\n.bg-primary {\n background-color: var(--t3-primary);\n}\n.bg-primary\\/10 {\n background-color: var(--t3-primary);\n @supports (color: color-mix(in lab, red, red)) {\n background-color: color-mix(in oklab, var(--t3-primary) 10%, transparent);\n }\n}\n.bg-transparent {\n background-color: transparent;\n}\n.p-0 {\n padding: 0px;\n}\n.p-1 {\n padding: var(--spacing);\n}\n.p-2 {\n padding: calc(var(--spacing) * 2);\n}\n.px-0 {\n padding-inline: 0px;\n}\n.px-1 {\n padding-inline: var(--spacing);\n}\n.px-2 {\n padding-inline: calc(var(--spacing) * 2);\n}\n.px-2\\.5 {\n padding-inline: calc(var(--spacing) * 2.5);\n}\n.px-3 {\n padding-inline: calc(var(--spacing) * 3);\n}\n.py-1 {\n padding-block: var(--spacing);\n}\n.py-1\\.5 {\n padding-block: calc(var(--spacing) * 1.5);\n}\n.py-2 {\n padding-block: calc(var(--spacing) * 2);\n}\n.pb-2 {\n padding-bottom: calc(var(--spacing) * 2);\n}\n.text-right {\n text-align: right;\n}\n.font-mono {\n font-family: var(--t3-font-mono);\n}\n.font-sans {\n font-family: var(--t3-font-sans);\n}\n.text-lg {\n font-size: var(--text-lg);\n line-height: var(--tw-leading, var(--text-lg--line-height));\n}\n.text-sm {\n font-size: var(--text-sm);\n line-height: var(--tw-leading, var(--text-sm--line-height));\n}\n.text-xs {\n font-size: var(--text-xs);\n line-height: var(--tw-leading, var(--text-xs--line-height));\n}\n.leading-5 {\n --tw-leading: calc(var(--spacing) * 5);\n line-height: calc(var(--spacing) * 5);\n}\n.font-bold {\n --tw-font-weight: var(--font-weight-bold);\n font-weight: var(--font-weight-bold);\n}\n.font-medium {\n --tw-font-weight: var(--font-weight-medium);\n font-weight: var(--font-weight-medium);\n}\n.font-semibold {\n --tw-font-weight: var(--font-weight-semibold);\n font-weight: var(--font-weight-semibold);\n}\n.text-foreground {\n color: var(--t3-foreground);\n}\n.text-muted-foreground {\n color: var(--t3-muted-foreground);\n}\n.text-popover-foreground {\n color: var(--t3-popover-foreground);\n}\n.text-primary {\n color: var(--t3-primary);\n}\n.text-primary-foreground {\n color: var(--t3-primary-foreground);\n}\n.tabular-nums {\n --tw-numeric-spacing: tabular-nums;\n font-variant-numeric: var(--tw-ordinal,) var(--tw-slashed-zero,) var(--tw-numeric-figure,) var(--tw-numeric-spacing,) var(--tw-numeric-fraction,);\n}\n.shadow {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-2xl {\n --tw-shadow: 0 25px 50px -12px var(--tw-shadow-color, rgb(0 0 0 / 0.25));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-lg {\n --tw-shadow: 0 10px 15px -3px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 4px 6px -4px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-md {\n --tw-shadow: 0 4px 6px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 2px 4px -2px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-sm {\n --tw-shadow: 0 1px 3px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.1)), 0 1px 2px -1px var(--tw-shadow-color, rgb(0 0 0 / 0.1));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.shadow-xs {\n --tw-shadow: 0 1px 2px 0 var(--tw-shadow-color, rgb(0 0 0 / 0.05));\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.ring-0 {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.blur {\n --tw-blur: blur(8px);\n filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);\n}\n.backdrop-blur-xl {\n --tw-backdrop-blur: blur(var(--blur-xl));\n -webkit-backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n backdrop-filter: var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);\n}\n.outline-none {\n --tw-outline-style: none;\n outline-style: none;\n}\n.select-none {\n -webkit-user-select: none;\n user-select: none;\n}\n.placeholder\\:text-muted-foreground::placeholder {\n color: var(--t3-muted-foreground);\n}\n@media (hover: hover) {\n .hover\\:bg-accent:hover {\n background-color: var(--t3-accent);\n }\n .hover\\:bg-primary\\/90:hover {\n background-color: var(--t3-primary);\n }\n @supports (color: color-mix(in lab, red, red)) {\n .hover\\:bg-primary\\/90:hover {\n background-color: color-mix(in oklab, var(--t3-primary) 90%, transparent);\n }\n }\n .hover\\:text-accent-foreground:hover {\n color: var(--t3-accent-foreground);\n }\n}\n.focus\\:border-b-primary:focus {\n border-bottom-color: var(--t3-primary);\n}\n.focus\\:ring-0:focus {\n --tw-ring-shadow: var(--tw-ring-inset,) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color, currentcolor);\n box-shadow: var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow);\n}\n.focus\\:outline-none:focus {\n --tw-outline-style: none;\n outline-style: none;\n}\n.disabled\\:pointer-events-none:disabled {\n pointer-events: none;\n}\n.disabled\\:opacity-60:disabled {\n opacity: 60%;\n}\n:host {\n --t3-font-sans: "DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,\n sans-serif;\n --t3-font-mono: "SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;\n --t3-radius: 0.625rem;\n --t3-background: white;\n --t3-foreground: oklch(0.269 0 0);\n --t3-popover: white;\n --t3-popover-foreground: oklch(0.269 0 0);\n --t3-primary: oklch(0.488 0.217 264);\n --t3-primary-foreground: white;\n --t3-destructive: oklch(0.577 0.245 27.325);\n --t3-muted: rgb(0 0 0 / 4%);\n --t3-muted-foreground: oklch(0.556 0 0);\n --t3-accent: rgb(0 0 0 / 4%);\n --t3-accent-foreground: oklch(0.269 0 0);\n --t3-border: rgb(0 0 0 / 8%);\n --t3-input: rgb(0 0 0 / 10%);\n --t3-ring: oklch(0.488 0.217 264);\n color: var(--t3-foreground);\n font-family: var(--t3-font-sans);\n}\n* {\n box-sizing: border-box;\n border-color: var(--t3-border);\n}\nbutton, input, select, textarea {\n font: inherit;\n}\nbutton:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible {\n outline: 2px solid var(--t3-ring);\n @supports (color: color-mix(in lab, red, red)) {\n outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);\n }\n outline-offset: -2px;\n}\n[hidden] {\n display: none !important;\n}\n@property --tw-translate-x {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-y {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-translate-z {\n syntax: "*";\n inherits: false;\n initial-value: 0;\n}\n@property --tw-border-style {\n syntax: "*";\n inherits: false;\n initial-value: solid;\n}\n@property --tw-leading {\n syntax: "*";\n inherits: false;\n}\n@property --tw-font-weight {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ordinal {\n syntax: "*";\n inherits: false;\n}\n@property --tw-slashed-zero {\n syntax: "*";\n inherits: false;\n}\n@property --tw-numeric-figure {\n syntax: "*";\n inherits: false;\n}\n@property --tw-numeric-spacing {\n syntax: "*";\n inherits: false;\n}\n@property --tw-numeric-fraction {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-inset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-inset-ring-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-inset-ring-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-ring-inset {\n syntax: "*";\n inherits: false;\n}\n@property --tw-ring-offset-width {\n syntax: "";\n inherits: false;\n initial-value: 0px;\n}\n@property --tw-ring-offset-color {\n syntax: "*";\n inherits: false;\n initial-value: #fff;\n}\n@property --tw-ring-offset-shadow {\n syntax: "*";\n inherits: false;\n initial-value: 0 0 #0000;\n}\n@property --tw-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-sepia {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-color {\n syntax: "*";\n inherits: false;\n}\n@property --tw-drop-shadow-alpha {\n syntax: "";\n inherits: false;\n initial-value: 100%;\n}\n@property --tw-drop-shadow-size {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-blur {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-brightness {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-contrast {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-grayscale {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-hue-rotate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-invert {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-opacity {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-saturate {\n syntax: "*";\n inherits: false;\n}\n@property --tw-backdrop-sepia {\n syntax: "*";\n inherits: false;\n}\n@layer properties {\n *, ::before, ::after, ::backdrop {\n --tw-translate-x: 0;\n --tw-translate-y: 0;\n --tw-translate-z: 0;\n --tw-border-style: solid;\n --tw-leading: initial;\n --tw-font-weight: initial;\n --tw-ordinal: initial;\n --tw-slashed-zero: initial;\n --tw-numeric-figure: initial;\n --tw-numeric-spacing: initial;\n --tw-numeric-fraction: initial;\n --tw-shadow: 0 0 #0000;\n --tw-shadow-color: initial;\n --tw-shadow-alpha: 100%;\n --tw-inset-shadow: 0 0 #0000;\n --tw-inset-shadow-color: initial;\n --tw-inset-shadow-alpha: 100%;\n --tw-ring-color: initial;\n --tw-ring-shadow: 0 0 #0000;\n --tw-inset-ring-color: initial;\n --tw-inset-ring-shadow: 0 0 #0000;\n --tw-ring-inset: initial;\n --tw-ring-offset-width: 0px;\n --tw-ring-offset-color: #fff;\n --tw-ring-offset-shadow: 0 0 #0000;\n --tw-blur: initial;\n --tw-brightness: initial;\n --tw-contrast: initial;\n --tw-grayscale: initial;\n --tw-hue-rotate: initial;\n --tw-invert: initial;\n --tw-opacity: initial;\n --tw-saturate: initial;\n --tw-sepia: initial;\n --tw-drop-shadow: initial;\n --tw-drop-shadow-color: initial;\n --tw-drop-shadow-alpha: 100%;\n --tw-drop-shadow-size: initial;\n --tw-backdrop-blur: initial;\n --tw-backdrop-brightness: initial;\n --tw-backdrop-contrast: initial;\n --tw-backdrop-grayscale: initial;\n --tw-backdrop-hue-rotate: initial;\n --tw-backdrop-invert: initial;\n --tw-backdrop-opacity: initial;\n --tw-backdrop-saturate: initial;\n --tw-backdrop-sepia: initial;\n }\n}\n'; diff --git a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts index 0bf95cd641c5b..e5f8665d11358 100644 --- a/apps/desktop/src/preview/BrowserImport/BrowserImport.ts +++ b/apps/desktop/src/preview/BrowserImport/BrowserImport.ts @@ -92,16 +92,25 @@ export const checkBrowserImportPolicy = Effect.fn("BrowserImport.checkPolicy")(f } }); +class BrowserCookieFlushError extends Schema.TaggedError()( + "BrowserCookieFlushError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Imported cookies could not be flushed to disk."; + } +} + export class BrowserCookieWriteError extends Schema.TaggedError()( "BrowserCookieWriteError", { url: Schema.String, - name: Schema.String, + cookieName: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { - return `Could not write imported cookie ${this.name} for ${this.url}.`; + return `Could not write imported cookie ${this.cookieName} for ${this.url}.`; } } @@ -167,7 +176,8 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* ( sameSite: cookie.sameSite, ...(cookie.expirationDate === undefined ? {} : { expirationDate: cookie.expirationDate }), }), - catch: (cause) => new BrowserCookieWriteError({ url: cookie.url, name: cookie.name, cause }), + catch: (cause) => + new BrowserCookieWriteError({ url: cookie.url, cookieName: cookie.name, cause }), }).pipe( Effect.as(true), Effect.tapError((error) => Effect.logDebug(error.message, { cause: error.cause })), @@ -182,7 +192,10 @@ export const writeCookies = Effect.fn("BrowserImport.writeCookies")(function* ( } // Cookie writes settle in memory; flush to disk before reporting a durable import. if (imported > 0) { - yield* Effect.tryPromise(() => session.cookies.flushStore()).pipe( + yield* Effect.tryPromise({ + try: () => session.cookies.flushStore(), + catch: (cause) => new BrowserCookieFlushError({ cause }), + }).pipe( Effect.tapError((error) => Effect.logWarning("Imported cookies could not be flushed to disk", { cause: error.cause }), ), diff --git a/apps/desktop/src/preview/BrowserImport/Sources.test.ts b/apps/desktop/src/preview/BrowserImport/Sources.test.ts index 898d94221b8d4..720a57e64a9dc 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.test.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.test.ts @@ -199,6 +199,51 @@ describe("chromiumProcessIsAlive", () => { }); describe("isSourceInstalled", () => { + it.effect.each([undefined, "", "relative-config", "relocated", "chrome-override"])( + "discovers Linux Chromium profiles with XDG_CONFIG_HOME=%s", + (configHome) => + run( + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-sources-xdg-" }); + const xdgConfigHome = + configHome === "relocated" || configHome === "chrome-override" + ? path.join(home, "config") + : configHome; + const chromeConfigHome = + configHome === "chrome-override" ? path.join(home, ".config") : undefined; + const context = yield* sourcePathContext.pipe( + Effect.provideService(HostProcess.Environment, { + HOME: home, + XDG_CONFIG_HOME: xdgConfigHome, + CHROME_CONFIG_HOME: chromeConfigHome, + }), + Effect.provideService(HostProcess.Platform, "linux"), + ); + const configRoot = + chromeConfigHome ?? + (configHome === "relocated" ? path.join(home, "config") : path.join(home, ".config")); + const source = BROWSER_IMPORT_SOURCES.find((source) => source.id === "chrome")!; + const root = path.join(configRoot, "google-chrome"); + const database = path.join(root, "Default", "Network", "Cookies"); + assert.isFalse(yield* isSourceInstalled(source, context)); + yield* fileSystem.makeDirectory(path.dirname(database), { recursive: true }); + yield* writeCookieDatabase(database, 2); + yield* fileSystem.writeFileString( + path.join(root, "Local State"), + '{"profile":{"info_cache":{"Default":{"name":"Fixture"}}}}', + ); + + assert.isTrue(yield* isSourceInstalled(source, context)); + assert.deepEqual(yield* listSourceProfiles(source, context), [ + { directory: "Default", name: "Fixture", cookieCount: 2 }, + ]); + assert.equal(yield* resolveCookieDatabase(source, context, "Default"), database); + }), + ), + ); + it.effect("ignores a user-data directory that holds no cookie database", () => run( Effect.gen(function* () { @@ -325,13 +370,18 @@ describe("Zen", () => { run( Effect.gen(function* () { const darwinContext = yield* sourcePathContext.pipe( - Effect.provideService(HostProcess.Environment, { HOME: "/Users/zen-user" }), + Effect.provideService(HostProcess.Environment, { + HOME: "/Users/zen-user", + XDG_CONFIG_HOME: "/custom-config", + }), Effect.provideService(HostProcess.Platform, "darwin"), ); const windowsContext = yield* sourcePathContext.pipe( Effect.provideService(HostProcess.Environment, { HOME: "C:\\Users\\zen-user", APPDATA: "C:\\Users\\zen-user\\AppData\\Roaming", + LOCALAPPDATA: "C:\\Users\\zen-user\\AppData\\Local", + XDG_CONFIG_HOME: "/custom-config", }), Effect.provideService(HostProcess.Platform, "win32"), ); @@ -359,6 +409,24 @@ describe("Zen", () => { linuxContext.path.join("/home/zen-user", ".zen"), linuxContext.path.join("/home/zen-user", ".var", "app", "app.zen_browser.zen", "zen"), ]); + assert.equal( + helium.userDataDirectory(darwinContext), + darwinContext.path.join( + "/Users/zen-user", + "Library", + "Application Support", + "net.imput.helium", + ), + ); + assert.equal( + helium.userDataDirectory(windowsContext), + windowsContext.path.join( + "C:\\Users\\zen-user\\AppData\\Local", + "imput", + "Helium", + "User Data", + ), + ); }), ), ); @@ -415,16 +483,19 @@ describe("Zen", () => { ), ); - it.effect("discovers Zen profiles in both current and legacy Linux roots", () => + it.effect("discovers Zen profiles in relocated and legacy Linux roots", () => run( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-zen-linux-" }); const context = yield* sourcePathContext.pipe( - Effect.provideService(HostProcess.Environment, { HOME: home }), + Effect.provideService(HostProcess.Environment, { + HOME: home, + XDG_CONFIG_HOME: NodePath.join(home, "config"), + }), Effect.provideService(HostProcess.Platform, "linux"), ); - const currentRoot = context.path.join(home, ".config", "zen"); + const currentRoot = context.path.join(home, "config", "zen"); const legacyRoot = context.path.join(home, ".zen"); const currentProfile = context.path.join(currentRoot, "current.default"); const legacyProfile = context.path.join(legacyRoot, "legacy.default"); diff --git a/apps/desktop/src/preview/BrowserImport/Sources.ts b/apps/desktop/src/preview/BrowserImport/Sources.ts index 3f94269bfe273..20a35752ed979 100644 --- a/apps/desktop/src/preview/BrowserImport/Sources.ts +++ b/apps/desktop/src/preview/BrowserImport/Sources.ts @@ -16,6 +16,8 @@ export interface BrowserImportPathContext { readonly path: Path.Path; readonly platform: NodeJS.Platform; readonly home: string; + readonly linuxConfigHome: string; + readonly linuxChromeConfigHome: string; readonly appData: string | undefined; readonly localAppData: string | undefined; } @@ -68,7 +70,10 @@ const chromiumSource = (input: { : undefined; } return input.linuxSegments - ? context.path.join(context.home, ".config", ...input.linuxSegments) + ? context.path.join( + input.id === "chrome" ? context.linuxChromeConfigHome : context.linuxConfigHome, + ...input.linuxSegments, + ) : undefined; }, }); @@ -185,7 +190,7 @@ export const BROWSER_IMPORT_SOURCES: ReadonlyArray [ context.path.join(context.home, ".zen"), @@ -292,10 +297,18 @@ export const sourcePathContext = Effect.gen(function* () { const path = yield* Path.Path; const platform = yield* HostProcess.Platform; const environment = yield* HostProcess.Environment; + const home = environment.HOME ?? environment.USERPROFILE ?? ""; + const xdgConfigHome = environment.XDG_CONFIG_HOME; + const linuxConfigHome = + xdgConfigHome && path.isAbsolute(xdgConfigHome) ? xdgConfigHome : path.join(home, ".config"); + const chromeConfigHome = environment.CHROME_CONFIG_HOME; return { path, platform, - home: environment.HOME ?? environment.USERPROFILE ?? "", + home, + linuxConfigHome, + linuxChromeConfigHome: + chromeConfigHome && path.isAbsolute(chromeConfigHome) ? chromeConfigHome : linuxConfigHome, appData: environment.APPDATA, localAppData: environment.LOCALAPPDATA, } satisfies BrowserImportPathContext; diff --git a/apps/desktop/src/preview/BrowserSession.test.ts b/apps/desktop/src/preview/BrowserSession.test.ts index 7a339102f19a6..e68e52961fa60 100644 --- a/apps/desktop/src/preview/BrowserSession.test.ts +++ b/apps/desktop/src/preview/BrowserSession.test.ts @@ -16,6 +16,7 @@ const { fromPartition, sessions } = vi.hoisted(() => ({ readonly setPermissionRequestHandler: ReturnType; readonly setPermissionCheckHandler: ReturnType; readonly setUserAgent: ReturnType; + readonly webRequest: { readonly onBeforeSendHeaders: ReturnType }; } >(), })); @@ -62,6 +63,7 @@ describe("BrowserSession", () => { setPermissionRequestHandler: vi.fn(), setPermissionCheckHandler: vi.fn(), setUserAgent: vi.fn(), + webRequest: { onBeforeSendHeaders: vi.fn() }, }; sessions.set(partition, browserSession); return browserSession; @@ -115,10 +117,12 @@ describe("BrowserSession", () => { }).pipe(Effect.provide(layer)), ); - it.effect("keeps the guest's effective User-Agent equal to Electron's native one", () => + it.effect("keeps the native User-Agent except for the Electron token sent to Teams", () => Effect.gen(function* () { const nativeUserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) T3Code(Alpha)/0.0.33 Chrome/146.0.7680.216 Electron/41.5.0 Safari/537.36"; + const teamsUserAgent = + "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) T3Code(Alpha)/0.0.33 Chrome/146.0.7680.216 Safari/537.36"; fromPartition.mockReset(); fromPartition.mockImplementation((partition: string) => { let userAgent = nativeUserAgent; @@ -131,6 +135,7 @@ describe("BrowserSession", () => { setUserAgent: vi.fn((next: string) => { userAgent = next; }), + webRequest: { onBeforeSendHeaders: vi.fn() }, }; sessions.set(partition, browserSession); return browserSession; @@ -143,6 +148,29 @@ describe("BrowserSession", () => { const browserSession = sessions.get(partition); assert.isDefined(browserSession); assert.strictEqual(browserSession.getUserAgent(), nativeUserAgent); + + // Teams redirects Electron to an error page before sign-in; every other host sees the native one. + const calls = browserSession.webRequest.onBeforeSendHeaders.mock.calls; + assert.strictEqual(calls.length, 1); + const [filter, listener] = calls[0] ?? []; + assert.deepStrictEqual(filter, { + urls: ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"], + }); + const send = (requestHeaders: Record) => { + let response: { requestHeaders?: Record } | undefined; + listener({ requestHeaders }, (next: typeof response) => { + response = next; + }); + return response; + }; + for (const key of ["User-Agent", "user-agent"]) { + const requestHeaders = { [key]: nativeUserAgent, Accept: "*/*" }; + assert.deepStrictEqual(send(requestHeaders), { + requestHeaders: { [key]: teamsUserAgent, Accept: "*/*" }, + }); + assert.strictEqual(requestHeaders[key], nativeUserAgent); + } + assert.deepStrictEqual(send({ Accept: "*/*" }), {}); }).pipe(Effect.provide(layer)), ); diff --git a/apps/desktop/src/preview/BrowserSession.ts b/apps/desktop/src/preview/BrowserSession.ts index a780cacf11ea9..b2523ba62b973 100644 --- a/apps/desktop/src/preview/BrowserSession.ts +++ b/apps/desktop/src/preview/BrowserSession.ts @@ -55,6 +55,9 @@ const externalProtocolPromptUrl = (rawUrl: string | undefined): string | null => } }; +// Teams sends Electron User-Agents to an error page before sign-in. Electron allows one listener per session. +const TEAMS_URL_PATTERNS = ["https://teams.cloud.microsoft/*", "https://teams.microsoft.com/*"]; + const MAX_PROMPT_URL_LENGTH = 300; const truncateForPrompt = (text: string): string => @@ -342,6 +345,22 @@ export const make = Effect.gen(function* BrowserSessionMake() { ? clipboardReadDecisions.get(permissionOrigin(requestingOrigin) ?? "") === true : ALLOWED_PREVIEW_PERMISSIONS.has(permission), ); + browserSession.webRequest.onBeforeSendHeaders( + { urls: TEAMS_URL_PATTERNS }, + ({ requestHeaders }, callback) => { + const userAgent = Object.entries(requestHeaders).find( + ([name]) => name.toLowerCase() === "user-agent", + ); + if (userAgent === undefined) { + callback({}); + return; + } + const [name, value] = userAgent; + callback({ + requestHeaders: { ...requestHeaders, [name]: value.replace(/ Electron\/\S+/, "") }, + }); + }, + ); const next = new Map(sessions); next.set(partition, browserSession); return [browserSession, next] as const; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 2e6e54a5293a7..b2a3886f87668 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -144,6 +144,44 @@ describe("DesktopBrowserHost", () => { }), ); + it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + host.attach(key, makeDebuggee().tab); + host.setShown(key, true); + const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped); + + yield* Effect.yieldNow; + host.detach(key); + host.attach(key, makeDebuggee().tab); + + expect(yield* Fiber.join(reader)).toEqual([ + { type: "attached", ...key }, + { type: "shown", ...key, shown: true }, + { type: "detached", ...key }, + { type: "attached", ...key }, + { type: "shown", ...key, shown: true }, + ]); + }), + ); + + it.effect("replays an explicit hidden report before announcing another tab", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const other = { ...key, tabId: "tab-2" }; + host.setShown(key, false); + host.attach(key, makeDebuggee().tab); + host.setShown(other, true); + host.attach(other, makeDebuggee().tab); + + expect(yield* takeEvents(host, 3)).toEqual([ + { type: "attached", ...key }, + { type: "shown", ...key, shown: false }, + { type: "attached", ...other }, + ]); + }), + ); + it.effect("drops replies from a relay the server released", () => Effect.gen(function* () { const host = yield* DesktopBrowserHost.make; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index 3ac6c6d73caec..80a23417b7163 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -87,6 +87,7 @@ export class DesktopBrowserHost extends Context.Service< readonly handleCommandLine: (line: string) => Effect.Effect; readonly attach: (key: DesktopBrowserTabKey, debuggee: DesktopBrowserTabDebugger) => void; readonly detach: (key: DesktopBrowserTabKey) => void; + readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void; readonly humanStartedDownload: (source: Electron.WebContents) => boolean; readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean; readonly pointers: Stream.Stream<{ @@ -119,6 +120,9 @@ export const make = Effect.gen(function* () { const tabs = new Map(); /** Threads whose agent turn runs, by the server's account. */ const agentTurns = new Set(); + // Kept apart from attachment: the renderer can show a webview before its debugger attaches, + // and the server forgets `shown` on detach, for example while DevTools holds the debugger. + const shownTabs = new Map(); const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event)); const nextScreenshot = (tab: AttachedTab) => { @@ -456,6 +460,19 @@ export const make = Effect.gen(function* () { debuggee.debugger.on("message", tab.onMessage); debuggee.webContents.on("did-navigate", tab.onNewDocument); emit({ type: "attached", ...key }); + const shown = shownTabs.get(id); + if (shown !== undefined) emit({ type: "shown", ...key, shown }); + }; + + const setShown = (key: DesktopBrowserTabKey, shown: boolean | undefined) => { + const id = keyOf(key); + if (shown === undefined) { + shownTabs.delete(id); + return; + } + if (shownTabs.get(id) === shown) return; + shownTabs.set(id, shown); + if (tabs.has(id)) emit({ type: "shown", ...key, shown }); }; const handleCommandLine = (line: string) => @@ -494,7 +511,14 @@ export const make = Effect.gen(function* () { [...tabs.values()], (tab) => { dropRelay(tab); - return PubSub.publish(outbox, { type: "attached", ...tab.key }); + const shown = shownTabs.get(keyOf(tab.key)); + return PubSub.publish(outbox, { type: "attached", ...tab.key }).pipe( + Effect.andThen( + shown !== undefined + ? PubSub.publish(outbox, { type: "shown", ...tab.key, shown }) + : Effect.void, + ), + ); }, { discard: true }, ); @@ -514,6 +538,7 @@ export const make = Effect.gen(function* () { handleCommandLine, attach, detach, + setShown, placeDownload, humanStartedDownload, }); diff --git a/apps/desktop/src/preview/GuestProtocol.ts b/apps/desktop/src/preview/GuestProtocol.ts index 29011a3db7e01..a4fd88c475bca 100644 --- a/apps/desktop/src/preview/GuestProtocol.ts +++ b/apps/desktop/src/preview/GuestProtocol.ts @@ -14,3 +14,5 @@ export const RECORDING_CONTROLLER_CHANNEL = "preview:recording-controller"; export const PASSKEY_CREATE_CHANNEL = "preview:passkey-create"; export const PASSKEY_GET_CHANNEL = "preview:passkey-get"; export const PASSKEY_BRIDGE_ARGUMENT = "--t3code-preview-passkey-bridge"; +export const ANNOTATION_VOICE_EVENT_CHANNEL = "preview:annotation-voice-event"; +export const ANNOTATION_VOICE_STATE_CHANNEL = "preview:annotation-voice-state"; diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 32b9ad23f9c93..b4e4b2a8b75ce 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -1,5 +1,6 @@ import { it as effectIt } from "@effect/vitest"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import type { DesktopPreviewRecordingInputEvent, PreviewAnnotationPayload, @@ -7,6 +8,7 @@ import type { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { parseKeybindingShortcut } from "@t3tools/shared/keybindings"; +import { app, shell } from "electron"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -169,6 +171,7 @@ const { })); vi.mock("electron", () => ({ + app: { getPath: vi.fn() }, BrowserWindow: browserWindowConstructor, // oxlint-disable-next-line typescript/no-extraneous-class -- This constructor-only mock implements the browser ClipboardItem API. ClipboardItem: class { @@ -571,6 +574,103 @@ describe("PreviewManager", () => { webviewSend.mockClear(); }); + effectIt.effect.each([false, true])( + "preserves simultaneous same-name downloads with an existing destination: %s", + (existing) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-download-test-" }); + const downloads = `${dir}/downloads`; + yield* fs.makeDirectory(downloads); + using _downloads = vi.spyOn(app, "getPath").mockReturnValue(downloads); + if (existing) yield* fs.writeFileString(`${downloads}/report.txt`, "existing download"); + const sources = [`${dir}/first`, `${dir}/second`]; + yield* fs.writeFileString(sources[0]!, "first download"); + yield* fs.writeFileString(sources[1]!, "second download"); + const checked = yield* Deferred.make(); + const finished = makeChangeSignal(); + let probes = 0; + let completions = 0; + using _reveal = vi.spyOn(shell, "showItemInFolder").mockImplementation(() => { + completions += 1; + finished.notify(); + }); + const raceTarget = `${downloads}/${existing ? "report (1).txt" : "report.txt"}`; + const exists = (target: string) => + Effect.gen(function* () { + const found = yield* fs.exists(target); + if (target === raceTarget) { + if (++probes === 2) yield* Deferred.succeed(checked, undefined); + yield* Deferred.await(checked); + } + return found; + }); + const manager = yield* PreviewManager.make.pipe( + Effect.provideService(FileSystem.FileSystem, { ...fs, exists }), + Effect.provide( + Layer.mergeAll( + layerEnvironment, + layerBrowserSession, + Layer.mock(DesktopBrowserHost.DesktopBrowserHost)({ + attach: () => {}, + detach: () => {}, + setShown: () => {}, + humanStartedDownload: () => true, + placeDownload: () => true, + }), + Layer.mock(PreviewPasskeys.PreviewPasskeys)({ + bridgeEnabled: false, + installSessionHandlers: () => {}, + attachGuest: () => () => {}, + }), + Layer.mock(DesktopRendererHistory.DesktopRendererHistory)({}), + Layer.succeed(HostProcess.Platform, "linux"), + ), + ), + ); + yield* manager.getBrowserSession("downloads"); + const listener = previewSession.on.mock.calls[0]![1] as ( + event: unknown, + item: { + once: (event: string, done: (event: unknown, state: string) => void) => void; + getFilename: () => string; + getSavePath: () => string; + }, + source: unknown, + ) => void; + for (const source of sources) { + listener( + {}, + { + once: (_event, done) => done({}, "completed"), + getFilename: () => "report.txt", + getSavePath: () => source, + }, + {}, + ); + } + yield* finished.until(() => completions === 2); + const names = yield* fs.readDirectory(downloads); + expect(names.toSorted()).toEqual( + existing + ? ["report (1).txt", "report (2).txt", "report.txt"] + : ["report (1).txt", "report.txt"], + ); + const contents = yield* Effect.forEach(names, (name) => + fs.readFileString(`${downloads}/${name}`), + ); + expect(contents.toSorted()).toEqual( + (existing + ? ["existing download", "first download", "second download"] + : ["first download", "second download"] + ).toSorted(), + ); + if (existing) { + expect(yield* fs.readFileString(`${downloads}/report.txt`)).toBe("existing download"); + } + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), Effect.scoped), + ); + effectIt.effect.each([ ["linux", "ctrl+alt+[", "[", "BracketLeft", false], ["win32", "ctrl+alt+8", "[", "Digit8", false], @@ -824,6 +924,53 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("treats a load superseded by a page redirect as a successful navigation", () => + withManager((manager) => + Effect.gen(function* () { + // Same shape Electron's loadURL rejects with in lib/browser/api/web-contents.ts. + const loadError = (errno: number, code: string, url: string) => + Object.assign(new Error(`${code} (${errno}) loading '${url}'`), { errno, code, url }); + const preview = makeFaviconWebContents(); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_redirect"); + yield* manager.registerWebview("tab_redirect", 42); + + preview.loadURL.mockRejectedValueOnce( + loadError(-3, "ERR_ABORTED", "https://example.com/target"), + ); + yield* manager.navigate("tab_redirect", "https://example.com/"); + + preview.loadURL.mockRejectedValueOnce( + loadError(-3, "ERR_ABORTED", "https://example.com/reload"), + ); + yield* manager.navigate("tab_redirect", "https://example.com/reload"); + + preview.loadURL.mockImplementationOnce(async () => { + preview.listeners.get("will-prevent-unload")?.(); + throw loadError(-3, "ERR_ABORTED", "https://example.com/blocked"); + }); + const blocked = yield* Effect.exit( + manager.navigate("tab_redirect", "https://example.com/blocked"), + ); + expect(Exit.isFailure(blocked)).toBe(true); + + preview.loadURL.mockRejectedValueOnce( + loadError(-105, "ERR_NAME_NOT_RESOLVED", "https://missing.invalid/"), + ); + const failed = yield* Effect.exit( + manager.navigate("tab_redirect", "https://missing.invalid/"), + ); + expect(Exit.isFailure(failed)).toBe(true); + if (Exit.isSuccess(failed)) return; + expect(Option.getOrThrow(Cause.findErrorOption(failed.cause))).toMatchObject({ + _tag: "PreviewOperationError", + operation: "navigate.loadURL", + cause: { errno: -105 }, + }); + }), + ), + ); + effectIt.effect("detaches through the pinned debugger after the webview is destroyed", () => withManager((manager) => Effect.gen(function* () { @@ -2443,6 +2590,70 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("delivers annotation voice state only to the pick session that owns it", () => + withManager((manager) => + Effect.gen(function* () { + const firstReady = yield* Deferred.make(); + const secondReady = yield* Deferred.make(); + let registrations = 0; + const guest = { + ...makeTestPreviewWebContents(async () => ({ + toPNG: () => Buffer.from("unused"), + toJPEG: () => Buffer.from("unused"), + getSize: () => ({ width: 1, height: 1 }), + })), + isFocused: () => true, + focus: vi.fn(), + send: (channel: string, ...args: unknown[]) => { + webviewSend(channel, ...args); + if (channel === "preview:start-pick") + Deferred.doneUnsafe(registrations++ === 0 ? firstReady : secondReady, Effect.void); + }, + once: vi.fn(), + ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, + }; + fromId.mockReturnValue(guest as never); + yield* manager.createTab("tab_1"); + yield* manager.registerWebview("tab_1", 42); + const first = yield* manager + .pickElement("tab_1", { sessionId: "first", shortcuts: [] }) + .pipe(Effect.forkChild); + yield* Deferred.await(firstReady); + const state = { + tabId: "tab_1", + sessionId: "first", + available: true, + phase: "recording" as const, + status: "Recording", + errorAction: null, + preview: null, + freezesEditor: true, + blocksSubmission: true, + level: 0, + shortcutLabel: "Ctrl+D", + draft: { text: "Tighten spacing", cursor: 15 }, + }; + yield* manager.updateAnnotationVoice(state); + expect(webviewSend).toHaveBeenCalledWith("preview:annotation-voice-state", state); + const second = yield* manager + .pickElement("tab_1", { sessionId: "second", shortcuts: [] }) + .pipe(Effect.forkChild); + yield* Deferred.await(secondReady); + expect(yield* Fiber.join(first)).toBeNull(); + webviewSend.mockClear(); + yield* manager.updateAnnotationVoice(state); + expect(webviewSend).not.toHaveBeenCalled(); + yield* manager.updateAnnotationVoice({ ...state, sessionId: "second" }); + expect(webviewSend).toHaveBeenCalledOnce(); + yield* manager.cancelPickElement("tab_1"); + expect(yield* Fiber.join(second)).toBeNull(); + webviewSend.mockClear(); + yield* manager.updateAnnotationVoice({ ...state, sessionId: "second" }); + expect(webviewSend).not.toHaveBeenCalled(); + }), + ), + ); + effectIt.effect("keeps annotation send grants isolated and updates an active pick", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 18eb4b2b75968..c668c39061e00 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -1,10 +1,15 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- FileSystem.copyFile cannot request an exclusive copy. +import * as NodeFSP from "node:fs/promises"; import * as NodeZlib from "node:zlib"; import { + DesktopPreviewAnnotationVoiceEventSchema, DesktopPreviewRecordingInputSchema, DESKTOP_PREVIEW_RECORDING_CAPTURE_TRIGGER, } from "@t3tools/contracts"; import type { DesktopPreviewAnnotationTheme, + DesktopPreviewAnnotationVoiceConfig, + DesktopPreviewAnnotationVoiceState, DesktopPreviewColorScheme, DesktopPreviewFavicon, DesktopPreviewOpenLinkEvent, @@ -45,6 +50,7 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Predicate from "effect/Predicate"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; @@ -56,13 +62,19 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; -import { MENU_ACTION_CHANNEL, PREVIEW_PICTURE_IN_PICTURE_FRAME_CHANNEL } from "../ipc/channels.ts"; +import { + MENU_ACTION_CHANNEL, + PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL, + PREVIEW_PICTURE_IN_PICTURE_FRAME_CHANNEL, +} from "../ipc/channels.ts"; import * as DesktopBrowserHost from "./DesktopBrowserHost.ts"; import * as PreviewPasskeys from "./Passkeys.ts"; import * as BrowserSession from "./BrowserSession.ts"; import { ANNOTATION_CAPTURED_CHANNEL, ANNOTATION_SEND_ENABLED_CHANNEL, + ANNOTATION_VOICE_EVENT_CHANNEL, + ANNOTATION_VOICE_STATE_CHANNEL, ANNOTATION_THEME_CHANNEL, CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, @@ -396,9 +408,14 @@ interface PendingRecording { } interface PickSession { + readonly voiceSessionId?: string | undefined; readonly cancel: Effect.Effect; } +const decodeAnnotationVoiceEvent = Schema.decodeUnknownOption( + DesktopPreviewAnnotationVoiceEventSchema, +); + interface BrowserControlSession { readonly webContentsId: number; // Retain the attached Debugger to prevent GC crashes (electron/electron#53376); wc.debugger throws after destruction. @@ -1685,6 +1702,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); if (Option.isNone(tab)) return; const closedTab = tab.value; + if (closedTab.serverTab) browserHost.setShown(closedTab.serverTab, undefined); if (closedTab.webContentsId != null) { yield* Effect.all( [ @@ -1893,6 +1911,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* rendererHistory.register(wc, { surface: "preview" }); const webContentsId = wc.id; wc.once("destroyed", () => { + runFork(hideDestroyedGuest(webContentsId)); runFork(detachControlSession(webContentsId)); }); yield* ensureControlSession(wc).pipe( @@ -1993,8 +2012,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); return; } - yield* attemptPromise({ operation: "navigate.loadURL", tabId, webContentsId: wc.id }, () => - wc.loadURL(url), + let unloadPrevented = false; + const onPreventUnload = () => { + unloadPrevented = true; + }; + yield* attemptPromise({ operation: "navigate.loadURL", tabId, webContentsId: wc.id }, () => { + wc.on("will-prevent-unload", onPreventUnload); + return wc.loadURL(url); + }).pipe( + // Blocked unloads and superseding navigations both reject with ERR_ABORTED. + Effect.catchIf( + (error) => + !unloadPrevented && + Predicate.hasProperty(error.cause, "errno") && + error.cause.errno === -3, + () => Effect.void, + ), + Effect.ensuring(Effect.sync(() => wc.off("will-prevent-unload", onPreventUnload))), ); }); @@ -2072,16 +2106,35 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); }); - const pickElement = Effect.fn("PreviewManager.pickElement")(function* (tabId: string) { + // Voice state reaches a guest only while its pick session, by id, still owns the tab. + const updateAnnotationVoice = Effect.fn("PreviewManager.updateAnnotationVoice")(function* ( + state: DesktopPreviewAnnotationVoiceState, + ) { + const sessions = yield* Ref.get(pickSessionsRef); + if (sessions.get(state.tabId)?.voiceSessionId !== state.sessionId) return; + const wc = yield* requireWebContents(state.tabId); + yield* attempt({ operation: "annotationVoice.update", tabId: state.tabId }, () => + wc.send(ANNOTATION_VOICE_STATE_CHANNEL, state), + ); + }); + + const pickElement = Effect.fn("PreviewManager.pickElement")(function* ( + tabId: string, + voice?: DesktopPreviewAnnotationVoiceConfig, + ) { const wc = yield* requireWebContents(tabId); yield* cancelPickElement(tabId); const annotationTheme = yield* Ref.get(annotationThemeRef); return yield* Effect.callback( (resume) => { - const session: PickSession = { cancel: Effect.suspend(() => cancelPickSession()) }; + const session: PickSession = { + voiceSessionId: voice?.sessionId, + cancel: Effect.suspend(() => cancelPickSession()), + }; const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () { yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => { wc.ipc.removeListener(ELEMENT_PICKED_CHANNEL, onMessage); + wc.ipc.removeListener(ANNOTATION_VOICE_EVENT_CHANNEL, onVoiceEvent); wc.off("destroyed", onDestroyed); wc.off("did-start-navigation", onNavigated); }).pipe(Effect.ignore); @@ -2189,6 +2242,25 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ), ); }; + // Only this guest's listener sees these; the renderer still checks the session id. + const onVoiceEvent = (_event: Electron.IpcMainEvent, value: unknown) => { + const decoded = decodeAnnotationVoiceEvent(value); + if (settled || !voice || Option.isNone(decoded)) return; + if (decoded.value.sessionId !== voice.sessionId) return; + runFork( + Effect.gen(function* () { + const window = yield* Ref.get(mainWindowRef); + if (Option.isNone(window) || window.value.isDestroyed()) return; + yield* attempt({ operation: "annotationVoice.forward", tabId }, () => + window.value.webContents.send( + PREVIEW_ANNOTATION_VOICE_EVENT_CHANNEL, + tabId, + decoded.value, + ), + ).pipe(Effect.ignore); + }), + ); + }; const onDestroyed = () => settle(null); const onNavigated = ( event: Electron.Event, @@ -2208,10 +2280,16 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (settled) return; yield* attempt({ operation: "pickElement.register", tabId, webContentsId: wc.id }, () => { wc.ipc.on(ELEMENT_PICKED_CHANNEL, onMessage); + if (voice) wc.ipc.on(ANNOTATION_VOICE_EVENT_CHANNEL, onVoiceEvent); wc.once("destroyed", onDestroyed); wc.on("did-start-navigation", onNavigated); if (!wc.isFocused()) wc.focus(); - wc.send(START_PICK_CHANNEL, annotationTheme, annotationSendEnabled.get(tabId) === true); + wc.send( + START_PICK_CHANNEL, + annotationTheme, + annotationSendEnabled.get(tabId) === true, + voice, + ); }); }); runFork( @@ -2346,6 +2424,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function yield* applyColorScheme(tabId, wc, colorScheme); }); + const setShown = Effect.fn("PreviewManager.setShown")(function* (tabId: string, shown: boolean) { + const serverTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.serverTab; + if (serverTab) browserHost.setShown(serverTab, shown); + }); + + // A window reload or guest crash destroys the guest without the renderer reporting it hidden. + // The renderer reports again once a new guest registers. + const hideDestroyedGuest = Effect.fnUntraced(function* (webContentsId: number) { + for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) { + if (tab.webContentsId === webContentsId && tab.serverTab) { + browserHost.setShown(tab.serverTab, false); + } + } + }); + const setAudioMuted = Effect.fn("PreviewManager.setAudioMuted")(function* ( tabId: string, audioMuted: boolean, @@ -3295,6 +3388,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function openPictureInPicture, openDevTools, pickElement, + updateAnnotationVoice, prepareWebview, reapplyZoom, refresh, @@ -3307,6 +3401,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setAnnotationTheme, setAnnotationSendEnabled, setAudioMuted, + setShown, setColorScheme, setMainWindow, setForwardedShortcuts: (shortcuts: ReadonlyArray) => @@ -3512,6 +3607,7 @@ export class PreviewManager extends Context.Service< tabId: string, audioMuted: boolean, ) => Effect.Effect; + readonly setShown: (tabId: string, shown: boolean) => Effect.Effect; readonly openDevTools: (tabId: string) => Effect.Effect; readonly clearCookies: ( partitions?: ReadonlyArray, @@ -3533,7 +3629,11 @@ export class PreviewManager extends Context.Service< ) => Effect.Effect; readonly pickElement: ( tabId: string, + voice?: DesktopPreviewAnnotationVoiceConfig, ) => Effect.Effect; + readonly updateAnnotationVoice: ( + state: DesktopPreviewAnnotationVoiceState, + ) => Effect.Effect; readonly cancelPickElement: (tabId: string) => Effect.Effect; readonly captureScreenshot: ( tabId: string, @@ -3588,7 +3688,18 @@ export const make = Effect.gen(function* PreviewManagerMake() { attempt === 0 ? `${stem}${extension}` : `${stem} (${attempt})${extension}`, ); if (yield* fileSystem.exists(target)) continue; - yield* fileSystem.copyFile(source, target); + const copied = yield* Effect.tryPromise({ + try: () => NodeFSP.copyFile(source, target, NodeFSP.constants.COPYFILE_EXCL), + catch: (cause) => new PreviewOperationError({ operation: "copyToDownloads", cause }), + }).pipe( + Effect.as(true), + Effect.catchIf( + (error) => + error.cause instanceof Error && "code" in error.cause && error.cause.code === "EEXIST", + () => Effect.succeed(false), + ), + ); + if (!copied) continue; shell.showItemInFolder(target); return; } @@ -3652,6 +3763,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { setColorScheme: operations.setColorScheme, setZoomFactor: operations.setZoomFactor, setAudioMuted: operations.setAudioMuted, + setShown: operations.setShown, openDevTools: operations.openDevTools, clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) { yield* browserSession @@ -3683,6 +3795,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { setAnnotationTheme: operations.setAnnotationTheme, setAnnotationSendEnabled: operations.setAnnotationSendEnabled, pickElement: operations.pickElement, + updateAnnotationVoice: operations.updateAnnotationVoice, cancelPickElement: operations.cancelPickElement, captureScreenshot: operations.captureScreenshot, revealArtifact: operations.revealArtifact, diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 4cb5987cdeb85..dcb16b851dc23 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -1,8 +1,12 @@ // @effect-diagnostics globalDate:off globalTimers:off - This isolated Electron preload does not run inside an Effect runtime. import { ipcRenderer } from "electron"; import { getElementContext } from "react-grab/primitives"; +import { matchesKeybindingShortcut } from "@t3tools/shared/keybindingMatching"; import type { DesktopPreviewAnnotationTheme, + DesktopPreviewAnnotationVoiceConfig, + DesktopPreviewAnnotationVoiceEvent, + DesktopPreviewAnnotationVoiceState, PickedElementPayload, PickedElementStackFrame, PreviewAnnotationPayload, @@ -23,6 +27,8 @@ import { ANNOTATION_CAPTURED_CHANNEL, ANNOTATION_SEND_ENABLED_CHANNEL, ANNOTATION_THEME_CHANNEL, + ANNOTATION_VOICE_EVENT_CHANNEL, + ANNOTATION_VOICE_STATE_CHANNEL, CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, @@ -43,6 +49,16 @@ const MAX_MARQUEE_ELEMENTS = 20; const ELEMENT_CONTEXT_TIMEOUT_MS = 5_000; const CONTENT_LAYER_Z_INDEX = 1; const CHROME_LAYER_Z_INDEX = 10; +// Page dialogs (Radix, react-remove-scroll) dismiss, refocus or block scrolling on document events +// that shadow retargeting attributes to the overlay host. +const PAGE_ISOLATED_EVENTS = [ + "pointerdown", + "focusin", + "focusout", + "wheel", + "touchstart", + "touchmove", +] as const; let recordingCursor: ReturnType | null = null; ipcRenderer.on( @@ -524,7 +540,10 @@ function strokeBounds( return { x: left, y: top, width: right - left, height: bottom - top }; } -function startAnnotation(sendEnabled: boolean): void { +function startAnnotation( + sendEnabled: boolean, + voice: DesktopPreviewAnnotationVoiceConfig | undefined, +): void { activeSession?.teardown(false); let finished = false; const host = document.createElement("div"); @@ -595,6 +614,225 @@ function startAnnotation(sendEnabled: boolean): void { "min-h-8 max-h-24 min-w-0 flex-1 resize-none overflow-y-hidden border-0 border-b border-b-transparent bg-transparent px-0 py-1.5 font-sans text-sm leading-5 text-foreground outline-none ring-0 placeholder:text-muted-foreground focus:border-b-primary focus:outline-none focus:ring-0"; composerRow.appendChild(comment); + // Recording happens in the application renderer, which owns the microphone consent. + // This guest only draws the controls, forwards trusted gestures, and mirrors state. + let voicePhase: DesktopPreviewAnnotationVoiceState["phase"] = "idle"; + let voiceSettings = false; + let voiceBusy = false; + let voiceAvailable = false; + let voiceKeyCode: string | null = null; + let pendingVoiceSubmission: PreviewAnnotationSubmission | null = null; + let voiceSubmissionReady = false; + const voiceButton = createButton("", "Start voice input"); + voiceButton.innerHTML = + ''; + voiceButton.className += " h-8 w-8 shrink-0 p-0 text-muted-foreground"; + voiceButton.hidden = true; + voiceButton.setAttribute("aria-label", "Start voice input"); + composerRow.appendChild(voiceButton); + const voiceRow = document.createElement("div"); + voiceRow.className = "flex min-w-0 items-center justify-end gap-1 px-2 pb-2"; + voiceRow.hidden = true; + const voicePill = document.createElement("div"); + const voiceCancel = createButton("", "Cancel voice input"); + voiceCancel.innerHTML = + ''; + voiceCancel.className += " h-7 w-7 shrink-0 rounded-full p-0"; + const voiceFinish = createButton("", "Finish voice input"); + voiceFinish.className += + " h-7 w-7 shrink-0 rounded-full border-primary bg-primary p-0 text-primary-foreground hover:bg-primary/90"; + const voiceSkip = createButton("Skip", "Skip transcript cleanup"); + voiceSkip.className += " h-7 shrink-0 rounded-full px-2.5"; + // createButton's rounded-md sorts after rounded-full in the generated CSS, so it would win. + for (const button of [voiceCancel, voiceFinish, voiceSkip]) button.classList.remove("rounded-md"); + const voiceStatus = document.createElement("div"); + voiceStatus.className = "flex h-7 min-w-0 flex-1 items-center gap-2"; + voiceStatus.setAttribute("role", "status"); + const voiceStatusText = document.createElement("span"); + voiceStatusText.className = "min-w-0 flex-1 truncate text-right text-sm text-muted-foreground"; + const waveform = document.createElement("div"); + waveform.className = + "flex h-5 min-w-0 flex-1 items-center justify-between gap-px overflow-hidden"; + waveform.setAttribute("aria-hidden", "true"); + const waveformLevels = Array(24).fill(0); + const waveformBars = waveformLevels.map(() => { + const bar = document.createElement("span"); + bar.className = "h-full w-0.5 shrink-0 origin-center rounded-full bg-primary"; + bar.style.transform = "scaleY(0.08)"; + bar.style.opacity = "0.25"; + waveform.appendChild(bar); + return bar; + }); + const voiceElapsed = document.createElement("span"); + voiceElapsed.className = "shrink-0 text-xs tabular-nums text-muted-foreground"; + let recordingStartedAt = 0; + let elapsedTimer: ReturnType | null = null; + const updateElapsed = () => { + const seconds = Math.floor((Date.now() - recordingStartedAt) / 1_000); + voiceElapsed.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; + }; + voiceStatus.append(voiceStatusText, waveform, voiceElapsed); + voicePill.append(voiceCancel, voiceStatus, voiceSkip, voiceFinish); + voiceRow.appendChild(voicePill); + const voicePreview = document.createElement("p"); + voicePreview.className = "px-2 pb-2 text-sm text-muted-foreground"; + voicePreview.setAttribute("role", "status"); + voicePreview.hidden = true; + const sendVoice = ( + action: DesktopPreviewAnnotationVoiceEvent["action"], + keyboard?: KeyboardEvent, + ) => { + if (!voice || finished) return; + const event: DesktopPreviewAnnotationVoiceEvent = { + sessionId: voice.sessionId, + text: comment.value, + cursor: comment.selectionStart, + selectionEnd: comment.selectionEnd, + action, + ...(keyboard + ? { + keyboard: { + type: keyboard.type === "keyup" ? ("keyup" as const) : ("keydown" as const), + key: keyboard.key, + code: keyboard.code, + metaKey: keyboard.metaKey, + ctrlKey: keyboard.ctrlKey, + shiftKey: keyboard.shiftKey, + altKey: keyboard.altKey, + repeat: keyboard.repeat, + }, + } + : {}), + }; + ipcRenderer.send(ANNOTATION_VOICE_EVENT_CHANNEL, event); + }; + const isDictationChord = (event: KeyboardEvent) => + voice !== undefined && + voice.shortcuts.some((shortcut) => + matchesKeybindingShortcut(event, shortcut, navigator.platform), + ); + for (const button of [voiceButton, voiceFinish, voiceCancel, voiceSkip]) { + button.addEventListener("pointerdown", (event) => event.preventDefault()); + } + // Page scripts cannot reach the closed shadow root, and a synthetic click never counts. + voiceButton.addEventListener("click", (event) => { + if (!event.isTrusted) return; + if (voiceSettings) { + sendVoice("settings"); + return; + } + if (!voiceAvailable || (voiceBusy && voicePhase !== "recording")) return; + sendVoice(voicePhase === "recording" ? "stop" : "start"); + }); + voiceFinish.addEventListener("click", (event) => { + if (event.isTrusted) sendVoice("stop"); + }); + voiceCancel.addEventListener("click", (event) => { + if (!event.isTrusted) return; + pendingVoiceSubmission = null; + sendVoice("cancel"); + }); + voiceSkip.addEventListener("click", (event) => { + if (event.isTrusted) sendVoice("skip"); + }); + const onVoiceState = ( + _event: Electron.IpcRendererEvent, + state: DesktopPreviewAnnotationVoiceState, + ) => { + if (finished || state.sessionId !== voice?.sessionId) return; + const phaseChanged = voicePhase !== state.phase; + const submissionChanged = voiceBusy !== state.blocksSubmission; + const previewChanged = voicePreview.textContent !== (state.preview ?? ""); + voicePhase = state.phase; + voiceSettings = state.errorAction === "settings"; + voiceBusy = state.blocksSubmission; + voiceAvailable = state.available; + comment.readOnly = state.freezesEditor; + if (state.draft) { + voiceSubmissionReady = pendingVoiceSubmission !== null; + comment.value = state.draft.text; + comment.setSelectionRange(state.draft.cursor, state.draft.cursor); + resizeComment(); + } + const recording = state.phase === "recording"; + const active = state.phase !== "idle" && state.phase !== "error"; + const wasActive = voicePill.parentElement === composerRow; + voiceButton.hidden = !state.available || active; + voiceButton.disabled = voiceBusy; + const label = voiceSettings ? "Open voice settings" : "Start voice input"; + voiceButton.title = + !voiceSettings && state.shortcutLabel ? `${label} (${state.shortcutLabel})` : label; + voiceButton.setAttribute("aria-label", label); + // An active dictation takes the textarea's place; it takes focus once (sr-only) so Enter still attaches. + voiceRow.hidden = state.phase === "idle" || active; + comment.classList.toggle("sr-only", active); + if (active && !wasActive) comment.focus({ preventScroll: true }); + submit.hidden = active; + // Re-inserting on every level update would blur a focused Finish or Cancel. + if (active && voicePill.parentElement !== composerRow) comment.after(voicePill); + else if (!active && voicePill.parentElement !== voiceRow) voiceRow.appendChild(voicePill); + voicePill.className = active + ? "flex h-8 min-w-0 flex-1 items-center gap-2" + : "flex min-w-0 items-center gap-1"; + // A draft that arrived while the textarea was sr-only was measured at 1px wide. + if (wasActive && !active) resizeComment(); + else if (phaseChanged) queueEditorLayout(); + voiceCancel.title = + state.phase === "error" ? "Dismiss voice input error" : "Cancel voice input"; + voiceCancel.setAttribute("aria-label", voiceCancel.title); + voiceStatus.setAttribute("aria-label", state.status ?? "Voice input"); + voiceStatus.setAttribute("aria-live", recording ? "off" : "polite"); + voiceStatusText.textContent = state.status; + voiceStatusText.style.color = state.phase === "error" ? "var(--t3-destructive)" : ""; + voiceStatusText.hidden = recording; + waveform.hidden = !recording; + voiceElapsed.hidden = !recording; + if (recording && elapsedTimer === null) { + recordingStartedAt = Date.now(); + waveformLevels.fill(0); + updateElapsed(); + elapsedTimer = setInterval(updateElapsed, 250); + } else if (!recording && elapsedTimer !== null) { + clearInterval(elapsedTimer); + elapsedTimer = null; + } + if (recording) { + waveformLevels.copyWithin(0, 1); + waveformLevels[waveformLevels.length - 1] = state.level; + const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; + waveformBars.forEach((bar, index) => { + const level = waveformLevels[index] ?? 0; + bar.style.opacity = String(0.25 + level * 0.75); + bar.style.transform = `scaleY(${reducedMotion ? 0.35 : Math.max(0.08, level)})`; + }); + } + voiceSkip.hidden = state.phase !== "post-processing"; + voiceFinish.hidden = !active || state.phase === "post-processing"; + voiceFinish.disabled = !recording; + voiceFinish.title = recording ? "Finish voice input" : (state.status ?? "Voice input is busy"); + if (recording && state.shortcutLabel) voiceFinish.title += ` (${state.shortcutLabel})`; + voiceFinish.setAttribute("aria-label", voiceFinish.title); + if (phaseChanged) + voiceFinish.innerHTML = recording + ? '' + : ''; + if (!active) voicePill.append(voiceStatus, voiceCancel); + else if (phaseChanged) voicePill.append(voiceCancel, voiceStatus, voiceSkip, voiceFinish); + voicePreview.textContent = state.preview; + voicePreview.hidden = !state.preview; + if (phaseChanged || submissionChanged || previewChanged || state.draft) updateStatus(); + if (pendingVoiceSubmission !== null) { + if (state.phase === "recording") sendVoice("stop"); + if (state.phase === "error") pendingVoiceSubmission = null; + if (state.phase === "idle") { + const submission = pendingVoiceSubmission; + pendingVoiceSubmission = null; + if (voiceSubmissionReady && submission !== null) submitAnnotation(submission); + voiceSubmissionReady = false; + } + } + }; + const dragHandle = document.createElement("button"); dragHandle.type = "button"; dragHandle.textContent = "⠿"; @@ -613,7 +851,7 @@ function startAnnotation(sendEnabled: boolean): void { submit.className += " h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90"; composerRow.appendChild(submit); - editor.appendChild(composerRow); + editor.append(composerRow, voicePreview, voiceRow); const stylePanel = document.createElement("div"); stylePanel.className = @@ -654,12 +892,19 @@ function startAnnotation(sendEnabled: boolean): void { comment.style.overflowY = comment.scrollHeight > maxHeight ? "auto" : "hidden"; queueEditorLayout(); }; - comment.addEventListener("input", resizeComment); + comment.addEventListener("input", () => { + resizeComment(); + sendVoice("sync"); + }); const updateStatus = (): void => { const hasTargets = selected.size > 0 || regions.length > 0 || strokes.length > 0; + if (!hasTargets && voiceBusy) { + pendingVoiceSubmission = null; + sendVoice("cancel"); + } editor.style.display = hasTargets ? "flex" : "none"; - submit.disabled = !hasTargets; + submit.disabled = !hasTargets || voicePhase === "preparing" || pendingCapture; submit.style.opacity = hasTargets ? "1" : "0.45"; adjust.disabled = !hasTargets; stylePanel.style.display = editorExpanded && selected.size > 0 ? "grid" : "none"; @@ -695,7 +940,6 @@ function startAnnotation(sendEnabled: boolean): void { for (const [key, change] of styleChanges) { if (change.targetId === target.id) styleChanges.delete(key); } - updateStatus(); }; const addSelected = (element: Element): void => { @@ -710,7 +954,6 @@ function startAnnotation(sendEnabled: boolean): void { selected.set(element, target); root.append(target.outline, target.label); updateSelectedVisual(target); - updateStatus(); if (editorExpanded) { stylePanel.style.display = "grid"; syncStyleControls(); @@ -721,12 +964,13 @@ function startAnnotation(sendEnabled: boolean): void { const existing = selected.get(element); if (existing) { removeSelected(existing); - return; - } - if (!additive) { - for (const target of Array.from(selected.values())) removeSelected(target); + } else { + if (!additive) { + for (const target of Array.from(selected.values())) removeSelected(target); + } + addSelected(element); } - addSelected(element); + updateStatus(); }; const setStyleForSelected = (property: string, value: string): void => { @@ -1140,6 +1384,7 @@ function startAnnotation(sendEnabled: boolean): void { const rect = target.element.getBoundingClientRect(); if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) { removeSelected(target); + updateStatus(); return true; } } @@ -1314,11 +1559,22 @@ function startAnnotation(sendEnabled: boolean): void { event.stopPropagation(); }; + const stopAtOverlay = (event: Event): void => event.stopPropagation(); + // Focus moving from the page into the overlay targets the page element, so the host never sees it. + const onFocusOutToOverlay = (event: FocusEvent): void => { + if (event.relatedTarget instanceof Element && isAnnotationNode(event.relatedTarget)) + event.stopPropagation(); + }; + const onPointerOut = (event: PointerEvent): void => { if (event.relatedTarget === null) clearHoverOutline(); }; + const onWindowFocus = (): void => { + if (editor.style.display !== "none") sendVoice("focus"); + }; const onWindowBlur = (): void => { + sendVoice("blur"); clearHoverOutline(); }; @@ -1344,16 +1600,22 @@ function startAnnotation(sendEnabled: boolean): void { window.removeEventListener("pointerout", onPointerOut, true); window.removeEventListener("click", onClick, true); window.removeEventListener("blur", onWindowBlur); + window.removeEventListener("focus", onWindowFocus); window.removeEventListener("keydown", onKeyDown, true); + window.removeEventListener("keyup", onVoiceKeyUp, true); window.removeEventListener("scroll", repaint, true); window.removeEventListener("resize", repaint); dragHandle.removeEventListener("pointerdown", onEditorPointerDown); dragHandle.removeEventListener("pointermove", onEditorPointerMove); dragHandle.removeEventListener("pointerup", onEditorPointerUp); dragHandle.removeEventListener("pointercancel", onEditorPointerUp); + for (const type of PAGE_ISOLATED_EVENTS) host.removeEventListener(type, stopAtOverlay); + document.documentElement.removeEventListener("focusout", onFocusOutToOverlay); if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame); ipcRenderer.off(CANCEL_PICK_CHANNEL, onCancel); ipcRenderer.off(ANNOTATION_CAPTURED_CHANNEL, onCaptured); + ipcRenderer.off(ANNOTATION_VOICE_STATE_CHANNEL, onVoiceState); + if (elapsedTimer !== null) clearInterval(elapsedTimer); document.documentElement.removeAttribute("data-t3code-annotation-tool"); cursorStyle.remove(); inputLayer?.remove(); @@ -1364,7 +1626,32 @@ function startAnnotation(sendEnabled: boolean): void { const onCancel = (): void => teardown(false); const onCaptured = (): void => teardown(false); + const onVoiceKeyUp = (event: KeyboardEvent): void => { + if (!event.isTrusted || (event.code || event.key) !== voiceKeyCode) return; + voiceKeyCode = null; + event.preventDefault(); + event.stopImmediatePropagation(); + sendVoice("key", event); + }; const onKeyDown = (event: KeyboardEvent): void => { + // Only the keyboard drives dictation; a page cannot synthesize the chord or Escape. + if (voice && event.isTrusted && !event.isComposing && event.keyCode !== 229) { + if (event.key === "Escape" && voiceBusy) { + event.preventDefault(); + event.stopImmediatePropagation(); + voiceKeyCode = null; + pendingVoiceSubmission = null; + sendVoice("key", event); + return; + } + if (voiceAvailable && editor.style.display !== "none" && isDictationChord(event)) { + event.preventDefault(); + event.stopImmediatePropagation(); + voiceKeyCode = event.code || event.key; + sendVoice("key", event); + return; + } + } if (isAnnotationNode(event.target as Element) && event.key !== "Escape") return; if (event.key === "Escape") { event.preventDefault(); @@ -1382,6 +1669,16 @@ function startAnnotation(sendEnabled: boolean): void { const submitAnnotation = (submission: PreviewAnnotationSubmission): void => { if (submission === "send" && !sendEnabled) return; + if (voicePhase === "preparing") return; + // Submitting while dictating finishes the recording and submits once the text lands. + if (voiceBusy) { + if (pendingVoiceSubmission === null) { + pendingVoiceSubmission = submission; + voiceSubmissionReady = false; + if (voicePhase === "recording") sendVoice("stop"); + } + return; + } if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0)) return; pendingCapture = true; @@ -1460,11 +1757,18 @@ function startAnnotation(sendEnabled: boolean): void { window.addEventListener("pointerout", onPointerOut, { capture: true, passive: true }); window.addEventListener("click", onClick, { capture: true, passive: false }); window.addEventListener("blur", onWindowBlur); + window.addEventListener("focus", onWindowFocus); window.addEventListener("keydown", onKeyDown, { capture: true }); + window.addEventListener("keyup", onVoiceKeyUp, { capture: true }); window.addEventListener("scroll", repaint, { capture: true, passive: true }); window.addEventListener("resize", repaint, { passive: true }); + // Bubble phase, so the overlay's own handlers still see these events. + for (const type of PAGE_ISOLATED_EVENTS) + host.addEventListener(type, stopAtOverlay, { passive: true }); + document.documentElement.addEventListener("focusout", onFocusOutToOverlay); ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel); ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured); + if (voice) ipcRenderer.on(ANNOTATION_VOICE_STATE_CHANNEL, onVoiceState); if (inputLayer) { document.documentElement.appendChild(inputLayer); inputLayer.focus({ preventScroll: true }); @@ -1473,6 +1777,7 @@ function startAnnotation(sendEnabled: boolean): void { rootResizeObserver.observe(document.documentElement); refreshToolButtons(); updateStatus(); + sendVoice(document.hasFocus() ? "focus" : "sync"); activeSession = { teardown, applyTheme: (theme) => applyAnnotationTheme(host, theme), @@ -1485,9 +1790,14 @@ function startAnnotation(sendEnabled: boolean): void { ipcRenderer.on( START_PICK_CHANNEL, - (_event, theme: DesktopPreviewAnnotationTheme | undefined, sendEnabled?: boolean) => { + ( + _event, + theme: DesktopPreviewAnnotationTheme | undefined, + sendEnabled?: boolean, + voice?: DesktopPreviewAnnotationVoiceConfig, + ) => { if (theme) annotationTheme = theme; - startAnnotation(sendEnabled === true); + startAnnotation(sendEnabled === true, voice); }, ); ipcRenderer.on(ANNOTATION_SEND_ENABLED_CHANNEL, (_event, enabled: boolean) => { diff --git a/apps/desktop/src/preview/RecordingCursor.ts b/apps/desktop/src/preview/RecordingCursor.ts index 5b9fb3c13bc37..29f1865de291f 100644 --- a/apps/desktop/src/preview/RecordingCursor.ts +++ b/apps/desktop/src/preview/RecordingCursor.ts @@ -11,6 +11,11 @@ import { type RecordingKeyPress, } from "./RecordingInput.ts"; +// Modal dialogs, popovers and fullscreen elements paint above any z-index, so the cursors live in +// the top layer as manual popovers and move back to its front whenever the page adds to it. +const POPOVER_RESET = + "all:initial;margin:0;padding:0;border:0;background:transparent;overflow:visible;inset:auto;animation:none;transition:none;"; + /** Draw in guest coordinates; Chromium's native cursor ignores webview CSS placement/scale. Hide it to avoid duplicates. */ export function installRecordingCursor( document: Document, @@ -20,22 +25,43 @@ export function installRecordingCursor( ) { const style = document.createElement("style"); style.textContent = - "html, html * { cursor: none !important; } @media (prefers-reduced-motion: reduce) { [data-t3code-recording-agent-cursor] { transition: none !important; } }"; + "html, html * { cursor: none !important; } [data-t3code-recording-cursor]::backdrop, [data-t3code-recording-agent-cursor]::backdrop { display: none !important; } @media (prefers-reduced-motion: reduce) { [data-t3code-recording-agent-cursor] { transition: none !important; } }"; const cursor = document.createElement("div"); cursor.setAttribute("aria-hidden", "true"); cursor.setAttribute("data-t3code-recording-cursor", ""); + cursor.popover = "manual"; cursor.style.cssText = + POPOVER_RESET + "position:fixed;left:0;top:0;width:16px;height:24px;pointer-events:none;z-index:2147483647;display:none;"; cursor.innerHTML = ''; const agentCursor = document.createElement("div"); agentCursor.setAttribute("aria-hidden", "true"); agentCursor.setAttribute("data-t3code-recording-agent-cursor", ""); + agentCursor.popover = "manual"; agentCursor.style.cssText = + POPOVER_RESET + "position:fixed;left:0;top:0;width:20px;height:20px;pointer-events:none;z-index:2147483647;display:none;filter:drop-shadow(0 1px 2px #0003);transition:transform 150ms ease-out,opacity 150ms ease-out;"; agentCursor.innerHTML = ''; document.documentElement.append(style, cursor, agentCursor); + const cursors = [cursor, agentCursor]; + const raise = () => { + for (const element of cursors) { + if (!element.isConnected || typeof element.showPopover !== "function") continue; + if (element.matches(":popover-open")) element.hidePopover(); + element.showPopover(); + } + }; + raise(); + const dialogObserver = new MutationObserver(raise); + dialogObserver.observe(document, { subtree: true, attributes: true, attributeFilter: ["open"] }); + const toggle = (event: Event) => { + if (cursors.some((element) => element === event.target)) return; + if ("newState" in event && event.newState === "open") raise(); + }; + document.addEventListener("toggle", toggle, true); + document.addEventListener("fullscreenchange", raise); let controller: "human" | "agent" | "none" = "none"; let humanPoint: { readonly x: number; readonly y: number } | null = null; const drawHuman = () => { @@ -182,6 +208,9 @@ export function installRecordingCursor( window.removeEventListener("keyup", keyUp, true); window.removeEventListener("pointerout", leave, true); window.removeEventListener("blur", hide); + dialogObserver.disconnect(); + document.removeEventListener("toggle", toggle, true); + document.removeEventListener("fullscreenchange", raise); cancelPendingPointer(); window.clearTimeout(agentTimer); cursor.remove(); diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 7e4b530083097..868e1c139fbdd 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -200,16 +200,22 @@ describe("DesktopSettings", () => { withSettings( Effect.gen(function* () { const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* writeSettingsPatch({ - mainWindowBounds: { x: 10.5, y: 20, width: 839, height: 620 }, - mainWindowMaximized: true, - serverExposureMode: "network-accessible", - }); - - const loaded = yield* settings.load; - assert.isNull(loaded.mainWindowBounds); - assert.isFalse(loaded.mainWindowMaximized); - assert.equal(loaded.serverExposureMode, "network-accessible"); + for (const bounds of [ + { x: 10.5, y: 20, width: 400, height: 360 }, + { x: 10, y: 20, width: 399, height: 360 }, + { x: 10, y: 20, width: 400, height: 359 }, + ]) { + yield* writeSettingsPatch({ + mainWindowBounds: bounds, + mainWindowMaximized: true, + serverExposureMode: "network-accessible", + }); + + const loaded = yield* settings.load; + assert.isNull(loaded.mainWindowBounds); + assert.isFalse(loaded.mainWindowMaximized); + assert.equal(loaded.serverExposureMode, "network-accessible"); + } }), ), ); @@ -221,17 +227,24 @@ describe("DesktopSettings", () => { const fileSystem = yield* FileSystem.FileSystem; const settings = yield* DesktopAppSettings.DesktopAppSettings; - yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 1440, height: 960 }, true); + yield* settings.setMainWindowBounds({ x: -1200, y: 40, width: 400, height: 360 }, true); yield* settings.setServerExposureMode("network-accessible"); const persisted = yield* decodeDesktopSettingsPatch( yield* fileSystem.readFileString(environment.desktopSettingsPath), ); assert.deepEqual(persisted, { - mainWindowBounds: { x: -1200, y: 40, width: 1440, height: 960 }, + mainWindowBounds: { x: -1200, y: 40, width: 400, height: 360 }, mainWindowMaximized: true, serverExposureMode: "network-accessible", } satisfies typeof DesktopSettingsPatch.Type); + + const restored = yield* Effect.gen(function* () { + const freshSettings = yield* DesktopAppSettings.DesktopAppSettings; + return yield* freshSettings.load; + }).pipe(Effect.provide(DesktopAppSettings.layer)); + assert.deepEqual(restored.mainWindowBounds, persisted.mainWindowBounds); + assert.isTrue(restored.mainWindowMaximized); }), ), ); diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index 6cd34322d98c2..4c2ae8d1d1342 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -47,9 +47,12 @@ export interface DesktopSettingsChange { } const DEFAULT_TAILSCALE_SERVE_PORT = 443; -const MIN_MAIN_WINDOW_SIZE = { - width: 840, - height: 620, +// Fits half and third tiles of common scaled displays (down to 480x432 DIP) on +// Wayland, where Electron's client-side frame adds 32x42 DIP to the enforced +// minimum. The web layout already handles phone widths. +export const MIN_MAIN_WINDOW_SIZE = { + width: 400, + height: 360, } as const; export const DesktopWindowBoundsSchema = Schema.Struct({ x: Schema.Int, diff --git a/apps/desktop/src/settings/DesktopClientSettings.test.ts b/apps/desktop/src/settings/DesktopClientSettings.test.ts index 0dab1c8d83cc6..1ab9b3159e1f9 100644 --- a/apps/desktop/src/settings/DesktopClientSettings.test.ts +++ b/apps/desktop/src/settings/DesktopClientSettings.test.ts @@ -34,7 +34,6 @@ const clientSettings: ClientSettings = { confirmThreadArchive: true, confirmThreadDelete: false, confirmThreadUnpin: false, - contextWindowMeterEnabled: false, diffFilesCollapsed: true, diffIgnoreWhitespace: true, diffLayout: "stacked", @@ -52,7 +51,6 @@ const clientSettings: ClientSettings = { glassOpacity: 80, onboardingCompletedAt: null, panelAnimationDurationMs: 0, - planModeEnabled: false, proactivePanelsEnabled: true, showSkillsInSlashMenu: false, persistComposerContextStrip: true, @@ -67,7 +65,6 @@ const clientSettings: ClientSettings = { boringSidebarMultilineRows: false, threadDetailsUsageEnabled: false, threadDetailsItems: {}, - legacySidebarEnabled: false, sidebarWorkingShelfEnabled: false, loadBalancingEnabled: false, loadBalancingWeights: { "environment-1": 75, "environment-2": 0 }, diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 124dbbeae89e0..0c7869194323c 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -444,10 +444,13 @@ describe("DesktopShellEnvironment", () => { const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" }; const commands: string[] = []; - yield* runShellEnvironment({ + const discovery = (service: DesktopShellEnvironment.DesktopShellEnvironment["Service"]) => + Effect.all([service.awaitDiscovery, service.awaitUserShellDiscovery]); + const answered = yield* runShellEnvironment({ env, platform: "linux", userShell: "/usr/local/bin/fish", + use: (service) => discovery(service).pipe(Effect.map(([, fromUserShell]) => fromUserShell)), handler: (command) => { if (command._tag !== "StandardCommand") return ""; commands.push(command.command); @@ -459,6 +462,23 @@ describe("DesktopShellEnvironment", () => { assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]); assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin"); + // The account's own login shell answered. + assert.isTrue(answered); + + // Only the platform fallback answered: its PATH can miss folders the user's shell adds. + const fallbackOnly = yield* runShellEnvironment({ + env: { SHELL: "/usr/bin/fish", PATH: "/usr/bin" }, + platform: "linux", + use: (service) => + discovery(service).pipe( + Effect.map(([prepared, fromUserShell]) => prepared && !fromUserShell), + ), + handler: (command) => + command._tag === "StandardCommand" && command.command === "/usr/bin/fish" + ? { output: "", exitCode: 7 } + : envOutput({ PATH: "/usr/bin" }), + }).pipe(Effect.provide(Logger.layer([]))); + assert.isTrue(fallbackOnly); }), ); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 37826f8ee5aba..9d9e390c95496 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -3,6 +3,7 @@ import { applyShellEnvironment, buildEnvironmentCaptureCommand, listLoginShellCandidates, + readUserLoginShell, setWindowsPath, } from "@t3tools/shared/shell"; import * as Context from "effect/Context"; @@ -79,6 +80,8 @@ export class DesktopShellEnvironment extends Context.Service< // Desktop owns discovery, including on cache misses; the backend receives updates over fd4. readonly installIntoProcess: Effect.Effect; readonly awaitDiscovery: Effect.Effect; + /** Whether the user's own login shell, not a fallback, gave the PATH a new terminal gets. */ + readonly awaitUserShellDiscovery: Effect.Effect; readonly updates: Stream.Stream; } >()("@t3tools/desktop/shell/DesktopShellEnvironment") {} @@ -417,19 +420,24 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix function* ( config: ShellEnvironmentConfig, ): Effect.fn.Return< - boolean, + ShellDiscovery, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem > { const fileSystem = yield* FileSystem.FileSystem; const shellEnvironment: EnvironmentPatch = {}; + const userShells = [config.env.SHELL?.trim(), readUserLoginShell()]; + let answeredBy: string | undefined; for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) { Object.assign( shellEnvironment, yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env), ); - if (shellEnvironment.PATH) break; + if (shellEnvironment.PATH) { + answeredBy = shell; + break; + } } const launchctlPath = @@ -518,24 +526,33 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix } } - return Option.isSome(trimNonEmpty(shellEnvironment.PATH)); + const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH)); + return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) }; }, ); +/** `fromUserShell` is false when only a fallback shell answered, whose PATH can miss folders. */ +interface ShellDiscovery { + readonly prepared: boolean; + readonly fromUserShell: boolean; +} + const installShellEnvironment = ( config: ShellEnvironmentConfig, ): Effect.Effect< - boolean, + ShellDiscovery, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem > => { if (config.platform === "win32") { - return installWindowsEnvironment(config); + return installWindowsEnvironment(config).pipe( + Effect.map((prepared) => ({ prepared, fromUserShell: prepared })), + ); } if (config.platform === "darwin" || config.platform === "linux") { return installPosixEnvironment(config); } - return Effect.succeed(false); + return Effect.succeed({ prepared: false, fromUserShell: false }); }; const ShellEnvironmentCache = Schema.fromJsonString( @@ -578,7 +595,7 @@ export const make = Effect.gen(function* () { const cachePath = path.join(environment.stateDir, "shell-environment-cache.json"); const changes = yield* PubSub.unbounded(); const latest = yield* Ref.make>(Option.none()); - const discovered = yield* Deferred.make(); + const discovered = yield* Deferred.make(); const publish = Effect.fn("desktop.shellEnvironment.publish")(function* ( patch: ShellEnvironmentPatch, discovered = false, @@ -597,7 +614,11 @@ export const make = Effect.gen(function* () { const refresh = Effect.gen(function* () { // Refresh from the inherited baseline so removed cached paths and values do not survive. const fresh = { ...inherited }; - const prepared = yield* installShellEnvironment({ env: fresh, platform: environment.platform }); + const discovery = yield* installShellEnvironment({ + env: fresh, + platform: environment.platform, + }); + const { prepared } = discovery; const patch = Object.fromEntries( Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]), ); @@ -616,7 +637,7 @@ export const make = Effect.gen(function* () { Effect.catch(() => Effect.logWarning("Could not cache shell environment")), ); } - return prepared; + return discovery; }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), @@ -669,7 +690,14 @@ export const make = Effect.gen(function* () { ); return DesktopShellEnvironment.of({ installIntoProcess, - awaitDiscovery: installIntoProcess.pipe(Effect.andThen(Deferred.await(discovered))), + awaitDiscovery: installIntoProcess.pipe( + Effect.andThen(Deferred.await(discovered)), + Effect.map(({ prepared }) => prepared), + ), + awaitUserShellDiscovery: installIntoProcess.pipe( + Effect.andThen(Deferred.await(discovered)), + Effect.map(({ fromUserShell }) => fromUserShell), + ), updates, }); }); diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index 721f130ef5e56..57a38d2ff314d 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -978,7 +978,7 @@ it.effect.each(["succeeds", "fails"] as const)( }, ); -it.effect("matches Windows accessibility windows on a scaled display", () => { +it.effect("captures and reads Windows windows in physical pixels on a scaled display", () => { const png = Buffer.from([1, 2, 3]); const active = { platform: "windows", @@ -987,26 +987,26 @@ it.effect("matches Windows accessibility windows on a scaled display", () => { owner: { name: "Editor", processId: 123 }, bounds: { x: 10, y: 20, width: 800, height: 600 }, } as const; - const dipBounds = { x: 5, y: 10, width: 400, height: 300 }; + const window = (name: string, value: string) => ({ + role: "window", + name, + bounds: active.bounds, + children: async () => [ + { + role: "button", + name: "Save", + bounds: { x: 210, y: 220, width: 200, height: 100 }, + children: async () => [], + }, + ], + tree: async () => ({ name, value, children: [] }), + }); activeWindowMock.mockReset().mockResolvedValue(active); - screenToDipRectMock.mockImplementation(() => dipBounds); + screenToDipRectMock.mockImplementation(() => ({ x: 5, y: 10, width: 400, height: 300 })); regionCaptureMock.mockReset().mockResolvedValue({ width: 800, height: 600, png }); accessibilityForegroundMock.mockReset().mockResolvedValue({ pid: 123, - asElement: () => ({ - role: "window", - name: "Editor", - bounds: dipBounds, - children: async () => [ - { - role: "button", - name: "Save", - bounds: { x: 105, y: 110, width: 100, height: 50 }, - children: async () => [], - }, - ], - tree: async () => ({ name: "Editor", value: "Scaled text", children: [] }), - }), + children: async () => [window("Settings", "Wrong window"), window("Editor", "Scaled text")], }); let metadata = ""; return Effect.scoped( @@ -1015,6 +1015,7 @@ it.effect("matches Windows accessibility windows on a scaled display", () => { yield* service.configure(enabledSettings()); yield* service.capture; const saved = yield* decodePendingMetadata(metadata); + assert.deepEqual(regionCaptureMock.mock.calls[0]?.[0], active.bounds); assert.include(saved.source.accessibleText, "Scaled text"); assert.deepEqual( saved.source.accessibility?.format === "element-tree" @@ -1402,7 +1403,7 @@ it.each(["darwin", "win32", "linux"] as const)( accessibilityByPidMock.mockReset().mockResolvedValue({ children: async () => [window] }); accessibilityForegroundMock .mockReset() - .mockResolvedValue({ pid: 123, asElement: () => window }); + .mockResolvedValue({ pid: 123, children: async () => [window] }); const result = await readAccessibleWindowContext( { title: "Editor", bounds, owner: { processId: 123 } }, @@ -1442,7 +1443,7 @@ it.each(["darwin", "win32"] as const)( accessibilityByPidMock.mockReset().mockResolvedValue({ children: async () => [window] }); accessibilityForegroundMock .mockReset() - .mockResolvedValue({ pid: 123, asElement: () => window }); + .mockResolvedValue({ pid: 123, children: async () => [window] }); try { assert.isUndefined( await readAccessibleWindowText( @@ -1484,7 +1485,7 @@ it.each([ accessibilityByPidMock.mockReset().mockResolvedValue({ children: async () => [window] }); accessibilityForegroundMock .mockReset() - .mockResolvedValue({ pid: 123, asElement: () => window }); + .mockResolvedValue({ pid: 123, children: async () => [window] }); try { const result = await readAccessibleWindowContext( { title: "Editor", bounds, owner: { processId: 123 } }, @@ -1872,7 +1873,9 @@ it.effect("capture fails closed while snapshots are disabled", () => { it.effect("points capture setup failures at SnapShot settings", () => { vi.stubEnv("XDG_SESSION_TYPE", "wayland"); - linuxCaptureMock.mockRejectedValueOnce(new CaptureSetupRequiredError("Install the helper.")); + linuxCaptureMock.mockRejectedValueOnce( + new CaptureSetupRequiredError({ state: "Install the helper." }), + ); return Effect.scoped( Effect.gen(function* () { const service = yield* DesktopSnapShot.make; diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index a3d4db0bb4dc2..d995758619bfe 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -94,6 +94,8 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import { readImageDimensions } from "@t3tools/shared/imageDimensions"; +const isCaptureSetupRequiredError = Schema.is(CaptureSetupRequiredError); + const MAX_CAPTURE_WIDTH = 2_560; const MAX_CAPTURE_HEIGHT = 1_600; const SHORTCUT_COOLDOWN_NS = 200_000_000n; @@ -167,9 +169,20 @@ export class DesktopSnapShotError extends Schema.TaggedError()( + "SnapShotShortcutError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not register the SnapShot shortcut."; + } +} + +const shortcutFailure = (cause: unknown) => new SnapShotShortcutError({ cause }); + function captureFailure(cause: unknown, captureId?: string): DesktopSnapShotError { if (isDesktopSnapShotError(cause)) return cause; - const operation = cause instanceof CaptureSetupRequiredError ? "setup-required" : "capture"; + const operation = isCaptureSetupRequiredError(cause) ? "setup-required" : "capture"; return new DesktopSnapShotError({ operation, captureId, cause }); } @@ -495,7 +508,6 @@ async function captureSource({ ({ source, png } = await captureRegionWindowSnapshot( regionSnapShotPool, active, - snapShotFlashBounds(active, platform), snapShotThumbnailSize(active), )); } else { @@ -534,7 +546,7 @@ async function captureSource({ } } const accessibleIdentity = active - ? { ...active, bounds: snapShotFlashBounds(active, platform) } + ? active : linuxWindow?.processId ? { title: linuxWindow.title, @@ -768,6 +780,8 @@ export const make = Effect.gen(function* () { const captureDirectory = path.join(environment.stateDir, "snap-shots"); const linuxAppId = environment.linuxDesktopEntryName.replace(/\.desktop$/, ""); const home = yield* HostProcess.HomeDirectory; + // Shell discovery can replace XDG_CURRENT_DESKTOP after startup, so read the live env per state. + const hostEnv = yield* HostProcess.Environment; let shortcutVerified = false; const gnomeSetupPaths = { bundle: environment.isPackaged @@ -1066,13 +1080,15 @@ export const make = Effect.gen(function* () { if (mode === "portal") { return { available: false, message: WAYLAND_MODIFIER_PAIR_UNAVAILABLE_MESSAGE }; } - const available = yield* Effect.tryPromise(() => - startPairShortcutProcess( - snapShotShortcutModifierPair(shortcut), - () => undefined, - () => undefined, - ), - ).pipe( + const available = yield* Effect.tryPromise({ + try: () => + startPairShortcutProcess( + snapShotShortcutModifierPair(shortcut), + () => undefined, + () => undefined, + ), + catch: shortcutFailure, + }).pipe( Effect.tap((stop) => Effect.sync(stop)), Effect.as(true), Effect.orElseSucceed(() => false), @@ -1087,7 +1103,10 @@ export const make = Effect.gen(function* () { const systemConflict = snapShotShortcutSystemConflict(shortcut); if (systemConflict) return { available: false, message: systemConflict }; if (mode === "portal") { - return yield* Effect.try(() => portalShortcutTrigger(shortcut)).pipe( + return yield* Effect.try({ + try: () => portalShortcutTrigger(shortcut), + catch: shortcutFailure, + }).pipe( Effect.match({ onSuccess: () => ({ available: true, @@ -1197,13 +1216,16 @@ export const make = Effect.gen(function* () { return; } if (mode === "portal" && niriSocketPath()) { - const registered = yield* Effect.tryPromise(async () => { - const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts"); - return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => { - void runPromise( - setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."), - ).catch(() => undefined); - }); + const registered = yield* Effect.tryPromise({ + try: async () => { + const { startNiriCaptureShortcut } = await import("./NiriCaptureShortcut.ts"); + return startNiriCaptureShortcut(linuxAppId, onCurrentShortcut, () => { + void runPromise( + setShortcutFailure("The Niri capture endpoint disconnected. Restart T3 Code."), + ).catch(() => undefined); + }); + }, + catch: shortcutFailure, }).pipe( Effect.tap((stop) => Effect.sync(() => { @@ -1247,29 +1269,32 @@ export const make = Effect.gen(function* () { shortcutMessage: null, message: null, }); - yield* Effect.tryPromise(async () => { - const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts"); - return new PortalCaptureShortcut( - linuxAppId, - isModifierPairShortcut(shortcut) - ? { - key: "2", - ctrlKey: true, - modKey: false, - altKey: false, - shiftKey: true, - metaKey: false, - } - : shortcut, - onCurrentShortcut, - () => { - if (generation !== shortcutGeneration) return; - shortcutVerified = false; - void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined); - }, - undefined, - hyprland, - ); + yield* Effect.tryPromise({ + try: async () => { + const { PortalCaptureShortcut } = await import("./PortalCaptureShortcut.ts"); + return new PortalCaptureShortcut( + linuxAppId, + isModifierPairShortcut(shortcut) + ? { + key: "2", + ctrlKey: true, + modKey: false, + altKey: false, + shiftKey: true, + metaKey: false, + } + : shortcut, + onCurrentShortcut, + () => { + if (generation !== shortcutGeneration) return; + shortcutVerified = false; + void runPromise(emit({ type: "shortcut-changed" })).catch(() => undefined); + }, + undefined, + hyprland, + ); + }, + catch: shortcutFailure, }).pipe( Effect.tap((registration) => Effect.sync(() => { @@ -1291,15 +1316,21 @@ export const make = Effect.gen(function* () { let registered = false; if (isModifierPairShortcut(shortcut)) { - registered = yield* Effect.tryPromise(() => - startPairShortcutProcess(snapShotShortcutModifierPair(shortcut), onCurrentShortcut, () => { - void pipe( - snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform), - setShortcutFailure, - runPromise, - ).catch(() => undefined); - }), - ).pipe( + registered = yield* Effect.tryPromise({ + try: () => + startPairShortcutProcess( + snapShotShortcutModifierPair(shortcut), + onCurrentShortcut, + () => { + void pipe( + snapShotShortcutRegistrationFailureMessage(shortcut, environment.platform), + setShortcutFailure, + runPromise, + ).catch(() => undefined); + }, + ), + catch: shortcutFailure, + }).pipe( Effect.tap((stop) => Effect.sync(() => { stopShiftShortcut = stop; @@ -1487,7 +1518,10 @@ export const make = Effect.gen(function* () { if (action === "retry-shortcut") { const currentPortal = portalShortcut; if (currentPortal?.hasSession && !currentPortal.state.shortcutPending) { - yield* Effect.tryPromise(() => currentPortal.configure()).pipe( + yield* Effect.tryPromise({ + try: () => currentPortal.configure(), + catch: shortcutFailure, + }).pipe( Effect.mapError( (error) => new DesktopSnapShotSetupError({ @@ -1581,9 +1615,12 @@ export const make = Effect.gen(function* () { state: Ref.get(stateRef).pipe( Effect.flatMap((state) => state.mode === "portal" - ? Effect.tryPromise(async () => { - const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts"); - return getLinuxCaptureSupport(linuxAppId); + ? Effect.tryPromise({ + try: async () => { + const { getLinuxCaptureSupport } = await import("./LinuxSnapShot.ts"); + return getLinuxCaptureSupport(linuxAppId); + }, + catch: (cause) => new DesktopSnapShotError({ operation: "unsupported", cause }), }).pipe( Effect.map((support) => ({ ...state, ...support })), Effect.catch((error) => @@ -1621,7 +1658,8 @@ export const make = Effect.gen(function* () { Effect.gen(function* () { const linuxDesktop = state.mode === "portal" - ? process.env.XDG_CURRENT_DESKTOP?.toLowerCase() + ? (hostEnv.XDG_CURRENT_DESKTOP ?? "") + .toLowerCase() .split(":") .find( (name) => diff --git a/apps/desktop/src/snapShot/HyprlandSnapShot.ts b/apps/desktop/src/snapShot/HyprlandSnapShot.ts index a0b8b4181cd2a..c40f397809d26 100644 --- a/apps/desktop/src/snapShot/HyprlandSnapShot.ts +++ b/apps/desktop/src/snapShot/HyprlandSnapShot.ts @@ -171,11 +171,11 @@ export async function captureHyprlandWindow( let state = await setup.state(); if (state.status === "update-required") { await setup.perform("install-hyprland-helper").catch((cause: unknown) => { - throw new CaptureSetupRequiredError(state.message, { cause }); + throw new CaptureSetupRequiredError({ state: state.message, cause }); }); state = await setup.state(); } - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message); + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message }); const executable = hyprlandCaptureExecutable(paths); const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-hyprland-capture-")); const cleanup = () => NodeFSP.rm(directory, { recursive: true, force: true }); diff --git a/apps/desktop/src/snapShot/KdeSnapShot.ts b/apps/desktop/src/snapShot/KdeSnapShot.ts index 2e5723f51aae0..f141bd485d027 100644 --- a/apps/desktop/src/snapShot/KdeSnapShot.ts +++ b/apps/desktop/src/snapShot/KdeSnapShot.ts @@ -215,7 +215,7 @@ export async function captureKdeWindow( options?: { readonly flash: boolean; readonly animate: boolean }, ): Promise { const state = await new KdeCaptureSetup(paths).state(); - if (state.status !== "ready") throw new CaptureSetupRequiredError(state.message); + if (state.status !== "ready") throw new CaptureSetupRequiredError({ state: state.message }); const { executable } = kdeCapturePaths(paths); const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-kde-capture-")); let retained = false; diff --git a/apps/desktop/src/snapShot/RegionSnapShot.ts b/apps/desktop/src/snapShot/RegionSnapShot.ts index c640198524af0..d354f41acf3f3 100644 --- a/apps/desktop/src/snapShot/RegionSnapShot.ts +++ b/apps/desktop/src/snapShot/RegionSnapShot.ts @@ -175,10 +175,9 @@ export function makeRegionSnapShotPool( export async function captureRegionWindowSnapshot( pool: Pick, active: ActiveWindow, - region: Electron.Rectangle, maxSize: Electron.Size, ): Promise<{ readonly source: RegionSnapShotSource; readonly png: Buffer }> { - const shot = await pool.capture(region); + const shot = await pool.capture(active.bounds); const scale = Math.min(maxSize.width / shot.width, maxSize.height / shot.height, 1); const png = scale < 1 diff --git a/apps/desktop/src/snapShot/SnapShotAccessibility.ts b/apps/desktop/src/snapShot/SnapShotAccessibility.ts index 9021c8904e3fe..3a6d3367c583f 100644 --- a/apps/desktop/src/snapShot/SnapShotAccessibility.ts +++ b/apps/desktop/src/snapShot/SnapShotAccessibility.ts @@ -125,7 +125,7 @@ async function readCapturedWindowAccessibility( const pidWindows = foreground !== undefined ? foreground.pid === active.owner.processId - ? [foreground.asElement()] + ? await foreground.children().catch(() => []) : [] : await windowsForPid(App, active.owner.processId); const matchMode = isWaylandSession(platform, process.env) ? "wayland" : "screen-bounds"; diff --git a/apps/desktop/src/snapShot/linuxCaptureSession.ts b/apps/desktop/src/snapShot/linuxCaptureSession.ts index 11bf3984223df..e1f7c3601efc0 100644 --- a/apps/desktop/src/snapShot/linuxCaptureSession.ts +++ b/apps/desktop/src/snapShot/linuxCaptureSession.ts @@ -2,15 +2,19 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeURL from "node:url"; import type { SnapShotKeyChord } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { nativeImage } from "electron"; // Keep dbus-next out of desktop detection and PNG reads in the main process. export const HYPRLAND_CAPTURE_ACTION = "capture-window"; -export class CaptureSetupRequiredError extends Error { - constructor(state: string, options?: ErrorOptions) { - super(`${state} Open Settings → SnapShots to continue setup.`, options); +export class CaptureSetupRequiredError extends Schema.TaggedError()( + "CaptureSetupRequiredError", + { state: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return `${this.state} Open Settings → SnapShots to continue setup.`; } } export const NIRI_CAPTURE_PATH = "/com/t3tools/SnapShot"; diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index 3a3e84e03a9b7..7b480b36fbd12 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -23,6 +23,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -74,11 +75,13 @@ function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { return discoverSshHosts(input ?? {}); } +const isSshPasswordPromptError = Schema.is(SshPasswordPromptError); + export function isDesktopSshPasswordPromptCancellation( error: unknown, ): error is SshPasswordPromptError { return ( - error instanceof SshPasswordPromptError && + isSshPasswordPromptError(error) && DesktopSshPasswordPrompts.isDesktopSshPasswordPromptCancellation(error.cause) ); } diff --git a/apps/desktop/src/telemetry/DesktopRendererHistory.ts b/apps/desktop/src/telemetry/DesktopRendererHistory.ts index ed1590f63b19b..dc3e157f95351 100644 --- a/apps/desktop/src/telemetry/DesktopRendererHistory.ts +++ b/apps/desktop/src/telemetry/DesktopRendererHistory.ts @@ -273,7 +273,11 @@ const make = Effect.fn("DesktopRendererHistory.make")(function* () { accepting = false; for (const renderer of active.values()) renderer.removeListeners(); active.clear(); - }).pipe(Effect.andThen(Fiber.interrupt(writerFiber)), Effect.asVoid); + }).pipe( + Effect.andThen(Fiber.interrupt(writerFiber)), + Effect.asVoid, + Effect.withSpan("desktop.rendererHistory.shutdown"), + ); yield* Effect.addFinalizer(() => shutdown); return DesktopRendererHistory.of({ register, recordMetrics, shutdown }); diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index 1180c0fa70915..e2bfabe32762c 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -37,6 +37,7 @@ function layerElectronApp( metadata: Effect.die("unexpected metadata read"), name: Effect.succeed("T3 Code"), systemLocale: Effect.succeed("en-US"), + preferredSystemLanguages: Effect.succeed(["en-US"]), whenReady: Effect.void, requestSingleInstanceLock: Effect.succeed(true), quit: Effect.void, @@ -91,6 +92,7 @@ describe("DesktopTelemetryPublisher", () => { Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, { installIntoProcess: Effect.succeed(true), awaitDiscovery: Effect.succeed(true), + awaitUserShellDiscovery: Effect.succeed(true), updates: Stream.make({ version: 1, type: "shellEnvironment", diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 6279e8b6141a8..14688e5258067 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -25,6 +25,7 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts"; import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts"; import * as DesktopConfig from "../app/DesktopConfig.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; @@ -819,7 +820,8 @@ export const make = Effect.gen(function* () { yield* Ref.set(installRunningBackendsRef, runningInstances); yield* Effect.forEach( instances, - (instance) => instance.stop({ timeout: Duration.seconds(5) }), + (instance) => + instance.stop({ timeout: DesktopBackendManager.BACKEND_QUIT_STOP_TIMEOUT }), { concurrency: "unbounded" }, ); yield* electronUpdater.quitAndInstall({ diff --git a/apps/desktop/src/window/DesktopApplicationMenu.test.ts b/apps/desktop/src/window/DesktopApplicationMenu.test.ts index 9d8efd056665b..612ec441ba99b 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.test.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.test.ts @@ -4,7 +4,12 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import type * as Electron from "electron"; +import * as Electron from "electron"; +import { vi } from "vite-plus/test"; + +vi.mock("electron", () => ({ + webContents: { getAllWebContents: vi.fn(() => []) }, +})); import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; @@ -31,6 +36,7 @@ const layerElectronApp = Layer.succeed(ElectronApp.ElectronApp, { metadata: Effect.die("unexpected metadata read"), name: Effect.succeed("T3 Code"), systemLocale: Effect.succeed("en-US"), + preferredSystemLanguages: Effect.succeed(["en-US"]), whenReady: Effect.void, requestSingleInstanceLock: Effect.succeed(true), quit: Effect.void, @@ -226,10 +232,32 @@ describe("DesktopApplicationMenu", () => { items.find((item) => item.role === "windowMenu" && item.submenu === undefined), platform, ); - assert.isUndefined( - items.find((item) => item.accelerator?.toLowerCase().endsWith("+w")), - platform, - ); + const closeTools = items.find((item) => item.accelerator === "CmdOrCtrl+W"); + assert.equal(closeTools?.label, "Close Developer Tools", platform); + assert.isFunction(closeTools?.click); + const appContents = { + isDestroyed: () => false, + isDevToolsFocused: () => false, + closeDevTools: vi.fn(), + }; + const inspectedContents = { + ...appContents, + isDevToolsFocused: () => true, + closeDevTools: vi.fn(), + }; + using allContents = vi + .spyOn(Electron.webContents, "getAllWebContents") + .mockReturnValue([ + appContents as unknown as Electron.WebContents, + inspectedContents as unknown as Electron.WebContents, + ]); + closeTools?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(inspectedContents.closeDevTools.mock.calls.length, 1); + assert.equal(appContents.closeDevTools.mock.calls.length, 0); + + allContents.mockReturnValue([appContents as unknown as Electron.WebContents]); + closeTools?.click?.({} as Electron.MenuItem, undefined, {} as KeyboardEvent); + assert.equal(appContents.closeDevTools.mock.calls.length, 0); } }), ); diff --git a/apps/desktop/src/window/DesktopApplicationMenu.ts b/apps/desktop/src/window/DesktopApplicationMenu.ts index 07fd8654af6be..44d2c234f8358 100644 --- a/apps/desktop/src/window/DesktopApplicationMenu.ts +++ b/apps/desktop/src/window/DesktopApplicationMenu.ts @@ -4,7 +4,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import type * as Electron from "electron"; +import * as Electron from "electron"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; import * as ElectronDialog from "../electron/ElectronDialog.ts"; @@ -200,6 +200,17 @@ export const make = Effect.gen(function* () { }, { type: "separator" as const }, ]), + { + label: "Close Developer Tools", + accelerator: "CmdOrCtrl+W", + visible: false, + click: () => { + Electron.webContents + .getAllWebContents() + .find((contents) => !contents.isDestroyed() && contents.isDevToolsFocused()) + ?.closeDevTools(); + }, + }, // Cmd/Ctrl+W belongs to the renderer's tab close; it must never close the window. environment.platform === "darwin" ? { label: "Close Window", click: (_item, window) => window?.close() } diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index 4f8949823e354..03b9a2e6ad64a 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -94,6 +94,7 @@ function makeFakeBrowserWindow() { replaceMisspelling: vi.fn(), send: vi.fn(), setBackgroundThrottling: vi.fn(), + setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), toggleDevTools: vi.fn(), }; @@ -143,6 +144,7 @@ function makeFakeBrowserWindow() { reloadIgnoringCache: webContents.reloadIgnoringCache, toggleDevTools: webContents.toggleDevTools, navigationHistory: webContents.navigationHistory, + setIgnoreMenuShortcuts: webContents.setIgnoreMenuShortcuts, send: webContents.send, setZoomLevel: webContents.setZoomLevel, setWindowButtonPosition: window.setWindowButtonPosition, @@ -479,6 +481,30 @@ describe("DesktopWindow", () => { ); }); + it("restores a window saved 1px past a display edge, and nothing further out", () => { + const displays = [ + { x: 0, y: 0, width: 1920, height: 1280 }, + { x: 1920, y: 0, width: 1280, height: 1920 }, + ]; + const snappedBounds = { x: 1921, y: 30, width: 1280, height: 945 }; + + assert.strictEqual( + DesktopWindow.resolveInitialMainWindowBounds(snappedBounds, displays), + snappedBounds, + ); + for (const bounds of [ + { x: 1922, y: 30, width: 1280, height: 945 }, + { x: 1918, y: 30, width: 1280, height: 945 }, + { x: 1921, y: -2, width: 1279, height: 945 }, + { x: 1920, y: 976, width: 1280, height: 946 }, + ]) { + assert.deepEqual( + DesktopWindow.resolveInitialMainWindowBounds(bounds, displays), + DesktopAppSettings.DEFAULT_MAIN_WINDOW_SIZE, + ); + } + }); + it("rejects renderer navigations whose origin only serializes as null", () => { for (const applicationUrl of ["t3code://app/", "t3code-dev://app/"]) { assert.isTrue( @@ -622,7 +648,7 @@ describe("DesktopWindow", () => { }), ); - it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () => + it.effect("leaves Cmd+W to the renderer and blocks repeated presses", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); const createCount = yield* Ref.make(0); @@ -663,6 +689,13 @@ describe("DesktopWindow", () => { prevented = false; beforeInput(event, { ...input, meta: false }); assert.isFalse(prevented); + + assert.deepEqual( + fakeWindow.setIgnoreMenuShortcuts.mock.calls.map(([ignore]) => ignore), + [true, true, false], + ); + beforeInput(event, { ...input, key: "r", isAutoRepeat: false }); + assert.isFalse(fakeWindow.setIgnoreMenuShortcuts.mock.lastCall?.[0]); }).pipe(Effect.provide(layer)); }), ); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 5e02f4cfd8bbe..17dba6742f795 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Electron from "electron"; @@ -39,6 +40,15 @@ import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; const TITLEBAR_HEIGHT = 40; + +class ContextMenuImageCopyError extends Schema.TaggedError()( + "ContextMenuImageCopyError", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Could not copy the context-menu image."; + } +} // Match --workspace-topbar-height in apps/web/src/index.css; native macOS buttons stay 14 points at any zoom. const MACOS_WORKSPACE_TOPBAR_HEIGHT = 52; const MACOS_WINDOW_BUTTON_RADIUS = 7; @@ -138,15 +148,19 @@ function getInitialWindowBackgroundColor(shouldUseDarkColors: boolean): string { type DisplayBounds = Pick; +// A window snapped to a display edge can be reported 1px past that edge. +const SAVED_BOUNDS_EDGE_TOLERANCE_PX = 1; + function windowFitsWithinDisplay( windowBounds: DesktopAppSettings.DesktopWindowBounds, displayBounds: DisplayBounds, ): boolean { + const tolerance = SAVED_BOUNDS_EDGE_TOLERANCE_PX; return ( - windowBounds.x >= displayBounds.x && - windowBounds.y >= displayBounds.y && - windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width && - windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height + windowBounds.x >= displayBounds.x - tolerance && + windowBounds.y >= displayBounds.y - tolerance && + windowBounds.x + windowBounds.width <= displayBounds.x + displayBounds.width + tolerance && + windowBounds.y + windowBounds.height <= displayBounds.y + displayBounds.height + tolerance ); } @@ -389,8 +403,8 @@ export const make = Effect.gen(function* () { if (yield* Ref.get(desktopState.quitting)) return Option.none(); const window = yield* electronWindow.create({ ...initialBounds, - minWidth: 840, - minHeight: 620, + minWidth: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.width, + minHeight: DesktopAppSettings.MIN_MAIN_WINDOW_SIZE.height, show: false, autoHideMenuBar: true, ...(environment.platform === "darwin" ? { disableAutoHideCursor: true } : {}), @@ -407,6 +421,7 @@ export const make = Effect.gen(function* () { sandbox: true, webviewTag: true, // Guest fullscreen propagates to the embedder; both must opt out to keep it inside the webview. + // The app's own fullscreen elements reach OS fullscreen through syncHtmlFullscreen. disableHtmlFullscreenWindowResize: true, }, }); @@ -580,9 +595,10 @@ export const make = Effect.gen(function* () { label: "Copy Image", click: () => { void runPromise( - Effect.tryPromise(() => copyContextMenuImage(contents, params)).pipe( - Effect.catch(() => logWindowWarning("failed to copy context-menu image")), - ), + Effect.tryPromise({ + try: () => copyContextMenuImage(contents, params), + catch: (cause) => new ContextMenuImageCopyError({ cause }), + }).pipe(Effect.catch(() => logWindowWarning("failed to copy context-menu image"))), ); }, }); @@ -661,6 +677,13 @@ export const make = Effect.gen(function* () { }); window.webContents.on("before-input-event", (event, input) => { quitShortcutHandler(event, input); + // Cmd/Ctrl+W reaches the renderer; DevTools uses the native menu shortcut. + window.webContents.setIgnoreMenuShortcuts( + (environment.platform === "darwin" ? input.meta : input.control) && + !input.alt && + !input.shift && + input.key.toLowerCase() === "w", + ); // A held Cmd/Ctrl+W closes one tab or terminal, not each one behind it. if (input.type !== "keyDown" || !input.isAutoRepeat) return; const modifier = environment.platform === "darwin" ? input.meta : input.control; diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f65fc11f59a75..57d6c61f7c43a 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -9,6 +9,7 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { buildRemoteNodeEnvScript } from "@t3tools/ssh/tunnel"; import { satisfiesSemverRange } from "@t3tools/shared/semver"; @@ -1141,7 +1142,8 @@ export const layer = Layer.effect( const environment = yield* DesktopEnvironment.DesktopEnvironment; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const fileSystem = yield* FileSystem.FileSystem; - const windir = process.env.WINDIR ?? "C:\\Windows"; + // Not Config: Windows variable names are case-insensitive only on the live process.env. + const windir = (yield* HostProcess.Environment).WINDIR ?? "C:\\Windows"; const provideSpawner = ( effect: Effect.Effect, diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 1160d9011275d..ba37576815097 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -25,6 +25,12 @@ export default defineConfig({ dependsOn: ["t3#build"], cache: false, }, + // CI bundle jobs skip the Linux browser secret helper; packaging stages one per arch. + "build:bundle": { + command: "node scripts/build-preview-annotation-css.mjs && vp pack", + dependsOn: ["t3#build"], + cache: false, + }, dev: { command: "node scripts/build-browser-secret.mjs && node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch", @@ -41,9 +47,9 @@ export default defineConfig({ dependsOn: ["t3#build"], cache: false, }, - // tsc (tsc-rs) rewrites the tsbuildinfo it reads, which keeps a task out of the cache. + // A local tsbuildinfo is leftover build state, not a typecheck input. typecheck: { - command: "tsc --noEmit", + command: "effect-tsgo tsrs --noEmit", cache: { input: [{ auto: true }, "!*.tsbuildinfo"] }, }, }, @@ -120,7 +126,10 @@ export default defineConfig({ outExtensions: () => ({ js: ".cjs" }), entry: ["src/preview-pick-preload.ts"], deps: { - alwaysBundle: (id) => id === "react-grab" || id.startsWith("react-grab/"), + alwaysBundle: (id) => + id === "react-grab" || + id.startsWith("react-grab/") || + id === "@t3tools/shared/keybindingMatching", }, }, { diff --git a/apps/marketing/astro.config.mjs b/apps/marketing/astro.config.mjs index 15a8a8f916333..45fb17a8e9622 100644 --- a/apps/marketing/astro.config.mjs +++ b/apps/marketing/astro.config.mjs @@ -1,5 +1,7 @@ import { defineConfig } from "astro/config"; +import { LOCALES } from "./src/i18n/locales.ts"; + // Astro loads env with an empty prefix, and under `vp run` Vite+'s loadEnv then reports every // variable to the task cache. Any env difference (TERM, VP_RAW_SUBCOMMAND, an agent's session // vars) would rerun `astro check`. Without the runner client, loadEnv reads process.env directly; @@ -8,6 +10,16 @@ delete process.env.VP_RUN_NODE_CLIENT_PATH; export default defineConfig({ site: "https://t3.codes", + // Vercel 308s `/path/` to `/path` (see vercel.ts), so every internal link and canonical uses one form. + trailingSlash: "never", + // English stays unprefixed at `/`; see src/i18n/locales.ts for each locale's URL segment. + i18n: { + defaultLocale: "en", + locales: LOCALES.map(({ code, path }) => + !path || path === code ? code : { path, codes: [code] }, + ), + routing: { prefixDefaultLocale: false }, + }, server: { port: Number(process.env.PORT ?? 4173), }, diff --git a/apps/marketing/package.json b/apps/marketing/package.json index e37dd8fb7a894..04f6830066a1e 100644 --- a/apps/marketing/package.json +++ b/apps/marketing/package.json @@ -13,7 +13,7 @@ "@fontsource-variable/inter": "^5.3.0", "@t3tools/shared": "workspace:*", "astro": "^7.3.5", - "sharp": "0.35.4" + "sharp": "0.35.5" }, "devDependencies": { "@astrojs/check": "^0.9.10", diff --git a/apps/marketing/public/robots.txt b/apps/marketing/public/robots.txt new file mode 100644 index 0000000000000..495a72e25e4b3 --- /dev/null +++ b/apps/marketing/public/robots.txt @@ -0,0 +1,4 @@ +User-agent: * +Allow: / + +Sitemap: https://t3.codes/sitemap.xml diff --git a/apps/marketing/src/i18n/de.ts b/apps/marketing/src/i18n/de.ts new file mode 100644 index 0000000000000..648b35beebe07 --- /dev/null +++ b/apps/marketing/src/i18n/de.ts @@ -0,0 +1,100 @@ +import type { Messages } from "./en"; + +export const de: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. Die Open-Source-Steuerzentrale für Coding-Agents.", + socialImageAlt: + "T3 Code: die Open-Source-Steuerzentrale für Coding-Agents, mit Claude Code, Codex, Cursor, OpenCode, Grok und Antigravity.", + homeLabel: "Startseite von T3 Code", + download: "Download", + starsLabel: "T3 Code auf GitHub einen Stern geben, {stars} Sterne", + githubStars: "{stars} GitHub-Sterne", + language: "Sprache", + mitLicensed: "MIT-lizenziert", + iosApp: "iOS-App", + androidApp: "Android-App", + terms: "Nutzungsbedingungen", + privacy: "Datenschutz", + security: "Sicherheit", + }, + home: { + title: "T3 Code | Die Open-Source-Steuerzentrale für Coding-Agents", + description: "T3 Code. Die Open-Source-Steuerzentrale für Coding-Agents.", + heroTitle: ["Die Open-Source-", "Steuerzentrale", "für Coding-Agents."], + heroSub: + "Steuere Claude Code, Codex, Antigravity, OpenCode, Cursor und Grok von einer Oberfläche aus. Nutze dein eigenes Abo. Forke das ganze Ding.", + downloadForMac: "Für macOS herunterladen", + downloadForWindows: "Für Windows herunterladen", + downloadForLinux: "Für Linux herunterladen", + sourceLink: "Klau unseren Code (legal)", + alsoOnPhone: "Auch auf deinem Handy:", + screenshotAlt: "T3 Code führt Subagents von Claude, Codex, Muse und Gemini in einem Thread aus", + endorsementsTitle: "Toleriert von über {users} Devs", + endorsementsSub: "Manche haben sogar darüber getwittert.", + endorsementsLabel: "Stimmen von Entwicklern", + readPost: "Beitrag von {handle} auf X lesen", + harnessTitle: "Bring dein eigenes Abo mit", + harnessBody: + "T3 Code verkauft keine Tokens weiter. Verbinde Claude Code, Codex, Antigravity, OpenCode, Cursor oder Grok mit den Zugangsdaten, die du schon hast. Wir orchestrieren sie, du behältst dein Abo.", + googleSignIn: "Google-Anmeldung", + harnessPoints: [ + "Keine weiterverkauften Keys. Keine Kontingentgrenzen.", + "Modell mitten im Thread wechseln.", + "Jede Woche neue Agents.", + ], + gitVisualLabel: + "Illustration des Git-Workflows in T3 Code: Diff prüfen, Änderungen committen und pushen, Pull Request öffnen.", + prReady: "Bereit", + prCommits: "3 Commits", + viewDiff: "Diff ansehen", + openPullRequest: "Pull Request öffnen", + commitPush: "Commit & Push", + gitTitle: "Ein Klick für Commit, Push und PR.", + gitBody: + "Jeder Agent-Thread schreibt in seinen eigenen Branch. Wenn alles passt, öffnet ein Klick den PR auf GitHub, mit generiertem Titel, Beschreibung und Changelog. Kein Terminal-Gefrickel nötig.", + gitPoints: [ + "Automatisch generierte PR-Titel und -Beschreibungen", + "Inline-Diff-Review vor dem Push", + "Draft-PRs, gestapelte PRs, PRs nachbessern", + "Funktioniert mit deinem bestehenden GitHub-Login", + ], + openTitle: "Wenn dir etwas nicht gefällt, forke es.", + openPoints: [ + { lead: "Ändere die UI.", rest: "Gestalte jede Oberfläche nach deinem Geschmack." }, + { lead: "Füge einen Agenten hinzu.", rest: "Binde eigene Tools, Modelle und Abläufe ein." }, + { + lead: "Veröffentliche deinen eigenen Build.", + rest: "Hoste ihn selbst oder vertreibe ihn als deinen eigenen.", + }, + ], + stars: "{stars} Sterne", + forkOnGithub: "Auf GitHub forken", + browseSource: "Quellcode ansehen", + ctaTitle: "Deine Agents verdienen Besseres als ein Terminal.", + ctaSub: + "T3 Code ist kostenlos, Open Source und schnell. Installier es, verbinde das Abo, für das du schon zahlst, und lass deine Agents loslegen.", + otherPlatforms: "Andere Plattformen", + }, + download: { + title: "T3 Code für macOS, Windows und Linux herunterladen | T3 Code", + description: + "Lade die offizielle Desktop-App von T3 Code für macOS, Windows oder Linux herunter, oder hol dir die Apps für iOS und Android. t3.codes ist die einzige offizielle Download-Seite.", + breadcrumb: "Download", + heading: "T3 Code herunterladen", + channelLabel: "Release-Kanal", + stable: "Stable", + nightly: "Nightly", + intelNote: "Mac mit Intel-Chip? {link}.", + intelLink: "Lade den x64-Build herunter", + armNote: "Auf ARM? Lade das {deb} oder {appimage} für arm64 herunter.", + mobile: "Mobil", + iphoneIpad: "iPhone & iPad", + terminal: "Terminal", + tryOnce: "Oder einmal ohne Installation ausprobieren:", + allBuilds: "Alle Builds findest du auf der {link}", + releasesPage: "GitHub-Releases-Seite", + builtAgo: "Erstellt {age}", + releasesFallback: "Releases", + }, +}; diff --git a/apps/marketing/src/i18n/en.ts b/apps/marketing/src/i18n/en.ts new file mode 100644 index 0000000000000..1769d81184c5b --- /dev/null +++ b/apps/marketing/src/i18n/en.ts @@ -0,0 +1,105 @@ +// Source strings. Every other locale must provide the same shape (see `Messages`). +// `{name}` placeholders are filled at render time and must survive translation. +export const en = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. The open-source control plane for coding agents.", + socialImageAlt: + "T3 Code: the open-source control plane for coding agents, with Claude Code, Codex, Cursor, OpenCode, Grok and Antigravity.", + homeLabel: "T3 Code home", + download: "Download", + starsLabel: "Star T3 Code on GitHub, {stars} stars", + githubStars: "{stars} GitHub stars", + language: "Language", + mitLicensed: "MIT licensed", + iosApp: "iOS app", + androidApp: "Android app", + terms: "Terms", + privacy: "Privacy", + security: "Security", + }, + home: { + title: "T3 Code | The open-source control plane for coding agents", + description: "T3 Code. The open-source control plane for coding agents.", + heroTitle: ["The open-source", "control plane", "for coding agents."], + heroSub: + "Orchestrate Claude Code, Codex, Antigravity, OpenCode, Cursor, and Grok from one surface. Bring your own subscription. Fork the whole thing.", + downloadForMac: "Download for macOS", + downloadForWindows: "Download for Windows", + downloadForLinux: "Download for Linux", + sourceLink: "Steal our code (legally)", + alsoOnPhone: "Also on your phone:", + screenshotAlt: "T3 Code running Claude, Codex, Muse, and Gemini subagents in one thread", + endorsementsTitle: "Tolerated by over {users} devs", + endorsementsSub: "Some of them even tweeted about it.", + endorsementsLabel: "Developer endorsements", + readPost: "Read {handle}'s post on X", + harnessTitle: "Bring your own sub", + harnessBody: + "T3 Code doesn't resell tokens. Plug in Claude Code, Codex, Antigravity, OpenCode, Cursor, or Grok with the credentials you already have. We orchestrate them, you keep your plan.", + googleSignIn: "Google sign-in", + harnessPoints: [ + "No keys resold. No quota caps.", + "Switch models mid-thread.", + "More harnesses shipping weekly.", + ], + gitVisualLabel: + "Illustration of the T3 Code Git workflow: review a diff, commit and push changes, and open a pull request.", + prReady: "Ready", + prCommits: "3 commits", + viewDiff: "View diff", + openPullRequest: "Open pull request", + commitPush: "Commit & push", + gitTitle: "One button to commit, push, and make a PR.", + gitBody: + "Every agent thread writes to its own branch. When it's good, one button opens the PR on GitHub with a generated title, body and changelog. No terminal dance required.", + gitPoints: [ + "Auto-generated PR titles & bodies", + "Inline diff review before you push", + "Draft PRs, stack PRs, amend PRs", + "Works with your existing GitHub auth", + ], + openTitle: "If you don't like something, fork it.", + openPoints: [ + { lead: "Change the UI.", rest: "Restyle every surface to match your taste." }, + { lead: "Add an agent.", rest: "Wire in your own tools, models, and flows." }, + { lead: "Ship your own build.", rest: "Self-host it or distribute it as your own." }, + ], + stars: "{stars} stars", + forkOnGithub: "Fork on GitHub", + browseSource: "Browse source", + ctaTitle: "Your agents deserve better than a terminal.", + ctaSub: + "T3 Code is free, open source and fast. Install it, plug in the harness you already pay for, and let your agents get to work.", + otherPlatforms: "Other platforms", + }, + download: { + title: "Download T3 Code for macOS, Windows, and Linux | T3 Code", + description: + "Download the official T3 Code desktop app for macOS, Windows, or Linux, or get the iOS and Android apps. t3.codes is the only official download site.", + breadcrumb: "Download", + heading: "Download T3 Code", + channelLabel: "Release channel", + stable: "Stable", + nightly: "Nightly", + intelNote: "On an Intel Mac? {link}.", + intelLink: "Download the x64 build", + armNote: "On ARM? Download the arm64 {deb} or {appimage}.", + mobile: "Mobile", + iphoneIpad: "iPhone & iPad", + terminal: "Terminal", + tryOnce: "Or try it once without installing:", + allBuilds: "All builds are on the {link}", + releasesPage: "GitHub releases page", + builtAgo: "Built {age}", + releasesFallback: "Releases", + }, +}; + +type Widen = T extends string + ? string + : T extends ReadonlyArray + ? ReadonlyArray> + : { readonly [Key in keyof T]: Widen }; + +export type Messages = Widen; diff --git a/apps/marketing/src/i18n/es.ts b/apps/marketing/src/i18n/es.ts new file mode 100644 index 0000000000000..cb4c28e9871fd --- /dev/null +++ b/apps/marketing/src/i18n/es.ts @@ -0,0 +1,98 @@ +import type { Messages } from "./en"; + +export const es: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: + "T3 Code. El panel de control de código abierto para agentes de programación.", + socialImageAlt: + "T3 Code: el panel de control de código abierto para agentes de programación, con Claude Code, Codex, Cursor, OpenCode, Grok y Antigravity.", + homeLabel: "Inicio de T3 Code", + download: "Descargar", + starsLabel: "Dale una estrella a T3 Code en GitHub, {stars} estrellas", + githubStars: "{stars} estrellas en GitHub", + language: "Idioma", + mitLicensed: "Licencia MIT", + iosApp: "App para iOS", + androidApp: "App para Android", + terms: "Términos", + privacy: "Privacidad", + security: "Seguridad", + }, + home: { + title: "T3 Code | El panel de control de código abierto para agentes de programación", + description: "T3 Code. El panel de control de código abierto para agentes de programación.", + heroTitle: ["El panel de control", "de código abierto", "para agentes de código."], + heroSub: + "Orquesta Claude Code, Codex, Antigravity, OpenCode, Cursor y Grok desde un solo lugar. Usa tu propia suscripción. Haz un fork del proyecto entero.", + downloadForMac: "Descargar para macOS", + downloadForWindows: "Descargar para Windows", + downloadForLinux: "Descargar para Linux", + sourceLink: "Roba nuestro código (legalmente)", + 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.", + endorsementsLabel: "Opiniones de desarrolladores", + readPost: "Leer la publicación de {handle} en X", + harnessTitle: "Trae tu propia suscripción", + harnessBody: + "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.", + "Cambia de modelo a mitad del hilo.", + "Nuevas integraciones cada semana.", + ], + gitVisualLabel: + "Ilustración del flujo de Git en T3 Code: revisar un diff, hacer commit y push de los cambios y abrir un pull request.", + prReady: "Listo", + prCommits: "3 commits", + viewDiff: "Ver diff", + openPullRequest: "Abrir pull request", + commitPush: "Commit y push", + gitTitle: "Un botón para hacer commit, push y abrir un PR.", + gitBody: + "Cada hilo de agente escribe en su propia rama. Cuando está listo, un botón abre el PR en GitHub con título, descripción y changelog generados. Sin malabares en la terminal.", + gitPoints: [ + "Títulos y descripciones de PR generados automáticamente", + "Revisa el diff en la app antes de hacer push", + "Crea PRs en borrador, apílalos o modifícalos", + "Funciona con tu autenticación de GitHub actual", + ], + openTitle: "Si algo no te gusta, haz un fork.", + openPoints: [ + { lead: "Cambia la interfaz.", rest: "Rediseña cada pantalla a tu gusto." }, + { lead: "Añade un agente.", rest: "Integra tus propias herramientas, modelos y flujos." }, + { lead: "Publica tu propia versión.", rest: "Alójala tú mismo o distribúyela como tuya." }, + ], + stars: "{stars} estrellas", + forkOnGithub: "Hacer fork en GitHub", + browseSource: "Ver el código", + ctaTitle: "Tus agentes merecen algo mejor que una terminal.", + ctaSub: + "T3 Code es gratis, de código abierto y rápido. Instálalo, conecta la herramienta que ya pagas y deja que tus agentes se pongan a trabajar.", + otherPlatforms: "Otras plataformas", + }, + download: { + title: "Descarga T3 Code para macOS, Windows y Linux | T3 Code", + description: + "Descarga la app oficial de escritorio de T3 Code para macOS, Windows o Linux, o consigue las apps para iOS y Android. t3.codes es el único sitio oficial de descarga.", + breadcrumb: "Descargar", + heading: "Descargar T3 Code", + channelLabel: "Canal de versiones", + stable: "Estable", + nightly: "Nightly", + intelNote: "¿Tienes un Mac con Intel? {link}.", + intelLink: "Descarga la versión x64", + armNote: "¿Usas ARM? Descarga el {deb} o el {appimage} para arm64.", + mobile: "Móvil", + iphoneIpad: "iPhone y iPad", + terminal: "Terminal", + tryOnce: "O pruébalo sin instalar nada:", + allBuilds: "Todas las compilaciones están en la {link}", + releasesPage: "página de versiones de GitHub", + builtAgo: "Compilada {age}", + releasesFallback: "Versiones", + }, +}; diff --git a/apps/marketing/src/i18n/fr.ts b/apps/marketing/src/i18n/fr.ts new file mode 100644 index 0000000000000..8fd918efc815b --- /dev/null +++ b/apps/marketing/src/i18n/fr.ts @@ -0,0 +1,101 @@ +import type { Messages } from "./en"; + +export const fr: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. Le poste de pilotage open source pour agents de codage.", + socialImageAlt: + "T3 Code : le poste de pilotage open source pour agents de codage, avec Claude Code, Codex, Cursor, OpenCode, Grok et Antigravity.", + homeLabel: "Accueil T3 Code", + download: "Télécharger", + starsLabel: "Mettre une étoile à T3 Code sur GitHub, {stars} étoiles", + githubStars: "{stars} étoiles sur GitHub", + language: "Langue", + mitLicensed: "Licence MIT", + iosApp: "App iOS", + androidApp: "App Android", + terms: "Conditions", + privacy: "Confidentialité", + security: "Sécurité", + }, + home: { + title: "T3 Code | Le poste de pilotage open source pour agents de codage", + description: "T3 Code. Le poste de pilotage open source pour agents de codage.", + heroTitle: ["Le poste de pilotage", "open source", "pour agents de codage."], + heroSub: + "Orchestrez Claude Code, Codex, Antigravity, OpenCode, Cursor et Grok depuis une seule interface. Utilisez votre propre abonnement. Forkez tout le projet.", + downloadForMac: "Télécharger pour macOS", + downloadForWindows: "Télécharger pour Windows", + downloadForLinux: "Télécharger pour Linux", + sourceLink: "Volez notre code (légalement)", + alsoOnPhone: "Aussi sur votre téléphone :", + 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.", + endorsementsLabel: "Avis de développeurs", + readPost: "Lire le post de {handle} sur X", + harnessTitle: "Apportez votre abonnement", + harnessBody: + "T3 Code ne revend pas de tokens. Branchez Claude Code, Codex, Antigravity, OpenCode, Cursor ou Grok avec les identifiants que vous avez déjà. Nous les orchestrons, vous gardez votre abonnement.", + googleSignIn: "Connexion Google", + harnessPoints: [ + "Aucune clé revendue. Aucun quota imposé.", + "Changez de modèle en cours de fil.", + "De nouveaux agents chaque semaine.", + ], + gitVisualLabel: + "Illustration du flux Git de T3 Code : relire un diff, commiter et pousser les modifications, puis ouvrir une pull request.", + prReady: "Prête", + prCommits: "3 commits", + viewDiff: "Voir le diff", + openPullRequest: "Ouvrir la pull request", + commitPush: "Commit et push", + gitTitle: "Un bouton pour commiter, pousser et ouvrir une PR.", + gitBody: + "Chaque fil d'agent écrit dans sa propre branche. Quand c'est bon, un bouton ouvre la PR sur GitHub avec un titre, une description et un changelog générés. Plus besoin de jongler dans le terminal.", + gitPoints: [ + "Titres et descriptions de PR générés automatiquement", + "Revue du diff intégrée avant de pousser", + "PR en brouillon, empilées ou amendées", + "Fonctionne avec votre authentification GitHub actuelle", + ], + openTitle: "Si quelque chose ne vous plaît pas, forkez-le.", + openPoints: [ + { lead: "Changez l'interface.", rest: "Personnalisez chaque écran à votre goût." }, + { lead: "Ajoutez un agent.", rest: "Branchez vos propres outils, modèles et workflows." }, + { + lead: "Publiez votre propre version.", + rest: "Hébergez-le vous-même ou distribuez-le sous votre nom.", + }, + ], + stars: "{stars} étoiles", + forkOnGithub: "Forker sur GitHub", + browseSource: "Parcourir le code", + ctaTitle: "Vos agents méritent mieux qu'un terminal.", + ctaSub: + "T3 Code est gratuit, open source et rapide. Installez-le, branchez l'outil auquel vous êtes déjà abonné et laissez vos agents se mettre au travail.", + otherPlatforms: "Autres plateformes", + }, + download: { + title: "Télécharger T3 Code pour macOS, Windows et Linux | T3 Code", + description: + "Téléchargez l'app de bureau officielle T3 Code pour macOS, Windows ou Linux, ou les apps iOS et Android. t3.codes est le seul site de téléchargement officiel.", + breadcrumb: "Télécharger", + heading: "Télécharger T3 Code", + channelLabel: "Canal de publication", + stable: "Stable", + nightly: "Nightly", + intelNote: "Sur un Mac Intel ? {link}.", + intelLink: "Téléchargez la version x64", + armNote: "Sur ARM ? Téléchargez le {deb} ou l'{appimage} arm64.", + mobile: "Mobile", + iphoneIpad: "iPhone et iPad", + terminal: "Terminal", + tryOnce: "Ou essayez-le sans rien installer :", + allBuilds: "Toutes les versions sont sur la {link}", + releasesPage: "page des releases GitHub", + builtAgo: "Compilé {age}", + releasesFallback: "Versions", + }, +}; diff --git a/apps/marketing/src/i18n/index.ts b/apps/marketing/src/i18n/index.ts new file mode 100644 index 0000000000000..c62950cafe0c9 --- /dev/null +++ b/apps/marketing/src/i18n/index.ts @@ -0,0 +1,24 @@ +import { de } from "./de"; +import { en, type Messages } from "./en"; +import { es } from "./es"; +import { fr } from "./fr"; +import { ja } from "./ja"; +import { ko } from "./ko"; +import type { Locale } from "./locales"; +import { ptBR } from "./pt-BR"; +import { ru } from "./ru"; +import { zh } from "./zh"; + +const MESSAGES: Record = { + en, + es, + "zh-Hans": zh, + "pt-BR": ptBR, + fr, + de, + ja, + ko, + ru, +}; + +export const messagesFor = (locale: Locale): Messages => MESSAGES[locale]; diff --git a/apps/marketing/src/i18n/ja.ts b/apps/marketing/src/i18n/ja.ts new file mode 100644 index 0000000000000..55117b609ac08 --- /dev/null +++ b/apps/marketing/src/i18n/ja.ts @@ -0,0 +1,102 @@ +import type { Messages } from "./en"; + +export const ja: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: + "T3 Code。コーディングエージェントのためのオープンソースのコントロールプレーン。", + socialImageAlt: + "T3 Code:コーディングエージェントのためのオープンソースのコントロールプレーン。Claude Code、Codex、Cursor、OpenCode、Grok、Antigravity に対応。", + homeLabel: "T3 Code ホーム", + download: "ダウンロード", + starsLabel: "GitHub で T3 Code にスターを付ける({stars} スター)", + githubStars: "GitHub スター {stars}", + language: "言語", + mitLicensed: "MIT ライセンス", + iosApp: "iOS アプリ", + androidApp: "Android アプリ", + terms: "利用規約", + privacy: "プライバシー", + security: "セキュリティ", + }, + home: { + title: "T3 Code | コーディングエージェントのためのオープンソースのコントロールプレーン", + description: "T3 Code。コーディングエージェントのためのオープンソースのコントロールプレーン。", + heroTitle: ["コーディングエージェントの", "オープンソース", "コントロールプレーン。"], + heroSub: + "Claude Code、Codex、Antigravity、OpenCode、Cursor、Grok をひとつの画面からオーケストレーション。サブスクリプションは手持ちのものをそのまま。まるごとフォークも自由です。", + downloadForMac: "macOS 版をダウンロード", + downloadForWindows: "Windows 版をダウンロード", + downloadForLinux: "Linux 版をダウンロード", + sourceLink: "コードを盗もう(合法的に)", + alsoOnPhone: "スマホでも使えます:", + screenshotAlt: + "ひとつのスレッドで Claude、Codex、Muse、Gemini のサブエージェントを動かす T3 Code", + endorsementsTitle: "{users} 人以上の開発者が我慢して使っています", + endorsementsSub: "ツイートまでしてくれた人もいます。", + endorsementsLabel: "開発者の声", + readPost: "X で {handle} の投稿を読む", + harnessTitle: "サブスクは持ち込みで", + harnessBody: + "T3 Code はトークンを転売しません。Claude Code、Codex、Antigravity、OpenCode、Cursor、Grok を、すでに持っている認証情報でつなぐだけ。オーケストレーションは私たちに任せて、プランは今のままで。", + googleSignIn: "Google でサインイン", + harnessPoints: [ + "キーの転売なし。使用量の上限なし。", + "スレッドの途中でモデルを切り替え。", + "対応エージェントは毎週追加。", + ], + gitVisualLabel: + "T3 Code の Git ワークフローの図:diff を確認し、変更をコミットしてプッシュし、プルリクエストを作成する。", + prReady: "準備完了", + prCommits: "3 コミット", + viewDiff: "diff を表示", + openPullRequest: "プルリクエストを作成", + commitPush: "コミット&プッシュ", + gitTitle: "ボタンひとつでコミット、プッシュ、PR 作成。", + gitBody: + "エージェントのスレッドはそれぞれ専用のブランチに書き込みます。仕上がったら、ボタンひとつで GitHub に PR を作成。タイトル、本文、変更履歴も自動で生成されます。ターミナルでの面倒な操作は不要です。", + gitPoints: [ + "PR のタイトルと本文を自動生成", + "プッシュ前にインラインで diff をレビュー", + "ドラフト PR、スタック PR、PR の修正", + "既存の GitHub 認証をそのまま利用", + ], + openTitle: "気に入らなければ、フォークすればいい。", + openPoints: [ + { lead: "UI を変える。", rest: "あらゆる画面を好みのスタイルに。" }, + { lead: "エージェントを追加する。", rest: "独自のツール、モデル、フローを組み込めます。" }, + { + lead: "自分のビルドを出す。", + rest: "セルフホストも、自分のアプリとして配布するのも自由です。", + }, + ], + stars: "{stars} スター", + forkOnGithub: "GitHub でフォーク", + browseSource: "ソースを見る", + ctaTitle: "あなたのエージェントに、ターミナルだけではもったいない。", + ctaSub: + "T3 Code は無料、オープンソース、そして高速。インストールして、契約中のツールをつなぐだけ。あとはエージェントにおまかせ。", + otherPlatforms: "ほかのプラットフォーム", + }, + download: { + title: "T3 Code をダウンロード(macOS、Windows、Linux)| T3 Code", + description: + "公式の T3 Code デスクトップアプリ(macOS、Windows、Linux)や、iOS・Android アプリをダウンロードできます。公式のダウンロードサイトは t3.codes だけです。", + breadcrumb: "ダウンロード", + heading: "T3 Code をダウンロード", + channelLabel: "リリースチャンネル", + stable: "安定版", + nightly: "Nightly", + intelNote: "Intel Mac をお使いですか? {link}。", + intelLink: "x64 版をダウンロード", + armNote: "ARM をお使いですか? arm64 版の {deb} または {appimage} をダウンロード。", + mobile: "モバイル", + iphoneIpad: "iPhone と iPad", + terminal: "ターミナル", + tryOnce: "インストールせずに試すなら:", + allBuilds: "すべてのビルドは {link} にあります", + releasesPage: "GitHub のリリースページ", + builtAgo: "{age}にビルド", + releasesFallback: "リリース", + }, +}; diff --git a/apps/marketing/src/i18n/ko.ts b/apps/marketing/src/i18n/ko.ts new file mode 100644 index 0000000000000..f2c09c0af06ac --- /dev/null +++ b/apps/marketing/src/i18n/ko.ts @@ -0,0 +1,97 @@ +import type { Messages } from "./en"; + +export const ko: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. 코딩 에이전트를 위한 오픈 소스 컨트롤 플레인.", + socialImageAlt: + "T3 Code: 코딩 에이전트를 위한 오픈 소스 컨트롤 플레인. Claude Code, Codex, Cursor, OpenCode, Grok, Antigravity 지원.", + homeLabel: "T3 Code 홈", + download: "다운로드", + starsLabel: "GitHub에서 T3 Code에 스타 주기, 현재 스타 {stars}", + githubStars: "GitHub 스타 {stars}", + language: "언어", + mitLicensed: "MIT 라이선스", + iosApp: "iOS 앱", + androidApp: "Android 앱", + terms: "이용약관", + privacy: "개인정보처리방침", + security: "보안", + }, + home: { + title: "T3 Code | 코딩 에이전트를 위한 오픈 소스 컨트롤 플레인", + description: "T3 Code. 코딩 에이전트를 위한 오픈 소스 컨트롤 플레인.", + heroTitle: ["코딩 에이전트용", "오픈 소스", "컨트롤 플레인."], + heroSub: + "Claude Code, Codex, Antigravity, OpenCode, Cursor, Grok을 한 화면에서 오케스트레이션하세요. 구독은 쓰던 그대로. 통째로 포크하세요.", + downloadForMac: "macOS용 다운로드", + downloadForWindows: "Windows용 다운로드", + downloadForLinux: "Linux용 다운로드", + sourceLink: "코드 훔쳐 가기(합법적으로)", + alsoOnPhone: "휴대폰에서도:", + screenshotAlt: "하나의 스레드에서 Claude, Codex, Muse, Gemini 서브에이전트를 실행 중인 T3 Code", + endorsementsTitle: "{users}명이 넘는 개발자가 참고 쓰는 중", + endorsementsSub: "몇몇은 트윗까지 했습니다.", + endorsementsLabel: "개발자 추천", + readPost: "X에서 {handle}님의 게시물 읽기", + harnessTitle: "쓰던 구독 그대로", + harnessBody: + "T3 Code는 토큰을 되팔지 않습니다. 이미 쓰고 있는 계정으로 Claude Code, Codex, Antigravity, OpenCode, Cursor, Grok을 연결하세요. 오케스트레이션은 저희가, 요금제는 그대로.", + googleSignIn: "Google 로그인", + harnessPoints: [ + "키 재판매 없음. 사용량 한도 없음.", + "스레드 도중 모델 전환.", + "매주 새 에이전트 추가.", + ], + gitVisualLabel: + "T3 Code Git 워크플로 그림: diff를 검토하고, 변경 사항을 커밋 및 푸시하고, 풀 리퀘스트를 엽니다.", + prReady: "준비됨", + prCommits: "커밋 3개", + viewDiff: "diff 보기", + openPullRequest: "풀 리퀘스트 열기", + commitPush: "커밋 & 푸시", + gitTitle: "버튼 하나로 커밋, 푸시, PR까지.", + gitBody: + "에이전트 스레드마다 별도 브랜치에서 작업합니다. 결과가 마음에 들면 버튼 하나로 GitHub에 PR이 열리고, 제목과 본문, 변경 로그까지 자동으로 생성됩니다. 터미널에서 씨름할 필요가 없습니다.", + gitPoints: [ + "PR 제목과 본문 자동 생성", + "푸시 전에 인라인 diff 리뷰", + "드래프트 PR, 스택 PR, PR 수정", + "기존 GitHub 인증 그대로 사용", + ], + openTitle: "마음에 안 들면 포크하세요.", + openPoints: [ + { lead: "UI를 바꾸세요.", rest: "모든 화면을 취향대로 꾸밀 수 있습니다." }, + { lead: "에이전트를 추가하세요.", rest: "나만의 도구, 모델, 워크플로를 연결하세요." }, + { lead: "나만의 빌드를 만드세요.", rest: "직접 호스팅하거나 내 이름으로 배포하세요." }, + ], + stars: "스타 {stars}", + forkOnGithub: "GitHub에서 포크", + browseSource: "소스 보기", + ctaTitle: "에이전트를 터미널에만 두기엔 아깝습니다.", + ctaSub: + "T3 Code는 무료이고, 오픈 소스이며, 빠릅니다. 설치하고, 이미 구독 중인 서비스를 연결한 뒤, 에이전트에게 일을 맡기세요.", + otherPlatforms: "다른 플랫폼", + }, + download: { + title: "macOS, Windows, Linux용 T3 Code 다운로드 | T3 Code", + description: + "macOS, Windows, Linux용 공식 T3 Code 데스크톱 앱을 다운로드하거나 iOS 및 Android 앱을 받으세요. 공식 다운로드 사이트는 t3.codes뿐입니다.", + breadcrumb: "다운로드", + heading: "T3 Code 다운로드", + channelLabel: "릴리스 채널", + stable: "안정판", + nightly: "Nightly", + intelNote: "Intel Mac을 쓰시나요? {link}.", + intelLink: "x64 빌드 다운로드", + armNote: "ARM을 쓰시나요? arm64 {deb} 또는 {appimage}를 다운로드하세요.", + mobile: "모바일", + iphoneIpad: "iPhone & iPad", + terminal: "터미널", + tryOnce: "설치 없이 한 번 실행해 보려면:", + allBuilds: "모든 빌드는 {link}에 있습니다", + releasesPage: "GitHub 릴리스 페이지", + builtAgo: "{age} 빌드됨", + releasesFallback: "릴리스", + }, +}; diff --git a/apps/marketing/src/i18n/locales.ts b/apps/marketing/src/i18n/locales.ts new file mode 100644 index 0000000000000..4a2935c8688c9 --- /dev/null +++ b/apps/marketing/src/i18n/locales.ts @@ -0,0 +1,51 @@ +// `code` is Astro's locale code and the BCP 47 tag for `` and hreflang. `path` is the URL +// segment. pt-BR lives at `/pt-br`: lowercase like every other path on the site, with the region +// kept so a future pt-PT can sit beside it. zh is Simplified Chinese. +export const LOCALES = [ + { code: "en", path: "", name: "English" }, + { code: "es", path: "es", name: "Español" }, + { code: "zh-Hans", path: "zh", name: "简体中文" }, + { code: "pt-BR", path: "pt-br", name: "Português (Brasil)" }, + { code: "fr", path: "fr", name: "Français" }, + { code: "de", path: "de", name: "Deutsch" }, + { code: "ja", path: "ja", name: "日本語" }, + { code: "ko", path: "ko", name: "한국어" }, + { code: "ru", path: "ru", name: "Русский" }, +] as const; + +export type Locale = (typeof LOCALES)[number]["code"]; + +export const DEFAULT_LOCALE: Locale = "en"; + +/** Pages that exist in every locale. Legal pages, the 404, and /95 stay English-only. */ +export const LOCALIZED_PATHS = ["/", "/download"] as const; + +export type LocalizedPath = (typeof LOCALIZED_PATHS)[number]; + +export const isLocalizedPath = (path: string): path is LocalizedPath => + (LOCALIZED_PATHS as ReadonlyArray).includes(path); + +export const localeInfo = (locale: Locale) => LOCALES.find((entry) => entry.code === locale)!; + +export const localizedHref = (locale: Locale, path: LocalizedPath): string => { + const prefix = localeInfo(locale).path; + if (!prefix) return path; + return path === "/" ? `/${prefix}` : `/${prefix}${path}`; +}; + +/** `getStaticPaths` entries for a `[...locale]` route: English at the root, the rest prefixed. */ +export const localeStaticPaths = () => + LOCALES.map((entry) => ({ + params: { locale: entry.path || undefined }, + props: { locale: entry.code as Locale }, + })); + +/** Splits `"On ARM? {deb} or {appimage}."` so callers can render each `{key}` as markup. */ +export const templateParts = (template: string): Array => + template + .split(/(\{\w+\})/) + .filter(Boolean) + .map((part) => (/^\{\w+\}$/.test(part) ? { key: part.slice(1, -1) } : part)); + +export const fillTemplate = (template: string, values: Record): string => + template.replace(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match); diff --git a/apps/marketing/src/i18n/pt-BR.ts b/apps/marketing/src/i18n/pt-BR.ts new file mode 100644 index 0000000000000..33841e839c527 --- /dev/null +++ b/apps/marketing/src/i18n/pt-BR.ts @@ -0,0 +1,101 @@ +import type { Messages } from "./en"; + +export const ptBR: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. O painel de controle open source para agentes de programação.", + socialImageAlt: + "T3 Code: o painel de controle open source para agentes de programação, com Claude Code, Codex, Cursor, OpenCode, Grok e Antigravity.", + homeLabel: "Página inicial do T3 Code", + download: "Baixar", + starsLabel: "Dê uma estrela ao T3 Code no GitHub, {stars} estrelas", + githubStars: "{stars} estrelas no GitHub", + language: "Idioma", + mitLicensed: "Licença MIT", + iosApp: "App para iOS", + androidApp: "App para Android", + terms: "Termos", + privacy: "Privacidade", + security: "Segurança", + }, + home: { + title: "T3 Code | O painel de controle open source para agentes de programação", + description: "T3 Code. O painel de controle open source para agentes de programação.", + heroTitle: ["O painel de controle", "open source para", "agentes de código."], + heroSub: + "Orquestre Claude Code, Codex, Antigravity, OpenCode, Cursor e Grok em um só lugar. Use a sua própria assinatura. Faça um fork do projeto inteiro.", + downloadForMac: "Baixar para macOS", + downloadForWindows: "Baixar para Windows", + downloadForLinux: "Baixar para Linux", + sourceLink: "Roube nosso código (legalmente)", + alsoOnPhone: "Também no seu celular:", + screenshotAlt: + "T3 Code executando subagentes do Claude, Codex, Muse e Gemini em uma mesma thread", + endorsementsTitle: "Tolerado por mais de {users} devs", + endorsementsSub: "Alguns até tuitaram sobre isso.", + endorsementsLabel: "Depoimentos de desenvolvedores", + readPost: "Ler o post de {handle} no X", + harnessTitle: "Traga sua própria assinatura", + harnessBody: + "O T3 Code não revende tokens. Conecte Claude Code, Codex, Antigravity, OpenCode, Cursor ou Grok com as credenciais que você já tem. Nós orquestramos, você mantém seu plano.", + googleSignIn: "Login com Google", + harnessPoints: [ + "Sem revenda de chaves. Sem limite de cota.", + "Troque de modelo no meio da thread.", + "Novos agentes toda semana.", + ], + gitVisualLabel: + "Ilustração do fluxo de Git no T3 Code: revisar um diff, fazer commit e push das alterações e abrir um pull request.", + prReady: "Pronto", + prCommits: "3 commits", + viewDiff: "Ver diff", + openPullRequest: "Abrir pull request", + commitPush: "Commit e push", + gitTitle: "Um botão para fazer commit, push e abrir um PR.", + gitBody: + "Cada thread de agente escreve no seu próprio branch. Quando estiver bom, um botão abre o PR no GitHub com título, descrição e changelog gerados. Sem malabarismo no terminal.", + gitPoints: [ + "Títulos e descrições de PR gerados automaticamente", + "Revisão do diff inline antes do push", + "PRs em rascunho, stacks de PRs e amend", + "Funciona com a sua autenticação atual do GitHub", + ], + openTitle: "Se não gostar de algo, faça um fork.", + openPoints: [ + { lead: "Mude a interface.", rest: "Redesenhe cada tela do seu jeito." }, + { lead: "Adicione um agente.", rest: "Integre suas próprias ferramentas, modelos e fluxos." }, + { + lead: "Lance sua própria versão.", + rest: "Hospede por conta própria ou distribua como sua.", + }, + ], + stars: "{stars} estrelas", + forkOnGithub: "Fazer fork no GitHub", + 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 a assinatura que você já tem e deixe seus agentes trabalharem.", + otherPlatforms: "Outras plataformas", + }, + download: { + title: "Baixe o T3 Code para macOS, Windows e Linux | T3 Code", + description: + "Baixe o app oficial de desktop do T3 Code para macOS, Windows ou Linux, ou os apps para iOS e Android. t3.codes é o único site oficial de download.", + breadcrumb: "Baixar", + heading: "Baixar o T3 Code", + channelLabel: "Canal de versões", + stable: "Estável", + nightly: "Nightly", + intelNote: "Tem um Mac com Intel? {link}.", + intelLink: "Baixe a versão x64", + armNote: "Usa ARM? Baixe o {deb} ou o {appimage} para arm64.", + mobile: "Mobile", + iphoneIpad: "iPhone e iPad", + terminal: "Terminal", + tryOnce: "Ou experimente uma vez sem instalar:", + allBuilds: "Todas as versões estão na {link}", + releasesPage: "página de releases do GitHub", + builtAgo: "Compilado {age}", + releasesFallback: "Versões", + }, +}; diff --git a/apps/marketing/src/i18n/ru.ts b/apps/marketing/src/i18n/ru.ts new file mode 100644 index 0000000000000..8fdeefdb9fadd --- /dev/null +++ b/apps/marketing/src/i18n/ru.ts @@ -0,0 +1,97 @@ +import type { Messages } from "./en"; + +export const ru: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code. Открытый пульт управления ИИ-агентами для программирования.", + socialImageAlt: + "T3 Code: открытый пульт управления ИИ-агентами для программирования. Claude Code, Codex, Cursor, OpenCode, Grok и Antigravity.", + homeLabel: "Главная страница T3 Code", + download: "Скачать", + starsLabel: "Поставить звезду T3 Code на GitHub, звёзд: {stars}", + githubStars: "{stars} звёзд на GitHub", + language: "Язык", + mitLicensed: "Лицензия MIT", + iosApp: "Приложение для iOS", + androidApp: "Приложение для Android", + terms: "Условия", + privacy: "Конфиденциальность", + security: "Безопасность", + }, + home: { + title: "T3 Code | Открытый пульт управления ИИ-агентами для программирования", + description: "T3 Code. Открытый пульт управления ИИ-агентами для программирования.", + heroTitle: ["Открытый пульт", "управления", "ИИ-агентами для кода."], + heroSub: + "Управляйте Claude Code, Codex, Antigravity, OpenCode, Cursor и Grok из одного окна. Пользуйтесь своей подпиской. Форкайте всё целиком.", + downloadForMac: "Скачать для macOS", + downloadForWindows: "Скачать для Windows", + downloadForLinux: "Скачать для Linux", + sourceLink: "Украдите наш код (легально)", + alsoOnPhone: "Есть и для телефона:", + screenshotAlt: "T3 Code запускает субагентов Claude, Codex, Muse и Gemini в одном треде", + endorsementsTitle: "Нас терпят более {users} разработчиков", + endorsementsSub: "Некоторые даже написали об этом в X.", + endorsementsLabel: "Отзывы разработчиков", + readPost: "Читать пост {handle} в X", + harnessTitle: "Со своей подпиской", + harnessBody: + "T3 Code не перепродаёт токены. Подключайте Claude Code, Codex, Antigravity, OpenCode, Cursor или Grok с учётными данными, которые у вас уже есть. Мы управляем агентами, тариф остаётся вашим.", + googleSignIn: "Вход через Google", + harnessPoints: [ + "Никакой перепродажи ключей. Никаких лимитов.", + "Меняйте модель прямо посреди треда.", + "Новые агенты каждую неделю.", + ], + gitVisualLabel: + "Схема работы с Git в T3 Code: просмотр диффа, коммит и пуш изменений, создание пул-реквеста.", + prReady: "Готово", + prCommits: "3 коммита", + viewDiff: "Открыть дифф", + openPullRequest: "Создать пул-реквест", + commitPush: "Коммит и пуш", + gitTitle: "Одна кнопка для коммита, пуша и PR.", + gitBody: + "Каждый тред агента работает в своей ветке. Когда всё готово, одна кнопка открывает PR на GitHub со сгенерированным заголовком, описанием и списком изменений. Никаких плясок с терминалом.", + gitPoints: [ + "Автоматические заголовки и описания PR", + "Просмотр диффа перед пушем", + "Черновые PR, стеки PR, правки PR", + "Работает с вашей текущей авторизацией GitHub", + ], + openTitle: "Что-то не нравится? Форкните.", + openPoints: [ + { lead: "Измените интерфейс.", rest: "Перерисуйте каждый экран на свой вкус." }, + { lead: "Добавьте агента.", rest: "Подключите свои инструменты, модели и сценарии." }, + { lead: "Выпустите свою сборку.", rest: "Хостите сами или распространяйте как свою." }, + ], + stars: "{stars} звёзд", + forkOnGithub: "Форкнуть на GitHub", + browseSource: "Исходный код", + ctaTitle: "Ваши агенты заслуживают лучшего, чем терминал.", + ctaSub: + "T3 Code бесплатный, открытый и быстрый. Установите его, подключите подписку, за которую уже платите, и дайте агентам поработать.", + otherPlatforms: "Другие платформы", + }, + download: { + title: "Скачать T3 Code для macOS, Windows и Linux | T3 Code", + description: + "Скачайте официальное десктопное приложение T3 Code для macOS, Windows или Linux либо приложения для iOS и Android. Единственный официальный сайт для загрузки: t3.codes.", + breadcrumb: "Скачать", + heading: "Скачать T3 Code", + channelLabel: "Канал релизов", + stable: "Стабильный", + nightly: "Nightly", + intelNote: "Mac на Intel? {link}.", + intelLink: "Скачайте сборку x64", + armNote: "На ARM? Скачайте {deb} или {appimage} для arm64.", + mobile: "Телефон", + iphoneIpad: "iPhone и iPad", + terminal: "Терминал", + tryOnce: "Или попробуйте без установки:", + allBuilds: "Все сборки на {link}", + releasesPage: "странице релизов GitHub", + builtAgo: "Собрано {age}", + releasesFallback: "Релизы", + }, +}; diff --git a/apps/marketing/src/i18n/zh.ts b/apps/marketing/src/i18n/zh.ts new file mode 100644 index 0000000000000..bae711530051a --- /dev/null +++ b/apps/marketing/src/i18n/zh.ts @@ -0,0 +1,95 @@ +import type { Messages } from "./en"; + +export const zh: Messages = { + layout: { + defaultTitle: "T3 Code", + defaultDescription: "T3 Code:面向编程智能体的开源控制中心。", + socialImageAlt: + "T3 Code:面向编程智能体的开源控制中心,支持 Claude Code、Codex、Cursor、OpenCode、Grok 和 Antigravity。", + homeLabel: "T3 Code 首页", + download: "下载", + starsLabel: "在 GitHub 上为 T3 Code 加星标,已有 {stars} 个星标", + githubStars: "{stars} GitHub 星标", + language: "语言", + mitLicensed: "MIT 许可", + iosApp: "iOS 应用", + androidApp: "Android 应用", + terms: "条款", + privacy: "隐私", + security: "安全", + }, + home: { + title: "T3 Code | 面向编程智能体的开源控制中心", + description: "T3 Code:面向编程智能体的开源控制中心。", + heroTitle: ["开源的", "编程智能体", "控制中心。"], + heroSub: + "在同一个界面里调度 Claude Code、Codex、Antigravity、OpenCode、Cursor 和 Grok。用你自己的订阅。整个项目都可以 fork。", + downloadForMac: "下载 macOS 版", + downloadForWindows: "下载 Windows 版", + downloadForLinux: "下载 Linux 版", + sourceLink: "来偷我们的代码(合法的)", + alsoOnPhone: "手机上也能用:", + screenshotAlt: "T3 Code 在同一个线程中运行 Claude、Codex、Muse 和 Gemini 子智能体", + endorsementsTitle: "超过 {users} 名开发者表示还能忍", + endorsementsSub: "有些人甚至发推夸了它。", + endorsementsLabel: "开发者评价", + readPost: "在 X 上阅读 {handle} 的帖子", + harnessTitle: "自带订阅", + harnessBody: + "T3 Code 不转售 token。用你现有的凭据接入 Claude Code、Codex、Antigravity、OpenCode、Cursor 或 Grok。我们负责调度,你的套餐还是你的。", + googleSignIn: "Google 登录", + harnessPoints: [ + "不转售密钥,不设额度上限。", + "线程进行中也能切换模型。", + "每周都有新的智能体接入。", + ], + gitVisualLabel: "T3 Code Git 工作流示意图:审查 diff、提交并推送更改、创建 PR。", + prReady: "就绪", + prCommits: "3 个提交", + viewDiff: "查看 diff", + openPullRequest: "创建 PR", + commitPush: "提交并推送", + gitTitle: "一键提交、推送并创建 PR。", + gitBody: + "每个智能体线程都写入自己的分支。满意之后,一键在 GitHub 上创建 PR,标题、描述和更新日志都会自动生成。不用在终端里来回折腾。", + gitPoints: [ + "自动生成 PR 标题和描述", + "推送前就地审查 diff", + "草稿 PR、堆叠 PR、修改 PR", + "沿用你现有的 GitHub 授权", + ], + openTitle: "哪里不喜欢,就 fork 它。", + openPoints: [ + { lead: "改 UI。", rest: "按你的喜好重新设计每个界面。" }, + { lead: "加智能体。", rest: "接入你自己的工具、模型和工作流。" }, + { lead: "发布你自己的版本。", rest: "自行托管,或以你自己的名义分发。" }, + ], + stars: "{stars} 星标", + forkOnGithub: "在 GitHub 上 fork", + browseSource: "浏览源码", + ctaTitle: "终端配不上你的智能体。", + ctaSub: "T3 Code 免费、开源、速度快。安装它,接入你已经订阅的智能体,然后让它们开工。", + otherPlatforms: "其他平台", + }, + download: { + title: "下载 T3 Code:macOS、Windows 和 Linux 版 | T3 Code", + description: + "下载 T3 Code 官方桌面应用(macOS、Windows 或 Linux),或获取 iOS 和 Android 应用。t3.codes 是唯一的官方下载网站。", + breadcrumb: "下载", + heading: "下载 T3 Code", + channelLabel: "发布通道", + stable: "稳定版", + nightly: "Nightly 版", + intelNote: "使用 Intel 芯片的 Mac?{link}。", + intelLink: "下载 x64 版本", + armNote: "ARM 架构?下载 arm64 版 {deb} 或 {appimage}。", + mobile: "移动端", + iphoneIpad: "iPhone 和 iPad", + terminal: "终端", + tryOnce: "或者无需安装,直接试用一次:", + allBuilds: "所有版本都在 {link}上", + releasesPage: "GitHub 发布页面", + builtAgo: "{age}构建", + releasesFallback: "发布页面", + }, +}; diff --git a/apps/marketing/src/layouts/Layout.astro b/apps/marketing/src/layouts/Layout.astro index d1aea12f09bc9..bd5d3e00a2f81 100644 --- a/apps/marketing/src/layouts/Layout.astro +++ b/apps/marketing/src/layouts/Layout.astro @@ -9,18 +9,52 @@ import { IOS_APP_STORE_URL, MARKETING_STATS, } from "../lib/site"; +import { type JsonLd, jsonLdGraph, organizationJsonLd, websiteJsonLd } from "../lib/seo"; +import { messagesFor } from "../i18n"; +import { + DEFAULT_LOCALE, + fillTemplate, + LOCALES, + type Locale, + localeInfo, + type LocalizedPath, + localizedHref, + templateParts, +} from "../i18n/locales"; interface Props { title?: string; description?: string; pageClass?: string; + /** Page-specific schema.org nodes. Organization and WebSite are always included. */ + jsonLd?: ReadonlyArray; + noindex?: boolean; + locale?: Locale; + /** Set when the page exists in every locale; enables the language picker and hreflang links. */ + localizedPath?: LocalizedPath; } +const { locale = DEFAULT_LOCALE, localizedPath } = Astro.props; +const t = messagesFor(locale).layout; const { - title = "T3 Code", - description = "T3 Code. The open-source control plane for coding agents.", + title = t.defaultTitle, + description = t.defaultDescription, pageClass, + jsonLd = [], + noindex = false, } = Astro.props; +const currentLocale = localeInfo(locale); +const homeHref = localizedHref(locale, "/"); +const downloadHref = localizedHref(locale, "/download"); +// English-only pages still declare themselves, so every page carries hreflang and x-default. +const alternates = localizedPath + ? LOCALES.map((entry) => ({ + hreflang: entry.code, + href: new URL(localizedHref(entry.code, localizedPath), Astro.site).href, + })) + : [{ hreflang: DEFAULT_LOCALE, href: new URL(Astro.url.pathname, Astro.site).href }]; +const defaultAlternate = alternates.find((entry) => entry.hreflang === DEFAULT_LOCALE)!; +const structuredData = jsonLdGraph([organizationJsonLd(), websiteJsonLd(), ...jsonLd]); // Link unfurlers require a 1200x630 JPG/PNG at an absolute URL. const socialImage = await getImage({ @@ -31,17 +65,16 @@ const socialImage = await getImage({ quality: 90, }); const socialImageUrl = new URL(socialImage.src, Astro.site); -const socialImageAlt = - "T3 Code: the open-source control plane for coding agents, with Claude Code, Codex, Cursor, OpenCode, Grok and Antigravity."; +const socialImageAlt = t.socialImageAlt; const canonicalUrl = new URL(Astro.url.pathname, Astro.site); --- - + - + {noindex ? : } @@ -61,13 +94,17 @@ const canonicalUrl = new URL(Astro.url.pathname, Astro.site); + + {alternates.map((entry) => )} + {title} + @@ -420,6 +504,88 @@ const canonicalUrl = new URL(Astro.url.pathname, Astro.site); flex-shrink: 0; } + .nav-lang { + position: relative; + } + + .nav-lang-trigger { + display: inline-flex; + align-items: center; + gap: 7px; + height: 36px; + padding: 0 10px; + color: var(--fg-muted); + font-size: 13px; + letter-spacing: -0.01em; + white-space: nowrap; + list-style: none; + cursor: pointer; + transition: color 0.18s ease; + } + + .nav-lang-trigger::-webkit-details-marker { + display: none; + } + + .nav-lang-trigger svg { + flex-shrink: 0; + } + + .nav-lang-trigger:hover, + .nav-lang[open] .nav-lang-trigger { + color: var(--fg); + } + + .nav-lang-chevron { + opacity: 0.6; + transition: transform 0.18s ease; + } + + .nav-lang[open] .nav-lang-chevron { + transform: rotate(180deg); + } + + .nav-lang-menu { + position: absolute; + top: calc(100% + 6px); + right: 0; + min-width: 200px; + padding: 6px; + list-style: none; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + background: var(--bg-card); + box-shadow: 0 12px 32px -16px rgba(0, 0, 0, 0.65); + animation: fade-in 0.18s ease both; + } + + .nav-lang-menu a { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 7px 10px; + border-radius: 6px; + color: var(--fg-muted); + font-size: 13px; + white-space: nowrap; + transition: color 0.18s ease, background 0.18s ease; + } + + .nav-lang-menu a:hover { + color: var(--fg); + background: rgba(255, 255, 255, 0.04); + } + + .nav-lang-menu a[aria-current="true"] { + color: var(--fg); + } + + .nav-lang-menu svg { + color: var(--ok); + flex-shrink: 0; + } + .main { flex: 1; display: flex; @@ -485,6 +651,12 @@ const canonicalUrl = new URL(Astro.url.pathname, Astro.site); display: none; } + /* The trigger sits near the left on narrow screens, so the menu opens rightward. */ + .nav-lang-menu { + right: auto; + left: 0; + } + .footer { padding-bottom: max(32px, env(safe-area-inset-bottom)); } @@ -509,6 +681,16 @@ const canonicalUrl = new URL(Astro.url.pathname, Astro.site); gap: 12px; } + .nav-lang-current, + .nav-lang-chevron { + display: none; + } + + .nav-lang-trigger { + height: 34px; + padding: 0 8px; + } + .nav-stars { height: 34px; gap: 6px; diff --git a/apps/marketing/src/lib/seo.ts b/apps/marketing/src/lib/seo.ts new file mode 100644 index 0000000000000..452d53338689c --- /dev/null +++ b/apps/marketing/src/lib/seo.ts @@ -0,0 +1,79 @@ +import { ANDROID_PLAY_STORE_URL, GITHUB_REPOSITORY_URL, IOS_APP_STORE_URL } from "./site"; + +export const SITE_ORIGIN = "https://t3.codes"; +export const SITE_NAME = "T3 Code"; +export const SITE_TAGLINE = "The open-source control plane for coding agents"; + +// The canonical set of official properties. Search engines and AI answer engines read `sameAs` +// to tie an entity to its real homes, which is the signal a look-alike domain cannot copy. +export const OFFICIAL_PROFILES = [ + GITHUB_REPOSITORY_URL, + IOS_APP_STORE_URL, + ANDROID_PLAY_STORE_URL, + "https://discord.gg/jn4EGJjrvv", +] as const; + +export type JsonLd = Record; + +const ORGANIZATION_ID = `${SITE_ORIGIN}/#organization`; +const WEBSITE_ID = `${SITE_ORIGIN}/#website`; +const SOFTWARE_ID = `${SITE_ORIGIN}/#software`; + +export const absoluteUrl = (pathname: string): string => new URL(pathname, SITE_ORIGIN).href; + +export const organizationJsonLd = (): JsonLd => ({ + "@type": "Organization", + "@id": ORGANIZATION_ID, + name: "T3 Tools Inc", + url: SITE_ORIGIN, + logo: absoluteUrl("/apple-touch-icon.png"), + sameAs: ["https://github.com/pingdotgg"], +}); + +export const websiteJsonLd = (): JsonLd => ({ + "@type": "WebSite", + "@id": WEBSITE_ID, + name: SITE_NAME, + url: SITE_ORIGIN, + publisher: { "@id": ORGANIZATION_ID }, +}); + +export const softwareJsonLd = (): JsonLd => ({ + "@type": "SoftwareApplication", + "@id": SOFTWARE_ID, + name: SITE_NAME, + description: `${SITE_NAME}. ${SITE_TAGLINE}.`, + url: SITE_ORIGIN, + downloadUrl: absoluteUrl("/download"), + applicationCategory: "DeveloperApplication", + operatingSystem: "macOS, Windows, Linux, iOS, Android", + license: "https://opensource.org/license/mit", + isAccessibleForFree: true, + offers: { "@type": "Offer", price: "0", priceCurrency: "USD" }, + publisher: { "@id": ORGANIZATION_ID }, + sameAs: [...OFFICIAL_PROFILES], +}); + +export const breadcrumbJsonLd = (items: ReadonlyArray<{ name: string; path: string }>): JsonLd => ({ + "@type": "BreadcrumbList", + itemListElement: items.map((item, index) => ({ + "@type": "ListItem", + position: index + 1, + name: item.name, + item: absoluteUrl(item.path), + })), +}); + +export const jsonLdGraph = (nodes: ReadonlyArray): string => + // `<` is escaped so page text inside the graph can never close the script tag. + JSON.stringify({ "@context": "https://schema.org", "@graph": nodes }).replace(/ { + const body = [ + "Contact: mailto:security@t3.codes", + `Policy: ${absoluteUrl("/security-policy")}`, + `Canonical: ${absoluteUrl("/.well-known/security.txt")}`, + "Preferred-Languages: en", + `Expires: ${new Date(Date.now() + ONE_YEAR_MS).toISOString()}`, + "", + ].join("\n"); + return new Response(body, { headers: { "Content-Type": "text/plain; charset=utf-8" } }); +}; diff --git a/apps/marketing/src/pages/404.astro b/apps/marketing/src/pages/404.astro new file mode 100644 index 0000000000000..3bc695c7b60e9 --- /dev/null +++ b/apps/marketing/src/pages/404.astro @@ -0,0 +1,44 @@ +--- +import Layout from "../layouts/Layout.astro"; +--- + + +
+

404

+

This page does not exist.

+

+ t3.codes is the only official T3 Code website. Download builds from this site, GitHub releases, + or the app stores. +

+ +
+
+ + diff --git a/apps/marketing/src/pages/download.astro b/apps/marketing/src/pages/[...locale]/download.astro similarity index 89% rename from apps/marketing/src/pages/download.astro rename to apps/marketing/src/pages/[...locale]/download.astro index 494ad60ef94e4..5a3828f968865 100644 --- a/apps/marketing/src/pages/download.astro +++ b/apps/marketing/src/pages/[...locale]/download.astro @@ -1,11 +1,19 @@ --- import type { ComponentProps } from "astro/types"; import { Image } from "astro:assets"; -import iconStable from "../assets/icon.webp"; -import iconNightly from "../assets/icon-nightly.webp"; -import Layout from "../layouts/Layout.astro"; -import { RELEASES_URL } from "../lib/releases"; -import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site"; +import iconStable from "../../assets/icon.webp"; +import iconNightly from "../../assets/icon-nightly.webp"; +import Layout from "../../layouts/Layout.astro"; +import { RELEASES_URL } from "../../lib/releases"; +import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../../lib/site"; +import { breadcrumbJsonLd, softwareJsonLd } from "../../lib/seo"; +import { messagesFor } from "../../i18n"; +import { localeStaticPaths, localizedHref, templateParts } from "../../i18n/locales"; + +export const getStaticPaths = localeStaticPaths; + +const { locale } = Astro.props; +const t = messagesFor(locale).download; const imageProps = { alt: "", @@ -16,8 +24,26 @@ const imageProps = { } satisfies Partial>; --- - -
+ +
@@ -25,12 +51,12 @@ const imageProps = { -

Download T3 Code

+

{t.heading}

-
+
- - + +

@@ -58,7 +84,9 @@ const imageProps = {

- On an Intel Mac? Download the x64 build. + {templateParts(t.intelNote).map((part) => + typeof part === "string" ? part : {t.intelLink}, + )}

@@ -109,8 +137,11 @@ const imageProps = {

- On ARM? Download the arm64 .deb or - AppImage. + {templateParts(t.armNote).map((part) => + typeof part === "string" ? part + : part.key === "deb" ? .deb + : AppImage, + )}

@@ -118,12 +149,12 @@ const imageProps = {
-

Mobile

+

{t.mobile}

- iPhone & iPad + {t.iphoneIpad} App Store @@ -139,29 +170,32 @@ const imageProps = {
-

Terminal

+

{t.terminal}

curl -fsSL https://t3.codes/install.sh | sh irm https://t3.codes/install.ps1 | iex curl -fsSL https://t3.codes/install.sh | T3CODE_CHANNEL=nightly sh $env:T3CODE_CHANNEL="nightly"; irm https://t3.codes/install.ps1 | iex -

Or try it once without installing:

+

{t.tryOnce}

npx t3@latest npx t3@nightly
& > 😀\u00a0end\n", + ); + const html = selectableSourceHtml(source.contents, { + foreground: "#000000", + selection: "#3366ff", + fontSize: 14, + rowHeight: 24, + wordBreak: true, + }); + const page = new DOMParser().parseFromString(html, "text/html"); + + expect(page.querySelector("script")).toBeNull(); + expect(page.body.textContent).toBe("\n\tlead\n & > 😀\u00a0end\n"); + expect(page.getElementById("L2")?.textContent).toBe("\tlead"); +}); diff --git a/apps/mobile/src/features/files/source-file-document.ts b/apps/mobile/src/features/files/source-file-document.ts index 2c4c275b85a18..98c10de0d12fd 100644 --- a/apps/mobile/src/features/files/source-file-document.ts +++ b/apps/mobile/src/features/files/source-file-document.ts @@ -66,3 +66,28 @@ export function boundedSelectableSourceTokens( } return tokens; } + +export interface SelectableSourceHtmlStyle { + readonly foreground: string; + readonly selection: string; + readonly fontSize: number; + readonly rowHeight: number; + readonly wordBreak: boolean; +} + +// A
 would drop a leading newline, so whitespace is preserved on a plain 
. +export function selectableSourceHtml(contents: string, style: SelectableSourceHtmlStyle): string { + const text = contents + .split("\n") + .map( + (line, index) => + `${line.replace(/[&<>]/g, (char) => + char === "&" ? "&" : char === "<" ? "<" : ">", + )}`, + ) + .join("\n"); + const wrap = style.wordBreak + ? "white-space:pre-wrap;overflow-wrap:anywhere" + : "white-space:pre;width:max-content"; + return `
${text}
`; +} diff --git a/apps/mobile/src/features/files/sourceHighlightingState.ts b/apps/mobile/src/features/files/sourceHighlightingState.ts index 2a2db842ec4be..5dcc5eff50511 100644 --- a/apps/mobile/src/features/files/sourceHighlightingState.ts +++ b/apps/mobile/src/features/files/sourceHighlightingState.ts @@ -1,5 +1,6 @@ import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import { resolveHighlightLanguage } from "../../lib/highlightLanguage"; @@ -15,9 +16,10 @@ export interface SourceHighlightInput { class SourceHighlightCacheKey extends Data.Class {} -class SourceHighlightError extends Data.TaggedError("SourceHighlightError")<{ - readonly cause: unknown; -}> {} +class SourceHighlightError extends Schema.TaggedError()( + "SourceHighlightError", + { cause: Schema.Defect() }, +) {} // Highlighting is synchronous, so a cold atom resolves on its first read. The // family keeps results for files the user moves between. diff --git a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx index 0c3d3f772a8c0..2fd52284106be 100644 --- a/apps/mobile/src/features/files/thread-file-navigator-pane.tsx +++ b/apps/mobile/src/features/files/thread-file-navigator-pane.tsx @@ -1,46 +1,27 @@ import { resolveFilesystemReadAccess } from "@t3tools/client-runtime/state/filesystem"; import { environmentSession } from "../../state/session"; import type { EnvironmentId } from "@t3tools/contracts"; -import { SymbolView } from "../../components/ui/AppSymbol"; +import { AppBar } from "../../components/ui/AppBar"; import { ScreenContent } from "../../components/ui/ScreenContent"; -import { useState, type ComponentProps } from "react"; -import { Platform, Pressable, View, type NativeSyntheticEvent } from "react-native"; -import { - Screen, - ScreenStack, - ScreenStackHeaderConfig, - ScreenStackHeaderSearchBarView, - SearchBar, -} from "react-native-screens"; +import { useState } from "react"; +import { View } from "react-native"; -import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; -import { FilesHeader } from "./FilesHeader"; -import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader"; -import { useUniwindTheme } from "../../lib/useUniwindTheme"; import { useEnvironmentQuery } from "../../state/query"; import { useEnvironmentPresentation } from "../../state/presentation"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { FileTreeBrowser } from "./FileTreeBrowser"; -import { NativeInspectorContent } from "../../native/NativeInspectorContent"; import { useFileTreeEntries } from "./useFileTreeEntries"; import { preloadWorkspaceFileContents } from "./preload-workspace-file"; -import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; export function ThreadFileNavigatorPane(props: { readonly cwd: string; readonly environmentId: EnvironmentId; - readonly headerInset: number; readonly projectName: string; readonly selectedPath: string | null; readonly onSelectFile: (path: string) => void; }) { const [searchQuery, setSearchQuery] = useState(""); - const { toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout(); const { themeAppearance: highlightTheme } = useAppearancePreferences(); - const theme = useUniwindTheme(); - const foregroundColor = theme["--color-foreground"]; - const sheetColor = theme["--color-sheet"]; - const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); const fileAccessSession = useEnvironmentQuery( environmentSession.sessionStateAtom(props.environmentId), ); @@ -65,18 +46,6 @@ export function ThreadFileNavigatorPane(props: { theme: highlightTheme, }); }; - const nativeHeaderRightBarButtonItems = [ - { - accessibilityLabel: "Close files", - icon: { name: "xmark", type: "sfSymbol" as const }, - identifier: "thread-file-navigator-close", - onPress: toggleAuxiliaryPane, - sharesBackground: false, - tintColor: foregroundColor, - type: "button" as const, - }, - ] as ComponentProps["headerRightBarButtonItems"]; - const fileTree = ( ); - if (Platform.OS === "ios") { - return ( - - - - {fileTree} - - - { - setSearchQuery(""); - }} - onChangeText={(event: NativeSyntheticEvent<{ readonly text?: string }>) => { - setSearchQuery(event.nativeEvent.text ?? ""); - }} - placement="integratedButton" - placeholder="Search files" - textColor={foregroundColor} - tintColor={foregroundColor} - /> - - - - - - ); - } - return ( - - - {Platform.OS === "android" ? ( - - ) : ( - - - Files - - {props.projectName} - - - - - - - )} - {Platform.OS !== "android" ? ( - - - - - ) : null} - + + {fileTree} ); diff --git a/apps/mobile/src/features/files/useFileTreeEntries.test.tsx b/apps/mobile/src/features/files/useFileTreeEntries.test.tsx index 8d707fd379a83..e7f0f2d4136af 100644 --- a/apps/mobile/src/features/files/useFileTreeEntries.test.tsx +++ b/apps/mobile/src/features/files/useFileTreeEntries.test.tsx @@ -141,6 +141,10 @@ vi.mock("react-native", () => ({ vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: Nothing })); vi.mock("../../native/native-layout-metrics", () => ({ useNativeColumnLayoutMetrics: () => null })); +vi.mock("../../components/ui/useBarInset", () => ({ + useContentTopInset: () => 0, + useContentBottomInset: () => 0, +})); vi.mock("@legendapp/list/react-native", () => ({ LegendList: (props: { data: ReadonlyArray; diff --git a/apps/mobile/src/features/files/useFileTreeEntries.ts b/apps/mobile/src/features/files/useFileTreeEntries.ts index 62c2e33746a9f..53354bc640db7 100644 --- a/apps/mobile/src/features/files/useFileTreeEntries.ts +++ b/apps/mobile/src/features/files/useFileTreeEntries.ts @@ -2,6 +2,7 @@ import { useAtomMount, useAtomSubscribe } from "@effect/atom-react"; import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; import { ProjectListEntriesError, type EnvironmentId, type ProjectEntry } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Schema from "effect/Schema"; import { useLayoutEffect, useRef, useState } from "react"; import { Atom } from "effect/reactivity"; @@ -11,6 +12,8 @@ import { projectEnvironment } from "../../state/projects"; import { useDebouncedValue } from "../../state/queries"; import { useEnvironmentQuery } from "../../state/query"; +const isProjectListEntriesError = Schema.is(ProjectListEntriesError); + function createDirectories() { return { target: {}, @@ -273,8 +276,7 @@ export function useFileTreeEntries(input: { }); }; const missingRoot = - root.failure instanceof ProjectListEntriesError && - root.failure.failure === "workspace_root_not_found"; + isProjectListEntriesError(root.failure) && root.failure.failure === "workspace_root_not_found"; const rootData = missingRoot ? null : root.data; const rootListing = root.successResult ?? directories.rootListing; if ( diff --git a/apps/mobile/src/features/home/AndroidHomeFab.android.tsx b/apps/mobile/src/features/home/AndroidHomeFab.android.tsx index bc1fe6af518a2..b5c86e3295c7b 100644 --- a/apps/mobile/src/features/home/AndroidHomeFab.android.tsx +++ b/apps/mobile/src/features/home/AndroidHomeFab.android.tsx @@ -15,9 +15,9 @@ import { useWorkspaceState } from "../../state/workspace"; import { FabScrollContext } from "./FabScrollContext"; import { updateFabScroll } from "./fab-scroll"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { WorkspaceTabsContext, useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; -import { FLOATING_TABS, floatingTabsMetrics } from "../workspace/floating-workspace-tabs"; -import { useEnabledNavigationTabs } from "../workspace/navigation-tabs"; +import { WorkspaceTabsContext, useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; +import { FLOATING_TABS, floatingTabsMetrics } from "../layout/workspace/floating-workspace-tabs"; +import { useEnabledNavigationTabs } from "../layout/workspace/navigation-tabs"; import { useAppearancePreferences, useAndroidFloatingTabs, diff --git a/apps/mobile/src/features/home/HomeHeader.android.tsx b/apps/mobile/src/features/home/HomeHeader.android.tsx deleted file mode 100644 index 1d984c2f0fd3c..0000000000000 --- a/apps/mobile/src/features/home/HomeHeader.android.tsx +++ /dev/null @@ -1,98 +0,0 @@ -import type { MenuAction } from "@react-native-menu/menu"; -import { NativeStackScreenOptions } from "../../native/StackHeader"; -import { ThreadListToolbar } from "./ThreadListToolbar"; -import type { HomeHeaderProps } from "./HomeHeader.types"; - -export type { HomeHeaderEnvironment } from "./HomeHeader.types"; - -function checkedMenuState(checked: boolean) { - return checked ? ("on" as const) : undefined; -} - -export function HomeHeader(props: HomeHeaderProps) { - const hasCustomListOptions = - props.selectedEnvironmentId !== null || props.selectedProjectKey !== null; - const menuActions: MenuAction[] = [ - { - id: "environment", - title: "Environment", - subactions: [ - { - id: "environment:all", - title: "All environments", - state: checkedMenuState(props.selectedEnvironmentId === null), - }, - ...props.environments.map((environment) => ({ - id: `environment:${environment.environmentId}`, - title: environment.label, - state: checkedMenuState(props.selectedEnvironmentId === environment.environmentId), - })), - ], - }, - ...(props.projects.length === 0 - ? [] - : ([ - { - id: "project", - title: "Project", - subactions: [ - { - id: "project:all", - title: "All projects", - state: checkedMenuState(props.selectedProjectKey === null), - }, - ...props.projects.map((project) => ({ - id: `project:${project.key}`, - title: project.label, - state: checkedMenuState(props.selectedProjectKey === project.key), - })), - ], - }, - ] satisfies MenuAction[])), - ]; - const handleMenuAction = (event: { nativeEvent: { event: string } }) => { - const id = event.nativeEvent.event; - if (id === "environment:all") { - props.onEnvironmentChange(null); - return; - } - - if (id.startsWith("environment:")) { - const environmentId = id.slice("environment:".length); - const environment = props.environments.find( - (candidate) => candidate.environmentId === environmentId, - ); - if (environment) { - props.onEnvironmentChange(environment.environmentId); - } - return; - } - - if (id === "project:all") { - props.onProjectChange(null); - return; - } - - if (id.startsWith("project:")) { - const projectKey = id.slice("project:".length); - if (props.projects.some((project) => project.key === projectKey)) { - props.onProjectChange(projectKey); - } - return; - } - }; - - return ( - <> - - - - ); -} diff --git a/apps/mobile/src/features/home/HomeHeader.tsx b/apps/mobile/src/features/home/HomeHeader.tsx deleted file mode 100644 index 2062c518afef3..0000000000000 --- a/apps/mobile/src/features/home/HomeHeader.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import type { HomeHeaderProps } from "./HomeHeader.types"; - -export type { HomeHeaderEnvironment } from "./HomeHeader.types"; - -/** The iOS thread list lives in the workspace, whose WorkspaceToolbar owns its header and search. */ -export function HomeHeader(_props: HomeHeaderProps) { - return null; -} diff --git a/apps/mobile/src/features/home/HomeHeader.types.ts b/apps/mobile/src/features/home/HomeHeader.types.ts deleted file mode 100644 index 3c5f580f9eefb..0000000000000 --- a/apps/mobile/src/features/home/HomeHeader.types.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { EnvironmentId } from "@t3tools/contracts"; -import type { - HomeListFilterMenuEnvironment, - HomeListFilterMenuProject, -} from "./home-list-filter-menu"; - -export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment; - -export interface HomeHeaderProps { - readonly environments: ReadonlyArray; - readonly projects: ReadonlyArray; - readonly searchQuery: string; - readonly selectedEnvironmentId: EnvironmentId | null; - readonly selectedProjectKey: string | null; - readonly onSearchQueryChange: (query: string) => void; - readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void; - readonly onProjectChange: (projectKey: string | null) => void; - readonly onOpenEnvironments: () => void; - readonly onOpenSettings: () => void; - readonly onStartNewTask: () => void; -} diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index c522da701e75c..99ede8afe7c4a 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -1,13 +1,12 @@ import { uuidv4 } from "../../lib/uuid"; import { ThreadUndoNotice } from "./ThreadUndoNotice"; -import { Toolbar } from "../../components/ui/Toolbar"; import { use } from "react"; import { NativePrimaryColumnContext } from "../../native/v5-workspace-context"; import * as Arr from "effect/Array"; import * as Order from "effect/Order"; import { useNavigation } from "@react-navigation/native"; import { useMemo, useState } from "react"; -import { Platform, useWindowDimensions } from "react-native"; +import { Platform } from "react-native"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { @@ -15,37 +14,30 @@ import { resolveScratchProjectScopeKey, } from "@t3tools/client-runtime/state/project-grouping"; -import { NativeStackScreenOptions } from "../../native/StackHeader"; import { useProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; import { usePendingNewTasks } from "../../state/use-pending-new-tasks"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout"; -import { useDeviceType, useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics"; -import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail"; -import { AndroidScreenHeader } from "../../components/ui/AndroidScreenHeader"; import { AndroidHomeFabLayout } from "./AndroidHomeFab"; import { HomeScreen } from "./HomeScreen"; -import { HomeHeader } from "./HomeHeader"; import { useHomeListOptions } from "./home-list-options"; import { useAtomValueWhileVisible, useHomeRouteVisible } from "./home-route-visibility"; import { buildHomeProjectScopes } from "./homeThreadList"; import { usePendingTaskListActions } from "./usePendingTaskListActions"; import { useThreadListActions } from "./useThreadListActions"; -import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle"; -import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; +import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; import { openSettings } from "../settings/settings-navigation"; -import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab"; -import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail"; +import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab"; +import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; +import { WorkspaceListEmptyDetail } from "../layout/workspace/WorkspaceListEmptyDetail"; +import { WorkspaceListHeader } from "../layout/workspace/WorkspaceListHeader"; +import { buildHomeListFilterMenuItems } from "./home-list-filter-menu"; export function HomeRouteScreen() { - const { width: windowWidth } = useWindowDimensions(); const nativePrimaryColumn = use(NativePrimaryColumnContext); - const columnMetrics = useNativeColumnLayoutMetrics(); - const deviceType = useDeviceType(); - const headerWidth = nativePrimaryColumn ? (columnMetrics?.width ?? windowWidth) : windowWidth; - const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery, startNewTask } = + const { layout, primarySidebarSearchQuery, setPrimarySidebarSearchQuery, startNewTask } = useAdaptiveWorkspaceLayout(); const selectDetail = useSelectWorkspaceDetail(); const projects = useProjects(); @@ -161,77 +153,37 @@ export function HomeRouteScreen() { if (layout.usesSplitView && !nativePrimaryColumn) { return ( - <> - [], - headerSearchBarOptions: undefined, - unstable_headerRightItems: () => [], - unstable_headerToolbarItems: () => [], - } - } - /> - {Platform.OS === "ios" ? ( - - - - ) : null} - {Platform.OS === "android" ? : null} - openSettings(navigation, "SettingsEnvironmentNew") - : undefined - } - onStartNewTask={ - Platform.OS === "android" && panes.primarySidebarVisible ? undefined : startNewTask - } - /> - + openSettings(navigation, "SettingsEnvironmentNew")} + onStartNewTask={startNewTask} + /> ); } return ( - + <> - {/* Screen options merge shallowly; restore the header after split view. */} - {workspace !== null && Platform.OS === "ios" ? null : ( - openSettings(navigation, "SettingsEnvironments"), - }), - headerShown: Platform.OS !== "android", - }} - /> - )} - openSettings(navigation, "SettingsEnvironments")} - onOpenSettings={() => selectTab("settings")} - onSearchQueryChange={setSearchQuery} - onStartNewTask={startNewTask} + search={{ + value: searchQuery, + onChangeText: setSearchQuery, + placeholder: "Search", + accessibilityLabel: "Search threads", + }} + filter={{ + customized: selectedEnvironmentId !== null || selectedProjectKey !== null, + items: buildHomeListFilterMenuItems({ + environments, + projects: projectFilterOptions, + selectedEnvironmentId, + selectedProjectKey, + onEnvironmentChange: setSelectedEnvironmentId, + onProjectChange: setSelectedProjectKey, + }), + }} /> ) { const primaryColumn = use(NativePrimaryColumnContext); + const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null; if (Platform.OS !== "ios") return ; // Register the scroll view explicitly; layout and header siblings hide it from UIKit. @@ -229,7 +233,7 @@ function HomeScrollView(props: ComponentProps) { ); @@ -245,7 +249,8 @@ export function HomeScreen(props: HomeScreenProps) { const workspace = useWorkspaceTabs(); const [initialScrollOffset] = useState(() => workspace?.getScrollOffset("threads") ?? 0); const primaryColumn = use(NativePrimaryColumnContext); - const contentBackground = primaryColumn ? "bg-drawer" : "bg-screen"; + const sidebarSurface = usePaneRole() === "sidebar" && primaryColumn !== null; + const contentBackground = sidebarSurface ? "bg-drawer" : "bg-screen"; const containerClassName = cn( "flex-1", Platform.OS === "android" ? "bg-header" : contentBackground, @@ -258,6 +263,8 @@ export function HomeScreen(props: HomeScreenProps) { const openSwipeableRef = useRef(null); const homeScrollGesture = useNativeGesture(); const insets = useSafeAreaInsets(); + const contentTopInset = useContentTopInset(); + const emptyTopInset = useWorkspaceListEmptyTopInset(); const { fabClearance } = useAndroidControlSizing(); const screenMetrics = useNativeLayoutMetrics(); const contentSideInsets = usesNativeWorkspaceColumns @@ -321,7 +328,7 @@ export function HomeScreen(props: HomeScreenProps) { useSearchScrollRestoration(searchMode, () => { if (restoredOffset === undefined) return; void listRef.current?.scrollToOffset({ - offset: restoredOffset - (Platform.OS === "ios" ? insets.top : 0), + offset: restoredOffset - contentTopInset, animated: false, }); }); @@ -342,7 +349,7 @@ export function HomeScreen(props: HomeScreenProps) { if (workspace) workspace.recordScrollOffset( "threads", - Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)), + Math.max(0, event.nativeEvent.contentOffset.y + contentTopInset), ); clearTimeout(activationTimerRef.current); activationTimerRef.current = setTimeout( @@ -507,7 +514,7 @@ export function HomeScreen(props: HomeScreenProps) { ); return ( - - - - ) : undefined - } - variant="plain" - /> - {emptyState.loading ? ( - - - - ) : null} + + + + + ) : undefined + } + variant="plain" + /> + {emptyState.loading ? ( + + + + ) : null} + - + ); } @@ -719,7 +732,7 @@ export function HomeScreen(props: HomeScreenProps) { {listHeader} {Platform.OS === "ios" && workspace ? ( ({ key: scope.key, @@ -763,97 +776,89 @@ export function HomeScreen(props: HomeScreenProps) { if (Platform.OS === "android" && threadListV2Items.length === 0) { return ( - + {v2ListEmpty} - + ); } return ( - - - - activateVisibleRows(threadListV2Items)} - onTouchStart={(event) => trackListTouches(event, true)} - onTouchEnd={(event) => trackListTouches(event, false)} - onTouchCancel={(event) => trackListTouches(event, false)} - renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined} - data={threadListV2Items} - renderItem={renderV2Item} - keyExtractor={v2KeyExtractor} - getItemType={(item) => item.type} - itemsAreEqual={threadListV2ListItemsAreEqual} - estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT} - drawDistance={THREAD_LIST_V2_DRAW_DISTANCE} - recycleItems - extraData={v2ExtraData} - ListHeaderComponent={v2ListHeader} - ListFooterComponent={ - settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? ( - { - olderSettledShelf.retry(); - showMoreSettled(); - }} - /> - ) : null - } - ListEmptyComponent={v2ListEmpty} - style={{ flex: 1 }} - automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"} - // UIKit owns the bar's inset, so a minimizing bar and a resized column move - // the list in the same frame as the bar. - contentInsetAdjustmentBehavior="automatic" - contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0} - // RN scrollTo clamps against raw insets and ignores the automatic bar inset. - scrollToOverflowEnabled - initialScrollOffset={ - initialScrollOffset > 0 - ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0) - : undefined - } - showsVerticalScrollIndicator={false} - keyboardDismissMode="on-drag" - keyboardShouldPersistTaps="handled" - {...scrollGateHandlers} - scrollEventThrottle={16} - contentContainerStyle={{ - paddingLeft: - (contentSideInsets?.left ?? 0) + (primaryColumn ? 8 : 0) + androidListGutter, - paddingRight: - (contentSideInsets?.right ?? 0) + (primaryColumn ? 8 : 0) + androidListGutter, - paddingBottom: - Platform.OS === "ios" - ? iosBottomClearance - (columnMetrics?.safeArea.bottom ?? insets.bottom) - : (workspace?.bottomClearance ?? - Math.max(insets.bottom, 16) + - (Platform.OS === "android" ? fabClearance : 88)), - }} - /> - - - + + + + + activateVisibleRows(threadListV2Items)} + onTouchStart={(event) => trackListTouches(event, true)} + onTouchEnd={(event) => trackListTouches(event, false)} + onTouchCancel={(event) => trackListTouches(event, false)} + renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined} + data={threadListV2Items} + renderItem={renderV2Item} + keyExtractor={v2KeyExtractor} + getItemType={(item) => item.type} + itemsAreEqual={threadListV2ListItemsAreEqual} + estimatedItemSize={ESTIMATED_THREAD_LIST_V2_ROW_HEIGHT} + drawDistance={THREAD_LIST_V2_DRAW_DISTANCE} + recycleItems + extraData={v2ExtraData} + ListHeaderComponent={v2ListHeader} + // Lifted above the rows so an iOS filter menu's dismissal morph is not covered. + ListHeaderComponentStyle={{ zIndex: 1 }} + ListFooterComponent={ + settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? ( + { + olderSettledShelf.retry(); + showMoreSettled(); + }} + /> + ) : null + } + ListEmptyComponent={v2ListEmpty} + style={{ flex: 1 }} + automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"} + contentInsetAdjustmentBehavior="never" + contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined} + initialScrollOffset={ + initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined + } + showsVerticalScrollIndicator={false} + keyboardDismissMode="on-drag" + keyboardShouldPersistTaps="handled" + {...scrollGateHandlers} + scrollEventThrottle={16} + contentContainerStyle={{ + paddingLeft: + (contentSideInsets?.left ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter, + paddingRight: + (contentSideInsets?.right ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter, + paddingBottom: + Platform.OS === "ios" + ? iosBottomClearance + : (workspace?.bottomClearance ?? + Math.max(insets.bottom, 16) + + (Platform.OS === "android" ? fabClearance : 88)), + }} + /> + + + + ); } diff --git a/apps/mobile/src/features/home/ThreadListFilters.tsx b/apps/mobile/src/features/home/ThreadListFilters.tsx index a7d6894c35d91..196e6a86480b5 100644 --- a/apps/mobile/src/features/home/ThreadListFilters.tsx +++ b/apps/mobile/src/features/home/ThreadListFilters.tsx @@ -1,22 +1,22 @@ import { Pressable, ScrollView } from "react-native"; import { SymbolView } from "../../components/ui/AppSymbol"; -import { ListFilterMenu } from "../workspace/ListFilterMenu"; -import type { HomeHeaderProps } from "./HomeHeader.types"; +import { ListFilterMenu } from "../layout/workspace/ListFilterMenu"; +import type { EnvironmentId } from "@t3tools/contracts"; +import type { + HomeListFilterMenuEnvironment, + HomeListFilterMenuProject, +} from "./home-list-filter-menu"; -export function ThreadListFilters( - props: Pick< - HomeHeaderProps, - | "environments" - | "projects" - | "selectedEnvironmentId" - | "selectedProjectKey" - | "onEnvironmentChange" - | "onProjectChange" - > & { - /** List padding the scroller bleeds through so pills start where row content does. */ - readonly gutter: number; - }, -) { +export function ThreadListFilters(props: { + readonly environments: ReadonlyArray; + readonly projects: ReadonlyArray; + readonly selectedEnvironmentId: EnvironmentId | null; + readonly selectedProjectKey: string | null; + readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void; + readonly onProjectChange: (projectKey: string | null) => void; + /** List padding the scroller bleeds through so pills start where row content does. */ + readonly gutter: number; +}) { const selectedEnvironment = props.environments.find( (environment) => environment.environmentId === props.selectedEnvironmentId, ); @@ -27,7 +27,7 @@ export function ThreadListFilters( void; - readonly filterActions: MenuAction[]; - readonly filterCustomized: boolean; - readonly onFilterAction: NonNullable["onPressAction"]>; - readonly onOpenEnvironments: () => void; - readonly sidebar?: boolean; - readonly onLayout?: (event: LayoutChangeEvent) => void; - readonly onRequestVisibility?: () => void; -}) { - const navigation = useNavigation(); - const workspace = useWorkspaceTabs(); - const isTabActive = workspace?.isTabActive; - const homeFocused = useNavigationState((state) => state.routes[state.index]?.name === "Home"); - const listFocused = - homeFocused && (workspace === null || workspace.state.selectedTab === "threads"); - const { paddingTop, paddingBottom } = useToolbarLayout(); - const connectionState = useWorkspaceConnectionState(); - const { onRequestVisibility, onSearchQueryChange } = props; - const searchRef = useRef(null); - const [searchOpen, setSearchOpen] = useState(false); - const searching = searchOpen || props.searchQuery.length > 0; - const openSearch = () => { - onRequestVisibility?.(); - setSearchOpen(true); - searchRef.current?.focus(); - return true; - }; - useHardwareKeyboardCommand("focusSearch", openSearch); - - const closeSearch = () => { - onSearchQueryChange(""); - setSearchOpen(false); - Keyboard.dismiss(); - }; - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to BackHandler while searching to close search on Android back - useEffect(() => { - if (!searching || !listFocused) return; - const subscription = BackHandler.addEventListener("hardwareBackPress", () => { - // Frozen Home screens can keep effects alive after a detail route opens. - const state = navigation.getState(); - if ( - !state || - state.routes[state.index]?.name !== "Home" || - isTabActive?.("threads") === false - ) - return false; - if (Keyboard.isVisible()) Keyboard.dismiss(); - else closeSearch(); - return true; - }); - return () => subscription.remove(); - }, [closeSearch, searching, listFocused, navigation, isTabActive]); - - const filterIcon = props.filterCustomized - ? "line.3.horizontal.decrease.circle.fill" - : "line.3.horizontal.decrease.circle"; - const searchField = ( - - ); - const filterButton = connectionState.hasConnections ? ( - - {(open) => ( - - )} - - ) : null; - - return ( - - - - ); -} diff --git a/apps/mobile/src/features/home/ThreadUndoNotice.tsx b/apps/mobile/src/features/home/ThreadUndoNotice.tsx index 364873a3eadeb..caeb47a3c2195 100644 --- a/apps/mobile/src/features/home/ThreadUndoNotice.tsx +++ b/apps/mobile/src/features/home/ThreadUndoNotice.tsx @@ -10,8 +10,8 @@ import { useNativeLayoutMetrics, useNativeColumnLayoutMetrics, } from "../../native/native-layout-metrics"; -import { workspaceSearchBottomClearance } from "../workspace/workspace-tabs-state"; -import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; +import { workspaceSearchBottomClearance } from "../layout/workspace/workspace-tabs-state"; +import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; import { dismissThreadUndoNotice, readThreadUndoNotice, diff --git a/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx b/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx index 58cf4138483a2..540831ad18f0e 100644 --- a/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx +++ b/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx @@ -1,4 +1,3 @@ -import type { NativeStackNavigationOptions } from "@react-navigation/native-stack"; import { createContext, use, useEffect, useState, type ReactNode } from "react"; import { Animated, Platform, Pressable, View } from "react-native"; @@ -6,11 +5,6 @@ import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { - brandTitleOffset, - CompactBrandTitle, - getCompactBrandHeaderOptions, -} from "../../components/CompactBrandTitle"; import { useDeadlinePassed } from "../../lib/clock"; import { useWorkspaceState } from "../../state/workspace"; import { @@ -159,24 +153,3 @@ export function WorkspaceConnectionTitle(props: { ); } - -export function getConnectionAwareBrandHeaderOptions(opts: { - readonly headerWidth: number; - readonly trailingItemCount?: number; - readonly onOpenEnvironments: () => void; - readonly fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"]; -}): NativeStackNavigationOptions { - const maxWidth = Math.max(0, opts.headerWidth - 64 - 44 * (opts.trailingItemCount ?? 1)); - - return { - ...getCompactBrandHeaderOptions(opts.fallbackTitleStyle), - headerTitle: () => ( - } - maxWidth={maxWidth} - onPress={opts.onOpenEnvironments} - statusOffset={brandTitleOffset()} - /> - ), - }; -} diff --git a/apps/mobile/src/features/home/home-list-filter-menu.ts b/apps/mobile/src/features/home/home-list-filter-menu.ts index ac53e427d21f3..617c3fa0988ef 100644 --- a/apps/mobile/src/features/home/home-list-filter-menu.ts +++ b/apps/mobile/src/features/home/home-list-filter-menu.ts @@ -1,5 +1,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; +import type { AppBarMenuItem } from "../../components/ui/AppBar.types"; + export interface HomeListFilterMenuEnvironment { readonly environmentId: EnvironmentId; readonly label: string; @@ -10,82 +12,57 @@ export interface HomeListFilterMenuProject { readonly label: string; } -type HomeListFilterMenuAction = { - readonly type: "action"; - readonly title: string; - readonly subtitle?: string; - readonly state?: "on" | "off"; - readonly onPress: () => void; -}; - -type HomeListFilterMenuSubmenu = { - readonly type: "submenu"; - readonly title: string; - readonly items: HomeListFilterMenuAction[]; -}; - -export interface HomeListFilterMenu { - readonly title: string; - readonly items: Array; -} - -export function buildHomeListFilterMenu(props: { +export function buildHomeListFilterMenuItems(props: { readonly environments: ReadonlyArray; readonly projects: ReadonlyArray; readonly selectedEnvironmentId: EnvironmentId | null; readonly selectedProjectKey: string | null; readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void; readonly onProjectChange: (projectKey: string | null) => void; -}): HomeListFilterMenu { - const items: Array = []; - - items.push({ - type: "submenu", - title: "Environment", - items: [ - { - type: "action", - title: "All environments", - subtitle: "Show threads from every environment", - state: props.selectedEnvironmentId === null ? "on" : "off", - onPress: () => props.onEnvironmentChange(null), - }, - ...props.environments.map((environment) => ({ - type: "action" as const, - title: environment.label, - state: - props.selectedEnvironmentId === environment.environmentId - ? ("on" as const) - : ("off" as const), - onPress: () => props.onEnvironmentChange(environment.environmentId), - })), - ], - }); +}): AppBarMenuItem[] { + const items: AppBarMenuItem[] = [ + { + id: "environment", + title: "Environment", + items: [ + { + id: "environment:all", + title: "All environments", + subtitle: "Show threads from every environment", + selected: props.selectedEnvironmentId === null, + onPress: () => props.onEnvironmentChange(null), + }, + ...props.environments.map((environment) => ({ + id: `environment:${environment.environmentId}`, + title: environment.label, + selected: props.selectedEnvironmentId === environment.environmentId, + onPress: () => props.onEnvironmentChange(environment.environmentId), + })), + ], + }, + ]; if (props.projects.length > 0) { items.push({ - type: "submenu", + id: "project", title: "Project", items: [ { - type: "action", + id: "project:all", title: "All projects", subtitle: "Show threads from every project", - state: props.selectedProjectKey === null ? "on" : "off", + selected: props.selectedProjectKey === null, onPress: () => props.onProjectChange(null), }, ...props.projects.map((project) => ({ - type: "action" as const, + id: `project:${project.key}`, title: project.label, - state: props.selectedProjectKey === project.key ? ("on" as const) : ("off" as const), + selected: props.selectedProjectKey === project.key, onPress: () => props.onProjectChange(project.key), })), ], }); } - return { - title: "Thread list options", - items, - }; + return items; } diff --git a/apps/mobile/src/features/home/thread-swipe-actions.tsx b/apps/mobile/src/features/home/thread-swipe-actions.tsx index a6c48086f2c85..6f2e8a7a9020f 100644 --- a/apps/mobile/src/features/home/thread-swipe-actions.tsx +++ b/apps/mobile/src/features/home/thread-swipe-actions.tsx @@ -391,10 +391,10 @@ export function ThreadSwipeable(props: ThreadSwipeableProps) { } }, [commitPrimaryAction, content, fullSwipeAction, onDelete]); const handleRelease = useCallback( - (translation: SharedValue) => { + (translation: SharedValue, canceled: boolean) => { "worklet"; if (dismissing.value) return true; - if (-translation.value >= fullSwipeThreshold) { + if (!canceled && -translation.value >= fullSwipeThreshold) { runOnJS(commitFullSwipe)(); return true; } diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index 248c436905311..3893569c6886d 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -308,9 +308,7 @@ export function useThreadListActions(): { if (!canSnooze(thread, { now: new Date().toISOString() })) { Dialog.alert( "Could not snooze thread", - thread.hasPendingApprovals || - thread.hasPendingUserInput || - thread.pendingSubagentRequest != null + thread.hasPendingApprovals || thread.pendingSubagentRequest != null ? "This thread is waiting on you. Respond to the pending request before snoozing it." : "This thread is still starting a turn. Try again once it's running.", ); diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx index e9e9e50d4527f..198ac724f526c 100644 --- a/apps/mobile/src/features/keyboard/CommandPalette.tsx +++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx @@ -71,8 +71,8 @@ import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareK import { threadJumpIndex } from "./threadKeyboardShortcuts"; import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs"; import { openSettings } from "../settings/settings-navigation"; -import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab"; -import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail"; +import { useSelectWorkspaceTab } from "../layout/workspace/useSelectWorkspaceTab"; +import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail"; const PALETTE_COMMANDS: ReadonlyArray = [ "commandPalette", diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx index 135715f064924..98fba788bbd31 100644 --- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx +++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx @@ -18,7 +18,7 @@ import { copyThreadReference } from "../../lib/copyThreadReference"; import { firstWorkspaceDetailOpen, workspaceHasColumns, -} from "../workspace/workspace-selection-store"; +} from "../layout/workspace/workspace-selection-store"; import { T3KeyboardCommands } from "../../native/T3KeyboardCommands"; import { useThreadShell } from "../../state/entities"; import type { GitActionProgress } from "../../state/use-vcs-action-state"; @@ -32,7 +32,7 @@ import { subscribeToHardwareKeyboardCommandRegistrations, type HardwareKeyboardCommand, } from "./hardwareKeyboardCommands"; -import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection"; +import { selectWorkspaceDetail } from "../layout/workspace/workspace-detail-selection"; const EMPTY_COPY_FEEDBACK: GitActionProgress = { phase: "idle", diff --git a/apps/mobile/src/features/keyboard/keyboardControllerState.test.tsx b/apps/mobile/src/features/keyboard/keyboardControllerState.test.tsx new file mode 100644 index 0000000000000..f628e495f9e29 --- /dev/null +++ b/apps/mobile/src/features/keyboard/keyboardControllerState.test.tsx @@ -0,0 +1,84 @@ +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import type { KeyboardEventData } from "react-native-keyboard-controller"; +import { expect, it, vi } from "vite-plus/test"; + +const listeners = vi.hoisted(() => new Map void>>()); + +// Exercises the patched library source with only its native bindings replaced. +vi.mock("react-native-keyboard-controller/src/bindings", () => ({ + KeyboardEvents: { + addListener: (name: string, listener: (event: KeyboardEventData) => void) => { + const named = listeners.get(name) ?? new Set(); + named.add(listener); + listeners.set(name, named); + return { remove: () => named.delete(listener) }; + }, + }, + KeyboardControllerNative: { dismiss: () => {} }, +})); + +import { useKeyboardState } from "react-native-keyboard-controller/src/hooks/useKeyboardState"; +import { KeyboardController } from "react-native-keyboard-controller/src/module"; + +function emit(name: string, height: number) { + const event: KeyboardEventData = { + height, + duration: 0, + timestamp: 1, + target: 42, + type: "default", + appearance: "light", + }; + act(() => { + for (const listener of listeners.get(name) ?? []) listener(event); + }); +} + +function KeyboardState() { + const { isVisible, height } = useKeyboardState(); + return {JSON.stringify({ isVisible, height })}; +} + +// The library keeps keyboard state at module scope; every test starts and ends hidden. +function setup() { + emit("keyboardDidHide", 0); + return { [Symbol.dispose]: () => emit("keyboardDidHide", 0) }; +} + +function renderKeyboardState() { + const container = document.createElement("div"); + const root = createRoot(container); + act(() => root.render()); + return { container, [Symbol.dispose]: () => act(() => root.unmount()) }; +} + +// Android's syncKeyboardPosition repairs a nonanimated IME inset change with +// keyboardDidHide then keyboardDidShow, and no keyboardWillShow. +it("reports the keyboard shown after Android repairs the IME inset without keyboardWillShow", () => { + using _keyboard = setup(); + using screen = renderKeyboardState(); + + emit("keyboardDidShow", 376); + + expect({ + isVisible: KeyboardController.isVisible(), + height: KeyboardController.state().height, + hook: JSON.parse(screen.container.textContent ?? ""), + }).toEqual({ isVisible: true, height: 376, hook: { isVisible: true, height: 376 } }); +}); + +it("waits for the native hide before dismiss resolves after a didShow-only repair", async () => { + using _keyboard = setup(); + emit("keyboardDidShow", 376); + + let dismissed = false; + const dismissal = KeyboardController.dismiss().then(() => { + dismissed = true; + }); + await act(async () => {}); + + expect(dismissed).toBe(false); + emit("keyboardDidHide", 0); + await dismissal; +}); diff --git a/apps/mobile/src/features/keyboard/useSoftKeyboardShowing.ts b/apps/mobile/src/features/keyboard/useSoftKeyboardShowing.ts new file mode 100644 index 0000000000000..b7956524a10f3 --- /dev/null +++ b/apps/mobile/src/features/keyboard/useSoftKeyboardShowing.ts @@ -0,0 +1,26 @@ +import { useSyncExternalStore } from "react"; +import { KeyboardController, KeyboardEvents } from "react-native-keyboard-controller"; + +// `useKeyboardState` only flips on willShow and didHide. This follows the will-events, so a +// layout that makes room for the keyboard gives it back as soon as the keyboard starts hiding. +let keyboardShowing = KeyboardController.isVisible(); +function subscribeKeyboardShowing(onChange: () => void) { + keyboardShowing = KeyboardController.isVisible(); + const willShow = KeyboardEvents.addListener("keyboardWillShow", () => { + keyboardShowing = true; + onChange(); + }); + const willHide = KeyboardEvents.addListener("keyboardWillHide", () => { + keyboardShowing = false; + onChange(); + }); + return () => { + willShow.remove(); + willHide.remove(); + }; +} +const getKeyboardShowing = () => keyboardShowing; + +export function useSoftKeyboardShowing() { + return useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing); +} diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index 09e7f8a8c449c..14121e4efe9d2 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -3,17 +3,14 @@ import { WorkspacePresentationHostContext, } from "./workspace-presentation-context"; import { useAndroidFloatingTabs } from "../settings/appearance/AppearancePreferencesProvider"; +import { useSoftKeyboardShowing } from "../keyboard/useSoftKeyboardShowing"; import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context"; import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context"; import { threadSelectionDeferral } from "./deferred-navigation"; import { uuidv4 } from "../../lib/uuid"; -import type { - EnvironmentProject, - EnvironmentThreadShell, -} from "@t3tools/client-runtime/state/shell"; +import { useToolbarLayout } from "../../components/ui/useToolbarLayout"; import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; -import { useFocusEffect } from "@react-navigation/native"; import { NavigationContext, NavigationRouteContext, useNavigation } from "@react-navigation/native"; import { use, @@ -25,8 +22,19 @@ import { useState, type ReactNode, } from "react"; -import { Keyboard, Platform, useWindowDimensions, View } from "react-native"; -import { KeyboardController, useKeyboardState } from "react-native-keyboard-controller"; +import { + BackHandler, + Keyboard, + Platform, + Pressable, + useWindowDimensions, + View, +} from "react-native"; +import { + KeyboardController, + useKeyboardContext, + useKeyboardState, +} from "react-native-keyboard-controller"; import Animated, { runOnJS, useAnimatedStyle, @@ -44,14 +52,13 @@ import { deriveWorkspacePaneLayout, isPrimarySidebarPinned, isWorkspaceListPath, - type WorkspaceAuxiliaryPaneRole, + nativeInspectorColumnWidth, } from "../../lib/layout"; -import { scopedThreadKey } from "../../lib/scopedEntities"; import type { ThreadListFilters } from "../../persistence/mobile-preferences"; import { appAtomRegistry } from "../../state/atom-registry"; import { useProjects } from "../../state/entities"; -import { useThreadCwd } from "../../state/use-selected-thread-worktree"; import { environmentThreadShells } from "../../state/threads"; +import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; import { mobilePreferencesAtom } from "../../state/preferences"; import { DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS, @@ -62,30 +69,28 @@ import { useHardwareKeyboardCommand, } from "../keyboard/hardwareKeyboardCommands"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { useEnabledNavigationTabs } from "../workspace/navigation-tabs"; -import { FLOATING_TABS, floatingTabsMetrics } from "../workspace/floating-workspace-tabs"; -import { AndroidHomeFabLayout } from "../home/AndroidHomeFab"; +import { useEnabledNavigationTabs } from "./workspace/navigation-tabs"; +import { FLOATING_TABS, floatingTabsMetrics } from "./workspace/floating-workspace-tabs"; import { AndroidWorkspaceNavigation, FloatingWorkspaceTabs, ANDROID_WORKSPACE_RAIL_WIDTH, -} from "../workspace/AndroidWorkspaceNavigation"; -import { AndroidWorkspaceSidebar } from "../workspace/AndroidWorkspaceSidebar"; +} from "./workspace/AndroidWorkspaceNavigation"; import { selectWorkspaceDetail, type WorkspaceDetail, type WorkspaceDetailSheet, -} from "../workspace/workspace-detail-selection"; -import { startOpeningDetail } from "../workspace/useSelectWorkspaceDetail"; -import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; +} from "./workspace/workspace-detail-selection"; +import { startOpeningDetail } from "./workspace/useSelectWorkspaceDetail"; +import { useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; import { HomeListOptionsProvider } from "../home/home-list-options"; import { newTaskDestination } from "../threads/new-task-project-selection"; -import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; -import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar"; -import { useOpenThreadPullRequests } from "../threads/use-open-thread-pull-requests"; import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary"; +import { PaneContext } from "../../components/ui/Pane"; import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; import { WorkspaceInspectorPane } from "./workspace-inspector-pane"; +import { WorkspaceInspectorSheet } from "./workspace-inspector-sheet"; +import type { InspectorContent } from "./inspector-panes"; import { WorkspaceContentWidthContext, WorkspaceSettledContentWidthContext, @@ -98,55 +103,58 @@ import { import { useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { AndroidHingeObserver } from "../../native/AndroidHingeObserver"; import { WindowHingeContext } from "../../native/window-hinge-context"; -import { useAndroidWorkspaceRoot } from "../workspace/AndroidWorkspaceTabsProvider"; -import { openSettings } from "../settings/settings-navigation"; +import { useAndroidWorkspaceRoot } from "./workspace/AndroidWorkspaceTabsProvider"; import { dispatchRootStackReset, rootStackState } from "../../lib/root-stack-reset"; import { currentWorkspaceSelections, workspaceSelectionCheck, -} from "../workspace/workspace-selection-store"; +} from "./workspace/workspace-selection-store"; import { workspaceTabColumns, workspaceTabNavigationState, -} from "../workspace/workspace-tab-navigation"; -import type { WorkspaceTab } from "../workspace/workspace-tabs-state"; +} from "./workspace/workspace-tab-navigation"; +import type { WorkspaceTab } from "./workspace/workspace-tabs-state"; import { workspaceRoutesOf } from "./workspace-overlay-routes"; import { SettingsWorkspaceLayout } from "../settings/SettingsWorkspaceLayout"; +import { WorkspaceThreadSidebar } from "./workspace/WorkspaceThreadSidebar"; export { useAdaptiveWorkspaceLayout }; -export function useAdaptiveWorkspacePaneRole(role: WorkspaceAuxiliaryPaneRole) { - const { activateAuxiliaryPaneRole } = useAdaptiveWorkspaceLayout(); - - useFocusEffect(() => activateAuxiliaryPaneRole(role)); -} - -/** Capture inspector navigation contexts. Register on focus events because frozen blurred screens may never clean up. */ -export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefined) { +/** + * Shows these panes in the workspace's inspector while this screen is focused. Register on focus + * events because frozen blurred screens may never clean up. + */ +export function Inspector(props: { + readonly content: InspectorContent; + /** Opens the column the first time this key registers while its route stays on the stack. */ + readonly revealKey?: string; +}) { const { registerWorkspaceInspector } = useAdaptiveWorkspaceLayout(); const navigation = use(NavigationContext); const route = use(NavigationRouteContext); - - const wrappedRender = (() => { - if (render === undefined) { - return undefined; - } - return () => ( - - {render()} - - ); - })(); - + const content: InspectorContent = { + ...props.content, + resetKeys: [route?.key, ...(props.content.resetKeys ?? [])], + panes: props.content.panes.map((pane) => ({ + ...pane, + render: () => ( + + + {pane.render()} + + + ), + })), + }; const focusedRef = useRef(false); const deactivateRef = useRef<(() => void) | null>(null); const syncRegistration = useEffectEvent(() => { - if (!focusedRef.current || wrappedRender === undefined) { + if (!focusedRef.current) { deactivateRef.current?.(); return; } - deactivateRef.current = registerWorkspaceInspector(wrappedRender); + deactivateRef.current = registerWorkspaceInspector(content, route?.key, props.revealKey); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Navigation focus events own the inspector registration lifetime. @@ -173,13 +181,14 @@ export function useRegisterWorkspaceInspector(render: (() => ReactNode) | undefi }; }, [navigation]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Changed pane content replaces the focused inspector registration. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Changed column content replaces the focused inspector registration. useEffect(() => { if (focusedRef.current) { syncRegistration(); } - // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Changed pane content replaces its existing native workspace registration. - }, [wrappedRender]); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Changed column content replaces its existing native workspace registration. + }, [props.content, props.revealKey]); + return null; } export function AdaptiveWorkspaceLayout(props: { @@ -187,8 +196,6 @@ export function AdaptiveWorkspaceLayout(props: { readonly pathname: string; readonly workspaceRouteKey: string | undefined; readonly workspaceRouteName: string | undefined; - readonly workspaceRouteKeys: ReadonlyArray; - readonly selectedPullRequestKey?: string | null; }) { const preferencesResult = useAtomValue(mobilePreferencesAtom); if (!AsyncResult.isSuccess(preferencesResult)) { @@ -215,8 +222,6 @@ function AdaptiveWorkspaceLayoutContent( readonly pathname: string; readonly workspaceRouteKey: string | undefined; readonly workspaceRouteName: string | undefined; - readonly workspaceRouteKeys: ReadonlyArray; - readonly selectedPullRequestKey?: string | null; } & { readonly projectGroupingMode: SidebarProjectGroupingMode; readonly savedThreadListFilters?: ThreadListFilters | undefined; @@ -237,20 +242,19 @@ function AdaptiveWorkspaceLayoutContent( const workspacePage = Platform.OS === "android" && (androidSettingsOpen || workspace?.state.selectedTab === "usage"); const navigation = useNavigation(); - const activeRoleOwner = useRef(null); const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true); - const [supplementaryPanePreferredVisible, setSupplementaryPanePreferredVisible] = useState(true); - const [supplementaryPanePreferredWidth, setSupplementaryPanePreferredWidth] = useState< - number | null - >(null); const [fileInspectorPreferredVisible, setFileInspectorPreferredVisible] = useState(true); + const [nativeInspectorWidthFraction, setNativeInspectorWidthFraction] = useState(0.4); + const horizontalSafeArea = + (nativeMetrics?.safeArea.left ?? 0) + (nativeMetrics?.safeArea.right ?? 0); + const inspectorWidthFor = (fraction: number) => + nativeInspectorColumnWidth({ viewportWidth, horizontalSafeArea, fraction }); + const nativeInspectorWidth = inspectorWidthFor(nativeInspectorWidthFraction); const [fileInspectorPreferredWidth, setFileInspectorPreferredWidth] = useState( null, ); const [primarySidebarSearchQuery, setPrimarySidebarSearchQuery] = useState(""); const [railOverlay, setRailOverlay] = useState(false); - const [focusedAuxiliaryPaneRole, setFocusedAuxiliaryPaneRole] = - useState(null); // The compiler can't memoize these derivations: they stay live across later hook calls. Fresh // objects here change the workspace context on every render, so every workspace screen // re-renders on any layout state change, and the inspector registration then loops: each @@ -262,17 +266,17 @@ function AdaptiveWorkspaceLayoutContent( // The overlay sidebar closes when a page opens from it, and stays open on a list or on the // page a tab switch opened (`keepOpenFor`, set by that switch). const [overlaySidebar, setOverlaySidebar] = useState({ - active: baseLayout.primarySidebarOverlaysContent, + active: baseLayout.variant === "medium", pathname, visible: isWorkspaceListPath(pathname), keepOpenFor: null as string | null, }); if ( - overlaySidebar.active !== baseLayout.primarySidebarOverlaysContent || + overlaySidebar.active !== (baseLayout.variant === "medium") || (overlaySidebar.active && overlaySidebar.pathname !== pathname) ) { setOverlaySidebar({ - active: baseLayout.primarySidebarOverlaysContent, + active: baseLayout.variant === "medium", pathname, visible: isWorkspaceListPath(pathname) || @@ -281,34 +285,51 @@ function AdaptiveWorkspaceLayoutContent( keepOpenFor: null, }); } - const preferredSidebarVisible = baseLayout.primarySidebarOverlaysContent - ? overlaySidebar.visible - : primarySidebarPreferredVisible; + const preferredSidebarVisible = + baseLayout.variant === "medium" ? overlaySidebar.visible : primarySidebarPreferredVisible; const primarySidebarPinned = isPrimarySidebarPinned({ pathname, nativeWorkspace, usesSplitView: baseLayout.usesSplitView, }); const [composerEditing, setComposerEditing] = useState(false); - const softKeyboardVisible = useKeyboardState((state) => state.isVisible); + const softKeyboardVisible = useSoftKeyboardShowing(); // Keyed on the soft keyboard, not focus: a hardware keyboard leaves room for the sidebar, and - // Back closes the keyboard while the editor keeps focus. Deferred so the composer commits its - // keyboard render first; relaying out in the same commit held it behind the keyboard. + // Back closes the keyboard while the editor keeps focus. The sidebar returns as the keyboard + // starts hiding, not after. Deferred so the composer commits its keyboard render first; + // relaying out in the same commit held it behind the keyboard. const composerKeyboardActive = useDeferredValue( Platform.OS === "android" && baseLayout.usesSplitView && composerEditing && softKeyboardVisible, ); + const sidebarWithoutKeyboard = + !workspacePage && (primarySidebarPinned || preferredSidebarVisible); const showPrimarySidebar = + sidebarWithoutKeyboard && (primarySidebarPinned || !composerKeyboardActive); + // Medium windows float the sidebar over a page; beside a list it keeps its room. + const sidebarFloats = + baseLayout.variant === "medium" && + (nativeWorkspace || (!primarySidebarPinned && !workspacePage)); + // While the composer edits, the sidebar's width follows the keyboard's own progress, so it + // leaves and returns in step with the keyboard instead of on a timer of its own. + const keyboardHoldsSidebar = + Platform.OS === "android" && + baseLayout.usesSplitView && !workspacePage && - (primarySidebarPinned || (preferredSidebarVisible && !composerKeyboardActive)); + !primarySidebarPinned && + !sidebarFloats && + (composerEditing || composerKeyboardActive); + const keyboardProgress = useKeyboardContext().reanimated.progress; + // From the moment the keyboard starts showing until it has fully hidden. The detail pane keeps + // the sidebar's room for that whole span, so on the way back the sidebar pushes the wide pane + // aside instead of arriving beside one that already shrank. + const keyboardOnScreen = useKeyboardState((state) => state.isVisible); const shouldRenderNavigationRail = Platform.OS === "android" && baseLayout.usesSplitView && !floatingTabsEnabled; const enabledTabs = useEnabledNavigationTabs(); const { scale, fabSize } = useAndroidControlSizing(); const floatingTabs = floatingTabsMetrics(enabledTabs.length + 1, scale, fabSize); - const navigationRailWidth = - shouldRenderNavigationRail && (showPrimarySidebar || workspacePage) - ? ANDROID_WORKSPACE_RAIL_WIDTH - : 0; + // The rail stays whether or not the sidebar shows; only the list pane comes and goes. + const navigationRailWidth = shouldRenderNavigationRail ? ANDROID_WORKSPACE_RAIL_WIDTH : 0; const [hinge, setHinge] = useState(null); const [windowHinge, setWindowHinge] = useState(null); const handleHingeChange = (next: VerticalHinge | null, nextWindow: VerticalHinge | null) => { @@ -340,7 +361,8 @@ function AdaptiveWorkspaceLayoutContent( floatingTabs.row, floatingTabsEnabled, ]); - const width = viewportWidth - navigationRailWidth; + // A floating sidebar brings the rail with it. + const width = viewportWidth - (sidebarFloats ? 0 : navigationRailWidth); // The sidebar stays mounted under a workspace page, so its list is ready on the way back. const shouldRenderPrimarySidebar = layout.usesSplitView; const fileInspector = useMemo( @@ -350,102 +372,121 @@ function AdaptiveWorkspaceLayoutContent( viewportWidth: width, preferredWidth: fileInspectorPreferredWidth ?? undefined, reservedLeadingWidth: - shouldRenderPrimarySidebar && showPrimarySidebar && !layout.primarySidebarOverlaysContent + shouldRenderPrimarySidebar && showPrimarySidebar && !sidebarFloats ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0, }), - [fileInspectorPreferredWidth, layout, showPrimarySidebar, shouldRenderPrimarySidebar, width], + [ + fileInspectorPreferredWidth, + layout, + showPrimarySidebar, + shouldRenderPrimarySidebar, + sidebarFloats, + width, + ], ); - const auxiliaryPaneRole: WorkspaceAuxiliaryPaneRole = - focusedAuxiliaryPaneRole ?? (/\/files(?:\/|$)/.test(pathname) ? "inspector" : "supplementary"); - const auxiliaryPanePreferredVisible = + const [workspaceInspector, setWorkspaceInspector] = useState<{ + readonly content: InspectorContent; + readonly active: boolean; + readonly routeKey: string | undefined; + } | null>(null); + // Without a column the inspector is a sheet, opened only on request for the route on top, and + // shown again when that route returns to the top. + const [inspectorSheetRoute, setInspectorSheetRoute] = useState(null); + const inspectorSheetOpen = + !fileInspector.supported && !workspacePage && - (auxiliaryPaneRole === "inspector" - ? fileInspectorPreferredVisible - : supplementaryPanePreferredVisible); - const auxiliaryPanePreferredWidth = - auxiliaryPaneRole === "inspector" - ? fileInspectorPreferredWidth - : supplementaryPanePreferredWidth; + inspectorSheetRoute !== null && + workspaceInspector?.active === true && + workspaceInspector.routeKey === inspectorSheetRoute; + const inspectorActive = workspaceInspector?.active ?? false; const panes = useMemo( () => deriveWorkspacePaneLayout({ layout, viewportWidth: width, + horizontalSafeArea, nativeWorkspace, + primarySidebarFloats: sidebarFloats, primarySidebarPreferredVisible: showPrimarySidebar, - auxiliaryPanePreferredVisible, - auxiliaryPaneRole, - auxiliaryPanePreferredWidth: auxiliaryPanePreferredWidth ?? undefined, + // Only a column a screen fills makes room, so a stale preference can't hide the sidebar. + auxiliaryPanePreferredVisible: + !workspacePage && inspectorActive && fileInspectorPreferredVisible, + auxiliaryPanePreferredWidth: fileInspectorPreferredWidth ?? undefined, + nativeInspectorWidth, }), [ - auxiliaryPanePreferredVisible, - auxiliaryPaneRole, - auxiliaryPanePreferredWidth, + nativeInspectorWidth, + horizontalSafeArea, + fileInspectorPreferredVisible, + fileInspectorPreferredWidth, + inspectorActive, layout, nativeWorkspace, showPrimarySidebar, + sidebarFloats, width, + workspacePage, ], ); - const activeThread = parseActiveThreadPath(pathname); - const environmentId = activeThread?.environmentId ?? null; - const threadId = activeThread?.threadId ?? null; - const selectedThreadRef = (() => { - if (environmentId === null || threadId === null) { - return null; - } - try { - return { - environmentId: EnvironmentId.make(environmentId), - threadId: ThreadId.make(threadId), - }; - } catch { - return null; - } - })(); - const selectedThreadKey = - selectedThreadRef === null - ? null - : scopedThreadKey(selectedThreadRef.environmentId, selectedThreadRef.threadId); - const isFilesRoute = props.workspaceRouteName === "ThreadFiles"; - // Same resolution the Files screen uses: without a cwd it shows "Files unavailable" and - // registers no inspector, so revealing would only hide the sidebar beside that screen. - const filesCwd = useThreadCwd(isFilesRoute && fileInspector.supported ? selectedThreadRef : null); - // Opening a review or the files route reveals its inspector once per route and thread. - // Routes still on the stack remember their reveal, so going back to one keeps the user's choice. - const revealsInspector = - props.workspaceRouteName === "ThreadReview" || (isFilesRoute && filesCwd !== null); - const [revealedInspectors, setRevealedInspectors] = useState>( - () => new Map(), + // Whether the sidebar is open once the keyboard is gone; the keyboard's progress scales it. + const sidebarRestsOpen = useMemo( + () => + showPrimarySidebar === sidebarWithoutKeyboard + ? panes.primarySidebarVisible + : deriveWorkspacePaneLayout({ + layout, + viewportWidth: width, + horizontalSafeArea, + nativeWorkspace, + primarySidebarFloats: sidebarFloats, + primarySidebarPreferredVisible: sidebarWithoutKeyboard, + auxiliaryPanePreferredVisible: + !workspacePage && inspectorActive && fileInspectorPreferredVisible, + auxiliaryPanePreferredWidth: fileInspectorPreferredWidth ?? undefined, + nativeInspectorWidth, + }).primarySidebarVisible, + [ + nativeInspectorWidth, + horizontalSafeArea, + fileInspectorPreferredVisible, + fileInspectorPreferredWidth, + inspectorActive, + layout, + nativeWorkspace, + panes.primarySidebarVisible, + showPrimarySidebar, + sidebarFloats, + sidebarWithoutKeyboard, + width, + workspacePage, + ], ); - if ( - revealsInspector && - props.workspaceRouteKey !== undefined && - selectedThreadKey !== null && - revealedInspectors.get(props.workspaceRouteKey) !== selectedThreadKey - ) { - const next = new Map(); - for (const routeKey of props.workspaceRouteKeys) { - const revealedThreadKey = revealedInspectors.get(routeKey); - if (revealedThreadKey !== undefined) { - next.set(routeKey, revealedThreadKey); - } - } - next.set(props.workspaceRouteKey, selectedThreadKey); - setRevealedInspectors(next); - setFocusedAuxiliaryPaneRole("inspector"); - setFileInspectorPreferredVisible(true); - } - const [workspaceInspector, setWorkspaceInspector] = useState<{ - readonly render: () => ReactNode; - readonly active: boolean; - } | null>(null); + // Routes still on the stack remember their reveal, so going back to one keeps the user's choice. + const revealedInspectors = useRef>(new Map()); const workspaceInspectorOwner = useRef(null); - const registerWorkspaceInspector = (render: () => ReactNode) => { + const registerWorkspaceInspector = ( + content: InspectorContent, + routeKey: string | undefined, + revealKey?: string, + ) => { const owner = Symbol("workspace-inspector"); workspaceInspectorOwner.current = owner; - setWorkspaceInspector({ render, active: true }); + setWorkspaceInspector({ content, active: true, routeKey }); + if ( + routeKey !== undefined && + revealKey !== undefined && + revealedInspectors.current.get(routeKey) !== revealKey + ) { + const state = rootStackState(navigation); + const live = new Set(state?.routes.slice(0, state.index + 1).map((route) => route.key)); + revealedInspectors.current = new Map( + [...revealedInspectors.current, [routeKey, revealKey] as const].filter( + ([key]) => live.has(key) || key === routeKey, + ), + ); + setFileInspectorPreferredVisible(true); + } return () => { // Outgoing screens deactivate after incoming registration; only the current owner may deactivate. @@ -458,21 +499,8 @@ function AdaptiveWorkspaceLayoutContent( const handleWorkspaceInspectorClosed = () => { setWorkspaceInspector((current) => (current !== null && !current.active ? null : current)); }; - const activateAuxiliaryPaneRole = (role: WorkspaceAuxiliaryPaneRole) => { - const owner = Symbol(role); - activeRoleOwner.current = owner; - setFocusedAuxiliaryPaneRole(role); - - return () => { - if (activeRoleOwner.current !== owner) { - return; - } - activeRoleOwner.current = null; - setFocusedAuxiliaryPaneRole(null); - }; - }; const setPrimarySidebarVisible = (visible: boolean) => { - if (layout.primarySidebarOverlaysContent) { + if (layout.variant === "medium") { setOverlaySidebar((current) => ({ ...current, visible })); } else { setPrimarySidebarPreferredVisible(visible); @@ -486,7 +514,7 @@ function AdaptiveWorkspaceLayoutContent( // intact. One the user had hidden still opens. if (composerKeyboardActive) { void KeyboardController.dismiss(); - if (primarySidebarPreferredVisible) return; + if (preferredSidebarVisible) return; } if (!panes.primarySidebarVisible && panes.primarySidebarSuppressedByAuxiliary) { setFileInspectorPreferredVisible(false); @@ -508,22 +536,28 @@ function AdaptiveWorkspaceLayoutContent( }; const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const); useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand); - const showAuxiliaryPane = (role: WorkspaceAuxiliaryPaneRole) => { - if (role === "inspector") { - setFocusedAuxiliaryPaneRole("inspector"); - setFileInspectorPreferredVisible(true); + // Resizing into a column closes the sheet without this, so the inspector moves into the column. + const dismissInspectorSheet = () => { + setFileInspectorPreferredVisible(false); + setInspectorSheetRoute(null); + }; + const showInspector = () => { + setFileInspectorPreferredVisible(true); + if (fileInspector.supported) { + setInspectorSheetRoute(null); return; } - setFocusedAuxiliaryPaneRole("supplementary"); - setSupplementaryPanePreferredVisible(true); + const state = rootStackState(navigation); + const top = workspaceRoutesOf(state?.routes.slice(0, state.index + 1) ?? []).workspace.at(-1); + setInspectorSheetRoute(top?.key ?? null); }; const handleOpenFilesCommand = () => { const activeThread = parseActiveThreadPath(pathname); if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) { return false; } - showAuxiliaryPane("inspector"); - if (/\/files(?:\/|$)/.test(pathname)) { + showInspector(); + if (props.workspaceRouteName === "ThreadFiles" || props.workspaceRouteName === "ThreadFile") { return true; } navigation.navigate("ThreadFiles", activeThread); @@ -531,18 +565,11 @@ function AdaptiveWorkspaceLayoutContent( }; useHardwareKeyboardCommand("files", handleOpenFilesCommand); const toggleAuxiliaryPane = () => { - if (auxiliaryPaneRole === "inspector") { + if (fileInspector.supported) { setFileInspectorPreferredVisible((current) => !current); - return; - } - setSupplementaryPanePreferredVisible((current) => !current); - }; - const setAuxiliaryPaneWidth = (nextWidth: number) => { - if (auxiliaryPaneRole === "inspector") { - setFileInspectorPreferredWidth(nextWidth); - return; - } - setSupplementaryPanePreferredWidth(nextWidth); + setInspectorSheetRoute(null); + } else if (inspectorSheetOpen) dismissInspectorSheet(); + else showInspector(); }; /** * The one way to open a workspace tab: replaces the workspace with the tab's list and, when the @@ -564,9 +591,10 @@ function AdaptiveWorkspaceLayoutContent( columns: workspaceTabColumns(Platform.OS, tab, options?.columns ?? layout.usesSplitView), check: workspaceSelectionCheck, overlays, + seedPullRequest: withKnownPullRequestSummary, }, ); - if (layout.primarySidebarOverlaysContent) { + if (layout.variant === "medium") { const opened = next.routes.at(-1 - overlays.length)?.key ?? null; setOverlaySidebar((current) => ({ ...current, visible: true, keepOpenFor: opened })); } @@ -579,7 +607,8 @@ function AdaptiveWorkspaceLayoutContent( threadSelectionDeferral.run(() => { if (Platform.OS === "android") Keyboard.dismiss(); setFileInspectorPreferredVisible(false); - if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false); + setInspectorSheetRoute(null); + if (layout.variant === "medium") setPrimarySidebarVisible(false); workspace?.dispatch({ type: "select", tab: detail.name === "Thread" ? "threads" : "pullRequests", @@ -635,47 +664,63 @@ function AdaptiveWorkspaceLayoutContent( return true; }); - // Create at root: the iOS sidebar renders in an independent navigation tree. - const handleOpenEnvironmentSettings = () => { - openSettings(navigation, "SettingsEnvironments"); - }; - - const handleOpenThreadPullRequests = useOpenThreadPullRequests(); - const { openPendingTask: handleOpenPendingTask } = - usePendingTaskListActions(handleSelectThreadRoute); - - const handleNewThreadOnBranch = (thread: EnvironmentThreadShell) => { - handleSelectThreadRoute({ - draft: { - requestId: uuidv4(), - environmentId: String(thread.environmentId), - projectId: String(thread.projectId), - branch: thread.branch, - worktreePath: thread.worktreePath, - }, - }); - }; - - const handleNewThreadInProject = (project: EnvironmentProject) => { - handleSelectThreadRoute({ - draft: { - requestId: uuidv4(), - environmentId: String(project.environmentId), - projectId: String(project.id), - title: project.title, - }, - }); - }; - - const inspectorColumnTargetWidth = - workspaceInspector !== null && workspaceInspector.active && panes.auxiliaryPaneVisible - ? (panes.auxiliaryPaneWidth ?? 0) - : 0; + const inspectorColumnTargetWidth = panes.auxiliaryPaneVisible + ? (panes.auxiliaryPaneWidth ?? 0) + : 0; // Android's split content is a rounded card: keep it off the screen edge like the list card. const contentEndGap = Platform.OS === "android" && layout.usesSplitView ? 4 : 0; - const contentTargetWidth = layout.usesSplitView - ? Math.max(0, panes.contentPaneWidth - inspectorColumnTargetWidth - contentEndGap) - : null; + // Android's split is one strip: a sidebar slot of fixed width, then the detail pane. The + // sidebar never resizes; both slide by one offset, so together they always fill the width. + // The pane spans the sidebar's room too unless the sidebar has finished arriving: a sidebar on + // its way in pushes the wide pane past the edge, and one leaving uncovers it. + const stripSidebar = + Platform.OS === "android" && + layout.usesSplitView && + layout.listPaneWidth !== null && + !workspacePage && + !sidebarFloats; + const sidebarSlotWidth = (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0); + const sidebarTargetOpen = keyboardHoldsSidebar ? sidebarRestsOpen : panes.primarySidebarVisible; + const [sidebarMotion, setSidebarMotion] = useState({ + strip: stripSidebar, + settledOpen: sidebarTargetOpen, + }); + if (sidebarMotion.strip !== stripSidebar) { + // Entering or leaving the strip (a workspace page, a fold) snaps the sidebar into place. + setSidebarMotion({ strip: stripSidebar, settledOpen: sidebarTargetOpen }); + } else if (sidebarMotion.settledOpen && !sidebarTargetOpen) { + setSidebarMotion({ strip: stripSidebar, settledOpen: false }); + } + const sidebarSettledOpen = + sidebarMotion.strip === stripSidebar ? sidebarMotion.settledOpen : sidebarTargetOpen; + const markSidebarSettled = (open: boolean) => + setSidebarMotion((current) => + current.settledOpen === open ? current : { ...current, settledOpen: open }, + ); + // The keyboard covers the sidebar's share from the moment it starts showing until it is gone. + const contentSpansSidebar = + stripSidebar && + (!sidebarSettledOpen || !sidebarTargetOpen || (keyboardHoldsSidebar && keyboardOnScreen)); + const contentTargetWidth = !layout.usesSplitView + ? null + : Math.max( + 0, + (contentSpansSidebar ? width : panes.contentPaneWidth) - + inspectorColumnTargetWidth - + contentEndGap, + ); + // A workspace page (Usage) lays out at this width even while hidden behind another tab, so + // opening it widens nothing it measured. + const workspacePageWidth = !layout.usesSplitView + ? null + : workspacePage + ? contentTargetWidth + : Math.max( + 0, + viewportWidth - + (shouldRenderNavigationRail ? ANDROID_WORKSPACE_RAIL_WIDTH : 0) - + contentEndGap, + ); const [listPaneSizing, setListPaneSizing] = useState({ viewportWidth, workspacePage, @@ -734,11 +779,12 @@ function AdaptiveWorkspaceLayoutContent( // against the edge that stays put while the other one slides, so nothing reflows after the // panes land. A sliding sidebar uncovers the strip it is about to fill, or covers the content // until it is gone. - const contentLeftTarget = - navigationRailWidth + - (shouldRenderPrimarySidebar && !workspacePage && panes.primarySidebarVisible - ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) - : 0); + const contentLeftTarget = sidebarFloats + ? 0 + : navigationRailWidth + + (shouldRenderPrimarySidebar && !workspacePage && panes.primarySidebarVisible + ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) + : 0); const [contentAnchor, setContentAnchor] = useState({ viewportWidth, left: contentLeftTarget, @@ -765,10 +811,16 @@ function AdaptiveWorkspaceLayoutContent( panes.primarySidebarVisible ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0, ); const renderedRailWidth = useSharedValue(navigationRailWidth); + const keyboardHold = useSharedValue(keyboardHoldsSidebar); const leavingWorkspacePage = useRef(false); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- animates the Reanimated rail and sidebar width shared values toward the layout's targets useEffect(() => { if (nativeWorkspace) return; + // Released mid-keyboard (the composer blurred), the timing starts where the sidebar is drawn. + if (keyboardHold.get() && !keyboardHoldsSidebar) { + renderedSidebarWidth.set(renderedSidebarWidth.get() * (1 - keyboardProgress.get())); + } + keyboardHold.set(keyboardHoldsSidebar); renderedRailWidth.set(withTiming(navigationRailWidth, WORKSPACE_PANE_TIMING)); // A workspace page hides the sidebar through React instead, in the same commit that mounts // the page. Animating it here would hide it a few frames before the page appears. @@ -778,13 +830,16 @@ function AdaptiveWorkspaceLayoutContent( } const snap = leavingWorkspacePage.current; leavingWorkspacePage.current = false; - const targetWidth = panes.primarySidebarVisible + const targetWidth = (keyboardHoldsSidebar ? sidebarRestsOpen : panes.primarySidebarVisible) ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) : 0; // The content beside it already took its final width when the page closed. renderedSidebarWidth.set( withTiming(targetWidth, snap ? { duration: 0 } : WORKSPACE_PANE_TIMING, (finished) => { - if (finished && Platform.OS === "android") runOnJS(settleListPane)(listPaneRevision); + if (finished && Platform.OS === "android") { + runOnJS(settleListPane)(listPaneRevision); + runOnJS(markSidebarSettled)(targetWidth > 0); + } }), ); }, [ @@ -793,30 +848,83 @@ function AdaptiveWorkspaceLayoutContent( layout.listPaneWidth, layout.listPaneGap, panes.primarySidebarVisible, + keyboardHoldsSidebar, + keyboardHold, + keyboardProgress, + sidebarRestsOpen, renderedSidebarWidth, renderedRailWidth, settleListPane, + markSidebarSettled, listPaneRevision, workspacePage, ]); const railAnimatedStyle = useAnimatedStyle(() => ({ width: renderedRailWidth.value })); + const floatingSidebarAnimatedStyle = useAnimatedStyle(() => ({ left: renderedRailWidth.value })); + const floatingSidebarOpen = sidebarFloats && panes.primarySidebarVisible; + // Its own value, so a sidebar that was beside a list doesn't dim the page as it leaves. + const scrimOpacity = useSharedValue(0); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- animates the Reanimated scrim with the floating sidebar + useEffect(() => { + scrimOpacity.set(withTiming(floatingSidebarOpen ? 0.32 : 0, WORKSPACE_PANE_TIMING)); + }, [floatingSidebarOpen, scrimOpacity]); + const scrimAnimatedStyle = useAnimatedStyle(() => ({ opacity: scrimOpacity.value })); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Back closes a floating sidebar before it leaves the page + useEffect(() => { + if (!floatingSidebarOpen || nativeWorkspace) return; + const subscription = BackHandler.addEventListener("hardwareBackPress", () => { + // A sheet or modal over the workspace takes Back first. + const state = rootStackState(navigation); + if (state && workspaceRoutesOf(state.routes.slice(0, state.index + 1)).overlays.length > 0) { + return false; + } + setPrimarySidebarVisible(false); + return true; + }); + return () => subscription.remove(); + }, [floatingSidebarOpen, nativeWorkspace, navigation, setPrimarySidebarVisible]); // Showing or hiding the sidebar clips a fixed-width list. A hinge resize instead tracks the // animated edge, so the header actions slide with it rather than jumping or being covered. const listPaneGap = layout.listPaneGap ?? 0; + const keyboardSidebarRest = sidebarRestsOpen + ? (layout.listPaneWidth ?? 0) + (layout.listPaneGap ?? 0) + : 0; + const drawnSidebarWidth = useDerivedValue( + () => renderedSidebarWidth.value * (keyboardHold.value ? 1 - keyboardProgress.value : 1), + ); const listPaneAnimatedStyle = useAnimatedStyle(() => ({ width: Math.min( listPaneCeiling, - Math.max(listPaneFloor, renderedSidebarWidth.value - listPaneGap), + Math.max( + listPaneFloor, + (stripSidebar ? sidebarSlotWidth : drawnSidebarWidth.value) - listPaneGap, + ), ), })); + // How far the strip has slid: 0 with the sidebar shown, minus its width with it gone. + const stripOffset = useDerivedValue(() => + stripSidebar ? drawnSidebarWidth.value - sidebarSlotWidth : 0, + ); const sidebarAnimatedStyle = useAnimatedStyle(() => ({ // Fading a UIKit glass ancestor can leave remounted header effects missing. opacity: - Platform.OS === "ios" || floatingTabsEnabled + stripSidebar || Platform.OS === "ios" || floatingTabsEnabled ? 1 - : Math.min(1, renderedSidebarWidth.value / 80), - width: renderedSidebarWidth.value, + : Math.min(1, drawnSidebarWidth.value / 80), + width: stripSidebar ? sidebarSlotWidth : drawnSidebarWidth.value, + flexShrink: stripSidebar ? 0 : 1, + transform: [{ translateX: stripOffset.value }], + })); + // The content keeps the width React laid it out at and rides the sidebar's edge, so a keyboard + // transition relays nothing out per frame, the way UIKit animates the iOS split view. + // Until React commits the wider layout, the detail card continues past its right edge, so the + // strip the narrower column leaves shows the card instead of the row behind it. + const contentOverhangStyle = useAnimatedStyle(() => ({ + opacity: keyboardHold.value && keyboardProgress.value > 0 ? 1 : 0, })); + const threadHeader = useToolbarLayout(false, composerKeyboardActive); + const threadHeaderHeight = + threadHeader.paddingTop + threadHeader.height + threadHeader.paddingBottom; // Clip the navigator at its settled width so native headers and markdown reflow only once per pane toggle. const renderedInspectorWidth = useSharedValue(inspectorColumnTargetWidth); @@ -824,43 +932,56 @@ function AdaptiveWorkspaceLayoutContent( Math.max( 0, viewportWidth - - renderedRailWidth.value - - (workspacePage ? 0 : renderedSidebarWidth.value) - + (sidebarFloats ? 0 : renderedRailWidth.value) - + (workspacePage || sidebarFloats ? 0 : drawnSidebarWidth.value) - renderedInspectorWidth.value, ), ); // Android can resize the native row before React removes its split panes on a fold. const androidSplit = Platform.OS === "android" && layout.usesSplitView; - const androidContentSlotStyle = useAnimatedStyle(() => ({ - width: androidSplit ? renderedContentWidth.value : ("100%" as const), - })); + // In the strip the column itself slides with the sidebar: Android only delivers touches inside a + // parent's bounds, so content may not slide out of its column. Every branch sets every key: + // Reanimated keeps a key a branch drops, so a fold mid-slide would leave the column shifted. + const androidContentSlotStyle = useAnimatedStyle(() => + !androidSplit + ? { width: "100%" as const, marginRight: 0, transform: [{ translateX: 0 }] } + : stripSidebar + ? { + // Wide enough for the pane at either width; the margin gives the sidebar's share + // back to the row, so a column after it stays put while the strip slides. + width: Math.max( + 0, + viewportWidth - renderedRailWidth.value - renderedInspectorWidth.value, + ), + marginRight: -sidebarSlotWidth, + transform: [{ translateX: stripOffset.value }], + } + : { width: renderedContentWidth.value, marginRight: 0, transform: [{ translateX: 0 }] }, + ); // While the sidebar animates, clip the settled navigator instead of reflowing its text every frame. + // In the strip it lifts entirely: the content outgrows its column, and a cap that follows + // React's width would clip the wider layout for the frame it lands. const androidNavigatorLimit = useAnimatedStyle(() => ({ - maxWidth: - androidSplit && contentTargetWidth !== null && renderedContentWidth.value < contentTargetWidth + maxWidth: stripSidebar + ? viewportWidth + : androidSplit && + contentTargetWidth !== null && + renderedContentWidth.value < contentTargetWidth ? contentTargetWidth : ("100%" as const), })); - const handleSelectThread = (thread: EnvironmentThreadShell) => { - handleSelectThreadRoute({ - environmentId: String(thread.environmentId), - threadId: String(thread.id), - }); - }; - // Rotating flips the overlay; until the new size reaches JS, predict the reset above. const sidebarOverRotates = nativeWorkspace && nativeMetrics?.hasHinge === true && layout.usesSplitView; // The current orientation's panes already account for an inspector that needs the sidebar's room. - const sidebarInLandscape = baseLayout.primarySidebarOverlaysContent - ? primarySidebarPinned || primarySidebarPreferredVisible - : panes.primarySidebarVisible; + const sidebarInLandscape = + baseLayout.variant === "medium" + ? primarySidebarPinned || primarySidebarPreferredVisible + : panes.primarySidebarVisible; const sidebarInPortrait = primarySidebarPinned || - (baseLayout.primarySidebarOverlaysContent - ? overlaySidebar.visible - : isWorkspaceListPath(pathname)); + (baseLayout.variant === "medium" ? overlaySidebar.visible : isWorkspaceListPath(pathname)); const sidebarByOrientation = useMemo( () => sidebarOverRotates ? { landscape: sidebarInLandscape, portrait: sidebarInPortrait } : null, @@ -874,20 +995,33 @@ function AdaptiveWorkspaceLayoutContent( primarySidebarSearchQuery, startNewTask: handleStartNewTask, selectDetail: handleSelectDetail, - activateAuxiliaryPaneRole, registerWorkspaceInspector, setPrimarySidebarSearchQuery, - showAuxiliaryPane, + showInspector, toggleAuxiliaryPane, + sidebarToggleable: layout.usesSplitView && !primarySidebarPinned && !workspacePage, togglePrimarySidebar, + revealPrimarySidebar, setPrimarySidebarVisible, openWorkspaceTab, - setAuxiliaryPaneWidth, + setAuxiliaryPaneWidth: setFileInspectorPreferredWidth, + nativeInspectorWidth, + setNativeInspectorWidth: (width: number) => + setNativeInspectorWidthFraction(inspectorWidthFor(width / viewportWidth) / viewportWidth), composerKeyboardActive, + keyboardHoldsSidebar, setComposerEditing, sidebarByOrientation, + workspacePageWidth, }; + const inspectorSheet = ( + + ); if (nativeWorkspace) { return ( 0 }} + value={{ + // Without a column the sheet shows it; the hidden native column must not mount it too. + content: fileInspector.supported ? workspaceInspector?.content : undefined, + visible: inspectorColumnTargetWidth > 0, + }} > {props.children} + {inspectorSheet} ); } - const renderColumns = (children: ReactNode) => ( + const renderColumns = (children: ReactNode, sidebar?: ReactNode) => ( {shouldRenderNavigationRail ? ( - + ) : null} {shouldRenderPrimarySidebar && layout.listPaneWidth !== null ? ( - ( - - )} - > - - - + ( + - - - + )} + > + {/* Without a sidebar route (iPadOS before 26) the columns draw the thread list. */} + {sidebar ?? } + + {/* Keep the pill under the content throughout the sidebar's clipping animation. */} {floatingTabsEnabled && !workspacePage ? ( - {children} + + {children} + {floatingTabsEnabled && @@ -1043,25 +1174,71 @@ function AdaptiveWorkspaceLayoutContent( + {keyboardHoldsSidebar && contentTargetWidth !== null ? ( + <> + + + + ) : null} - + {sidebarFloats ? ( + + setPrimarySidebarVisible(false)} + /> + + ) : null} + + setFileInspectorPreferredVisible(false)} + onClosed={handleWorkspaceInspectorClosed} + /> + + {inspectorSheet} {shouldRenderNavigationRail && navigationRailWidth > 0 ? ( // Its trailing inset clips the old rail as soon as Android fits the workspace to a cover display. ; return ( - - {props.onAddConnection ? ( - - - } - /> - - ) : ( - - - - {settings - ? "Select a setting" - : pullRequests - ? "Select a pull request" - : "Select a thread"} - - - {settings - ? "Choose a page from the sidebar." - : pullRequests - ? "Choose a pull request from the sidebar to review it." - : Platform.OS === "android" - ? "Choose a thread from the sidebar or start a new thread." - : "Choose a thread from the sidebar or start a new task."} - - {props.onStartNewTask && !pullRequests && !settings ? ( - Platform.OS === "android" ? ( - - ) : ( - - New thread - - ) - ) : null} - - )} - + + + {props.onAddConnection ? ( + + + } + /> + + ) : ( + + + + {settings + ? "Select a setting" + : pullRequests + ? "Select a pull request" + : "Select a thread"} + + + {settings + ? "Choose a page from the sidebar." + : pullRequests + ? "Choose a pull request from the sidebar to review it." + : Platform.OS === "android" + ? "Choose a thread from the sidebar or start a new thread." + : "Choose a thread from the sidebar or start a new task."} + + {props.onStartNewTask && !pullRequests && !settings ? ( + Platform.OS === "android" ? ( + + ) : ( + + New thread + + ) + ) : null} + + )} + + ); } diff --git a/apps/mobile/src/features/layout/adaptive-workspace-context.ts b/apps/mobile/src/features/layout/adaptive-workspace-context.ts index a22459e6ecdb4..d82e6202c633b 100644 --- a/apps/mobile/src/features/layout/adaptive-workspace-context.ts +++ b/apps/mobile/src/features/layout/adaptive-workspace-context.ts @@ -1,16 +1,13 @@ -import type { WorkspaceTab } from "../workspace/workspace-tabs-state"; -import { createContext, use, type ReactNode } from "react"; -import type { - WorkspaceDetail, - WorkspaceDetailSheet, -} from "../workspace/workspace-detail-selection"; +import type { WorkspaceTab } from "./workspace/workspace-tabs-state"; +import { createContext, use } from "react"; +import type { InspectorContent } from "./inspector-panes"; +import type { WorkspaceDetail, WorkspaceDetailSheet } from "./workspace/workspace-detail-selection"; import { deriveFileInspectorPaneLayout, deriveLayout, deriveWorkspacePaneLayout, type FileInspectorPaneLayout, type Layout, - type WorkspaceAuxiliaryPaneRole, type WorkspacePaneLayout, } from "../../lib/layout"; @@ -22,12 +19,23 @@ interface AdaptiveWorkspaceContextValue { readonly startNewTask: () => void; /** Use `useSelectWorkspaceDetail`, which also works outside the layout. */ readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void; - readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void; - readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void; + readonly registerWorkspaceInspector: ( + content: InspectorContent, + routeKey: string | undefined, + revealKey?: string, + ) => () => void; readonly setPrimarySidebarSearchQuery: (query: string) => void; - readonly showAuxiliaryPane: (role: WorkspaceAuxiliaryPaneRole) => void; + /** Opens the inspector: its column where the window has one, otherwise a sheet. */ + readonly showInspector: () => void; readonly toggleAuxiliaryPane: () => void; + /** + * Whether the content pane offers a sidebar button: false without columns, on a list that keeps + * its sidebar, and on a workspace page (Android Settings, Usage) that covers it. + */ + readonly sidebarToggleable: boolean; readonly togglePrimarySidebar: () => void; + /** Shows the sidebar, setting aside the keyboard or an inspector that took its room. */ + readonly revealPrimarySidebar: () => void; readonly setPrimarySidebarVisible: (visible: boolean) => void; /** Opens a workspace tab with its list and, with columns, the page it last showed. */ readonly openWorkspaceTab: ( @@ -35,6 +43,8 @@ interface AdaptiveWorkspaceContextValue { options?: { readonly columns?: boolean }, ) => void; readonly setAuxiliaryPaneWidth: (width: number) => void; + readonly nativeInspectorWidth: number; + readonly setNativeInspectorWidth: (width: number) => void; /** * Android split view while the thread composer has the soft keyboard: the * sidebar and rail step aside and the thread header drops to one line. @@ -45,6 +55,10 @@ interface AdaptiveWorkspaceContextValue { * (the unfolded Duo). The native split switches between them as a rotation starts. */ readonly sidebarByOrientation: { readonly landscape: boolean; readonly portrait: boolean } | null; + /** Android split: the composer's keyboard slides the sidebar, from focus until it lets go. */ + readonly keyboardHoldsSidebar?: boolean; + /** Android split: the width a workspace page (Usage) opens at; null without columns. */ + readonly workspacePageWidth?: number | null; /** The thread composer reports its focus so the layout can make room for typing. */ readonly setComposerEditing: (editing: boolean) => void; } @@ -66,15 +80,18 @@ export const AdaptiveWorkspaceContext = createContext undefined, - activateAuxiliaryPaneRole: () => () => undefined, registerWorkspaceInspector: () => () => undefined, setPrimarySidebarSearchQuery: () => undefined, - showAuxiliaryPane: () => undefined, + showInspector: () => undefined, toggleAuxiliaryPane: () => undefined, + sidebarToggleable: false, togglePrimarySidebar: () => undefined, + revealPrimarySidebar: () => undefined, setPrimarySidebarVisible: () => undefined, openWorkspaceTab: () => undefined, setAuxiliaryPaneWidth: () => undefined, + nativeInspectorWidth: 0, + setNativeInspectorWidth: () => undefined, composerKeyboardActive: false, sidebarByOrientation: null, setComposerEditing: () => undefined, diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.android.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.android.tsx index 765b23243798b..2ee2000d400f0 100644 --- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.android.tsx +++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.android.tsx @@ -21,7 +21,10 @@ import { use, type ComponentProps } from "react"; import { RoutedFormSheetContext } from "../../components/ui/RoutedFormSheetContext"; -import { projectStackPresentation } from "../../native/workspace-stack-projection"; +import { + isPresentedRoute, + projectStackPresentation, +} from "../../native/workspace-stack-projection"; import { WorkspaceColumnsRendererContext, WorkspacePresentationHostContext, @@ -37,8 +40,7 @@ function WorkspaceStackView(props: ViewProps) { const isOverlay = (route: Route) => { const descriptor = props.descriptors[route.key] ?? props.describe(route, true); - const presentation = descriptor.options.presentation; - return presentation !== undefined && presentation !== "card"; + return isPresentedRoute(descriptor.options); }; const projection = projectStackPresentation(props.state, isOverlay); const workspaceRoutes = projection.workspace; @@ -46,6 +48,8 @@ function WorkspaceStackView(props: ViewProps) { if (!visibleRoute) return ; const visibleDescriptor = props.descriptors[visibleRoute.key]!; + // Home is the sidebar beside the pages, and under them the page shown when none is selected. + const home = workspaceRoutes.find((route) => route.name === "Home"); const baseRoute = { key: `${props.state.key}:workspace`, name: "Workspace" }; const baseDescriptor: Descriptor = { ...visibleDescriptor, @@ -61,6 +65,7 @@ function WorkspaceStackView(props: ViewProps) { preloadedRoutes: props.state.preloadedRoutes.filter((route) => !isOverlay(route)), }} />, + home ? props.descriptors[home.key]?.render() : null, ), }; const routes = [baseRoute, ...projection.overlays]; @@ -118,14 +123,19 @@ function WorkspaceStackNavigator({ descriptors={Object.fromEntries( Object.entries(descriptors).map(([key, descriptor]) => [ key, - descriptor.options.presentation === "formSheet" - ? { - ...descriptor, - render: () => ( - {descriptor.render()} - ), - } - : descriptor, + { + ...descriptor, + // Screens draw their bar in-tree; hiding the native one only after mount + // shows it for the first frame and leaves the page measured short. + options: { ...descriptor.options, headerShown: false }, + ...(descriptor.options.presentation === "formSheet" + ? { + render: () => ( + {descriptor.render()} + ), + } + : undefined), + }, ]), )} navigation={navigation} diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx index e2697f4e4d238..14ffb11abf22b 100644 --- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx +++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx @@ -19,19 +19,31 @@ import { type NativeStackNavigatorProps, type NativeStackTypeBag, } from "@react-navigation/native-stack"; -import { Fragment, use, useEffect, useRef, useState, type ComponentProps } from "react"; -import { StyleSheet, useWindowDimensions, View } from "react-native"; +import { + Fragment, + use, + useEffect, + useRef, + useState, + type ComponentProps, + type ReactNode, +} from "react"; +import { StyleSheet, View } from "react-native"; import { Split, type SplitHostCommands } from "react-native-screens"; import { SafeAreaView } from "react-native-safe-area-context"; import { GestureHandlerRootView } from "react-native-gesture-handler"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { NATIVE_INSPECTOR_MIN_MAIN_WIDTH } from "../../lib/layout"; import { scopedThreadKey } from "../../lib/scopedEntities"; -import { WorkspaceTabsProvider, useWorkspaceTabs } from "../workspace/WorkspaceTabsContext"; -import { WorkspaceNativeTabs } from "../workspace/WorkspaceNativeTabs.ios"; -import { workspaceUsesColumns } from "../workspace/workspace-tabs-state"; +import { WorkspaceTabsProvider, useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; +import { + WorkspaceNativeTabs, + WorkspaceSidebarTabsFooter, +} from "./workspace/WorkspaceNativeTabs.ios"; +import { workspaceUsesColumns } from "./workspace/workspace-tabs-state"; import { isSettingsRoute, settingsOpenIn } from "../settings/settings-navigation"; import { workspaceRoutesOf } from "./workspace-overlay-routes"; -import { setNativelyPoppingWorkspaceRoute } from "../workspace/workspace-detail-selection"; +import { setNativelyPoppingWorkspaceRoute } from "./workspace/workspace-detail-selection"; import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics"; import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout"; @@ -48,6 +60,9 @@ import { useNativeWorkspaceColumnsSupported, } from "../../native/NativeWorkspaceColumns"; import { V5StackHeader } from "../../native/V5StackHeader.ios"; +import { InspectorColumnScreens } from "./inspector-host"; +import { PaneContext } from "../../components/ui/Pane"; +import { useWorkspaceSidebarHeaderItem } from "./useWorkspaceSidebarHeaderItem"; import type { AppNativeStackNavigationOptions } from "../../native/StackHeader"; import { collapsedSplitTransition, @@ -56,6 +71,7 @@ import { partitionStackPresentations, reconcileStackScreens, type CollapsedSplitColumn, + isPresentedRoute, } from "../../native/workspace-stack-projection"; import { NativePrimaryColumnContext, @@ -88,8 +104,12 @@ function ColumnScreen(props: { readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void; readonly onCompose?: () => void; readonly navigation: ViewProps["navigation"]; + readonly footer?: ReactNode; }) { const { descriptor } = props; + const { layout } = useAdaptiveWorkspaceLayout(); + // A collapsed split shows the primary column as the page itself, not as a sidebar. + const sidebar = props.primary === true && layout.usesSplitView; // Options a screen set inside this workspace tab slot, over its route's. const options = slotScreenOptions( use(WorkspaceSlotOptionsContext), @@ -130,59 +150,72 @@ function ColumnScreen(props: { props.navigation.emit({ type: "transitionEnd", target: key, data: { closing: true } }) } > - - - - - - {/* The Settings slot swaps pages here; its column keeps its measured insets. */} - {descriptor.render()} - - - - + + + + + + + {/* The Settings slot swaps pages here; its column keeps its measured insets. */} + {descriptor.render()} + + + {props.footer} + + + ); } +function EmptyDetailHeader(props: { readonly onCompose: (() => void) | undefined }) { + const sidebarItem = useWorkspaceSidebarHeaderItem(); + return ( + (sidebarItem ? [sidebarItem] : []), + }} + canGoBack={false} + column="detail" + onCompose={props.onCompose} + /> + ); +} + function WorkspaceColumns( props: ViewProps & { readonly primary: Route; readonly detail: Route[] }, ) { const { layout, panes, - togglePrimarySidebar, setPrimarySidebarVisible, toggleAuxiliaryPane, startNewTask, openWorkspaceTab, sidebarByOrientation, + nativeInspectorWidth, + setNativeInspectorWidth, } = useAdaptiveWorkspaceLayout(); const deviceType = useDeviceType(); - const windowDimensions = useWindowDimensions(); - const nativeMetrics = useNativeLayoutMetrics(); - const viewportWidth = nativeMetrics?.width ?? windowDimensions.width; - const [inspectorWidthFraction, setInspectorWidthFraction] = useState(0.4); - const inspectorWidth = Math.max( - 260, - Math.min(viewportWidth * 0.6, viewportWidth * inspectorWidthFraction), - ); + const inspectorWidth = nativeInspectorWidth; const resizeStartWidth = useRef(inspectorWidth); const settingsDetailIn = (detail: readonly Route[]) => layout.usesSplitView && detail[0] && isSettingsRoute(detail[0].name) ? detail[0] : undefined; @@ -229,6 +262,9 @@ function WorkspaceColumns( ? openNewTask : undefined; const inspector = use(NativeWorkspaceInspectorContext); + const hideInspector = () => { + if (inspector.visible) toggleAuxiliaryPane(); + }; const hostRef = useRef(null); const activeDetailKey = props.detail.at(-1)?.key; const compactColumn = activeDetailKey ? "secondary" : "primary"; @@ -301,7 +337,7 @@ function WorkspaceColumns( ref={hostRef} testID="adaptive-workspace-layout" preferredSplitBehavior={ - !sidebarByOrientation && layout.primarySidebarOverlaysContent ? "overlay" : "tile" + !sidebarByOrientation && layout.variant === "medium" ? "overlay" : "tile" } portraitPreferredSplitBehavior={sidebarByOrientation ? "overlay" : undefined} portraitPreferredDisplayMode={ @@ -339,25 +375,23 @@ function WorkspaceColumns( ? panes.primarySidebarVisible : panes.primarySidebarWhenExpanded) || (!layout.usesSplitView && !activeDetailKey), - layout.primarySidebarOverlaysContent, + layout.variant === "medium", ) } onDisplayModeWillChange={({ nativeEvent }) => { - if (!layout.primarySidebarOverlaysContent) return; + if (layout.variant !== "medium") return; if (nativeEvent.nextDisplayMode === "oneOverSecondary") setPrimarySidebarVisible(true); else if (nativeEvent.nextDisplayMode === "secondaryOnly") setPrimarySidebarVisible(false); }} displayModeButtonVisibility="never" presentsWithGesture showInspector={inspector.visible} - onInspectorHide={() => { - if (inspector.visible) toggleAuxiliaryPane(); - }} + onInspectorHide={hideInspector} columnMetrics={{ minimumPrimaryColumnWidth: 280, maximumPrimaryColumnWidth: Math.max(380, layout.listPaneWidth ?? 0), preferredPrimaryColumnWidthOrFraction: layout.listPaneWidth ?? 320, - minimumSecondaryColumnWidth: 320, + minimumSecondaryColumnWidth: NATIVE_INSPECTOR_MIN_MAIN_WIDTH, // UIKit can retain its automatic width despite a new preference; constrain both edges. minimumInspectorColumnWidth: inspectorWidth, maximumInspectorColumnWidth: inspectorWidth, @@ -369,6 +403,16 @@ function WorkspaceColumns( + + + ) : undefined + } selectedThreadKey={selectedThreadKey} selectedPullRequestKey={selectedPullRequestKey} onDismiss={handleNativeDismiss} @@ -383,23 +427,9 @@ function WorkspaceColumns( screenKey="workspace-empty" activityMode={layout.usesSplitView && !activeDetailKey ? "attached" : "detached"} > - [ - { - type: "button", - label: "", - icon: { type: "sfSymbol", name: "sidebar.left" }, - onPress: togglePrimarySidebar, - }, - ], - }} - canGoBack={false} - column="detail" - onCompose={detailCompose} - /> + + + - - + + + + ) : null + } + /> ); } function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean }) { const { layout } = useAdaptiveWorkspaceLayout(); + const deviceType = useDeviceType(); const workspace = useWorkspaceTabs()!; // Native dismiss commits the route pop after the transition. Restore the dock // when the primary screen starts appearing, including interactive back gestures. const [primaryVisible, setPrimaryVisible] = useState(false); const metrics = useNativeLayoutMetrics(); const projection = projectWorkspaceStack(props.state, (route) => { - const presentation = props.descriptors[route.key]?.options.presentation; - return presentation !== undefined && presentation !== "card"; + return isPresentedRoute(props.descriptors[route.key]?.options); }); // The root's willDisappear reaches JS frames into the push, so hide the dock in the commit that // pushes; the native events still own every later change, including back gestures. @@ -514,6 +532,7 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean options: { headerShown: false }, render: () => (